barejs 0.1.47 → 0.1.49
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/LICENSE +20 -20
- package/README.md +221 -184
- package/dist/index.js +122 -187
- package/dist/types/client/index.d.ts +48 -0
- package/dist/types/core/bare.d.ts +14 -1
- package/dist/types/core/context.d.ts +9 -1
- package/dist/types/core/router.d.ts +1 -0
- package/dist/types/index.d.ts +6 -2
- package/dist/types/security/auth.d.ts +2 -2
- package/dist/types/security/headers.d.ts +9 -0
- package/dist/types/security/rateLimit.d.ts +9 -0
- package/dist/types/utils/openapi.d.ts +15 -0
- package/package.json +68 -68
- package/src/client/index.ts +121 -0
- package/src/core/bare.ts +463 -318
- package/src/core/config.ts +31 -31
- package/src/core/context.ts +205 -111
- package/src/core/loader.ts +12 -12
- package/src/core/radix.ts +184 -171
- package/src/core/router.ts +61 -62
- package/src/index.ts +73 -61
- package/src/security/auth.ts +174 -153
- package/src/security/cors.ts +45 -26
- package/src/security/hash.ts +22 -19
- package/src/security/headers.ts +59 -0
- package/src/security/rateLimit.ts +76 -0
- package/src/security/validators.ts +137 -133
- package/src/utils/openapi.ts +116 -0
- package/src/utils/static.ts +42 -25
package/src/security/auth.ts
CHANGED
|
@@ -1,154 +1,175 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* UTILS: Internal Crypto Helpers using Native Web Crypto
|
|
6
|
-
* Optimized for Bun performance and
|
|
7
|
-
*/
|
|
8
|
-
const encoder = new TextEncoder();
|
|
9
|
-
|
|
10
|
-
//
|
|
11
|
-
const base64Url = (input: Uint8Array | string): string => {
|
|
12
|
-
|
|
13
|
-
? Buffer.from(input).toString('
|
|
14
|
-
: Buffer.from(input).toString('
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
const
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
const
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
if (
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
const
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
1
|
+
import type { Next } from '../core/context';
|
|
2
|
+
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* UTILS: Internal Crypto Helpers using Native Web Crypto & Node Crypto
|
|
6
|
+
* Optimized for Bun performance and constant-time security.
|
|
7
|
+
*/
|
|
8
|
+
const encoder = new TextEncoder();
|
|
9
|
+
|
|
10
|
+
// Base64Url Helpers (RFC 4648) using native C++ Buffer encoding
|
|
11
|
+
const base64Url = (input: Uint8Array | string): string => {
|
|
12
|
+
return typeof input === 'string'
|
|
13
|
+
? Buffer.from(input).toString('base64url')
|
|
14
|
+
: Buffer.from(input).toString('base64url');
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const fromBase64Url = (str: string): string => {
|
|
18
|
+
return Buffer.from(str, 'base64url').toString('utf-8');
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// PERF: Cache CryptoKeys to avoid repeated async importKey calls for createToken
|
|
22
|
+
const keyCache = new Map<string, CryptoKey>();
|
|
23
|
+
|
|
24
|
+
const importKey = async (secret: string): Promise<CryptoKey> => {
|
|
25
|
+
if (keyCache.has(secret)) return keyCache.get(secret)!;
|
|
26
|
+
|
|
27
|
+
const key = await crypto.subtle.importKey(
|
|
28
|
+
"raw",
|
|
29
|
+
encoder.encode(secret),
|
|
30
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
31
|
+
false,
|
|
32
|
+
["sign", "verify"]
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
keyCache.set(secret, key);
|
|
36
|
+
return key;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 4. TOKEN GENERATOR (Standard JWT)
|
|
41
|
+
*/
|
|
42
|
+
export const createToken = async (payload: object, secret: string): Promise<string> => {
|
|
43
|
+
const header = JSON.stringify({ alg: "HS256", typ: "JWT" });
|
|
44
|
+
const body = JSON.stringify(payload);
|
|
45
|
+
|
|
46
|
+
const encodedHeader = base64Url(header);
|
|
47
|
+
const encodedBody = base64Url(body);
|
|
48
|
+
const data = `${encodedHeader}.${encodedBody}`;
|
|
49
|
+
|
|
50
|
+
const key = await importKey(secret);
|
|
51
|
+
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(data));
|
|
52
|
+
const encodedSig = base64Url(new Uint8Array(signature));
|
|
53
|
+
|
|
54
|
+
return `${data}.${encodedSig}`;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 1. BARE TOKEN AUTH (Standard JWT Middleware)
|
|
59
|
+
* High-performance, constant-time JWT middleware for BareJS
|
|
60
|
+
*/
|
|
61
|
+
export const bareAuth = (secret: string) => {
|
|
62
|
+
return (ctx: any, next: any) => {
|
|
63
|
+
const authHeader = ctx.req.headers.get('Authorization');
|
|
64
|
+
|
|
65
|
+
if (!authHeader?.startsWith('Bearer ')) {
|
|
66
|
+
return ctx.status(401).send("Bearer token required");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const token = authHeader.slice(7);
|
|
70
|
+
const firstDot = token.indexOf('.');
|
|
71
|
+
const secondDot = firstDot === -1 ? -1 : token.indexOf('.', firstDot + 1);
|
|
72
|
+
if (firstDot === -1 || secondDot === -1 || token.indexOf('.', secondDot + 1) !== -1) {
|
|
73
|
+
return ctx.status(401).send("Malformed JWT token");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const headerB64 = token.slice(0, firstDot);
|
|
77
|
+
const payloadB64 = token.slice(firstDot + 1, secondDot);
|
|
78
|
+
const sigB64 = token.slice(secondDot + 1);
|
|
79
|
+
const data = token.slice(0, secondDot);
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
const expectedSig = createHmac('sha256', secret).update(data).digest();
|
|
83
|
+
const actualSig = Buffer.from(sigB64, 'base64url');
|
|
84
|
+
|
|
85
|
+
if (actualSig.length !== expectedSig.length || !timingSafeEqual(actualSig, expectedSig)) {
|
|
86
|
+
return ctx.status(401).send("Invalid signature");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const headerObj = JSON.parse(fromBase64Url(headerB64));
|
|
90
|
+
if (!headerObj || headerObj.alg !== 'HS256') {
|
|
91
|
+
return ctx.status(401).send("Unsupported token algorithm");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const decoded = JSON.parse(fromBase64Url(payloadB64));
|
|
95
|
+
const nowSec = Date.now() * 0.001;
|
|
96
|
+
if (typeof decoded.exp === 'number' && nowSec >= decoded.exp) {
|
|
97
|
+
return ctx.status(401).send("Token expired");
|
|
98
|
+
}
|
|
99
|
+
if (typeof decoded.nbf === 'number' && nowSec < decoded.nbf) {
|
|
100
|
+
return ctx.status(401).send("Token not active");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
ctx.set('user', decoded);
|
|
104
|
+
|
|
105
|
+
if (Array.isArray(next)) {
|
|
106
|
+
if (next.length === 0) return;
|
|
107
|
+
const [current, ...rest] = next;
|
|
108
|
+
return current(ctx, rest);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (typeof next === 'function') {
|
|
112
|
+
return next();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return;
|
|
116
|
+
} catch {
|
|
117
|
+
return ctx.status(401).send("Token verification failed");
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const sha256 = (value: string): Buffer => createHash('sha256').update(value).digest();
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* 2. BASIC AUTH
|
|
126
|
+
* Useful for internal tools and simple admin panels
|
|
127
|
+
*/
|
|
128
|
+
export const basicAuth = (credentials: { user: string; pass: string }) => {
|
|
129
|
+
const expectedUserHash = sha256(credentials.user);
|
|
130
|
+
const expectedPassHash = sha256(credentials.pass);
|
|
131
|
+
|
|
132
|
+
return async (ctx: any, next: Next) => {
|
|
133
|
+
const authHeader = ctx.req.headers.get('Authorization');
|
|
134
|
+
if (!authHeader?.startsWith('Basic ')) {
|
|
135
|
+
return ctx.status(401).json({ status: 'error', message: 'Basic Auth required' });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const token = authHeader.slice(6).trim();
|
|
139
|
+
if (!token) return ctx.status(401).json({ status: 'error', message: 'Missing credentials' });
|
|
140
|
+
|
|
141
|
+
const decoded = Buffer.from(token, 'base64').toString('utf-8');
|
|
142
|
+
const colonIdx = decoded.indexOf(':');
|
|
143
|
+
if (colonIdx === -1) {
|
|
144
|
+
return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const user = decoded.slice(0, colonIdx);
|
|
148
|
+
const pass = decoded.slice(colonIdx + 1);
|
|
149
|
+
|
|
150
|
+
const userMatch = timingSafeEqual(sha256(user), expectedUserHash);
|
|
151
|
+
const passMatch = timingSafeEqual(sha256(pass), expectedPassHash);
|
|
152
|
+
|
|
153
|
+
if (userMatch && passMatch) {
|
|
154
|
+
return next();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 5. ROLE AUTHORIZATION (Bonus Max Function)
|
|
165
|
+
* Ensures user has specific permissions after bareAuth
|
|
166
|
+
*/
|
|
167
|
+
export const hasRole = (role: string) => {
|
|
168
|
+
return async (ctx: any, next: Next) => {
|
|
169
|
+
const user = ctx.get('user');
|
|
170
|
+
if (!user || user.role !== role) {
|
|
171
|
+
return ctx.status(403).json({ status: 'error', message: `Required role: ${role}` });
|
|
172
|
+
}
|
|
173
|
+
return next();
|
|
174
|
+
};
|
|
154
175
|
};
|
package/src/security/cors.ts
CHANGED
|
@@ -1,27 +1,46 @@
|
|
|
1
|
-
import type { Middleware } from '../core/context';
|
|
2
|
-
|
|
3
|
-
export const cors = (options: { origin?: string; methods?: string } = {}) => {
|
|
4
|
-
const origin = options.origin || '*';
|
|
5
|
-
const methods = options.methods || 'GET,POST,PUT,PATCH,DELETE,OPTIONS';
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
1
|
+
import type { Middleware } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export const cors = (options: { origin?: string; methods?: string } = {}) => {
|
|
4
|
+
const origin = options.origin || '*';
|
|
5
|
+
const methods = options.methods || 'GET,POST,PUT,PATCH,DELETE,OPTIONS';
|
|
6
|
+
const preflightHeaders: Record<string, string> = {
|
|
7
|
+
'Access-Control-Allow-Origin': origin,
|
|
8
|
+
'Access-Control-Allow-Methods': methods,
|
|
9
|
+
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
|
|
10
|
+
};
|
|
11
|
+
if (origin !== '*') {
|
|
12
|
+
preflightHeaders['Vary'] = 'Origin';
|
|
13
|
+
}
|
|
14
|
+
const preflightInit = { status: 204, headers: preflightHeaders };
|
|
15
|
+
|
|
16
|
+
const mw: Middleware = (ctx, next) => {
|
|
17
|
+
if (ctx.req.method === 'OPTIONS') {
|
|
18
|
+
return new Response(null, preflightInit);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
ctx.setHeader('Access-Control-Allow-Origin', origin);
|
|
22
|
+
ctx.setHeader('Access-Control-Allow-Methods', methods);
|
|
23
|
+
if (origin !== '*') {
|
|
24
|
+
ctx.setHeader('Vary', 'Origin');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const res = next?.();
|
|
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;
|
|
44
|
+
};
|
|
45
|
+
return mw;
|
|
27
46
|
};
|
package/src/security/hash.ts
CHANGED
|
@@ -1,20 +1,23 @@
|
|
|
1
|
-
// src/security/hash.ts
|
|
2
|
-
import { BARE_CONFIG } from '../core/config';
|
|
3
|
-
|
|
4
|
-
export const Hash = {
|
|
5
|
-
make: (data: string): Promise<string> =>
|
|
6
|
-
Bun.password.hash(data, BARE_CONFIG.hash),
|
|
7
|
-
|
|
8
|
-
verify: (data: string, hash: string): Promise<boolean> =>
|
|
9
|
-
Bun.password.verify(data, hash),
|
|
10
|
-
|
|
11
|
-
needsRehash: (hash: string): boolean => {
|
|
12
|
-
const { algorithm, memoryCost, timeCost } = BARE_CONFIG.hash;
|
|
13
|
-
if (
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
);
|
|
19
|
-
|
|
1
|
+
// src/security/hash.ts
|
|
2
|
+
import { BARE_CONFIG } from '../core/config';
|
|
3
|
+
|
|
4
|
+
export const Hash = {
|
|
5
|
+
make: (data: string): Promise<string> =>
|
|
6
|
+
Bun.password.hash(data, BARE_CONFIG.hash),
|
|
7
|
+
|
|
8
|
+
verify: (data: string, hash: string): Promise<boolean> =>
|
|
9
|
+
Bun.password.verify(data, hash),
|
|
10
|
+
|
|
11
|
+
needsRehash: (hash: string): boolean => {
|
|
12
|
+
const { algorithm, memoryCost, timeCost } = BARE_CONFIG.hash;
|
|
13
|
+
if (algorithm === 'bcrypt') {
|
|
14
|
+
if (!/^\$2[aby]\$/.test(hash)) return true;
|
|
15
|
+
const costMatch = hash.match(/^\$2[aby]\$(\d+)\$/);
|
|
16
|
+
return !costMatch || Number(costMatch[1]) !== timeCost;
|
|
17
|
+
}
|
|
18
|
+
if (!hash.startsWith(`$${algorithm}$`)) return true;
|
|
19
|
+
const mMatch = hash.match(/(?:^|[,$])m=(\d+)(?:[,$]|$)/);
|
|
20
|
+
const tMatch = hash.match(/(?:^|[,$])t=(\d+)(?:[,$]|$)/);
|
|
21
|
+
return !mMatch || Number(mMatch[1]) !== memoryCost || !tMatch || Number(tMatch[1]) !== timeCost;
|
|
22
|
+
}
|
|
20
23
|
};
|
|
@@ -0,0 +1,59 @@
|
|
|
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
|
+
|
|
33
|
+
return (ctx, next) => {
|
|
34
|
+
for (let i = 0; i < len; i++) {
|
|
35
|
+
const pair = headersToSet[i]!;
|
|
36
|
+
ctx.setHeader(pair[0], pair[1]);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const res = next?.();
|
|
40
|
+
if (res && typeof (res as any).then === 'function') {
|
|
41
|
+
return (res as Promise<any>).then((r) => {
|
|
42
|
+
if (r instanceof Response) {
|
|
43
|
+
for (let i = 0; i < len; i++) {
|
|
44
|
+
const pair = headersToSet[i]!;
|
|
45
|
+
if (!r.headers.has(pair[0])) r.headers.set(pair[0], pair[1]);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return r;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
if (res instanceof Response) {
|
|
52
|
+
for (let i = 0; i < len; i++) {
|
|
53
|
+
const pair = headersToSet[i]!;
|
|
54
|
+
if (!res.headers.has(pair[0])) res.headers.set(pair[0], pair[1]);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return res;
|
|
58
|
+
};
|
|
59
|
+
};
|
|
@@ -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
|
+
};
|