fix: harden production flows and user messaging
This commit is contained in:
1 parent
52dce168dd
commit
86dfe8053d
43 files changed
+3520
-358
No files matched your search
@@ -0,0 +1,42 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { isIP } from "node:net";
|
||||
|
||||
import type { RateLimitPolicy, RateLimitResult } from "./rate-limit";
|
||||
|
||||
export type ConsumeRateLimit = (
|
||||
key: string,
|
||||
policy: RateLimitPolicy,
|
||||
) => Promise<RateLimitResult>;
|
||||
|
||||
export class RateLimitExceededError extends Error {
|
||||
readonly name = "RateLimitExceededError";
|
||||
|
||||
constructor(readonly retryAfterSeconds: number) {
|
||||
super("Rate limit exceeded");
|
||||
}
|
||||
}
|
||||
|
||||
export async function enforceRateLimit(
|
||||
consume: ConsumeRateLimit,
|
||||
key: string,
|
||||
policy: RateLimitPolicy,
|
||||
) {
|
||||
const result = await consume(key, policy);
|
||||
if (!result.allowed) throw new RateLimitExceededError(result.retryAfterSeconds);
|
||||
}
|
||||
|
||||
export function hashedRequestIdentity(scope: string, identity: string, headers: Headers) {
|
||||
const normalizedIdentity = identity.trim().toLocaleLowerCase("en-US");
|
||||
const address = safeProxyAddress(headers) ?? "unknown";
|
||||
const digest = createHash("sha256")
|
||||
.update(`${scope}\0${normalizedIdentity}\0${address}`, "utf8")
|
||||
.digest("hex");
|
||||
return `${scope}:${digest}`;
|
||||
}
|
||||
|
||||
function safeProxyAddress(headers: Headers) {
|
||||
const realIp = headers.get("x-real-ip")?.trim();
|
||||
if (realIp && isIP(realIp)) return realIp;
|
||||
const forwarded = headers.get("x-forwarded-for")?.split(",").at(-1)?.trim();
|
||||
return forwarded && isIP(forwarded) ? forwarded : null;
|
||||
}
|
||||
Reference in new issue
Block a user