import type { AppContext } from "@/worker/types"; import { hashNullable } from "@/worker/util/request-context"; import { jsonError } from "@/worker/util/response"; export type RateLimitBinding = "RL_AUTH" | "RL_DAV_AUTH" | "RL_REPORT"; export async function rateLimitKey(parts: (string | null | undefined)[]): Promise { return (await hashNullable(parts.filter((part): part is string => !!part).join(":"))) ?? "unknown"; } export async function enforceRateLimit( c: AppContext, binding: RateLimitBinding, keyParts: (string | null | undefined)[], ): Promise { if (import.meta.env.DEV) return null; const key = await rateLimitKey(keyParts); const { success } = await c.env[binding].limit({ key }); return success ? null : jsonError("rate_limited", "Too many requests.", 429); }