barejs 0.1.51 → 0.1.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -29
- package/dist/index.js +95 -86
- package/dist/types/core/bare.d.ts +10 -2
- package/dist/types/core/context.d.ts +2 -1
- package/dist/types/core/router.d.ts +61 -10
- package/dist/types/index.d.ts +5 -4
- package/dist/types/security/auth.d.ts +17 -4
- package/dist/types/security/idempotency.d.ts +3 -0
- package/dist/types/security/rateLimit.d.ts +3 -0
- package/dist/types/security/store.d.ts +36 -0
- package/dist/types/utils/compress.d.ts +6 -3
- package/dist/types/utils/static.d.ts +8 -0
- package/llms.txt +19 -20
- package/package.json +1 -1
- package/src/client/index.ts +4 -3
- package/src/core/bare.ts +110 -58
- package/src/core/context.ts +67 -33
- package/src/core/radix.ts +3 -1
- package/src/core/router.ts +94 -16
- package/src/index.ts +13 -4
- package/src/security/auth.ts +282 -49
- package/src/security/cors.ts +25 -1
- package/src/security/csrf.ts +8 -1
- package/src/security/idempotency.ts +127 -26
- package/src/security/rateLimit.ts +40 -22
- package/src/security/store.ts +159 -0
- package/src/security/validators.ts +10 -4
- package/src/utils/compress.ts +50 -7
- package/src/utils/static.ts +69 -16
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Context, Middleware } from '../core/context';
|
|
2
|
+
import type { CachedIdempotentEntry, IdempotencyStore } from './store';
|
|
2
3
|
|
|
3
4
|
export interface IdempotencyOptions {
|
|
4
5
|
/** Header name (default: 'idempotency-key') */
|
|
@@ -7,13 +8,35 @@ export interface IdempotencyOptions {
|
|
|
7
8
|
ttlMs?: number;
|
|
8
9
|
/** Maximum cached keys before LRU eviction (default: 10_000) */
|
|
9
10
|
maxKeys?: number;
|
|
11
|
+
/** Optional external store (e.g. redisStore(client)). Uses in-memory Map fast path when omitted. */
|
|
12
|
+
store?: IdempotencyStore;
|
|
10
13
|
}
|
|
11
14
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
const buildReplayResponse = (existing: CachedIdempotentEntry): Response => {
|
|
16
|
+
if (existing.rawBody !== undefined) {
|
|
17
|
+
return new Response(existing.rawBody, {
|
|
18
|
+
status: existing.status,
|
|
19
|
+
headers: {
|
|
20
|
+
'content-type': existing.contentType || 'application/json',
|
|
21
|
+
'X-Idempotent-Replayed': 'true'
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
return Response.json(existing.body, {
|
|
26
|
+
status: existing.status,
|
|
27
|
+
headers: { 'X-Idempotent-Replayed': 'true' }
|
|
28
|
+
});
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const extractIdemKey = (ctx: Context, headerName: string): string | undefined => {
|
|
32
|
+
const rawKey = ctx.req.headers.get(headerName);
|
|
33
|
+
if (!rawKey) return undefined;
|
|
34
|
+
const rawUrl = ctx.req.url;
|
|
35
|
+
const s = rawUrl.indexOf('/', 8);
|
|
36
|
+
const q = s === -1 ? -1 : rawUrl.indexOf('?', s);
|
|
37
|
+
const path = s === -1 ? '/' : (q === -1 ? rawUrl.slice(s) : rawUrl.slice(s, q));
|
|
38
|
+
return `${ctx.req.method}:${path}:${rawKey}`;
|
|
39
|
+
};
|
|
17
40
|
|
|
18
41
|
/**
|
|
19
42
|
* Payment & Order Double-Charge Protection Middleware (Idempotency-Key).
|
|
@@ -23,32 +46,97 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
|
|
|
23
46
|
const headerName = (options.headerName || 'idempotency-key').toLowerCase();
|
|
24
47
|
const ttlMs = options.ttlMs ?? 300_000;
|
|
25
48
|
const maxKeys = options.maxKeys ?? 10_000;
|
|
49
|
+
const externalStore = options.store;
|
|
50
|
+
|
|
51
|
+
if (externalStore) {
|
|
52
|
+
const storeLockShim = { delete: (k: string) => { void externalStore.release(k); } };
|
|
53
|
+
const mw: Middleware = async (ctx: Context) => {
|
|
54
|
+
const key = extractIdemKey(ctx, headerName);
|
|
55
|
+
if (!key) {
|
|
56
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const existing = await externalStore.get(key);
|
|
61
|
+
if (existing && Date.now() < existing.expiresAt) {
|
|
62
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
63
|
+
return buildReplayResponse(existing);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const acquired = await externalStore.acquire(key, ttlMs);
|
|
67
|
+
if (!acquired) {
|
|
68
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
69
|
+
return Response.json(
|
|
70
|
+
{ status: 'error', code: 'IDEMPOTENT_IN_FLIGHT', message: 'Duplicate request is currently in flight' },
|
|
71
|
+
{ status: 409 }
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
(ctx as any)._idempotencyKey = key;
|
|
76
|
+
(ctx as any)._idemInFlight = storeLockShim;
|
|
77
|
+
return undefined;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
(mw as any).__idempotencyCommit = (ctx: Context, resVal: any, status: number) => {
|
|
81
|
+
const key = (ctx as any)._idempotencyKey;
|
|
82
|
+
if (!key) return;
|
|
83
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
84
|
+
(ctx as any)._idemInFlight = undefined;
|
|
85
|
+
const clonedRes = status >= 200 && status < 300 && resVal instanceof Response ? resVal.clone() : null;
|
|
86
|
+
const ct = clonedRes ? (clonedRes.headers.get('content-type') || 'application/json') : undefined;
|
|
87
|
+
void (async () => {
|
|
88
|
+
try {
|
|
89
|
+
if (status >= 200 && status < 300) {
|
|
90
|
+
if (clonedRes) {
|
|
91
|
+
const buf = await clonedRes.arrayBuffer();
|
|
92
|
+
await externalStore.set(key, { status, rawBody: buf, contentType: ct, expiresAt: Date.now() + ttlMs }, ttlMs);
|
|
93
|
+
} else {
|
|
94
|
+
await externalStore.set(key, { status, body: resVal, expiresAt: Date.now() + ttlMs }, ttlMs);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
} catch {
|
|
98
|
+
// Best-effort cache write
|
|
99
|
+
} finally {
|
|
100
|
+
await externalStore.release(key);
|
|
101
|
+
}
|
|
102
|
+
})();
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
(mw as any).__idempotencyRelease = (ctx: Context) => {
|
|
106
|
+
const key = (ctx as any)._idempotencyKey;
|
|
107
|
+
if (key) {
|
|
108
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
109
|
+
(ctx as any)._idemInFlight = undefined;
|
|
110
|
+
void externalStore.release(key);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
return mw;
|
|
115
|
+
}
|
|
26
116
|
|
|
27
117
|
const cache = new Map<string, CachedIdempotentEntry>();
|
|
28
118
|
const inFlight = new Set<string>();
|
|
29
119
|
|
|
120
|
+
const evictIfNeeded = () => {
|
|
121
|
+
if (cache.size >= maxKeys) {
|
|
122
|
+
const oldest = cache.keys().next().value;
|
|
123
|
+
if (oldest !== undefined) cache.delete(oldest);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
|
|
30
127
|
const mw: Middleware = (ctx: Context) => {
|
|
31
|
-
const
|
|
32
|
-
if (!
|
|
128
|
+
const key = extractIdemKey(ctx, headerName);
|
|
129
|
+
if (!key) {
|
|
33
130
|
(ctx as any)._idempotencyKey = undefined;
|
|
34
131
|
return undefined;
|
|
35
132
|
}
|
|
36
133
|
|
|
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
134
|
const now = Date.now();
|
|
44
135
|
const existing = cache.get(key);
|
|
45
136
|
if (existing) {
|
|
46
137
|
if (now < existing.expiresAt) {
|
|
47
138
|
(ctx as any)._idempotencyKey = undefined;
|
|
48
|
-
return
|
|
49
|
-
status: existing.status,
|
|
50
|
-
headers: { 'X-Idempotent-Replayed': 'true' }
|
|
51
|
-
});
|
|
139
|
+
return buildReplayResponse(existing);
|
|
52
140
|
}
|
|
53
141
|
cache.delete(key);
|
|
54
142
|
}
|
|
@@ -63,6 +151,7 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
|
|
|
63
151
|
|
|
64
152
|
inFlight.add(key);
|
|
65
153
|
(ctx as any)._idempotencyKey = key;
|
|
154
|
+
(ctx as any)._idemInFlight = inFlight;
|
|
66
155
|
return undefined;
|
|
67
156
|
};
|
|
68
157
|
|
|
@@ -70,17 +159,28 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
|
|
|
70
159
|
const key = (ctx as any)._idempotencyKey;
|
|
71
160
|
if (!key) return;
|
|
72
161
|
(ctx as any)._idempotencyKey = undefined;
|
|
162
|
+
(ctx as any)._idemInFlight = undefined;
|
|
73
163
|
inFlight.delete(key);
|
|
74
|
-
if (status >= 200 && status < 300
|
|
75
|
-
if (
|
|
76
|
-
const
|
|
77
|
-
|
|
164
|
+
if (status >= 200 && status < 300) {
|
|
165
|
+
if (resVal instanceof Response) {
|
|
166
|
+
const ct = resVal.headers.get('content-type') || 'application/json';
|
|
167
|
+
resVal.clone().arrayBuffer().then((buf) => {
|
|
168
|
+
evictIfNeeded();
|
|
169
|
+
cache.set(key, {
|
|
170
|
+
status,
|
|
171
|
+
rawBody: buf,
|
|
172
|
+
contentType: ct,
|
|
173
|
+
expiresAt: Date.now() + ttlMs
|
|
174
|
+
});
|
|
175
|
+
}).catch(() => {});
|
|
176
|
+
} else {
|
|
177
|
+
evictIfNeeded();
|
|
178
|
+
cache.set(key, {
|
|
179
|
+
status,
|
|
180
|
+
body: resVal,
|
|
181
|
+
expiresAt: Date.now() + ttlMs
|
|
182
|
+
});
|
|
78
183
|
}
|
|
79
|
-
cache.set(key, {
|
|
80
|
-
status,
|
|
81
|
-
body: resVal,
|
|
82
|
-
expiresAt: Date.now() + ttlMs
|
|
83
|
-
});
|
|
84
184
|
}
|
|
85
185
|
};
|
|
86
186
|
|
|
@@ -88,6 +188,7 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
|
|
|
88
188
|
const key = (ctx as any)._idempotencyKey;
|
|
89
189
|
if (key) {
|
|
90
190
|
(ctx as any)._idempotencyKey = undefined;
|
|
191
|
+
(ctx as any)._idemInFlight = undefined;
|
|
91
192
|
inFlight.delete(key);
|
|
92
193
|
}
|
|
93
194
|
};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Context, Middleware } from '../core/context';
|
|
2
|
+
import type { RateLimitStore } from './store';
|
|
2
3
|
|
|
3
4
|
export interface RateLimitOptions {
|
|
4
5
|
windowMs?: number;
|
|
@@ -6,6 +7,8 @@ export interface RateLimitOptions {
|
|
|
6
7
|
message?: string;
|
|
7
8
|
keyGenerator?: (ctx: Context) => string;
|
|
8
9
|
maxEntries?: number;
|
|
10
|
+
/** Optional external store (e.g. redisStore(client)). Uses in-memory Map fast path when omitted. */
|
|
11
|
+
store?: RateLimitStore;
|
|
9
12
|
}
|
|
10
13
|
|
|
11
14
|
interface RateBucket {
|
|
@@ -19,6 +22,42 @@ export const rateLimit = (options: RateLimitOptions = {}): Middleware => {
|
|
|
19
22
|
const message = options.message ?? 'Too many requests, please try again later.';
|
|
20
23
|
const maxEntries = options.maxEntries ?? 10_000;
|
|
21
24
|
const keyGenerator = options.keyGenerator ?? ((ctx: Context) => ctx.ip);
|
|
25
|
+
const store = options.store;
|
|
26
|
+
|
|
27
|
+
const finalizeBucket = (ctx: Context, count: number, resetAt: number, now: number, next: any) => {
|
|
28
|
+
const remaining = Math.max(0, max - count);
|
|
29
|
+
const resetSec = String(Math.ceil(resetAt / 1000));
|
|
30
|
+
ctx.setHeader('X-RateLimit-Limit', String(max));
|
|
31
|
+
ctx.setHeader('X-RateLimit-Remaining', String(remaining));
|
|
32
|
+
ctx.setHeader('X-RateLimit-Reset', resetSec);
|
|
33
|
+
|
|
34
|
+
if (count > max) {
|
|
35
|
+
const retryAfter = Math.max(1, Math.ceil((resetAt - now) / 1000));
|
|
36
|
+
return Response.json(
|
|
37
|
+
{ status: 'error', code: 'RATE_LIMITED', message },
|
|
38
|
+
{
|
|
39
|
+
status: 429,
|
|
40
|
+
headers: {
|
|
41
|
+
'Retry-After': String(retryAfter),
|
|
42
|
+
'X-RateLimit-Limit': String(max),
|
|
43
|
+
'X-RateLimit-Remaining': '0',
|
|
44
|
+
'X-RateLimit-Reset': resetSec
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return next?.();
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
if (store) {
|
|
54
|
+
return async (ctx, next) => {
|
|
55
|
+
const now = Date.now();
|
|
56
|
+
const key = keyGenerator(ctx);
|
|
57
|
+
const { count, resetAt } = await store.increment(key, windowMs);
|
|
58
|
+
return finalizeBucket(ctx, count, resetAt, now, next);
|
|
59
|
+
};
|
|
60
|
+
}
|
|
22
61
|
|
|
23
62
|
const buckets = new Map<string, RateBucket>();
|
|
24
63
|
|
|
@@ -45,27 +84,6 @@ export const rateLimit = (options: RateLimitOptions = {}): Middleware => {
|
|
|
45
84
|
bucket.count++;
|
|
46
85
|
}
|
|
47
86
|
|
|
48
|
-
|
|
49
|
-
ctx.setHeader('X-RateLimit-Limit', String(max));
|
|
50
|
-
ctx.setHeader('X-RateLimit-Remaining', String(remaining));
|
|
51
|
-
ctx.setHeader('X-RateLimit-Reset', String(Math.ceil(bucket.resetAt / 1000)));
|
|
52
|
-
|
|
53
|
-
if (bucket.count > max) {
|
|
54
|
-
const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000));
|
|
55
|
-
return Response.json(
|
|
56
|
-
{ status: 'error', code: 'RATE_LIMITED', message },
|
|
57
|
-
{
|
|
58
|
-
status: 429,
|
|
59
|
-
headers: {
|
|
60
|
-
'Retry-After': String(retryAfter),
|
|
61
|
-
'X-RateLimit-Limit': String(max),
|
|
62
|
-
'X-RateLimit-Remaining': '0',
|
|
63
|
-
'X-RateLimit-Reset': String(Math.ceil(bucket.resetAt / 1000))
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
return next?.();
|
|
87
|
+
return finalizeBucket(ctx, bucket.count, bucket.resetAt, now, next);
|
|
70
88
|
};
|
|
71
89
|
};
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
export interface RateLimitStore {
|
|
2
|
+
increment(key: string, windowMs: number): Promise<{ count: number; resetAt: number }> | { count: number; resetAt: number };
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export interface CachedIdempotentEntry {
|
|
6
|
+
status: number;
|
|
7
|
+
body?: any;
|
|
8
|
+
rawBody?: ArrayBuffer;
|
|
9
|
+
contentType?: string;
|
|
10
|
+
expiresAt: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface IdempotencyStore {
|
|
14
|
+
get(key: string): Promise<CachedIdempotentEntry | undefined> | CachedIdempotentEntry | undefined;
|
|
15
|
+
set(key: string, entry: CachedIdempotentEntry, ttlMs: number): Promise<void> | void;
|
|
16
|
+
acquire(key: string, ttlMs?: number): Promise<boolean> | boolean;
|
|
17
|
+
release(key: string): Promise<void> | void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface RevocationStore {
|
|
21
|
+
revoke(tokenOrJti: string, ttlMs: number): Promise<void> | void;
|
|
22
|
+
isRevoked(tokenOrJti: string): Promise<boolean> | boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type BareStore = RateLimitStore & IdempotencyStore & RevocationStore;
|
|
26
|
+
|
|
27
|
+
export interface RedisStoreOptions {
|
|
28
|
+
/** Key prefix for all entries (default: 'barejs:') */
|
|
29
|
+
prefix?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Lightweight Redis adapter compatible with both Bun.redis and ioredis.
|
|
34
|
+
* Implements RateLimitStore, IdempotencyStore, and RevocationStore.
|
|
35
|
+
*/
|
|
36
|
+
export const redisStore = (client: any, options: RedisStoreOptions = {}): BareStore => {
|
|
37
|
+
const prefix = options.prefix ?? 'barejs:';
|
|
38
|
+
|
|
39
|
+
const useSend = typeof client.send === 'function';
|
|
40
|
+
|
|
41
|
+
const cmdGet = (key: string) =>
|
|
42
|
+
useSend ? client.send('GET', [key]) : client.get(key);
|
|
43
|
+
|
|
44
|
+
const cmdDel = (key: string) =>
|
|
45
|
+
useSend ? client.send('DEL', [key]) : client.del(key);
|
|
46
|
+
|
|
47
|
+
const cmdIncr = (key: string) =>
|
|
48
|
+
useSend ? client.send('INCR', [key]) : client.incr(key);
|
|
49
|
+
|
|
50
|
+
const setWithTtl = async (key: string, value: string, ttlMs: number): Promise<void> => {
|
|
51
|
+
if (useSend) {
|
|
52
|
+
await client.send('SET', [key, value, 'PX', String(ttlMs)]);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
await client.set(key, value, 'PX', ttlMs);
|
|
57
|
+
} catch {
|
|
58
|
+
await client.set(key, value);
|
|
59
|
+
if (typeof client.pexpire === 'function') {
|
|
60
|
+
await client.pexpire(key, ttlMs);
|
|
61
|
+
} else if (typeof client.expire === 'function') {
|
|
62
|
+
await client.expire(key, Math.max(1, Math.ceil(ttlMs / 1000)));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const setExpiry = async (fullKey: string, windowMs: number): Promise<void> => {
|
|
68
|
+
if (useSend) {
|
|
69
|
+
await client.send('PEXPIRE', [fullKey, String(windowMs)]);
|
|
70
|
+
} else if (typeof client.pexpire === 'function') {
|
|
71
|
+
await client.pexpire(fullKey, windowMs);
|
|
72
|
+
} else if (typeof client.expire === 'function') {
|
|
73
|
+
await client.expire(fullKey, Math.max(1, Math.ceil(windowMs / 1000)));
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
async increment(key: string, windowMs: number): Promise<{ count: number; resetAt: number }> {
|
|
79
|
+
const fullKey = `${prefix}rl:${key}`;
|
|
80
|
+
const count = Number(await cmdIncr(fullKey));
|
|
81
|
+
if (count === 1) {
|
|
82
|
+
await setExpiry(fullKey, windowMs);
|
|
83
|
+
}
|
|
84
|
+
let pttl = windowMs;
|
|
85
|
+
let rawPttl: number | null = null;
|
|
86
|
+
if (useSend) {
|
|
87
|
+
rawPttl = Number(await client.send('PTTL', [fullKey]));
|
|
88
|
+
} else if (typeof client.pttl === 'function') {
|
|
89
|
+
rawPttl = Number(await client.pttl(fullKey));
|
|
90
|
+
} else if (typeof client.ttl === 'function') {
|
|
91
|
+
const t = Number(await client.ttl(fullKey));
|
|
92
|
+
rawPttl = t < 0 ? t : t * 1000;
|
|
93
|
+
}
|
|
94
|
+
if (rawPttl === -1) {
|
|
95
|
+
await setExpiry(fullKey, windowMs);
|
|
96
|
+
} else if (rawPttl !== null && Number.isFinite(rawPttl) && rawPttl > 0) {
|
|
97
|
+
pttl = rawPttl;
|
|
98
|
+
}
|
|
99
|
+
return { count, resetAt: Date.now() + pttl };
|
|
100
|
+
},
|
|
101
|
+
|
|
102
|
+
async get(key: string): Promise<CachedIdempotentEntry | undefined> {
|
|
103
|
+
const raw = await cmdGet(`${prefix}idem:${key}`);
|
|
104
|
+
if (!raw) return undefined;
|
|
105
|
+
try {
|
|
106
|
+
const parsed = JSON.parse(typeof raw === 'string' ? raw : String(raw));
|
|
107
|
+
if (typeof parsed.rawBodyBase64 === 'string') {
|
|
108
|
+
const buf = Buffer.from(parsed.rawBodyBase64, 'base64');
|
|
109
|
+
return {
|
|
110
|
+
status: parsed.status,
|
|
111
|
+
rawBody: buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength),
|
|
112
|
+
contentType: parsed.contentType,
|
|
113
|
+
expiresAt: parsed.expiresAt
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
return parsed;
|
|
117
|
+
} catch {
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
|
|
122
|
+
async set(key: string, entry: CachedIdempotentEntry, ttlMs: number): Promise<void> {
|
|
123
|
+
const serializable: any = {
|
|
124
|
+
status: entry.status,
|
|
125
|
+
expiresAt: entry.expiresAt
|
|
126
|
+
};
|
|
127
|
+
if (entry.rawBody !== undefined) {
|
|
128
|
+
serializable.rawBodyBase64 = Buffer.from(entry.rawBody).toString('base64');
|
|
129
|
+
serializable.contentType = entry.contentType;
|
|
130
|
+
} else {
|
|
131
|
+
serializable.body = entry.body;
|
|
132
|
+
}
|
|
133
|
+
await setWithTtl(`${prefix}idem:${key}`, JSON.stringify(serializable), ttlMs);
|
|
134
|
+
},
|
|
135
|
+
|
|
136
|
+
async acquire(key: string, ttlMs: number = 30_000): Promise<boolean> {
|
|
137
|
+
const lockKey = `${prefix}idem:lock:${key}`;
|
|
138
|
+
if (useSend) {
|
|
139
|
+
const res = await client.send('SET', [lockKey, '1', 'PX', String(ttlMs), 'NX']);
|
|
140
|
+
return res === 'OK' || res === true;
|
|
141
|
+
}
|
|
142
|
+
const res = await client.set(lockKey, '1', 'PX', ttlMs, 'NX');
|
|
143
|
+
return res === 'OK' || res === true || res === 1;
|
|
144
|
+
},
|
|
145
|
+
|
|
146
|
+
async release(key: string): Promise<void> {
|
|
147
|
+
await cmdDel(`${prefix}idem:lock:${key}`);
|
|
148
|
+
},
|
|
149
|
+
|
|
150
|
+
async revoke(tokenOrJti: string, ttlMs: number): Promise<void> {
|
|
151
|
+
await setWithTtl(`${prefix}rev:${tokenOrJti}`, '1', ttlMs);
|
|
152
|
+
},
|
|
153
|
+
|
|
154
|
+
async isRevoked(tokenOrJti: string): Promise<boolean> {
|
|
155
|
+
const val = await cmdGet(`${prefix}rev:${tokenOrJti}`);
|
|
156
|
+
return val !== null && val !== undefined;
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
};
|
|
@@ -189,6 +189,7 @@ const buildProjectorExpr = (schema: any, accessor: string): string | null => {
|
|
|
189
189
|
if (!props || typeof props !== 'object') return null;
|
|
190
190
|
const entries: string[] = [];
|
|
191
191
|
for (const [k, subSchema] of Object.entries<any>(props)) {
|
|
192
|
+
if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
|
|
192
193
|
const keyLit = JSON.stringify(k);
|
|
193
194
|
const propAccess = `${accessor}[${keyLit}]`;
|
|
194
195
|
const nestedExpr = buildProjectorExpr(subSchema, propAccess);
|
|
@@ -274,6 +275,7 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
274
275
|
const bodyProjector = schemas.stripUnknown && schemas.body ? compileProjector(schemas.body) : null;
|
|
275
276
|
const responseFilter = schemas.response ? createResponseFilter(schemas.response) : null;
|
|
276
277
|
const maxBodySize = schemas.maxBodySize ?? 1048576;
|
|
278
|
+
const hasSyncParts = Boolean(paramsCheck || queryCheck || headersCheck);
|
|
277
279
|
|
|
278
280
|
const validateSyncParts = (ctx: Context): Response | undefined => {
|
|
279
281
|
if (paramsCheck) {
|
|
@@ -299,8 +301,10 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
299
301
|
|
|
300
302
|
if (!bodyCheck) {
|
|
301
303
|
const syncMw: Middleware = (ctx: Context, next?: Next) => {
|
|
302
|
-
|
|
303
|
-
|
|
304
|
+
if (hasSyncParts) {
|
|
305
|
+
const errRes = validateSyncParts(ctx);
|
|
306
|
+
if (errRes) return errRes;
|
|
307
|
+
}
|
|
304
308
|
return next ? next() : undefined;
|
|
305
309
|
};
|
|
306
310
|
(syncMw as any).__routeSchemas = schemas;
|
|
@@ -309,8 +313,10 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
309
313
|
}
|
|
310
314
|
|
|
311
315
|
const mw: Middleware = async (ctx: Context, next?: Next) => {
|
|
312
|
-
|
|
313
|
-
|
|
316
|
+
if (hasSyncParts) {
|
|
317
|
+
const errRes = validateSyncParts(ctx);
|
|
318
|
+
if (errRes) return errRes;
|
|
319
|
+
}
|
|
314
320
|
|
|
315
321
|
let body: any;
|
|
316
322
|
try {
|
package/src/utils/compress.ts
CHANGED
|
@@ -1,24 +1,56 @@
|
|
|
1
1
|
import type { Context, Middleware, Next } from '../core/context';
|
|
2
|
+
import { brotliCompressSync, constants as zlibConstants } from 'node:zlib';
|
|
3
|
+
|
|
4
|
+
export type CompressionEncoding = 'zstd' | 'br' | 'gzip';
|
|
2
5
|
|
|
3
6
|
export interface CompressOptions {
|
|
4
|
-
/** Minimum response size in bytes before
|
|
7
|
+
/** Minimum response size in bytes before compression is applied (default: 1024) */
|
|
5
8
|
minSize?: number;
|
|
6
9
|
/** Gzip compression level 0-9 (default: 6) */
|
|
7
10
|
level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
|
|
11
|
+
/** Preferred compression encodings in priority order (default: ['zstd', 'br', 'gzip']) */
|
|
12
|
+
encodings?: CompressionEncoding[];
|
|
8
13
|
}
|
|
9
14
|
|
|
10
15
|
/**
|
|
11
|
-
* Zero-dependency
|
|
12
|
-
*
|
|
16
|
+
* Zero-dependency response compression middleware supporting zstd, brotli (br), and gzip.
|
|
17
|
+
* Negotiates encoding from Accept-Encoding, and skips streaming SSE, 204/304, already-encoded, and small payloads.
|
|
13
18
|
*/
|
|
14
19
|
export const compress = (options: CompressOptions = {}): Middleware => {
|
|
15
20
|
const minSize = options.minSize ?? 1024;
|
|
16
21
|
const level = options.level ?? 6;
|
|
22
|
+
const encodings: CompressionEncoding[] = options.encodings ?? ['zstd', 'br', 'gzip'];
|
|
23
|
+
const hasZstd = typeof (Bun as any).zstdCompressSync === 'function';
|
|
24
|
+
|
|
25
|
+
const isAccepted = (lower: string, enc: CompressionEncoding): boolean => {
|
|
26
|
+
const idx = lower.indexOf(enc);
|
|
27
|
+
if (idx === -1) return false;
|
|
28
|
+
const comma = lower.indexOf(',', idx);
|
|
29
|
+
const segment = comma === -1 ? lower.slice(idx) : lower.slice(idx, comma);
|
|
30
|
+
const qIdx = segment.indexOf(';q=');
|
|
31
|
+
if (qIdx !== -1) {
|
|
32
|
+
const qVal = parseFloat(segment.slice(qIdx + 3));
|
|
33
|
+
if (Number.isFinite(qVal) && qVal <= 0) return false;
|
|
34
|
+
}
|
|
35
|
+
return true;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const negotiate = (accept: string): CompressionEncoding | null => {
|
|
39
|
+
const lower = accept.toLowerCase();
|
|
40
|
+
for (let i = 0; i < encodings.length; i++) {
|
|
41
|
+
const enc = encodings[i]!;
|
|
42
|
+
if (enc === 'zstd' && !hasZstd) continue;
|
|
43
|
+
if (isAccepted(lower, enc)) return enc;
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
};
|
|
17
47
|
|
|
18
48
|
const applyCompress = async (ctx: Context, res: any) => {
|
|
19
49
|
if (ctx.req.method === 'HEAD') return res;
|
|
20
50
|
const accept = ctx.req.headers.get('accept-encoding');
|
|
21
|
-
if (!accept
|
|
51
|
+
if (!accept) return res;
|
|
52
|
+
const chosen = negotiate(accept);
|
|
53
|
+
if (!chosen) return res;
|
|
22
54
|
if (!(res instanceof Response)) return res;
|
|
23
55
|
if (res.status === 204 || res.status === 304) return res;
|
|
24
56
|
if (res.headers.has('content-encoding')) return res;
|
|
@@ -31,13 +63,24 @@ export const compress = (options: CompressOptions = {}): Middleware => {
|
|
|
31
63
|
return new Response(buf, { status: res.status, headers: res.headers });
|
|
32
64
|
}
|
|
33
65
|
|
|
34
|
-
const
|
|
66
|
+
const raw = new Uint8Array(buf);
|
|
67
|
+
let compressed: Uint8Array;
|
|
68
|
+
if (chosen === 'zstd') {
|
|
69
|
+
compressed = (Bun as any).zstdCompressSync(raw);
|
|
70
|
+
} else if (chosen === 'br') {
|
|
71
|
+
compressed = brotliCompressSync(raw, {
|
|
72
|
+
params: { [zlibConstants.BROTLI_PARAM_QUALITY]: Math.min(11, Math.max(1, level)) }
|
|
73
|
+
});
|
|
74
|
+
} else {
|
|
75
|
+
compressed = Bun.gzipSync(raw, { level });
|
|
76
|
+
}
|
|
77
|
+
|
|
35
78
|
const headers = new Headers(res.headers);
|
|
36
|
-
headers.set('Content-Encoding',
|
|
79
|
+
headers.set('Content-Encoding', chosen);
|
|
37
80
|
headers.set('Vary', 'Accept-Encoding');
|
|
38
81
|
headers.delete('Content-Length');
|
|
39
82
|
|
|
40
|
-
return new Response(
|
|
83
|
+
return new Response(compressed, { status: res.status, headers });
|
|
41
84
|
};
|
|
42
85
|
|
|
43
86
|
const mw: Middleware = async (ctx: Context, next?: Next) => {
|