barejs 0.2.6 → 0.2.7
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 +13 -13
- package/dist/edge.js +19 -19
- package/dist/index.js +188 -185
- package/dist/node.js +188 -185
- package/dist/types/core/bare.d.ts +8 -5
- package/dist/types/core/router.d.ts +3 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/security/validators.d.ts +1 -0
- package/dist/types/utils/file.d.ts +23 -0
- package/llms.txt +5 -3
- package/package.json +1 -1
- package/src/core/bare.ts +63 -6
- package/src/core/router.ts +1 -0
- package/src/index.ts +1 -0
- package/src/security/validators.ts +24 -4
- package/src/utils/file.ts +111 -0
- package/src/utils/openapi.ts +7 -0
|
@@ -58,6 +58,9 @@ type TypedRouteHandler<Derived, Macros extends Record<string, MacroDefinition<an
|
|
|
58
58
|
params: S extends {
|
|
59
59
|
params: infer Pa;
|
|
60
60
|
} ? InferSchema<Pa> : Record<string, any>;
|
|
61
|
+
cookies: S extends {
|
|
62
|
+
cookies: infer C;
|
|
63
|
+
} ? InferSchema<C> : Record<string, string>;
|
|
61
64
|
}) => Res | Promise<Res>;
|
|
62
65
|
type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M extends string, Macros extends Record<string, MacroDefinition<any, any, any>> = {}> = {
|
|
63
66
|
<P extends string, S extends RouteSchemas & MacroOptions<Macros>, Res = S extends {
|
|
@@ -169,11 +172,11 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
|
|
|
169
172
|
head: AddRoute<Derived, Routes, 'HEAD', Macros>;
|
|
170
173
|
all: AddRoute<Derived, Routes, 'ALL', Macros>;
|
|
171
174
|
route: <P extends string, R2 extends RouteSchema = {}>(prefix: P, router: BareRouter<R2>) => BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
|
|
172
|
-
use:
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
175
|
+
use<D2 extends Record<string, any> = {}, R2 extends RouteSchema = {}, M2 extends Record<string, MacroDefinition<any, any, any>> = {}>(mw: BareJS<D2, R2, M2>): BareJS<Derived & D2, Routes & R2, Macros & M2>;
|
|
176
|
+
use<P extends string, D2 extends Record<string, any> = {}, R2 extends RouteSchema = {}, M2 extends Record<string, MacroDefinition<any, any, any>> = {}>(prefix: P, mw: BareJS<D2, R2, M2>): BareJS<Derived & D2, Routes & PrefixRoutes<P, R2>, Macros & M2>;
|
|
177
|
+
use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2, Macros>;
|
|
178
|
+
use<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
|
|
179
|
+
use(...mws: any[]): BareJS<Derived, Routes, Macros>;
|
|
177
180
|
/**
|
|
178
181
|
* Registers declarative per-route macros (`beforeHandle` and/or `resolve`).
|
|
179
182
|
* Zero overhead on routes that do not opt into a macro.
|
|
@@ -47,6 +47,9 @@ type TypedRouterHandler<S extends RouteSchemas, Res> = (ctx: Context & {
|
|
|
47
47
|
params: S extends {
|
|
48
48
|
params: infer Pa;
|
|
49
49
|
} ? InferSchema<Pa> : Record<string, any>;
|
|
50
|
+
cookies: S extends {
|
|
51
|
+
cookies: infer C;
|
|
52
|
+
} ? InferSchema<C> : Record<string, string>;
|
|
50
53
|
}) => Res | Promise<Res>;
|
|
51
54
|
type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
|
|
52
55
|
<P extends string, S extends RouteSchemas, Res = S extends {
|
package/dist/types/index.d.ts
CHANGED
|
@@ -29,6 +29,7 @@ export { redisStore, type BareStore, type RateLimitStore, type IdempotencyStore,
|
|
|
29
29
|
export { circuitBreaker, type CircuitBreakerOptions, type CircuitState } from './security/resilience';
|
|
30
30
|
export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
|
|
31
31
|
export { staticFile, type StaticOptions, type StaticMetadataCacheOptions } from './utils/static';
|
|
32
|
+
export { file, type FileResponseOptions } from './utils/file';
|
|
32
33
|
export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
|
|
33
34
|
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
34
35
|
export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export interface FileResponseOptions {
|
|
2
|
+
/** Optional root directory jail — blocks path traversal and symlinks escaping `root` (403) */
|
|
3
|
+
root?: string;
|
|
4
|
+
/** Override Content-Type header */
|
|
5
|
+
type?: string;
|
|
6
|
+
/** Set Content-Disposition: attachment (pass `true` for basename or a custom filename) */
|
|
7
|
+
download?: boolean | string;
|
|
8
|
+
/** Optional Cache-Control header value */
|
|
9
|
+
cacheControl?: string;
|
|
10
|
+
/** Additional custom response headers */
|
|
11
|
+
headers?: Record<string, string>;
|
|
12
|
+
/** HTTP status code (default: 200) */
|
|
13
|
+
status?: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Ergonomic 1-liner file response helper:
|
|
17
|
+
* `app.get('/logo', () => file('public/logo.png'))`
|
|
18
|
+
* `app.get('/dl/:name', (ctx) => file(ctx.params.name, { root: './uploads', download: true }))`
|
|
19
|
+
*
|
|
20
|
+
* Uses zero-copy `Bun.file` on Bun and streaming `fs.createReadStream` on Node.js.
|
|
21
|
+
* Enforces null-byte rejection and optional `root` directory/symlink containment.
|
|
22
|
+
*/
|
|
23
|
+
export declare const file: (filePath: string, options?: FileResponseOptions) => Response;
|
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 `Bun.serve({ routes })`), **Node.js** (`>= 20` via `barejs/node` with optional `uWebSockets.js` auto-detection & `uWS.SSLApp` TLS), **Deno**, and **Edge Workers** (`barejs/edge` — zero `node:*` imports) with official scaffolding CLI **[`create-barejs`](https://github.com/xarhang/create-barejs)** (`bun create barejs my-app [--bun|--node|--node-uws|--deno]`), built-in security (Argon2id/scrypt, HS256/RS256/ES256 JWT, HMAC-signed HttpOnly cookies, CRLF injection protection, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip/Brotli/Zstd `compress`, `app.cron`, Security Headers, DoS limits), and **Full Multi-Runtime Test Suite (
|
|
3
|
+
> BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1` with `Bun.serve({ routes })`), **Node.js** (`>= 20` via `barejs/node` with optional `uWebSockets.js` auto-detection & `uWS.SSLApp` TLS), **Deno**, and **Edge Workers** (`barejs/edge` — `50 KB`, zero `node:*` imports) with official scaffolding CLI **[`create-barejs`](https://github.com/xarhang/create-barejs)** (`bun create barejs my-app [--bun|--node|--node-uws|--deno]`), built-in security (Argon2id/scrypt, HS256/RS256/ES256 JWT, HMAC-signed HttpOnly cookies, CRLF injection protection, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip/Brotli/Zstd `compress`, `app.cron`, `app.macro()`, `tracing()`/`serverTiming()`, Security Headers, DoS limits), and **Full Multi-Runtime Test Suite (491 tests / 6,801 assertions verified in CI across Bun, Node.js 20/22, and Deno 2)**.
|
|
4
4
|
|
|
5
5
|
## 1. Scaffolding (`create-barejs`) & Minimal App (Bun, Node.js, Deno, Edge)
|
|
6
6
|
```bash
|
|
@@ -8,14 +8,16 @@ bun create barejs my-app # Interactive (Bun, Node.js, Node.js + uWebS
|
|
|
8
8
|
bun create barejs my-app --bun # --bun | --node | --node-uws | --deno
|
|
9
9
|
```
|
|
10
10
|
```ts
|
|
11
|
-
import { BareJS, Context, Type } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20) or 'barejs/edge' on Cloudflare/Vercel/Deno Deploy
|
|
11
|
+
import { BareJS, Context, Type, file } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20) or 'barejs/edge' on Cloudflare/Vercel/Deno Deploy
|
|
12
12
|
|
|
13
13
|
// Optional poolSize (0..65536, default 1024): lazy bounded LIFO Context pool with in-flight slot clearing, shared state across JIT recompiles, & dev-mode UAF guard (0 overhead in prod)
|
|
14
14
|
const app = new BareJS();
|
|
15
15
|
|
|
16
|
-
// Direct return (
|
|
16
|
+
// Direct return (auto-detects JSON, text, Response, file(), or sync/async generator streams)
|
|
17
17
|
app.get('/hello/:name', (ctx: Context) => ({ hello: ctx.params.name }));
|
|
18
18
|
app.get('/ping', () => 'pong');
|
|
19
|
+
app.get('/logo', () => file('public/logo.png')); // Or file(ctx.params.name, { root: './uploads', download: true })
|
|
20
|
+
app.get('/stream', function* () { yield 'Hello '; yield 'BareJS!'; }); // Pull-based ReadableStream backpressure
|
|
19
21
|
|
|
20
22
|
// Wildcard catch-all route (`ctx.params['*']`)
|
|
21
23
|
app.get('/files/*', (ctx: Context) => ({ filePath: ctx.params['*'] }));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "barejs",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.7",
|
|
4
4
|
"author": "xarhang",
|
|
5
5
|
"description": "Batteries-included web framework for Bun, Node.js, and Deno with O(1) JIT routing, TypeBox/Zod validation, OpenAPI 3.1, WebSockets, JSON-RPC 2.0, and built-in security.",
|
|
6
6
|
"main": "./dist/index.js",
|
package/src/core/bare.ts
CHANGED
|
@@ -121,6 +121,7 @@ type TypedRouteHandler<Derived, Macros extends Record<string, MacroDefinition<an
|
|
|
121
121
|
body: S extends { body: infer B } ? InferSchema<B> : any;
|
|
122
122
|
query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, string>;
|
|
123
123
|
params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
|
|
124
|
+
cookies: S extends { cookies: infer C } ? InferSchema<C> : Record<string, string>;
|
|
124
125
|
}
|
|
125
126
|
) => Res | Promise<Res>;
|
|
126
127
|
|
|
@@ -624,11 +625,29 @@ export class BareJS<
|
|
|
624
625
|
router: BareRouter<R2>
|
|
625
626
|
) => BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
|
|
626
627
|
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
628
|
+
public override use<D2 extends Record<string, any> = {}, R2 extends RouteSchema = {}, M2 extends Record<string, MacroDefinition<any, any, any>> = {}>(
|
|
629
|
+
mw: BareJS<D2, R2, M2>
|
|
630
|
+
): BareJS<Derived & D2, Routes & R2, Macros & M2>;
|
|
631
|
+
public override use<P extends string, D2 extends Record<string, any> = {}, R2 extends RouteSchema = {}, M2 extends Record<string, MacroDefinition<any, any, any>> = {}>(
|
|
632
|
+
prefix: P,
|
|
633
|
+
mw: BareJS<D2, R2, M2>
|
|
634
|
+
): BareJS<Derived & D2, Routes & PrefixRoutes<P, R2>, Macros & M2>;
|
|
635
|
+
public override use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2, Macros>;
|
|
636
|
+
public override use<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
|
|
637
|
+
public override use(...mws: any[]): BareJS<Derived, Routes, Macros>;
|
|
638
|
+
public override use(prefixOrMw: any, ...rest: any[]): any {
|
|
639
|
+
const mergeMacrosFrom = (candidate: any) => {
|
|
640
|
+
if (candidate && typeof candidate === 'object' && candidate.macros && typeof candidate.macros === 'object') {
|
|
641
|
+
for (const [k, def] of Object.entries(candidate.macros)) {
|
|
642
|
+
if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
|
|
643
|
+
if (def && typeof def === 'object') this.macros[k] = def as any;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
};
|
|
647
|
+
mergeMacrosFrom(prefixOrMw);
|
|
648
|
+
for (let i = 0; i < rest.length; i++) mergeMacrosFrom(rest[i]);
|
|
649
|
+
return super.use(prefixOrMw, ...rest);
|
|
650
|
+
}
|
|
632
651
|
|
|
633
652
|
/**
|
|
634
653
|
* Registers declarative per-route macros (`beforeHandle` and/or `resolve`).
|
|
@@ -698,7 +717,7 @@ export class BareJS<
|
|
|
698
717
|
}
|
|
699
718
|
// Only pass schemaValidator if any RouteSchemas key is present
|
|
700
719
|
const hasSchemaKey =
|
|
701
|
-
'body' in h || 'query' in h || 'params' in h || 'headers' in h || 'response' in h || 'detail' in h || 'maxBodySize' in h;
|
|
720
|
+
'body' in h || 'query' in h || 'params' in h || 'headers' in h || 'cookies' in h || 'response' in h || 'detail' in h || 'maxBodySize' in h;
|
|
702
721
|
if (hasSchemaKey) expanded.push(h);
|
|
703
722
|
for (let j = 0; j < macroMws.length; j++) expanded.push(macroMws[j]);
|
|
704
723
|
} else {
|
|
@@ -905,6 +924,40 @@ export class BareJS<
|
|
|
905
924
|
return res;
|
|
906
925
|
`;
|
|
907
926
|
|
|
927
|
+
const genEncoder = new TextEncoder();
|
|
928
|
+
const generatorToResponse = (gen: any, status: number, hdrs?: Record<string, string>): Response => {
|
|
929
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
930
|
+
async pull(controller) {
|
|
931
|
+
try {
|
|
932
|
+
const step = await gen.next();
|
|
933
|
+
if (step.done) {
|
|
934
|
+
controller.close();
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
const val = step.value;
|
|
938
|
+
if (val === undefined || val === null) return;
|
|
939
|
+
if (val instanceof Uint8Array) {
|
|
940
|
+
controller.enqueue(val);
|
|
941
|
+
} else if (typeof val === 'string') {
|
|
942
|
+
controller.enqueue(genEncoder.encode(val));
|
|
943
|
+
} else {
|
|
944
|
+
controller.enqueue(genEncoder.encode(JSON.stringify(val) + '\n'));
|
|
945
|
+
}
|
|
946
|
+
} catch (err) {
|
|
947
|
+
controller.error(err);
|
|
948
|
+
}
|
|
949
|
+
},
|
|
950
|
+
cancel() {
|
|
951
|
+
try { gen.return?.(); } catch {}
|
|
952
|
+
}
|
|
953
|
+
});
|
|
954
|
+
const outHeaders: Record<string, string> = hdrs ? { ...hdrs } : {};
|
|
955
|
+
if (!outHeaders['content-type'] && !outHeaders['Content-Type']) {
|
|
956
|
+
outHeaders['content-type'] = 'text/plain; charset=utf-8';
|
|
957
|
+
}
|
|
958
|
+
return new Response(stream, { status, headers: outHeaders });
|
|
959
|
+
};
|
|
960
|
+
|
|
908
961
|
const buildNonResFinalize = `
|
|
909
962
|
${logStatusCode}
|
|
910
963
|
let outRes;
|
|
@@ -917,6 +970,8 @@ export class BareJS<
|
|
|
917
970
|
headers: ctx._headers || text200.headers
|
|
918
971
|
});
|
|
919
972
|
}
|
|
973
|
+
} else if (res !== null && typeof res === 'object' && typeof res.next === 'function') {
|
|
974
|
+
outRes = genToRes(res, finalStatus, ctx._headers);
|
|
920
975
|
} else if (finalStatus === 200 && !ctx._headers) {
|
|
921
976
|
outRes = Response.json(res ?? null);
|
|
922
977
|
} else if (finalStatus === 200 && ctx._headers === lastHdrs) {
|
|
@@ -966,6 +1021,7 @@ export class BareJS<
|
|
|
966
1021
|
const extraNames = [
|
|
967
1022
|
'applyShortCircuit',
|
|
968
1023
|
'noop',
|
|
1024
|
+
'genToRes',
|
|
969
1025
|
...(rFilter ? ['rFilter'] : []),
|
|
970
1026
|
...(idemCommit ? ['idemCommit'] : []),
|
|
971
1027
|
...(idemRelease ? ['idemRelease'] : [])
|
|
@@ -973,6 +1029,7 @@ export class BareJS<
|
|
|
973
1029
|
const extraVals = [
|
|
974
1030
|
applyCtxHeadersToRes,
|
|
975
1031
|
noop,
|
|
1032
|
+
generatorToResponse,
|
|
976
1033
|
...(rFilter ? [rFilter] : []),
|
|
977
1034
|
...(idemCommit ? [idemCommit] : []),
|
|
978
1035
|
...(idemRelease ? [idemRelease] : [])
|
package/src/core/router.ts
CHANGED
|
@@ -76,6 +76,7 @@ type TypedRouterHandler<S extends RouteSchemas, Res> = (
|
|
|
76
76
|
body: S extends { body: infer B } ? InferSchema<B> : any;
|
|
77
77
|
query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, string>;
|
|
78
78
|
params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
|
|
79
|
+
cookies: S extends { cookies: infer C } ? InferSchema<C> : Record<string, string>;
|
|
79
80
|
}
|
|
80
81
|
) => Res | Promise<Res>;
|
|
81
82
|
|
package/src/index.ts
CHANGED
|
@@ -84,6 +84,7 @@ export {
|
|
|
84
84
|
export { circuitBreaker, type CircuitBreakerOptions, type CircuitState } from './security/resilience';
|
|
85
85
|
export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
|
|
86
86
|
export { staticFile, type StaticOptions, type StaticMetadataCacheOptions } from './utils/static';
|
|
87
|
+
export { file, type FileResponseOptions } from './utils/file';
|
|
87
88
|
export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
|
|
88
89
|
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
89
90
|
export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
|
|
@@ -244,6 +244,7 @@ export interface RouteSchemas {
|
|
|
244
244
|
query?: any;
|
|
245
245
|
params?: any;
|
|
246
246
|
headers?: any;
|
|
247
|
+
cookies?: any;
|
|
247
248
|
response?: any;
|
|
248
249
|
/** Strip undeclared properties from validated body using JIT projector (prevents Mass Assignment) */
|
|
249
250
|
stripUnknown?: boolean;
|
|
@@ -909,9 +910,11 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
909
910
|
const queryCheck = schemas.query ? compileSingleSchema(schemas.query) : null;
|
|
910
911
|
const paramsCheck = schemas.params ? compileSingleSchema(schemas.params) : null;
|
|
911
912
|
const headersCheck = schemas.headers ? compileSingleSchema(schemas.headers) : null;
|
|
913
|
+
const cookiesCheck = schemas.cookies ? compileSingleSchema(schemas.cookies) : null;
|
|
912
914
|
const bodyProjector = schemas.stripUnknown && schemas.body ? compileProjector(schemas.body) : null;
|
|
913
915
|
const queryProjector = schemas.stripUnknown && schemas.query ? compileProjector(schemas.query) : null;
|
|
914
916
|
const paramsProjector = schemas.stripUnknown && schemas.params ? compileProjector(schemas.params) : null;
|
|
917
|
+
const cookiesProjector = schemas.stripUnknown && schemas.cookies ? compileProjector(schemas.cookies) : null;
|
|
915
918
|
const responseFilter = schemas.response ? createResponseFilter(schemas.response) : null;
|
|
916
919
|
const maxBodySize = schemas.maxBodySize ?? 1048576;
|
|
917
920
|
const queryArrayKeys: string[] = [];
|
|
@@ -942,11 +945,28 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
942
945
|
}
|
|
943
946
|
}
|
|
944
947
|
}
|
|
945
|
-
const hasSyncParts = Boolean(paramsCheck || queryCheck || headersCheck);
|
|
948
|
+
const hasSyncParts = Boolean(paramsCheck || queryCheck || headersCheck || cookiesCheck);
|
|
946
949
|
|
|
947
950
|
const validateSyncParts = (ctx: Context): Response | undefined | Promise<Response | undefined> => {
|
|
951
|
+
const runCookies = (): Response | undefined | Promise<Response | undefined> => {
|
|
952
|
+
if (!cookiesCheck) return undefined;
|
|
953
|
+
const coerced = coerceFields(ctx.cookies, schemas.cookies);
|
|
954
|
+
const r = cookiesCheck(coerced);
|
|
955
|
+
if (r && typeof (r as any).then === 'function') {
|
|
956
|
+
return (r as Promise<CheckResult>).then((res) => {
|
|
957
|
+
if (!res.ok) return errorJSON({ status: 'error', code: 'COOKIES_INVALID', error: res.error });
|
|
958
|
+
ctx._cookies = cookiesProjector ? cookiesProjector(res.data) : res.data;
|
|
959
|
+
return undefined;
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
const syncR = r as CheckResult;
|
|
963
|
+
if (!syncR.ok) return errorJSON({ status: 'error', code: 'COOKIES_INVALID', error: syncR.error });
|
|
964
|
+
ctx._cookies = cookiesProjector ? cookiesProjector(syncR.data) : syncR.data;
|
|
965
|
+
return undefined;
|
|
966
|
+
};
|
|
967
|
+
|
|
948
968
|
const runHeaders = (): Response | undefined | Promise<Response | undefined> => {
|
|
949
|
-
if (!headersCheck) return
|
|
969
|
+
if (!headersCheck) return runCookies();
|
|
950
970
|
const hdrObj: Record<string, string> = {};
|
|
951
971
|
ctx.req.headers.forEach((v, k) => {
|
|
952
972
|
const lower = k.toLowerCase();
|
|
@@ -957,12 +977,12 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
957
977
|
const r = headersCheck(hdrObj);
|
|
958
978
|
if (r && typeof (r as any).then === 'function') {
|
|
959
979
|
return (r as Promise<CheckResult>).then((res) =>
|
|
960
|
-
res.ok ?
|
|
980
|
+
res.ok ? runCookies() : errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: res.error })
|
|
961
981
|
);
|
|
962
982
|
}
|
|
963
983
|
const syncR = r as CheckResult;
|
|
964
984
|
if (!syncR.ok) return errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: syncR.error });
|
|
965
|
-
return
|
|
985
|
+
return runCookies();
|
|
966
986
|
};
|
|
967
987
|
|
|
968
988
|
const runQuery = (): Response | undefined | Promise<Response | undefined> => {
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { existsSync, realpathSync, statSync } from 'node:fs';
|
|
2
|
+
import { basename, resolve, sep } from 'node:path';
|
|
3
|
+
import { runtime } from '../runtime';
|
|
4
|
+
|
|
5
|
+
export interface FileResponseOptions {
|
|
6
|
+
/** Optional root directory jail — blocks path traversal and symlinks escaping `root` (403) */
|
|
7
|
+
root?: string;
|
|
8
|
+
/** Override Content-Type header */
|
|
9
|
+
type?: string;
|
|
10
|
+
/** Set Content-Disposition: attachment (pass `true` for basename or a custom filename) */
|
|
11
|
+
download?: boolean | string;
|
|
12
|
+
/** Optional Cache-Control header value */
|
|
13
|
+
cacheControl?: string;
|
|
14
|
+
/** Additional custom response headers */
|
|
15
|
+
headers?: Record<string, string>;
|
|
16
|
+
/** HTTP status code (default: 200) */
|
|
17
|
+
status?: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const sanitizeHeaderVal = (v: string): string => v.replace(/[\r\n]+/g, '');
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Ergonomic 1-liner file response helper:
|
|
24
|
+
* `app.get('/logo', () => file('public/logo.png'))`
|
|
25
|
+
* `app.get('/dl/:name', (ctx) => file(ctx.params.name, { root: './uploads', download: true }))`
|
|
26
|
+
*
|
|
27
|
+
* Uses zero-copy `Bun.file` on Bun and streaming `fs.createReadStream` on Node.js.
|
|
28
|
+
* Enforces null-byte rejection and optional `root` directory/symlink containment.
|
|
29
|
+
*/
|
|
30
|
+
export const file = (filePath: string, options: FileResponseOptions = {}): Response => {
|
|
31
|
+
if (typeof filePath !== 'string' || filePath.length === 0 || filePath.includes('\0')) {
|
|
32
|
+
return new Response('Bad Request', { status: 400 });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
let resolved: string;
|
|
36
|
+
if (options.root) {
|
|
37
|
+
let decodedPath = filePath;
|
|
38
|
+
if (decodedPath.includes('%')) {
|
|
39
|
+
try {
|
|
40
|
+
decodedPath = decodeURIComponent(decodedPath);
|
|
41
|
+
} catch {
|
|
42
|
+
return new Response('Bad Request', { status: 400 });
|
|
43
|
+
}
|
|
44
|
+
if (decodedPath.includes('\0')) {
|
|
45
|
+
return new Response('Bad Request', { status: 400 });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const rootAbs = resolve(options.root);
|
|
49
|
+
let realRoot: string;
|
|
50
|
+
try {
|
|
51
|
+
realRoot = realpathSync(rootAbs);
|
|
52
|
+
} catch {
|
|
53
|
+
return new Response('Not Found', { status: 404 });
|
|
54
|
+
}
|
|
55
|
+
const cleanRel = decodedPath.replace(/^[/\\]+/, '');
|
|
56
|
+
const candidate = resolve(realRoot, cleanRel);
|
|
57
|
+
if (candidate !== realRoot && !candidate.startsWith(realRoot + sep)) {
|
|
58
|
+
return new Response('Forbidden', { status: 403 });
|
|
59
|
+
}
|
|
60
|
+
if (!existsSync(candidate)) {
|
|
61
|
+
return new Response('Not Found', { status: 404 });
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
resolved = realpathSync(candidate);
|
|
65
|
+
} catch {
|
|
66
|
+
return new Response('Not Found', { status: 404 });
|
|
67
|
+
}
|
|
68
|
+
if (resolved !== realRoot && !resolved.startsWith(realRoot + sep)) {
|
|
69
|
+
return new Response('Forbidden', { status: 403 });
|
|
70
|
+
}
|
|
71
|
+
} else {
|
|
72
|
+
resolved = resolve(filePath);
|
|
73
|
+
if (!existsSync(resolved)) {
|
|
74
|
+
return new Response('Not Found', { status: 404 });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
let st;
|
|
79
|
+
try {
|
|
80
|
+
st = statSync(resolved);
|
|
81
|
+
} catch {
|
|
82
|
+
return new Response('Not Found', { status: 404 });
|
|
83
|
+
}
|
|
84
|
+
if (!st.isFile()) {
|
|
85
|
+
return new Response('Not Found', { status: 404 });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const handle = runtime.openFile(resolved);
|
|
89
|
+
const headers: Record<string, string> = {
|
|
90
|
+
'content-type': sanitizeHeaderVal(options.type || handle.type || 'application/octet-stream'),
|
|
91
|
+
'content-length': String(st.size)
|
|
92
|
+
};
|
|
93
|
+
if (options.cacheControl) {
|
|
94
|
+
headers['cache-control'] = sanitizeHeaderVal(options.cacheControl);
|
|
95
|
+
}
|
|
96
|
+
if (options.download) {
|
|
97
|
+
const rawName = typeof options.download === 'string' ? options.download : basename(resolved);
|
|
98
|
+
const safeName = sanitizeHeaderVal(rawName).replace(/["\\]/g, '_');
|
|
99
|
+
headers['content-disposition'] = `attachment; filename="${safeName}"`;
|
|
100
|
+
}
|
|
101
|
+
if (options.headers) {
|
|
102
|
+
for (const [k, v] of Object.entries(options.headers)) {
|
|
103
|
+
headers[k] = sanitizeHeaderVal(String(v));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return new Response(handle.full(), {
|
|
108
|
+
status: options.status ?? 200,
|
|
109
|
+
headers
|
|
110
|
+
});
|
|
111
|
+
};
|
package/src/utils/openapi.ts
CHANGED
|
@@ -120,6 +120,13 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
|
|
|
120
120
|
params.push({ name: k, in: 'header', required: hReq.has(k), schema: prop });
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
|
+
if (rs.cookies) {
|
|
124
|
+
const cSchema = extractSchema(rs.cookies);
|
|
125
|
+
const cReq = new Set<string>(cSchema.required || []);
|
|
126
|
+
for (const [k, prop] of Object.entries(cSchema.properties || {})) {
|
|
127
|
+
params.push({ name: k, in: 'cookie', required: cReq.has(k), schema: prop });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
123
130
|
if (rs.response) {
|
|
124
131
|
responseSchema = rs.response;
|
|
125
132
|
}
|