|
| 1 | +import type { Context, Next } from "hono" |
| 2 | + |
| 3 | +import consola from "consola" |
| 4 | + |
| 5 | +import { state } from "~/lib/state" |
| 6 | + |
| 7 | +const AUTH_WINDOW_MS = 5 * 60 * 1000 |
| 8 | +const AUTH_MAX_FAILURES = 10 |
| 9 | +const AUTH_BLOCK_MS = 15 * 60 * 1000 |
| 10 | + |
| 11 | +function getBearerToken( |
| 12 | + authorizationHeader: string | undefined, |
| 13 | +): string | undefined { |
| 14 | + if (!authorizationHeader) return undefined |
| 15 | + |
| 16 | + const [scheme, token] = authorizationHeader.trim().split(/\s+/, 2) |
| 17 | + if (scheme.toLowerCase() !== "bearer" || !token) return undefined |
| 18 | + |
| 19 | + return token |
| 20 | +} |
| 21 | + |
| 22 | +function getForwardedIp( |
| 23 | + forwardedHeader: string | undefined, |
| 24 | +): string | undefined { |
| 25 | + if (!forwardedHeader) return undefined |
| 26 | + |
| 27 | + const match = forwardedHeader.match(/for="?\[?([^;,"]+)/i) |
| 28 | + return match?.[1]?.trim() |
| 29 | +} |
| 30 | + |
| 31 | +function getClientAddress(c: Context): string { |
| 32 | + const candidates = [ |
| 33 | + c.req.header("cf-connecting-ip"), |
| 34 | + c.req.header("x-real-ip"), |
| 35 | + c.req.header("x-client-ip"), |
| 36 | + c.req.header("x-forwarded-for")?.split(",")[0]?.trim(), |
| 37 | + getForwardedIp(c.req.header("forwarded")), |
| 38 | + c.req.header("fly-client-ip"), |
| 39 | + ] |
| 40 | + |
| 41 | + return candidates.find((value) => value && value.length > 0) ?? "unknown" |
| 42 | +} |
| 43 | + |
| 44 | +function getRequestTarget(c: Context): string { |
| 45 | + try { |
| 46 | + const url = new URL(c.req.url) |
| 47 | + return `${c.req.method} ${url.pathname}` |
| 48 | + } catch { |
| 49 | + return `${c.req.method} unknown` |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +function isClientBlocked(clientAddress: string, now: number): boolean { |
| 54 | + const entry = state.authFailures.get(clientAddress) |
| 55 | + if (!entry?.blockedUntil) return false |
| 56 | + |
| 57 | + if (entry.blockedUntil <= now) { |
| 58 | + state.authFailures.delete(clientAddress) |
| 59 | + return false |
| 60 | + } |
| 61 | + |
| 62 | + return true |
| 63 | +} |
| 64 | + |
| 65 | +function recordAuthFailure(clientAddress: string, now: number): void { |
| 66 | + const entry = state.authFailures.get(clientAddress) |
| 67 | + |
| 68 | + if (!entry || entry.resetAt <= now) { |
| 69 | + state.authFailures.set(clientAddress, { |
| 70 | + blockedUntil: undefined, |
| 71 | + count: 1, |
| 72 | + resetAt: now + AUTH_WINDOW_MS, |
| 73 | + }) |
| 74 | + return |
| 75 | + } |
| 76 | + |
| 77 | + entry.count += 1 |
| 78 | + if (entry.count >= AUTH_MAX_FAILURES) { |
| 79 | + entry.blockedUntil = now + AUTH_BLOCK_MS |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +function clearAuthFailures(clientAddress: string): void { |
| 84 | + state.authFailures.delete(clientAddress) |
| 85 | +} |
| 86 | + |
| 87 | +function rejectUnauthorized() { |
| 88 | + return { |
| 89 | + error: { |
| 90 | + message: "Invalid API key", |
| 91 | + type: "authentication_error", |
| 92 | + }, |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +export async function safeRequestLogger(c: Context, next: Next) { |
| 97 | + const startedAt = Date.now() |
| 98 | + const target = getRequestTarget(c) |
| 99 | + |
| 100 | + consola.info(`<-- ${target}`) |
| 101 | + await next() |
| 102 | + consola.info(`--> ${target} ${c.res.status} ${Date.now() - startedAt}ms`) |
| 103 | +} |
| 104 | + |
| 105 | +export async function requireApiKey(c: Context, next: Next) { |
| 106 | + if (!state.apiKey) { |
| 107 | + await next() |
| 108 | + return |
| 109 | + } |
| 110 | + |
| 111 | + const now = Date.now() |
| 112 | + const clientAddress = getClientAddress(c) |
| 113 | + |
| 114 | + if (isClientBlocked(clientAddress, now)) { |
| 115 | + consola.warn( |
| 116 | + `Blocked API key request from ${clientAddress} to ${getRequestTarget(c)}`, |
| 117 | + ) |
| 118 | + return c.json(rejectUnauthorized(), 429) |
| 119 | + } |
| 120 | + |
| 121 | + const authorization = c.req.header("authorization") |
| 122 | + const bearerToken = getBearerToken(authorization) |
| 123 | + const xApiKey = c.req.header("x-api-key") |
| 124 | + |
| 125 | + if (bearerToken === state.apiKey || xApiKey === state.apiKey) { |
| 126 | + clearAuthFailures(clientAddress) |
| 127 | + await next() |
| 128 | + return |
| 129 | + } |
| 130 | + |
| 131 | + recordAuthFailure(clientAddress, now) |
| 132 | + consola.warn( |
| 133 | + `Rejected API key request from ${clientAddress} to ${getRequestTarget(c)}`, |
| 134 | + ) |
| 135 | + |
| 136 | + return c.json(rejectUnauthorized(), 401) |
| 137 | +} |
0 commit comments