Compare commits
21
Commits
e38d972566
...
b8670772e9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8670772e9 | ||
|
|
0f11ad1e61 | ||
|
|
456dd52df8 | ||
|
|
eb494ff254 | ||
|
|
101833d52d | ||
|
|
81dc9d3a70 | ||
|
|
9316397694 | ||
|
|
97284935aa | ||
|
|
34017f6ab2 | ||
|
|
ec2e3a0e62 | ||
|
|
5808da8012 | ||
|
|
0f7932c696 | ||
|
|
d2d4fc1d21 | ||
|
|
258130bf30 | ||
|
|
cb77216a53 | ||
|
|
0982873462 | ||
|
|
04da79721f | ||
|
|
0dba41606a | ||
|
|
b8ee1b14a5 | ||
|
|
b87bdc698f | ||
|
|
881bc59419 |
No files matched your search
@@ -228,6 +228,210 @@ const app = createApp({ modules: [ApiModule], plugins: [logger] });
|
|||||||
Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`,
|
Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`,
|
||||||
`mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
|
`mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
|
||||||
|
|
||||||
|
## 7. Transport security
|
||||||
|
|
||||||
|
Four `createApp` options cover TLS, proxying, CORS, and response headers.
|
||||||
|
|
||||||
|
### TLS (native https/wss)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { readFileSync } from 'fs';
|
||||||
|
|
||||||
|
const app = createApp({
|
||||||
|
modules: [App],
|
||||||
|
tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
When `tls` is set the server serves https, and WebSocket upgrades become wss on the same
|
||||||
|
port — no other changes.
|
||||||
|
|
||||||
|
### `trustProxy`
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = createApp({ modules: [App], trustProxy: true });
|
||||||
|
```
|
||||||
|
|
||||||
|
Behind a reverse proxy, reads `X-Forwarded-Proto` / `X-Forwarded-For` to populate
|
||||||
|
`ctx.protocol` (`'http' | 'https'`) and `ctx.ip` (read via `@ctx()`). Off by default —
|
||||||
|
forwarded headers are ignored (and spoofable) until you opt in. It trusts the immediate hop
|
||||||
|
unconditionally; there's no CIDR allowlist yet.
|
||||||
|
|
||||||
|
### CORS
|
||||||
|
|
||||||
|
Off unless `origins` is set.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = createApp({
|
||||||
|
modules: [App],
|
||||||
|
cors: { origins: 'https://app.example.com', credentials: true },
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
|
||||||
|
request (with `Access-Control-Request-Method`) is auto-answered with 204.
|
||||||
|
|
||||||
|
- With `credentials: true`, the server never sends `Access-Control-Allow-Origin: *` — it
|
||||||
|
echoes the concrete allowed origin (or blocks the request).
|
||||||
|
- **Security warning:** `origins: '*'` together with `credentials: true` reflects *any*
|
||||||
|
origin with credentials attached — the classic reflect-any foot-gun. Only combine them if
|
||||||
|
you truly intend an open credentialed API; prefer an explicit allowlist.
|
||||||
|
|
||||||
|
### `security` (headers, ON by default)
|
||||||
|
|
||||||
|
Applied to every HTTP response. Disable everything with `security: false`, or override
|
||||||
|
individual headers with an options object.
|
||||||
|
|
||||||
|
| Header | Default |
|
||||||
|
|---|---|
|
||||||
|
| `X-Content-Type-Options` | `nosniff` |
|
||||||
|
| `X-Frame-Options` | `SAMEORIGIN` |
|
||||||
|
| `Referrer-Policy` | `no-referrer` |
|
||||||
|
| `X-DNS-Prefetch-Control` | `off` |
|
||||||
|
| `Strict-Transport-Security` | `max-age=15552000` (180d) — **only when the connection is secure** (native TLS, or `trustProxy` + `X-Forwarded-Proto: https`); no `includeSubDomains`/`preload` |
|
||||||
|
| `Content-Security-Policy` | not set — pass `security: { csp: "..." }` |
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = createApp({ modules: [App], security: { csp: "default-src 'self'" } });
|
||||||
|
```
|
||||||
|
|
||||||
|
**Scope caveat:** `security` and `cors` headers apply to HTTP responses; they do not apply
|
||||||
|
to the WebSocket handshake (101/upgrade) response.
|
||||||
|
|
||||||
|
### Defaults
|
||||||
|
|
||||||
|
| Option | Default |
|
||||||
|
|---|---|
|
||||||
|
| `tls` | off (plain http/ws) |
|
||||||
|
| `trustProxy` | off |
|
||||||
|
| `cors` | off (same-origin only) |
|
||||||
|
| `security` | ON (HSTS only when the connection is secure) |
|
||||||
|
|
||||||
|
## 8. File uploads / multipart
|
||||||
|
|
||||||
|
A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }`
|
||||||
|
instead of a plain object:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Route, Post, body } from '@green-tea/core';
|
||||||
|
import type { MultipartBody } from '@green-tea/core';
|
||||||
|
|
||||||
|
@Route('/profile')
|
||||||
|
class ProfileController {
|
||||||
|
@Post('/avatar')
|
||||||
|
upload(@body() form: MultipartBody) {
|
||||||
|
const name = form.fields.name; // string | string[]
|
||||||
|
const avatar = form.files.avatar; // UploadedFile | UploadedFile[]
|
||||||
|
return { name, size: Array.isArray(avatar) ? undefined : avatar?.size };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered
|
||||||
|
in memory, no temp files.
|
||||||
|
|
||||||
|
> **Access note (asymmetry).** For multipart, `@body('title')` returns `undefined` — the value
|
||||||
|
> lives at `body.fields.title`, not `body.title`, unlike JSON/urlencoded where `@body('title')`
|
||||||
|
> picks the value directly. Use `@body()` and read `.fields`/`.files`, or key into the envelope
|
||||||
|
> itself with `@body('fields')` / `@body('files')`.
|
||||||
|
|
||||||
|
### Repeated fields — `bodyDuplicates`
|
||||||
|
|
||||||
|
By default, a repeated field name keeps the **last** value (`'last'`, matching urlencoded).
|
||||||
|
Set `bodyDuplicates: 'array'` on `createApp` to accumulate repeats into a `string[]` instead —
|
||||||
|
this applies to **both** urlencoded and multipart text fields:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = createApp({ modules: [ApiModule], bodyDuplicates: 'array' });
|
||||||
|
```
|
||||||
|
|
||||||
|
Files under a repeated field name always become an array (`UploadedFile[]`), regardless of
|
||||||
|
`bodyDuplicates`.
|
||||||
|
|
||||||
|
### Per-endpoint override
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
@Post('/upload', { duplicates: 'array' })
|
||||||
|
upload(@body() form: MultipartBody) { /* ... */ }
|
||||||
|
```
|
||||||
|
|
||||||
|
Precedence: route `duplicates` → app `bodyDuplicates` → `'last'`.
|
||||||
|
|
||||||
|
### Limits
|
||||||
|
|
||||||
|
Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes` limit as any
|
||||||
|
other request body (over the limit → 413). `maxParts` (default `1000`) caps the number of
|
||||||
|
multipart parts per request:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } });
|
||||||
|
```
|
||||||
|
|
||||||
|
A malformed multipart body (bad boundary, missing headers, truncated part) → 400.
|
||||||
|
|
||||||
|
## 9. Validation
|
||||||
|
|
||||||
|
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema**
|
||||||
|
(the [`~standard` interface](https://standardschema.dev) shared by zod, valibot, arktype,
|
||||||
|
and others). green-tea's core has **zero runtime dependency** on any of them — bring
|
||||||
|
whichever validator you already use:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { Route, Post, body } from '@green-tea/core';
|
||||||
|
|
||||||
|
const CreateUser = z.object({ email: z.string().email() });
|
||||||
|
|
||||||
|
@Route('/users')
|
||||||
|
class UserController {
|
||||||
|
@Post('/')
|
||||||
|
create(@body(CreateUser) user: { email: string }) {
|
||||||
|
return { created: user.email };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The value the handler receives is the schema's **parsed/coerced output**, not the raw
|
||||||
|
input — `ctx.body` (via `@ctx()` or a `@needs`-fed step) stays exactly what the transport
|
||||||
|
parsed. Query strings are always strings on the wire, so a schema is often the coercion
|
||||||
|
point:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const ListQuery = z.object({ page: z.coerce.number() });
|
||||||
|
|
||||||
|
@Get('/list')
|
||||||
|
list(@query(ListQuery) q: { page: number }) {
|
||||||
|
return { page: q.page, isNum: typeof q.page === 'number' }; // GET /list?page=2 → true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Access shape (asymmetry).** `@param('id', Schema)` takes the key in slot 1 and the schema
|
||||||
|
> in slot 2 — `@param` always needs a name to say which route param it binds. `@body(Schema)`,
|
||||||
|
> `@query(Schema)`, and `@headers(Schema)` take the schema as their only argument, validating
|
||||||
|
> the whole parsed object (all of `body`/`query`/`headers`).
|
||||||
|
|
||||||
|
A failing schema short-circuits the request with **422**:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "error": "Validation failed", "source": "body", "issues": [{ "path": "email", "message": "Invalid email" }] }
|
||||||
|
```
|
||||||
|
|
||||||
|
`source` is which envelope failed (`'body' | 'query' | 'params' | 'headers'`); `issues` is
|
||||||
|
the schema's issues flattened to `{ path, message }` (`path` is dot-joined).
|
||||||
|
|
||||||
|
**Caveats:**
|
||||||
|
- **Fail-fast.** Arguments validate in order; the **first** failing one throws — later args in
|
||||||
|
the same handler are not checked in that request.
|
||||||
|
- **Steps see raw input.** Only the resolved handler argument is coerced/validated; a `@Step`
|
||||||
|
reading the same data via `ctx.body`/`ctx.query`/etc. always sees the untouched value.
|
||||||
|
- **A throwing schema is a 500, not a 422.** The Standard Schema contract says `validate()`
|
||||||
|
returns `{ issues }` on failure — it isn't supposed to throw. If it does anyway, that
|
||||||
|
propagates as an uncaught error (→ 500), since it signals a bug in the schema, not user input.
|
||||||
|
- **Async schemas are awaited** — `validate()` returning a `Promise` works transparently.
|
||||||
|
|
||||||
|
**Not covered yet:** response/output validation, validating a `@Step`'s own inputs, and
|
||||||
|
mesh remote-route validation are all out of scope for this feature.
|
||||||
|
|
||||||
## Inspect & test the graph
|
## Inspect & test the graph
|
||||||
|
|
||||||
### Visualize with Mermaid
|
### Visualize with Mermaid
|
||||||
|
|||||||
+14
-8
@@ -14,6 +14,7 @@ import {
|
|||||||
import { getArgs, getHandlerNeeds, resolveArgs } from './params';
|
import { getArgs, getHandlerNeeds, resolveArgs } from './params';
|
||||||
import { connectLink, type Link } from './mesh/link';
|
import { connectLink, type Link } from './mesh/link';
|
||||||
import { Rooms } from './rooms';
|
import { Rooms } from './rooms';
|
||||||
|
import type { TlsOptions, SecurityOptions, CorsOptions } from './security';
|
||||||
import { buildRemote } from './mesh/teacup';
|
import { buildRemote } from './mesh/teacup';
|
||||||
import { buildManifest, createMeshControl } from './mesh/teapot';
|
import { buildManifest, createMeshControl } from './mesh/teapot';
|
||||||
import type { MeshControl } from './http';
|
import type { MeshControl } from './http';
|
||||||
@@ -42,8 +43,9 @@ interface RoutePlan {
|
|||||||
steps: GraphNode[];
|
steps: GraphNode[];
|
||||||
handlerName: string;
|
handlerName: string;
|
||||||
needs: string[];
|
needs: string[];
|
||||||
run: (ctx: any) => unknown;
|
run: (ctx: any) => Promise<unknown>;
|
||||||
transformer: typeof JsonTransformer;
|
transformer: typeof JsonTransformer;
|
||||||
|
duplicates?: 'array' | 'last';
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MeshConfig {
|
export interface MeshConfig {
|
||||||
@@ -52,7 +54,7 @@ export interface MeshConfig {
|
|||||||
timeoutMs?: number;
|
timeoutMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record<string, unknown> }): App {
|
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record<string, unknown>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' }): App {
|
||||||
const bus = new Bus();
|
const bus = new Bus();
|
||||||
const container = new Container();
|
const container = new Container();
|
||||||
let server: http.Server | undefined;
|
let server: http.Server | undefined;
|
||||||
@@ -112,8 +114,9 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
|||||||
steps: [],
|
steps: [],
|
||||||
handlerName: route.handlerName,
|
handlerName: route.handlerName,
|
||||||
needs: getHandlerNeeds(argSpecs),
|
needs: getHandlerNeeds(argSpecs),
|
||||||
run: (c: any) => inst[route.handlerName](...resolveArgs(argSpecs, c)),
|
run: async (c: any) => inst[route.handlerName](...(await resolveArgs(argSpecs, c))),
|
||||||
transformer: getTransformer(C, route.handlerName) ?? JsonTransformer,
|
transformer: getTransformer(C, route.handlerName) ?? JsonTransformer,
|
||||||
|
duplicates: route.duplicates,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -318,12 +321,13 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
|||||||
...routePlans
|
...routePlans
|
||||||
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
|
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
|
||||||
.map((plan): RouteDef => ({
|
.map((plan): RouteDef => ({
|
||||||
method: plan.method, pattern: plan.pattern, transport: plan.transport,
|
method: plan.method, pattern: plan.pattern, transport: plan.transport, bodyDuplicates: plan.duplicates,
|
||||||
handler: async (req) => {
|
handler: async (req) => {
|
||||||
const provided = await providedSeed(plan);
|
const provided = await providedSeed(plan);
|
||||||
return runPipeline({
|
return runPipeline({
|
||||||
steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus,
|
steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus,
|
||||||
seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers },
|
seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers,
|
||||||
|
protocol: req.protocol, ip: req.ip },
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
})),
|
})),
|
||||||
@@ -349,16 +353,18 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
|||||||
pattern: plan.pattern,
|
pattern: plan.pattern,
|
||||||
open: async ({ params, inbound, abort, req }) => {
|
open: async ({ params, inbound, abort, req }) => {
|
||||||
const provided = await providedSeed(plan);
|
const provided = await providedSeed(plan);
|
||||||
|
// ws upgrades come in on the raw Node req; trustProxy derivation for ws is out of scope here
|
||||||
let ctx: any = { ...provided, req, params, query: parseQuery(req.url ?? ''), body: undefined,
|
let ctx: any = { ...provided, req, params, query: parseQuery(req.url ?? ''), body: undefined,
|
||||||
headers: req.headers, inbound, abort };
|
headers: req.headers, inbound, abort,
|
||||||
|
protocol: (req.socket as any).encrypted ? 'https' : 'http', ip: req.socket.remoteAddress ?? '' };
|
||||||
for (const s of planSteps(plan)) { ctx = { ...ctx, ...(await s.run(ctx)) }; }
|
for (const s of planSteps(plan)) { ctx = { ...ctx, ...(await s.run(ctx)) }; }
|
||||||
const out = plan.run(ctx);
|
const out = await plan.run(ctx);
|
||||||
if (!isAsyncIterable(out)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
|
if (!isAsyncIterable(out)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
|
||||||
return out as AsyncIterable<unknown>;
|
return out as AsyncIterable<unknown>;
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams });
|
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true, cors: opts.cors, bodyDuplicates: opts.bodyDuplicates });
|
||||||
server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
|
server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
|
||||||
await new Promise<void>((resolve) => server!.listen(port, resolve));
|
await new Promise<void>((resolve) => server!.listen(port, resolve));
|
||||||
return server;
|
return server;
|
||||||
|
|||||||
+89
-15
@@ -1,4 +1,5 @@
|
|||||||
import http from 'http';
|
import http from 'http';
|
||||||
|
import https from 'https';
|
||||||
import { once } from 'events';
|
import { once } from 'events';
|
||||||
import { channel } from './channel';
|
import { channel } from './channel';
|
||||||
import { errorToResponse } from './transformers';
|
import { errorToResponse } from './transformers';
|
||||||
@@ -7,14 +8,18 @@ import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
|
|||||||
import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
|
import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
|
||||||
import type { Transport } from './metadata';
|
import type { Transport } from './metadata';
|
||||||
import type { Bus } from './bus';
|
import type { Bus } from './bus';
|
||||||
|
import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from './security';
|
||||||
|
import type { TlsOptions, SecurityOptions, CorsOptions } from './security';
|
||||||
|
import { parseMultipart, extractBoundary, collapseDuplicates } from './multipart';
|
||||||
|
|
||||||
export interface RequestLimits {
|
export interface RequestLimits {
|
||||||
maxBodyBytes?: number; // default 1_000_000
|
maxBodyBytes?: number; // default 1_000_000
|
||||||
requestTimeoutMs?: number; // default 30_000
|
requestTimeoutMs?: number; // default 30_000
|
||||||
headersTimeoutMs?: number; // default 10_000
|
headersTimeoutMs?: number; // default 10_000
|
||||||
keepAliveTimeoutMs?: number; // default 5_000
|
keepAliveTimeoutMs?: number; // default 5_000
|
||||||
|
maxParts?: number; // default 1000
|
||||||
}
|
}
|
||||||
export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void> }
|
export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' }
|
||||||
|
|
||||||
export type RouteHandler = (req: {
|
export type RouteHandler = (req: {
|
||||||
method: string; url: string;
|
method: string; url: string;
|
||||||
@@ -22,9 +27,11 @@ export type RouteHandler = (req: {
|
|||||||
params: Record<string, string>;
|
params: Record<string, string>;
|
||||||
query: Record<string, string>;
|
query: Record<string, string>;
|
||||||
body: unknown;
|
body: unknown;
|
||||||
|
protocol: 'http' | 'https';
|
||||||
|
ip: string;
|
||||||
}) => Promise<PipelineResult>;
|
}) => Promise<PipelineResult>;
|
||||||
|
|
||||||
export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler }
|
export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler; bodyDuplicates?: 'array' | 'last' }
|
||||||
export interface MatchedRoute { params: Record<string, string>; def: RouteDef }
|
export interface MatchedRoute { params: Record<string, string>; def: RouteDef }
|
||||||
|
|
||||||
export interface WsOpenCtx {
|
export interface WsOpenCtx {
|
||||||
@@ -67,7 +74,7 @@ export function parseQuery(url: string): Record<string, string> {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<string | undefined> {
|
async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
|
||||||
const chunks: Buffer[] = [];
|
const chunks: Buffer[] = [];
|
||||||
let total = 0;
|
let total = 0;
|
||||||
for await (const chunk of req) {
|
for await (const chunk of req) {
|
||||||
@@ -75,9 +82,20 @@ async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promis
|
|||||||
if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large');
|
if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large');
|
||||||
chunks.push(chunk as Buffer);
|
chunks.push(chunk as Buffer);
|
||||||
}
|
}
|
||||||
if (chunks.length === 0) return undefined;
|
return chunks.length === 0 ? undefined : Buffer.concat(chunks);
|
||||||
const raw = Buffer.concat(chunks).toString('utf8');
|
}
|
||||||
return raw === '' ? undefined : raw;
|
|
||||||
|
function firstToken(v: string | string[] | undefined): string | undefined {
|
||||||
|
const s = Array.isArray(v) ? v[0] : v;
|
||||||
|
return s?.split(',')[0].trim();
|
||||||
|
}
|
||||||
|
function deriveSecure(req: http.IncomingMessage, trustProxy: boolean): boolean {
|
||||||
|
if (trustProxy) { const p = firstToken(req.headers['x-forwarded-proto']); if (p) return p === 'https'; }
|
||||||
|
return (req.socket as any).encrypted === true;
|
||||||
|
}
|
||||||
|
function deriveIp(req: http.IncomingMessage, trustProxy: boolean): string {
|
||||||
|
if (trustProxy) { const f = firstToken(req.headers['x-forwarded-for']); if (f) return f; }
|
||||||
|
return req.socket.remoteAddress ?? '';
|
||||||
}
|
}
|
||||||
|
|
||||||
function pickEncoder(transport: Transport, accept: string): StreamEncoder {
|
function pickEncoder(transport: Transport, accept: string): StreamEncoder {
|
||||||
@@ -186,41 +204,93 @@ export function createHttpServer(
|
|||||||
routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions,
|
routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions,
|
||||||
): http.Server {
|
): http.Server {
|
||||||
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
|
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||||
const server = http.createServer(async (req, res) => {
|
const trustProxy = opts?.trustProxy ?? false;
|
||||||
|
const handler = async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
|
||||||
const url = req.url ?? '/';
|
const url = req.url ?? '/';
|
||||||
const path = url.split('?')[0];
|
const path = url.split('?')[0];
|
||||||
|
// Install the security-header patch BEFORE any routing/response so every path
|
||||||
|
// (200, 404, error, stream) writes headers through the same patched writeHead.
|
||||||
|
const secure = deriveSecure(req, trustProxy);
|
||||||
|
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
|
||||||
|
const orig = res.writeHead.bind(res);
|
||||||
|
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
|
||||||
|
// normalize (statusMessage?, headers?) overloads
|
||||||
|
const hdrs = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
|
||||||
|
// injected (security/CORS) is authoritative. Node's writeHead does NOT dedupe case-variant
|
||||||
|
// keys — both lines would ship and a browser honors the first — so drop any handler header
|
||||||
|
// whose name case-insensitively collides with an injected one before merging.
|
||||||
|
const merged: Record<string, any> = {};
|
||||||
|
const injectedLower = new Set(Object.keys(injected).map((k) => k.toLowerCase()));
|
||||||
|
let handlerVary: string | undefined;
|
||||||
|
if (hdrs) for (const k of Object.keys(hdrs)) {
|
||||||
|
const lk = k.toLowerCase();
|
||||||
|
if (lk === 'vary') { handlerVary = hdrs[k]; continue; } // merged separately below
|
||||||
|
if (!injectedLower.has(lk)) merged[k] = hdrs[k];
|
||||||
|
}
|
||||||
|
Object.assign(merged, injected);
|
||||||
|
if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']);
|
||||||
|
else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS
|
||||||
|
return typeof arg2 === 'string' ? orig(status, arg2, merged) : orig(status, merged);
|
||||||
|
};
|
||||||
|
// CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily
|
||||||
|
// by reference at writeHead time, so keys added here still land on every response.
|
||||||
|
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
|
||||||
|
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
||||||
|
const pf = corsPreflightHeaders(opts.cors, req);
|
||||||
|
res.writeHead(204, pf);
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
const matched = matchRoute(routes, req.method ?? 'GET', path);
|
const matched = matchRoute(routes, req.method ?? 'GET', path);
|
||||||
if (!matched) {
|
if (!matched) {
|
||||||
res.writeHead(404, { 'content-type': 'application/json' });
|
res.writeHead(404, { 'content-type': 'application/json' });
|
||||||
res.end(JSON.stringify({ error: 'Not Found' }));
|
res.end(JSON.stringify({ error: 'Not Found' }));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let raw: string | undefined;
|
let buf: Buffer | undefined;
|
||||||
try {
|
try {
|
||||||
raw = await readBody(req, maxBody);
|
buf = await readBody(req, maxBody);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const r = errorToResponse(error);
|
const r = errorToResponse(error);
|
||||||
res.writeHead(r.status, { ...r.headers, connection: 'close' });
|
res.writeHead(r.status, { ...r.headers, connection: 'close' });
|
||||||
res.end(r.body);
|
res.end(r.body);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let body: unknown = raw;
|
let body: unknown;
|
||||||
const ct = String(req.headers['content-type'] ?? '');
|
const ct = String(req.headers['content-type'] ?? '');
|
||||||
if (raw !== undefined && ct.includes('application/json')) {
|
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
|
||||||
try { body = JSON.parse(raw); }
|
if (buf !== undefined && ct.includes('application/json')) {
|
||||||
|
try { body = JSON.parse(buf.toString('utf8')); }
|
||||||
catch {
|
catch {
|
||||||
res.writeHead(400, { 'content-type': 'application/json' });
|
res.writeHead(400, { 'content-type': 'application/json' });
|
||||||
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
|
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} else if (raw !== undefined && ct.includes('application/x-www-form-urlencoded')) {
|
} else if (buf !== undefined && ct.includes('application/x-www-form-urlencoded')) {
|
||||||
body = Object.fromEntries(new URLSearchParams(raw));
|
body = collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates);
|
||||||
|
} else if (buf !== undefined && ct.includes('multipart/form-data')) {
|
||||||
|
const boundary = extractBoundary(ct);
|
||||||
|
if (!boundary) {
|
||||||
|
res.writeHead(400, { 'content-type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ error: 'Invalid multipart body' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try { body = parseMultipart(buf, boundary, { maxParts: opts?.limits?.maxParts ?? 1000, duplicates }); }
|
||||||
|
catch {
|
||||||
|
res.writeHead(400, { 'content-type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ error: 'Invalid multipart body' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const s = buf?.toString('utf8');
|
||||||
|
body = s === '' ? undefined : s;
|
||||||
}
|
}
|
||||||
let result: PipelineResult;
|
let result: PipelineResult;
|
||||||
try {
|
try {
|
||||||
result = await matched.def.handler({
|
result = await matched.def.handler({
|
||||||
method: req.method ?? 'GET', url, headers: req.headers,
|
method: req.method ?? 'GET', url, headers: req.headers,
|
||||||
params: matched.params, query: parseQuery(url), body,
|
params: matched.params, query: parseQuery(url), body,
|
||||||
|
protocol: secure ? 'https' : 'http', ip: deriveIp(req, trustProxy),
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
result = errorToResponse(error);
|
result = errorToResponse(error);
|
||||||
@@ -233,7 +303,11 @@ export function createHttpServer(
|
|||||||
const r: ResponseShape = result;
|
const r: ResponseShape = result;
|
||||||
res.writeHead(r.status, r.headers);
|
res.writeHead(r.status, r.headers);
|
||||||
res.end(r.body);
|
res.end(r.body);
|
||||||
});
|
};
|
||||||
|
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
|
||||||
|
const server: http.Server = (opts?.tls
|
||||||
|
? https.createServer(opts.tls as https.ServerOptions, handler)
|
||||||
|
: http.createServer(handler)) as unknown as http.Server;
|
||||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
||||||
|
|||||||
+4
-1
@@ -8,7 +8,7 @@ export type { GraphView } from './graph-viz';
|
|||||||
export { Provider, Step, Route, Get, Module, Transformer } from './metadata';
|
export { Provider, Step, Route, Get, Module, Transformer } from './metadata';
|
||||||
export type { Plugin } from './plugin';
|
export type { Plugin } from './plugin';
|
||||||
export { JsonTransformer } from './transformers';
|
export { JsonTransformer } from './transformers';
|
||||||
export { HttpError, Unauthorized, NotFound, Redirect, NotModified } from './signals';
|
export { HttpError, Unauthorized, NotFound, Redirect, NotModified, ValidationError } from './signals';
|
||||||
export { Bus } from './bus';
|
export { Bus } from './bus';
|
||||||
export { flow, Flow } from './flow';
|
export { flow, Flow } from './flow';
|
||||||
export type { StepFn, CompiledFlow } from './flow';
|
export type { StepFn, CompiledFlow } from './flow';
|
||||||
@@ -24,6 +24,9 @@ export { sseEncoder, ndjsonEncoder } from './encoders';
|
|||||||
export type { StreamEncoder } from './encoders';
|
export type { StreamEncoder } from './encoders';
|
||||||
export type { MeshConfig } from './app';
|
export type { MeshConfig } from './app';
|
||||||
export type { RequestLimits } from './http';
|
export type { RequestLimits } from './http';
|
||||||
|
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
|
||||||
|
export type { UploadedFile, MultipartBody } from './multipart';
|
||||||
|
export type { StandardSchemaV1 } from './standard-schema';
|
||||||
export { connectLink } from './mesh/link';
|
export { connectLink } from './mesh/link';
|
||||||
export { buildRemote, envelopeFrom } from './mesh/teacup';
|
export { buildRemote, envelopeFrom } from './mesh/teacup';
|
||||||
export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
|
export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
|
||||||
|
|||||||
+3
-3
@@ -7,7 +7,7 @@ export interface ProviderMeta { provides: string; needs: string[]; optional: boo
|
|||||||
export interface StepMeta { provides: string; needs: string[]; optional: boolean; export: boolean }
|
export interface StepMeta { provides: string; needs: string[]; optional: boolean; export: boolean }
|
||||||
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
||||||
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
|
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
|
||||||
export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport; export: boolean }
|
export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport; export: boolean; duplicates?: 'array' | 'last' }
|
||||||
export interface ModuleOptions {
|
export interface ModuleOptions {
|
||||||
mountpoint: string; providers?: Ctor[]; steps?: Ctor[]; controllers?: Ctor[];
|
mountpoint: string; providers?: Ctor[]; steps?: Ctor[]; controllers?: Ctor[];
|
||||||
}
|
}
|
||||||
@@ -40,11 +40,11 @@ export function Route(prefix: string): ClassDecorator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function routeDecorator(method: HttpMethod, transport: Transport) {
|
function routeDecorator(method: HttpMethod, transport: Transport) {
|
||||||
return (path: string, opts?: { export?: boolean }): MethodDecorator =>
|
return (path: string, opts?: { export?: boolean; duplicates?: 'array' | 'last' }): MethodDecorator =>
|
||||||
(target, propertyKey) => {
|
(target, propertyKey) => {
|
||||||
const ctor = target.constructor;
|
const ctor = target.constructor;
|
||||||
const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
|
const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
|
||||||
routes.push({ method, path, handlerName: String(propertyKey), transport, export: opts?.export ?? false });
|
routes.push({ method, path, handlerName: String(propertyKey), transport, export: opts?.export ?? false, duplicates: opts?.duplicates });
|
||||||
Reflect.defineMetadata(K.routes, routes, ctor);
|
Reflect.defineMetadata(K.routes, routes, ctor);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
// src/multipart.ts — pure, binary-safe multipart/form-data parser. No server deps.
|
||||||
|
export interface UploadedFile { filename: string; contentType: string; data: Buffer; size: number }
|
||||||
|
export interface MultipartBody {
|
||||||
|
fields: Record<string, string | string[]>;
|
||||||
|
files: Record<string, UploadedFile | UploadedFile[]>;
|
||||||
|
}
|
||||||
|
export interface MultipartOpts { maxParts: number; duplicates: 'array' | 'last' }
|
||||||
|
|
||||||
|
const CRLF = Buffer.from('\r\n');
|
||||||
|
|
||||||
|
// boundary token from a Content-Type value; supports quoted form.
|
||||||
|
export function extractBoundary(contentType: string): string | undefined {
|
||||||
|
const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType);
|
||||||
|
const b = (m?.[1] ?? m?.[2])?.trim();
|
||||||
|
return b || undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// order-independent, quoted-or-unquoted param lookup within a header value.
|
||||||
|
// The `(?:^|[;\s])` prefix anchors the key to a param boundary so `name=` does NOT
|
||||||
|
// match the tail of `filename=`, and `filename=` does not match `filename*=`.
|
||||||
|
function param(header: string, key: string): string | undefined {
|
||||||
|
const q = new RegExp(`(?:^|[;\\s])${key}="([^"]*)"`, 'i').exec(header);
|
||||||
|
if (q) return q[1];
|
||||||
|
const u = new RegExp(`(?:^|[;\\s])${key}=([^";]+)`, 'i').exec(header);
|
||||||
|
return u ? u[1].trim() : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addField(fields: MultipartBody['fields'], name: string, value: string, dup: 'array' | 'last'): void {
|
||||||
|
if (dup === 'array') {
|
||||||
|
const ex = fields[name];
|
||||||
|
if (Array.isArray(ex)) ex.push(value);
|
||||||
|
else fields[name] = [value];
|
||||||
|
} else {
|
||||||
|
fields[name] = value; // last-wins
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reusable accumulator for any iterable of [key, value] pairs (e.g. URLSearchParams)
|
||||||
|
// so urlencoded bodies collapse duplicates with the exact same policy as multipart fields.
|
||||||
|
export function collapseDuplicates(
|
||||||
|
pairs: Iterable<[string, string]>, dup: 'array' | 'last',
|
||||||
|
): Record<string, string | string[]> {
|
||||||
|
const out: Record<string, string | string[]> = {};
|
||||||
|
for (const [k, v] of pairs) addField(out, k, v, dup);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addFile(files: MultipartBody['files'], name: string, file: UploadedFile): void {
|
||||||
|
const ex = files[name];
|
||||||
|
if (ex === undefined) files[name] = file;
|
||||||
|
else if (Array.isArray(ex)) ex.push(file);
|
||||||
|
else files[name] = [ex, file];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find the next REAL delimiter at/after `from`: a `\r\n--boundary` occurrence that is
|
||||||
|
// followed by `\r\n` (a part) or `--` (the terminator). This skips false hits where the
|
||||||
|
// exact `\r\n--boundary` byte sequence appears INSIDE a file body — the data-integrity case.
|
||||||
|
function findDelim(buf: Buffer, delim: Buffer, from: number): number {
|
||||||
|
let i = buf.indexOf(delim, from);
|
||||||
|
while (i !== -1) {
|
||||||
|
const a = i + delim.length;
|
||||||
|
if ((buf[a] === 0x0d && buf[a + 1] === 0x0a) || (buf[a] === 0x2d && buf[a + 1] === 0x2d)) return i;
|
||||||
|
i = buf.indexOf(delim, i + delim.length); // false hit inside a body — keep searching
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): MultipartBody {
|
||||||
|
const fields: MultipartBody['fields'] = {};
|
||||||
|
const files: MultipartBody['files'] = {};
|
||||||
|
const delim = Buffer.concat([CRLF, Buffer.from(`--${boundary}`)]); // \r\n--boundary
|
||||||
|
// Normalize: prepend CRLF so the FIRST boundary (which a browser sends with no
|
||||||
|
// leading CRLF) is also preceded by the delimiter and isn't dropped as preamble.
|
||||||
|
const buf = Buffer.concat([CRLF, raw]);
|
||||||
|
|
||||||
|
let pos = findDelim(buf, delim, 0);
|
||||||
|
if (pos === -1) throw new Error('Invalid multipart body');
|
||||||
|
let count = 0;
|
||||||
|
while (true) {
|
||||||
|
let start = pos + delim.length;
|
||||||
|
// terminator "--" immediately after the boundary → done
|
||||||
|
if (buf[start] === 0x2d && buf[start + 1] === 0x2d) break;
|
||||||
|
// skip the CRLF that ends the boundary line
|
||||||
|
if (buf[start] === 0x0d && buf[start + 1] === 0x0a) start += 2;
|
||||||
|
const next = findDelim(buf, delim, start);
|
||||||
|
if (next === -1) throw new Error('Invalid multipart body');
|
||||||
|
if (++count > opts.maxParts) throw new Error('Invalid multipart body');
|
||||||
|
const part = buf.subarray(start, next);
|
||||||
|
const sep = part.indexOf('\r\n\r\n');
|
||||||
|
if (sep === -1) throw new Error('Invalid multipart body');
|
||||||
|
const headerText = part.subarray(0, sep).toString('utf8');
|
||||||
|
const partBody = part.subarray(sep + 4);
|
||||||
|
|
||||||
|
let disposition = '';
|
||||||
|
let contentType = '';
|
||||||
|
for (const line of headerText.split('\r\n')) {
|
||||||
|
const c = line.indexOf(':');
|
||||||
|
if (c === -1) continue;
|
||||||
|
const k = line.slice(0, c).trim().toLowerCase();
|
||||||
|
const v = line.slice(c + 1).trim();
|
||||||
|
if (k === 'content-disposition') disposition = v;
|
||||||
|
else if (k === 'content-type') contentType = v;
|
||||||
|
}
|
||||||
|
|
||||||
|
const name = param(disposition, 'name');
|
||||||
|
if (name === undefined) throw new Error('Invalid multipart body');
|
||||||
|
const filename = param(disposition, 'filename');
|
||||||
|
if (filename !== undefined) {
|
||||||
|
if (filename === '' && partBody.length === 0) { pos = next; continue; } // unselected file input
|
||||||
|
addFile(files, name, {
|
||||||
|
filename,
|
||||||
|
contentType: contentType || 'application/octet-stream',
|
||||||
|
data: Buffer.from(partBody), // copy out of the shared buffer
|
||||||
|
size: partBody.length,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
addField(fields, name, partBody.toString('utf8'), opts.duplicates);
|
||||||
|
}
|
||||||
|
pos = next;
|
||||||
|
}
|
||||||
|
return { fields, files };
|
||||||
|
}
|
||||||
+23
-9
@@ -1,12 +1,14 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import type { Ctor } from './metadata';
|
import type { Ctor } from './metadata';
|
||||||
|
import { isStandardSchema, type StandardSchemaV1 } from './standard-schema';
|
||||||
|
import { ValidationError } from './signals';
|
||||||
|
|
||||||
export type Query = Record<string, string>;
|
export type Query = Record<string, string>;
|
||||||
export type Headers = Record<string, string | string[] | undefined>;
|
export type Headers = Record<string, string | string[] | undefined>;
|
||||||
export type Context = Record<string, unknown>;
|
export type Context = Record<string, unknown>;
|
||||||
|
|
||||||
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort';
|
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort';
|
||||||
export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[] }
|
export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[]; schema?: StandardSchemaV1 }
|
||||||
|
|
||||||
const ARGS = Symbol('gt:args');
|
const ARGS = Symbol('gt:args');
|
||||||
|
|
||||||
@@ -21,13 +23,17 @@ function record(target: object, methodKey: string | symbol | undefined, spec: Ar
|
|||||||
}
|
}
|
||||||
|
|
||||||
function envelope(source: ArgSource) {
|
function envelope(source: ArgSource) {
|
||||||
return (arg?: string | string[]): ParameterDecorator =>
|
return (arg?: string | string[] | StandardSchemaV1, schema?: StandardSchemaV1): ParameterDecorator =>
|
||||||
(target, methodKey, index) => {
|
(target, methodKey, index) => {
|
||||||
const spec: ArgSpec = Array.isArray(arg)
|
const spec: ArgSpec = { index, source };
|
||||||
? { index, source, keys: arg }
|
if (Array.isArray(arg)) spec.keys = arg;
|
||||||
: typeof arg === 'string'
|
else if (typeof arg === 'string') spec.key = arg;
|
||||||
? { index, source, key: arg }
|
else if (isStandardSchema(arg)) spec.schema = arg;
|
||||||
: { index, source };
|
else if (arg !== undefined) throw new Error(`@${source}: expected a Standard Schema or a string/array key`);
|
||||||
|
if (schema !== undefined) {
|
||||||
|
if (!isStandardSchema(schema)) throw new Error(`@${source}: second argument must be a Standard Schema`);
|
||||||
|
spec.schema = schema;
|
||||||
|
}
|
||||||
record(target, methodKey, spec);
|
record(target, methodKey, spec);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -62,11 +68,19 @@ export function getHandlerNeeds(specs: ArgSpec[]): string[] {
|
|||||||
return specs.filter((s) => s.source === 'needs' && s.key).map((s) => s.key as string);
|
return specs.filter((s) => s.source === 'needs' && s.key).map((s) => s.key as string);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveArgs(specs: ArgSpec[], context: Context): unknown[] {
|
export async function resolveArgs(specs: ArgSpec[], context: Context): Promise<unknown[]> {
|
||||||
if (specs.length === 0) return [];
|
if (specs.length === 0) return [];
|
||||||
const max = Math.max(...specs.map((s) => s.index));
|
const max = Math.max(...specs.map((s) => s.index));
|
||||||
const args: unknown[] = new Array(max + 1).fill(undefined);
|
const args: unknown[] = new Array(max + 1).fill(undefined);
|
||||||
for (const s of specs) args[s.index] = resolveOne(s, context);
|
for (const s of specs) {
|
||||||
|
let value = resolveOne(s, context);
|
||||||
|
if (s.schema) {
|
||||||
|
const result = await s.schema['~standard'].validate(value);
|
||||||
|
if (result.issues) throw new ValidationError([...result.issues], s.source);
|
||||||
|
value = result.value;
|
||||||
|
}
|
||||||
|
args[s.index] = value;
|
||||||
|
}
|
||||||
return args;
|
return args;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
// src/security.ts — pure header computation, no server deps
|
||||||
|
export interface TlsOptions { key: Buffer | string; cert: Buffer | string; ca?: Buffer | string; passphrase?: string }
|
||||||
|
|
||||||
|
export interface CorsOptions {
|
||||||
|
origins: string | string[] | '*' | ((origin: string) => boolean);
|
||||||
|
methods?: string[];
|
||||||
|
allowedHeaders?: string[];
|
||||||
|
exposedHeaders?: string[];
|
||||||
|
credentials?: boolean;
|
||||||
|
maxAge?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SecurityOptions {
|
||||||
|
hsts?: boolean | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean };
|
||||||
|
frameOptions?: 'SAMEORIGIN' | 'DENY' | false;
|
||||||
|
referrerPolicy?: string | false;
|
||||||
|
noSniff?: boolean;
|
||||||
|
dnsPrefetchControl?: boolean;
|
||||||
|
csp?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Headers = Record<string, string>;
|
||||||
|
const HSTS_DEFAULT_MAXAGE = 15552000; // 180 days
|
||||||
|
|
||||||
|
// scheme "://" host [":" port], or literal "null". Rejects control chars/whitespace.
|
||||||
|
const ORIGIN_RE = /^(?:null|[a-z][a-z0-9+.-]*:\/\/[^\s/?#\x00-\x1f\x7f]+)$/i;
|
||||||
|
export function isValidOrigin(o: string): boolean { return ORIGIN_RE.test(o); }
|
||||||
|
|
||||||
|
export function mergeVary(existing: string | undefined, add: string): string {
|
||||||
|
const parts = (existing ? existing.split(',').map((s) => s.trim()).filter(Boolean) : []);
|
||||||
|
if (!parts.some((p) => p.toLowerCase() === add.toLowerCase())) parts.push(add);
|
||||||
|
return parts.join(', ');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: boolean): Headers {
|
||||||
|
if (opts === false) return {};
|
||||||
|
const o: SecurityOptions = opts === true ? {} : opts;
|
||||||
|
const h: Headers = {};
|
||||||
|
if (o.noSniff !== false) h['x-content-type-options'] = 'nosniff';
|
||||||
|
if (o.frameOptions !== false) h['x-frame-options'] = o.frameOptions ?? 'SAMEORIGIN';
|
||||||
|
if (o.referrerPolicy !== false) h['referrer-policy'] = o.referrerPolicy ?? 'no-referrer';
|
||||||
|
if (o.dnsPrefetchControl !== false) h['x-dns-prefetch-control'] = 'off';
|
||||||
|
if (o.csp) h['content-security-policy'] = o.csp;
|
||||||
|
if (secure && o.hsts !== false) {
|
||||||
|
const hs = o.hsts && o.hsts !== true ? o.hsts : {};
|
||||||
|
let v = `max-age=${hs.maxAge ?? HSTS_DEFAULT_MAXAGE}`;
|
||||||
|
if (hs.includeSubDomains) v += '; includeSubDomains';
|
||||||
|
if (hs.preload) v += '; preload';
|
||||||
|
h['strict-transport-security'] = v;
|
||||||
|
}
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
function originAllowed(spec: CorsOptions['origins'], origin: string): boolean {
|
||||||
|
if (spec === '*') return true;
|
||||||
|
if (typeof spec === 'function') return spec(origin);
|
||||||
|
if (Array.isArray(spec)) return spec.includes(origin);
|
||||||
|
return spec === origin;
|
||||||
|
}
|
||||||
|
|
||||||
|
// req: minimal shape { headers: { origin? } }
|
||||||
|
export function resolveCors(opts: CorsOptions, req: { headers: Record<string, string | string[] | undefined> }): Headers {
|
||||||
|
const h: Headers = {};
|
||||||
|
const raw = req.headers['origin'];
|
||||||
|
const origin = Array.isArray(raw) ? raw[0] : raw;
|
||||||
|
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return h;
|
||||||
|
|
||||||
|
// credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic.
|
||||||
|
if (opts.credentials) {
|
||||||
|
h['access-control-allow-origin'] = origin;
|
||||||
|
h['access-control-allow-credentials'] = 'true';
|
||||||
|
h['vary'] = mergeVary(h['vary'], 'Origin');
|
||||||
|
} else if (opts.origins === '*') {
|
||||||
|
h['access-control-allow-origin'] = '*';
|
||||||
|
} else {
|
||||||
|
h['access-control-allow-origin'] = origin;
|
||||||
|
h['vary'] = mergeVary(h['vary'], 'Origin');
|
||||||
|
}
|
||||||
|
if (opts.exposedHeaders?.length) h['access-control-expose-headers'] = opts.exposedHeaders.join(', ');
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Preflight-specific headers (methods/allowed-headers/max-age). Call only for OPTIONS+ACRM.
|
||||||
|
export function corsPreflightHeaders(opts: CorsOptions, req: { headers: Record<string, string | string[] | undefined> }): Headers {
|
||||||
|
const h = resolveCors(opts, req);
|
||||||
|
if (!h['access-control-allow-origin']) return h; // origin not allowed → bare 204
|
||||||
|
h['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(', ');
|
||||||
|
const reqHdrs = req.headers['access-control-request-headers'];
|
||||||
|
h['access-control-allow-headers'] = opts.allowedHeaders?.join(', ')
|
||||||
|
?? (Array.isArray(reqHdrs) ? reqHdrs.join(', ') : reqHdrs ?? '*');
|
||||||
|
if (opts.maxAge != null) h['access-control-max-age'] = String(opts.maxAge);
|
||||||
|
return h;
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { StandardIssue } from './standard-schema';
|
||||||
|
|
||||||
export class HttpError extends Error {
|
export class HttpError extends Error {
|
||||||
constructor(readonly status: number, message?: string, readonly body?: unknown) {
|
constructor(readonly status: number, message?: string, readonly body?: unknown) {
|
||||||
super(message ?? `HTTP ${status}`);
|
super(message ?? `HTTP ${status}`);
|
||||||
@@ -21,6 +23,12 @@ export class Redirect extends HttpError {
|
|||||||
constructor(readonly location: string) { super(302); }
|
constructor(readonly location: string) { super(302); }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class ValidationError extends HttpError {
|
||||||
|
constructor(public issues: StandardIssue[], public source: string) {
|
||||||
|
super(422, 'Validation failed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function isHttpError(e: unknown): e is HttpError {
|
export function isHttpError(e: unknown): e is HttpError {
|
||||||
return e instanceof HttpError;
|
return e instanceof HttpError;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
// src/standard-schema.ts — vendored Standard Schema (~standard) types + helpers. No imports.
|
||||||
|
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
||||||
|
readonly '~standard': {
|
||||||
|
readonly version: 1;
|
||||||
|
readonly vendor: string;
|
||||||
|
validate(value: unknown): StandardResult<Output> | Promise<StandardResult<Output>>;
|
||||||
|
readonly types?: { readonly input: Input; readonly output: Output };
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export type StandardResult<T> =
|
||||||
|
| { readonly value: T; readonly issues?: undefined }
|
||||||
|
| { readonly issues: ReadonlyArray<StandardIssue> };
|
||||||
|
|
||||||
|
export interface StandardIssue {
|
||||||
|
readonly message: string;
|
||||||
|
readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isStandardSchema(x: unknown): x is StandardSchemaV1 {
|
||||||
|
return (
|
||||||
|
typeof x === 'object' && x !== null &&
|
||||||
|
'~standard' in x &&
|
||||||
|
typeof (x as { ['~standard']?: { validate?: unknown } })['~standard']?.validate === 'function'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function flattenPath(issue: StandardIssue): string {
|
||||||
|
if (!issue.path) return '';
|
||||||
|
return issue.path
|
||||||
|
.map((seg) => (typeof seg === 'object' && seg !== null && 'key' in seg ? seg.key : seg))
|
||||||
|
.map((k) => String(k))
|
||||||
|
.join('.');
|
||||||
|
}
|
||||||
+13
-1
@@ -1,5 +1,6 @@
|
|||||||
import { isHttpError, Redirect } from './signals';
|
import { isHttpError, Redirect, ValidationError } from './signals';
|
||||||
import type { TransformerFn } from './metadata';
|
import type { TransformerFn } from './metadata';
|
||||||
|
import { flattenPath } from './standard-schema';
|
||||||
|
|
||||||
export const JsonTransformer: TransformerFn = (value) => ({
|
export const JsonTransformer: TransformerFn = (value) => ({
|
||||||
status: 200,
|
status: 200,
|
||||||
@@ -8,6 +9,17 @@ export const JsonTransformer: TransformerFn = (value) => ({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export function errorToResponse(e: unknown): { status: number; headers: Record<string, string>; body: string } {
|
export function errorToResponse(e: unknown): { status: number; headers: Record<string, string>; body: string } {
|
||||||
|
if (e instanceof ValidationError) {
|
||||||
|
return {
|
||||||
|
status: 422,
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
error: 'Validation failed',
|
||||||
|
source: e.source,
|
||||||
|
issues: e.issues.map((i) => ({ path: flattenPath(i), message: i.message })),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
if (isHttpError(e)) {
|
if (isHttpError(e)) {
|
||||||
const headers: Record<string, string> = { 'content-type': 'application/json' };
|
const headers: Record<string, string> = { 'content-type': 'application/json' };
|
||||||
if (e instanceof Redirect) headers.location = e.location;
|
if (e instanceof Redirect) headers.location = e.location;
|
||||||
|
|||||||
Vendored
+19
@@ -0,0 +1,19 @@
|
|||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIDJTCCAg2gAwIBAgIUK+VdG3SgV5CP0vc6Yg0JETvNuHYwDQYJKoZIhvcNAQEL
|
||||||
|
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MDcwNjIzNTcwOVoXDTM2MDcw
|
||||||
|
MzIzNTcwOVowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF
|
||||||
|
AAOCAQ8AMIIBCgKCAQEAud6rNrdOg8RgXNb1Kw/94JgUvrVm/5dmaq81/TwHeeRc
|
||||||
|
1AIzj3rJk8KM/ZyHr8FtY0BUMrvun29hQO4F0kV7EOBu8jk/vmu+QscCjwIjpG3U
|
||||||
|
BidYqa7dQay2R8RJVn4knr0bi6/IYYCrUZY+NTHRGbX9saX7DaLePSivmKfO4bsp
|
||||||
|
2TpOkYWCqACeEs0XqIGvsOo7XpX5CYllr5uXz3iqP2P8/FUWXYC/NtwWXuL5Gefj
|
||||||
|
4ltmyx7z0cFpQ9bOu6/z7VvMMHi3tM+HWHKZF29H/q8MeIThp1LWwD4GcSBV+idI
|
||||||
|
fo3waL0utB0xHMZj2Jt9SA11NnyrDyIj7ShuO1BeOQIDAQABo28wbTAdBgNVHQ4E
|
||||||
|
FgQU9sWqlq9NwCrJSgrOvJhNNBFzg90wHwYDVR0jBBgwFoAU9sWqlq9NwCrJSgrO
|
||||||
|
vJhNNBFzg90wDwYDVR0TAQH/BAUwAwEB/zAaBgNVHREEEzARgglsb2NhbGhvc3SH
|
||||||
|
BH8AAAEwDQYJKoZIhvcNAQELBQADggEBAKgkHesXrvwiucQi/0cVFvt3KH/OGfif
|
||||||
|
gqNJvuVxnMPMMWe74ANcd5eOF9YDMjrxEfd2jMKtP0F0EXevLnI94ugQ5FRMJaIp
|
||||||
|
laj2On0rNhxVt+nSWSP4mqj0Sp1lIRGzqz46+vnKZnydM4Q8kgzfwwQeXTMrOgMa
|
||||||
|
ppxWNg+6gnDz1wEvO66M3eLxyaVMO8CFbzs1vahUANMi1lwa8BZiwRx5jhcIFOlh
|
||||||
|
e4gdHPIFQcomuJX75LRry+OEnFOmHGyK1eYs8sT9D9F+TmJHVA51qvp3v7KRdxBS
|
||||||
|
wGWh9ghqzXnyfyCkQgpxJfLJgAMR5j91IGXpSJg5D1ISXyLeqooCyw8=
|
||||||
|
-----END CERTIFICATE-----
|
||||||
Vendored
+28
@@ -0,0 +1,28 @@
|
|||||||
|
-----BEGIN PRIVATE KEY-----
|
||||||
|
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC53qs2t06DxGBc
|
||||||
|
1vUrD/3gmBS+tWb/l2ZqrzX9PAd55FzUAjOPesmTwoz9nIevwW1jQFQyu+6fb2FA
|
||||||
|
7gXSRXsQ4G7yOT++a75CxwKPAiOkbdQGJ1iprt1BrLZHxElWfiSevRuLr8hhgKtR
|
||||||
|
lj41MdEZtf2xpfsNot49KK+Yp87huynZOk6RhYKoAJ4SzReoga+w6jtelfkJiWWv
|
||||||
|
m5fPeKo/Y/z8VRZdgL823BZe4vkZ5+PiW2bLHvPRwWlD1s67r/PtW8wweLe0z4dY
|
||||||
|
cpkXb0f+rwx4hOGnUtbAPgZxIFX6J0h+jfBovS60HTEcxmPYm31IDXU2fKsPIiPt
|
||||||
|
KG47UF45AgMBAAECggEAASvLkTLFTPQRNbHesGivd+QKvhXcrNpqboclPwUgY0P3
|
||||||
|
/Wz4dVxicJV5TRrDScKdUBKxGnMP1+jRfcwndLxJKswjNCWosWgyi29UueEbUjdP
|
||||||
|
7pb+X8P73bn7GbIn/SJv1CE1uc2qefTKf4nZC/2WR0Qb3FaYTEJyWy51BsWd5Sha
|
||||||
|
4XfUzHBldJdZcELCBtwQFJWnqpc1qlnn4Uj9nmD+n7q5t54jqaa67qDhqDScU4DH
|
||||||
|
nguXuH+Cb1zWGsKfoOc//jGWZKX3FJ6nKLHhh4QxxJa/A0VIoqf2lHDfKiJNUqMl
|
||||||
|
BLq78MiFD1SnPXp/024EtEpC5KAS9oSHRusEmDbgAQKBgQDy6j5h9fgI5Bnxjv+E
|
||||||
|
+ASagBSYN4+mszHvZVXtXAl8OZVXkHUKoaco5IPe4/Ysg7WTPVAQAggtbqq/QE15
|
||||||
|
S1sQZyPBmr2ewqQHKNJHMsB0u9AlXOHK3DHVq3+6kM7RGeuuWDvycsM2KHV9pUtA
|
||||||
|
rIg1aMc9NGMkCsaQT2lJeyTOOQKBgQDD4cgK0a4XCot3fW4FaofDUE69TDJwk0Me
|
||||||
|
IneH0BpK3iuSqS/mqjH8ZV6Z5lNVopUGGObnwLtEHZX8q2jakBPa7mCYnulnAsO9
|
||||||
|
WTEZ5oHoN3Gr8O7WJW4LoOOIeci8qPiz58CazhBjK+Qa6/C+rRN0u5hbG3zTEAoS
|
||||||
|
vsjMDYgQAQKBgC8P1OAzwEcwshoLo1OGnZW1RMgs04bvZrhDwL8Iusm3ekiJszNJ
|
||||||
|
GFKi2y2eqr37En2hPlarnhv3OdttwNTEFbN62AGVUjFk8lR0wzCKE6FKFcx3T0N3
|
||||||
|
H6yO2mMx1O/L/s47R/nz5AAlHIYoNQklpAn878Ta1m5QLCIfUH2s/vd5AoGBAL01
|
||||||
|
9i6FNj2pgOiOL11p9vQyOaze0oYtqZKNRprY6NzS2JIVfWC5nAkqvgO5GVxJ7Ntz
|
||||||
|
6G+KmxmD3qKvzFv6+kLrKkGiluBbKkpXwnc7UtbF37Zvx7TxeOggpEjrIn0iVwIo
|
||||||
|
5cJjNC8ncXKT3/u/YWDL6LJwzdVu09whkAKTO5ABAoGBANGHFvW/LCn0R24Xk2lF
|
||||||
|
tFXsj2M5TqjqEeAa37doHPsUx2Bvp/YTpkA6sRKzlHcfyEC/gUKjNaEjIil5836P
|
||||||
|
qjd7abz8xF7STS+9SzGDBEbjKk/IRrBjcYEh9x6kGWqnN6w4wXHsoZyMi/zSP/OG
|
||||||
|
KPTzBQvDzHuVu5n+/a7izTeb
|
||||||
|
-----END PRIVATE KEY-----
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { readFileSync } from 'fs';
|
||||||
|
import { join } from 'path';
|
||||||
|
|
||||||
|
const dir = join(__dirname, '..', 'fixtures');
|
||||||
|
|
||||||
|
export const selfSignedTls = () => ({
|
||||||
|
key: readFileSync(join(dir, 'key.pem')),
|
||||||
|
cert: readFileSync(join(dir, 'cert.pem')),
|
||||||
|
});
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import { describe, it, expect, afterEach } from 'vitest';
|
||||||
|
import { createApp, Route, Post, Module, body } from '../src';
|
||||||
|
|
||||||
|
let app: any;
|
||||||
|
afterEach(async () => { await app?.close(); });
|
||||||
|
|
||||||
|
describe('multipart over http', () => {
|
||||||
|
it('parses fields + a binary file round-trip', async () => {
|
||||||
|
@Route('/') class C {
|
||||||
|
@Post('/upload') up(@body() b: any) {
|
||||||
|
const f = b.files.file;
|
||||||
|
return { name: b.fields.name, filename: f.filename, bytes: [...f.data], type: f.contentType };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
app = createApp({ modules: [CMod] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.set('name', 'joe');
|
||||||
|
const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x00, 0x0d, 0x0a]);
|
||||||
|
fd.set('file', new Blob([bytes], { type: 'image/png' }), 'p.png');
|
||||||
|
const r = await fetch(`http://127.0.0.1:${port}/upload`, { method: 'POST', body: fd });
|
||||||
|
const out = (await r.json()) as any;
|
||||||
|
expect(out.name).toBe('joe');
|
||||||
|
expect(out.filename).toBe('p.png');
|
||||||
|
expect(out.type).toBe('image/png');
|
||||||
|
expect(out.bytes).toEqual([...bytes]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('text/plain body still arrives as a string (fallthrough preserved)', async () => {
|
||||||
|
@Route('/') class C { @Post('/t') t(@body() b: any) { return { isString: typeof b === 'string', b }; } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
app = createApp({ modules: [CMod] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const r = await fetch(`http://127.0.0.1:${port}/t`, {
|
||||||
|
method: 'POST', headers: { 'content-type': 'text/plain' }, body: 'hello' });
|
||||||
|
expect(await r.json()).toEqual({ isString: true, b: 'hello' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('malformed multipart → 400', async () => {
|
||||||
|
@Route('/') class C { @Post('/u') u(@body() b: any) { return b; } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
app = createApp({ modules: [CMod] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const r = await fetch(`http://127.0.0.1:${port}/u`, {
|
||||||
|
method: 'POST', headers: { 'content-type': 'multipart/form-data; boundary=' }, body: 'x' });
|
||||||
|
expect(r.status).toBe(400);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('bodyDuplicates', () => {
|
||||||
|
it('app "array" makes repeated urlencoded fields arrays', async () => {
|
||||||
|
@Route('/') class C { @Post('/f') f(@body() b: any) { return b; } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
app = createApp({ modules: [CMod], bodyDuplicates: 'array' });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const r = await fetch(`http://127.0.0.1:${port}/f`, {
|
||||||
|
method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'x=1&x=2&y=9' });
|
||||||
|
expect(await r.json()).toEqual({ x: ['1', '2'], y: ['9'] });
|
||||||
|
});
|
||||||
|
it('default (no option) keeps urlencoded last-wins', async () => {
|
||||||
|
@Route('/') class C { @Post('/f') f(@body() b: any) { return b; } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
app = createApp({ modules: [CMod] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const r = await fetch(`http://127.0.0.1:${port}/f`, {
|
||||||
|
method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'x=1&x=2' });
|
||||||
|
expect(await r.json()).toEqual({ x: '2' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('per-endpoint override beats app default', async () => {
|
||||||
|
@Route('/') class C {
|
||||||
|
@Post('/a', { duplicates: 'last' }) a(@body() b: any) { return b; }
|
||||||
|
@Post('/b', { duplicates: 'array' }) b2(@body() b: any) { return b; }
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
app = createApp({ modules: [CMod], bodyDuplicates: 'last' });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const post = (p: string) => fetch(`http://127.0.0.1:${port}${p}`, {
|
||||||
|
method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'x=1&x=2' }).then((r) => r.json());
|
||||||
|
expect(await post('/a')).toEqual({ x: '2' });
|
||||||
|
expect(await post('/b')).toEqual({ x: ['1', '2'] });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { parseMultipart, extractBoundary } from '../src/multipart';
|
||||||
|
|
||||||
|
const B = 'X-BOUND';
|
||||||
|
function body(parts: string[]): Buffer {
|
||||||
|
return Buffer.concat([
|
||||||
|
...parts.map((p) => Buffer.from(`--${B}\r\n${p}\r\n`)),
|
||||||
|
Buffer.from(`--${B}--\r\n`),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
const field = (name: string, val: string) => `Content-Disposition: form-data; name="${name}"\r\n\r\n${val}`;
|
||||||
|
const file = (name: string, fn: string, ct: string, data: string) =>
|
||||||
|
`Content-Disposition: form-data; name="${name}"; filename="${fn}"\r\nContent-Type: ${ct}\r\n\r\n${data}`;
|
||||||
|
const opts = { maxParts: 1000, duplicates: 'last' as const };
|
||||||
|
|
||||||
|
describe('extractBoundary', () => {
|
||||||
|
it('plain and quoted', () => {
|
||||||
|
expect(extractBoundary('multipart/form-data; boundary=abc')).toBe('abc');
|
||||||
|
expect(extractBoundary('multipart/form-data; boundary="a b"')).toBe('a b');
|
||||||
|
expect(extractBoundary('multipart/form-data')).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('parseMultipart', () => {
|
||||||
|
it('single text field is NOT lost (first-part off-by-one guard)', () => {
|
||||||
|
const r = parseMultipart(body([field('title', 'hello')]), B, opts);
|
||||||
|
expect(r.fields.title).toBe('hello');
|
||||||
|
});
|
||||||
|
it('multiple distinct fields', () => {
|
||||||
|
const r = parseMultipart(body([field('a', '1'), field('b', '2')]), B, opts);
|
||||||
|
expect(r.fields).toEqual({ a: '1', b: '2' });
|
||||||
|
});
|
||||||
|
it("duplicates 'last' vs 'array'", () => {
|
||||||
|
const b = body([field('t', 'x'), field('t', 'y')]);
|
||||||
|
expect(parseMultipart(b, B, { maxParts: 1000, duplicates: 'last' }).fields.t).toBe('y');
|
||||||
|
expect(parseMultipart(b, B, { maxParts: 1000, duplicates: 'array' }).fields.t).toEqual(['x', 'y']);
|
||||||
|
});
|
||||||
|
it('single file: metadata + exact bytes incl. embedded CRLF and boundary-like text', () => {
|
||||||
|
const payload = 'ab\r\n--X-BOUNDnope\r\ncd';
|
||||||
|
const r = parseMultipart(body([file('doc', 'a.txt', 'text/plain', payload)]), B, opts);
|
||||||
|
const f = r.files.doc as any;
|
||||||
|
expect(f.filename).toBe('a.txt');
|
||||||
|
expect(f.contentType).toBe('text/plain');
|
||||||
|
expect(f.size).toBe(Buffer.byteLength(payload));
|
||||||
|
expect(f.data.toString()).toBe(payload);
|
||||||
|
});
|
||||||
|
it('multiple files same name → array', () => {
|
||||||
|
const r = parseMultipart(body([file('f', '1', 'text/plain', 'a'), file('f', '2', 'text/plain', 'b')]), B, opts);
|
||||||
|
expect(Array.isArray(r.files.f)).toBe(true);
|
||||||
|
expect((r.files.f as any).length).toBe(2);
|
||||||
|
});
|
||||||
|
it('mixed fields + files', () => {
|
||||||
|
const r = parseMultipart(body([field('name', 'joe'), file('avatar', 'p.png', 'image/png', 'PNG')]), B, opts);
|
||||||
|
expect(r.fields.name).toBe('joe');
|
||||||
|
expect((r.files.avatar as any).filename).toBe('p.png');
|
||||||
|
});
|
||||||
|
it('case-insensitive headers + filename-before-name (order independent)', () => {
|
||||||
|
const part = `content-disposition: form-data; filename="z.bin"; name="up"\r\ncontent-type: application/octet-stream\r\n\r\nDATA`;
|
||||||
|
const r = parseMultipart(body([part]), B, opts);
|
||||||
|
expect((r.files.up as any).filename).toBe('z.bin');
|
||||||
|
});
|
||||||
|
it('filename="" with empty body is skipped', () => {
|
||||||
|
const part = `Content-Disposition: form-data; name="up"; filename=""\r\n\r\n`;
|
||||||
|
const r = parseMultipart(body([part]), B, opts);
|
||||||
|
expect(r.files.up).toBeUndefined();
|
||||||
|
});
|
||||||
|
it('malformed → throws: no boundary present', () => {
|
||||||
|
expect(() => parseMultipart(Buffer.from('garbage'), B, opts)).toThrow();
|
||||||
|
});
|
||||||
|
it('malformed → throws: part without name', () => {
|
||||||
|
const part = `Content-Disposition: form-data\r\n\r\nx`;
|
||||||
|
expect(() => parseMultipart(body([part]), B, opts)).toThrow();
|
||||||
|
});
|
||||||
|
it('malformed → throws: part with no header/body separator', () => {
|
||||||
|
const raw = Buffer.from(`--${B}\r\nContent-Disposition: form-data; name="a"\r\n--${B}--\r\n`);
|
||||||
|
expect(() => parseMultipart(raw, B, opts)).toThrow();
|
||||||
|
});
|
||||||
|
it('parts over maxParts → throws', () => {
|
||||||
|
const b = body([field('a', '1'), field('b', '2'), field('c', '3')]);
|
||||||
|
expect(() => parseMultipart(b, B, { maxParts: 2, duplicates: 'last' })).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
+58
-7
@@ -1,6 +1,7 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import { expect, test, describe, it } from 'vitest';
|
import { expect, test, describe, it } from 'vitest';
|
||||||
import { needs, ctx, param, query, inbound, abort, getArgs, getHandlerNeeds, resolveArgs } from '../src/params';
|
import { needs, ctx, param, query, body, inbound, abort, getArgs, getHandlerNeeds, resolveArgs } from '../src/params';
|
||||||
|
import { ValidationError } from '../src/signals';
|
||||||
|
|
||||||
class Ctl {
|
class Ctl {
|
||||||
handler(
|
handler(
|
||||||
@@ -27,13 +28,13 @@ test('getHandlerNeeds extracts only @needs keys', () => {
|
|||||||
expect(getHandlerNeeds(getArgs(Ctl, 'handler'))).toEqual(['user']);
|
expect(getHandlerNeeds(getArgs(Ctl, 'handler'))).toEqual(['user']);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('resolveArgs builds positional args from context', () => {
|
test('resolveArgs builds positional args from context', async () => {
|
||||||
const context = {
|
const context = {
|
||||||
user: { id: 'u1' },
|
user: { id: 'u1' },
|
||||||
params: { id: '7' },
|
params: { id: '7' },
|
||||||
query: { a: '1', b: '2', c: '3' },
|
query: { a: '1', b: '2', c: '3' },
|
||||||
};
|
};
|
||||||
const args = resolveArgs(getArgs(Ctl, 'handler'), context);
|
const args = await resolveArgs(getArgs(Ctl, 'handler'), context);
|
||||||
expect(args[0]).toEqual({ id: 'u1' });
|
expect(args[0]).toEqual({ id: 'u1' });
|
||||||
expect(args[1]).toBe('7');
|
expect(args[1]).toBe('7');
|
||||||
expect(args[2]).toEqual({ a: '1', b: '2', c: '3' });
|
expect(args[2]).toEqual({ a: '1', b: '2', c: '3' });
|
||||||
@@ -41,18 +42,18 @@ test('resolveArgs builds positional args from context', () => {
|
|||||||
expect(args[4]).toBe(context);
|
expect(args[4]).toBe(context);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('a handler with no arg decorators resolves to no args', () => {
|
test('a handler with no arg decorators resolves to no args', async () => {
|
||||||
class Bare { ping() { return 1; } }
|
class Bare { ping() { return 1; } }
|
||||||
expect(resolveArgs(getArgs(Bare, 'ping'), {})).toEqual([]);
|
expect(await resolveArgs(getArgs(Bare, 'ping'), {})).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('@inbound / @abort', () => {
|
describe('@inbound / @abort', () => {
|
||||||
it('resolves inbound and abort from reserved context keys, not as bags', () => {
|
it('resolves inbound and abort from reserved context keys, not as bags', async () => {
|
||||||
class Ctl { handle(@inbound() inc: AsyncIterable<unknown>, @abort() sig: AbortSignal) { return [inc, sig]; } }
|
class Ctl { handle(@inbound() inc: AsyncIterable<unknown>, @abort() sig: AbortSignal) { return [inc, sig]; } }
|
||||||
const specs = getArgs(Ctl, 'handle');
|
const specs = getArgs(Ctl, 'handle');
|
||||||
const ac = new AbortController();
|
const ac = new AbortController();
|
||||||
const inc = (async function* () {})();
|
const inc = (async function* () {})();
|
||||||
const args = resolveArgs(specs, { inbound: inc, abort: ac.signal });
|
const args = await resolveArgs(specs, { inbound: inc, abort: ac.signal });
|
||||||
expect(args[0]).toBe(inc);
|
expect(args[0]).toBe(inc);
|
||||||
expect(args[1]).toBe(ac.signal);
|
expect(args[1]).toBe(ac.signal);
|
||||||
});
|
});
|
||||||
@@ -62,3 +63,53 @@ describe('@inbound / @abort', () => {
|
|||||||
expect(getHandlerNeeds(getArgs(Ctl, 'handle'))).toEqual([]);
|
expect(getHandlerNeeds(getArgs(Ctl, 'handle'))).toEqual([]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const numFromStr = {
|
||||||
|
'~standard': {
|
||||||
|
version: 1 as const, vendor: 'test',
|
||||||
|
validate: (v: unknown) => {
|
||||||
|
const n = Number(v);
|
||||||
|
return Number.isNaN(n) ? { issues: [{ message: 'not a number', path: ['n'] }] } : { value: n };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const asyncSchema = {
|
||||||
|
'~standard': { version: 1 as const, vendor: 'test', validate: async (v: unknown) => ({ value: `async:${v}` }) },
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('resolveArgs validation', () => {
|
||||||
|
it('valid: substitutes the parsed/coerced value; ctx source untouched', async () => {
|
||||||
|
class C { m(@query(numFromStr) _q: number) {} }
|
||||||
|
const specs = getArgs(C, 'm');
|
||||||
|
const ctx: any = { query: '42' };
|
||||||
|
const args = await resolveArgs(specs, ctx);
|
||||||
|
expect(args[0]).toBe(42);
|
||||||
|
expect(ctx.query).toBe('42');
|
||||||
|
});
|
||||||
|
it('invalid: throws ValidationError with source', async () => {
|
||||||
|
class C { m(@body(numFromStr) _b: number) {} }
|
||||||
|
const specs = getArgs(C, 'm');
|
||||||
|
await expect(resolveArgs(specs, { body: 'nope' })).rejects.toBeInstanceOf(ValidationError);
|
||||||
|
await resolveArgs(specs, { body: 'nope' }).catch((e) => { expect(e.source).toBe('body'); expect(e.issues[0].message).toBe('not a number'); });
|
||||||
|
});
|
||||||
|
it('async schema is awaited', async () => {
|
||||||
|
class C { m(@body(asyncSchema) _b: string) {} }
|
||||||
|
const args = await resolveArgs(getArgs(C, 'm'), { body: 'x' });
|
||||||
|
expect(args[0]).toBe('async:x');
|
||||||
|
});
|
||||||
|
it('@param(name, schema) validates the named param (slot-2 schema)', async () => {
|
||||||
|
class C { m(@param('id', numFromStr) _id: number) {} }
|
||||||
|
const args = await resolveArgs(getArgs(C, 'm'), { params: { id: '7' } });
|
||||||
|
expect(args[0]).toBe(7);
|
||||||
|
});
|
||||||
|
it('non-schema decorators unchanged: @body("key"), @body(), @query(["a","b"])', async () => {
|
||||||
|
class C { m(@body('x') _x: any, @body() _b: any, @query(['a', 'b']) _q: any) {} }
|
||||||
|
const args = await resolveArgs(getArgs(C, 'm'), { body: { x: 1, y: 2 }, query: { a: 'A', b: 'B', c: 'C' } });
|
||||||
|
expect(args[0]).toBe(1);
|
||||||
|
expect(args[1]).toEqual({ x: 1, y: 2 });
|
||||||
|
expect(args[2]).toEqual({ a: 'A', b: 'B' });
|
||||||
|
});
|
||||||
|
it('decoration-time guard: a non-schema object throws', () => {
|
||||||
|
expect(() => { class C { m(@body({} as any) _b: any) {} } return C; }).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { buildSecurityHeaders, resolveCors, mergeVary, isValidOrigin } from '../src/security';
|
||||||
|
|
||||||
|
describe('buildSecurityHeaders', () => {
|
||||||
|
it('default set (security:true), no HSTS over insecure', () => {
|
||||||
|
const h = buildSecurityHeaders(true, false);
|
||||||
|
expect(h['x-content-type-options']).toBe('nosniff');
|
||||||
|
expect(h['x-frame-options']).toBe('SAMEORIGIN');
|
||||||
|
expect(h['referrer-policy']).toBe('no-referrer');
|
||||||
|
expect(h['x-dns-prefetch-control']).toBe('off');
|
||||||
|
expect(h['strict-transport-security']).toBeUndefined();
|
||||||
|
});
|
||||||
|
it('HSTS only when secure', () => {
|
||||||
|
const h = buildSecurityHeaders(true, true);
|
||||||
|
expect(h['strict-transport-security']).toBe('max-age=15552000');
|
||||||
|
});
|
||||||
|
it('security:false → empty', () => {
|
||||||
|
expect(buildSecurityHeaders(false, true)).toEqual({});
|
||||||
|
});
|
||||||
|
it('object overrides: disable frameOptions, custom referrer, csp, hsts opts', () => {
|
||||||
|
const h = buildSecurityHeaders({ frameOptions: false, referrerPolicy: 'strict-origin',
|
||||||
|
csp: "default-src 'self'", hsts: { maxAge: 100, includeSubDomains: true } }, true);
|
||||||
|
expect(h['x-frame-options']).toBeUndefined();
|
||||||
|
expect(h['referrer-policy']).toBe('strict-origin');
|
||||||
|
expect(h['content-security-policy']).toBe("default-src 'self'");
|
||||||
|
expect(h['strict-transport-security']).toBe('max-age=100; includeSubDomains');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('resolveCors', () => {
|
||||||
|
const req = (origin?: string) => ({ headers: origin ? { origin } : {} });
|
||||||
|
it('exact-string allowlist echoes origin + Vary', () => {
|
||||||
|
const r = resolveCors({ origins: 'https://a.com' }, req('https://a.com') as any);
|
||||||
|
expect(r['access-control-allow-origin']).toBe('https://a.com');
|
||||||
|
expect(r['vary']).toBe('Origin');
|
||||||
|
});
|
||||||
|
it('disallowed origin → no allow-origin header', () => {
|
||||||
|
const r = resolveCors({ origins: 'https://a.com' }, req('https://evil.com') as any);
|
||||||
|
expect(r['access-control-allow-origin']).toBeUndefined();
|
||||||
|
});
|
||||||
|
it("'*' without credentials returns *", () => {
|
||||||
|
const r = resolveCors({ origins: '*' }, req('https://a.com') as any);
|
||||||
|
expect(r['access-control-allow-origin']).toBe('*');
|
||||||
|
});
|
||||||
|
it('credentials:true never returns * — echoes concrete origin', () => {
|
||||||
|
const r = resolveCors({ origins: '*', credentials: true }, req('https://a.com') as any);
|
||||||
|
expect(r['access-control-allow-origin']).toBe('https://a.com');
|
||||||
|
expect(r['access-control-allow-credentials']).toBe('true');
|
||||||
|
});
|
||||||
|
it('rejects malformed Origin (control char) even if predicate allows', () => {
|
||||||
|
const r = resolveCors({ origins: () => true }, req('https://a.com\r\nX: y') as any);
|
||||||
|
expect(r['access-control-allow-origin']).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isValidOrigin', () => {
|
||||||
|
it('accepts valid origins and literal null', () => {
|
||||||
|
expect(isValidOrigin('https://a.com')).toBe(true);
|
||||||
|
expect(isValidOrigin('http://localhost:3000')).toBe(true);
|
||||||
|
expect(isValidOrigin('null')).toBe(true);
|
||||||
|
});
|
||||||
|
it('rejects CRLF and other control bytes', () => {
|
||||||
|
expect(isValidOrigin('https://a.com\r\nX: y')).toBe(false);
|
||||||
|
expect(isValidOrigin('https://a.com\x00evil')).toBe(false);
|
||||||
|
expect(isValidOrigin('https://a.com\x1bevil')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('mergeVary', () => {
|
||||||
|
it('appends, dedupes, handles empty', () => {
|
||||||
|
expect(mergeVary(undefined, 'Origin')).toBe('Origin');
|
||||||
|
expect(mergeVary('Accept-Encoding', 'Origin')).toBe('Accept-Encoding, Origin');
|
||||||
|
expect(mergeVary('Origin', 'Origin')).toBe('Origin');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { isStandardSchema, flattenPath } from '../src/standard-schema';
|
||||||
|
|
||||||
|
const schema = { '~standard': { version: 1, vendor: 't', validate: (v: unknown) => ({ value: v }) } };
|
||||||
|
|
||||||
|
describe('isStandardSchema', () => {
|
||||||
|
it('true for a Standard Schema, false for string/array/plain object/null', () => {
|
||||||
|
expect(isStandardSchema(schema)).toBe(true);
|
||||||
|
expect(isStandardSchema('id')).toBe(false);
|
||||||
|
expect(isStandardSchema(['a', 'b'])).toBe(false);
|
||||||
|
expect(isStandardSchema({})).toBe(false);
|
||||||
|
expect(isStandardSchema(null)).toBe(false);
|
||||||
|
expect(isStandardSchema({ '~standard': {} })).toBe(false); // no validate fn
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('flattenPath', () => {
|
||||||
|
it('flattens key + {key} segments to a dot string', () => {
|
||||||
|
expect(flattenPath({ message: 'x', path: ['address', 'city'] })).toBe('address.city');
|
||||||
|
expect(flattenPath({ message: 'x', path: ['items', 0, { key: 'qty' }] })).toBe('items.0.qty');
|
||||||
|
expect(flattenPath({ message: 'x' })).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { expect, test } from 'vitest';
|
import { describe, expect, it, test } from 'vitest';
|
||||||
import { JsonTransformer, errorToResponse } from '../src/transformers';
|
import { JsonTransformer, errorToResponse } from '../src/transformers';
|
||||||
import { Unauthorized, Redirect } from '../src/signals';
|
import { HttpError, Unauthorized, Redirect, ValidationError } from '../src/signals';
|
||||||
|
|
||||||
test('JsonTransformer serializes value with json content-type', () => {
|
test('JsonTransformer serializes value with json content-type', () => {
|
||||||
expect(JsonTransformer({ a: 1 })).toEqual({
|
expect(JsonTransformer({ a: 1 })).toEqual({
|
||||||
@@ -21,3 +21,20 @@ test('errorToResponse sets location for Redirect', () => {
|
|||||||
test('unknown error becomes 500', () => {
|
test('unknown error becomes 500', () => {
|
||||||
expect(errorToResponse(new Error('boom')).status).toBe(500);
|
expect(errorToResponse(new Error('boom')).status).toBe(500);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('errorToResponse ValidationError', () => {
|
||||||
|
it('maps ValidationError to 422 with source + flattened issues (before generic HttpError)', () => {
|
||||||
|
const err = new ValidationError([{ message: 'Invalid email', path: ['email'] }], 'body');
|
||||||
|
const r = errorToResponse(err);
|
||||||
|
expect(r.status).toBe(422);
|
||||||
|
expect(JSON.parse(r.body)).toEqual({
|
||||||
|
error: 'Validation failed', source: 'body',
|
||||||
|
issues: [{ path: 'email', message: 'Invalid email' }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it('still maps a plain HttpError to { error: message }', () => {
|
||||||
|
const r = errorToResponse(new HttpError(403, 'Nope'));
|
||||||
|
expect(r.status).toBe(403);
|
||||||
|
expect(JSON.parse(r.body)).toEqual({ error: 'Nope' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
import { describe, it, expect, afterEach } from 'vitest';
|
||||||
|
import https from 'https';
|
||||||
|
import WebSocket from 'ws';
|
||||||
|
import { createApp, Route, Get, Sse, Ws, Module, Transformer, inbound, channel, ctx } from '../src';
|
||||||
|
import { selfSignedTls } from './helpers/tls';
|
||||||
|
|
||||||
|
@Route('/')
|
||||||
|
class Api {
|
||||||
|
@Get('/ping') ping() { return { ok: true }; }
|
||||||
|
@Ws('/echo') echo(@inbound() msgs: AsyncIterable<unknown>) {
|
||||||
|
const out = channel<unknown>();
|
||||||
|
(async () => { for await (const m of msgs) out.push(m); })();
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/', controllers: [Api] })
|
||||||
|
class ApiModule {}
|
||||||
|
|
||||||
|
let app: any;
|
||||||
|
afterEach(async () => { await app?.close(); });
|
||||||
|
|
||||||
|
describe('TLS', () => {
|
||||||
|
it('serves https', async () => {
|
||||||
|
app = createApp({ modules: [ApiModule], tls: selfSignedTls() });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const body = await new Promise<string>((resolve, reject) => {
|
||||||
|
https.get({ port, path: '/ping', rejectUnauthorized: false }, (res) => {
|
||||||
|
let d = ''; res.on('data', (c) => (d += c)); res.on('end', () => resolve(d));
|
||||||
|
}).on('error', reject);
|
||||||
|
});
|
||||||
|
expect(JSON.parse(body)).toEqual({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('upgrades wss on the same server', async () => {
|
||||||
|
app = createApp({ modules: [ApiModule], tls: selfSignedTls() });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const ws = new WebSocket(`wss://127.0.0.1:${port}/echo`, { rejectUnauthorized: false });
|
||||||
|
const got = await new Promise<string>((resolve, reject) => {
|
||||||
|
ws.on('open', () => ws.send('hi'));
|
||||||
|
ws.on('message', (d) => resolve(d.toString()));
|
||||||
|
ws.on('error', reject);
|
||||||
|
});
|
||||||
|
expect(got).toBe('hi');
|
||||||
|
ws.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('trustProxy', () => {
|
||||||
|
it('trustProxy honors X-Forwarded-Proto; ctx exposes protocol/ip', async () => {
|
||||||
|
@Route('/') class P { @Get('/who') who(@ctx() c: any) { return { proto: c.protocol, ip: c.ip }; } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [P] }) class PMod {}
|
||||||
|
app = createApp({ modules: [PMod], trustProxy: true });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const r = await fetch(`http://127.0.0.1:${port}/who`, {
|
||||||
|
headers: { 'x-forwarded-proto': 'https', 'x-forwarded-for': '9.9.9.9' } });
|
||||||
|
expect(await r.json()).toEqual({ proto: 'https', ip: '9.9.9.9' });
|
||||||
|
});
|
||||||
|
it('without trustProxy, forwarded headers are ignored', async () => {
|
||||||
|
@Route('/') class P { @Get('/who') who(@ctx() c: any) { return { proto: c.protocol }; } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [P] }) class PMod {}
|
||||||
|
app = createApp({ modules: [PMod] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const r = await fetch(`http://127.0.0.1:${port}/who`, { headers: { 'x-forwarded-proto': 'https' } });
|
||||||
|
expect(await r.json()).toEqual({ proto: 'http' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('security headers', () => {
|
||||||
|
it('on 200, 404, error; HSTS only when secure', async () => {
|
||||||
|
@Route('/') class S {
|
||||||
|
@Get('/ok') ok() { return { a: 1 }; }
|
||||||
|
@Get('/boom') boom() { throw new Error('x'); }
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [S] }) class SMod {}
|
||||||
|
app = createApp({ modules: [SMod] }); // security defaults on
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const ok = await fetch(`http://127.0.0.1:${port}/ok`);
|
||||||
|
expect(ok.headers.get('x-content-type-options')).toBe('nosniff');
|
||||||
|
expect(ok.headers.get('strict-transport-security')).toBeNull(); // http, not secure
|
||||||
|
const nf = await fetch(`http://127.0.0.1:${port}/nope`);
|
||||||
|
expect(nf.status).toBe(404);
|
||||||
|
expect(nf.headers.get('x-frame-options')).toBe('SAMEORIGIN');
|
||||||
|
const boom = await fetch(`http://127.0.0.1:${port}/boom`);
|
||||||
|
expect(boom.status).toBe(500);
|
||||||
|
expect(boom.headers.get('x-content-type-options')).toBe('nosniff');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('security:false emits none', async () => {
|
||||||
|
@Route('/') class S { @Get('/ok') ok() { return { a: 1 }; } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [S] }) class SMod {}
|
||||||
|
app = createApp({ modules: [SMod], security: false });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const ok = await fetch(`http://127.0.0.1:${port}/ok`);
|
||||||
|
expect(ok.headers.get('x-content-type-options')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('HSTS present over https', async () => {
|
||||||
|
@Route('/') class S { @Get('/ok') ok() { return { a: 1 }; } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [S] }) class SMod {}
|
||||||
|
app = createApp({ modules: [SMod], tls: selfSignedTls() });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const hsts = await new Promise<string | undefined>((resolve, reject) => {
|
||||||
|
https.get({ port, path: '/ok', rejectUnauthorized: false }, (res) => {
|
||||||
|
res.resume();
|
||||||
|
resolve(res.headers['strict-transport-security'] as string | undefined);
|
||||||
|
}).on('error', reject);
|
||||||
|
});
|
||||||
|
expect(hsts).toContain('max-age=');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('injected header wins over a case-variant handler header (no double line)', async () => {
|
||||||
|
@Route('/') class S {
|
||||||
|
@Get('/sneaky')
|
||||||
|
@Transformer((v) => ({ status: 200, headers: { 'X-Content-Type-Options': 'SNIFF' }, body: JSON.stringify(v) }))
|
||||||
|
sneaky() { return { a: 1 }; }
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [S] }) class SMod {}
|
||||||
|
app = createApp({ modules: [SMod] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const res = await fetch(`http://127.0.0.1:${port}/sneaky`);
|
||||||
|
expect(res.headers.get('x-content-type-options')).toBe('nosniff'); // NOT 'SNIFF, nosniff'
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves a handler's Title-Case Vary when no CORS is configured", async () => {
|
||||||
|
@Route('/') class S {
|
||||||
|
@Get('/vary')
|
||||||
|
@Transformer((v) => ({ status: 200, headers: { Vary: 'Accept-Encoding' }, body: JSON.stringify(v) }))
|
||||||
|
vary() { return { a: 1 }; }
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [S] }) class SMod {}
|
||||||
|
app = createApp({ modules: [SMod] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const res = await fetch(`http://127.0.0.1:${port}/vary`);
|
||||||
|
expect(res.headers.get('vary')).toBe('Accept-Encoding');
|
||||||
|
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stream response carries security headers', async () => {
|
||||||
|
@Route('/') class S {
|
||||||
|
@Sse('/stream') async *stream() { yield 'a'; }
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [S] }) class SMod {}
|
||||||
|
app = createApp({ modules: [SMod] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const res = await fetch(`http://127.0.0.1:${port}/stream`, { headers: { accept: 'text/event-stream' } });
|
||||||
|
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
|
||||||
|
await res.body?.cancel();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('CORS', () => {
|
||||||
|
it('echoes allowed origin, sets Vary; preflight 204', async () => {
|
||||||
|
@Route('/') class C { @Get('/x') x() { return { ok: 1 }; } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://a.com' } });
|
||||||
|
expect(r.headers.get('access-control-allow-origin')).toBe('https://a.com');
|
||||||
|
expect(r.headers.get('vary')).toContain('Origin');
|
||||||
|
const pre = await fetch(`http://127.0.0.1:${port}/x`, {
|
||||||
|
method: 'OPTIONS', headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' } });
|
||||||
|
expect(pre.status).toBe(204);
|
||||||
|
expect(pre.headers.get('access-control-allow-methods')).toContain('GET');
|
||||||
|
expect(pre.headers.get('x-content-type-options')).toBe('nosniff'); // security headers on preflight too
|
||||||
|
});
|
||||||
|
|
||||||
|
it('credentials never returns *; echoes concrete origin', async () => {
|
||||||
|
@Route('/') class C { @Get('/x') x() { return { ok: 1 }; } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
app = createApp({ modules: [CMod], cors: { origins: '*', credentials: true } });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://a.com' } });
|
||||||
|
expect(r.headers.get('access-control-allow-origin')).toBe('https://a.com');
|
||||||
|
expect(r.headers.get('access-control-allow-credentials')).toBe('true');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) falls through to 404', async () => {
|
||||||
|
@Route('/') class C { @Get('/x') x() { return { ok: 1 }; } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://evil.com' } });
|
||||||
|
expect(r.headers.get('access-control-allow-origin')).toBeNull();
|
||||||
|
const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' }); // no ACRM
|
||||||
|
expect(bare.status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("merges a handler's Title-Case Vary with CORS's Origin", async () => {
|
||||||
|
@Route('/') class C {
|
||||||
|
@Get('/x')
|
||||||
|
@Transformer((v) => ({ status: 200, headers: { Vary: 'Accept-Encoding' }, body: JSON.stringify(v) }))
|
||||||
|
x() { return { ok: 1 }; }
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://a.com' } });
|
||||||
|
const vary = r.headers.get('vary');
|
||||||
|
expect(vary).toContain('Accept-Encoding');
|
||||||
|
expect(vary).toContain('Origin');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { describe, it, expect, afterEach } from 'vitest';
|
||||||
|
import { createApp, Route, Get, Post, Module, body, query, param } from '../src';
|
||||||
|
|
||||||
|
const numQuery = { '~standard': { version: 1 as const, vendor: 't', validate: (v: any) => {
|
||||||
|
const n = Number(v?.page); return Number.isNaN(n) ? { issues: [{ message: 'bad', path: ['page'] }] } : { value: { page: n } }; } } };
|
||||||
|
const userBody = { '~standard': { version: 1 as const, vendor: 't', validate: (v: any) =>
|
||||||
|
(typeof v?.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'Invalid email', path: ['email'] }] } } };
|
||||||
|
const idParam = { '~standard': { version: 1 as const, vendor: 't', validate: (v: any) => {
|
||||||
|
const n = Number(v); return Number.isNaN(n) ? { issues: [{ message: 'nan', path: [] }] } : { value: n }; } } };
|
||||||
|
|
||||||
|
let app: any;
|
||||||
|
afterEach(async () => { await app?.close(); });
|
||||||
|
|
||||||
|
describe('validation over http', () => {
|
||||||
|
it('valid body → 200 with parsed value; query coerced to number; param coerced', async () => {
|
||||||
|
@Route('/') class C {
|
||||||
|
@Post('/u') create(@body(userBody) b: any) { return { ok: b.email }; }
|
||||||
|
@Get('/list') list(@query(numQuery) q: any) { return { page: q.page, isNum: typeof q.page === 'number' }; }
|
||||||
|
@Get('/u/:id') get(@param('id', idParam) id: any) { return { id, isNum: typeof id === 'number' }; }
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
app = createApp({ modules: [CMod] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const ok = await fetch(`http://127.0.0.1:${port}/u`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: 'a@b.com' }) });
|
||||||
|
expect(await ok.json()).toEqual({ ok: 'a@b.com' });
|
||||||
|
const li = await fetch(`http://127.0.0.1:${port}/list?page=2`);
|
||||||
|
expect(await li.json()).toEqual({ page: 2, isNum: true });
|
||||||
|
const g = await fetch(`http://127.0.0.1:${port}/u/7`);
|
||||||
|
expect(await g.json()).toEqual({ id: 7, isNum: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalid body → 422 with source + issues', async () => {
|
||||||
|
@Route('/') class C { @Post('/u') create(@body(userBody) b: any) { return b; } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
app = createApp({ modules: [CMod] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
const r = await fetch(`http://127.0.0.1:${port}/u`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: 'nope' }) });
|
||||||
|
expect(r.status).toBe(422);
|
||||||
|
expect(await r.json()).toEqual({ error: 'Validation failed', source: 'body', issues: [{ path: 'email', message: 'Invalid email' }] });
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user