barejs 0.1.54 → 0.1.56
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 +13 -13
- package/dist/index.js +245 -142
- package/dist/types/core/bare.d.ts +5 -3
- package/dist/types/core/context.d.ts +7 -1
- package/dist/types/core/radix.d.ts +3 -5
- package/dist/types/core/router.d.ts +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/security/csrf.d.ts +2 -0
- package/dist/types/security/idempotency.d.ts +6 -1
- package/dist/types/security/store.d.ts +4 -1
- package/dist/types/utils/openapi.d.ts +1 -0
- package/llms.txt +4 -4
- package/package.json +2 -2
- package/src/client/index.ts +41 -13
- package/src/core/bare.ts +372 -114
- package/src/core/config.ts +3 -2
- package/src/core/context.ts +261 -76
- package/src/core/loader.ts +13 -3
- package/src/core/radix.ts +197 -110
- package/src/core/router.ts +39 -12
- package/src/index.ts +2 -2
- package/src/security/auth.ts +100 -11
- package/src/security/cors.ts +59 -9
- package/src/security/csrf.ts +33 -8
- package/src/security/hash.ts +10 -3
- package/src/security/idempotency.ts +170 -52
- package/src/security/rateLimit.ts +15 -5
- package/src/security/resilience.ts +34 -7
- package/src/security/store.ts +52 -8
- package/src/security/timeout.ts +8 -4
- package/src/security/validators.ts +618 -70
- package/src/utils/compress.ts +35 -18
- package/src/utils/logger.ts +2 -2
- package/src/utils/openapi.ts +46 -8
- package/src/utils/static.ts +36 -10
package/src/security/auth.ts
CHANGED
|
@@ -31,10 +31,36 @@ const importKey = async (secret: string): Promise<CryptoKey> => {
|
|
|
31
31
|
["sign", "verify"]
|
|
32
32
|
);
|
|
33
33
|
|
|
34
|
+
if (keyCache.size >= 1000) {
|
|
35
|
+
const oldest = keyCache.keys().next().value;
|
|
36
|
+
if (oldest !== undefined) keyCache.delete(oldest);
|
|
37
|
+
}
|
|
34
38
|
keyCache.set(secret, key);
|
|
35
39
|
return key;
|
|
36
40
|
};
|
|
37
41
|
|
|
42
|
+
const stripProtoKeys = (root: unknown): void => {
|
|
43
|
+
if (!root || typeof root !== 'object') return;
|
|
44
|
+
const stack: unknown[] = [root];
|
|
45
|
+
while (stack.length > 0) {
|
|
46
|
+
const cur = stack.pop();
|
|
47
|
+
if (!cur || typeof cur !== 'object') continue;
|
|
48
|
+
if (Array.isArray(cur)) {
|
|
49
|
+
for (let i = 0; i < cur.length; i++) {
|
|
50
|
+
if (cur[i] && typeof cur[i] === 'object') stack.push(cur[i]);
|
|
51
|
+
}
|
|
52
|
+
} else {
|
|
53
|
+
if (Object.hasOwn(cur, '__proto__')) {
|
|
54
|
+
delete (cur as Record<string, unknown>).__proto__;
|
|
55
|
+
}
|
|
56
|
+
const vals = Object.values(cur);
|
|
57
|
+
for (let i = 0; i < vals.length; i++) {
|
|
58
|
+
if (vals[i] && typeof vals[i] === 'object') stack.push(vals[i]);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
38
64
|
/**
|
|
39
65
|
* 4. TOKEN GENERATOR (Standard JWT)
|
|
40
66
|
*/
|
|
@@ -53,6 +79,33 @@ export const createToken = async (payload: object, secret: string): Promise<stri
|
|
|
53
79
|
return `${data}.${encodedSig}`;
|
|
54
80
|
};
|
|
55
81
|
|
|
82
|
+
const P256_N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
|
|
83
|
+
|
|
84
|
+
const getEs256TwinToken = (token: string): string | null => {
|
|
85
|
+
const d1 = token.indexOf('.');
|
|
86
|
+
if (d1 <= 0) return null;
|
|
87
|
+
const d2 = token.indexOf('.', d1 + 1);
|
|
88
|
+
if (d2 <= d1 + 1) return null;
|
|
89
|
+
const sigB64 = token.slice(d2 + 1);
|
|
90
|
+
if (!/^[A-Za-z0-9_-]+$/.test(sigB64)) return null;
|
|
91
|
+
const sigBuf = Buffer.from(sigB64, 'base64url');
|
|
92
|
+
if (sigBuf.length !== 64) return null;
|
|
93
|
+
try {
|
|
94
|
+
const hdr = JSON.parse(fromBase64Url(token.slice(0, d1)));
|
|
95
|
+
if (hdr?.alg !== 'ES256') return null;
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
const s = BigInt('0x' + sigBuf.subarray(32, 64).toString('hex'));
|
|
100
|
+
if (s <= 0n || s >= P256_N) return null;
|
|
101
|
+
const sTwin = P256_N - s;
|
|
102
|
+
const twinHex = sTwin.toString(16).padStart(64, '0');
|
|
103
|
+
const twinBuf = Buffer.allocUnsafe(64);
|
|
104
|
+
sigBuf.copy(twinBuf, 0, 0, 32);
|
|
105
|
+
Buffer.from(twinHex, 'hex').copy(twinBuf, 32);
|
|
106
|
+
return token.slice(0, d2 + 1) + twinBuf.toString('base64url');
|
|
107
|
+
};
|
|
108
|
+
|
|
56
109
|
const revokedTokens = new Map<string, number>();
|
|
57
110
|
|
|
58
111
|
/**
|
|
@@ -62,7 +115,11 @@ const revokedTokens = new Map<string, number>();
|
|
|
62
115
|
export function revokeToken(tokenOrJti: string, ttlMs?: number): void;
|
|
63
116
|
export function revokeToken(tokenOrJti: string, ttlMs: number, store: RevocationStore): Promise<void>;
|
|
64
117
|
export function revokeToken(tokenOrJti: string, ttlMs: number = 3600_000, store?: RevocationStore): void | Promise<void> {
|
|
118
|
+
const twin = getEs256TwinToken(tokenOrJti);
|
|
65
119
|
if (store) {
|
|
120
|
+
if (twin) {
|
|
121
|
+
return Promise.all([store.revoke(tokenOrJti, ttlMs), store.revoke(twin, ttlMs)]).then(() => {});
|
|
122
|
+
}
|
|
66
123
|
return store.revoke(tokenOrJti, ttlMs);
|
|
67
124
|
}
|
|
68
125
|
if (revokedTokens.size >= 10_000) {
|
|
@@ -75,7 +132,9 @@ export function revokeToken(tokenOrJti: string, ttlMs: number = 3600_000, store?
|
|
|
75
132
|
if (oldest !== undefined) revokedTokens.delete(oldest);
|
|
76
133
|
}
|
|
77
134
|
}
|
|
78
|
-
|
|
135
|
+
const exp = Date.now() + ttlMs;
|
|
136
|
+
revokedTokens.set(tokenOrJti, exp);
|
|
137
|
+
if (twin) revokedTokens.set(twin, exp);
|
|
79
138
|
}
|
|
80
139
|
|
|
81
140
|
export function isTokenRevoked(tokenOrJti: string): boolean;
|
|
@@ -140,6 +199,10 @@ const importPublicKey = async (keyOrPem: string | CryptoKey, alg: 'RS256' | 'ES2
|
|
|
140
199
|
false,
|
|
141
200
|
['verify']
|
|
142
201
|
);
|
|
202
|
+
if (pemKeyCache.size >= 1000) {
|
|
203
|
+
const oldest = pemKeyCache.keys().next().value;
|
|
204
|
+
if (oldest !== undefined) pemKeyCache.delete(oldest);
|
|
205
|
+
}
|
|
143
206
|
pemKeyCache.set(cacheKey, imported);
|
|
144
207
|
return imported;
|
|
145
208
|
};
|
|
@@ -196,13 +259,15 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
196
259
|
}
|
|
197
260
|
}
|
|
198
261
|
|
|
199
|
-
|
|
262
|
+
const twin = getEs256TwinToken(token);
|
|
263
|
+
if (isTokenRevoked(token) || (twin && isTokenRevoked(twin)) || (decoded?.jti && isTokenRevoked(String(decoded.jti)))) {
|
|
200
264
|
return ctx.status(401).send("Token revoked");
|
|
201
265
|
}
|
|
202
266
|
|
|
203
267
|
if (revocationStore) {
|
|
204
268
|
const checkStore = async () => {
|
|
205
269
|
if (await revocationStore.isRevoked(token)) return ctx.status(401).send("Token revoked");
|
|
270
|
+
if (twin && await revocationStore.isRevoked(twin)) return ctx.status(401).send("Token revoked");
|
|
206
271
|
if (decoded?.jti && await revocationStore.isRevoked(String(decoded.jti))) {
|
|
207
272
|
return ctx.status(401).send("Token revoked");
|
|
208
273
|
}
|
|
@@ -237,6 +302,9 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
237
302
|
|
|
238
303
|
if (isSymmetricOnly) {
|
|
239
304
|
const verifySync = (ctx: any, next: any) => {
|
|
305
|
+
if (!secret) {
|
|
306
|
+
return ctx.status(401).send("Unsupported token algorithm");
|
|
307
|
+
}
|
|
240
308
|
const authHeader = ctx.req.headers.get('Authorization');
|
|
241
309
|
|
|
242
310
|
if (!authHeader?.startsWith('Bearer ')) {
|
|
@@ -253,13 +321,17 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
253
321
|
const headerB64 = token.slice(0, firstDot);
|
|
254
322
|
const payloadB64 = token.slice(firstDot + 1, secondDot);
|
|
255
323
|
const sigB64 = token.slice(secondDot + 1);
|
|
324
|
+
if (!/^[A-Za-z0-9_-]+$/.test(sigB64)) {
|
|
325
|
+
return ctx.status(401).send("Invalid signature");
|
|
326
|
+
}
|
|
256
327
|
const data = token.slice(0, secondDot);
|
|
257
328
|
|
|
329
|
+
let decoded: any;
|
|
258
330
|
try {
|
|
259
331
|
const expectedSig = createHmac('sha256', secret).update(data).digest();
|
|
260
332
|
const actualSig = Buffer.from(sigB64, 'base64url');
|
|
261
333
|
|
|
262
|
-
if (actualSig.length !== expectedSig.length || !timingSafeEqual(actualSig, expectedSig)) {
|
|
334
|
+
if (actualSig.length !== expectedSig.length || actualSig.toString('base64url') !== sigB64 || !timingSafeEqual(actualSig, expectedSig)) {
|
|
263
335
|
return ctx.status(401).send("Invalid signature");
|
|
264
336
|
}
|
|
265
337
|
|
|
@@ -268,11 +340,15 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
268
340
|
return ctx.status(401).send("Unsupported token algorithm");
|
|
269
341
|
}
|
|
270
342
|
|
|
271
|
-
const
|
|
272
|
-
|
|
343
|
+
const payloadStr = fromBase64Url(payloadB64);
|
|
344
|
+
decoded = JSON.parse(payloadStr);
|
|
345
|
+
if (decoded && typeof decoded === 'object' && (payloadStr.indexOf('__proto__') !== -1 || payloadStr.indexOf('\\u') !== -1)) {
|
|
346
|
+
stripProtoKeys(decoded);
|
|
347
|
+
}
|
|
273
348
|
} catch {
|
|
274
349
|
return ctx.status(401).send("Token verification failed");
|
|
275
350
|
}
|
|
351
|
+
return checkClaimsAndRevocation(ctx, decoded, token, next);
|
|
276
352
|
};
|
|
277
353
|
|
|
278
354
|
if (customRevoked || revocationStore) {
|
|
@@ -306,7 +382,7 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
306
382
|
const body = (await res.json()) as { keys?: any[] };
|
|
307
383
|
jwksKeys = Array.isArray(body?.keys) ? body.keys : [];
|
|
308
384
|
jwksFetchedAt = Date.now();
|
|
309
|
-
|
|
385
|
+
jwkKeyCache.clear();
|
|
310
386
|
return jwksKeys;
|
|
311
387
|
})().finally(() => {
|
|
312
388
|
inFlightJwks = null;
|
|
@@ -315,9 +391,11 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
315
391
|
};
|
|
316
392
|
|
|
317
393
|
const matchJwk = (keys: any[], kid: string | undefined, alg: 'RS256' | 'ES256') => {
|
|
394
|
+
const expectedKty = alg === 'RS256' ? 'RSA' : 'EC';
|
|
318
395
|
const isUsable = (k: any) =>
|
|
319
396
|
k &&
|
|
320
397
|
k.use !== 'enc' &&
|
|
398
|
+
(!k.kty || k.kty === expectedKty) &&
|
|
321
399
|
(!k.alg || k.alg === alg);
|
|
322
400
|
return kid
|
|
323
401
|
? keys.find((k) => k.kid === kid && isUsable(k))
|
|
@@ -364,8 +442,12 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
364
442
|
const headerB64 = token.slice(0, firstDot);
|
|
365
443
|
const payloadB64 = token.slice(firstDot + 1, secondDot);
|
|
366
444
|
const sigB64 = token.slice(secondDot + 1);
|
|
445
|
+
if (!/^[A-Za-z0-9_-]+$/.test(sigB64)) {
|
|
446
|
+
return ctx.status(401).send("Invalid signature");
|
|
447
|
+
}
|
|
367
448
|
const data = token.slice(0, secondDot);
|
|
368
449
|
|
|
450
|
+
let decoded: any;
|
|
369
451
|
try {
|
|
370
452
|
const headerObj = JSON.parse(fromBase64Url(headerB64));
|
|
371
453
|
const alg = headerObj?.alg as JwtAlgorithm | undefined;
|
|
@@ -377,7 +459,7 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
377
459
|
if (!secret) return ctx.status(401).send("Unsupported token algorithm");
|
|
378
460
|
const expectedSig = createHmac('sha256', secret).update(data).digest();
|
|
379
461
|
const actualSig = Buffer.from(sigB64, 'base64url');
|
|
380
|
-
if (actualSig.length !== expectedSig.length || !timingSafeEqual(actualSig, expectedSig)) {
|
|
462
|
+
if (actualSig.length !== expectedSig.length || actualSig.toString('base64url') !== sigB64 || !timingSafeEqual(actualSig, expectedSig)) {
|
|
381
463
|
return ctx.status(401).send("Invalid signature");
|
|
382
464
|
}
|
|
383
465
|
} else {
|
|
@@ -391,6 +473,9 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
391
473
|
return ctx.status(401).send("Invalid signature");
|
|
392
474
|
}
|
|
393
475
|
const sigBuf = Buffer.from(sigB64, 'base64url');
|
|
476
|
+
if (sigBuf.toString('base64url') !== sigB64) {
|
|
477
|
+
return ctx.status(401).send("Invalid signature");
|
|
478
|
+
}
|
|
394
479
|
const sigBytes = sigBuf.buffer.slice(sigBuf.byteOffset, sigBuf.byteOffset + sigBuf.byteLength);
|
|
395
480
|
const valid = await crypto.subtle.verify(
|
|
396
481
|
getVerifyParams(alg),
|
|
@@ -403,11 +488,15 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
403
488
|
}
|
|
404
489
|
}
|
|
405
490
|
|
|
406
|
-
const
|
|
407
|
-
|
|
491
|
+
const payloadStr = fromBase64Url(payloadB64);
|
|
492
|
+
decoded = JSON.parse(payloadStr);
|
|
493
|
+
if (decoded && typeof decoded === 'object' && (payloadStr.indexOf('__proto__') !== -1 || payloadStr.indexOf('\\u') !== -1)) {
|
|
494
|
+
stripProtoKeys(decoded);
|
|
495
|
+
}
|
|
408
496
|
} catch {
|
|
409
497
|
return ctx.status(401).send("Token verification failed");
|
|
410
498
|
}
|
|
499
|
+
return checkClaimsAndRevocation(ctx, decoded, token, next);
|
|
411
500
|
};
|
|
412
501
|
};
|
|
413
502
|
|
|
@@ -443,7 +532,7 @@ export const basicAuth = (credentials: { user: string; pass: string }) => {
|
|
|
443
532
|
const passMatch = timingSafeEqual(sha256(pass), expectedPassHash);
|
|
444
533
|
|
|
445
534
|
if (userMatch && passMatch) {
|
|
446
|
-
return next();
|
|
535
|
+
return next?.();
|
|
447
536
|
}
|
|
448
537
|
|
|
449
538
|
return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
|
|
@@ -460,6 +549,6 @@ export const hasRole = (role: string) => {
|
|
|
460
549
|
if (!user || user.role !== role) {
|
|
461
550
|
return ctx.status(403).json({ status: 'error', message: `Required role: ${role}` });
|
|
462
551
|
}
|
|
463
|
-
return next();
|
|
552
|
+
return next?.();
|
|
464
553
|
};
|
|
465
554
|
};
|
package/src/security/cors.ts
CHANGED
|
@@ -8,8 +8,17 @@ export interface CorsOptions {
|
|
|
8
8
|
exposedHeaders?: string | string[];
|
|
9
9
|
}
|
|
10
10
|
|
|
11
|
+
const appendVaryOrigin = (headers: Headers) => {
|
|
12
|
+
const existing = headers.get('Vary');
|
|
13
|
+
if (!existing) {
|
|
14
|
+
headers.set('Vary', 'Origin');
|
|
15
|
+
} else if (!existing.toLowerCase().split(',').some((v) => v.trim() === 'origin')) {
|
|
16
|
+
headers.set('Vary', `${existing}, Origin`);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
11
20
|
export const cors = (options: CorsOptions = {}) => {
|
|
12
|
-
const originOpt = options.origin
|
|
21
|
+
const originOpt = options.origin ?? '*';
|
|
13
22
|
const methods = options.methods || 'GET,POST,PUT,PATCH,DELETE,OPTIONS';
|
|
14
23
|
const allowHeaders = Array.isArray(options.allowedHeaders)
|
|
15
24
|
? options.allowedHeaders.join(', ')
|
|
@@ -19,15 +28,46 @@ export const cors = (options: CorsOptions = {}) => {
|
|
|
19
28
|
: options.exposedHeaders;
|
|
20
29
|
const credentials = options.credentials === true;
|
|
21
30
|
|
|
31
|
+
const ensureCtxVaryOrigin = (ctx: any) => {
|
|
32
|
+
const existing = ctx._headers?.['vary'];
|
|
33
|
+
if (!existing) {
|
|
34
|
+
ctx.setHeader('Vary', 'Origin');
|
|
35
|
+
} else if (!existing.toLowerCase().split(',').map((s: string) => s.trim()).includes('origin')) {
|
|
36
|
+
ctx.setHeader('Vary', `${existing}, Origin`);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
|
|
22
40
|
// Fast-path for static string origin
|
|
23
41
|
if (typeof originOpt === 'string') {
|
|
42
|
+
if (originOpt === '') {
|
|
43
|
+
const mw: Middleware = (ctx, next) => {
|
|
44
|
+
if (ctx.req.method === 'OPTIONS') {
|
|
45
|
+
return new Response(null, { status: 204, headers: { 'Vary': 'Origin' } });
|
|
46
|
+
}
|
|
47
|
+
ctx.setHeader('Vary', 'Origin');
|
|
48
|
+
const res = next?.();
|
|
49
|
+
if (res && typeof (res as any).then === 'function') {
|
|
50
|
+
return (res as Promise<any>).then((r) => {
|
|
51
|
+
if (r instanceof Response) appendVaryOrigin(r.headers);
|
|
52
|
+
else ensureCtxVaryOrigin(ctx);
|
|
53
|
+
return r;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
if (res instanceof Response) appendVaryOrigin(res.headers);
|
|
57
|
+
else ensureCtxVaryOrigin(ctx);
|
|
58
|
+
return res;
|
|
59
|
+
};
|
|
60
|
+
(mw as any).__isCors = true;
|
|
61
|
+
return mw;
|
|
62
|
+
}
|
|
63
|
+
const allowCreds = credentials && originOpt !== '*';
|
|
24
64
|
const preflightHeaders: Record<string, string> = {
|
|
25
65
|
'Access-Control-Allow-Origin': originOpt,
|
|
26
66
|
'Access-Control-Allow-Methods': methods,
|
|
27
67
|
'Access-Control-Allow-Headers': allowHeaders
|
|
28
68
|
};
|
|
29
69
|
if (originOpt !== '*') preflightHeaders['Vary'] = 'Origin';
|
|
30
|
-
if (
|
|
70
|
+
if (allowCreds) preflightHeaders['Access-Control-Allow-Credentials'] = 'true';
|
|
31
71
|
const preflightInit = { status: 204, headers: preflightHeaders };
|
|
32
72
|
|
|
33
73
|
const mw: Middleware = (ctx, next) => {
|
|
@@ -37,7 +77,7 @@ export const cors = (options: CorsOptions = {}) => {
|
|
|
37
77
|
ctx.setHeader('Access-Control-Allow-Origin', originOpt);
|
|
38
78
|
ctx.setHeader('Access-Control-Allow-Methods', methods);
|
|
39
79
|
if (originOpt !== '*') ctx.setHeader('Vary', 'Origin');
|
|
40
|
-
if (
|
|
80
|
+
if (allowCreds) ctx.setHeader('Access-Control-Allow-Credentials', 'true');
|
|
41
81
|
if (exposeHeaders) ctx.setHeader('Access-Control-Expose-Headers', exposeHeaders);
|
|
42
82
|
|
|
43
83
|
const res = next?.();
|
|
@@ -46,9 +86,11 @@ export const cors = (options: CorsOptions = {}) => {
|
|
|
46
86
|
if (r instanceof Response) {
|
|
47
87
|
r.headers.set('Access-Control-Allow-Origin', originOpt);
|
|
48
88
|
r.headers.set('Access-Control-Allow-Methods', methods);
|
|
49
|
-
if (originOpt !== '*') r.headers
|
|
50
|
-
if (
|
|
89
|
+
if (originOpt !== '*') appendVaryOrigin(r.headers);
|
|
90
|
+
if (allowCreds) r.headers.set('Access-Control-Allow-Credentials', 'true');
|
|
51
91
|
if (exposeHeaders) r.headers.set('Access-Control-Expose-Headers', exposeHeaders);
|
|
92
|
+
} else if (originOpt !== '*') {
|
|
93
|
+
ensureCtxVaryOrigin(ctx);
|
|
52
94
|
}
|
|
53
95
|
return r;
|
|
54
96
|
});
|
|
@@ -56,12 +98,15 @@ export const cors = (options: CorsOptions = {}) => {
|
|
|
56
98
|
if (res instanceof Response) {
|
|
57
99
|
res.headers.set('Access-Control-Allow-Origin', originOpt);
|
|
58
100
|
res.headers.set('Access-Control-Allow-Methods', methods);
|
|
59
|
-
if (originOpt !== '*') res.headers
|
|
60
|
-
if (
|
|
101
|
+
if (originOpt !== '*') appendVaryOrigin(res.headers);
|
|
102
|
+
if (allowCreds) res.headers.set('Access-Control-Allow-Credentials', 'true');
|
|
61
103
|
if (exposeHeaders) res.headers.set('Access-Control-Expose-Headers', exposeHeaders);
|
|
104
|
+
} else if (originOpt !== '*') {
|
|
105
|
+
ensureCtxVaryOrigin(ctx);
|
|
62
106
|
}
|
|
63
107
|
return res;
|
|
64
108
|
};
|
|
109
|
+
(mw as any).__isCors = true;
|
|
65
110
|
return mw;
|
|
66
111
|
}
|
|
67
112
|
|
|
@@ -98,27 +143,32 @@ export const cors = (options: CorsOptions = {}) => {
|
|
|
98
143
|
if (res && typeof (res as any).then === 'function') {
|
|
99
144
|
return (res as Promise<any>).then((r) => {
|
|
100
145
|
if (r instanceof Response) {
|
|
101
|
-
r.headers
|
|
146
|
+
appendVaryOrigin(r.headers);
|
|
102
147
|
r.headers.set('Access-Control-Allow-Methods', methods);
|
|
103
148
|
if (matched) {
|
|
104
149
|
r.headers.set('Access-Control-Allow-Origin', matched);
|
|
105
150
|
if (credentials) r.headers.set('Access-Control-Allow-Credentials', 'true');
|
|
106
151
|
}
|
|
107
152
|
if (exposeHeaders) r.headers.set('Access-Control-Expose-Headers', exposeHeaders);
|
|
153
|
+
} else {
|
|
154
|
+
ensureCtxVaryOrigin(ctx);
|
|
108
155
|
}
|
|
109
156
|
return r;
|
|
110
157
|
});
|
|
111
158
|
}
|
|
112
159
|
if (res instanceof Response) {
|
|
113
|
-
res.headers
|
|
160
|
+
appendVaryOrigin(res.headers);
|
|
114
161
|
res.headers.set('Access-Control-Allow-Methods', methods);
|
|
115
162
|
if (matched) {
|
|
116
163
|
res.headers.set('Access-Control-Allow-Origin', matched);
|
|
117
164
|
if (credentials) res.headers.set('Access-Control-Allow-Credentials', 'true');
|
|
118
165
|
}
|
|
119
166
|
if (exposeHeaders) res.headers.set('Access-Control-Expose-Headers', exposeHeaders);
|
|
167
|
+
} else {
|
|
168
|
+
ensureCtxVaryOrigin(ctx);
|
|
120
169
|
}
|
|
121
170
|
return res;
|
|
122
171
|
};
|
|
172
|
+
(mw as any).__isCors = true;
|
|
123
173
|
return mw;
|
|
124
174
|
};
|
package/src/security/csrf.ts
CHANGED
|
@@ -10,20 +10,45 @@ export interface CsrfOptions {
|
|
|
10
10
|
cookieName?: string;
|
|
11
11
|
headerName?: string;
|
|
12
12
|
requireToken?: boolean;
|
|
13
|
+
/** Allow requests that omit both Origin and Referer headers (default: false) */
|
|
14
|
+
allowMissingOrigin?: boolean;
|
|
13
15
|
}
|
|
14
16
|
|
|
15
17
|
const DEFAULT_IGNORE = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
16
18
|
|
|
19
|
+
const resolveRequestOrigin = (ctx: Context): string => {
|
|
20
|
+
try {
|
|
21
|
+
const parsed = new URL(ctx.req.url);
|
|
22
|
+
const host = ctx.req.headers.get('host')?.trim();
|
|
23
|
+
if (ctx._trustProxy) {
|
|
24
|
+
const fwdHost = ctx.req.headers.get('x-forwarded-host')?.split(',')[0]?.trim();
|
|
25
|
+
const fwdProto = ctx.req.headers.get('x-forwarded-proto')?.split(',')[0]?.trim();
|
|
26
|
+
const effectiveHost = fwdHost || host;
|
|
27
|
+
if (effectiveHost) {
|
|
28
|
+
const proto = fwdProto ? `${fwdProto.replace(/:$/, '')}:` : parsed.protocol;
|
|
29
|
+
return new URL(`${proto}//${effectiveHost}`).origin;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (host) {
|
|
33
|
+
return new URL(`${parsed.protocol}//${host}`).origin;
|
|
34
|
+
}
|
|
35
|
+
return parsed.origin;
|
|
36
|
+
} catch {
|
|
37
|
+
return '';
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
|
|
17
41
|
export const csrf = (options: CsrfOptions = {}): Middleware => {
|
|
18
42
|
const ignore = options.ignoreMethods ? new Set(options.ignoreMethods.map((m) => m.toUpperCase())) : DEFAULT_IGNORE;
|
|
19
43
|
const allowed = options.allowedOrigins ? new Set(options.allowedOrigins) : null;
|
|
20
44
|
const cookieName = options.cookieName || 'csrf_token';
|
|
21
45
|
const headerName = (options.headerName || 'x-csrf-token').toLowerCase();
|
|
22
46
|
const requireToken = options.requireToken === true;
|
|
47
|
+
const allowMissingOrigin = options.allowMissingOrigin === true;
|
|
23
48
|
|
|
24
49
|
return (ctx: Context, next: Next) => {
|
|
25
50
|
const method = ctx.req.method.toUpperCase();
|
|
26
|
-
if (ignore.has(method)) return next();
|
|
51
|
+
if (ignore.has(method)) return next?.();
|
|
27
52
|
|
|
28
53
|
const secFetchSite = ctx.req.headers.get('sec-fetch-site');
|
|
29
54
|
const origin = ctx.req.headers.get('origin');
|
|
@@ -53,19 +78,19 @@ export const csrf = (options: CsrfOptions = {}): Middleware => {
|
|
|
53
78
|
}
|
|
54
79
|
|
|
55
80
|
if (sourceOrigin) {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
reqOrigin = new URL(ctx.req.url).origin;
|
|
59
|
-
} catch {
|
|
60
|
-
reqOrigin = '';
|
|
61
|
-
}
|
|
62
|
-
const isAllowed = sourceOrigin === reqOrigin || (allowed !== null && allowed.has(sourceOrigin));
|
|
81
|
+
const reqOrigin = resolveRequestOrigin(ctx);
|
|
82
|
+
const isAllowed = (reqOrigin !== '' && sourceOrigin === reqOrigin) || (allowed !== null && allowed.has(sourceOrigin));
|
|
63
83
|
if (!isAllowed) {
|
|
64
84
|
return Response.json(
|
|
65
85
|
{ status: 'error', code: 'CSRF_FORBIDDEN', message: 'Origin mismatch' },
|
|
66
86
|
{ status: 403 }
|
|
67
87
|
);
|
|
68
88
|
}
|
|
89
|
+
} else if (!allowMissingOrigin && secFetchSite !== 'same-origin') {
|
|
90
|
+
return Response.json(
|
|
91
|
+
{ status: 'error', code: 'CSRF_FORBIDDEN', message: 'Missing Origin or Referer header' },
|
|
92
|
+
{ status: 403 }
|
|
93
|
+
);
|
|
69
94
|
}
|
|
70
95
|
|
|
71
96
|
// 3. Optional double-submit token check
|
package/src/security/hash.ts
CHANGED
|
@@ -2,8 +2,13 @@
|
|
|
2
2
|
import { BARE_CONFIG } from '../core/config';
|
|
3
3
|
|
|
4
4
|
export const Hash = {
|
|
5
|
-
make: (data: string): Promise<string> =>
|
|
6
|
-
|
|
5
|
+
make: (data: string): Promise<string> => {
|
|
6
|
+
if (BARE_CONFIG.hash.algorithm === 'bcrypt') {
|
|
7
|
+
const cost = Math.max(4, Math.min(31, BARE_CONFIG.hash.timeCost));
|
|
8
|
+
return Bun.password.hash(data, { algorithm: 'bcrypt', cost });
|
|
9
|
+
}
|
|
10
|
+
return Bun.password.hash(data, BARE_CONFIG.hash);
|
|
11
|
+
},
|
|
7
12
|
|
|
8
13
|
verify: async (data: string, hash: string): Promise<boolean> => {
|
|
9
14
|
if (!hash || typeof hash !== 'string') return false;
|
|
@@ -15,11 +20,13 @@ export const Hash = {
|
|
|
15
20
|
},
|
|
16
21
|
|
|
17
22
|
needsRehash: (hash: string): boolean => {
|
|
23
|
+
if (!hash || typeof hash !== 'string') return true;
|
|
18
24
|
const { algorithm, memoryCost, timeCost } = BARE_CONFIG.hash;
|
|
19
25
|
if (algorithm === 'bcrypt') {
|
|
20
26
|
if (!/^\$2[aby]\$/.test(hash)) return true;
|
|
21
27
|
const costMatch = hash.match(/^\$2[aby]\$(\d+)\$/);
|
|
22
|
-
|
|
28
|
+
const expectedCost = Math.max(4, Math.min(31, timeCost));
|
|
29
|
+
return !costMatch || Number(costMatch[1]) !== expectedCost;
|
|
23
30
|
}
|
|
24
31
|
if (!hash.startsWith(`$${algorithm}$`)) return true;
|
|
25
32
|
const mMatch = hash.match(/(?:^|[,$])m=(\d+)(?:[,$]|$)/);
|