diff --git a/docs/quickstart.md b/docs/quickstart.md index 552729c..2f0a365 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -228,6 +228,85 @@ const app = createApp({ modules: [ApiModule], plugins: [logger] }); Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`, `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) | + ## Inspect & test the graph ### Visualize with Mermaid diff --git a/src/app.ts b/src/app.ts index 00a58ef..ecc64fb 100644 --- a/src/app.ts +++ b/src/app.ts @@ -14,6 +14,7 @@ import { import { getArgs, getHandlerNeeds, resolveArgs } from './params'; import { connectLink, type Link } from './mesh/link'; import { Rooms } from './rooms'; +import type { TlsOptions, SecurityOptions, CorsOptions } from './security'; import { buildRemote } from './mesh/teacup'; import { buildManifest, createMeshControl } from './mesh/teapot'; import type { MeshControl } from './http'; @@ -52,7 +53,7 @@ export interface MeshConfig { timeoutMs?: number; } -export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record }): App { +export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions }): App { const bus = new Bus(); const container = new Container(); let server: http.Server | undefined; @@ -323,7 +324,8 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me const provided = await providedSeed(plan); return runPipeline({ 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,8 +351,10 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me pattern: plan.pattern, open: async ({ params, inbound, abort, req }) => { 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, - 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)) }; } const out = plan.run(ctx); if (!isAsyncIterable(out)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`); @@ -358,7 +362,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me }, })); - 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 }); server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } }); await new Promise((resolve) => server!.listen(port, resolve)); return server; diff --git a/src/http.ts b/src/http.ts index adf4252..abc83a5 100644 --- a/src/http.ts +++ b/src/http.ts @@ -1,4 +1,5 @@ import http from 'http'; +import https from 'https'; import { once } from 'events'; import { channel } from './channel'; import { errorToResponse } from './transformers'; @@ -7,6 +8,8 @@ import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders'; import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline'; import type { Transport } from './metadata'; import type { Bus } from './bus'; +import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from './security'; +import type { TlsOptions, SecurityOptions, CorsOptions } from './security'; export interface RequestLimits { maxBodyBytes?: number; // default 1_000_000 @@ -14,7 +17,7 @@ export interface RequestLimits { headersTimeoutMs?: number; // default 10_000 keepAliveTimeoutMs?: number; // default 5_000 } -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 } export type RouteHandler = (req: { method: string; url: string; @@ -22,6 +25,8 @@ export type RouteHandler = (req: { params: Record; query: Record; body: unknown; + protocol: 'http' | 'https'; + ip: string; }) => Promise; export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler } @@ -80,6 +85,19 @@ async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promis 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 { if (transport === 'sse') return sseEncoder; if (transport === 'ndjson') return ndjsonEncoder; @@ -186,9 +204,43 @@ export function createHttpServer( routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions, ): http.Server { 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 => { const url = req.url ?? '/'; 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 = { ...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 | 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 = {}; + 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); if (!matched) { res.writeHead(404, { 'content-type': 'application/json' }); @@ -221,6 +273,7 @@ export function createHttpServer( result = await matched.def.handler({ method: req.method ?? 'GET', url, headers: req.headers, params: matched.params, query: parseQuery(url), body, + protocol: secure ? 'https' : 'http', ip: deriveIp(req, trustProxy), }); } catch (error) { result = errorToResponse(error); @@ -233,7 +286,11 @@ export function createHttpServer( const r: ResponseShape = result; res.writeHead(r.status, r.headers); 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.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; diff --git a/src/index.ts b/src/index.ts index cbaa2e0..28cf546 100644 --- a/src/index.ts +++ b/src/index.ts @@ -24,6 +24,7 @@ export { sseEncoder, ndjsonEncoder } from './encoders'; export type { StreamEncoder } from './encoders'; export type { MeshConfig } from './app'; export type { RequestLimits } from './http'; +export type { TlsOptions, CorsOptions, SecurityOptions } from './security'; export { connectLink } from './mesh/link'; export { buildRemote, envelopeFrom } from './mesh/teacup'; export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot'; diff --git a/src/security.ts b/src/security.ts new file mode 100644 index 0000000..18c58b8 --- /dev/null +++ b/src/security.ts @@ -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; +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 }): 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 }): 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; +} diff --git a/test/fixtures/cert.pem b/test/fixtures/cert.pem new file mode 100644 index 0000000..5131dca --- /dev/null +++ b/test/fixtures/cert.pem @@ -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----- diff --git a/test/fixtures/key.pem b/test/fixtures/key.pem new file mode 100644 index 0000000..278d9ad --- /dev/null +++ b/test/fixtures/key.pem @@ -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----- diff --git a/test/helpers/tls.ts b/test/helpers/tls.ts new file mode 100644 index 0000000..95f5cf5 --- /dev/null +++ b/test/helpers/tls.ts @@ -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')), +}); diff --git a/test/security.test.ts b/test/security.test.ts new file mode 100644 index 0000000..4cba1e9 --- /dev/null +++ b/test/security.test.ts @@ -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'); + }); +}); diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts new file mode 100644 index 0000000..7f880d9 --- /dev/null +++ b/test/transport-security.test.ts @@ -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) { + const out = channel(); + (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((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((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((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'); + }); +});