barejs 0.2.4 → 0.2.6
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 +80 -33
- package/dist/edge.js +70 -0
- package/dist/index.js +200 -189
- package/dist/node.js +200 -189
- package/dist/types/client/index.d.ts +100 -0
- package/dist/types/core/bare.d.ts +68 -25
- package/dist/types/core/context.d.ts +1 -0
- package/dist/types/core/router.d.ts +27 -2
- package/dist/types/core/ws-match.d.ts +34 -2
- package/dist/types/edge.d.ts +99 -0
- package/dist/types/index.d.ts +6 -5
- package/dist/types/runtime/types.d.ts +15 -0
- package/dist/types/security/validators.d.ts +46 -1
- package/dist/types/utils/tracing.d.ts +25 -0
- package/llms.txt +13 -6
- package/package.json +7 -3
- package/src/client/index.ts +399 -6
- package/src/core/bare.ts +366 -46
- package/src/core/context.ts +10 -3
- package/src/core/radix.ts +54 -31
- package/src/core/router.ts +37 -4
- package/src/core/ws-match.ts +17 -2
- package/src/edge.ts +494 -0
- package/src/index.ts +16 -5
- package/src/runtime/bun.ts +39 -7
- package/src/runtime/node.ts +37 -4
- package/src/runtime/types.ts +16 -0
- package/src/runtime/uws.ts +60 -12
- package/src/security/auth.ts +7 -5
- package/src/security/validators.ts +240 -38
- package/src/utils/openapi.ts +39 -9
- package/src/utils/tracing.ts +86 -0
package/src/runtime/bun.ts
CHANGED
|
@@ -11,6 +11,16 @@ export const bunDriver: RuntimeDriver = {
|
|
|
11
11
|
serve(opts: ServeOptions): ServerHandle {
|
|
12
12
|
const wsCfg = opts.ws;
|
|
13
13
|
const routes = opts.routes;
|
|
14
|
+
const toBunPem = (v?: string | Uint8Array) =>
|
|
15
|
+
typeof v === 'string' && !v.includes('-----BEGIN') ? Bun.file(v) : v;
|
|
16
|
+
const tls = opts.tls
|
|
17
|
+
? {
|
|
18
|
+
key: toBunPem(opts.tls.keyFileName ?? opts.tls.key),
|
|
19
|
+
cert: toBunPem(opts.tls.certFileName ?? opts.tls.cert),
|
|
20
|
+
...(opts.tls.passphrase ? { passphrase: opts.tls.passphrase } : {}),
|
|
21
|
+
...(opts.tls.ca ? { ca: toBunPem(opts.tls.ca) } : {})
|
|
22
|
+
}
|
|
23
|
+
: undefined;
|
|
14
24
|
let server: any;
|
|
15
25
|
try {
|
|
16
26
|
server = wsCfg
|
|
@@ -20,16 +30,37 @@ export const bunDriver: RuntimeDriver = {
|
|
|
20
30
|
reusePort: opts.reusePort,
|
|
21
31
|
maxRequestBodySize: opts.maxRequestBodySize,
|
|
22
32
|
...(routes ? { routes } : {}),
|
|
33
|
+
...(tls ? { tls } : {}),
|
|
23
34
|
fetch(req: Request, srv: any) {
|
|
24
35
|
if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
|
25
36
|
const matched = matchWsRoute(wsCfg.routes, req.url);
|
|
26
|
-
if (
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
37
|
+
if (matched) {
|
|
38
|
+
const doUpgrade = (extra?: { query?: any; headers?: any }) => {
|
|
39
|
+
const data =
|
|
40
|
+
matched.params || extra
|
|
41
|
+
? { ...matched.handler, ...(matched.params ? { params: matched.params } : {}), ...(extra || {}) }
|
|
42
|
+
: matched.handler;
|
|
43
|
+
return srv.upgrade(req, { data }) ? (undefined as any) : new Response('Upgrade failed', { status: 400 });
|
|
44
|
+
};
|
|
45
|
+
const validate = matched.handler.__validateUpgrade;
|
|
46
|
+
if (validate) {
|
|
47
|
+
const vr = validate(req);
|
|
48
|
+
if (vr && typeof (vr as any).then === 'function') {
|
|
49
|
+
return (vr as Promise<any>).then((r) =>
|
|
50
|
+
r?.ok
|
|
51
|
+
? doUpgrade({ query: r.query, headers: r.headers })
|
|
52
|
+
: Response.json({ status: 'error', code: r?.code || 'WS_UPGRADE_INVALID', error: r?.error }, { status: 400 })
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
if (!(vr as any)?.ok) {
|
|
56
|
+
return Response.json(
|
|
57
|
+
{ status: 'error', code: (vr as any)?.code || 'WS_UPGRADE_INVALID', error: (vr as any)?.error },
|
|
58
|
+
{ status: 400 }
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
return doUpgrade({ query: (vr as any).query, headers: (vr as any).headers });
|
|
62
|
+
}
|
|
63
|
+
if (doUpgrade() === undefined) return undefined as any;
|
|
33
64
|
}
|
|
34
65
|
}
|
|
35
66
|
return opts.fetch(req, srv?.requestIP?.(req)?.address);
|
|
@@ -42,6 +73,7 @@ export const bunDriver: RuntimeDriver = {
|
|
|
42
73
|
reusePort: opts.reusePort,
|
|
43
74
|
maxRequestBodySize: opts.maxRequestBodySize,
|
|
44
75
|
...(routes ? { routes } : {}),
|
|
76
|
+
...(tls ? { tls } : {}),
|
|
45
77
|
fetch(req: Request, srv: any) {
|
|
46
78
|
return opts.fetch(req, srv?.requestIP?.(req)?.address);
|
|
47
79
|
}
|
package/src/runtime/node.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHash, randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
|
|
3
|
-
import {
|
|
3
|
+
import { createServer as createHttpsServer } from 'node:https';
|
|
4
|
+
import { createReadStream, readFileSync } from 'node:fs';
|
|
4
5
|
import { extname } from 'node:path';
|
|
5
6
|
import { Readable } from 'node:stream';
|
|
6
7
|
import * as zlib from 'node:zlib';
|
|
@@ -206,7 +207,7 @@ export const nodeDriver: RuntimeDriver = {
|
|
|
206
207
|
throw new Error("[BareJS] engine: 'uws' was requested, but 'uWebSockets.js' is not installed.");
|
|
207
208
|
}
|
|
208
209
|
}
|
|
209
|
-
const
|
|
210
|
+
const reqHandler = async (req: IncomingMessage, res: ServerResponse) => {
|
|
210
211
|
const parsed = toWebRequest(req, opts.maxRequestBodySize);
|
|
211
212
|
if (parsed.errorStatus === 413 || !parsed.request) {
|
|
212
213
|
res.writeHead(413, { 'content-type': 'application/json' });
|
|
@@ -228,7 +229,24 @@ export const nodeDriver: RuntimeDriver = {
|
|
|
228
229
|
res.end();
|
|
229
230
|
}
|
|
230
231
|
}
|
|
231
|
-
}
|
|
232
|
+
};
|
|
233
|
+
const toNodePem = (v?: string | Uint8Array): string | Buffer | undefined =>
|
|
234
|
+
v === undefined
|
|
235
|
+
? undefined
|
|
236
|
+
: typeof v === 'string'
|
|
237
|
+
? (v.includes('-----BEGIN') ? v : readFileSync(v))
|
|
238
|
+
: Buffer.from(v);
|
|
239
|
+
const server = opts.tls
|
|
240
|
+
? createHttpsServer(
|
|
241
|
+
{
|
|
242
|
+
key: toNodePem(opts.tls.keyFileName ?? opts.tls.key),
|
|
243
|
+
cert: toNodePem(opts.tls.certFileName ?? opts.tls.cert),
|
|
244
|
+
...(opts.tls.passphrase ? { passphrase: opts.tls.passphrase } : {}),
|
|
245
|
+
...(opts.tls.ca ? { ca: toNodePem(opts.tls.ca) } : {})
|
|
246
|
+
},
|
|
247
|
+
reqHandler
|
|
248
|
+
)
|
|
249
|
+
: createServer(reqHandler);
|
|
232
250
|
|
|
233
251
|
if (opts.ws) {
|
|
234
252
|
const wsCfg = opts.ws;
|
|
@@ -428,8 +446,23 @@ export const nodeDriver: RuntimeDriver = {
|
|
|
428
446
|
return;
|
|
429
447
|
}
|
|
430
448
|
try {
|
|
449
|
+
let extra: { query?: any; headers?: any } | undefined;
|
|
450
|
+
if (matched.handler.__validateUpgrade) {
|
|
451
|
+
const vr = await matched.handler.__validateUpgrade(req.url || '/', req.headers as Record<string, string>);
|
|
452
|
+
if (!vr?.ok) {
|
|
453
|
+
try {
|
|
454
|
+
socket.write('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n');
|
|
455
|
+
} catch {}
|
|
456
|
+
socket.destroy();
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
extra = { query: vr.query, headers: vr.headers };
|
|
460
|
+
}
|
|
431
461
|
const wss = await getWss();
|
|
432
|
-
const data =
|
|
462
|
+
const data =
|
|
463
|
+
matched.params || extra
|
|
464
|
+
? { ...matched.handler, ...(matched.params ? { params: matched.params } : {}), ...(extra || {}) }
|
|
465
|
+
: matched.handler;
|
|
433
466
|
if (!wss) {
|
|
434
467
|
handleNativeWsUpgrade(req, socket, head, data);
|
|
435
468
|
return;
|
package/src/runtime/types.ts
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
import type { WebSocketRouteHandler } from '../core/ws-match';
|
|
2
2
|
|
|
3
|
+
export interface ServeTlsOptions {
|
|
4
|
+
/** Path to TLS private key file, or PEM string/bytes (Bun & Node https) */
|
|
5
|
+
key?: string | Uint8Array;
|
|
6
|
+
/** Path to TLS certificate file, or PEM string/bytes (Bun & Node https) */
|
|
7
|
+
cert?: string | Uint8Array;
|
|
8
|
+
/** Optional key file path alias (uWebSockets.js parity) */
|
|
9
|
+
keyFileName?: string;
|
|
10
|
+
/** Optional cert file path alias (uWebSockets.js parity) */
|
|
11
|
+
certFileName?: string;
|
|
12
|
+
/** Optional passphrase for encrypted private key */
|
|
13
|
+
passphrase?: string;
|
|
14
|
+
/** Optional CA certificate file path or PEM bytes */
|
|
15
|
+
ca?: string | Uint8Array;
|
|
16
|
+
}
|
|
17
|
+
|
|
3
18
|
export interface ServeOptions {
|
|
4
19
|
port: number;
|
|
5
20
|
hostname: string;
|
|
@@ -8,6 +23,7 @@ export interface ServeOptions {
|
|
|
8
23
|
fetch: (req: Request, peerIp?: string) => Response | Promise<Response>;
|
|
9
24
|
routes?: Record<string, any>;
|
|
10
25
|
engine?: 'auto' | 'http' | 'uws';
|
|
26
|
+
tls?: ServeTlsOptions;
|
|
11
27
|
uwsRoutes?: any[];
|
|
12
28
|
ws?: {
|
|
13
29
|
routes: Map<string, WebSocketRouteHandler>;
|
package/src/runtime/uws.ts
CHANGED
|
@@ -348,7 +348,15 @@ export function serveUws(
|
|
|
348
348
|
opts: ServeOptions & { uwsRoutes?: UwsRouteEntry[] },
|
|
349
349
|
uwsMod: any
|
|
350
350
|
): ServerHandle {
|
|
351
|
-
const
|
|
351
|
+
const isTls = Boolean(opts.tls);
|
|
352
|
+
const app = opts.tls
|
|
353
|
+
? uwsMod.SSLApp({
|
|
354
|
+
key_file_name: opts.tls.keyFileName ?? (typeof opts.tls.key === 'string' ? opts.tls.key : undefined),
|
|
355
|
+
cert_file_name: opts.tls.certFileName ?? (typeof opts.tls.cert === 'string' ? opts.tls.cert : undefined),
|
|
356
|
+
...(opts.tls.passphrase ? { passphrase: opts.tls.passphrase } : {}),
|
|
357
|
+
...(opts.tls.ca && typeof opts.tls.ca === 'string' ? { ca_file_name: opts.tls.ca } : {})
|
|
358
|
+
})
|
|
359
|
+
: uwsMod.App();
|
|
352
360
|
const isProd = process.env.NODE_ENV === 'production';
|
|
353
361
|
const pool: UwsContext[] = [];
|
|
354
362
|
const maxPool = 4096;
|
|
@@ -477,7 +485,7 @@ export function serveUws(
|
|
|
477
485
|
if (k === 'host') host = v;
|
|
478
486
|
headers.append(k, v);
|
|
479
487
|
});
|
|
480
|
-
const fullUrl =
|
|
488
|
+
const fullUrl = `${isTls ? 'https' : 'http'}://${host}${urlPath}${queryStr ? `?${queryStr}` : ''}`;
|
|
481
489
|
let peerIp = '127.0.0.1';
|
|
482
490
|
try {
|
|
483
491
|
peerIp = Buffer.from(res.getRemoteAddressAsText()).toString() || '127.0.0.1';
|
|
@@ -573,16 +581,56 @@ export function serveUws(
|
|
|
573
581
|
res.writeStatus('404 Not Found').end();
|
|
574
582
|
return;
|
|
575
583
|
}
|
|
576
|
-
const
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
context
|
|
585
|
-
|
|
584
|
+
const wsKey = req.getHeader('sec-websocket-key');
|
|
585
|
+
const wsProto = req.getHeader('sec-websocket-protocol');
|
|
586
|
+
const wsExt = req.getHeader('sec-websocket-extensions');
|
|
587
|
+
const validate = matched.handler.__validateUpgrade;
|
|
588
|
+
if (!validate) {
|
|
589
|
+
const handler: any = matched.params
|
|
590
|
+
? { ...matched.handler, params: matched.params }
|
|
591
|
+
: matched.handler;
|
|
592
|
+
res.upgrade({ handler, wrapped: null }, wsKey, wsProto, wsExt, context);
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
const hdrs: Record<string, string> = {};
|
|
597
|
+
req.forEach((k: string, v: string) => {
|
|
598
|
+
const lower = k.toLowerCase();
|
|
599
|
+
if (lower !== '__proto__' && lower !== 'constructor' && lower !== 'prototype') hdrs[lower] = v;
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
const finishUpgrade = (vr: any, isAsync: boolean) => {
|
|
603
|
+
if (!vr?.ok) {
|
|
604
|
+
const body = JSON.stringify({ status: 'error', code: vr?.code || 'WS_UPGRADE_INVALID', error: vr?.error });
|
|
605
|
+
const sendErr = () => {
|
|
606
|
+
res.writeStatus('400 Bad Request').writeHeader('content-type', 'application/json').end(body);
|
|
607
|
+
};
|
|
608
|
+
if (isAsync) res.cork(sendErr);
|
|
609
|
+
else sendErr();
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
const handler: any = {
|
|
613
|
+
...matched.handler,
|
|
614
|
+
...(matched.params ? { params: matched.params } : {}),
|
|
615
|
+
...(vr.query !== undefined ? { query: vr.query } : {}),
|
|
616
|
+
...(vr.headers !== undefined ? { headers: vr.headers } : {})
|
|
617
|
+
};
|
|
618
|
+
const doUp = () => res.upgrade({ handler, wrapped: null }, wsKey, wsProto, wsExt, context);
|
|
619
|
+
if (isAsync) res.cork(doUp);
|
|
620
|
+
else doUp();
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
const vr = validate(fullUrl, hdrs);
|
|
624
|
+
if (vr && typeof (vr as any).then === 'function') {
|
|
625
|
+
let aborted = false;
|
|
626
|
+
res.onAborted(() => { aborted = true; });
|
|
627
|
+
(vr as Promise<any>).then(
|
|
628
|
+
(resolved) => { if (!aborted) finishUpgrade(resolved, true); },
|
|
629
|
+
() => { if (!aborted) finishUpgrade({ ok: false, code: 'WS_UPGRADE_INVALID' }, true); }
|
|
630
|
+
);
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
finishUpgrade(vr, false);
|
|
586
634
|
},
|
|
587
635
|
open(ws: any) {
|
|
588
636
|
wsCfg.adapter.open(getWrapped(ws));
|
package/src/security/auth.ts
CHANGED
|
@@ -516,16 +516,18 @@ export const basicAuth = (credentials: { user: string; pass: string }) => {
|
|
|
516
516
|
const mw = async (ctx: any, next: Next) => {
|
|
517
517
|
const authHeader = ctx.req.headers.get('Authorization');
|
|
518
518
|
if (!authHeader?.startsWith('Basic ')) {
|
|
519
|
-
return ctx.status(401).json({ status: 'error', message: 'Basic Auth required' });
|
|
519
|
+
return ctx.setHeader('WWW-Authenticate', 'Basic realm="Restricted"').status(401).json({ status: 'error', message: 'Basic Auth required' });
|
|
520
520
|
}
|
|
521
521
|
|
|
522
522
|
const token = authHeader.slice(6).trim();
|
|
523
|
-
if (!token)
|
|
523
|
+
if (!token) {
|
|
524
|
+
return ctx.setHeader('WWW-Authenticate', 'Basic realm="Restricted"').status(401).json({ status: 'error', message: 'Missing credentials' });
|
|
525
|
+
}
|
|
524
526
|
|
|
525
527
|
const decoded = Buffer.from(token, 'base64').toString('utf-8');
|
|
526
528
|
const colonIdx = decoded.indexOf(':');
|
|
527
529
|
if (colonIdx === -1) {
|
|
528
|
-
return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
|
|
530
|
+
return ctx.setHeader('WWW-Authenticate', 'Basic realm="Restricted"').status(401).json({ status: 'error', message: 'Invalid credentials' });
|
|
529
531
|
}
|
|
530
532
|
|
|
531
533
|
const user = decoded.slice(0, colonIdx);
|
|
@@ -538,7 +540,7 @@ export const basicAuth = (credentials: { user: string; pass: string }) => {
|
|
|
538
540
|
return next?.();
|
|
539
541
|
}
|
|
540
542
|
|
|
541
|
-
return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
|
|
543
|
+
return ctx.setHeader('WWW-Authenticate', 'Basic realm="Restricted"').status(401).json({ status: 'error', message: 'Invalid credentials' });
|
|
542
544
|
};
|
|
543
545
|
(mw as any).__isBasicAuth = true;
|
|
544
546
|
return mw;
|
|
@@ -550,7 +552,7 @@ export const basicAuth = (credentials: { user: string; pass: string }) => {
|
|
|
550
552
|
*/
|
|
551
553
|
export const hasRole = (role: string) => {
|
|
552
554
|
return async (ctx: any, next: Next) => {
|
|
553
|
-
const user = ctx.get('user');
|
|
555
|
+
const user = ctx.get('user') ?? ctx.user;
|
|
554
556
|
if (!user || user.role !== role) {
|
|
555
557
|
return ctx.status(403).json({ status: 'error', message: `Required role: ${role}` });
|
|
556
558
|
}
|
|
@@ -126,11 +126,98 @@ export const zod = (schema: z.ZodSchema): Middleware => {
|
|
|
126
126
|
return mw;
|
|
127
127
|
};
|
|
128
128
|
|
|
129
|
+
export interface StandardSchemaV1Issue {
|
|
130
|
+
readonly message: string;
|
|
131
|
+
readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }>;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export type StandardSchemaV1Result<Output = unknown> =
|
|
135
|
+
| { readonly value: Output; readonly issues?: undefined }
|
|
136
|
+
| { readonly issues: ReadonlyArray<StandardSchemaV1Issue> };
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Standard Schema v1 interface (https://standardschema.dev)
|
|
140
|
+
* Supported natively by Zod 4, Valibot, ArkType, Effect, Typia, and custom validators.
|
|
141
|
+
*/
|
|
142
|
+
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
143
|
+
readonly '~standard': {
|
|
144
|
+
readonly version: 1;
|
|
145
|
+
readonly vendor: string;
|
|
146
|
+
readonly validate: (
|
|
147
|
+
value: unknown
|
|
148
|
+
) => StandardSchemaV1Result<Output> | Promise<StandardSchemaV1Result<Output>>;
|
|
149
|
+
readonly types?: {
|
|
150
|
+
readonly input: Input;
|
|
151
|
+
readonly output: Output;
|
|
152
|
+
};
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export const isStandardSchema = (schema: any): schema is StandardSchemaV1 =>
|
|
157
|
+
Boolean(
|
|
158
|
+
schema &&
|
|
159
|
+
typeof schema === 'object' &&
|
|
160
|
+
'~standard' in schema &&
|
|
161
|
+
schema['~standard'] &&
|
|
162
|
+
typeof schema['~standard'].validate === 'function'
|
|
163
|
+
);
|
|
164
|
+
|
|
165
|
+
const formatStandardResult = (res: any): { ok: boolean; data?: any; error?: any } => {
|
|
166
|
+
if (!res || typeof res !== 'object') {
|
|
167
|
+
return { ok: false, error: { message: 'Invalid validator result' } };
|
|
168
|
+
}
|
|
169
|
+
if (Array.isArray(res.issues)) {
|
|
170
|
+
return {
|
|
171
|
+
ok: false,
|
|
172
|
+
error: res.issues.map((iss: any) => ({
|
|
173
|
+
message: iss?.message || 'Validation failed',
|
|
174
|
+
...(iss?.path ? { path: iss.path.map((p: any) => (typeof p === 'object' && p !== null && 'key' in p ? p.key : p)) } : {})
|
|
175
|
+
}))
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
if ('value' in res) {
|
|
179
|
+
return { ok: true, data: res.value };
|
|
180
|
+
}
|
|
181
|
+
return { ok: false, error: { message: 'Invalid validator result' } };
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Universal Standard Schema v1 Engine (Valibot, ArkType, Zod 4, Effect, etc.)
|
|
186
|
+
* Always awaits async validators and fails closed on issues or thrown errors.
|
|
187
|
+
*/
|
|
188
|
+
export const standard = (schema: StandardSchemaV1): Middleware => {
|
|
189
|
+
const mw: Middleware = async (ctx: any, next?: any) => {
|
|
190
|
+
try {
|
|
191
|
+
const isCtx = ctx instanceof Object && 'req' in ctx;
|
|
192
|
+
const body = isCtx ? await ctx.jsonBody() : await ctx.json();
|
|
193
|
+
const raw = await schema['~standard'].validate(body);
|
|
194
|
+
const r = formatStandardResult(raw);
|
|
195
|
+
if (!r.ok) {
|
|
196
|
+
return errorJSON({
|
|
197
|
+
status: 'error',
|
|
198
|
+
code: 'VALIDATION_FAILED',
|
|
199
|
+
errors: r.error
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
if (isCtx) (ctx as any).body = r.data;
|
|
203
|
+
return next ? next() : undefined;
|
|
204
|
+
} catch (e: any) {
|
|
205
|
+
if (e?.status === 413) {
|
|
206
|
+
return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
|
|
207
|
+
}
|
|
208
|
+
return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
(mw as any).__schema = schema;
|
|
212
|
+
return mw;
|
|
213
|
+
};
|
|
214
|
+
|
|
129
215
|
/**
|
|
130
216
|
* Smart Dispatcher (v)
|
|
131
217
|
*/
|
|
132
218
|
export const validate = (schema: any): Middleware => {
|
|
133
219
|
if (schema && '_def' in schema) return zod(schema);
|
|
220
|
+
if (isStandardSchema(schema)) return standard(schema);
|
|
134
221
|
if (schema && (schema.kind || schema[Symbol.for('TypeBox.Kind')])) {
|
|
135
222
|
return typebox(schema);
|
|
136
223
|
}
|
|
@@ -437,13 +524,29 @@ const compileNativeCheck = (schema: any): ((val: any) => { ok: boolean; data?: a
|
|
|
437
524
|
};
|
|
438
525
|
};
|
|
439
526
|
|
|
440
|
-
|
|
527
|
+
type CheckResult = { ok: boolean; data?: any; error?: any };
|
|
528
|
+
type SchemaChecker = (val: any) => CheckResult | Promise<CheckResult>;
|
|
529
|
+
|
|
530
|
+
export const compileSingleSchema = (schema: any): SchemaChecker => {
|
|
441
531
|
if (schema && '_def' in schema) {
|
|
442
532
|
return (val: any) => {
|
|
443
533
|
const r = schema.safeParse(val);
|
|
444
534
|
return r.success ? { ok: true, data: r.data } : { ok: false, error: r.error.flatten() };
|
|
445
535
|
};
|
|
446
536
|
}
|
|
537
|
+
if (isStandardSchema(schema)) {
|
|
538
|
+
const fn = schema['~standard'].validate;
|
|
539
|
+
return (val: any) => {
|
|
540
|
+
const raw = fn(val);
|
|
541
|
+
if (raw && typeof (raw as any).then === 'function') {
|
|
542
|
+
return (raw as Promise<any>).then(
|
|
543
|
+
(resolved) => formatStandardResult(resolved),
|
|
544
|
+
() => ({ ok: false, error: { message: 'Validation failed' } })
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
return formatStandardResult(raw);
|
|
548
|
+
};
|
|
549
|
+
}
|
|
447
550
|
try {
|
|
448
551
|
const check = Compiler.TypeCompiler.Compile(schema);
|
|
449
552
|
return (val: any) => {
|
|
@@ -573,7 +676,7 @@ const projectWithSchema = (val: any, schema: any): any => {
|
|
|
573
676
|
if (Array.isArray(branches) && branches.length > 0) {
|
|
574
677
|
let matchedBranch: any = null;
|
|
575
678
|
for (const b of branches) {
|
|
576
|
-
if (b && typeof b === 'object' && compileSingleSchema(b)(val).ok) {
|
|
679
|
+
if (b && typeof b === 'object' && (compileSingleSchema(b)(val) as CheckResult).ok) {
|
|
577
680
|
matchedBranch = b;
|
|
578
681
|
break;
|
|
579
682
|
}
|
|
@@ -650,7 +753,7 @@ const projectWithSchema = (val: any, schema: any): any => {
|
|
|
650
753
|
};
|
|
651
754
|
|
|
652
755
|
const compileProjector = (schema: any): ((val: any) => any) | null => {
|
|
653
|
-
if (!schema || '_def' in schema) return null; // Zod
|
|
756
|
+
if (!schema || '_def' in schema || isStandardSchema(schema)) return null; // Zod & Standard Schema produce validated output directly
|
|
654
757
|
if (schemaNeedsFallbackProjector(schema)) {
|
|
655
758
|
return (val: any) => projectWithSchema(val, schema);
|
|
656
759
|
}
|
|
@@ -691,18 +794,70 @@ const compileProjector = (schema: any): ((val: any) => any) | null => {
|
|
|
691
794
|
)();
|
|
692
795
|
};
|
|
693
796
|
|
|
694
|
-
|
|
797
|
+
const STATUS_CODE_RE = /^[1-5]\d\d$/;
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* Detects whether a `response` option is a per-status schema map
|
|
801
|
+
* (e.g. `{ 200: UserSchema, 404: NotFoundSchema }`) rather than a single schema.
|
|
802
|
+
*/
|
|
803
|
+
export const isStatusResponseMap = (schema: any): boolean => {
|
|
804
|
+
if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return false;
|
|
805
|
+
if (
|
|
806
|
+
'~standard' in schema ||
|
|
807
|
+
'_def' in schema ||
|
|
808
|
+
typeof schema.parse === 'function' ||
|
|
809
|
+
'type' in schema ||
|
|
810
|
+
'properties' in schema ||
|
|
811
|
+
'anyOf' in schema ||
|
|
812
|
+
'oneOf' in schema ||
|
|
813
|
+
'allOf' in schema ||
|
|
814
|
+
'$ref' in schema ||
|
|
815
|
+
Symbol.for('TypeBox.Kind') in schema
|
|
816
|
+
) {
|
|
817
|
+
return false;
|
|
818
|
+
}
|
|
819
|
+
const keys = Object.keys(schema);
|
|
820
|
+
if (keys.length === 0) return false;
|
|
821
|
+
for (let i = 0; i < keys.length; i++) {
|
|
822
|
+
if (!STATUS_CODE_RE.test(keys[i]!)) return false;
|
|
823
|
+
}
|
|
824
|
+
return true;
|
|
825
|
+
};
|
|
826
|
+
|
|
827
|
+
export const createResponseFilter = (schema: any): ((val: any, status?: number) => any) => {
|
|
828
|
+
if (isStatusResponseMap(schema)) {
|
|
829
|
+
const byStatus = new Map<number, (val: any, status?: number) => any>();
|
|
830
|
+
for (const [codeStr, subSchema] of Object.entries(schema)) {
|
|
831
|
+
const code = Number(codeStr);
|
|
832
|
+
if (Number.isInteger(code) && code >= 100 && code <= 599) {
|
|
833
|
+
byStatus.set(code, createResponseFilter(subSchema));
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
return (val: any, status?: number) => {
|
|
837
|
+
const code = status ?? (val instanceof Response ? val.status : 200);
|
|
838
|
+
const filter = byStatus.get(code);
|
|
839
|
+
return filter ? filter(val, code) : val;
|
|
840
|
+
};
|
|
841
|
+
}
|
|
842
|
+
|
|
695
843
|
const check = compileSingleSchema(schema);
|
|
696
844
|
const project = compileProjector(schema);
|
|
697
845
|
|
|
846
|
+
const finalize = (r: CheckResult) => {
|
|
847
|
+
if (!r.ok) {
|
|
848
|
+
return errorJSON({ status: 'error', code: 'RESPONSE_VALIDATION_FAILED', error: r.error }, 500);
|
|
849
|
+
}
|
|
850
|
+
return r.data;
|
|
851
|
+
};
|
|
852
|
+
|
|
698
853
|
return (val: any) => {
|
|
699
854
|
if (val instanceof Response) return val;
|
|
700
855
|
const filtered = project ? project(val) : val;
|
|
701
856
|
const r = check(filtered);
|
|
702
|
-
if (
|
|
703
|
-
return
|
|
857
|
+
if (r && typeof (r as any).then === 'function') {
|
|
858
|
+
return (r as Promise<CheckResult>).then(finalize);
|
|
704
859
|
}
|
|
705
|
-
return r
|
|
860
|
+
return finalize(r as CheckResult);
|
|
706
861
|
};
|
|
707
862
|
};
|
|
708
863
|
|
|
@@ -789,24 +944,9 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
789
944
|
}
|
|
790
945
|
const hasSyncParts = Boolean(paramsCheck || queryCheck || headersCheck);
|
|
791
946
|
|
|
792
|
-
const validateSyncParts = (ctx: Context): Response | undefined => {
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
const r = paramsCheck(coerced);
|
|
796
|
-
if (!r.ok) return errorJSON({ status: 'error', code: 'PARAMS_INVALID', error: r.error });
|
|
797
|
-
ctx.params = paramsProjector ? paramsProjector(r.data) : r.data;
|
|
798
|
-
}
|
|
799
|
-
if (queryCheck) {
|
|
800
|
-
const coerced = coerceFields(ctx.query, schemas.query);
|
|
801
|
-
for (const k of queryArrayKeys) {
|
|
802
|
-
const all = ctx.queryAll(k);
|
|
803
|
-
if (all.length > 0) coerced[k] = all.map((v) => (queryArrayNumeric.has(k) && NUMERIC_RE.test(v) ? Number(v) : v));
|
|
804
|
-
}
|
|
805
|
-
const r = queryCheck(coerced);
|
|
806
|
-
if (!r.ok) return errorJSON({ status: 'error', code: 'QUERY_INVALID', error: r.error });
|
|
807
|
-
ctx._query = queryProjector ? queryProjector(r.data) : r.data;
|
|
808
|
-
}
|
|
809
|
-
if (headersCheck) {
|
|
947
|
+
const validateSyncParts = (ctx: Context): Response | undefined | Promise<Response | undefined> => {
|
|
948
|
+
const runHeaders = (): Response | undefined | Promise<Response | undefined> => {
|
|
949
|
+
if (!headersCheck) return undefined;
|
|
810
950
|
const hdrObj: Record<string, string> = {};
|
|
811
951
|
ctx.req.headers.forEach((v, k) => {
|
|
812
952
|
const lower = k.toLowerCase();
|
|
@@ -815,16 +955,64 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
815
955
|
}
|
|
816
956
|
});
|
|
817
957
|
const r = headersCheck(hdrObj);
|
|
818
|
-
if (
|
|
958
|
+
if (r && typeof (r as any).then === 'function') {
|
|
959
|
+
return (r as Promise<CheckResult>).then((res) =>
|
|
960
|
+
res.ok ? undefined : errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: res.error })
|
|
961
|
+
);
|
|
962
|
+
}
|
|
963
|
+
const syncR = r as CheckResult;
|
|
964
|
+
if (!syncR.ok) return errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: syncR.error });
|
|
965
|
+
return undefined;
|
|
966
|
+
};
|
|
967
|
+
|
|
968
|
+
const runQuery = (): Response | undefined | Promise<Response | undefined> => {
|
|
969
|
+
if (!queryCheck) return runHeaders();
|
|
970
|
+
const coerced = coerceFields(ctx.query, schemas.query);
|
|
971
|
+
for (const k of queryArrayKeys) {
|
|
972
|
+
const all = ctx.queryAll(k);
|
|
973
|
+
if (all.length > 0) coerced[k] = all.map((v) => (queryArrayNumeric.has(k) && NUMERIC_RE.test(v) ? Number(v) : v));
|
|
974
|
+
}
|
|
975
|
+
const r = queryCheck(coerced);
|
|
976
|
+
if (r && typeof (r as any).then === 'function') {
|
|
977
|
+
return (r as Promise<CheckResult>).then((res) => {
|
|
978
|
+
if (!res.ok) return errorJSON({ status: 'error', code: 'QUERY_INVALID', error: res.error });
|
|
979
|
+
ctx._query = queryProjector ? queryProjector(res.data) : res.data;
|
|
980
|
+
return runHeaders();
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
const syncR = r as CheckResult;
|
|
984
|
+
if (!syncR.ok) return errorJSON({ status: 'error', code: 'QUERY_INVALID', error: syncR.error });
|
|
985
|
+
ctx._query = queryProjector ? queryProjector(syncR.data) : syncR.data;
|
|
986
|
+
return runHeaders();
|
|
987
|
+
};
|
|
988
|
+
|
|
989
|
+
if (paramsCheck) {
|
|
990
|
+
const coerced = coerceFields(ctx.params, schemas.params);
|
|
991
|
+
const r = paramsCheck(coerced);
|
|
992
|
+
if (r && typeof (r as any).then === 'function') {
|
|
993
|
+
return (r as Promise<CheckResult>).then((res) => {
|
|
994
|
+
if (!res.ok) return errorJSON({ status: 'error', code: 'PARAMS_INVALID', error: res.error });
|
|
995
|
+
ctx.params = paramsProjector ? paramsProjector(res.data) : res.data;
|
|
996
|
+
return runQuery();
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
const syncR = r as CheckResult;
|
|
1000
|
+
if (!syncR.ok) return errorJSON({ status: 'error', code: 'PARAMS_INVALID', error: syncR.error });
|
|
1001
|
+
ctx.params = paramsProjector ? paramsProjector(syncR.data) : syncR.data;
|
|
819
1002
|
}
|
|
820
|
-
return
|
|
1003
|
+
return runQuery();
|
|
821
1004
|
};
|
|
822
1005
|
|
|
823
1006
|
if (!bodyCheck) {
|
|
824
1007
|
const syncMw: Middleware = (ctx: Context, next?: Next) => {
|
|
825
1008
|
if (hasSyncParts) {
|
|
826
1009
|
const errRes = validateSyncParts(ctx);
|
|
827
|
-
if (errRes)
|
|
1010
|
+
if (errRes && typeof (errRes as any).then === 'function') {
|
|
1011
|
+
return (errRes as Promise<Response | undefined>).then((resolved) =>
|
|
1012
|
+
resolved ? resolved : (next ? next() : undefined)
|
|
1013
|
+
);
|
|
1014
|
+
}
|
|
1015
|
+
if (errRes) return errRes as Response;
|
|
828
1016
|
}
|
|
829
1017
|
return next ? next() : undefined;
|
|
830
1018
|
};
|
|
@@ -834,8 +1022,13 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
834
1022
|
}
|
|
835
1023
|
|
|
836
1024
|
const isZodBody = Boolean(schemas.body && '_def' in schemas.body);
|
|
1025
|
+
const finishBodyResult = (ctx: Context, r: CheckResult, next?: Next) => {
|
|
1026
|
+
if (!r.ok) return errorJSON({ status: 'error', code: 'VALIDATION_FAILED', error: r.error });
|
|
1027
|
+
ctx.body = bodyProjector ? bodyProjector(r.data) : r.data;
|
|
1028
|
+
return next ? next() : undefined;
|
|
1029
|
+
};
|
|
837
1030
|
const finishBodyValidation = (ctx: Context, body: any, next?: Next): any => {
|
|
838
|
-
let r:
|
|
1031
|
+
let r: CheckResult | Promise<CheckResult>;
|
|
839
1032
|
try {
|
|
840
1033
|
r = bodyCheck(body);
|
|
841
1034
|
} catch {
|
|
@@ -848,17 +1041,13 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
848
1041
|
}
|
|
849
1042
|
r = { ok: false, error: { message: 'Validation failed' } };
|
|
850
1043
|
}
|
|
851
|
-
if (
|
|
852
|
-
|
|
853
|
-
return next ? next() : undefined;
|
|
854
|
-
};
|
|
855
|
-
|
|
856
|
-
const mw: Middleware = (ctx: Context, next?: Next) => {
|
|
857
|
-
if (hasSyncParts) {
|
|
858
|
-
const errRes = validateSyncParts(ctx);
|
|
859
|
-
if (errRes) return errRes;
|
|
1044
|
+
if (r && typeof (r as any).then === 'function') {
|
|
1045
|
+
return (r as Promise<CheckResult>).then((resolved) => finishBodyResult(ctx, resolved, next));
|
|
860
1046
|
}
|
|
1047
|
+
return finishBodyResult(ctx, r as CheckResult, next);
|
|
1048
|
+
};
|
|
861
1049
|
|
|
1050
|
+
const runBodyStep = (ctx: Context, next?: Next): any => {
|
|
862
1051
|
let bodyOrPromise: any;
|
|
863
1052
|
try {
|
|
864
1053
|
bodyOrPromise = (ctx as any).jsonBodySyncOrAsync(maxBodySize);
|
|
@@ -881,6 +1070,19 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
881
1070
|
}
|
|
882
1071
|
return finishBodyValidation(ctx, bodyOrPromise, next);
|
|
883
1072
|
};
|
|
1073
|
+
|
|
1074
|
+
const mw: Middleware = (ctx: Context, next?: Next) => {
|
|
1075
|
+
if (hasSyncParts) {
|
|
1076
|
+
const errRes = validateSyncParts(ctx);
|
|
1077
|
+
if (errRes && typeof (errRes as any).then === 'function') {
|
|
1078
|
+
return (errRes as Promise<Response | undefined>).then((resolved) =>
|
|
1079
|
+
resolved ? resolved : runBodyStep(ctx, next)
|
|
1080
|
+
);
|
|
1081
|
+
}
|
|
1082
|
+
if (errRes) return errRes as Response;
|
|
1083
|
+
}
|
|
1084
|
+
return runBodyStep(ctx, next);
|
|
1085
|
+
};
|
|
884
1086
|
(mw as any).__schema = schemas.body;
|
|
885
1087
|
(mw as any).__routeSchemas = schemas;
|
|
886
1088
|
if (responseFilter) (mw as any).__responseFilter = responseFilter;
|