Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tiny-servers-listen.md
Original file line number Diff line number Diff line change
@@ -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.
31 changes: 30 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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.
Expand Down
9 changes: 8 additions & 1 deletion llms.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions packages/webdecoy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
122 changes: 122 additions & 0 deletions packages/webdecoy/src/node-http-guard.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>((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<void>((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)
);
});
});
92 changes: 92 additions & 0 deletions packages/webdecoy/src/node-http-guard.ts
Original file line number Diff line number Diff line change
@@ -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<string, string | string[] | undefined>;
socket: { remoteAddress?: string };
}

export interface NodeHttpGuard {
sdk: WebDecoy;
/** Evaluate a request without reading its body. Skipped paths return undefined. */
check(request: NodeHttpRequest): Promise<NodeHttpGuardOutcome | undefined>;
}

/** 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<string, string> = 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 },
},
};
},
};
}
Loading