-
-
Notifications
You must be signed in to change notification settings - Fork 582
Feature: upstream parity #226
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| import type { Context, Next } from "hono" | ||
|
|
||
| import consola from "consola" | ||
|
|
||
| import { state } from "~/lib/state" | ||
|
|
||
| const AUTH_WINDOW_MS = 5 * 60 * 1000 | ||
| const AUTH_MAX_FAILURES = 10 | ||
| const AUTH_BLOCK_MS = 15 * 60 * 1000 | ||
|
|
||
| function getBearerToken( | ||
| authorizationHeader: string | undefined, | ||
| ): string | undefined { | ||
| if (!authorizationHeader) return undefined | ||
|
|
||
| const [scheme, token] = authorizationHeader.trim().split(/\s+/, 2) | ||
| if (scheme.toLowerCase() !== "bearer" || !token) return undefined | ||
|
|
||
| return token | ||
| } | ||
|
|
||
| function getForwardedIp( | ||
| forwardedHeader: string | undefined, | ||
| ): string | undefined { | ||
| if (!forwardedHeader) return undefined | ||
|
|
||
| const match = forwardedHeader.match(/for="?\[?([^;,"]+)/i) | ||
| return match?.[1]?.trim() | ||
| } | ||
|
|
||
| function getClientAddress(c: Context): string { | ||
| const candidates = [ | ||
| c.req.header("cf-connecting-ip"), | ||
| c.req.header("x-real-ip"), | ||
| c.req.header("x-client-ip"), | ||
| c.req.header("x-forwarded-for")?.split(",")[0]?.trim(), | ||
| getForwardedIp(c.req.header("forwarded")), | ||
| c.req.header("fly-client-ip"), | ||
| ] | ||
|
|
||
| return candidates.find((value) => value && value.length > 0) ?? "unknown" | ||
| } | ||
|
|
||
| function getRequestTarget(c: Context): string { | ||
| try { | ||
| const url = new URL(c.req.url) | ||
| return `${c.req.method} ${url.pathname}` | ||
| } catch { | ||
| return `${c.req.method} unknown` | ||
| } | ||
| } | ||
|
|
||
| function isClientBlocked(clientAddress: string, now: number): boolean { | ||
| const entry = state.authFailures.get(clientAddress) | ||
| if (!entry?.blockedUntil) return false | ||
|
|
||
| if (entry.blockedUntil <= now) { | ||
| state.authFailures.delete(clientAddress) | ||
| return false | ||
| } | ||
|
|
||
| return true | ||
| } | ||
|
|
||
| function recordAuthFailure(clientAddress: string, now: number): void { | ||
| const entry = state.authFailures.get(clientAddress) | ||
|
|
||
| if (!entry || entry.resetAt <= now) { | ||
| state.authFailures.set(clientAddress, { | ||
| blockedUntil: undefined, | ||
| count: 1, | ||
| resetAt: now + AUTH_WINDOW_MS, | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| entry.count += 1 | ||
| if (entry.count >= AUTH_MAX_FAILURES) { | ||
| entry.blockedUntil = now + AUTH_BLOCK_MS | ||
| } | ||
| } | ||
|
|
||
| function clearAuthFailures(clientAddress: string): void { | ||
| state.authFailures.delete(clientAddress) | ||
| } | ||
|
|
||
| function rejectUnauthorized() { | ||
| return { | ||
| error: { | ||
| message: "Invalid API key", | ||
| type: "authentication_error", | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| export async function safeRequestLogger(c: Context, next: Next) { | ||
| const startedAt = Date.now() | ||
| const target = getRequestTarget(c) | ||
|
|
||
| consola.info(`<-- ${target}`) | ||
| await next() | ||
| consola.info(`--> ${target} ${c.res.status} ${Date.now() - startedAt}ms`) | ||
| } | ||
|
|
||
| export async function requireApiKey(c: Context, next: Next) { | ||
| if (!state.apiKey) { | ||
| await next() | ||
| return | ||
| } | ||
|
|
||
| const now = Date.now() | ||
| const clientAddress = getClientAddress(c) | ||
|
|
||
| if (isClientBlocked(clientAddress, now)) { | ||
| consola.warn( | ||
| `Blocked API key request from ${clientAddress} to ${getRequestTarget(c)}`, | ||
| ) | ||
| return c.json(rejectUnauthorized(), 429) | ||
| } | ||
|
|
||
| const authorization = c.req.header("authorization") | ||
| const bearerToken = getBearerToken(authorization) | ||
| const xApiKey = c.req.header("x-api-key") | ||
|
|
||
| if (bearerToken === state.apiKey || xApiKey === state.apiKey) { | ||
| clearAuthFailures(clientAddress) | ||
| await next() | ||
| return | ||
| } | ||
|
|
||
| recordAuthFailure(clientAddress, now) | ||
| consola.warn( | ||
| `Rejected API key request from ${clientAddress} to ${getRequestTarget(c)}`, | ||
| ) | ||
|
|
||
| return c.json(rejectUnauthorized(), 401) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
safeRequestLoggerdoesn’t use atry/finally, so if downstream middleware/handlers throw, the outbound log line (--> ...) will never be emitted. Wrappingawait next()intry/finally(and logging infinally) will ensure consistent request timing logs even on errors.