barejs 0.1.52 → 0.1.55

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.
@@ -101,6 +101,8 @@ export interface BareAuthOptions {
101
101
  publicKey?: string | CryptoKey;
102
102
  jwksUri?: string;
103
103
  jwksCacheTtlMs?: number;
104
+ issuer?: string | string[];
105
+ audience?: string | string[];
104
106
  revocationStore?: RevocationStore;
105
107
  isRevoked?: (payload: any, token: string) => boolean | Promise<boolean>;
106
108
  }
@@ -156,6 +158,8 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
156
158
  const jwksUri = opts.jwksUri;
157
159
  const jwksCacheTtlMs = opts.jwksCacheTtlMs ?? 300_000;
158
160
  const allowedAlgs: JwtAlgorithm[] = opts.algorithms ?? (publicKey || jwksUri ? ['RS256', 'ES256'] : ['HS256']);
161
+ const expectedIss = opts.issuer === undefined ? null : (Array.isArray(opts.issuer) ? opts.issuer : [opts.issuer]);
162
+ const expectedAud = opts.audience === undefined ? null : (Array.isArray(opts.audience) ? opts.audience : [opts.audience]);
159
163
 
160
164
  const finishAuth = (ctx: any, decoded: any, next: any) => {
161
165
  ctx.set('user', decoded);
@@ -171,6 +175,10 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
171
175
  };
172
176
 
173
177
  const checkClaimsAndRevocation = (ctx: any, decoded: any, token: string, next: any) => {
178
+ if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) {
179
+ return ctx.status(401).send("Invalid token payload");
180
+ }
181
+
174
182
  const nowSec = Date.now() * 0.001;
175
183
  if (typeof decoded.exp === 'number' && nowSec >= decoded.exp) {
176
184
  return ctx.status(401).send("Token expired");
@@ -178,6 +186,15 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
178
186
  if (typeof decoded.nbf === 'number' && nowSec < decoded.nbf) {
179
187
  return ctx.status(401).send("Token not active");
180
188
  }
189
+ if (expectedIss && (typeof decoded.iss !== 'string' || !expectedIss.includes(decoded.iss))) {
190
+ return ctx.status(401).send("Invalid token issuer");
191
+ }
192
+ if (expectedAud) {
193
+ const tokenAud = Array.isArray(decoded.aud) ? decoded.aud : (typeof decoded.aud === 'string' ? [decoded.aud] : []);
194
+ if (!tokenAud.some((a: any) => typeof a === 'string' && expectedAud.includes(a))) {
195
+ return ctx.status(401).send("Invalid token audience");
196
+ }
197
+ }
181
198
 
182
199
  if (isTokenRevoked(token) || (decoded?.jti && isTokenRevoked(String(decoded.jti)))) {
183
200
  return ctx.status(401).send("Token revoked");
@@ -266,21 +283,45 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
266
283
 
267
284
  // Asymmetric (RS256 / ES256) and/or JWKS verification path
268
285
  let jwksFetchedAt = 0;
286
+ let lastForceRefreshAt = 0;
269
287
  let jwksKeys: any[] = [];
288
+ let inFlightJwks: Promise<any[]> | null = null;
270
289
  const jwkKeyCache = new Map<string, CryptoKey>();
290
+ const JWKS_FORCE_COOLDOWN_MS = 15_000;
271
291
 
272
292
  const loadJwks = async (forceRefresh = false): Promise<any[]> => {
273
293
  const now = Date.now();
274
294
  if (!forceRefresh && jwksKeys.length > 0 && now - jwksFetchedAt < jwksCacheTtlMs) {
275
295
  return jwksKeys;
276
296
  }
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;
297
+ if (forceRefresh && now - lastForceRefreshAt < JWKS_FORCE_COOLDOWN_MS && jwksKeys.length > 0) {
298
+ return jwksKeys;
299
+ }
300
+ if (inFlightJwks) return inFlightJwks;
301
+
302
+ if (forceRefresh) lastForceRefreshAt = now;
303
+ inFlightJwks = (async () => {
304
+ const res = await fetch(jwksUri!, { signal: AbortSignal.timeout(5000) });
305
+ if (!res.ok) throw new Error(`JWKS fetch failed: ${res.status}`);
306
+ const body = (await res.json()) as { keys?: any[] };
307
+ jwksKeys = Array.isArray(body?.keys) ? body.keys : [];
308
+ jwksFetchedAt = Date.now();
309
+ if (forceRefresh) jwkKeyCache.clear();
310
+ return jwksKeys;
311
+ })().finally(() => {
312
+ inFlightJwks = null;
313
+ });
314
+ return inFlightJwks;
315
+ };
316
+
317
+ const matchJwk = (keys: any[], kid: string | undefined, alg: 'RS256' | 'ES256') => {
318
+ const isUsable = (k: any) =>
319
+ k &&
320
+ k.use !== 'enc' &&
321
+ (!k.alg || k.alg === alg);
322
+ return kid
323
+ ? keys.find((k) => k.kid === kid && isUsable(k))
324
+ : keys.find((k) => isUsable(k));
284
325
  };
285
326
 
286
327
  const resolveJwksKey = async (kid: string | undefined, alg: 'RS256' | 'ES256'): Promise<CryptoKey | null> => {
@@ -289,10 +330,10 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
289
330
  if (cached && Date.now() - jwksFetchedAt < jwksCacheTtlMs) return cached;
290
331
 
291
332
  let keys = await loadJwks(false);
292
- let match = kid ? keys.find((k) => k.kid === kid) : keys[0];
333
+ let match = matchJwk(keys, kid, alg);
293
334
  if (!match && kid) {
294
335
  keys = await loadJwks(true);
295
- match = keys.find((k) => k.kid === kid);
336
+ match = matchJwk(keys, kid, alg);
296
337
  }
297
338
  if (!match) return null;
298
339
 
@@ -402,7 +443,7 @@ export const basicAuth = (credentials: { user: string; pass: string }) => {
402
443
  const passMatch = timingSafeEqual(sha256(pass), expectedPassHash);
403
444
 
404
445
  if (userMatch && passMatch) {
405
- return next();
446
+ return next?.();
406
447
  }
407
448
 
408
449
  return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
@@ -419,6 +460,6 @@ export const hasRole = (role: string) => {
419
460
  if (!user || user.role !== role) {
420
461
  return ctx.status(403).json({ status: 'error', message: `Required role: ${role}` });
421
462
  }
422
- return next();
463
+ return next?.();
423
464
  };
424
465
  };
@@ -94,7 +94,31 @@ export const cors = (options: CorsOptions = {}) => {
94
94
  }
95
95
  if (exposeHeaders) ctx.setHeader('Access-Control-Expose-Headers', exposeHeaders);
96
96
 
97
- return next?.();
97
+ const res = next?.();
98
+ if (res && typeof (res as any).then === 'function') {
99
+ return (res as Promise<any>).then((r) => {
100
+ if (r instanceof Response) {
101
+ r.headers.set('Vary', 'Origin');
102
+ r.headers.set('Access-Control-Allow-Methods', methods);
103
+ if (matched) {
104
+ r.headers.set('Access-Control-Allow-Origin', matched);
105
+ if (credentials) r.headers.set('Access-Control-Allow-Credentials', 'true');
106
+ }
107
+ if (exposeHeaders) r.headers.set('Access-Control-Expose-Headers', exposeHeaders);
108
+ }
109
+ return r;
110
+ });
111
+ }
112
+ if (res instanceof Response) {
113
+ res.headers.set('Vary', 'Origin');
114
+ res.headers.set('Access-Control-Allow-Methods', methods);
115
+ if (matched) {
116
+ res.headers.set('Access-Control-Allow-Origin', matched);
117
+ if (credentials) res.headers.set('Access-Control-Allow-Credentials', 'true');
118
+ }
119
+ if (exposeHeaders) res.headers.set('Access-Control-Expose-Headers', exposeHeaders);
120
+ }
121
+ return res;
98
122
  };
99
123
  return mw;
100
124
  };
@@ -1,4 +1,5 @@
1
1
  import type { Context, Middleware, Next } from '../core/context';
2
+ import { timingSafeEqual } from 'node:crypto';
2
3
 
3
4
  export interface CsrfOptions {
4
5
  /** Allowed origins for state-changing requests (defaults to same-origin matching request Host) */
@@ -9,20 +10,44 @@ export interface CsrfOptions {
9
10
  cookieName?: string;
10
11
  headerName?: string;
11
12
  requireToken?: boolean;
13
+ /** Allow requests that omit both Origin and Referer headers (default: false) */
14
+ allowMissingOrigin?: boolean;
12
15
  }
13
16
 
14
17
  const DEFAULT_IGNORE = new Set(['GET', 'HEAD', 'OPTIONS']);
15
18
 
19
+ const resolveRequestOrigin = (ctx: Context): string => {
20
+ try {
21
+ const parsed = new URL(ctx.req.url);
22
+ if (ctx._trustProxy) {
23
+ const fwdHost = ctx.req.headers.get('x-forwarded-host')?.split(',')[0]?.trim();
24
+ const fwdProto = ctx.req.headers.get('x-forwarded-proto')?.split(',')[0]?.trim();
25
+ if (fwdHost) {
26
+ const proto = fwdProto ? `${fwdProto}:` : parsed.protocol;
27
+ return `${proto}//${fwdHost}`;
28
+ }
29
+ }
30
+ const host = ctx.req.headers.get('host')?.trim();
31
+ if (host) {
32
+ return `${parsed.protocol}//${host}`;
33
+ }
34
+ return parsed.origin;
35
+ } catch {
36
+ return '';
37
+ }
38
+ };
39
+
16
40
  export const csrf = (options: CsrfOptions = {}): Middleware => {
17
41
  const ignore = options.ignoreMethods ? new Set(options.ignoreMethods.map((m) => m.toUpperCase())) : DEFAULT_IGNORE;
18
42
  const allowed = options.allowedOrigins ? new Set(options.allowedOrigins) : null;
19
43
  const cookieName = options.cookieName || 'csrf_token';
20
44
  const headerName = (options.headerName || 'x-csrf-token').toLowerCase();
21
45
  const requireToken = options.requireToken === true;
46
+ const allowMissingOrigin = options.allowMissingOrigin === true;
22
47
 
23
48
  return (ctx: Context, next: Next) => {
24
49
  const method = ctx.req.method.toUpperCase();
25
- if (ignore.has(method)) return next();
50
+ if (ignore.has(method)) return next?.();
26
51
 
27
52
  const secFetchSite = ctx.req.headers.get('sec-fetch-site');
28
53
  const origin = ctx.req.headers.get('origin');
@@ -52,26 +77,32 @@ export const csrf = (options: CsrfOptions = {}): Middleware => {
52
77
  }
53
78
 
54
79
  if (sourceOrigin) {
55
- let reqOrigin: string;
56
- try {
57
- reqOrigin = new URL(ctx.req.url).origin;
58
- } catch {
59
- reqOrigin = '';
60
- }
61
- const isAllowed = sourceOrigin === reqOrigin || (allowed !== null && allowed.has(sourceOrigin));
80
+ const reqOrigin = resolveRequestOrigin(ctx);
81
+ const isAllowed = (reqOrigin !== '' && sourceOrigin === reqOrigin) || (allowed !== null && allowed.has(sourceOrigin));
62
82
  if (!isAllowed) {
63
83
  return Response.json(
64
84
  { status: 'error', code: 'CSRF_FORBIDDEN', message: 'Origin mismatch' },
65
85
  { status: 403 }
66
86
  );
67
87
  }
88
+ } else if (!allowMissingOrigin && secFetchSite !== 'same-origin') {
89
+ return Response.json(
90
+ { status: 'error', code: 'CSRF_FORBIDDEN', message: 'Missing Origin or Referer header' },
91
+ { status: 403 }
92
+ );
68
93
  }
69
94
 
70
95
  // 3. Optional double-submit token check
71
96
  if (requireToken) {
72
97
  const cookieToken = ctx.cookies[cookieName];
73
98
  const headerToken = ctx.req.headers.get(headerName);
74
- if (!cookieToken || !headerToken || cookieToken !== headerToken) {
99
+ let tokensMatch = false;
100
+ if (cookieToken && headerToken) {
101
+ const a = Buffer.from(cookieToken);
102
+ const b = Buffer.from(headerToken);
103
+ tokensMatch = a.length === b.length && timingSafeEqual(a, b);
104
+ }
105
+ if (!tokensMatch) {
75
106
  return Response.json(
76
107
  { status: 'error', code: 'CSRF_TOKEN_INVALID', message: 'Invalid or missing CSRF token' },
77
108
  { status: 403 }
@@ -15,6 +15,7 @@ export const Hash = {
15
15
  },
16
16
 
17
17
  needsRehash: (hash: string): boolean => {
18
+ if (!hash || typeof hash !== 'string') return true;
18
19
  const { algorithm, memoryCost, timeCost } = BARE_CONFIG.hash;
19
20
  if (algorithm === 'bcrypt') {
20
21
  if (!/^\$2[aby]\$/.test(hash)) return true;
@@ -29,7 +29,7 @@ const buildReplayResponse = (existing: CachedIdempotentEntry): Response => {
29
29
  };
30
30
 
31
31
  const extractIdemKey = (ctx: Context, headerName: string): string | undefined => {
32
- const rawKey = ctx.req.headers.get(headerName);
32
+ const rawKey = ctx.req.headers.get(headerName)?.trim();
33
33
  if (!rawKey) return undefined;
34
34
  const rawUrl = ctx.req.url;
35
35
  const s = rawUrl.indexOf('/', 8);
@@ -82,17 +82,25 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
82
82
  if (!key) return;
83
83
  (ctx as any)._idempotencyKey = undefined;
84
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);
85
+ const isStream = resVal instanceof Response && (resVal.headers.get('content-type') || '').includes('text/event-stream');
86
+ const clonedRes = !isStream && status >= 200 && status < 300 && resVal instanceof Response ? resVal.clone() : null;
87
+ const ct = clonedRes ? (clonedRes.headers.get('content-type') || 'application/json') : undefined;
88
+ void (async () => {
89
+ try {
90
+ if (!isStream && status >= 200 && status < 300) {
91
+ if (clonedRes) {
92
+ const buf = await clonedRes.arrayBuffer();
93
+ await externalStore.set(key, { status, rawBody: buf, contentType: ct, expiresAt: Date.now() + ttlMs }, ttlMs);
94
+ } else {
95
+ await externalStore.set(key, { status, body: resVal, expiresAt: Date.now() + ttlMs }, ttlMs);
96
+ }
97
+ }
98
+ } catch {
99
+ // Best-effort cache write
100
+ } finally {
101
+ await externalStore.release(key);
94
102
  }
95
- }
103
+ })();
96
104
  };
97
105
 
98
106
  (mw as any).__idempotencyRelease = (ctx: Context) => {
@@ -64,29 +64,37 @@ export const redisStore = (client: any, options: RedisStoreOptions = {}): BareSt
64
64
  }
65
65
  };
66
66
 
67
+ const setExpiry = async (fullKey: string, windowMs: number): Promise<void> => {
68
+ if (useSend) {
69
+ await client.send('PEXPIRE', [fullKey, String(windowMs)]);
70
+ } else if (typeof client.pexpire === 'function') {
71
+ await client.pexpire(fullKey, windowMs);
72
+ } else if (typeof client.expire === 'function') {
73
+ await client.expire(fullKey, Math.max(1, Math.ceil(windowMs / 1000)));
74
+ }
75
+ };
76
+
67
77
  return {
68
78
  async increment(key: string, windowMs: number): Promise<{ count: number; resetAt: number }> {
69
79
  const fullKey = `${prefix}rl:${key}`;
70
80
  const count = Number(await cmdIncr(fullKey));
71
81
  if (count === 1) {
72
- if (useSend) {
73
- await client.send('PEXPIRE', [fullKey, String(windowMs)]);
74
- } else if (typeof client.pexpire === 'function') {
75
- await client.pexpire(fullKey, windowMs);
76
- } else if (typeof client.expire === 'function') {
77
- await client.expire(fullKey, Math.max(1, Math.ceil(windowMs / 1000)));
78
- }
82
+ await setExpiry(fullKey, windowMs);
79
83
  }
80
84
  let pttl = windowMs;
85
+ let rawPttl: number | null = null;
81
86
  if (useSend) {
82
- const res = Number(await client.send('PTTL', [fullKey]));
83
- if (Number.isFinite(res) && res > 0) pttl = res;
87
+ rawPttl = Number(await client.send('PTTL', [fullKey]));
84
88
  } else if (typeof client.pttl === 'function') {
85
- const res = Number(await client.pttl(fullKey));
86
- if (Number.isFinite(res) && res > 0) pttl = res;
89
+ rawPttl = Number(await client.pttl(fullKey));
87
90
  } else if (typeof client.ttl === 'function') {
88
- const res = Number(await client.ttl(fullKey));
89
- if (Number.isFinite(res) && res > 0) pttl = res * 1000;
91
+ const t = Number(await client.ttl(fullKey));
92
+ rawPttl = t < 0 ? t : t * 1000;
93
+ }
94
+ if (rawPttl === -1) {
95
+ await setExpiry(fullKey, windowMs);
96
+ } else if (rawPttl !== null && Number.isFinite(rawPttl) && rawPttl > 0) {
97
+ pttl = rawPttl;
90
98
  }
91
99
  return { count, resetAt: Date.now() + pttl };
92
100
  },
@@ -96,7 +104,7 @@ export const redisStore = (client: any, options: RedisStoreOptions = {}): BareSt
96
104
  if (!raw) return undefined;
97
105
  try {
98
106
  const parsed = JSON.parse(typeof raw === 'string' ? raw : String(raw));
99
- if (parsed.rawBodyBase64) {
107
+ if (typeof parsed.rawBodyBase64 === 'string') {
100
108
  const buf = Buffer.from(parsed.rawBodyBase64, 'base64');
101
109
  return {
102
110
  status: parsed.status,
@@ -12,8 +12,10 @@ export const timeout = (ms = 10000, options: TimeoutOptions = {}): Middleware =>
12
12
  const mw: Middleware = async (_ctx: Context, next: Next) => {
13
13
  let timer: ReturnType<typeof setTimeout> | undefined;
14
14
  try {
15
+ const nextPromise = Promise.resolve(next());
15
16
  const timeoutPromise = new Promise<Response>((resolve) => {
16
17
  timer = setTimeout(() => {
18
+ nextPromise.catch(() => {});
17
19
  resolve(
18
20
  Response.json(
19
21
  { status: 'error', code: 'REQUEST_TIMEOUT', message },
@@ -22,7 +24,7 @@ export const timeout = (ms = 10000, options: TimeoutOptions = {}): Middleware =>
22
24
  );
23
25
  }, ms);
24
26
  });
25
- return await Promise.race([Promise.resolve(next()), timeoutPromise]);
27
+ return await Promise.race([nextPromise, timeoutPromise]);
26
28
  } finally {
27
29
  if (timer !== undefined) clearTimeout(timer);
28
30
  }
@@ -47,7 +47,10 @@ export const typebox = (schema: any): Middleware => {
47
47
 
48
48
  if (isCtx) (ctx as any).body = body;
49
49
  return next ? next() : undefined;
50
- } catch {
50
+ } catch (e: any) {
51
+ if (e?.status === 413) {
52
+ return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
53
+ }
51
54
  return errorJSON({ status: 'error', message: 'Malformed JSON payload' });
52
55
  }
53
56
  };
@@ -64,6 +67,14 @@ export const native = (schema: any): Middleware => {
64
67
  const kLen = keys.length;
65
68
  const reqSet = Array.isArray(schema.required) ? new Set<string>(schema.required) : null;
66
69
 
70
+ const matchesNativeType = (val: any, expected: string | undefined): boolean => {
71
+ if (expected === 'array') return Array.isArray(val);
72
+ if (expected === 'integer') return typeof val === 'number' && Number.isInteger(val);
73
+ if (expected === 'object') return val !== null && typeof val === 'object' && !Array.isArray(val);
74
+ if (expected === 'null') return val === null;
75
+ return typeof val === expected;
76
+ };
77
+
67
78
  const mw: Middleware = async (ctx: any, next?: any) => {
68
79
  try {
69
80
  const isCtx = ctx instanceof Object && 'req' in ctx;
@@ -87,7 +98,7 @@ export const native = (schema: any): Middleware => {
87
98
  }
88
99
  continue;
89
100
  }
90
- if (typeof body[k] !== props[k]?.type) {
101
+ if (!matchesNativeType(body[k], props[k]?.type)) {
91
102
  return errorJSON({
92
103
  status: 'error',
93
104
  code: 'TYPE_MISMATCH',
@@ -100,7 +111,10 @@ export const native = (schema: any): Middleware => {
100
111
  if (isCtx) (ctx as any).body = body;
101
112
 
102
113
  return next ? next() : undefined;
103
- } catch {
114
+ } catch (e: any) {
115
+ if (e?.status === 413) {
116
+ return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
117
+ }
104
118
  return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
105
119
  }
106
120
  };
@@ -130,7 +144,10 @@ export const zod = (schema: z.ZodSchema): Middleware => {
130
144
  if (isCtx) (ctx as any).body = result.data;
131
145
 
132
146
  return next ? next() : undefined;
133
- } catch {
147
+ } catch (e: any) {
148
+ if (e?.status === 413) {
149
+ return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
150
+ }
134
151
  return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
135
152
  }
136
153
  };
@@ -184,28 +201,35 @@ const compileSingleSchema = (schema: any): ((val: any) => { ok: boolean; data?:
184
201
  };
185
202
  };
186
203
 
187
- const buildProjectorExpr = (schema: any, accessor: string): string | null => {
204
+ const buildProjectorStatements = (schema: any, srcVar: string, dstVar: string, depth = 0): string | null => {
188
205
  const props = schema?.properties;
189
206
  if (!props || typeof props !== 'object') return null;
190
- const entries: string[] = [];
207
+ let stmts = '';
208
+ let idx = 0;
191
209
  for (const [k, subSchema] of Object.entries<any>(props)) {
210
+ if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
192
211
  const keyLit = JSON.stringify(k);
193
- const propAccess = `${accessor}[${keyLit}]`;
194
- const nestedExpr = buildProjectorExpr(subSchema, propAccess);
195
- if (nestedExpr) {
196
- entries.push(`${keyLit}: (${propAccess} && typeof ${propAccess} === 'object' && !Array.isArray(${propAccess})) ? ${nestedExpr} : ${propAccess}`);
212
+ const valVar = `v_${depth}_${idx++}`;
213
+ const nestedDst = `d_${depth}_${idx}`;
214
+ const nestedStmts = buildProjectorStatements(subSchema, valVar, nestedDst, depth + 1);
215
+ stmts += `const ${valVar} = ${srcVar}[${keyLit}];\n`;
216
+ if (nestedStmts) {
217
+ stmts += `if (${valVar} !== undefined) {\n`;
218
+ stmts += ` if (${valVar} && typeof ${valVar} === 'object' && !Array.isArray(${valVar})) {\n`;
219
+ stmts += ` const ${nestedDst} = {};\n${nestedStmts} ${dstVar}[${keyLit}] = ${nestedDst};\n`;
220
+ stmts += ` } else {\n ${dstVar}[${keyLit}] = ${valVar};\n }\n}\n`;
197
221
  } else {
198
- entries.push(`${keyLit}: ${propAccess}`);
222
+ stmts += `if (${valVar} !== undefined) ${dstVar}[${keyLit}] = ${valVar};\n`;
199
223
  }
200
224
  }
201
- return `{ ${entries.join(', ')} }`;
225
+ return stmts;
202
226
  };
203
227
 
204
228
  const compileProjector = (schema: any): ((val: any) => any) | null => {
205
229
  if (!schema || '_def' in schema) return null; // Zod safeParse strips unknown keys natively
206
230
  if (schema.type === 'array' && schema.items) {
207
- const itemExpr = buildProjectorExpr(schema.items, 'item');
208
- if (!itemExpr) return null;
231
+ const itemStmts = buildProjectorStatements(schema.items, 'item', 'outItem');
232
+ if (!itemStmts) return null;
209
233
  return new Function(
210
234
  `return function(arr) {
211
235
  if (!Array.isArray(arr)) return arr;
@@ -213,18 +237,26 @@ const compileProjector = (schema: any): ((val: any) => any) | null => {
213
237
  const out = new Array(len);
214
238
  for (let i = 0; i < len; i++) {
215
239
  const item = arr[i];
216
- out[i] = (item && typeof item === 'object' && !Array.isArray(item)) ? ${itemExpr} : item;
240
+ if (item && typeof item === 'object' && !Array.isArray(item)) {
241
+ const outItem = {};
242
+ ${itemStmts}
243
+ out[i] = outItem;
244
+ } else {
245
+ out[i] = item;
246
+ }
217
247
  }
218
248
  return out;
219
249
  }`
220
250
  )();
221
251
  }
222
- const objExpr = buildProjectorExpr(schema, 'o');
223
- if (!objExpr) return null;
252
+ const objStmts = buildProjectorStatements(schema, 'o', 'out');
253
+ if (!objStmts) return null;
224
254
  return new Function(
225
255
  `return function(o) {
226
256
  if (!o || typeof o !== 'object' || Array.isArray(o)) return o;
227
- return ${objExpr};
257
+ const out = {};
258
+ ${objStmts}
259
+ return out;
228
260
  }`
229
261
  )();
230
262
  };
@@ -244,6 +276,14 @@ export const createResponseFilter = (schema: any): ((val: any) => any) => {
244
276
  };
245
277
  };
246
278
 
279
+ const unwrapPropType = (propSchema: any): string | undefined => {
280
+ let cur = propSchema;
281
+ while (cur?._def && (cur._def.typeName === 'ZodOptional' || cur._def.typeName === 'ZodDefault' || cur._def.typeName === 'ZodNullable')) {
282
+ cur = cur._def.innerType;
283
+ }
284
+ return cur?.type || cur?._def?.typeName;
285
+ };
286
+
247
287
  const coerceFields = (obj: Record<string, any>, schema: any): Record<string, any> => {
248
288
  const props = schema?.properties || (schema?._def?.shape ? (typeof schema._def.shape === 'function' ? schema._def.shape() : schema._def.shape) : null);
249
289
  if (!props) return obj;
@@ -252,11 +292,11 @@ const coerceFields = (obj: Record<string, any>, schema: any): Record<string, any
252
292
  if (!Object.hasOwn(out, k)) continue;
253
293
  const val = out[k];
254
294
  if (typeof val !== 'string') continue;
255
- const tType = propSchema?.type || propSchema?._def?.typeName;
295
+ const tType = unwrapPropType(propSchema);
256
296
  if (tType === 'number' || tType === 'integer' || tType === 'ZodNumber') {
257
297
  if (val.trim() !== '') {
258
298
  const n = Number(val);
259
- if (!Number.isNaN(n)) out[k] = n;
299
+ if (Number.isFinite(n)) out[k] = n;
260
300
  }
261
301
  } else if (tType === 'boolean' || tType === 'ZodBoolean') {
262
302
  if (val === 'true') out[k] = true;
@@ -22,13 +22,32 @@ export const compress = (options: CompressOptions = {}): Middleware => {
22
22
  const encodings: CompressionEncoding[] = options.encodings ?? ['zstd', 'br', 'gzip'];
23
23
  const hasZstd = typeof (Bun as any).zstdCompressSync === 'function';
24
24
 
25
+ const isAccepted = (lower: string, enc: CompressionEncoding): boolean => {
26
+ const parts = lower.split(',');
27
+ for (let i = 0; i < parts.length; i++) {
28
+ const part = parts[i]!.trim();
29
+ if (!part) continue;
30
+ const semi = part.indexOf(';');
31
+ const name = (semi === -1 ? part : part.slice(0, semi)).trim();
32
+ if (name !== enc) continue;
33
+ if (semi !== -1) {
34
+ const qMatch = part.slice(semi + 1).match(/q\s*=\s*([0-9.]+)/);
35
+ if (qMatch) {
36
+ const qVal = parseFloat(qMatch[1]!);
37
+ if (Number.isFinite(qVal) && qVal <= 0) return false;
38
+ }
39
+ }
40
+ return true;
41
+ }
42
+ return false;
43
+ };
44
+
25
45
  const negotiate = (accept: string): CompressionEncoding | null => {
26
46
  const lower = accept.toLowerCase();
27
47
  for (let i = 0; i < encodings.length; i++) {
28
48
  const enc = encodings[i]!;
29
- if (enc === 'zstd' && hasZstd && lower.includes('zstd')) return 'zstd';
30
- if (enc === 'br' && lower.includes('br')) return 'br';
31
- if (enc === 'gzip' && lower.includes('gzip')) return 'gzip';
49
+ if (enc === 'zstd' && !hasZstd) continue;
50
+ if (isAccepted(lower, enc)) return enc;
32
51
  }
33
52
  return null;
34
53
  };
@@ -65,7 +84,12 @@ export const compress = (options: CompressOptions = {}): Middleware => {
65
84
 
66
85
  const headers = new Headers(res.headers);
67
86
  headers.set('Content-Encoding', chosen);
68
- headers.set('Vary', 'Accept-Encoding');
87
+ const existingVary = headers.get('Vary');
88
+ if (!existingVary) {
89
+ headers.set('Vary', 'Accept-Encoding');
90
+ } else if (!existingVary.toLowerCase().split(',').some((v) => v.trim() === 'accept-encoding')) {
91
+ headers.set('Vary', `${existingVary}, Accept-Encoding`);
92
+ }
69
93
  headers.delete('Content-Length');
70
94
 
71
95
  return new Response(compressed, { status: res.status, headers });
@@ -37,7 +37,7 @@ export const logger = (options: LoggerOptions = {}): Middleware => {
37
37
 
38
38
  return (ctx: Context, next) => {
39
39
  const path = getPath(ctx.req.url);
40
- if (skip?.(ctx, path)) return next();
40
+ if (skip?.(ctx, path)) return next?.();
41
41
 
42
42
  const reqId = attachId ? ctx.requestId : undefined;
43
43
  if (reqId) {
@@ -61,6 +61,6 @@ export const logger = (options: LoggerOptions = {}): Middleware => {
61
61
  console.log(`[${entry.timestamp}] ${entry.method} ${entry.path}${idPart}`);
62
62
  }
63
63
 
64
- return next();
64
+ return next?.();
65
65
  };
66
66
  };