From 6a828eb7818b13a9dc296dd9f21461ec2fda06ce Mon Sep 17 00:00:00 2001 From: Chris Portscheller Date: Fri, 20 Nov 2026 19:17:26 -0600 Subject: [PATCH] feat(node): add native HTTP request guard --- .changeset/tiny-servers-listen.md | 5 + README.md | 31 ++++- llms.txt | 9 +- packages/webdecoy/src/index.ts | 8 ++ packages/webdecoy/src/node-http-guard.test.ts | 122 ++++++++++++++++++ packages/webdecoy/src/node-http-guard.ts | 92 +++++++++++++ 6 files changed, 265 insertions(+), 2 deletions(-) create mode 100644 .changeset/tiny-servers-listen.md create mode 100644 packages/webdecoy/src/node-http-guard.test.ts create mode 100644 packages/webdecoy/src/node-http-guard.ts diff --git a/.changeset/tiny-servers-listen.md b/.changeset/tiny-servers-listen.md new file mode 100644 index 0000000..63833b3 --- /dev/null +++ b/.changeset/tiny-servers-listen.md @@ -0,0 +1,5 @@ +--- +'@webdecoy/node': minor +--- + +Add a monitor-first guard for native `node:http` servers. Evaluate requests and get a typed enforcement response without consuming the request body or trusting forwarded headers by default. diff --git a/README.md b/README.md index 69e1e2a..6dd093f 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ WebDecoy works alongside Cloudflare and other CDN protections. Server middleware | Next.js | [Next.js middleware](packages/nextjs/README.md) | | Hono, Cloudflare Workers, Bun or Deno | [Hono middleware](packages/hono/README.md) | | Astro, SvelteKit, Remix or another fetch handler | [`createFetchGuard()`](#any-other-fetch-runtime--no-package-needed) | -| A custom Node.js server | [Core SDK](packages/webdecoy/README.md) | +| Native `node:http` server | [`createNodeHttpGuard()`](#native-nodehttp-server) | The middleware starts in **monitor mode**: it records verdicts without blocking requests. A local rules setup needs no cloud connection; an API key is needed to send detections to the WebDecoy dashboard. @@ -206,6 +206,35 @@ export default { }; ``` +### Native `node:http` server + +Use `createNodeHttpGuard()` from `@webdecoy/node` in a plain Node.js server. +The guard defaults to monitor mode and returns the verdict to your handler. + +```typescript +import { createServer } from 'node:http'; +import { createNodeHttpGuard, tripwire } from '@webdecoy/node'; + +const guard = createNodeHttpGuard({ rules: [tripwire()], skipPaths: ['/health'] }); + +createServer(async (req, res) => { + const outcome = await guard.check(req); + if (outcome?.response) { + const { status, headers, body } = outcome.response; + res.writeHead(status, headers).end(JSON.stringify(body)); + return; + } + if (outcome?.decision.deniedBy('tripwire')) { + console.info('Tripwire matched', outcome.decision.id); + } + res.end('OK'); +}).listen(3000); +``` + +The request body stays available to your application. Set `mode: 'enforce'` +once you've reviewed the verdicts. When a trusted reverse proxy sits in front +of your server, configure [`trustProxy`](#client-ip-behind-a-proxy) for that proxy. + ## More local rules Rules run locally (no API key) before any server verification; the first `DENY`/`THROTTLE` wins and short-circuits the request. diff --git a/llms.txt b/llms.txt index 4736f2b..4246710 100644 --- a/llms.txt +++ b/llms.txt @@ -41,7 +41,7 @@ dashboard. ## Packages -- `@webdecoy/node` — core SDK, all rules, `createFetchGuard()` +- `@webdecoy/node` — core SDK, all rules, `createFetchGuard()` and `createNodeHttpGuard()` - `@webdecoy/express` — Express middleware - `@webdecoy/fastify` — Fastify plugin - `@webdecoy/nextjs` — Next.js middleware @@ -61,6 +61,13 @@ or replay application fetch/XHR requests. See packages/client/README.md. For Bun, Deno, Astro, Nitro, SvelteKit or Remix use `createFetchGuard()` from `@webdecoy/node` directly — no adapter package needed. +For a native `node:http` server use `createNodeHttpGuard({ rules, mode, trustProxy, skipPaths })`. +Call `await guard.check(req)` before handling the request. A skipped path returns +`undefined`. Other requests return `decision` and, for enforce-mode refusals, +`response` with `status`, `headers`, and a JSON `body`. The handler writes the +response and still owns the incoming body stream. Forwarded addresses require +explicit `trustProxy` configuration. + ## Rules All local, all keyless unless noted. First DENY or THROTTLE wins. diff --git a/packages/webdecoy/src/index.ts b/packages/webdecoy/src/index.ts index 4de9607..3c9b282 100644 --- a/packages/webdecoy/src/index.ts +++ b/packages/webdecoy/src/index.ts @@ -143,6 +143,14 @@ export type { BlockResponse, HoneytokenArmingOptions } from './adapter-core'; export { createFetchGuard } from './fetch-guard'; export type { FetchGuard, FetchGuardOptions, GuardOutcome } from './fetch-guard'; +export { createNodeHttpGuard } from './node-http-guard'; +export type { + NodeHttpGuard, + NodeHttpGuardOptions, + NodeHttpGuardOutcome, + NodeHttpRequest, +} from './node-http-guard'; + // Rules engine exports export { rateLimit, diff --git a/packages/webdecoy/src/node-http-guard.test.ts b/packages/webdecoy/src/node-http-guard.test.ts new file mode 100644 index 0000000..2de866e --- /dev/null +++ b/packages/webdecoy/src/node-http-guard.test.ts @@ -0,0 +1,122 @@ +import { createServer, request, type IncomingHttpHeaders } from 'node:http'; +import { rateLimit, tripwire } from './rules'; +import { createNodeHttpGuard, type NodeHttpGuard } from './node-http-guard'; + +async function hit( + guard: NodeHttpGuard, + path: string, + headers: IncomingHttpHeaders = {}, + body?: string +) { + const server = createServer(async (req, res) => { + try { + const outcome = await guard.check(req); + if (outcome?.response) { + const { status, headers, body } = outcome.response; + res.writeHead(status, headers).end(JSON.stringify(body)); + return; + } + + let input = ''; + req.setEncoding('utf8'); + for await (const chunk of req) input += chunk; + res.end(JSON.stringify({ conclusion: outcome?.decision.conclusion, input })); + } catch (error) { + res.writeHead(500).end(JSON.stringify({ error: String(error) })); + } + }); + + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', resolve); + }); + try { + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('Missing TCP address'); + return await new Promise<{ status: number; headers: IncomingHttpHeaders; body: string }>( + (resolve, reject) => { + const req = request( + { host: '127.0.0.1', port: address.port, path, headers, method: body ? 'POST' : 'GET' }, + (res) => { + let responseBody = ''; + res.setEncoding('utf8'); + res.on('data', (chunk) => { + responseBody += chunk; + }); + res.on('error', reject); + res.on('end', () => + resolve({ status: res.statusCode ?? 0, headers: res.headers, body: responseBody }) + ); + } + ); + req.on('error', reject); + req.end(body); + } + ); + } finally { + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())) + ); + } +} + +describe('createNodeHttpGuard', () => { + it('reports a tripwire verdict without blocking by default', async () => { + const result = await hit(createNodeHttpGuard({ rules: [tripwire()] }), '/.env'); + expect(result.status).toBe(200); + expect(JSON.parse(result.body)).toMatchObject({ conclusion: 'DENY' }); + }); + + it('produces a JSON denial in enforce mode and skips configured paths', async () => { + const guard = createNodeHttpGuard({ + rules: [tripwire()], + mode: 'enforce', + skipPaths: ['/health'], + }); + const protect = jest.spyOn(guard.sdk, 'protect'); + const blocked = await hit(guard, '/.env'); + expect(blocked.status).toBe(403); + expect(blocked.headers['content-type']).toBe('application/json'); + expect(JSON.parse(blocked.body)).toMatchObject({ + rule: 'tripwire', + detection_id: expect.any(String), + }); + expect((await hit(guard, '/health?probe=1')).status).toBe(200); + expect(protect).toHaveBeenCalledTimes(1); + }); + + it('responds with Retry-After and ignores untrusted forwarded addresses', async () => { + const guard = createNodeHttpGuard({ + rules: [rateLimit({ max: 1, window: 60 })], + mode: 'enforce', + }); + expect((await hit(guard, '/', { 'x-forwarded-for': '192.0.2.1' })).status).toBe(200); + const limited = await hit(guard, '/', { 'x-forwarded-for': '192.0.2.2' }); + expect(limited.status).toBe(429); + expect(Number(limited.headers['retry-after'])).toBeGreaterThan(0); + }); + + it('preserves the raw target and body stream and resolves an explicitly trusted proxy', async () => { + const guard = createNodeHttpGuard({ trustProxy: 1 }); + const protect = jest.spyOn(guard.sdk, 'protect'); + const result = await hit( + guard, + 'http://example.test/raw/%2Fpath?q=one?two', + { + 'x-forwarded-for': '192.0.2.1, 198.51.100.3', + }, + 'incoming body' + ); + expect(result.status).toBe(200); + expect(JSON.parse(result.body).input).toBe('incoming body'); + expect(protect).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'POST', + path: '/raw/%2Fpath', + query: 'q=one?two', + ip: '198.51.100.3', + }), + expect.any(Object) + ); + }); +}); diff --git a/packages/webdecoy/src/node-http-guard.ts b/packages/webdecoy/src/node-http-guard.ts new file mode 100644 index 0000000..6307645 --- /dev/null +++ b/packages/webdecoy/src/node-http-guard.ts @@ -0,0 +1,92 @@ +import { ruleBlockResponse, shouldSkipPath, type BlockResponse } from './adapter-core'; +import { normalizeIp, resolveClientIp, type TrustedProxies } from './client-ip'; +import type { Decision } from './decision'; +import { WebDecoy } from './sdk'; +import type { ProtectOptions, RequestMetadata, WebDecoyConfig } from './types'; + +export interface NodeHttpGuardOptions extends WebDecoyConfig, ProtectOptions { + /** Monitor serves the request even when the SDK reports a denial. */ + mode?: 'monitor' | 'enforce'; + /** Paths excluded from evaluation, such as health checks. */ + skipPaths?: (string | RegExp)[]; + /** Defaults to the connection peer. Set this to trust a known proxy chain. */ + trustProxy?: TrustedProxies; +} + +export interface NodeHttpGuardOutcome { + decision: Decision; + /** Present when enforce mode refuses the request. The caller writes it. */ + response?: BlockResponse; +} + +/** The request fields read from Node's IncomingMessage. */ +export interface NodeHttpRequest { + method?: string; + url?: string; + headers: Record; + socket: { remoteAddress?: string }; +} + +export interface NodeHttpGuard { + sdk: WebDecoy; + /** Evaluate a request without reading its body. Skipped paths return undefined. */ + check(request: NodeHttpRequest): Promise; +} + +/** Evaluate native Node HTTP requests with the same rules as the framework adapters. */ +export function createNodeHttpGuard(options: NodeHttpGuardOptions = {}): NodeHttpGuard { + const sdk = new WebDecoy(options); + const mode = options.mode ?? 'monitor'; + const protectOptions: ProtectOptions = { + threshold: options.threshold, + skipLocalAnalysis: options.skipLocalAnalysis, + metadata: options.metadata, + }; + + return { + sdk, + async check(request) { + // Strip an absolute-form authority without changing the raw path encoding. + const target = (request.url ?? '/').replace(/^https?:\/\/[^/?#]+/i, ''); + const queryStart = target.indexOf('?'); + const path = (queryStart === -1 ? target : target.slice(0, queryStart)) || '/'; + const query = queryStart === -1 ? undefined : target.slice(queryStart + 1); + if (shouldSkipPath(path, options.skipPaths)) return undefined; + + const headers: Record = Object.create(null); + for (const [name, value] of Object.entries(request.headers)) { + if (value !== undefined) headers[name] = Array.isArray(value) ? value.join(', ') : value; + } + const peer = request.socket.remoteAddress; + const metadata: RequestMetadata = { + method: request.method ?? 'GET', + path, + query, + headers, + user_agent: headers['user-agent'], + ip: + resolveClientIp({ headers, peer, trustProxy: options.trustProxy }) ?? + normalizeIp(peer) ?? + '127.0.0.1', + timestamp: Date.now(), + }; + + const decision = await sdk.protect(metadata, protectOptions); + if (decision.allowed || mode !== 'enforce') return { decision }; + + const block = ruleBlockResponse(decision) ?? { + status: 403, + headers: {}, + body: { error: 'Forbidden', message: 'Access denied by WebDecoy protection' }, + }; + return { + decision, + response: { + status: block.status, + headers: { 'content-type': 'application/json', ...block.headers }, + body: { ...block.body, detection_id: decision.id }, + }, + }; + }, + }; +}