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
|
@@ -92,7 +92,9 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
|
|
|
92
92
|
onError(handler: (err: any, ctx: Context) => any): this;
|
|
93
93
|
ws(path: string, handler: WebSocketRouteHandler): this;
|
|
94
94
|
docs(path?: string, options?: OpenAPIOptions): this;
|
|
95
|
-
rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any
|
|
95
|
+
rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>, options?: {
|
|
96
|
+
maxBatchSize?: number;
|
|
97
|
+
}): this;
|
|
96
98
|
get: AddRoute<Derived, Routes, 'GET'>;
|
|
97
99
|
post: AddRoute<Derived, Routes, 'POST'>;
|
|
98
100
|
put: AddRoute<Derived, Routes, 'PUT'>;
|
|
@@ -47,13 +47,14 @@ export declare class Context {
|
|
|
47
47
|
_requestId: string | undefined;
|
|
48
48
|
_peerIp: string | undefined;
|
|
49
49
|
_trustProxy: boolean;
|
|
50
|
+
_detached: boolean;
|
|
50
51
|
constructor(trustProxy?: boolean);
|
|
51
52
|
get query(): Record<string, string>;
|
|
52
53
|
getQuery(key: string): string | undefined;
|
|
53
54
|
get cookies(): Record<string, string>;
|
|
54
55
|
setCookie(name: string, value: string, options?: CookieOptions): this;
|
|
55
56
|
getSignedCookie(name: string, secret: string): string | null;
|
|
56
|
-
deleteCookie(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): this;
|
|
57
|
+
deleteCookie(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure' | 'sameSite'>): this;
|
|
57
58
|
jsonBody(maxBytes?: number): Promise<any>;
|
|
58
59
|
reset(req: Request): this;
|
|
59
60
|
status(code: number): this;
|
|
@@ -8,5 +8,7 @@ export interface CsrfOptions {
|
|
|
8
8
|
cookieName?: string;
|
|
9
9
|
headerName?: string;
|
|
10
10
|
requireToken?: boolean;
|
|
11
|
+
/** Allow requests that omit both Origin and Referer headers (default: false) */
|
|
12
|
+
allowMissingOrigin?: boolean;
|
|
11
13
|
}
|
|
12
14
|
export declare const csrf: (options?: CsrfOptions) => Middleware;
|
package/llms.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# BareJS (`barejs`) — AI Quick Reference (`llms.txt`)
|
|
2
2
|
|
|
3
|
-
> BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1`) with built-in security (Argon2id, HS256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip `compress`, `app.cron`, Security Headers, DoS limits) and **100% Function & Line Test Coverage (
|
|
3
|
+
> BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1`) with built-in security (Argon2id, HS256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip `compress`, `app.cron`, Security Headers, DoS limits) and **100% Function & Line Test Coverage (316 tests / 5,833 assertions)**.
|
|
4
4
|
|
|
5
5
|
## 1. Installation & Minimal App
|
|
6
6
|
```ts
|
|
@@ -61,7 +61,7 @@ const typedApp = app.route('/api/v1', api); // or app.use('/api/v1', api)
|
|
|
61
61
|
- `await ctx.getSignedCookie(name, secret)`: Verifies HMAC signature with `timingSafeEqual`; returns `null` if tampered or missing.
|
|
62
62
|
- `ctx.deleteCookie(name, opts?)`: Expires cookie immediately (`Max-Age=0`).
|
|
63
63
|
- `ctx.requestId`: Lazy `x-request-id` header or generated `crypto.randomUUID()`.
|
|
64
|
-
- `ctx.ip`: Client IP
|
|
64
|
+
- `ctx.ip`: Client IP from `x-forwarded-for` (first non-empty), `x-real-ip`, `cf-connecting-ip` (only when `trustProxy` is enabled), else peer IP or `'127.0.0.1'`.
|
|
65
65
|
- `ctx.user`: Authenticated user payload populated by `bareAuth` or `basicAuth`.
|
|
66
66
|
- `ctx.store` / `ctx.set(k, v)` / `ctx.get(k)`: Per-request `Map<string, any>` (automatically cleared on pool release).
|
|
67
67
|
- **Response Helpers (Hono / Express style):**
|
package/package.json
CHANGED
package/src/core/bare.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { Type as typebox, Type as t } from '@sinclair/typebox';
|
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { readFileSync } from "node:fs";
|
|
7
7
|
import { bootstrapConfig } from "./loader";
|
|
8
|
+
import { BARE_CONFIG } from "./config";
|
|
8
9
|
import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../utils/openapi";
|
|
9
10
|
import type { RouteSchemas } from "../security/validators";
|
|
10
11
|
import type { RouteSchema } from "../client/index";
|
|
@@ -69,7 +70,7 @@ export class BareJS<
|
|
|
69
70
|
private compiled = false;
|
|
70
71
|
private poolMask: number;
|
|
71
72
|
private _useLog: boolean = false;
|
|
72
|
-
private _trustProxy: boolean =
|
|
73
|
+
private _trustProxy: boolean = false;
|
|
73
74
|
private errorHandler?: (err: any, ctx: Context) => any;
|
|
74
75
|
private wsRoutes = new Map<string, WebSocketRouteHandler>();
|
|
75
76
|
private startHooks: (() => void | Promise<void>)[] = [];
|
|
@@ -215,7 +216,14 @@ export class BareJS<
|
|
|
215
216
|
return this;
|
|
216
217
|
}
|
|
217
218
|
|
|
218
|
-
public rpc(
|
|
219
|
+
public rpc(
|
|
220
|
+
path: string,
|
|
221
|
+
procedures: Record<string, (params: any, ctx: Context) => any>,
|
|
222
|
+
options: { maxBatchSize?: number } = {}
|
|
223
|
+
): this {
|
|
224
|
+
const maxBatchSize = options.maxBatchSize ?? 100;
|
|
225
|
+
const isProd = process.env.NODE_ENV === 'production';
|
|
226
|
+
|
|
219
227
|
const execCall = async (reqObj: any, ctx: Context) => {
|
|
220
228
|
if (!reqObj || reqObj.jsonrpc !== '2.0' || typeof reqObj.method !== 'string') {
|
|
221
229
|
return { jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: reqObj?.id ?? null };
|
|
@@ -229,9 +237,12 @@ export class BareJS<
|
|
|
229
237
|
if (reqObj.id === undefined) return null; // Notification
|
|
230
238
|
return { jsonrpc: '2.0', result, id: reqObj.id };
|
|
231
239
|
} catch (err: any) {
|
|
240
|
+
const msg = !isProd || err?.expose || (err?.status >= 400 && err?.status < 500)
|
|
241
|
+
? (err?.message || 'Internal error')
|
|
242
|
+
: 'Internal error';
|
|
232
243
|
return {
|
|
233
244
|
jsonrpc: '2.0',
|
|
234
|
-
error: { code: -32603, message:
|
|
245
|
+
error: { code: -32603, message: msg },
|
|
235
246
|
id: reqObj.id ?? null
|
|
236
247
|
};
|
|
237
248
|
}
|
|
@@ -243,7 +254,7 @@ export class BareJS<
|
|
|
243
254
|
return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32700, message: 'Parse error' }, id: null });
|
|
244
255
|
}
|
|
245
256
|
if (Array.isArray(payload)) {
|
|
246
|
-
if (payload.length === 0) {
|
|
257
|
+
if (payload.length === 0 || payload.length > maxBatchSize) {
|
|
247
258
|
return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: null });
|
|
248
259
|
}
|
|
249
260
|
const results = (await Promise.all(payload.map((item) => execCall(item, ctx)))).filter(Boolean);
|
|
@@ -301,6 +312,28 @@ export class BareJS<
|
|
|
301
312
|
// inherited use() from BareRouter handles router merging now
|
|
302
313
|
|
|
303
314
|
private compileHandler(pipeline: any[], isLog: boolean): Function {
|
|
315
|
+
if (pipeline.length === 0) {
|
|
316
|
+
return () => undefined;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const applyCtxHeadersToRes = (res: Response, ctx: Context): Response => {
|
|
320
|
+
if (ctx._headers) {
|
|
321
|
+
for (const k in ctx._headers) {
|
|
322
|
+
const val = ctx._headers[k];
|
|
323
|
+
if (val !== undefined && !res.headers.has(k)) {
|
|
324
|
+
try { res.headers.set(k, val); } catch { /* ignore invalid header */ }
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (ctx._setCookies) {
|
|
329
|
+
for (let i = 0; i < ctx._setCookies.length; i++) {
|
|
330
|
+
try { res.headers.append('Set-Cookie', ctx._setCookies[i]!); } catch { /* ignore */ }
|
|
331
|
+
}
|
|
332
|
+
ctx._setCookies = undefined;
|
|
333
|
+
}
|
|
334
|
+
return res;
|
|
335
|
+
};
|
|
336
|
+
|
|
304
337
|
const timeoutMw = pipeline.find((fn) => fn?.__timeout);
|
|
305
338
|
if (timeoutMw) {
|
|
306
339
|
const { ms, status, message } = timeoutMw.__timeout;
|
|
@@ -313,7 +346,9 @@ export class BareJS<
|
|
|
313
346
|
try {
|
|
314
347
|
const timeoutPromise = new Promise<Response>((resolve) => {
|
|
315
348
|
timer = setTimeout(() => {
|
|
316
|
-
|
|
349
|
+
ctx._detached = true;
|
|
350
|
+
if (typeof res.catch === 'function') res.catch(() => {});
|
|
351
|
+
resolve(applyCtxHeadersToRes(Response.json({ status: 'error', code: 'REQUEST_TIMEOUT', message }, { status }), ctx));
|
|
317
352
|
}, ms);
|
|
318
353
|
});
|
|
319
354
|
return await Promise.race([res, timeoutPromise]);
|
|
@@ -410,11 +445,13 @@ export class BareJS<
|
|
|
410
445
|
const argSig = isLog ? 'ctx, doLog' : 'ctx';
|
|
411
446
|
|
|
412
447
|
const extraNames = [
|
|
448
|
+
'applyShortCircuit',
|
|
413
449
|
...(rFilter ? ['rFilter'] : []),
|
|
414
450
|
...(idemCommit ? ['idemCommit'] : []),
|
|
415
451
|
...(idemRelease ? ['idemRelease'] : [])
|
|
416
452
|
];
|
|
417
453
|
const extraVals = [
|
|
454
|
+
applyCtxHeadersToRes,
|
|
418
455
|
...(rFilter ? [rFilter] : []),
|
|
419
456
|
...(idemCommit ? [idemCommit] : []),
|
|
420
457
|
...(idemRelease ? [idemRelease] : [])
|
|
@@ -473,7 +510,7 @@ export class BareJS<
|
|
|
473
510
|
code += `let r${i} = fn${i}(ctx, noop);\n`;
|
|
474
511
|
code += `if (r${i}) {\n`;
|
|
475
512
|
code += ` if (r${i}.then) r${i} = await r${i};\n`;
|
|
476
|
-
code += ` if (r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
|
|
513
|
+
code += ` if (r${i} instanceof Response) { applyShortCircuit(r${i}, ctx); ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
|
|
477
514
|
code += `}\n`;
|
|
478
515
|
}
|
|
479
516
|
code += `
|
|
@@ -484,7 +521,7 @@ export class BareJS<
|
|
|
484
521
|
} else {
|
|
485
522
|
for (let i = 0; i < len - 1; i++) {
|
|
486
523
|
code += `const r${i} = fn${i}(ctx, noop);\n`;
|
|
487
|
-
code += `if (r${i} && r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
|
|
524
|
+
code += `if (r${i} && r${i} instanceof Response) { applyShortCircuit(r${i}, ctx); ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
|
|
488
525
|
}
|
|
489
526
|
code += `
|
|
490
527
|
let res = fn${len - 1}(ctx);
|
|
@@ -580,20 +617,22 @@ export class BareJS<
|
|
|
580
617
|
: '';
|
|
581
618
|
|
|
582
619
|
const releaseCode = `
|
|
583
|
-
if (ctx.
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
620
|
+
if (!ctx._detached) {
|
|
621
|
+
if (ctx.store.size > 0) ctx.store.clear();
|
|
622
|
+
${deriveCleanup}
|
|
623
|
+
${idemCleanup}
|
|
624
|
+
ctx.req = undefined;
|
|
625
|
+
ctx._status = 200;
|
|
626
|
+
ctx.body = undefined;
|
|
627
|
+
ctx._query = undefined;
|
|
628
|
+
ctx._cookies = undefined;
|
|
629
|
+
ctx._setCookies = undefined;
|
|
630
|
+
ctx._headers = undefined;
|
|
631
|
+
ctx._requestId = undefined;
|
|
632
|
+
ctx._peerIp = undefined;
|
|
633
|
+
ctx.params = EMPTY_PARAMS;
|
|
634
|
+
if (poolTop < maxPool) pool[poolTop++] = ctx;
|
|
635
|
+
}
|
|
597
636
|
`;
|
|
598
637
|
|
|
599
638
|
const handleErrCode = `const errRes = hError(e, ctx);
|
|
@@ -759,8 +798,6 @@ export class BareJS<
|
|
|
759
798
|
}
|
|
760
799
|
const maxRequestBodySize = options.maxRequestBodySize ?? 10 * 1024 * 1024;
|
|
761
800
|
|
|
762
|
-
const { BARE_CONFIG } = require("./config");
|
|
763
|
-
|
|
764
801
|
const finalPort = port || BARE_CONFIG.port || 3000;
|
|
765
802
|
const isProd = process.env.NODE_ENV === 'production';
|
|
766
803
|
|
package/src/core/context.ts
CHANGED
|
@@ -53,8 +53,9 @@ export class Context {
|
|
|
53
53
|
public _setCookies: string[] | undefined = undefined;
|
|
54
54
|
public _requestId: string | undefined = undefined;
|
|
55
55
|
public _peerIp: string | undefined = undefined;
|
|
56
|
-
public _trustProxy: boolean =
|
|
57
|
-
|
|
56
|
+
public _trustProxy: boolean = false;
|
|
57
|
+
public _detached: boolean = false;
|
|
58
|
+
constructor(trustProxy: boolean = false) {
|
|
58
59
|
this._trustProxy = trustProxy;
|
|
59
60
|
}
|
|
60
61
|
|
|
@@ -185,7 +186,7 @@ export class Context {
|
|
|
185
186
|
return value;
|
|
186
187
|
}
|
|
187
188
|
|
|
188
|
-
public deleteCookie(name: string, options: Pick<CookieOptions, 'path' | 'domain'> = {}): this {
|
|
189
|
+
public deleteCookie(name: string, options: Pick<CookieOptions, 'path' | 'domain' | 'secure' | 'sameSite'> = {}): this {
|
|
189
190
|
return this.setCookie(name, '', {
|
|
190
191
|
...options,
|
|
191
192
|
maxAge: 0,
|
|
@@ -197,22 +198,15 @@ export class Context {
|
|
|
197
198
|
if (this.body !== undefined) return this.body;
|
|
198
199
|
|
|
199
200
|
const contentType = this.req.headers.get("content-type");
|
|
200
|
-
if (contentType && contentType.includes("application/json")) {
|
|
201
|
+
if (contentType && contentType.toLowerCase().includes("application/json")) {
|
|
201
202
|
const lenHeader = this.req.headers.get("content-length");
|
|
202
203
|
if (lenHeader !== null) {
|
|
203
204
|
const trimmed = lenHeader.trim();
|
|
204
205
|
const lenNum = trimmed.length > 0 ? Number(trimmed) : NaN;
|
|
205
|
-
if (Number.isInteger(lenNum) && lenNum
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
throw err;
|
|
210
|
-
}
|
|
211
|
-
try {
|
|
212
|
-
return this.body = await this.req.json();
|
|
213
|
-
} catch {
|
|
214
|
-
return this.body = null;
|
|
215
|
-
}
|
|
206
|
+
if (Number.isInteger(lenNum) && lenNum > maxBytes) {
|
|
207
|
+
const err: any = new Error("Payload Too Large");
|
|
208
|
+
err.status = 413;
|
|
209
|
+
throw err;
|
|
216
210
|
}
|
|
217
211
|
}
|
|
218
212
|
try {
|
|
@@ -347,16 +341,18 @@ export class Context {
|
|
|
347
341
|
| ((send: (data: any, event?: string, id?: string) => void, close: () => void) => Promise<void> | void)
|
|
348
342
|
): Response {
|
|
349
343
|
const encoder = new TextEncoder();
|
|
344
|
+
const formatDataLines = (raw: string): string =>
|
|
345
|
+
raw.split(/\r?\n/).map((line) => `data: ${line}`).join('\n') + '\n\n';
|
|
350
346
|
const formatChunk = (chunk: string | { event?: string; data: any; id?: string; retry?: number }): Uint8Array => {
|
|
351
347
|
if (typeof chunk === 'string') {
|
|
352
|
-
return encoder.encode(
|
|
348
|
+
return encoder.encode(formatDataLines(chunk));
|
|
353
349
|
}
|
|
354
350
|
let out = '';
|
|
355
|
-
if (chunk.id !== undefined) out += `id: ${chunk.id}\n`;
|
|
356
|
-
if (chunk.event !== undefined) out += `event: ${chunk.event}\n`;
|
|
357
|
-
if (chunk.retry !== undefined) out += `retry: ${chunk.retry}\n`;
|
|
351
|
+
if (chunk.id !== undefined) out += `id: ${String(chunk.id).replace(/[\r\n]/g, '')}\n`;
|
|
352
|
+
if (chunk.event !== undefined) out += `event: ${String(chunk.event).replace(/[\r\n]/g, '')}\n`;
|
|
353
|
+
if (chunk.retry !== undefined && Number.isFinite(chunk.retry)) out += `retry: ${Math.max(0, Math.floor(chunk.retry))}\n`;
|
|
358
354
|
const payload = typeof chunk.data === 'string' ? chunk.data : JSON.stringify(chunk.data);
|
|
359
|
-
out +=
|
|
355
|
+
out += formatDataLines(payload);
|
|
360
356
|
return encoder.encode(out);
|
|
361
357
|
};
|
|
362
358
|
|
|
@@ -407,10 +403,13 @@ export class Context {
|
|
|
407
403
|
public get ip(): string {
|
|
408
404
|
if (this._trustProxy) {
|
|
409
405
|
const xff = this.req?.headers?.get('x-forwarded-for');
|
|
410
|
-
if (xff)
|
|
406
|
+
if (xff) {
|
|
407
|
+
const first = xff.split(',')[0]?.trim();
|
|
408
|
+
if (first) return first;
|
|
409
|
+
}
|
|
411
410
|
const forwarded =
|
|
412
|
-
this.req?.headers?.get('x-real-ip') ||
|
|
413
|
-
this.req?.headers?.get('cf-connecting-ip');
|
|
411
|
+
this.req?.headers?.get('x-real-ip')?.trim() ||
|
|
412
|
+
this.req?.headers?.get('cf-connecting-ip')?.trim();
|
|
414
413
|
if (forwarded) return forwarded;
|
|
415
414
|
}
|
|
416
415
|
return this._peerIp || '127.0.0.1';
|
|
@@ -419,21 +418,25 @@ export class Context {
|
|
|
419
418
|
public async upload(options: UploadOptions = {}): Promise<UploadResult> {
|
|
420
419
|
const maxFileSize = options.maxFileSize ?? 5 * 1024 * 1024;
|
|
421
420
|
const maxFiles = options.maxFiles ?? 10;
|
|
422
|
-
const allowed = options.allowedTypes
|
|
421
|
+
const allowed = options.allowedTypes
|
|
422
|
+
? new Set(options.allowedTypes.map((t) => t.trim().toLowerCase()))
|
|
423
|
+
: null;
|
|
423
424
|
|
|
424
|
-
const ct = this.req?.headers?.get('content-type') || '';
|
|
425
|
+
const ct = (this.req?.headers?.get('content-type') || '').toLowerCase();
|
|
425
426
|
if (!ct.includes('multipart/form-data')) {
|
|
426
427
|
throw Object.assign(new Error('Expected multipart/form-data'), { status: 400 });
|
|
427
428
|
}
|
|
428
429
|
|
|
430
|
+
const maxTotalBytes = maxFileSize * maxFiles;
|
|
429
431
|
const contentLen = Number(this.req?.headers?.get('content-length') || 0);
|
|
430
|
-
if (contentLen
|
|
432
|
+
if (Number.isFinite(contentLen) && contentLen > maxTotalBytes + 65536) {
|
|
431
433
|
throw Object.assign(new Error('Payload Too Large'), { status: 413 });
|
|
432
434
|
}
|
|
433
435
|
|
|
434
436
|
const form = await this.req.formData();
|
|
435
437
|
const fields: Record<string, string> = {};
|
|
436
438
|
const files: UploadedFile[] = [];
|
|
439
|
+
let totalBytes = 0;
|
|
437
440
|
|
|
438
441
|
for (const [fieldName, value] of form.entries()) {
|
|
439
442
|
if (typeof value === 'string') {
|
|
@@ -450,6 +453,10 @@ export class Context {
|
|
|
450
453
|
if (fileObj.size > maxFileSize) {
|
|
451
454
|
throw Object.assign(new Error(`File exceeds max size of ${maxFileSize} bytes`), { status: 413 });
|
|
452
455
|
}
|
|
456
|
+
totalBytes += fileObj.size;
|
|
457
|
+
if (totalBytes > maxTotalBytes) {
|
|
458
|
+
throw Object.assign(new Error(`Total upload size exceeds ${maxTotalBytes} bytes`), { status: 413 });
|
|
459
|
+
}
|
|
453
460
|
const mime = (fileObj.type || '').split(';')[0]!.trim().toLowerCase();
|
|
454
461
|
if (allowed && !allowed.has(mime)) {
|
|
455
462
|
throw Object.assign(new Error(`Unsupported file type: ${fileObj.type || 'unknown'}`), { status: 415 });
|
package/src/security/auth.ts
CHANGED
|
@@ -443,7 +443,7 @@ export const basicAuth = (credentials: { user: string; pass: string }) => {
|
|
|
443
443
|
const passMatch = timingSafeEqual(sha256(pass), expectedPassHash);
|
|
444
444
|
|
|
445
445
|
if (userMatch && passMatch) {
|
|
446
|
-
return next();
|
|
446
|
+
return next?.();
|
|
447
447
|
}
|
|
448
448
|
|
|
449
449
|
return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
|
|
@@ -460,6 +460,6 @@ export const hasRole = (role: string) => {
|
|
|
460
460
|
if (!user || user.role !== role) {
|
|
461
461
|
return ctx.status(403).json({ status: 'error', message: `Required role: ${role}` });
|
|
462
462
|
}
|
|
463
|
-
return next();
|
|
463
|
+
return next?.();
|
|
464
464
|
};
|
|
465
465
|
};
|
package/src/security/csrf.ts
CHANGED
|
@@ -10,20 +10,44 @@ export interface CsrfOptions {
|
|
|
10
10
|
cookieName?: string;
|
|
11
11
|
headerName?: string;
|
|
12
12
|
requireToken?: boolean;
|
|
13
|
+
/** Allow requests that omit both Origin and Referer headers (default: false) */
|
|
14
|
+
allowMissingOrigin?: boolean;
|
|
13
15
|
}
|
|
14
16
|
|
|
15
17
|
const DEFAULT_IGNORE = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
16
18
|
|
|
19
|
+
const resolveRequestOrigin = (ctx: Context): string => {
|
|
20
|
+
try {
|
|
21
|
+
const parsed = new URL(ctx.req.url);
|
|
22
|
+
if (ctx._trustProxy) {
|
|
23
|
+
const fwdHost = ctx.req.headers.get('x-forwarded-host')?.split(',')[0]?.trim();
|
|
24
|
+
const fwdProto = ctx.req.headers.get('x-forwarded-proto')?.split(',')[0]?.trim();
|
|
25
|
+
if (fwdHost) {
|
|
26
|
+
const proto = fwdProto ? `${fwdProto}:` : parsed.protocol;
|
|
27
|
+
return `${proto}//${fwdHost}`;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const host = ctx.req.headers.get('host')?.trim();
|
|
31
|
+
if (host) {
|
|
32
|
+
return `${parsed.protocol}//${host}`;
|
|
33
|
+
}
|
|
34
|
+
return parsed.origin;
|
|
35
|
+
} catch {
|
|
36
|
+
return '';
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
|
|
17
40
|
export const csrf = (options: CsrfOptions = {}): Middleware => {
|
|
18
41
|
const ignore = options.ignoreMethods ? new Set(options.ignoreMethods.map((m) => m.toUpperCase())) : DEFAULT_IGNORE;
|
|
19
42
|
const allowed = options.allowedOrigins ? new Set(options.allowedOrigins) : null;
|
|
20
43
|
const cookieName = options.cookieName || 'csrf_token';
|
|
21
44
|
const headerName = (options.headerName || 'x-csrf-token').toLowerCase();
|
|
22
45
|
const requireToken = options.requireToken === true;
|
|
46
|
+
const allowMissingOrigin = options.allowMissingOrigin === true;
|
|
23
47
|
|
|
24
48
|
return (ctx: Context, next: Next) => {
|
|
25
49
|
const method = ctx.req.method.toUpperCase();
|
|
26
|
-
if (ignore.has(method)) return next();
|
|
50
|
+
if (ignore.has(method)) return next?.();
|
|
27
51
|
|
|
28
52
|
const secFetchSite = ctx.req.headers.get('sec-fetch-site');
|
|
29
53
|
const origin = ctx.req.headers.get('origin');
|
|
@@ -53,19 +77,19 @@ export const csrf = (options: CsrfOptions = {}): Middleware => {
|
|
|
53
77
|
}
|
|
54
78
|
|
|
55
79
|
if (sourceOrigin) {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
reqOrigin = new URL(ctx.req.url).origin;
|
|
59
|
-
} catch {
|
|
60
|
-
reqOrigin = '';
|
|
61
|
-
}
|
|
62
|
-
const isAllowed = sourceOrigin === reqOrigin || (allowed !== null && allowed.has(sourceOrigin));
|
|
80
|
+
const reqOrigin = resolveRequestOrigin(ctx);
|
|
81
|
+
const isAllowed = (reqOrigin !== '' && sourceOrigin === reqOrigin) || (allowed !== null && allowed.has(sourceOrigin));
|
|
63
82
|
if (!isAllowed) {
|
|
64
83
|
return Response.json(
|
|
65
84
|
{ status: 'error', code: 'CSRF_FORBIDDEN', message: 'Origin mismatch' },
|
|
66
85
|
{ status: 403 }
|
|
67
86
|
);
|
|
68
87
|
}
|
|
88
|
+
} else if (!allowMissingOrigin && secFetchSite !== 'same-origin') {
|
|
89
|
+
return Response.json(
|
|
90
|
+
{ status: 'error', code: 'CSRF_FORBIDDEN', message: 'Missing Origin or Referer header' },
|
|
91
|
+
{ status: 403 }
|
|
92
|
+
);
|
|
69
93
|
}
|
|
70
94
|
|
|
71
95
|
// 3. Optional double-submit token check
|
package/src/security/hash.ts
CHANGED
|
@@ -15,6 +15,7 @@ export const Hash = {
|
|
|
15
15
|
},
|
|
16
16
|
|
|
17
17
|
needsRehash: (hash: string): boolean => {
|
|
18
|
+
if (!hash || typeof hash !== 'string') return true;
|
|
18
19
|
const { algorithm, memoryCost, timeCost } = BARE_CONFIG.hash;
|
|
19
20
|
if (algorithm === 'bcrypt') {
|
|
20
21
|
if (!/^\$2[aby]\$/.test(hash)) return true;
|
|
@@ -29,7 +29,7 @@ const buildReplayResponse = (existing: CachedIdempotentEntry): Response => {
|
|
|
29
29
|
};
|
|
30
30
|
|
|
31
31
|
const extractIdemKey = (ctx: Context, headerName: string): string | undefined => {
|
|
32
|
-
const rawKey = ctx.req.headers.get(headerName);
|
|
32
|
+
const rawKey = ctx.req.headers.get(headerName)?.trim();
|
|
33
33
|
if (!rawKey) return undefined;
|
|
34
34
|
const rawUrl = ctx.req.url;
|
|
35
35
|
const s = rawUrl.indexOf('/', 8);
|
|
@@ -82,11 +82,12 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
|
|
|
82
82
|
if (!key) return;
|
|
83
83
|
(ctx as any)._idempotencyKey = undefined;
|
|
84
84
|
(ctx as any)._idemInFlight = undefined;
|
|
85
|
-
const
|
|
85
|
+
const isStream = resVal instanceof Response && (resVal.headers.get('content-type') || '').includes('text/event-stream');
|
|
86
|
+
const clonedRes = !isStream && status >= 200 && status < 300 && resVal instanceof Response ? resVal.clone() : null;
|
|
86
87
|
const ct = clonedRes ? (clonedRes.headers.get('content-type') || 'application/json') : undefined;
|
|
87
88
|
void (async () => {
|
|
88
89
|
try {
|
|
89
|
-
if (status >= 200 && status < 300) {
|
|
90
|
+
if (!isStream && status >= 200 && status < 300) {
|
|
90
91
|
if (clonedRes) {
|
|
91
92
|
const buf = await clonedRes.arrayBuffer();
|
|
92
93
|
await externalStore.set(key, { status, rawBody: buf, contentType: ct, expiresAt: Date.now() + ttlMs }, ttlMs);
|
package/src/security/timeout.ts
CHANGED
|
@@ -12,8 +12,10 @@ export const timeout = (ms = 10000, options: TimeoutOptions = {}): Middleware =>
|
|
|
12
12
|
const mw: Middleware = async (_ctx: Context, next: Next) => {
|
|
13
13
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
14
14
|
try {
|
|
15
|
+
const nextPromise = Promise.resolve(next());
|
|
15
16
|
const timeoutPromise = new Promise<Response>((resolve) => {
|
|
16
17
|
timer = setTimeout(() => {
|
|
18
|
+
nextPromise.catch(() => {});
|
|
17
19
|
resolve(
|
|
18
20
|
Response.json(
|
|
19
21
|
{ status: 'error', code: 'REQUEST_TIMEOUT', message },
|
|
@@ -22,7 +24,7 @@ export const timeout = (ms = 10000, options: TimeoutOptions = {}): Middleware =>
|
|
|
22
24
|
);
|
|
23
25
|
}, ms);
|
|
24
26
|
});
|
|
25
|
-
return await Promise.race([
|
|
27
|
+
return await Promise.race([nextPromise, timeoutPromise]);
|
|
26
28
|
} finally {
|
|
27
29
|
if (timer !== undefined) clearTimeout(timer);
|
|
28
30
|
}
|