Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

rate-limit.ts

211 lines6.4 KB

1/**
2 * Rate limiting (PLAN.md task 5.4) — fixed-window counters in KV (the
3 * Workers Rate Limiting binding only supports 10s/60s periods, not hourly
4 * windows). Anonymous traffic: 60 req/h per IP; authenticated: 5k req/h per
5 * credential. KV counters are eventually consistent, so bursts may slightly
6 * over/under-count — this is abuse mitigation, not billing.
7 */
8import { importJWK, jwtVerify } from 'jose'
9import { eq } from 'drizzle-orm'
10import type { JWK } from 'jose'
11​
12import { agent } from '#/db/schema.ts'
13import type { Db } from '#/db/index.ts'
14import type { Auth } from '#/lib/auth.ts'
15​
16export const ANONYMOUS_LIMIT = { limit: 60, windowSeconds: 3600 }
17export const AUTHENTICATED_LIMIT = { limit: 5000, windowSeconds: 3600 }
18​
19export interface RateLimitResult {
20 allowed: boolean
21 limit: number
22 remaining: number
23 /** Unix epoch seconds when the current window resets. */
24 resetAt: number
26​
27const KV_PREFIX = 'rl:'
28​
29export async function checkRateLimit(
30 kv: KVNamespace,
31 bucket: string,
32 limit: number,
33 windowSeconds: number,
34 now = Math.floor(Date.now() / 1000),
35): Promise<RateLimitResult> {
36 const windowStart = Math.floor(now / windowSeconds) * windowSeconds
37 const resetAt = windowStart + windowSeconds
38 const key = `${KV_PREFIX}${bucket}:${String(windowStart)}`
39​
40 const current = Number((await kv.get(key, 'text')) ?? '0')
41 if (current >= limit) {
42 return { allowed: false, limit, remaining: 0, resetAt }
43 }
44 await kv.put(key, String(current + 1), {
45 // Keep the counter around a full extra window so clock skew between
46 // isolates can't resurrect an expired key mid-window.
47 expirationTtl: Math.max(windowSeconds * 2, 60),
48 })
49 return { allowed: true, limit, remaining: limit - current - 1, resetAt }
51​
52export function rateLimitHeaders(
53 result: RateLimitResult,
54): Record<string, string> {
55 return {
56 'X-RateLimit-Limit': String(result.limit),
57 'X-RateLimit-Remaining': String(result.remaining),
58 'X-RateLimit-Reset': String(result.resetAt),
59 }
61​
62export function rateLimitedResponse(
63 result: RateLimitResult,
64 now = Math.floor(Date.now() / 1000),
65): Response {
66 return Response.json(
67 {
68 error: {
69 code: 'rate_limited',
70 message: `Rate limit exceeded (${String(result.limit)} requests/hour). Authenticate for higher limits: POST /v1/agents/register-key or the agent-auth protocol at /.well-known/agent-configuration.`,
71 },
72 },
73 {
74 status: 429,
75 headers: {
76 'Retry-After': String(Math.max(result.resetAt - now, 1)),
77 ...rateLimitHeaders(result),
78 },
79 },
80 )
82​
83function decodeJwtSub(token: string): string | null {
84 const parts = token.split('.')
85 if (parts.length !== 3 || !parts[1]) return null
86 try {
87 const payload = JSON.parse(
88 atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')),
89 ) as { sub?: unknown }
90 return typeof payload.sub === 'string' ? payload.sub : null
91 } catch {
92 return null
93 }
95​
96/**
97 * Verify an agent JWT's signature + expiry against the agent's stored public
98 * key WITHOUT consuming the replay-protected jti (full verification happens
99 * at the route layer; doing it here would burn the token before the route
100 * sees it). Returns true only when the JWT was signed by the agent named in
101 * its `sub`.
102 */
103async function verifyAgentJwtSignature(
104 db: Db,
105 sub: string,
106 token: string,
107): Promise<boolean> {
108 try {
109 const row = await db.query.agent.findFirst({
110 where: eq(agent.id, sub),
111 columns: { publicKey: true, status: true },
112 })
113 if (!row?.publicKey || row.status !== 'active') return false
114 const key = await importJWK(JSON.parse(row.publicKey) as JWK, 'EdDSA')
115 await jwtVerify(token, key, { clockTolerance: 5 })
116 return true
117 } catch {
118 return false
119 }
121​
122/**
123 * Resolve the rate-limit bucket for a request.
124 *
125 * - API keys (non-JWT bearer / X-Api-Key) are verified — invalid keys fall
126 * back to the anonymous IP bucket.
127 * - Agent JWTs are signature-verified against the agent's stored key (but
128 * the jti is NOT consumed — replay protection stays with the route's
129 * auth). Forged or unverifiable JWTs fall back to the anonymous IP
130 * bucket, so unverified claims can never mint authenticated windows.
131 */
132export async function resolveRateBucket(
133 auth: Auth,
134 db: Db,
135 request: Request,
136): Promise<{ bucket: string; limit: number; windowSeconds: number }> {
137 const header = request.headers.get('authorization')
138 const bearer = header?.startsWith('Bearer ')
139 ? header.slice('Bearer '.length)
140 : null
141 const credential = request.headers.get('x-api-key') ?? bearer
142​
143 if (credential) {
144 if (credential.split('.').length === 3) {
145 const sub = decodeJwtSub(credential)
146 if (sub && (await verifyAgentJwtSignature(db, sub, credential))) {
147 return { bucket: `agent:${sub}`, ...AUTHENTICATED_LIMIT }
148 }
149 } else {
150 const verified = await auth.api.verifyApiKey({
151 body: { key: credential },
152 })
153 if (verified.valid && verified.key) {
154 return { bucket: `key:${verified.key.id}`, ...AUTHENTICATED_LIMIT }
155 }
156 }
157 }
158​
159 const ip =
160 request.headers.get('cf-connecting-ip') ??
161 request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??
162 'unknown'
163 return { bucket: `ip:${ip}`, ...ANONYMOUS_LIMIT }
165​
166/** Read the current window's usage without incrementing (for /v1/agents/me). */
167export async function readRateUsage(
168 kv: KVNamespace,
169 bucket: string,
170 limit: number,
171 windowSeconds: number,
172 now = Math.floor(Date.now() / 1000),
173): Promise<{
174 used: number
175 remaining: number
176 limit: number
177 resetAt: number
178}> {
179 const windowStart = Math.floor(now / windowSeconds) * windowSeconds
180 const used = Number(
181 (await kv.get(`${KV_PREFIX}${bucket}:${String(windowStart)}`, 'text')) ??
182 '0',
183 )
184 return {
185 used,
186 remaining: Math.max(limit - used, 0),
187 limit,
188 resetAt: windowStart + windowSeconds,
189 }
191​
192/**
193 * Enforce the rate limit for a /v1 request. Returns a 429 Response when the
194 * window is exhausted, null when the request may proceed.
195 */
196export async function enforceRateLimit(
197 auth: Auth,
198 db: Db,
199 kv: KVNamespace,
200 request: Request,
201 now = Math.floor(Date.now() / 1000),
202): Promise<Response | null> {
203 const { bucket, limit, windowSeconds } = await resolveRateBucket(
204 auth,
205 db,
206 request,
207 )
208 const result = await checkRateLimit(kv, bucket, limit, windowSeconds, now)
209 if (!result.allowed) return rateLimitedResponse(result, now)
210 return null