barejs 0.1.48 → 0.1.50
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 +243 -84
- package/dist/index.js +162 -67
- package/dist/types/client/index.d.ts +50 -0
- package/dist/types/core/bare.d.ts +24 -1
- package/dist/types/core/context.d.ts +54 -2
- package/dist/types/core/radix.d.ts +1 -0
- package/dist/types/core/router.d.ts +3 -1
- package/dist/types/index.d.ts +14 -6
- package/dist/types/security/auth.d.ts +3 -1
- package/dist/types/security/cors.d.ts +7 -3
- package/dist/types/security/csrf.d.ts +12 -0
- package/dist/types/security/headers.d.ts +9 -0
- package/dist/types/security/idempotency.d.ts +22 -0
- package/dist/types/security/rateLimit.d.ts +9 -0
- package/dist/types/security/timeout.d.ts +6 -0
- package/dist/types/security/validators.d.ts +16 -0
- package/dist/types/utils/openapi.d.ts +15 -0
- package/dist/types/utils/static.d.ts +5 -1
- package/llms.txt +138 -0
- package/package.json +3 -1
- package/src/client/index.ts +123 -0
- package/src/core/bare.ts +352 -40
- package/src/core/context.ts +356 -33
- package/src/core/radix.ts +37 -3
- package/src/core/router.ts +17 -5
- package/src/index.ts +32 -8
- package/src/security/auth.ts +2 -1
- package/src/security/cors.ts +85 -31
- package/src/security/csrf.ts +84 -0
- package/src/security/headers.ts +68 -0
- package/src/security/idempotency.ts +99 -0
- package/src/security/rateLimit.ts +76 -0
- package/src/security/timeout.ts +32 -0
- package/src/security/validators.ts +206 -9
- package/src/utils/openapi.ts +151 -0
- package/src/utils/static.ts +62 -5
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
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { Middleware } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export interface SecurityHeadersOptions {
|
|
4
|
+
contentSecurityPolicy?: string | false;
|
|
5
|
+
frameOptions?: 'DENY' | 'SAMEORIGIN' | false;
|
|
6
|
+
hsts?: string | false;
|
|
7
|
+
referrerPolicy?: string | false;
|
|
8
|
+
noSniff?: boolean;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const securityHeaders = (options: SecurityHeadersOptions = {}): Middleware => {
|
|
12
|
+
const headersToSet: [string, string][] = [];
|
|
13
|
+
|
|
14
|
+
if (options.noSniff !== false) {
|
|
15
|
+
headersToSet.push(['X-Content-Type-Options', 'nosniff']);
|
|
16
|
+
}
|
|
17
|
+
if (options.frameOptions !== false) {
|
|
18
|
+
headersToSet.push(['X-Frame-Options', options.frameOptions ?? 'DENY']);
|
|
19
|
+
}
|
|
20
|
+
if (options.referrerPolicy !== false) {
|
|
21
|
+
headersToSet.push(['Referrer-Policy', options.referrerPolicy ?? 'strict-origin-when-cross-origin']);
|
|
22
|
+
}
|
|
23
|
+
if (options.hsts !== false) {
|
|
24
|
+
headersToSet.push(['Strict-Transport-Security', options.hsts ?? 'max-age=31536000; includeSubDomains']);
|
|
25
|
+
}
|
|
26
|
+
if (options.contentSecurityPolicy) {
|
|
27
|
+
headersToSet.push(['Content-Security-Policy', options.contentSecurityPolicy]);
|
|
28
|
+
}
|
|
29
|
+
headersToSet.push(['X-XSS-Protection', '0']);
|
|
30
|
+
|
|
31
|
+
const len = headersToSet.length;
|
|
32
|
+
const headersObj: Record<string, string> = Object.freeze((() => {
|
|
33
|
+
const o: Record<string, string> = {};
|
|
34
|
+
for (let i = 0; i < len; i++) {
|
|
35
|
+
const pair = headersToSet[i]!;
|
|
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 };
|
|
46
|
+
}
|
|
47
|
+
|
|
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) {
|
|
52
|
+
for (let i = 0; i < len; i++) {
|
|
53
|
+
const pair = headersToSet[i]!;
|
|
54
|
+
if (!r.headers.has(pair[0])) r.headers.set(pair[0], pair[1]);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return r;
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
if (res instanceof Response) {
|
|
61
|
+
for (let i = 0; i < len; i++) {
|
|
62
|
+
const pair = headersToSet[i]!;
|
|
63
|
+
if (!res.headers.has(pair[0])) res.headers.set(pair[0], pair[1]);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return res;
|
|
67
|
+
};
|
|
68
|
+
};
|
|
@@ -0,0 +1,99 @@
|
|
|
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 key = ctx.req.headers.get(headerName);
|
|
32
|
+
if (!key) return undefined;
|
|
33
|
+
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
const existing = cache.get(key);
|
|
36
|
+
if (existing) {
|
|
37
|
+
if (now < existing.expiresAt) {
|
|
38
|
+
return Response.json(existing.body, {
|
|
39
|
+
status: existing.status,
|
|
40
|
+
headers: { 'X-Idempotent-Replayed': 'true' }
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
cache.delete(key);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (inFlight.has(key)) {
|
|
47
|
+
return Response.json(
|
|
48
|
+
{ status: 'error', code: 'IDEMPOTENT_IN_FLIGHT', message: 'Duplicate request is currently in flight' },
|
|
49
|
+
{ status: 409 }
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
inFlight.add(key);
|
|
54
|
+
(ctx as any)._idempotencyKey = key;
|
|
55
|
+
(ctx as any)._idemInFlight = inFlight;
|
|
56
|
+
return undefined;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
(mw as any).__idempotencyCommit = (ctx: Context, resVal: any, status: number) => {
|
|
60
|
+
const key = (ctx as any)._idempotencyKey;
|
|
61
|
+
if (!key) return;
|
|
62
|
+
inFlight.delete(key);
|
|
63
|
+
if (status >= 200 && status < 300 && !(resVal instanceof Response)) {
|
|
64
|
+
if (cache.size >= maxKeys) {
|
|
65
|
+
const oldest = cache.keys().next().value;
|
|
66
|
+
if (oldest !== undefined) cache.delete(oldest);
|
|
67
|
+
}
|
|
68
|
+
cache.set(key, {
|
|
69
|
+
status,
|
|
70
|
+
body: resVal,
|
|
71
|
+
expiresAt: Date.now() + ttlMs
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
return mw;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Singleflight Helper for Thundering-Herd / Cache-Stampede Protection.
|
|
81
|
+
* Coalesces N concurrent identical async calls into 1 underlying execution.
|
|
82
|
+
*/
|
|
83
|
+
export const createSingleflight = () => {
|
|
84
|
+
const inFlight = new Map<string, Promise<any>>();
|
|
85
|
+
|
|
86
|
+
return async <T>(key: string, fn: () => Promise<T>): Promise<{ data: T; shared: boolean }> => {
|
|
87
|
+
const existing = inFlight.get(key);
|
|
88
|
+
if (existing) {
|
|
89
|
+
const data = await existing;
|
|
90
|
+
return { data, shared: true };
|
|
91
|
+
}
|
|
92
|
+
const promise = fn().finally(() => {
|
|
93
|
+
inFlight.delete(key);
|
|
94
|
+
});
|
|
95
|
+
inFlight.set(key, promise);
|
|
96
|
+
const data = await promise;
|
|
97
|
+
return { data, shared: false };
|
|
98
|
+
};
|
|
99
|
+
};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { Context, Middleware } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export interface RateLimitOptions {
|
|
4
|
+
windowMs?: number;
|
|
5
|
+
max?: number;
|
|
6
|
+
message?: string;
|
|
7
|
+
keyGenerator?: (ctx: Context) => string;
|
|
8
|
+
maxEntries?: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface RateBucket {
|
|
12
|
+
count: number;
|
|
13
|
+
resetAt: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const rateLimit = (options: RateLimitOptions = {}): Middleware => {
|
|
17
|
+
const windowMs = options.windowMs ?? 60_000;
|
|
18
|
+
const max = options.max ?? 100;
|
|
19
|
+
const message = options.message ?? 'Too many requests, please try again later.';
|
|
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');
|
|
27
|
+
|
|
28
|
+
const buckets = new Map<string, RateBucket>();
|
|
29
|
+
|
|
30
|
+
return (ctx, next) => {
|
|
31
|
+
const now = Date.now();
|
|
32
|
+
const key = keyGenerator(ctx);
|
|
33
|
+
let bucket = buckets.get(key);
|
|
34
|
+
|
|
35
|
+
if (!bucket || now >= bucket.resetAt) {
|
|
36
|
+
// Prevent unbounded memory growth under key-flooding DoS
|
|
37
|
+
if (buckets.size >= maxEntries) {
|
|
38
|
+
for (const [k, v] of buckets) {
|
|
39
|
+
if (now >= v.resetAt) buckets.delete(k);
|
|
40
|
+
if (buckets.size < maxEntries) break;
|
|
41
|
+
}
|
|
42
|
+
if (buckets.size >= maxEntries) {
|
|
43
|
+
const firstKey = buckets.keys().next().value;
|
|
44
|
+
if (firstKey !== undefined) buckets.delete(firstKey);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
bucket = { count: 1, resetAt: now + windowMs };
|
|
48
|
+
buckets.set(key, bucket);
|
|
49
|
+
} else {
|
|
50
|
+
bucket.count++;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const remaining = Math.max(0, max - bucket.count);
|
|
54
|
+
ctx.setHeader('X-RateLimit-Limit', String(max));
|
|
55
|
+
ctx.setHeader('X-RateLimit-Remaining', String(remaining));
|
|
56
|
+
ctx.setHeader('X-RateLimit-Reset', String(Math.ceil(bucket.resetAt / 1000)));
|
|
57
|
+
|
|
58
|
+
if (bucket.count > max) {
|
|
59
|
+
const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000));
|
|
60
|
+
return Response.json(
|
|
61
|
+
{ status: 'error', code: 'RATE_LIMITED', message },
|
|
62
|
+
{
|
|
63
|
+
status: 429,
|
|
64
|
+
headers: {
|
|
65
|
+
'Retry-After': String(retryAfter),
|
|
66
|
+
'X-RateLimit-Limit': String(max),
|
|
67
|
+
'X-RateLimit-Remaining': '0',
|
|
68
|
+
'X-RateLimit-Reset': String(Math.ceil(bucket.resetAt / 1000))
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return next?.();
|
|
75
|
+
};
|
|
76
|
+
};
|
|
@@ -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
|
+
};
|