barejs 0.1.51 → 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 => {
@@ -58,8 +57,14 @@ const revokedTokens = new Map<string, number>();
58
57
 
59
58
  /**
60
59
  * Revoke a JWT token or JTI for ttlMs (default: 1 hour).
60
+ * Optionally delegates to an external RevocationStore (e.g. redisStore).
61
61
  */
62
- export const revokeToken = (tokenOrJti: string, ttlMs: number = 3600_000): void => {
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
+ }
63
68
  if (revokedTokens.size >= 10_000) {
64
69
  const now = Date.now();
65
70
  for (const [k, exp] of revokedTokens) {
@@ -71,9 +76,14 @@ export const revokeToken = (tokenOrJti: string, ttlMs: number = 3600_000): void
71
76
  }
72
77
  }
73
78
  revokedTokens.set(tokenOrJti, Date.now() + ttlMs);
74
- };
79
+ }
75
80
 
76
- export const isTokenRevoked = (tokenOrJti: string): boolean => {
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
+ }
77
87
  const exp = revokedTokens.get(tokenOrJti);
78
88
  if (exp === undefined) return false;
79
89
  if (Date.now() >= exp) {
@@ -81,20 +91,71 @@ export const isTokenRevoked = (tokenOrJti: string): boolean => {
81
91
  return false;
82
92
  }
83
93
  return true;
84
- };
94
+ }
95
+
96
+ export type JwtAlgorithm = 'HS256' | 'RS256' | 'ES256';
85
97
 
86
98
  export interface BareAuthOptions {
87
- secret: string;
99
+ secret?: string;
100
+ algorithms?: JwtAlgorithm[];
101
+ publicKey?: string | CryptoKey;
102
+ jwksUri?: string;
103
+ jwksCacheTtlMs?: number;
104
+ revocationStore?: RevocationStore;
88
105
  isRevoked?: (payload: any, token: string) => boolean | Promise<boolean>;
89
106
  }
90
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
+
91
145
  /**
92
146
  * 1. BARE TOKEN AUTH (Standard JWT Middleware)
93
- * 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.
94
149
  */
95
150
  export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
96
- const secret = typeof secretOrOpts === 'string' ? secretOrOpts : secretOrOpts.secret;
97
- const customRevoked = typeof secretOrOpts === 'object' ? secretOrOpts.isRevoked : undefined;
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']);
98
159
 
99
160
  const finishAuth = (ctx: any, decoded: any, next: any) => {
100
161
  ctx.set('user', decoded);
@@ -109,9 +170,145 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
109
170
  return;
110
171
  };
111
172
 
112
- const verifySync = (ctx: any, next: any) => {
113
- const authHeader = ctx.req.headers.get('Authorization');
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
+ }
114
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;
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');
115
312
  if (!authHeader?.startsWith('Bearer ')) {
116
313
  return ctx.status(401).send("Bearer token required");
117
314
  }
@@ -129,51 +326,48 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
129
326
  const data = token.slice(0, secondDot);
130
327
 
131
328
  try {
132
- const expectedSig = createHmac('sha256', secret).update(data).digest();
133
- const actualSig = Buffer.from(sigB64, 'base64url');
134
-
135
- if (actualSig.length !== expectedSig.length || !timingSafeEqual(actualSig, expectedSig)) {
136
- return ctx.status(401).send("Invalid signature");
137
- }
138
-
139
329
  const headerObj = JSON.parse(fromBase64Url(headerB64));
140
- if (!headerObj || headerObj.alg !== 'HS256') {
330
+ const alg = headerObj?.alg as JwtAlgorithm | undefined;
331
+ if (!alg || !allowedAlgs.includes(alg)) {
141
332
  return ctx.status(401).send("Unsupported token algorithm");
142
333
  }
143
334
 
144
- const decoded = JSON.parse(fromBase64Url(payloadB64));
145
- const nowSec = Date.now() * 0.001;
146
- if (typeof decoded.exp === 'number' && nowSec >= decoded.exp) {
147
- return ctx.status(401).send("Token expired");
148
- }
149
- if (typeof decoded.nbf === 'number' && nowSec < decoded.nbf) {
150
- return ctx.status(401).send("Token not active");
151
- }
152
-
153
- if (isTokenRevoked(token) || (decoded?.jti && isTokenRevoked(String(decoded.jti)))) {
154
- return ctx.status(401).send("Token revoked");
155
- }
156
-
157
- if (customRevoked) {
158
- const rev = customRevoked(decoded, token);
159
- if (rev && typeof (rev as Promise<boolean>).then === 'function') {
160
- return (rev as Promise<boolean>).then((isRev) =>
161
- isRev ? ctx.status(401).send("Token revoked") : finishAuth(ctx, decoded, next)
162
- );
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");
163
362
  }
164
- if (rev) return ctx.status(401).send("Token revoked");
165
363
  }
166
364
 
167
- return finishAuth(ctx, decoded, next);
365
+ const decoded = JSON.parse(fromBase64Url(payloadB64));
366
+ return checkClaimsAndRevocation(ctx, decoded, token, next);
168
367
  } catch {
169
368
  return ctx.status(401).send("Token verification failed");
170
369
  }
171
370
  };
172
-
173
- if (customRevoked) {
174
- return async (ctx: any, next: any) => verifySync(ctx, next);
175
- }
176
- return verifySync;
177
371
  };
178
372
 
179
373
  const sha256 = (value: string): Buffer => createHash('sha256').update(value).digest();
@@ -215,8 +409,6 @@ export const basicAuth = (credentials: { user: string; pass: string }) => {
215
409
  };
216
410
  };
217
411
 
218
-
219
-
220
412
  /**
221
413
  * 5. ROLE AUTHORIZATION (Bonus Max Function)
222
414
  * Ensures user has specific permissions after bareAuth
@@ -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,32 +46,90 @@ 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 rawKey = ctx.req.headers.get(headerName);
32
- if (!rawKey) {
121
+ const key = extractIdemKey(ctx, headerName);
122
+ if (!key) {
33
123
  (ctx as any)._idempotencyKey = undefined;
34
124
  return undefined;
35
125
  }
36
126
 
37
- const rawUrl = ctx.req.url;
38
- const s = rawUrl.indexOf('/', 8);
39
- const q = s === -1 ? -1 : rawUrl.indexOf('?', s);
40
- const path = s === -1 ? '/' : (q === -1 ? rawUrl.slice(s) : rawUrl.slice(s, q));
41
- const key = `${ctx.req.method}:${path}:${rawKey}`;
42
-
43
127
  const now = Date.now();
44
128
  const existing = cache.get(key);
45
129
  if (existing) {
46
130
  if (now < existing.expiresAt) {
47
131
  (ctx as any)._idempotencyKey = undefined;
48
- return Response.json(existing.body, {
49
- status: existing.status,
50
- headers: { 'X-Idempotent-Replayed': 'true' }
51
- });
132
+ return buildReplayResponse(existing);
52
133
  }
53
134
  cache.delete(key);
54
135
  }
@@ -63,6 +144,7 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
63
144
 
64
145
  inFlight.add(key);
65
146
  (ctx as any)._idempotencyKey = key;
147
+ (ctx as any)._idemInFlight = inFlight;
66
148
  return undefined;
67
149
  };
68
150
 
@@ -70,17 +152,28 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
70
152
  const key = (ctx as any)._idempotencyKey;
71
153
  if (!key) return;
72
154
  (ctx as any)._idempotencyKey = undefined;
155
+ (ctx as any)._idemInFlight = undefined;
73
156
  inFlight.delete(key);
74
- if (status >= 200 && status < 300 && !(resVal instanceof Response)) {
75
- if (cache.size >= maxKeys) {
76
- const oldest = cache.keys().next().value;
77
- 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
+ });
78
176
  }
79
- cache.set(key, {
80
- status,
81
- body: resVal,
82
- expiresAt: Date.now() + ttlMs
83
- });
84
177
  }
85
178
  };
86
179
 
@@ -88,6 +181,7 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
88
181
  const key = (ctx as any)._idempotencyKey;
89
182
  if (key) {
90
183
  (ctx as any)._idempotencyKey = undefined;
184
+ (ctx as any)._idemInFlight = undefined;
91
185
  inFlight.delete(key);
92
186
  }
93
187
  };
@@ -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 {
@@ -19,6 +22,42 @@ export const rateLimit = (options: RateLimitOptions = {}): Middleware => {
19
22
  const message = options.message ?? 'Too many requests, please try again later.';
20
23
  const maxEntries = options.maxEntries ?? 10_000;
21
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
+ }
22
61
 
23
62
  const buckets = new Map<string, RateBucket>();
24
63
 
@@ -45,27 +84,6 @@ export const rateLimit = (options: RateLimitOptions = {}): Middleware => {
45
84
  bucket.count++;
46
85
  }
47
86
 
48
- const remaining = Math.max(0, max - bucket.count);
49
- ctx.setHeader('X-RateLimit-Limit', String(max));
50
- ctx.setHeader('X-RateLimit-Remaining', String(remaining));
51
- ctx.setHeader('X-RateLimit-Reset', String(Math.ceil(bucket.resetAt / 1000)));
52
-
53
- if (bucket.count > max) {
54
- const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000));
55
- return Response.json(
56
- { status: 'error', code: 'RATE_LIMITED', message },
57
- {
58
- status: 429,
59
- headers: {
60
- 'Retry-After': String(retryAfter),
61
- 'X-RateLimit-Limit': String(max),
62
- 'X-RateLimit-Remaining': '0',
63
- 'X-RateLimit-Reset': String(Math.ceil(bucket.resetAt / 1000))
64
- }
65
- }
66
- );
67
- }
68
-
69
- return next?.();
87
+ return finalizeBucket(ctx, bucket.count, bucket.resetAt, now, next);
70
88
  };
71
89
  };