barejs 0.1.49 → 0.1.51
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 +257 -98
- package/dist/index.js +157 -94
- package/dist/types/client/index.d.ts +24 -22
- package/dist/types/core/bare.d.ts +83 -3
- package/dist/types/core/context.d.ts +47 -1
- package/dist/types/core/radix.d.ts +1 -0
- package/dist/types/core/router.d.ts +21 -10
- package/dist/types/index.d.ts +16 -8
- package/dist/types/security/auth.d.ts +10 -1
- package/dist/types/security/cors.d.ts +7 -3
- package/dist/types/security/csrf.d.ts +12 -0
- package/dist/types/security/idempotency.d.ts +22 -0
- package/dist/types/security/resilience.d.ts +17 -0
- package/dist/types/security/timeout.d.ts +6 -0
- package/dist/types/security/validators.d.ts +18 -0
- package/dist/types/utils/compress.d.ts +12 -0
- package/dist/types/utils/health.d.ts +17 -0
- package/dist/types/utils/logger.d.ts +22 -0
- package/dist/types/utils/openapi.d.ts +23 -1
- package/dist/types/utils/static.d.ts +5 -1
- package/llms.txt +138 -0
- package/package.json +3 -1
- package/src/client/index.ts +61 -18
- package/src/core/bare.ts +409 -49
- package/src/core/context.ts +266 -32
- package/src/core/radix.ts +37 -3
- package/src/core/router.ts +43 -16
- package/src/index.ts +25 -9
- package/src/security/auth.ts +68 -11
- package/src/security/cors.ts +85 -31
- package/src/security/csrf.ts +84 -0
- package/src/security/hash.ts +8 -2
- package/src/security/headers.ts +12 -3
- package/src/security/idempotency.ts +118 -0
- package/src/security/rateLimit.ts +1 -6
- package/src/security/resilience.ts +91 -0
- package/src/security/timeout.ts +32 -0
- package/src/security/validators.ts +201 -5
- package/src/utils/compress.ts +49 -0
- package/src/utils/health.ts +65 -0
- package/src/utils/logger.ts +66 -0
- package/src/utils/openapi.ts +59 -14
- package/src/utils/static.ts +71 -5
package/src/security/auth.ts
CHANGED
|
@@ -54,12 +54,62 @@ export const createToken = async (payload: object, secret: string): Promise<stri
|
|
|
54
54
|
return `${data}.${encodedSig}`;
|
|
55
55
|
};
|
|
56
56
|
|
|
57
|
+
const revokedTokens = new Map<string, number>();
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Revoke a JWT token or JTI for ttlMs (default: 1 hour).
|
|
61
|
+
*/
|
|
62
|
+
export const revokeToken = (tokenOrJti: string, ttlMs: number = 3600_000): void => {
|
|
63
|
+
if (revokedTokens.size >= 10_000) {
|
|
64
|
+
const now = Date.now();
|
|
65
|
+
for (const [k, exp] of revokedTokens) {
|
|
66
|
+
if (now >= exp) revokedTokens.delete(k);
|
|
67
|
+
}
|
|
68
|
+
if (revokedTokens.size >= 10_000) {
|
|
69
|
+
const oldest = revokedTokens.keys().next().value;
|
|
70
|
+
if (oldest !== undefined) revokedTokens.delete(oldest);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
revokedTokens.set(tokenOrJti, Date.now() + ttlMs);
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
export const isTokenRevoked = (tokenOrJti: string): boolean => {
|
|
77
|
+
const exp = revokedTokens.get(tokenOrJti);
|
|
78
|
+
if (exp === undefined) return false;
|
|
79
|
+
if (Date.now() >= exp) {
|
|
80
|
+
revokedTokens.delete(tokenOrJti);
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
return true;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
export interface BareAuthOptions {
|
|
87
|
+
secret: string;
|
|
88
|
+
isRevoked?: (payload: any, token: string) => boolean | Promise<boolean>;
|
|
89
|
+
}
|
|
90
|
+
|
|
57
91
|
/**
|
|
58
92
|
* 1. BARE TOKEN AUTH (Standard JWT Middleware)
|
|
59
93
|
* High-performance, constant-time JWT middleware for BareJS
|
|
60
94
|
*/
|
|
61
|
-
export const bareAuth = (
|
|
62
|
-
|
|
95
|
+
export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
96
|
+
const secret = typeof secretOrOpts === 'string' ? secretOrOpts : secretOrOpts.secret;
|
|
97
|
+
const customRevoked = typeof secretOrOpts === 'object' ? secretOrOpts.isRevoked : undefined;
|
|
98
|
+
|
|
99
|
+
const finishAuth = (ctx: any, decoded: any, next: any) => {
|
|
100
|
+
ctx.set('user', decoded);
|
|
101
|
+
if (Array.isArray(next)) {
|
|
102
|
+
if (next.length === 0) return;
|
|
103
|
+
const [current, ...rest] = next;
|
|
104
|
+
return current(ctx, rest);
|
|
105
|
+
}
|
|
106
|
+
if (typeof next === 'function') {
|
|
107
|
+
return next();
|
|
108
|
+
}
|
|
109
|
+
return;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const verifySync = (ctx: any, next: any) => {
|
|
63
113
|
const authHeader = ctx.req.headers.get('Authorization');
|
|
64
114
|
|
|
65
115
|
if (!authHeader?.startsWith('Bearer ')) {
|
|
@@ -100,23 +150,30 @@ export const bareAuth = (secret: string) => {
|
|
|
100
150
|
return ctx.status(401).send("Token not active");
|
|
101
151
|
}
|
|
102
152
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
if (Array.isArray(next)) {
|
|
106
|
-
if (next.length === 0) return;
|
|
107
|
-
const [current, ...rest] = next;
|
|
108
|
-
return current(ctx, rest);
|
|
153
|
+
if (isTokenRevoked(token) || (decoded?.jti && isTokenRevoked(String(decoded.jti)))) {
|
|
154
|
+
return ctx.status(401).send("Token revoked");
|
|
109
155
|
}
|
|
110
156
|
|
|
111
|
-
if (
|
|
112
|
-
|
|
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
|
+
);
|
|
163
|
+
}
|
|
164
|
+
if (rev) return ctx.status(401).send("Token revoked");
|
|
113
165
|
}
|
|
114
166
|
|
|
115
|
-
return;
|
|
167
|
+
return finishAuth(ctx, decoded, next);
|
|
116
168
|
} catch {
|
|
117
169
|
return ctx.status(401).send("Token verification failed");
|
|
118
170
|
}
|
|
119
171
|
};
|
|
172
|
+
|
|
173
|
+
if (customRevoked) {
|
|
174
|
+
return async (ctx: any, next: any) => verifySync(ctx, next);
|
|
175
|
+
}
|
|
176
|
+
return verifySync;
|
|
120
177
|
};
|
|
121
178
|
|
|
122
179
|
const sha256 = (value: string): Buffer => createHash('sha256').update(value).digest();
|
package/src/security/cors.ts
CHANGED
|
@@ -1,46 +1,100 @@
|
|
|
1
1
|
import type { Middleware } from '../core/context';
|
|
2
2
|
|
|
3
|
-
export
|
|
4
|
-
|
|
3
|
+
export interface CorsOptions {
|
|
4
|
+
origin?: string | string[] | ((origin: string) => boolean);
|
|
5
|
+
methods?: string;
|
|
6
|
+
credentials?: boolean;
|
|
7
|
+
allowedHeaders?: string | string[];
|
|
8
|
+
exposedHeaders?: string | string[];
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const cors = (options: CorsOptions = {}) => {
|
|
12
|
+
const originOpt = options.origin || '*';
|
|
5
13
|
const methods = options.methods || 'GET,POST,PUT,PATCH,DELETE,OPTIONS';
|
|
6
|
-
const
|
|
7
|
-
'
|
|
8
|
-
'
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
14
|
+
const allowHeaders = Array.isArray(options.allowedHeaders)
|
|
15
|
+
? options.allowedHeaders.join(', ')
|
|
16
|
+
: (options.allowedHeaders || 'Content-Type, Authorization');
|
|
17
|
+
const exposeHeaders = Array.isArray(options.exposedHeaders)
|
|
18
|
+
? options.exposedHeaders.join(', ')
|
|
19
|
+
: options.exposedHeaders;
|
|
20
|
+
const credentials = options.credentials === true;
|
|
21
|
+
|
|
22
|
+
// Fast-path for static string origin
|
|
23
|
+
if (typeof originOpt === 'string') {
|
|
24
|
+
const preflightHeaders: Record<string, string> = {
|
|
25
|
+
'Access-Control-Allow-Origin': originOpt,
|
|
26
|
+
'Access-Control-Allow-Methods': methods,
|
|
27
|
+
'Access-Control-Allow-Headers': allowHeaders
|
|
28
|
+
};
|
|
29
|
+
if (originOpt !== '*') preflightHeaders['Vary'] = 'Origin';
|
|
30
|
+
if (credentials) preflightHeaders['Access-Control-Allow-Credentials'] = 'true';
|
|
31
|
+
const preflightInit = { status: 204, headers: preflightHeaders };
|
|
32
|
+
|
|
33
|
+
const mw: Middleware = (ctx, next) => {
|
|
34
|
+
if (ctx.req.method === 'OPTIONS') {
|
|
35
|
+
return new Response(null, preflightInit);
|
|
36
|
+
}
|
|
37
|
+
ctx.setHeader('Access-Control-Allow-Origin', originOpt);
|
|
38
|
+
ctx.setHeader('Access-Control-Allow-Methods', methods);
|
|
39
|
+
if (originOpt !== '*') ctx.setHeader('Vary', 'Origin');
|
|
40
|
+
if (credentials) ctx.setHeader('Access-Control-Allow-Credentials', 'true');
|
|
41
|
+
if (exposeHeaders) ctx.setHeader('Access-Control-Expose-Headers', exposeHeaders);
|
|
42
|
+
|
|
43
|
+
const res = next?.();
|
|
44
|
+
if (res && typeof (res as any).then === 'function') {
|
|
45
|
+
return (res as Promise<any>).then((r) => {
|
|
46
|
+
if (r instanceof Response) {
|
|
47
|
+
r.headers.set('Access-Control-Allow-Origin', originOpt);
|
|
48
|
+
r.headers.set('Access-Control-Allow-Methods', methods);
|
|
49
|
+
if (originOpt !== '*') r.headers.set('Vary', 'Origin');
|
|
50
|
+
if (credentials) r.headers.set('Access-Control-Allow-Credentials', 'true');
|
|
51
|
+
if (exposeHeaders) r.headers.set('Access-Control-Expose-Headers', exposeHeaders);
|
|
52
|
+
}
|
|
53
|
+
return r;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
if (res instanceof Response) {
|
|
57
|
+
res.headers.set('Access-Control-Allow-Origin', originOpt);
|
|
58
|
+
res.headers.set('Access-Control-Allow-Methods', methods);
|
|
59
|
+
if (originOpt !== '*') res.headers.set('Vary', 'Origin');
|
|
60
|
+
if (credentials) res.headers.set('Access-Control-Allow-Credentials', 'true');
|
|
61
|
+
if (exposeHeaders) res.headers.set('Access-Control-Expose-Headers', exposeHeaders);
|
|
62
|
+
}
|
|
63
|
+
return res;
|
|
64
|
+
};
|
|
65
|
+
return mw;
|
|
13
66
|
}
|
|
14
|
-
|
|
67
|
+
|
|
68
|
+
// Dynamic origin (array or function)
|
|
69
|
+
const allowedSet = Array.isArray(originOpt) ? new Set(originOpt) : null;
|
|
70
|
+
const resolveOrigin = (reqOrigin: string | null): string | null => {
|
|
71
|
+
if (!reqOrigin) return null;
|
|
72
|
+
if (allowedSet) return allowedSet.has(reqOrigin) ? reqOrigin : null;
|
|
73
|
+
return (originOpt as (o: string) => boolean)(reqOrigin) ? reqOrigin : null;
|
|
74
|
+
};
|
|
15
75
|
|
|
16
76
|
const mw: Middleware = (ctx, next) => {
|
|
77
|
+
const matched = resolveOrigin(ctx.req.headers.get('origin'));
|
|
17
78
|
if (ctx.req.method === 'OPTIONS') {
|
|
18
|
-
|
|
79
|
+
const h: Record<string, string> = {
|
|
80
|
+
'Access-Control-Allow-Methods': methods,
|
|
81
|
+
'Access-Control-Allow-Headers': allowHeaders,
|
|
82
|
+
'Vary': 'Origin'
|
|
83
|
+
};
|
|
84
|
+
if (matched) h['Access-Control-Allow-Origin'] = matched;
|
|
85
|
+
if (credentials && matched) h['Access-Control-Allow-Credentials'] = 'true';
|
|
86
|
+
return new Response(null, { status: 204, headers: h });
|
|
19
87
|
}
|
|
20
88
|
|
|
21
|
-
ctx.setHeader('
|
|
89
|
+
ctx.setHeader('Vary', 'Origin');
|
|
22
90
|
ctx.setHeader('Access-Control-Allow-Methods', methods);
|
|
23
|
-
if (
|
|
24
|
-
ctx.setHeader('
|
|
91
|
+
if (matched) {
|
|
92
|
+
ctx.setHeader('Access-Control-Allow-Origin', matched);
|
|
93
|
+
if (credentials) ctx.setHeader('Access-Control-Allow-Credentials', 'true');
|
|
25
94
|
}
|
|
95
|
+
if (exposeHeaders) ctx.setHeader('Access-Control-Expose-Headers', exposeHeaders);
|
|
26
96
|
|
|
27
|
-
|
|
28
|
-
if (res && typeof (res as any).then === 'function') {
|
|
29
|
-
return (res as Promise<any>).then((r) => {
|
|
30
|
-
if (r instanceof Response) {
|
|
31
|
-
r.headers.set('Access-Control-Allow-Origin', origin);
|
|
32
|
-
r.headers.set('Access-Control-Allow-Methods', methods);
|
|
33
|
-
if (origin !== '*') r.headers.set('Vary', 'Origin');
|
|
34
|
-
}
|
|
35
|
-
return r;
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
if (res instanceof Response) {
|
|
39
|
-
res.headers.set('Access-Control-Allow-Origin', origin);
|
|
40
|
-
res.headers.set('Access-Control-Allow-Methods', methods);
|
|
41
|
-
if (origin !== '*') res.headers.set('Vary', 'Origin');
|
|
42
|
-
}
|
|
43
|
-
return res;
|
|
97
|
+
return next?.();
|
|
44
98
|
};
|
|
45
99
|
return mw;
|
|
46
100
|
};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { Context, Middleware, Next } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export interface CsrfOptions {
|
|
4
|
+
/** Allowed origins for state-changing requests (defaults to same-origin matching request Host) */
|
|
5
|
+
allowedOrigins?: string[];
|
|
6
|
+
/** HTTP methods exempt from CSRF checks (default: ['GET', 'HEAD', 'OPTIONS']) */
|
|
7
|
+
ignoreMethods?: string[];
|
|
8
|
+
/** Optional cookie + header double-submit check */
|
|
9
|
+
cookieName?: string;
|
|
10
|
+
headerName?: string;
|
|
11
|
+
requireToken?: boolean;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const DEFAULT_IGNORE = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
15
|
+
|
|
16
|
+
export const csrf = (options: CsrfOptions = {}): Middleware => {
|
|
17
|
+
const ignore = options.ignoreMethods ? new Set(options.ignoreMethods.map((m) => m.toUpperCase())) : DEFAULT_IGNORE;
|
|
18
|
+
const allowed = options.allowedOrigins ? new Set(options.allowedOrigins) : null;
|
|
19
|
+
const cookieName = options.cookieName || 'csrf_token';
|
|
20
|
+
const headerName = (options.headerName || 'x-csrf-token').toLowerCase();
|
|
21
|
+
const requireToken = options.requireToken === true;
|
|
22
|
+
|
|
23
|
+
return (ctx: Context, next: Next) => {
|
|
24
|
+
const method = ctx.req.method.toUpperCase();
|
|
25
|
+
if (ignore.has(method)) return next();
|
|
26
|
+
|
|
27
|
+
const secFetchSite = ctx.req.headers.get('sec-fetch-site');
|
|
28
|
+
const origin = ctx.req.headers.get('origin');
|
|
29
|
+
const referer = ctx.req.headers.get('referer');
|
|
30
|
+
|
|
31
|
+
// 1. Sec-Fetch-Site check (modern browsers)
|
|
32
|
+
if (secFetchSite === 'cross-site') {
|
|
33
|
+
if (!allowed || !origin || !allowed.has(origin)) {
|
|
34
|
+
return Response.json(
|
|
35
|
+
{ status: 'error', code: 'CSRF_FORBIDDEN', message: 'Cross-site request blocked' },
|
|
36
|
+
{ status: 403 }
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// 2. Origin / Referer check
|
|
42
|
+
let sourceOrigin = origin;
|
|
43
|
+
if (!sourceOrigin && referer) {
|
|
44
|
+
try {
|
|
45
|
+
sourceOrigin = new URL(referer).origin;
|
|
46
|
+
} catch {
|
|
47
|
+
return Response.json(
|
|
48
|
+
{ status: 'error', code: 'CSRF_FORBIDDEN', message: 'Invalid Referer header' },
|
|
49
|
+
{ status: 403 }
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
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));
|
|
62
|
+
if (!isAllowed) {
|
|
63
|
+
return Response.json(
|
|
64
|
+
{ status: 'error', code: 'CSRF_FORBIDDEN', message: 'Origin mismatch' },
|
|
65
|
+
{ status: 403 }
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// 3. Optional double-submit token check
|
|
71
|
+
if (requireToken) {
|
|
72
|
+
const cookieToken = ctx.cookies[cookieName];
|
|
73
|
+
const headerToken = ctx.req.headers.get(headerName);
|
|
74
|
+
if (!cookieToken || !headerToken || cookieToken !== headerToken) {
|
|
75
|
+
return Response.json(
|
|
76
|
+
{ status: 'error', code: 'CSRF_TOKEN_INVALID', message: 'Invalid or missing CSRF token' },
|
|
77
|
+
{ status: 403 }
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return next();
|
|
83
|
+
};
|
|
84
|
+
};
|
package/src/security/hash.ts
CHANGED
|
@@ -5,8 +5,14 @@ export const Hash = {
|
|
|
5
5
|
make: (data: string): Promise<string> =>
|
|
6
6
|
Bun.password.hash(data, BARE_CONFIG.hash),
|
|
7
7
|
|
|
8
|
-
verify: (data: string, hash: string): Promise<boolean> =>
|
|
9
|
-
|
|
8
|
+
verify: async (data: string, hash: string): Promise<boolean> => {
|
|
9
|
+
if (!hash || typeof hash !== 'string') return false;
|
|
10
|
+
try {
|
|
11
|
+
return await Bun.password.verify(data, hash);
|
|
12
|
+
} catch {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
},
|
|
10
16
|
|
|
11
17
|
needsRehash: (hash: string): boolean => {
|
|
12
18
|
const { algorithm, memoryCost, timeCost } = BARE_CONFIG.hash;
|
package/src/security/headers.ts
CHANGED
|
@@ -29,11 +29,20 @@ export const securityHeaders = (options: SecurityHeadersOptions = {}): Middlewar
|
|
|
29
29
|
headersToSet.push(['X-XSS-Protection', '0']);
|
|
30
30
|
|
|
31
31
|
const len = headersToSet.length;
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
const headersObj: Record<string, string> = Object.freeze((() => {
|
|
33
|
+
const o: Record<string, string> = {};
|
|
34
34
|
for (let i = 0; i < len; i++) {
|
|
35
35
|
const pair = headersToSet[i]!;
|
|
36
|
-
|
|
36
|
+
o[pair[0].toLowerCase()] = pair[1];
|
|
37
|
+
}
|
|
38
|
+
return o;
|
|
39
|
+
})());
|
|
40
|
+
|
|
41
|
+
return (ctx, next) => {
|
|
42
|
+
if (!ctx._headers) {
|
|
43
|
+
ctx._headers = headersObj;
|
|
44
|
+
} else {
|
|
45
|
+
ctx._headers = { ...ctx._headers, ...headersObj };
|
|
37
46
|
}
|
|
38
47
|
|
|
39
48
|
const res = next?.();
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import type { Context, Middleware } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export interface IdempotencyOptions {
|
|
4
|
+
/** Header name (default: 'idempotency-key') */
|
|
5
|
+
headerName?: string;
|
|
6
|
+
/** Cache TTL in milliseconds (default: 300_000 = 5 minutes) */
|
|
7
|
+
ttlMs?: number;
|
|
8
|
+
/** Maximum cached keys before LRU eviction (default: 10_000) */
|
|
9
|
+
maxKeys?: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface CachedIdempotentEntry {
|
|
13
|
+
status: number;
|
|
14
|
+
body: any;
|
|
15
|
+
expiresAt: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Payment & Order Double-Charge Protection Middleware (Idempotency-Key).
|
|
20
|
+
* Prevents duplicate state-changing executions and concurrent race conditions.
|
|
21
|
+
*/
|
|
22
|
+
export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
|
|
23
|
+
const headerName = (options.headerName || 'idempotency-key').toLowerCase();
|
|
24
|
+
const ttlMs = options.ttlMs ?? 300_000;
|
|
25
|
+
const maxKeys = options.maxKeys ?? 10_000;
|
|
26
|
+
|
|
27
|
+
const cache = new Map<string, CachedIdempotentEntry>();
|
|
28
|
+
const inFlight = new Set<string>();
|
|
29
|
+
|
|
30
|
+
const mw: Middleware = (ctx: Context) => {
|
|
31
|
+
const rawKey = ctx.req.headers.get(headerName);
|
|
32
|
+
if (!rawKey) {
|
|
33
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
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
|
+
const now = Date.now();
|
|
44
|
+
const existing = cache.get(key);
|
|
45
|
+
if (existing) {
|
|
46
|
+
if (now < existing.expiresAt) {
|
|
47
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
48
|
+
return Response.json(existing.body, {
|
|
49
|
+
status: existing.status,
|
|
50
|
+
headers: { 'X-Idempotent-Replayed': 'true' }
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
cache.delete(key);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (inFlight.has(key)) {
|
|
57
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
58
|
+
return Response.json(
|
|
59
|
+
{ status: 'error', code: 'IDEMPOTENT_IN_FLIGHT', message: 'Duplicate request is currently in flight' },
|
|
60
|
+
{ status: 409 }
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
inFlight.add(key);
|
|
65
|
+
(ctx as any)._idempotencyKey = key;
|
|
66
|
+
return undefined;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
(mw as any).__idempotencyCommit = (ctx: Context, resVal: any, status: number) => {
|
|
70
|
+
const key = (ctx as any)._idempotencyKey;
|
|
71
|
+
if (!key) return;
|
|
72
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
73
|
+
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);
|
|
78
|
+
}
|
|
79
|
+
cache.set(key, {
|
|
80
|
+
status,
|
|
81
|
+
body: resVal,
|
|
82
|
+
expiresAt: Date.now() + ttlMs
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
(mw as any).__idempotencyRelease = (ctx: Context) => {
|
|
88
|
+
const key = (ctx as any)._idempotencyKey;
|
|
89
|
+
if (key) {
|
|
90
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
91
|
+
inFlight.delete(key);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
return mw;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Singleflight Helper for Thundering-Herd / Cache-Stampede Protection.
|
|
100
|
+
* Coalesces N concurrent identical async calls into 1 underlying execution.
|
|
101
|
+
*/
|
|
102
|
+
export const createSingleflight = () => {
|
|
103
|
+
const inFlight = new Map<string, Promise<any>>();
|
|
104
|
+
|
|
105
|
+
return async <T>(key: string, fn: () => Promise<T>): Promise<{ data: T; shared: boolean }> => {
|
|
106
|
+
const existing = inFlight.get(key);
|
|
107
|
+
if (existing) {
|
|
108
|
+
const data = await existing;
|
|
109
|
+
return { data, shared: true };
|
|
110
|
+
}
|
|
111
|
+
const promise = fn().finally(() => {
|
|
112
|
+
inFlight.delete(key);
|
|
113
|
+
});
|
|
114
|
+
inFlight.set(key, promise);
|
|
115
|
+
const data = await promise;
|
|
116
|
+
return { data, shared: false };
|
|
117
|
+
};
|
|
118
|
+
};
|
|
@@ -18,12 +18,7 @@ export const rateLimit = (options: RateLimitOptions = {}): Middleware => {
|
|
|
18
18
|
const max = options.max ?? 100;
|
|
19
19
|
const message = options.message ?? 'Too many requests, please try again later.';
|
|
20
20
|
const maxEntries = options.maxEntries ?? 10_000;
|
|
21
|
-
const keyGenerator =
|
|
22
|
-
options.keyGenerator ??
|
|
23
|
-
((ctx: Context) =>
|
|
24
|
-
ctx.req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||
|
|
25
|
-
ctx.req.headers.get('x-real-ip') ||
|
|
26
|
-
'global');
|
|
21
|
+
const keyGenerator = options.keyGenerator ?? ((ctx: Context) => ctx.ip);
|
|
27
22
|
|
|
28
23
|
const buckets = new Map<string, RateBucket>();
|
|
29
24
|
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { Context, Middleware, Next } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
|
|
4
|
+
|
|
5
|
+
export interface CircuitBreakerOptions {
|
|
6
|
+
/** Number of consecutive failures before opening the circuit (default: 5) */
|
|
7
|
+
failureThreshold?: number;
|
|
8
|
+
/** Cooldown in milliseconds before transitioning from OPEN to HALF_OPEN (default: 30000) */
|
|
9
|
+
resetTimeoutMs?: number;
|
|
10
|
+
/** Custom predicate to determine if a response or error counts as a failure */
|
|
11
|
+
isFailure?: (res: any, err?: any) => boolean;
|
|
12
|
+
/** Optional callback fired when circuit state changes */
|
|
13
|
+
onStateChange?: (from: CircuitState, to: CircuitState) => void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Lightweight Circuit Breaker middleware.
|
|
18
|
+
* Protects downstream databases and external APIs from cascading failures.
|
|
19
|
+
*/
|
|
20
|
+
export const circuitBreaker = (options: CircuitBreakerOptions = {}): Middleware => {
|
|
21
|
+
const failureThreshold = options.failureThreshold ?? 5;
|
|
22
|
+
const resetTimeoutMs = options.resetTimeoutMs ?? 30_000;
|
|
23
|
+
const isFailure = options.isFailure ?? ((res: any, err?: any) => Boolean(err) || (res instanceof Response && res.status >= 500));
|
|
24
|
+
|
|
25
|
+
let state: CircuitState = 'CLOSED';
|
|
26
|
+
let failures = 0;
|
|
27
|
+
let openedAt = 0;
|
|
28
|
+
let halfOpenInFlight = false;
|
|
29
|
+
|
|
30
|
+
const setState = (nextState: CircuitState) => {
|
|
31
|
+
if (state !== nextState) {
|
|
32
|
+
const prev = state;
|
|
33
|
+
state = nextState;
|
|
34
|
+
options.onStateChange?.(prev, nextState);
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const runWithBreaker = async (exec: () => any) => {
|
|
39
|
+
if (state === 'OPEN') {
|
|
40
|
+
const elapsed = Date.now() - openedAt;
|
|
41
|
+
if (elapsed < resetTimeoutMs) {
|
|
42
|
+
const retryAfterSec = Math.max(1, Math.ceil((resetTimeoutMs - elapsed) / 1000));
|
|
43
|
+
return Response.json(
|
|
44
|
+
{ status: 'error', code: 'CIRCUIT_OPEN', message: 'Service temporarily unavailable' },
|
|
45
|
+
{ status: 503, headers: { 'Retry-After': String(retryAfterSec) } }
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
setState('HALF_OPEN');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
let isHalfOpenProbe = false;
|
|
52
|
+
if (state === 'HALF_OPEN') {
|
|
53
|
+
if (halfOpenInFlight) {
|
|
54
|
+
return Response.json(
|
|
55
|
+
{ status: 'error', code: 'CIRCUIT_OPEN', message: 'Service temporarily unavailable' },
|
|
56
|
+
{ status: 503, headers: { 'Retry-After': '1' } }
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
halfOpenInFlight = true;
|
|
60
|
+
isHalfOpenProbe = true;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
const res = await exec();
|
|
65
|
+
if (isFailure(res)) {
|
|
66
|
+
failures++;
|
|
67
|
+
if (isHalfOpenProbe || failures >= failureThreshold) {
|
|
68
|
+
openedAt = Date.now();
|
|
69
|
+
setState('OPEN');
|
|
70
|
+
}
|
|
71
|
+
} else {
|
|
72
|
+
failures = 0;
|
|
73
|
+
if (isHalfOpenProbe) setState('CLOSED');
|
|
74
|
+
}
|
|
75
|
+
return res;
|
|
76
|
+
} catch (err) {
|
|
77
|
+
failures++;
|
|
78
|
+
if (isHalfOpenProbe || failures >= failureThreshold) {
|
|
79
|
+
openedAt = Date.now();
|
|
80
|
+
setState('OPEN');
|
|
81
|
+
}
|
|
82
|
+
throw err;
|
|
83
|
+
} finally {
|
|
84
|
+
if (isHalfOpenProbe) halfOpenInFlight = false;
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const mw: Middleware = (_ctx: Context, next?: Next) => runWithBreaker(() => (next ? next() : undefined));
|
|
89
|
+
(mw as any).__circuitBreaker = runWithBreaker;
|
|
90
|
+
return mw;
|
|
91
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Context, Middleware, Next } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export interface TimeoutOptions {
|
|
4
|
+
status?: number;
|
|
5
|
+
message?: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export const timeout = (ms = 10000, options: TimeoutOptions = {}): Middleware => {
|
|
9
|
+
const status = options.status ?? 408;
|
|
10
|
+
const message = options.message ?? 'Request Timeout';
|
|
11
|
+
|
|
12
|
+
const mw: Middleware = async (_ctx: Context, next: Next) => {
|
|
13
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
14
|
+
try {
|
|
15
|
+
const timeoutPromise = new Promise<Response>((resolve) => {
|
|
16
|
+
timer = setTimeout(() => {
|
|
17
|
+
resolve(
|
|
18
|
+
Response.json(
|
|
19
|
+
{ status: 'error', code: 'REQUEST_TIMEOUT', message },
|
|
20
|
+
{ status }
|
|
21
|
+
)
|
|
22
|
+
);
|
|
23
|
+
}, ms);
|
|
24
|
+
});
|
|
25
|
+
return await Promise.race([Promise.resolve(next()), timeoutPromise]);
|
|
26
|
+
} finally {
|
|
27
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
(mw as any).__timeout = { ms, status, message };
|
|
31
|
+
return mw;
|
|
32
|
+
};
|