barejs 0.1.54 → 0.1.55
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 +11 -11
- package/dist/index.js +100 -81
- package/dist/types/core/bare.d.ts +3 -1
- package/dist/types/core/context.d.ts +2 -1
- package/dist/types/security/csrf.d.ts +2 -0
- package/llms.txt +2 -2
- package/package.json +1 -1
- package/src/core/bare.ts +60 -23
- package/src/core/context.ts +33 -26
- package/src/security/auth.ts +2 -2
- package/src/security/csrf.ts +32 -8
- package/src/security/hash.ts +1 -0
- package/src/security/idempotency.ts +4 -3
- package/src/security/timeout.ts +3 -1
- package/src/security/validators.ts +59 -20
- package/src/utils/compress.ts +22 -10
- package/src/utils/logger.ts +2 -2
- package/src/utils/static.ts +3 -3
|
@@ -47,7 +47,10 @@ export const typebox = (schema: any): Middleware => {
|
|
|
47
47
|
|
|
48
48
|
if (isCtx) (ctx as any).body = body;
|
|
49
49
|
return next ? next() : undefined;
|
|
50
|
-
} catch {
|
|
50
|
+
} catch (e: any) {
|
|
51
|
+
if (e?.status === 413) {
|
|
52
|
+
return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
|
|
53
|
+
}
|
|
51
54
|
return errorJSON({ status: 'error', message: 'Malformed JSON payload' });
|
|
52
55
|
}
|
|
53
56
|
};
|
|
@@ -64,6 +67,14 @@ export const native = (schema: any): Middleware => {
|
|
|
64
67
|
const kLen = keys.length;
|
|
65
68
|
const reqSet = Array.isArray(schema.required) ? new Set<string>(schema.required) : null;
|
|
66
69
|
|
|
70
|
+
const matchesNativeType = (val: any, expected: string | undefined): boolean => {
|
|
71
|
+
if (expected === 'array') return Array.isArray(val);
|
|
72
|
+
if (expected === 'integer') return typeof val === 'number' && Number.isInteger(val);
|
|
73
|
+
if (expected === 'object') return val !== null && typeof val === 'object' && !Array.isArray(val);
|
|
74
|
+
if (expected === 'null') return val === null;
|
|
75
|
+
return typeof val === expected;
|
|
76
|
+
};
|
|
77
|
+
|
|
67
78
|
const mw: Middleware = async (ctx: any, next?: any) => {
|
|
68
79
|
try {
|
|
69
80
|
const isCtx = ctx instanceof Object && 'req' in ctx;
|
|
@@ -87,7 +98,7 @@ export const native = (schema: any): Middleware => {
|
|
|
87
98
|
}
|
|
88
99
|
continue;
|
|
89
100
|
}
|
|
90
|
-
if (
|
|
101
|
+
if (!matchesNativeType(body[k], props[k]?.type)) {
|
|
91
102
|
return errorJSON({
|
|
92
103
|
status: 'error',
|
|
93
104
|
code: 'TYPE_MISMATCH',
|
|
@@ -100,7 +111,10 @@ export const native = (schema: any): Middleware => {
|
|
|
100
111
|
if (isCtx) (ctx as any).body = body;
|
|
101
112
|
|
|
102
113
|
return next ? next() : undefined;
|
|
103
|
-
} catch {
|
|
114
|
+
} catch (e: any) {
|
|
115
|
+
if (e?.status === 413) {
|
|
116
|
+
return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
|
|
117
|
+
}
|
|
104
118
|
return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
|
|
105
119
|
}
|
|
106
120
|
};
|
|
@@ -130,7 +144,10 @@ export const zod = (schema: z.ZodSchema): Middleware => {
|
|
|
130
144
|
if (isCtx) (ctx as any).body = result.data;
|
|
131
145
|
|
|
132
146
|
return next ? next() : undefined;
|
|
133
|
-
} catch {
|
|
147
|
+
} catch (e: any) {
|
|
148
|
+
if (e?.status === 413) {
|
|
149
|
+
return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
|
|
150
|
+
}
|
|
134
151
|
return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
|
|
135
152
|
}
|
|
136
153
|
};
|
|
@@ -184,29 +201,35 @@ const compileSingleSchema = (schema: any): ((val: any) => { ok: boolean; data?:
|
|
|
184
201
|
};
|
|
185
202
|
};
|
|
186
203
|
|
|
187
|
-
const
|
|
204
|
+
const buildProjectorStatements = (schema: any, srcVar: string, dstVar: string, depth = 0): string | null => {
|
|
188
205
|
const props = schema?.properties;
|
|
189
206
|
if (!props || typeof props !== 'object') return null;
|
|
190
|
-
|
|
207
|
+
let stmts = '';
|
|
208
|
+
let idx = 0;
|
|
191
209
|
for (const [k, subSchema] of Object.entries<any>(props)) {
|
|
192
210
|
if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
|
|
193
211
|
const keyLit = JSON.stringify(k);
|
|
194
|
-
const
|
|
195
|
-
const
|
|
196
|
-
|
|
197
|
-
|
|
212
|
+
const valVar = `v_${depth}_${idx++}`;
|
|
213
|
+
const nestedDst = `d_${depth}_${idx}`;
|
|
214
|
+
const nestedStmts = buildProjectorStatements(subSchema, valVar, nestedDst, depth + 1);
|
|
215
|
+
stmts += `const ${valVar} = ${srcVar}[${keyLit}];\n`;
|
|
216
|
+
if (nestedStmts) {
|
|
217
|
+
stmts += `if (${valVar} !== undefined) {\n`;
|
|
218
|
+
stmts += ` if (${valVar} && typeof ${valVar} === 'object' && !Array.isArray(${valVar})) {\n`;
|
|
219
|
+
stmts += ` const ${nestedDst} = {};\n${nestedStmts} ${dstVar}[${keyLit}] = ${nestedDst};\n`;
|
|
220
|
+
stmts += ` } else {\n ${dstVar}[${keyLit}] = ${valVar};\n }\n}\n`;
|
|
198
221
|
} else {
|
|
199
|
-
|
|
222
|
+
stmts += `if (${valVar} !== undefined) ${dstVar}[${keyLit}] = ${valVar};\n`;
|
|
200
223
|
}
|
|
201
224
|
}
|
|
202
|
-
return
|
|
225
|
+
return stmts;
|
|
203
226
|
};
|
|
204
227
|
|
|
205
228
|
const compileProjector = (schema: any): ((val: any) => any) | null => {
|
|
206
229
|
if (!schema || '_def' in schema) return null; // Zod safeParse strips unknown keys natively
|
|
207
230
|
if (schema.type === 'array' && schema.items) {
|
|
208
|
-
const
|
|
209
|
-
if (!
|
|
231
|
+
const itemStmts = buildProjectorStatements(schema.items, 'item', 'outItem');
|
|
232
|
+
if (!itemStmts) return null;
|
|
210
233
|
return new Function(
|
|
211
234
|
`return function(arr) {
|
|
212
235
|
if (!Array.isArray(arr)) return arr;
|
|
@@ -214,18 +237,26 @@ const compileProjector = (schema: any): ((val: any) => any) | null => {
|
|
|
214
237
|
const out = new Array(len);
|
|
215
238
|
for (let i = 0; i < len; i++) {
|
|
216
239
|
const item = arr[i];
|
|
217
|
-
|
|
240
|
+
if (item && typeof item === 'object' && !Array.isArray(item)) {
|
|
241
|
+
const outItem = {};
|
|
242
|
+
${itemStmts}
|
|
243
|
+
out[i] = outItem;
|
|
244
|
+
} else {
|
|
245
|
+
out[i] = item;
|
|
246
|
+
}
|
|
218
247
|
}
|
|
219
248
|
return out;
|
|
220
249
|
}`
|
|
221
250
|
)();
|
|
222
251
|
}
|
|
223
|
-
const
|
|
224
|
-
if (!
|
|
252
|
+
const objStmts = buildProjectorStatements(schema, 'o', 'out');
|
|
253
|
+
if (!objStmts) return null;
|
|
225
254
|
return new Function(
|
|
226
255
|
`return function(o) {
|
|
227
256
|
if (!o || typeof o !== 'object' || Array.isArray(o)) return o;
|
|
228
|
-
|
|
257
|
+
const out = {};
|
|
258
|
+
${objStmts}
|
|
259
|
+
return out;
|
|
229
260
|
}`
|
|
230
261
|
)();
|
|
231
262
|
};
|
|
@@ -245,6 +276,14 @@ export const createResponseFilter = (schema: any): ((val: any) => any) => {
|
|
|
245
276
|
};
|
|
246
277
|
};
|
|
247
278
|
|
|
279
|
+
const unwrapPropType = (propSchema: any): string | undefined => {
|
|
280
|
+
let cur = propSchema;
|
|
281
|
+
while (cur?._def && (cur._def.typeName === 'ZodOptional' || cur._def.typeName === 'ZodDefault' || cur._def.typeName === 'ZodNullable')) {
|
|
282
|
+
cur = cur._def.innerType;
|
|
283
|
+
}
|
|
284
|
+
return cur?.type || cur?._def?.typeName;
|
|
285
|
+
};
|
|
286
|
+
|
|
248
287
|
const coerceFields = (obj: Record<string, any>, schema: any): Record<string, any> => {
|
|
249
288
|
const props = schema?.properties || (schema?._def?.shape ? (typeof schema._def.shape === 'function' ? schema._def.shape() : schema._def.shape) : null);
|
|
250
289
|
if (!props) return obj;
|
|
@@ -253,11 +292,11 @@ const coerceFields = (obj: Record<string, any>, schema: any): Record<string, any
|
|
|
253
292
|
if (!Object.hasOwn(out, k)) continue;
|
|
254
293
|
const val = out[k];
|
|
255
294
|
if (typeof val !== 'string') continue;
|
|
256
|
-
const tType = propSchema
|
|
295
|
+
const tType = unwrapPropType(propSchema);
|
|
257
296
|
if (tType === 'number' || tType === 'integer' || tType === 'ZodNumber') {
|
|
258
297
|
if (val.trim() !== '') {
|
|
259
298
|
const n = Number(val);
|
|
260
|
-
if (
|
|
299
|
+
if (Number.isFinite(n)) out[k] = n;
|
|
261
300
|
}
|
|
262
301
|
} else if (tType === 'boolean' || tType === 'ZodBoolean') {
|
|
263
302
|
if (val === 'true') out[k] = true;
|
package/src/utils/compress.ts
CHANGED
|
@@ -23,16 +23,23 @@ export const compress = (options: CompressOptions = {}): Middleware => {
|
|
|
23
23
|
const hasZstd = typeof (Bun as any).zstdCompressSync === 'function';
|
|
24
24
|
|
|
25
25
|
const isAccepted = (lower: string, enc: CompressionEncoding): boolean => {
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
if (
|
|
26
|
+
const parts = lower.split(',');
|
|
27
|
+
for (let i = 0; i < parts.length; i++) {
|
|
28
|
+
const part = parts[i]!.trim();
|
|
29
|
+
if (!part) continue;
|
|
30
|
+
const semi = part.indexOf(';');
|
|
31
|
+
const name = (semi === -1 ? part : part.slice(0, semi)).trim();
|
|
32
|
+
if (name !== enc) continue;
|
|
33
|
+
if (semi !== -1) {
|
|
34
|
+
const qMatch = part.slice(semi + 1).match(/q\s*=\s*([0-9.]+)/);
|
|
35
|
+
if (qMatch) {
|
|
36
|
+
const qVal = parseFloat(qMatch[1]!);
|
|
37
|
+
if (Number.isFinite(qVal) && qVal <= 0) return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return true;
|
|
34
41
|
}
|
|
35
|
-
return
|
|
42
|
+
return false;
|
|
36
43
|
};
|
|
37
44
|
|
|
38
45
|
const negotiate = (accept: string): CompressionEncoding | null => {
|
|
@@ -77,7 +84,12 @@ export const compress = (options: CompressOptions = {}): Middleware => {
|
|
|
77
84
|
|
|
78
85
|
const headers = new Headers(res.headers);
|
|
79
86
|
headers.set('Content-Encoding', chosen);
|
|
80
|
-
headers.
|
|
87
|
+
const existingVary = headers.get('Vary');
|
|
88
|
+
if (!existingVary) {
|
|
89
|
+
headers.set('Vary', 'Accept-Encoding');
|
|
90
|
+
} else if (!existingVary.toLowerCase().split(',').some((v) => v.trim() === 'accept-encoding')) {
|
|
91
|
+
headers.set('Vary', `${existingVary}, Accept-Encoding`);
|
|
92
|
+
}
|
|
81
93
|
headers.delete('Content-Length');
|
|
82
94
|
|
|
83
95
|
return new Response(compressed, { status: res.status, headers });
|
package/src/utils/logger.ts
CHANGED
|
@@ -37,7 +37,7 @@ export const logger = (options: LoggerOptions = {}): Middleware => {
|
|
|
37
37
|
|
|
38
38
|
return (ctx: Context, next) => {
|
|
39
39
|
const path = getPath(ctx.req.url);
|
|
40
|
-
if (skip?.(ctx, path)) return next();
|
|
40
|
+
if (skip?.(ctx, path)) return next?.();
|
|
41
41
|
|
|
42
42
|
const reqId = attachId ? ctx.requestId : undefined;
|
|
43
43
|
if (reqId) {
|
|
@@ -61,6 +61,6 @@ export const logger = (options: LoggerOptions = {}): Middleware => {
|
|
|
61
61
|
console.log(`[${entry.timestamp}] ${entry.method} ${entry.path}${idPart}`);
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
-
return next();
|
|
64
|
+
return next?.();
|
|
65
65
|
};
|
|
66
66
|
};
|
package/src/utils/static.ts
CHANGED
|
@@ -38,7 +38,7 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
|
|
|
38
38
|
|
|
39
39
|
const mw = async (ctx: any, next: any) => {
|
|
40
40
|
const method = ctx.req.method;
|
|
41
|
-
if (method !== 'GET' && method !== 'HEAD') return next();
|
|
41
|
+
if (method !== 'GET' && method !== 'HEAD') return next?.();
|
|
42
42
|
|
|
43
43
|
const rawUrl: string = ctx.req.url;
|
|
44
44
|
const pathStart = rawUrl.indexOf('/', 8);
|
|
@@ -90,7 +90,7 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
|
|
|
90
90
|
return ctx.status(403).send('Forbidden');
|
|
91
91
|
}
|
|
92
92
|
const st = await stat(resolvedFile);
|
|
93
|
-
if (st.isDirectory()) return next();
|
|
93
|
+
if (st.isDirectory()) return next?.();
|
|
94
94
|
realFile = resolvedFile;
|
|
95
95
|
fileSize = st.size;
|
|
96
96
|
mtimeMs = Math.floor(st.mtimeMs);
|
|
@@ -110,7 +110,7 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
|
|
|
110
110
|
});
|
|
111
111
|
}
|
|
112
112
|
} catch {
|
|
113
|
-
return next();
|
|
113
|
+
return next?.();
|
|
114
114
|
}
|
|
115
115
|
}
|
|
116
116
|
|