barejs 0.1.50 → 0.1.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import type { Next } from '../core/context';
2
+ import type { RevocationStore } from './store';
2
3
  import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
3
4
 
4
5
  /**
@@ -9,9 +10,7 @@ const encoder = new TextEncoder();
9
10
 
10
11
  // Base64Url Helpers (RFC 4648) using native C++ Buffer encoding
11
12
  const base64Url = (input: Uint8Array | string): string => {
12
- return typeof input === 'string'
13
- ? Buffer.from(input).toString('base64url')
14
- : Buffer.from(input).toString('base64url');
13
+ return Buffer.from(input).toString('base64url');
15
14
  };
16
15
 
17
16
  const fromBase64Url = (str: string): string => {
@@ -54,15 +53,262 @@ export const createToken = async (payload: object, secret: string): Promise<stri
54
53
  return `${data}.${encodedSig}`;
55
54
  };
56
55
 
56
+ const revokedTokens = new Map<string, number>();
57
+
58
+ /**
59
+ * Revoke a JWT token or JTI for ttlMs (default: 1 hour).
60
+ * Optionally delegates to an external RevocationStore (e.g. redisStore).
61
+ */
62
+ export function revokeToken(tokenOrJti: string, ttlMs?: number): void;
63
+ export function revokeToken(tokenOrJti: string, ttlMs: number, store: RevocationStore): Promise<void>;
64
+ export function revokeToken(tokenOrJti: string, ttlMs: number = 3600_000, store?: RevocationStore): void | Promise<void> {
65
+ if (store) {
66
+ return store.revoke(tokenOrJti, ttlMs);
67
+ }
68
+ if (revokedTokens.size >= 10_000) {
69
+ const now = Date.now();
70
+ for (const [k, exp] of revokedTokens) {
71
+ if (now >= exp) revokedTokens.delete(k);
72
+ }
73
+ if (revokedTokens.size >= 10_000) {
74
+ const oldest = revokedTokens.keys().next().value;
75
+ if (oldest !== undefined) revokedTokens.delete(oldest);
76
+ }
77
+ }
78
+ revokedTokens.set(tokenOrJti, Date.now() + ttlMs);
79
+ }
80
+
81
+ export function isTokenRevoked(tokenOrJti: string): boolean;
82
+ export function isTokenRevoked(tokenOrJti: string, store: RevocationStore): Promise<boolean>;
83
+ export function isTokenRevoked(tokenOrJti: string, store?: RevocationStore): boolean | Promise<boolean> {
84
+ if (store) {
85
+ return store.isRevoked(tokenOrJti);
86
+ }
87
+ const exp = revokedTokens.get(tokenOrJti);
88
+ if (exp === undefined) return false;
89
+ if (Date.now() >= exp) {
90
+ revokedTokens.delete(tokenOrJti);
91
+ return false;
92
+ }
93
+ return true;
94
+ }
95
+
96
+ export type JwtAlgorithm = 'HS256' | 'RS256' | 'ES256';
97
+
98
+ export interface BareAuthOptions {
99
+ secret?: string;
100
+ algorithms?: JwtAlgorithm[];
101
+ publicKey?: string | CryptoKey;
102
+ jwksUri?: string;
103
+ jwksCacheTtlMs?: number;
104
+ revocationStore?: RevocationStore;
105
+ isRevoked?: (payload: any, token: string) => boolean | Promise<boolean>;
106
+ }
107
+
108
+ const pemKeyCache = new Map<string, CryptoKey>();
109
+
110
+ const getAsymmetricAlgParams = (alg: 'RS256' | 'ES256') =>
111
+ alg === 'RS256'
112
+ ? ({ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' } as const)
113
+ : ({ name: 'ECDSA', namedCurve: 'P-256' } as const);
114
+
115
+ const getVerifyParams = (alg: 'RS256' | 'ES256') =>
116
+ alg === 'RS256'
117
+ ? ({ name: 'RSASSA-PKCS1-v1_5' } as const)
118
+ : ({ name: 'ECDSA', hash: 'SHA-256' } as const);
119
+
120
+ const pemToDer = (pem: string): ArrayBuffer => {
121
+ const b64 = pem
122
+ .replace(/-----BEGIN [A-Z0-9 ]+-----/g, '')
123
+ .replace(/-----END [A-Z0-9 ]+-----/g, '')
124
+ .replace(/\s+/g, '');
125
+ const buf = Buffer.from(b64, 'base64');
126
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
127
+ };
128
+
129
+ const importPublicKey = async (keyOrPem: string | CryptoKey, alg: 'RS256' | 'ES256'): Promise<CryptoKey> => {
130
+ if (typeof keyOrPem !== 'string') return keyOrPem;
131
+ const cacheKey = `${alg}:${keyOrPem}`;
132
+ const cached = pemKeyCache.get(cacheKey);
133
+ if (cached) return cached;
134
+ const imported = await crypto.subtle.importKey(
135
+ 'spki',
136
+ pemToDer(keyOrPem),
137
+ getAsymmetricAlgParams(alg),
138
+ false,
139
+ ['verify']
140
+ );
141
+ pemKeyCache.set(cacheKey, imported);
142
+ return imported;
143
+ };
144
+
57
145
  /**
58
146
  * 1. BARE TOKEN AUTH (Standard JWT Middleware)
59
- * High-performance, constant-time JWT middleware for BareJS
147
+ * High-performance, constant-time JWT middleware for BareJS.
148
+ * Supports HS256 (sync fast-path), RS256, ES256, and JWKS with kid caching.
60
149
  */
61
- export const bareAuth = (secretOrOpts: string | { secret: string }) => {
62
- const secret = typeof secretOrOpts === 'string' ? secretOrOpts : secretOrOpts.secret;
63
- return (ctx: any, next: any) => {
64
- const authHeader = ctx.req.headers.get('Authorization');
150
+ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
151
+ const opts: BareAuthOptions = typeof secretOrOpts === 'string' ? { secret: secretOrOpts } : secretOrOpts;
152
+ const secret = opts.secret ?? '';
153
+ const customRevoked = opts.isRevoked;
154
+ const revocationStore = opts.revocationStore;
155
+ const publicKey = opts.publicKey;
156
+ const jwksUri = opts.jwksUri;
157
+ const jwksCacheTtlMs = opts.jwksCacheTtlMs ?? 300_000;
158
+ const allowedAlgs: JwtAlgorithm[] = opts.algorithms ?? (publicKey || jwksUri ? ['RS256', 'ES256'] : ['HS256']);
159
+
160
+ const finishAuth = (ctx: any, decoded: any, next: any) => {
161
+ ctx.set('user', decoded);
162
+ if (Array.isArray(next)) {
163
+ if (next.length === 0) return;
164
+ const [current, ...rest] = next;
165
+ return current(ctx, rest);
166
+ }
167
+ if (typeof next === 'function') {
168
+ return next();
169
+ }
170
+ return;
171
+ };
172
+
173
+ const checkClaimsAndRevocation = (ctx: any, decoded: any, token: string, next: any) => {
174
+ const nowSec = Date.now() * 0.001;
175
+ if (typeof decoded.exp === 'number' && nowSec >= decoded.exp) {
176
+ return ctx.status(401).send("Token expired");
177
+ }
178
+ if (typeof decoded.nbf === 'number' && nowSec < decoded.nbf) {
179
+ return ctx.status(401).send("Token not active");
180
+ }
181
+
182
+ if (isTokenRevoked(token) || (decoded?.jti && isTokenRevoked(String(decoded.jti)))) {
183
+ return ctx.status(401).send("Token revoked");
184
+ }
185
+
186
+ if (revocationStore) {
187
+ const checkStore = async () => {
188
+ if (await revocationStore.isRevoked(token)) return ctx.status(401).send("Token revoked");
189
+ if (decoded?.jti && await revocationStore.isRevoked(String(decoded.jti))) {
190
+ return ctx.status(401).send("Token revoked");
191
+ }
192
+ if (customRevoked) {
193
+ const rev = await customRevoked(decoded, token);
194
+ if (rev) return ctx.status(401).send("Token revoked");
195
+ }
196
+ return finishAuth(ctx, decoded, next);
197
+ };
198
+ return checkStore();
199
+ }
200
+
201
+ if (customRevoked) {
202
+ const rev = customRevoked(decoded, token);
203
+ if (rev && typeof (rev as Promise<boolean>).then === 'function') {
204
+ return (rev as Promise<boolean>).then((isRev) =>
205
+ isRev ? ctx.status(401).send("Token revoked") : finishAuth(ctx, decoded, next)
206
+ );
207
+ }
208
+ if (rev) return ctx.status(401).send("Token revoked");
209
+ }
210
+
211
+ return finishAuth(ctx, decoded, next);
212
+ };
213
+
214
+ // Preserve zero-overhead synchronous HS256 fast path when no asymmetric keys/JWKS are configured
215
+ const isSymmetricOnly =
216
+ !publicKey &&
217
+ !jwksUri &&
218
+ allowedAlgs.length === 1 &&
219
+ allowedAlgs[0] === 'HS256';
220
+
221
+ if (isSymmetricOnly) {
222
+ const verifySync = (ctx: any, next: any) => {
223
+ const authHeader = ctx.req.headers.get('Authorization');
224
+
225
+ if (!authHeader?.startsWith('Bearer ')) {
226
+ return ctx.status(401).send("Bearer token required");
227
+ }
228
+
229
+ const token = authHeader.slice(7);
230
+ const firstDot = token.indexOf('.');
231
+ const secondDot = firstDot === -1 ? -1 : token.indexOf('.', firstDot + 1);
232
+ if (firstDot === -1 || secondDot === -1 || token.indexOf('.', secondDot + 1) !== -1) {
233
+ return ctx.status(401).send("Malformed JWT token");
234
+ }
235
+
236
+ const headerB64 = token.slice(0, firstDot);
237
+ const payloadB64 = token.slice(firstDot + 1, secondDot);
238
+ const sigB64 = token.slice(secondDot + 1);
239
+ const data = token.slice(0, secondDot);
240
+
241
+ try {
242
+ const expectedSig = createHmac('sha256', secret).update(data).digest();
243
+ const actualSig = Buffer.from(sigB64, 'base64url');
244
+
245
+ if (actualSig.length !== expectedSig.length || !timingSafeEqual(actualSig, expectedSig)) {
246
+ return ctx.status(401).send("Invalid signature");
247
+ }
248
+
249
+ const headerObj = JSON.parse(fromBase64Url(headerB64));
250
+ if (!headerObj || headerObj.alg !== 'HS256') {
251
+ return ctx.status(401).send("Unsupported token algorithm");
252
+ }
253
+
254
+ const decoded = JSON.parse(fromBase64Url(payloadB64));
255
+ return checkClaimsAndRevocation(ctx, decoded, token, next);
256
+ } catch {
257
+ return ctx.status(401).send("Token verification failed");
258
+ }
259
+ };
260
+
261
+ if (customRevoked || revocationStore) {
262
+ return async (ctx: any, next: any) => verifySync(ctx, next);
263
+ }
264
+ return verifySync;
265
+ }
266
+
267
+ // Asymmetric (RS256 / ES256) and/or JWKS verification path
268
+ let jwksFetchedAt = 0;
269
+ let jwksKeys: any[] = [];
270
+ const jwkKeyCache = new Map<string, CryptoKey>();
271
+
272
+ const loadJwks = async (forceRefresh = false): Promise<any[]> => {
273
+ const now = Date.now();
274
+ if (!forceRefresh && jwksKeys.length > 0 && now - jwksFetchedAt < jwksCacheTtlMs) {
275
+ return jwksKeys;
276
+ }
277
+ const res = await fetch(jwksUri!);
278
+ if (!res.ok) throw new Error(`JWKS fetch failed: ${res.status}`);
279
+ const body = (await res.json()) as { keys?: any[] };
280
+ jwksKeys = Array.isArray(body?.keys) ? body.keys : [];
281
+ jwksFetchedAt = now;
282
+ if (forceRefresh) jwkKeyCache.clear();
283
+ return jwksKeys;
284
+ };
285
+
286
+ const resolveJwksKey = async (kid: string | undefined, alg: 'RS256' | 'ES256'): Promise<CryptoKey | null> => {
287
+ const cacheId = `${alg}:${kid ?? '__default__'}`;
288
+ const cached = jwkKeyCache.get(cacheId);
289
+ if (cached && Date.now() - jwksFetchedAt < jwksCacheTtlMs) return cached;
65
290
 
291
+ let keys = await loadJwks(false);
292
+ let match = kid ? keys.find((k) => k.kid === kid) : keys[0];
293
+ if (!match && kid) {
294
+ keys = await loadJwks(true);
295
+ match = keys.find((k) => k.kid === kid);
296
+ }
297
+ if (!match) return null;
298
+
299
+ const imported = await crypto.subtle.importKey(
300
+ 'jwk',
301
+ match,
302
+ getAsymmetricAlgParams(alg),
303
+ false,
304
+ ['verify']
305
+ );
306
+ jwkKeyCache.set(cacheId, imported);
307
+ return imported;
308
+ };
309
+
310
+ return async (ctx: any, next: any) => {
311
+ const authHeader = ctx.req.headers.get('Authorization');
66
312
  if (!authHeader?.startsWith('Bearer ')) {
67
313
  return ctx.status(401).send("Bearer token required");
68
314
  }
@@ -80,40 +326,44 @@ export const bareAuth = (secretOrOpts: string | { secret: string }) => {
80
326
  const data = token.slice(0, secondDot);
81
327
 
82
328
  try {
83
- const expectedSig = createHmac('sha256', secret).update(data).digest();
84
- const actualSig = Buffer.from(sigB64, 'base64url');
85
-
86
- if (actualSig.length !== expectedSig.length || !timingSafeEqual(actualSig, expectedSig)) {
87
- return ctx.status(401).send("Invalid signature");
88
- }
89
-
90
329
  const headerObj = JSON.parse(fromBase64Url(headerB64));
91
- if (!headerObj || headerObj.alg !== 'HS256') {
330
+ const alg = headerObj?.alg as JwtAlgorithm | undefined;
331
+ if (!alg || !allowedAlgs.includes(alg)) {
92
332
  return ctx.status(401).send("Unsupported token algorithm");
93
333
  }
94
334
 
95
- const decoded = JSON.parse(fromBase64Url(payloadB64));
96
- const nowSec = Date.now() * 0.001;
97
- if (typeof decoded.exp === 'number' && nowSec >= decoded.exp) {
98
- return ctx.status(401).send("Token expired");
335
+ if (alg === 'HS256') {
336
+ if (!secret) return ctx.status(401).send("Unsupported token algorithm");
337
+ const expectedSig = createHmac('sha256', secret).update(data).digest();
338
+ const actualSig = Buffer.from(sigB64, 'base64url');
339
+ if (actualSig.length !== expectedSig.length || !timingSafeEqual(actualSig, expectedSig)) {
340
+ return ctx.status(401).send("Invalid signature");
341
+ }
342
+ } else {
343
+ let verifyKey: CryptoKey | null = null;
344
+ if (jwksUri) {
345
+ verifyKey = await resolveJwksKey(headerObj?.kid, alg);
346
+ } else if (publicKey) {
347
+ verifyKey = await importPublicKey(publicKey, alg);
348
+ }
349
+ if (!verifyKey) {
350
+ return ctx.status(401).send("Invalid signature");
351
+ }
352
+ const sigBuf = Buffer.from(sigB64, 'base64url');
353
+ const sigBytes = sigBuf.buffer.slice(sigBuf.byteOffset, sigBuf.byteOffset + sigBuf.byteLength);
354
+ const valid = await crypto.subtle.verify(
355
+ getVerifyParams(alg),
356
+ verifyKey,
357
+ sigBytes,
358
+ encoder.encode(data)
359
+ );
360
+ if (!valid) {
361
+ return ctx.status(401).send("Invalid signature");
362
+ }
99
363
  }
100
- if (typeof decoded.nbf === 'number' && nowSec < decoded.nbf) {
101
- return ctx.status(401).send("Token not active");
102
- }
103
-
104
- ctx.set('user', decoded);
105
364
 
106
- if (Array.isArray(next)) {
107
- if (next.length === 0) return;
108
- const [current, ...rest] = next;
109
- return current(ctx, rest);
110
- }
111
-
112
- if (typeof next === 'function') {
113
- return next();
114
- }
115
-
116
- return;
365
+ const decoded = JSON.parse(fromBase64Url(payloadB64));
366
+ return checkClaimsAndRevocation(ctx, decoded, token, next);
117
367
  } catch {
118
368
  return ctx.status(401).send("Token verification failed");
119
369
  }
@@ -159,8 +409,6 @@ export const basicAuth = (credentials: { user: string; pass: string }) => {
159
409
  };
160
410
  };
161
411
 
162
-
163
-
164
412
  /**
165
413
  * 5. ROLE AUTHORIZATION (Bonus Max Function)
166
414
  * Ensures user has specific permissions after bareAuth
@@ -5,8 +5,14 @@ export const Hash = {
5
5
  make: (data: string): Promise<string> =>
6
6
  Bun.password.hash(data, BARE_CONFIG.hash),
7
7
 
8
- verify: (data: string, hash: string): Promise<boolean> =>
9
- Bun.password.verify(data, hash),
8
+ verify: async (data: string, hash: string): Promise<boolean> => {
9
+ if (!hash || typeof hash !== 'string') return false;
10
+ try {
11
+ return await Bun.password.verify(data, hash);
12
+ } catch {
13
+ return false;
14
+ }
15
+ },
10
16
 
11
17
  needsRehash: (hash: string): boolean => {
12
18
  const { algorithm, memoryCost, timeCost } = BARE_CONFIG.hash;
@@ -1,4 +1,5 @@
1
1
  import type { Context, Middleware } from '../core/context';
2
+ import type { CachedIdempotentEntry, IdempotencyStore } from './store';
2
3
 
3
4
  export interface IdempotencyOptions {
4
5
  /** Header name (default: 'idempotency-key') */
@@ -7,13 +8,35 @@ export interface IdempotencyOptions {
7
8
  ttlMs?: number;
8
9
  /** Maximum cached keys before LRU eviction (default: 10_000) */
9
10
  maxKeys?: number;
11
+ /** Optional external store (e.g. redisStore(client)). Uses in-memory Map fast path when omitted. */
12
+ store?: IdempotencyStore;
10
13
  }
11
14
 
12
- interface CachedIdempotentEntry {
13
- status: number;
14
- body: any;
15
- expiresAt: number;
16
- }
15
+ const buildReplayResponse = (existing: CachedIdempotentEntry): Response => {
16
+ if (existing.rawBody !== undefined) {
17
+ return new Response(existing.rawBody, {
18
+ status: existing.status,
19
+ headers: {
20
+ 'content-type': existing.contentType || 'application/json',
21
+ 'X-Idempotent-Replayed': 'true'
22
+ }
23
+ });
24
+ }
25
+ return Response.json(existing.body, {
26
+ status: existing.status,
27
+ headers: { 'X-Idempotent-Replayed': 'true' }
28
+ });
29
+ };
30
+
31
+ const extractIdemKey = (ctx: Context, headerName: string): string | undefined => {
32
+ const rawKey = ctx.req.headers.get(headerName);
33
+ if (!rawKey) return undefined;
34
+ const rawUrl = ctx.req.url;
35
+ const s = rawUrl.indexOf('/', 8);
36
+ const q = s === -1 ? -1 : rawUrl.indexOf('?', s);
37
+ const path = s === -1 ? '/' : (q === -1 ? rawUrl.slice(s) : rawUrl.slice(s, q));
38
+ return `${ctx.req.method}:${path}:${rawKey}`;
39
+ };
17
40
 
18
41
  /**
19
42
  * Payment & Order Double-Charge Protection Middleware (Idempotency-Key).
@@ -23,27 +46,96 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
23
46
  const headerName = (options.headerName || 'idempotency-key').toLowerCase();
24
47
  const ttlMs = options.ttlMs ?? 300_000;
25
48
  const maxKeys = options.maxKeys ?? 10_000;
49
+ const externalStore = options.store;
50
+
51
+ if (externalStore) {
52
+ const storeLockShim = { delete: (k: string) => { void externalStore.release(k); } };
53
+ const mw: Middleware = async (ctx: Context) => {
54
+ const key = extractIdemKey(ctx, headerName);
55
+ if (!key) {
56
+ (ctx as any)._idempotencyKey = undefined;
57
+ return undefined;
58
+ }
59
+
60
+ const existing = await externalStore.get(key);
61
+ if (existing && Date.now() < existing.expiresAt) {
62
+ (ctx as any)._idempotencyKey = undefined;
63
+ return buildReplayResponse(existing);
64
+ }
65
+
66
+ const acquired = await externalStore.acquire(key, ttlMs);
67
+ if (!acquired) {
68
+ (ctx as any)._idempotencyKey = undefined;
69
+ return Response.json(
70
+ { status: 'error', code: 'IDEMPOTENT_IN_FLIGHT', message: 'Duplicate request is currently in flight' },
71
+ { status: 409 }
72
+ );
73
+ }
74
+
75
+ (ctx as any)._idempotencyKey = key;
76
+ (ctx as any)._idemInFlight = storeLockShim;
77
+ return undefined;
78
+ };
79
+
80
+ (mw as any).__idempotencyCommit = (ctx: Context, resVal: any, status: number) => {
81
+ const key = (ctx as any)._idempotencyKey;
82
+ if (!key) return;
83
+ (ctx as any)._idempotencyKey = undefined;
84
+ (ctx as any)._idemInFlight = undefined;
85
+ void externalStore.release(key);
86
+ if (status >= 200 && status < 300) {
87
+ if (resVal instanceof Response) {
88
+ const ct = resVal.headers.get('content-type') || 'application/json';
89
+ resVal.clone().arrayBuffer().then((buf) =>
90
+ externalStore.set(key, { status, rawBody: buf, contentType: ct, expiresAt: Date.now() + ttlMs }, ttlMs)
91
+ ).catch(() => {});
92
+ } else {
93
+ void externalStore.set(key, { status, body: resVal, expiresAt: Date.now() + ttlMs }, ttlMs);
94
+ }
95
+ }
96
+ };
97
+
98
+ (mw as any).__idempotencyRelease = (ctx: Context) => {
99
+ const key = (ctx as any)._idempotencyKey;
100
+ if (key) {
101
+ (ctx as any)._idempotencyKey = undefined;
102
+ (ctx as any)._idemInFlight = undefined;
103
+ void externalStore.release(key);
104
+ }
105
+ };
106
+
107
+ return mw;
108
+ }
26
109
 
27
110
  const cache = new Map<string, CachedIdempotentEntry>();
28
111
  const inFlight = new Set<string>();
29
112
 
113
+ const evictIfNeeded = () => {
114
+ if (cache.size >= maxKeys) {
115
+ const oldest = cache.keys().next().value;
116
+ if (oldest !== undefined) cache.delete(oldest);
117
+ }
118
+ };
119
+
30
120
  const mw: Middleware = (ctx: Context) => {
31
- const key = ctx.req.headers.get(headerName);
32
- if (!key) return undefined;
121
+ const key = extractIdemKey(ctx, headerName);
122
+ if (!key) {
123
+ (ctx as any)._idempotencyKey = undefined;
124
+ return undefined;
125
+ }
33
126
 
34
127
  const now = Date.now();
35
128
  const existing = cache.get(key);
36
129
  if (existing) {
37
130
  if (now < existing.expiresAt) {
38
- return Response.json(existing.body, {
39
- status: existing.status,
40
- headers: { 'X-Idempotent-Replayed': 'true' }
41
- });
131
+ (ctx as any)._idempotencyKey = undefined;
132
+ return buildReplayResponse(existing);
42
133
  }
43
134
  cache.delete(key);
44
135
  }
45
136
 
46
137
  if (inFlight.has(key)) {
138
+ (ctx as any)._idempotencyKey = undefined;
47
139
  return Response.json(
48
140
  { status: 'error', code: 'IDEMPOTENT_IN_FLIGHT', message: 'Duplicate request is currently in flight' },
49
141
  { status: 409 }
@@ -59,17 +151,38 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
59
151
  (mw as any).__idempotencyCommit = (ctx: Context, resVal: any, status: number) => {
60
152
  const key = (ctx as any)._idempotencyKey;
61
153
  if (!key) return;
154
+ (ctx as any)._idempotencyKey = undefined;
155
+ (ctx as any)._idemInFlight = undefined;
62
156
  inFlight.delete(key);
63
- if (status >= 200 && status < 300 && !(resVal instanceof Response)) {
64
- if (cache.size >= maxKeys) {
65
- const oldest = cache.keys().next().value;
66
- if (oldest !== undefined) cache.delete(oldest);
157
+ if (status >= 200 && status < 300) {
158
+ if (resVal instanceof Response) {
159
+ const ct = resVal.headers.get('content-type') || 'application/json';
160
+ resVal.clone().arrayBuffer().then((buf) => {
161
+ evictIfNeeded();
162
+ cache.set(key, {
163
+ status,
164
+ rawBody: buf,
165
+ contentType: ct,
166
+ expiresAt: Date.now() + ttlMs
167
+ });
168
+ }).catch(() => {});
169
+ } else {
170
+ evictIfNeeded();
171
+ cache.set(key, {
172
+ status,
173
+ body: resVal,
174
+ expiresAt: Date.now() + ttlMs
175
+ });
67
176
  }
68
- cache.set(key, {
69
- status,
70
- body: resVal,
71
- expiresAt: Date.now() + ttlMs
72
- });
177
+ }
178
+ };
179
+
180
+ (mw as any).__idempotencyRelease = (ctx: Context) => {
181
+ const key = (ctx as any)._idempotencyKey;
182
+ if (key) {
183
+ (ctx as any)._idempotencyKey = undefined;
184
+ (ctx as any)._idemInFlight = undefined;
185
+ inFlight.delete(key);
73
186
  }
74
187
  };
75
188
 
@@ -1,4 +1,5 @@
1
1
  import type { Context, Middleware } from '../core/context';
2
+ import type { RateLimitStore } from './store';
2
3
 
3
4
  export interface RateLimitOptions {
4
5
  windowMs?: number;
@@ -6,6 +7,8 @@ export interface RateLimitOptions {
6
7
  message?: string;
7
8
  keyGenerator?: (ctx: Context) => string;
8
9
  maxEntries?: number;
10
+ /** Optional external store (e.g. redisStore(client)). Uses in-memory Map fast path when omitted. */
11
+ store?: RateLimitStore;
9
12
  }
10
13
 
11
14
  interface RateBucket {
@@ -18,12 +21,43 @@ export const rateLimit = (options: RateLimitOptions = {}): Middleware => {
18
21
  const max = options.max ?? 100;
19
22
  const message = options.message ?? 'Too many requests, please try again later.';
20
23
  const maxEntries = options.maxEntries ?? 10_000;
21
- const keyGenerator =
22
- options.keyGenerator ??
23
- ((ctx: Context) =>
24
- ctx.req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||
25
- ctx.req.headers.get('x-real-ip') ||
26
- 'global');
24
+ const keyGenerator = options.keyGenerator ?? ((ctx: Context) => ctx.ip);
25
+ const store = options.store;
26
+
27
+ const finalizeBucket = (ctx: Context, count: number, resetAt: number, now: number, next: any) => {
28
+ const remaining = Math.max(0, max - count);
29
+ const resetSec = String(Math.ceil(resetAt / 1000));
30
+ ctx.setHeader('X-RateLimit-Limit', String(max));
31
+ ctx.setHeader('X-RateLimit-Remaining', String(remaining));
32
+ ctx.setHeader('X-RateLimit-Reset', resetSec);
33
+
34
+ if (count > max) {
35
+ const retryAfter = Math.max(1, Math.ceil((resetAt - now) / 1000));
36
+ return Response.json(
37
+ { status: 'error', code: 'RATE_LIMITED', message },
38
+ {
39
+ status: 429,
40
+ headers: {
41
+ 'Retry-After': String(retryAfter),
42
+ 'X-RateLimit-Limit': String(max),
43
+ 'X-RateLimit-Remaining': '0',
44
+ 'X-RateLimit-Reset': resetSec
45
+ }
46
+ }
47
+ );
48
+ }
49
+
50
+ return next?.();
51
+ };
52
+
53
+ if (store) {
54
+ return async (ctx, next) => {
55
+ const now = Date.now();
56
+ const key = keyGenerator(ctx);
57
+ const { count, resetAt } = await store.increment(key, windowMs);
58
+ return finalizeBucket(ctx, count, resetAt, now, next);
59
+ };
60
+ }
27
61
 
28
62
  const buckets = new Map<string, RateBucket>();
29
63
 
@@ -50,27 +84,6 @@ export const rateLimit = (options: RateLimitOptions = {}): Middleware => {
50
84
  bucket.count++;
51
85
  }
52
86
 
53
- const remaining = Math.max(0, max - bucket.count);
54
- ctx.setHeader('X-RateLimit-Limit', String(max));
55
- ctx.setHeader('X-RateLimit-Remaining', String(remaining));
56
- ctx.setHeader('X-RateLimit-Reset', String(Math.ceil(bucket.resetAt / 1000)));
57
-
58
- if (bucket.count > max) {
59
- const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000));
60
- return Response.json(
61
- { status: 'error', code: 'RATE_LIMITED', message },
62
- {
63
- status: 429,
64
- headers: {
65
- 'Retry-After': String(retryAfter),
66
- 'X-RateLimit-Limit': String(max),
67
- 'X-RateLimit-Remaining': '0',
68
- 'X-RateLimit-Reset': String(Math.ceil(bucket.resetAt / 1000))
69
- }
70
- }
71
- );
72
- }
73
-
74
- return next?.();
87
+ return finalizeBucket(ctx, bucket.count, bucket.resetAt, now, next);
75
88
  };
76
89
  };