barejs 0.2.4 → 0.2.5
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 +62 -33
- package/dist/edge.js +75 -0
- package/dist/index.js +185 -178
- package/dist/node.js +184 -177
- package/dist/types/client/index.d.ts +57 -0
- package/dist/types/core/bare.d.ts +4 -1
- package/dist/types/core/context.d.ts +1 -0
- package/dist/types/core/router.d.ts +6 -0
- package/dist/types/edge.d.ts +98 -0
- package/dist/types/index.d.ts +3 -3
- package/dist/types/runtime/types.d.ts +15 -0
- package/dist/types/security/validators.d.ts +33 -0
- package/llms.txt +9 -6
- package/package.json +5 -1
- package/src/client/index.ts +294 -6
- package/src/core/bare.ts +15 -5
- package/src/core/context.ts +10 -3
- package/src/core/router.ts +2 -1
- package/src/edge.ts +492 -0
- package/src/index.ts +11 -3
- package/src/runtime/bun.ts +12 -0
- package/src/runtime/node.ts +21 -3
- package/src/runtime/types.ts +16 -0
- package/src/runtime/uws.ts +10 -2
- package/src/security/auth.ts +7 -5
- package/src/security/validators.ts +194 -37
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
|
+
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
|
}
|
|
@@ -695,14 +798,21 @@ export const createResponseFilter = (schema: any): ((val: any) => any) => {
|
|
|
695
798
|
const check = compileSingleSchema(schema);
|
|
696
799
|
const project = compileProjector(schema);
|
|
697
800
|
|
|
801
|
+
const finalize = (r: CheckResult) => {
|
|
802
|
+
if (!r.ok) {
|
|
803
|
+
return errorJSON({ status: 'error', code: 'RESPONSE_VALIDATION_FAILED', error: r.error }, 500);
|
|
804
|
+
}
|
|
805
|
+
return r.data;
|
|
806
|
+
};
|
|
807
|
+
|
|
698
808
|
return (val: any) => {
|
|
699
809
|
if (val instanceof Response) return val;
|
|
700
810
|
const filtered = project ? project(val) : val;
|
|
701
811
|
const r = check(filtered);
|
|
702
|
-
if (
|
|
703
|
-
return
|
|
812
|
+
if (r && typeof (r as any).then === 'function') {
|
|
813
|
+
return (r as Promise<CheckResult>).then(finalize);
|
|
704
814
|
}
|
|
705
|
-
return r
|
|
815
|
+
return finalize(r as CheckResult);
|
|
706
816
|
};
|
|
707
817
|
};
|
|
708
818
|
|
|
@@ -789,24 +899,9 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
789
899
|
}
|
|
790
900
|
const hasSyncParts = Boolean(paramsCheck || queryCheck || headersCheck);
|
|
791
901
|
|
|
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) {
|
|
902
|
+
const validateSyncParts = (ctx: Context): Response | undefined | Promise<Response | undefined> => {
|
|
903
|
+
const runHeaders = (): Response | undefined | Promise<Response | undefined> => {
|
|
904
|
+
if (!headersCheck) return undefined;
|
|
810
905
|
const hdrObj: Record<string, string> = {};
|
|
811
906
|
ctx.req.headers.forEach((v, k) => {
|
|
812
907
|
const lower = k.toLowerCase();
|
|
@@ -815,16 +910,64 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
815
910
|
}
|
|
816
911
|
});
|
|
817
912
|
const r = headersCheck(hdrObj);
|
|
818
|
-
if (
|
|
913
|
+
if (r && typeof (r as any).then === 'function') {
|
|
914
|
+
return (r as Promise<CheckResult>).then((res) =>
|
|
915
|
+
res.ok ? undefined : errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: res.error })
|
|
916
|
+
);
|
|
917
|
+
}
|
|
918
|
+
const syncR = r as CheckResult;
|
|
919
|
+
if (!syncR.ok) return errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: syncR.error });
|
|
920
|
+
return undefined;
|
|
921
|
+
};
|
|
922
|
+
|
|
923
|
+
const runQuery = (): Response | undefined | Promise<Response | undefined> => {
|
|
924
|
+
if (!queryCheck) return runHeaders();
|
|
925
|
+
const coerced = coerceFields(ctx.query, schemas.query);
|
|
926
|
+
for (const k of queryArrayKeys) {
|
|
927
|
+
const all = ctx.queryAll(k);
|
|
928
|
+
if (all.length > 0) coerced[k] = all.map((v) => (queryArrayNumeric.has(k) && NUMERIC_RE.test(v) ? Number(v) : v));
|
|
929
|
+
}
|
|
930
|
+
const r = queryCheck(coerced);
|
|
931
|
+
if (r && typeof (r as any).then === 'function') {
|
|
932
|
+
return (r as Promise<CheckResult>).then((res) => {
|
|
933
|
+
if (!res.ok) return errorJSON({ status: 'error', code: 'QUERY_INVALID', error: res.error });
|
|
934
|
+
ctx._query = queryProjector ? queryProjector(res.data) : res.data;
|
|
935
|
+
return runHeaders();
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
const syncR = r as CheckResult;
|
|
939
|
+
if (!syncR.ok) return errorJSON({ status: 'error', code: 'QUERY_INVALID', error: syncR.error });
|
|
940
|
+
ctx._query = queryProjector ? queryProjector(syncR.data) : syncR.data;
|
|
941
|
+
return runHeaders();
|
|
942
|
+
};
|
|
943
|
+
|
|
944
|
+
if (paramsCheck) {
|
|
945
|
+
const coerced = coerceFields(ctx.params, schemas.params);
|
|
946
|
+
const r = paramsCheck(coerced);
|
|
947
|
+
if (r && typeof (r as any).then === 'function') {
|
|
948
|
+
return (r as Promise<CheckResult>).then((res) => {
|
|
949
|
+
if (!res.ok) return errorJSON({ status: 'error', code: 'PARAMS_INVALID', error: res.error });
|
|
950
|
+
ctx.params = paramsProjector ? paramsProjector(res.data) : res.data;
|
|
951
|
+
return runQuery();
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
const syncR = r as CheckResult;
|
|
955
|
+
if (!syncR.ok) return errorJSON({ status: 'error', code: 'PARAMS_INVALID', error: syncR.error });
|
|
956
|
+
ctx.params = paramsProjector ? paramsProjector(syncR.data) : syncR.data;
|
|
819
957
|
}
|
|
820
|
-
return
|
|
958
|
+
return runQuery();
|
|
821
959
|
};
|
|
822
960
|
|
|
823
961
|
if (!bodyCheck) {
|
|
824
962
|
const syncMw: Middleware = (ctx: Context, next?: Next) => {
|
|
825
963
|
if (hasSyncParts) {
|
|
826
964
|
const errRes = validateSyncParts(ctx);
|
|
827
|
-
if (errRes)
|
|
965
|
+
if (errRes && typeof (errRes as any).then === 'function') {
|
|
966
|
+
return (errRes as Promise<Response | undefined>).then((resolved) =>
|
|
967
|
+
resolved ? resolved : (next ? next() : undefined)
|
|
968
|
+
);
|
|
969
|
+
}
|
|
970
|
+
if (errRes) return errRes as Response;
|
|
828
971
|
}
|
|
829
972
|
return next ? next() : undefined;
|
|
830
973
|
};
|
|
@@ -834,8 +977,13 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
834
977
|
}
|
|
835
978
|
|
|
836
979
|
const isZodBody = Boolean(schemas.body && '_def' in schemas.body);
|
|
980
|
+
const finishBodyResult = (ctx: Context, r: CheckResult, next?: Next) => {
|
|
981
|
+
if (!r.ok) return errorJSON({ status: 'error', code: 'VALIDATION_FAILED', error: r.error });
|
|
982
|
+
ctx.body = bodyProjector ? bodyProjector(r.data) : r.data;
|
|
983
|
+
return next ? next() : undefined;
|
|
984
|
+
};
|
|
837
985
|
const finishBodyValidation = (ctx: Context, body: any, next?: Next): any => {
|
|
838
|
-
let r:
|
|
986
|
+
let r: CheckResult | Promise<CheckResult>;
|
|
839
987
|
try {
|
|
840
988
|
r = bodyCheck(body);
|
|
841
989
|
} catch {
|
|
@@ -848,17 +996,13 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
848
996
|
}
|
|
849
997
|
r = { ok: false, error: { message: 'Validation failed' } };
|
|
850
998
|
}
|
|
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;
|
|
999
|
+
if (r && typeof (r as any).then === 'function') {
|
|
1000
|
+
return (r as Promise<CheckResult>).then((resolved) => finishBodyResult(ctx, resolved, next));
|
|
860
1001
|
}
|
|
1002
|
+
return finishBodyResult(ctx, r as CheckResult, next);
|
|
1003
|
+
};
|
|
861
1004
|
|
|
1005
|
+
const runBodyStep = (ctx: Context, next?: Next): any => {
|
|
862
1006
|
let bodyOrPromise: any;
|
|
863
1007
|
try {
|
|
864
1008
|
bodyOrPromise = (ctx as any).jsonBodySyncOrAsync(maxBodySize);
|
|
@@ -881,6 +1025,19 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
881
1025
|
}
|
|
882
1026
|
return finishBodyValidation(ctx, bodyOrPromise, next);
|
|
883
1027
|
};
|
|
1028
|
+
|
|
1029
|
+
const mw: Middleware = (ctx: Context, next?: Next) => {
|
|
1030
|
+
if (hasSyncParts) {
|
|
1031
|
+
const errRes = validateSyncParts(ctx);
|
|
1032
|
+
if (errRes && typeof (errRes as any).then === 'function') {
|
|
1033
|
+
return (errRes as Promise<Response | undefined>).then((resolved) =>
|
|
1034
|
+
resolved ? resolved : runBodyStep(ctx, next)
|
|
1035
|
+
);
|
|
1036
|
+
}
|
|
1037
|
+
if (errRes) return errRes as Response;
|
|
1038
|
+
}
|
|
1039
|
+
return runBodyStep(ctx, next);
|
|
1040
|
+
};
|
|
884
1041
|
(mw as any).__schema = schemas.body;
|
|
885
1042
|
(mw as any).__routeSchemas = schemas;
|
|
886
1043
|
if (responseFilter) (mw as any).__responseFilter = responseFilter;
|