barejs 0.1.52 → 0.1.54
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.
- package/README.md +10 -10
- package/dist/index.js +62 -60
- package/dist/types/core/context.d.ts +1 -0
- package/dist/types/security/auth.d.ts +2 -0
- package/llms.txt +1 -1
- package/package.json +1 -1
- package/src/client/index.ts +4 -3
- package/src/core/bare.ts +9 -16
- package/src/core/context.ts +41 -22
- package/src/core/radix.ts +3 -1
- package/src/security/auth.ts +50 -9
- package/src/security/cors.ts +25 -1
- package/src/security/csrf.ts +8 -1
- package/src/security/idempotency.ts +17 -10
- package/src/security/store.ts +22 -14
- package/src/security/validators.ts +1 -0
- package/src/utils/compress.ts +15 -3
- package/src/utils/static.ts +7 -4
|
@@ -19,6 +19,8 @@ export interface BareAuthOptions {
|
|
|
19
19
|
publicKey?: string | CryptoKey;
|
|
20
20
|
jwksUri?: string;
|
|
21
21
|
jwksCacheTtlMs?: number;
|
|
22
|
+
issuer?: string | string[];
|
|
23
|
+
audience?: string | string[];
|
|
22
24
|
revocationStore?: RevocationStore;
|
|
23
25
|
isRevoked?: (payload: any, token: string) => boolean | Promise<boolean>;
|
|
24
26
|
}
|
package/llms.txt
CHANGED
|
@@ -107,7 +107,7 @@ app.post('/pay', idempotency({ ttlMs: 86_400_000, maxKeys: 10_000, store }), (ct
|
|
|
107
107
|
|
|
108
108
|
// Thundering-herd / Cache-stampede request coalescer
|
|
109
109
|
const sf = createSingleflight();
|
|
110
|
-
app.get('/report', () => sf
|
|
110
|
+
app.get('/report', () => sf('report-key', async () => ({ total: 100 })));
|
|
111
111
|
|
|
112
112
|
// Auth & Hashing (HS256 sync fast-path + RS256/ES256/JWKS async verification + revocationStore)
|
|
113
113
|
const hash = await Hash.make('password'); // Argon2id (64MB default)
|
package/package.json
CHANGED
package/src/client/index.ts
CHANGED
|
@@ -91,9 +91,10 @@ export interface BareClient<Routes extends RouteSchema = RouteSchema> {
|
|
|
91
91
|
const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions): string => {
|
|
92
92
|
let finalPath = path;
|
|
93
93
|
if (options?.params) {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
94
|
+
const params = options.params;
|
|
95
|
+
finalPath = finalPath.replace(/:([a-zA-Z0-9_]+)(?=\/|$)/g, (match, key) =>
|
|
96
|
+
Object.hasOwn(params, key) ? encodeURIComponent(String(params[key])) : match
|
|
97
|
+
);
|
|
97
98
|
}
|
|
98
99
|
const base = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
|
|
99
100
|
const normalizedPath = finalPath.startsWith('/') ? finalPath : `/${finalPath}`;
|
package/src/core/bare.ts
CHANGED
|
@@ -622,24 +622,17 @@ export class BareJS<
|
|
|
622
622
|
}`
|
|
623
623
|
: '';
|
|
624
624
|
|
|
625
|
-
const
|
|
626
|
-
const hasStaticMw = staticMws.length > 0;
|
|
625
|
+
const hasStaticMw = this.groupMiddleware.some((m: any) => m.__isStatic);
|
|
627
626
|
const runStatic = hasStaticMw
|
|
628
627
|
? async (ctx: Context) => {
|
|
629
|
-
const
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
}
|
|
638
|
-
}
|
|
639
|
-
return r;
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
return undefined;
|
|
628
|
+
const mws = this.groupMiddleware;
|
|
629
|
+
const dispatch = async (idx: number): Promise<Response | undefined> => {
|
|
630
|
+
if (idx >= mws.length) return undefined;
|
|
631
|
+
const r = await mws[idx](ctx, () => dispatch(idx + 1));
|
|
632
|
+
if (r instanceof Response) return applyCtxHeaders(r, ctx);
|
|
633
|
+
return undefined;
|
|
634
|
+
};
|
|
635
|
+
return dispatch(0);
|
|
643
636
|
}
|
|
644
637
|
: undefined;
|
|
645
638
|
|
package/src/core/context.ts
CHANGED
|
@@ -108,7 +108,8 @@ export class Context {
|
|
|
108
108
|
}
|
|
109
109
|
|
|
110
110
|
public getQuery(key: string): string | undefined {
|
|
111
|
-
|
|
111
|
+
const q = this.query;
|
|
112
|
+
return Object.hasOwn(q, key) ? q[key] : undefined;
|
|
112
113
|
}
|
|
113
114
|
|
|
114
115
|
public get cookies(): Record<string, string> {
|
|
@@ -140,13 +141,23 @@ export class Context {
|
|
|
140
141
|
}
|
|
141
142
|
|
|
142
143
|
public setCookie(name: string, value: string, options: CookieOptions = {}): this {
|
|
144
|
+
if (!name || /[\r\n;= \t]/.test(name)) {
|
|
145
|
+
throw new Error('Invalid cookie name');
|
|
146
|
+
}
|
|
147
|
+
const path = options.path ?? '/';
|
|
148
|
+
if (/[\r\n;]/.test(path)) {
|
|
149
|
+
throw new Error('Invalid cookie path');
|
|
150
|
+
}
|
|
151
|
+
if (options.domain && /[\r\n;]/.test(options.domain)) {
|
|
152
|
+
throw new Error('Invalid cookie domain');
|
|
153
|
+
}
|
|
143
154
|
let finalVal = value;
|
|
144
155
|
if (options.secret) {
|
|
145
156
|
const sig = createHmac('sha256', options.secret).update(value).digest('base64url');
|
|
146
157
|
finalVal = `${value}.${sig}`;
|
|
147
158
|
}
|
|
148
159
|
let cookieStr = `${name}=${encodeURIComponent(finalVal)}`;
|
|
149
|
-
cookieStr += `; Path=${
|
|
160
|
+
cookieStr += `; Path=${path}`;
|
|
150
161
|
if (options.domain) cookieStr += `; Domain=${options.domain}`;
|
|
151
162
|
if (options.maxAge !== undefined) cookieStr += `; Max-Age=${Math.floor(options.maxAge)}`;
|
|
152
163
|
if (options.expires) cookieStr += `; Expires=${options.expires.toUTCString()}`;
|
|
@@ -189,16 +200,19 @@ export class Context {
|
|
|
189
200
|
if (contentType && contentType.includes("application/json")) {
|
|
190
201
|
const lenHeader = this.req.headers.get("content-length");
|
|
191
202
|
if (lenHeader !== null) {
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
203
|
+
const trimmed = lenHeader.trim();
|
|
204
|
+
const lenNum = trimmed.length > 0 ? Number(trimmed) : NaN;
|
|
205
|
+
if (Number.isInteger(lenNum) && lenNum >= 0) {
|
|
206
|
+
if (lenNum > maxBytes) {
|
|
207
|
+
const err: any = new Error("Payload Too Large");
|
|
208
|
+
err.status = 413;
|
|
209
|
+
throw err;
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
return this.body = await this.req.json();
|
|
213
|
+
} catch {
|
|
214
|
+
return this.body = null;
|
|
215
|
+
}
|
|
202
216
|
}
|
|
203
217
|
}
|
|
204
218
|
try {
|
|
@@ -236,6 +250,16 @@ export class Context {
|
|
|
236
250
|
return this;
|
|
237
251
|
}
|
|
238
252
|
|
|
253
|
+
private _applyCookies(res: Response): Response {
|
|
254
|
+
if (this._setCookies) {
|
|
255
|
+
for (let i = 0; i < this._setCookies.length; i++) {
|
|
256
|
+
res.headers.append('Set-Cookie', this._setCookies[i]!);
|
|
257
|
+
}
|
|
258
|
+
this._setCookies = undefined;
|
|
259
|
+
}
|
|
260
|
+
return res;
|
|
261
|
+
}
|
|
262
|
+
|
|
239
263
|
public json(data: any): Response {
|
|
240
264
|
const status = this._status || 200;
|
|
241
265
|
let res: Response;
|
|
@@ -259,12 +283,7 @@ export class Context {
|
|
|
259
283
|
});
|
|
260
284
|
}
|
|
261
285
|
|
|
262
|
-
|
|
263
|
-
for (let i = 0; i < this._setCookies.length; i++) {
|
|
264
|
-
res.headers.append('Set-Cookie', this._setCookies[i]!);
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
return res;
|
|
286
|
+
return this._applyCookies(res);
|
|
268
287
|
}
|
|
269
288
|
|
|
270
289
|
public set(key: string, value: any): this {
|
|
@@ -303,7 +322,7 @@ export class Context {
|
|
|
303
322
|
'content-type': 'text/html; charset=utf-8',
|
|
304
323
|
...(this._headers || {})
|
|
305
324
|
};
|
|
306
|
-
return new Response(content, { status: status ?? this._status, headers });
|
|
325
|
+
return this._applyCookies(new Response(content, { status: status ?? this._status, headers }));
|
|
307
326
|
}
|
|
308
327
|
|
|
309
328
|
public text(content: string, status?: number): Response {
|
|
@@ -311,7 +330,7 @@ export class Context {
|
|
|
311
330
|
'content-type': 'text/plain; charset=utf-8',
|
|
312
331
|
...(this._headers || {})
|
|
313
332
|
};
|
|
314
|
-
return new Response(content, { status: status ?? this._status, headers });
|
|
333
|
+
return this._applyCookies(new Response(content, { status: status ?? this._status, headers }));
|
|
315
334
|
}
|
|
316
335
|
|
|
317
336
|
public redirect(url: string, status: number = 302): Response {
|
|
@@ -319,7 +338,7 @@ export class Context {
|
|
|
319
338
|
'location': url,
|
|
320
339
|
...(this._headers || {})
|
|
321
340
|
};
|
|
322
|
-
return new Response(null, { status, headers });
|
|
341
|
+
return this._applyCookies(new Response(null, { status, headers }));
|
|
323
342
|
}
|
|
324
343
|
|
|
325
344
|
public sse(
|
|
@@ -375,7 +394,7 @@ export class Context {
|
|
|
375
394
|
'connection': 'keep-alive',
|
|
376
395
|
...(this._headers || {})
|
|
377
396
|
};
|
|
378
|
-
return new Response(stream, { status: this._status || 200, headers });
|
|
397
|
+
return this._applyCookies(new Response(stream, { status: this._status || 200, headers }));
|
|
379
398
|
}
|
|
380
399
|
|
|
381
400
|
public get requestId(): string {
|
package/src/core/radix.ts
CHANGED
|
@@ -190,10 +190,12 @@ export class RadixNode {
|
|
|
190
190
|
}
|
|
191
191
|
|
|
192
192
|
const pVar = `pL${level}`;
|
|
193
|
-
code += `${indent}
|
|
193
|
+
code += `${indent}if (slash${level} > ${idxPrefix}) {\n`;
|
|
194
|
+
code += `${indent} const ${pVar} = ${pathPrefix}.slice(${idxPrefix}, slash${level});\n`;
|
|
194
195
|
|
|
195
196
|
const newAccumulator = [...paramAccumulator, { name: this.paramName!, varName: pVar }];
|
|
196
197
|
code += pNode.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, newAccumulator);
|
|
198
|
+
code += `${indent}}\n`;
|
|
197
199
|
}
|
|
198
200
|
|
|
199
201
|
// 3. Wildcard Node Logic (Catch-All *)
|
package/src/security/auth.ts
CHANGED
|
@@ -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
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
if (forceRefresh)
|
|
283
|
-
|
|
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 =
|
|
333
|
+
let match = matchJwk(keys, kid, alg);
|
|
293
334
|
if (!match && kid) {
|
|
294
335
|
keys = await loadJwks(true);
|
|
295
|
-
match = keys
|
|
336
|
+
match = matchJwk(keys, kid, alg);
|
|
296
337
|
}
|
|
297
338
|
if (!match) return null;
|
|
298
339
|
|
package/src/security/cors.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
};
|
package/src/security/csrf.ts
CHANGED
|
@@ -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) */
|
|
@@ -71,7 +72,13 @@ export const csrf = (options: CsrfOptions = {}): Middleware => {
|
|
|
71
72
|
if (requireToken) {
|
|
72
73
|
const cookieToken = ctx.cookies[cookieName];
|
|
73
74
|
const headerToken = ctx.req.headers.get(headerName);
|
|
74
|
-
|
|
75
|
+
let tokensMatch = false;
|
|
76
|
+
if (cookieToken && headerToken) {
|
|
77
|
+
const a = Buffer.from(cookieToken);
|
|
78
|
+
const b = Buffer.from(headerToken);
|
|
79
|
+
tokensMatch = a.length === b.length && timingSafeEqual(a, b);
|
|
80
|
+
}
|
|
81
|
+
if (!tokensMatch) {
|
|
75
82
|
return Response.json(
|
|
76
83
|
{ status: 'error', code: 'CSRF_TOKEN_INVALID', message: 'Invalid or missing CSRF token' },
|
|
77
84
|
{ status: 403 }
|
|
@@ -82,17 +82,24 @@ 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
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
85
|
+
const clonedRes = status >= 200 && status < 300 && resVal instanceof Response ? resVal.clone() : null;
|
|
86
|
+
const ct = clonedRes ? (clonedRes.headers.get('content-type') || 'application/json') : undefined;
|
|
87
|
+
void (async () => {
|
|
88
|
+
try {
|
|
89
|
+
if (status >= 200 && status < 300) {
|
|
90
|
+
if (clonedRes) {
|
|
91
|
+
const buf = await clonedRes.arrayBuffer();
|
|
92
|
+
await externalStore.set(key, { status, rawBody: buf, contentType: ct, expiresAt: Date.now() + ttlMs }, ttlMs);
|
|
93
|
+
} else {
|
|
94
|
+
await externalStore.set(key, { status, body: resVal, expiresAt: Date.now() + ttlMs }, ttlMs);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
} catch {
|
|
98
|
+
// Best-effort cache write
|
|
99
|
+
} finally {
|
|
100
|
+
await externalStore.release(key);
|
|
94
101
|
}
|
|
95
|
-
}
|
|
102
|
+
})();
|
|
96
103
|
};
|
|
97
104
|
|
|
98
105
|
(mw as any).__idempotencyRelease = (ctx: Context) => {
|
package/src/security/store.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
89
|
-
|
|
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,
|
|
@@ -189,6 +189,7 @@ const buildProjectorExpr = (schema: any, accessor: string): string | null => {
|
|
|
189
189
|
if (!props || typeof props !== 'object') return null;
|
|
190
190
|
const entries: string[] = [];
|
|
191
191
|
for (const [k, subSchema] of Object.entries<any>(props)) {
|
|
192
|
+
if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
|
|
192
193
|
const keyLit = JSON.stringify(k);
|
|
193
194
|
const propAccess = `${accessor}[${keyLit}]`;
|
|
194
195
|
const nestedExpr = buildProjectorExpr(subSchema, propAccess);
|
package/src/utils/compress.ts
CHANGED
|
@@ -22,13 +22,25 @@ 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 idx = lower.indexOf(enc);
|
|
27
|
+
if (idx === -1) return false;
|
|
28
|
+
const comma = lower.indexOf(',', idx);
|
|
29
|
+
const segment = comma === -1 ? lower.slice(idx) : lower.slice(idx, comma);
|
|
30
|
+
const qIdx = segment.indexOf(';q=');
|
|
31
|
+
if (qIdx !== -1) {
|
|
32
|
+
const qVal = parseFloat(segment.slice(qIdx + 3));
|
|
33
|
+
if (Number.isFinite(qVal) && qVal <= 0) return false;
|
|
34
|
+
}
|
|
35
|
+
return true;
|
|
36
|
+
};
|
|
37
|
+
|
|
25
38
|
const negotiate = (accept: string): CompressionEncoding | null => {
|
|
26
39
|
const lower = accept.toLowerCase();
|
|
27
40
|
for (let i = 0; i < encodings.length; i++) {
|
|
28
41
|
const enc = encodings[i]!;
|
|
29
|
-
if (enc === 'zstd' && hasZstd
|
|
30
|
-
if (enc
|
|
31
|
-
if (enc === 'gzip' && lower.includes('gzip')) return 'gzip';
|
|
42
|
+
if (enc === 'zstd' && !hasZstd) continue;
|
|
43
|
+
if (isAccepted(lower, enc)) return enc;
|
|
32
44
|
}
|
|
33
45
|
return null;
|
|
34
46
|
};
|
package/src/utils/static.ts
CHANGED
|
@@ -65,6 +65,7 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
|
|
|
65
65
|
return ctx.status(403).send('Forbidden');
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
+
let realFile = filePath;
|
|
68
69
|
let fileSize = 0;
|
|
69
70
|
let mtimeMs = 0;
|
|
70
71
|
let etag = '';
|
|
@@ -74,21 +75,23 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
|
|
|
74
75
|
// Refresh LRU position
|
|
75
76
|
metaCache!.delete(filePath);
|
|
76
77
|
metaCache!.set(filePath, cached);
|
|
78
|
+
realFile = cached.realFile;
|
|
77
79
|
fileSize = cached.fileSize;
|
|
78
80
|
mtimeMs = cached.mtimeMs;
|
|
79
81
|
etag = cached.etag;
|
|
80
82
|
} else {
|
|
81
83
|
try {
|
|
82
|
-
const [realRoot,
|
|
84
|
+
const [realRoot, resolvedFile] = await Promise.all([
|
|
83
85
|
(realRootPromise ??= realpath(rootDir)),
|
|
84
86
|
realpath(filePath)
|
|
85
87
|
]);
|
|
86
88
|
const realPrefix = realRoot.endsWith(sep) ? realRoot : realRoot + sep;
|
|
87
|
-
if (
|
|
89
|
+
if (resolvedFile !== realRoot && !resolvedFile.startsWith(realPrefix)) {
|
|
88
90
|
return ctx.status(403).send('Forbidden');
|
|
89
91
|
}
|
|
90
|
-
const st = await stat(
|
|
92
|
+
const st = await stat(resolvedFile);
|
|
91
93
|
if (st.isDirectory()) return next();
|
|
94
|
+
realFile = resolvedFile;
|
|
92
95
|
fileSize = st.size;
|
|
93
96
|
mtimeMs = Math.floor(st.mtimeMs);
|
|
94
97
|
etag = enableEtag ? `W/"${fileSize.toString(16)}-${mtimeMs.toString(16)}"` : '';
|
|
@@ -111,7 +114,7 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
|
|
|
111
114
|
}
|
|
112
115
|
}
|
|
113
116
|
|
|
114
|
-
const file = Bun.file(
|
|
117
|
+
const file = Bun.file(realFile);
|
|
115
118
|
|
|
116
119
|
const headers: Record<string, string> = {
|
|
117
120
|
'Cache-Control': `public, max-age=${maxAge}`,
|