diff --git a/src/app.ts b/src/app.ts index 02b9fad..d41aba1 100644 --- a/src/app.ts +++ b/src/app.ts @@ -53,7 +53,7 @@ export interface MeshConfig { timeoutMs?: number; } -export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions }): App { +export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean }): App { const bus = new Bus(); const container = new Container(); let server: http.Server | undefined; @@ -324,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 }, }); }, })), @@ -350,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`); @@ -359,7 +362,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me }, })); - server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls }); + server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy }); 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 6ab2874..345815b 100644 --- a/src/http.ts +++ b/src/http.ts @@ -16,7 +16,7 @@ export interface RequestLimits { headersTimeoutMs?: number; // default 10_000 keepAliveTimeoutMs?: number; // default 5_000 } -export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions } +export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean } export type RouteHandler = (req: { method: string; url: string; @@ -24,6 +24,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 } @@ -82,6 +84,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; @@ -218,11 +233,14 @@ export function createHttpServer( } else if (raw !== undefined && ct.includes('application/x-www-form-urlencoded')) { body = Object.fromEntries(new URLSearchParams(raw)); } + const trustProxy = opts?.trustProxy ?? false; + const secure = deriveSecure(req, trustProxy); let result: PipelineResult; try { 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); diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts index 1372f59..19c0138 100644 --- a/test/transport-security.test.ts +++ b/test/transport-security.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, afterEach } from 'vitest'; import https from 'https'; import WebSocket from 'ws'; -import { createApp, Route, Get, Ws, Module, inbound, channel } from '../src'; +import { createApp, Route, Get, Ws, Module, inbound, channel, ctx } from '../src'; import { selfSignedTls } from './helpers/tls'; @Route('/') @@ -47,3 +47,25 @@ describe('TLS', () => { 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' }); + }); +});