diff --git a/CHANGELOG.md b/CHANGELOG.md index c858d3c..1fb7810 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **One Vercel middleware for detection and clearance.** `@webdecoy/nextjs/vercel` (new) and `@webdecoy/node/vercel` now run detection and the clearance gate in one middleware, configured from `WEBDECOY_API_KEY`, `WEBDECOY_SITE_KEY`, `WEBDECOY_SCANNER_ID` and `WEBDECOY_SENSOR_KEY`. With the API key set, bots are reported to your dashboard, including the reserved test trigger (`curl -A "WebDecoy-Test/1.0"`), so Astro, SvelteKit, Nuxt and other frameworks on Vercel get detections from middleware alone. Detection starts in monitor mode, and a request the gate refuses, or would refuse, is still reported with the match key that labels its detection. Without `WEBDECOY_API_KEY`, `@webdecoy/node/vercel` is the clearance gate exactly as before; with nothing set, every request passes. `createVercelMiddleware(options)` in both packages customizes it, and `createDetectAndGate()` in `@webdecoy/node` is the framework-free core. + + ```ts + // Next.js: middleware.ts, or proxy.ts on Next.js 16 + import webdecoy from '@webdecoy/nextjs/vercel'; + export default webdecoy; + export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] }; + ``` + + Next.js 16 fails the build on `export { default } from '@webdecoy/nextjs/vercel'` (it does not follow the re-export when checking for a default export), so import then export. + +### Changed + +- **Agents the bot registry names are reported to WebDecoy by every adapter**, even when they send browser-like headers. Assistants that fetch a page for a person, such as ChatGPT-User, match none of the generic bot patterns, so local analysis used to treat them as browsers and report nothing. + +### Fixed + +- **`@webdecoy/node/vercel`, `@webdecoy/node/testing` and `@webdecoy/nextjs/vercel` resolve their types under `"moduleResolution": "node"`**, through `typesVersions`, as well as under `bundler` and `node16`. + ## [0.21.3] - 2026-11-10 ### Fixed diff --git a/packages/nextjs/README.md b/packages/nextjs/README.md index d2f2c7b..d0ef598 100644 --- a/packages/nextjs/README.md +++ b/packages/nextjs/README.md @@ -13,7 +13,47 @@ npm install @webdecoy/nextjs @webdecoy/node `@webdecoy/node` is the core SDK. Install it directly: rules such as `tripwire()` and `rateLimit()` are imported from it. Requires Next.js 13 or later. -## Quick start: detection middleware +## Quick start on Vercel: one middleware, from the environment + +Detection and clearance enforcement in one file, configured entirely by environment variables: + +```ts +// middleware.ts (Next.js 13-15), or proxy.ts (Next.js 16) +import webdecoy from '@webdecoy/nextjs/vercel'; + +export default webdecoy; + +export const config = { + // Everything but static assets. Keep /.well-known: the challenge uses it. + matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'], +}; +``` + +Write it as import then export. Next.js 16 does not follow `export { default } from '@webdecoy/nextjs/vercel'` when it checks the file for a default export, and fails the build. `config` must be declared in the file itself. + +| Variable | Turns on | Secret? | +|---|---|---| +| `WEBDECOY_API_KEY` | Detection: bots, tripwire hits and agents the bot registry names are reported to your dashboard. From the **API Keys** page. | Yes | +| `WEBDECOY_SITE_KEY`, `WEBDECOY_SCANNER_ID` | The clearance gate, with the sensor key. From **Enforcement, Setup**. | No | +| `WEBDECOY_SENSOR_KEY` | The clearance gate. From **Enforcement, Setup**. | Yes | + +Either half works without the other; with neither, every request passes. Detection starts in monitor mode and passes its verdict to your app as request headers (see [Monitor mode](#monitor-mode)); the gate follows the site's mode in WebDecoy, monitor until you switch it, and hands the page its verdict as `x-wd-clearance` (read it with `getEdgeVerdict()`). Every failure, WebDecoy unreachable included, lets the request through. + +To customize, use `createVercelMiddleware(options)` from the same path. It takes the core SDK options (`apiKey`, `rules`, `threatScoreThreshold`, ...), `mode`, `skipPaths`, `trustProxy`, `onBlocked` as `(request, decision) => Response`, and the gate's `siteKey`, `scannerId`, `sensorKey` and `ingest`; the key and the gate's identity come from the environment when not passed. + +```ts +// middleware.ts +import { createVercelMiddleware } from '@webdecoy/nextjs/vercel'; +import { tripwire } from '@webdecoy/node'; + +export default createVercelMiddleware({ + rules: [tripwire({ paths: ['/admin-backup.zip'] })], +}); + +export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] }; +``` + +## Detection middleware ```ts // middleware.ts (project root, or src/ if you use it) @@ -31,7 +71,7 @@ export const config = { ### API key -`apiKey` is optional. Without it the middleware runs local rules only (the built-in tripwire paths by default) and nothing reports to your dashboard. The middleware does **not** read `WEBDECOY_API_KEY` from the environment by itself: pass it as `apiKey`, as above. +`apiKey` is optional. Without it the middleware runs local rules only (the built-in tripwire paths by default) and nothing reports to your dashboard. `withWebDecoy` does **not** read `WEBDECOY_API_KEY` from the environment by itself: pass it as `apiKey`, as above. (`@webdecoy/nextjs/vercel` does read it.) To get a key: sign up at [app.webdecoy.com](https://app.webdecoy.com), add your site, then create a key on the **API Keys** page. Keys start with `sk_live_` or `sk_test_`. Set it in your deployment's environment (for example the Vercel project settings), never in committed code. @@ -109,7 +149,7 @@ export const config = { If any of the first three is missing, the gate passes every request and logs a warning once. Guide: [Vercel middleware](https://docs.webdecoy.com/installation/vercel-middleware/). -A project has one `middleware.ts`, so choose `withWebDecoy` or `withClearance` for it. +A project has one `middleware.ts`. `@webdecoy/nextjs/vercel` runs detection and the gate together; `withWebDecoy` and `withClearance` are each one half. ## Pages Router API routes @@ -140,7 +180,7 @@ It reads the socket address and trusts no forwarding header unless you pass `tru ## Environment variables -Only `withClearance()` reads environment variables (table above). `WEBDECOY_API_KEY` and `WEBDECOY_SECRET` are naming conventions: pass their values as `apiKey` and `secret`. +`@webdecoy/nextjs/vercel` reads `WEBDECOY_API_KEY` and the clearance variables; `withClearance()` reads the clearance variables (table above). Elsewhere `WEBDECOY_API_KEY` and `WEBDECOY_SECRET` are naming conventions: pass their values as `apiKey` and `secret`. ## Verify the install diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 4e4d05f..898e494 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -9,18 +9,30 @@ "require": "./dist/index.js", "import": "./dist/index.mjs", "types": "./dist/index.d.ts" + }, + "./vercel": { + "require": "./dist/vercel.js", + "import": "./dist/vercel.mjs", + "types": "./dist/vercel.d.ts" + } + }, + "typesVersions": { + "*": { + "vercel": [ + "./dist/vercel.d.ts" + ] } }, "files": [ "dist" ], "scripts": { - "build": "tsup src/index.ts --format cjs,esm --dts --clean", - "dev": "tsup src/index.ts --format cjs,esm --dts --watch", + "build": "tsup src/index.ts src/vercel.ts --format cjs,esm --dts --clean", + "dev": "tsup src/index.ts src/vercel.ts --format cjs,esm --dts --watch", "test": "jest --passWithNoTests", "lint": "eslint src --max-warnings 2", "clean": "rm -rf dist", - "check:edge": "node ../../scripts/check-edge.mjs src/index.ts" + "check:edge": "node ../../scripts/check-edge.mjs src/index.ts src/vercel.ts" }, "keywords": [ "web-decoy", diff --git a/packages/nextjs/src/vercel.test.ts b/packages/nextjs/src/vercel.test.ts new file mode 100644 index 0000000..3e8924b --- /dev/null +++ b/packages/nextjs/src/vercel.test.ts @@ -0,0 +1,130 @@ +import { NextRequest } from 'next/server'; +import middleware, { createVercelMiddleware } from './vercel'; +import { getEdgeVerdict } from './edge-verdict'; + +/** + * @webdecoy/nextjs/vercel: detection and the clearance gate from the + * environment. The combination is @webdecoy/node's and tested there; what is + * tested here is what the Next.js application and the visitor receive. + */ + +const ENV_NAMES = ['WEBDECOY_API_KEY', 'WEBDECOY_SITE_KEY', 'WEBDECOY_SCANNER_ID', 'WEBDECOY_SENSOR_KEY']; +const ENV = { + WEBDECOY_API_KEY: 'sk_test_next', + WEBDECOY_SITE_KEY: 'org-1', + WEBDECOY_SCANNER_ID: 'scanner-1', + WEBDECOY_SENSOR_KEY: 'wds1.test', +}; + +const CONFIG = { + mode: 'monitor', + allow: { search_engines: true, ai_crawlers: true, monitoring: true }, + keys: [], + active_credentials: [], + denied_fps: [], + generated_at: 0, + routes: ['/docs/*'], +}; + +const realFetch = global.fetch; +let hosts = 0; +const site = () => `https://nextvercel${++hosts}.example`; +let calls: string[] = []; + +beforeEach(() => { + calls = []; + global.fetch = jest.fn(async (input: RequestInfo | URL) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url; + calls.push(url); + if (url.includes('/api/v1/clearance/config')) return new Response(JSON.stringify(CONFIG), { status: 200 }); + if (url.includes('/api/v1/sdk/detect')) { + return new Response( + JSON.stringify({ decision: 'block', confidence: 100, threat_level: 'HIGH', bot_detected: true, detection_id: 'det-n' }), + { status: 200 } + ); + } + return new Response('{}', { status: 200 }); + }) as unknown as typeof fetch; +}); + +beforeAll(() => { + jest.useFakeTimers({ advanceTimers: true }); +}); + +afterAll(() => { + jest.clearAllTimers(); + jest.useRealTimers(); +}); + +afterEach(() => { + global.fetch = realFetch; + for (const name of ENV_NAMES) delete process.env[name]; +}); + +function forwarded(res: Response): Headers { + expect(res.headers.get('x-middleware-next')).toBe('1'); + const out = new Headers(); + for (const name of (res.headers.get('x-middleware-override-headers') ?? '').split(',').filter(Boolean)) { + out.set(name, res.headers.get(`x-middleware-request-${name}`) ?? ''); + } + return out; +} + +describe('@webdecoy/nextjs/vercel', () => { + it('the default export reports WebDecoy-Test/1.0 from env and labels the would-block verdict', async () => { + Object.assign(process.env, ENV); + const res = await middleware( + new NextRequest(`${site()}/docs/start`, { headers: { accept: 'text/html', 'user-agent': 'WebDecoy-Test/1.0' } }) + ); + expect(calls.filter((u) => u.includes('/api/v1/sdk/detect'))).toHaveLength(1); + const headers = forwarded(res); + expect(headers.get('x-webdecoy-would-block')).toBe('true'); + expect(headers.get('x-webdecoy-detection-id')).toBe('det-n'); + // The gate ran on the same request: a protected path with no token, monitor mode. + expect(getEdgeVerdict(headers).clearance).toBe('missing'); + // Neither verdict is sent back to the visitor. + expect(res.headers.get('x-wd-clearance')).toBeNull(); + expect(res.headers.get('x-webdecoy-would-block')).toBeNull(); + }); + + it('fails open and never throws with no environment at all', async () => { + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + const res = await middleware( + new NextRequest(`${site()}/docs/start`, { headers: { 'user-agent': 'WebDecoy-Test/1.0' } }) + ); + expect(res.status).not.toBe(403); + expect(calls).toHaveLength(0); + warn.mockRestore(); + }); + + it('without WEBDECOY_API_KEY runs the gate alone and reports nothing', async () => { + Object.assign(process.env, { ...ENV, WEBDECOY_API_KEY: '' }); + const res = await middleware(new NextRequest(`${site()}/docs/start`, { headers: { accept: 'text/html' } })); + expect(calls.some((u) => u.includes('/api/v1/sdk/detect'))).toBe(false); + expect(forwarded(res).get('x-wd-clearance')).toBe('missing'); + }); + + it('createVercelMiddleware takes options instead of the environment', async () => { + const res = await createVercelMiddleware({ + apiKey: ENV.WEBDECOY_API_KEY, + siteKey: 'org-1', + scannerId: 'scanner-1', + sensorKey: 'wds1.test', + mode: 'enforce', + })(new NextRequest(`${site()}/`, { headers: { 'user-agent': 'WebDecoy-Test/1.0' } })); + expect(res.status).toBe(403); + }); + + it('fails open when WebDecoy is unreachable', async () => { + Object.assign(process.env, ENV); + global.fetch = jest.fn(async () => { + throw new TypeError('fetch failed'); + }) as unknown as typeof fetch; + const error = jest.spyOn(console, 'error').mockImplementation(() => undefined); + const res = await middleware( + new NextRequest(`${site()}/docs/start`, { headers: { 'user-agent': 'python-requests/2.31' } }) + ); + expect(res.status).not.toBe(403); + error.mockRestore(); + }); +}); diff --git a/packages/nextjs/src/vercel.ts b/packages/nextjs/src/vercel.ts new file mode 100644 index 0000000..2cc18c2 --- /dev/null +++ b/packages/nextjs/src/vercel.ts @@ -0,0 +1,86 @@ +/** + * WebDecoy for Next.js on Vercel: detection and the clearance gate in one + * middleware, configured from the environment. + * + * @example + * ```typescript + * // middleware.ts (Next.js 13-15), or proxy.ts (Next.js 16) + * import webdecoy from '@webdecoy/nextjs/vercel'; + * + * export default webdecoy; + * + * export const config = { + * // Everything but static assets. Keep /.well-known: the challenge uses it. + * matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'], + * }; + * ``` + * + * Import then export, rather than `export { default } from ...`: Next.js 16 + * looks for the default export without following a re-export and fails the + * build on that one-line form, in `proxy.ts` and `middleware.ts` alike. And + * `config` has to be written in the file itself, because Next reads it + * statically. + * + * Environment: + * + * - `WEBDECOY_API_KEY` turns on detection: bots are reported to WebDecoy, + * including the reserved test trigger (`curl -A "WebDecoy-Test/1.0" ...`), + * and the verdict reaches the app as request headers + * (`x-webdecoy-decision`, `x-webdecoy-detection-id`, `x-webdecoy-would-block`). + * - `WEBDECOY_SITE_KEY`, `WEBDECOY_SCANNER_ID` and `WEBDECOY_SENSOR_KEY` turn + * on the clearance gate for the paths the site protects in WebDecoy; the + * page receives its verdict as `x-wd-clearance` (see `getEdgeVerdict()`). + * + * Either half works without the other; with neither, every request passes. + * Detection starts in monitor mode and the gate follows the site's mode in + * WebDecoy (monitor by default), so installing this changes no response until + * you choose to enforce. Every failure lets the request through. + * + * To customize, use {@link createVercelMiddleware}: + * + * ```typescript + * // middleware.ts + * import { createVercelMiddleware } from '@webdecoy/nextjs/vercel'; + * import { tripwire } from '@webdecoy/node'; + * + * export default createVercelMiddleware({ + * rules: [tripwire({ paths: ['/admin-backup.zip'] })], + * }); + * + * export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] }; + * ``` + */ + +import { NextResponse } from 'next/server'; +import type { NextRequest, NextFetchEvent } from 'next/server'; +import { createDetectAndGate } from '@webdecoy/node'; +import type { DetectAndGateOptions } from '@webdecoy/node'; + +export type { DetectAndGateOptions } from '@webdecoy/node'; + +/** + * Detection and the clearance gate as Next.js middleware. Options default to + * the environment (`WEBDECOY_API_KEY`, `WEBDECOY_SITE_KEY`, + * `WEBDECOY_SCANNER_ID`, `WEBDECOY_SENSOR_KEY`). + */ +export function createVercelMiddleware( + options: DetectAndGateOptions = {} +): (req: NextRequest, event?: NextFetchEvent) => Promise { + const decide = createDetectAndGate(options); + return async (req, event) => { + try { + const { outcome } = await decide(req, { + waitUntil: event ? (p) => event.waitUntil(p) : undefined, + }); + if (outcome.action === 'respond') return outcome.response; + if (!outcome.headers) return NextResponse.next(); + return NextResponse.next({ request: { headers: outcome.headers } }); + } catch { + return NextResponse.next(); // fail open + } + }; +} + +/** The middleware configured from WEBDECOY_* environment variables. */ +const middleware = createVercelMiddleware(); +export default middleware; diff --git a/packages/webdecoy/README.md b/packages/webdecoy/README.md index 39a9b3f..27a38a2 100644 --- a/packages/webdecoy/README.md +++ b/packages/webdecoy/README.md @@ -58,7 +58,7 @@ Behind a proxy, `req.socket.remoteAddress` is the proxy. Use `resolveClientIp()` `apiKey` is optional. Without it the SDK runs **local rules only** (tripwires by default, plus any rules you add), makes no network calls, and reports nothing to the dashboard. With it, the SDK also sends suspicious requests for server-side detection and reports rule hits to your dashboard. -The SDK does **not** read `WEBDECOY_API_KEY` from the environment by itself. Pass it as `apiKey`, as above. +`new WebDecoy()` does **not** read `WEBDECOY_API_KEY` from the environment by itself (only the Vercel middleware does). Pass it as `apiKey`, as above. To get a key: sign up at [app.webdecoy.com](https://app.webdecoy.com), add your site, then create a key on the **API Keys** page. Keys start with `sk_live_` (production) or `sk_test_` (testing); any other prefix throws when the SDK is constructed. Keep the key on the server and out of committed files. @@ -146,16 +146,35 @@ export default { Options: everything in [Configuration](#configuration), plus `mode` (default `'monitor'`), `skipPaths`, `trustProxy` (default `1`), `getIP`, `honeytoken` (default on when an `apiKey` is set; injects a hidden trap link into HTML through `decorate()`) and `onBlocked`. -## Clearance enforcement on Vercel +## Vercel middleware: detection and clearance -With a WebDecoy account, the paths you protect can require a clearance token, checked in Vercel Routing Middleware before the page renders. It follows the site's mode in WebDecoy (monitor until you switch it) and fails open. +One Routing Middleware file for Astro, SvelteKit, Nuxt, Remix or a static site on Vercel. It reports bots to WebDecoy and runs the clearance gate on the paths you protect, both configured from the project's environment. ```ts -// middleware.ts (Astro, SvelteKit, Nuxt, Remix or a static site) +// middleware.ts (project root) export { default } from '@webdecoy/node/vercel'; + +export const config = { + // Everything but static assets. Keep /.well-known: the challenge uses it. + matcher: ['/((?!_astro/|_next/static/|favicon.ico|.*\\.(?:css|js|png|jpg|svg|webp|woff2?)$).*)'], +}; ``` -Next.js sites use `withClearance()` from `@webdecoy/nextjs` instead. Set `WEBDECOY_SITE_KEY`, `WEBDECOY_SCANNER_ID` and `WEBDECOY_SENSOR_KEY` (a secret) from **Enforcement, Setup** in the dashboard. Guide: [Vercel middleware](https://docs.webdecoy.com/installation/vercel-middleware/). +| Variable | Turns on | Secret? | +|---|---|---| +| `WEBDECOY_API_KEY` | Detection: bots, tripwire hits and agents the bot registry names are reported to your dashboard. From the **API Keys** page. | Yes | +| `WEBDECOY_SITE_KEY`, `WEBDECOY_SCANNER_ID` | The clearance gate, with the sensor key. From **Enforcement, Setup**. | No | +| `WEBDECOY_SENSOR_KEY` | The clearance gate. From **Enforcement, Setup**. | Yes | + +Either half works without the other; with neither, every request passes. Detection starts in monitor mode (the request is served and the verdict rides on the request as `x-webdecoy-decision`, `x-webdecoy-detection-id` and `x-webdecoy-would-block`), and the gate follows the site's mode in WebDecoy, monitor until you switch it. Every failure, WebDecoy unreachable included, lets the request through. Without `WEBDECOY_API_KEY` the middleware is the clearance gate alone, exactly as before. + +To customize it, use `createVercelMiddleware(options)` from `@webdecoy/node/vercel`: it takes the core [Configuration](#configuration) options (`rules`, `threatScoreThreshold`, ...), `mode`, `skipPaths`, `trustProxy` and the gate's `siteKey`, `scannerId`, `sensorKey` and `ingest`, each defaulting to the environment. `clearanceMiddleware()` is the gate alone. Next.js sites use `@webdecoy/nextjs/vercel`, the same middleware in Next's types. Guide: [Vercel middleware](https://docs.webdecoy.com/installation/vercel-middleware/). + +Verify it with the reserved test User-Agent; a detection labeled **Test** appears within a few seconds: + +```bash +curl -A "WebDecoy-Test/1.0" https://your-site.vercel.app/ +``` ## Environment variables @@ -163,11 +182,12 @@ The SDK reads only these, and only in the features named: | Variable | Read by | |---|---| +| `WEBDECOY_API_KEY` | The Vercel middleware (`@webdecoy/node/vercel`, `createDetectAndGate()`), when `apiKey` is not passed. | | `WEBDECOY_SITE_KEY`, `WEBDECOY_SCANNER_ID`, `WEBDECOY_SENSOR_KEY` | The clearance gate (`@webdecoy/node/vercel`, `createClearanceGate()`), when the matching option is not passed. | | `WEBDECOY_INGEST` | The clearance gate, to override its ingest endpoint. Optional. | | `NODE_ENV` | The self-hosted captcha: with `production`, a missing or default `secret` throws. | -`WEBDECOY_API_KEY` is a naming convention used in these docs, not something the SDK reads. +Everywhere else `WEBDECOY_API_KEY` is a naming convention used in these docs: pass its value as `apiKey`. ## Configuration diff --git a/packages/webdecoy/package.json b/packages/webdecoy/package.json index 8b55173..9943869 100644 --- a/packages/webdecoy/package.json +++ b/packages/webdecoy/package.json @@ -21,6 +21,16 @@ "types": "./dist/vercel.d.ts" } }, + "typesVersions": { + "*": { + "testing": [ + "./dist/testing.d.ts" + ], + "vercel": [ + "./dist/vercel.d.ts" + ] + } + }, "files": [ "dist" ], diff --git a/packages/webdecoy/src/clearance/index.ts b/packages/webdecoy/src/clearance/index.ts index 6780f7f..5991a37 100644 --- a/packages/webdecoy/src/clearance/index.ts +++ b/packages/webdecoy/src/clearance/index.ts @@ -50,7 +50,8 @@ export interface ClearanceContext { waitUntil?: (promise: Promise) => void; } -function fromEnv(name: string): string { +/** One environment variable, trimmed; empty when unset or when there is no `process`. */ +export function fromEnv(name: string): string { try { const env = (globalThis as { process?: { env?: Record } }).process?.env; return (env?.[name] ?? '').trim(); diff --git a/packages/webdecoy/src/detect-and-gate.test.ts b/packages/webdecoy/src/detect-and-gate.test.ts new file mode 100644 index 0000000..a8e0175 --- /dev/null +++ b/packages/webdecoy/src/detect-and-gate.test.ts @@ -0,0 +1,289 @@ +/** + * Detection and the clearance gate in one Vercel middleware. + * + * The gate's decision and detection's scoring are tested where they are + * written. What is tested here is the combination: the default export reports + * with an API key and is the plain gate without one, a refusal still carries + * the match key that ties it to the detection of the same request, and nothing + * throws whatever the environment holds. + */ + +import { createHash } from 'crypto'; +import middleware, { createVercelMiddleware, clearanceMiddleware } from './vercel'; +import { createDetectAndGate } from './detect-and-gate'; +import { TEST_TRIGGER_USER_AGENT } from './test-trigger'; + +const GATE = { siteKey: 'org-1', scannerId: 'scanner-1', sensorKey: 'wds1.test' }; +const API_KEY = 'sk_test_combined'; +const BROWSER_UA = + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0 Safari/537.36'; +const BROWSER_HEADERS = { + accept: 'text/html', + 'accept-language': 'en-US', + 'accept-encoding': 'gzip', + 'sec-ch-ua': '"Chromium";v="141"', + 'user-agent': BROWSER_UA, +}; + +const CONFIG = (mode: 'monitor' | 'enforce') => ({ + mode, + allow: { search_engines: true, ai_crawlers: true, monitoring: true }, + keys: [], + active_credentials: [], + denied_fps: [], + generated_at: 0, + routes: ['/docs/*'], +}); + +interface Call { + url: string; + body: any; +} + +let hosts = 0; +const site = () => `https://combined${++hosts}.example`; +const realFetch = global.fetch; +const ENV_NAMES = ['WEBDECOY_API_KEY', 'WEBDECOY_SITE_KEY', 'WEBDECOY_SCANNER_ID', 'WEBDECOY_SENSOR_KEY']; + +/** Stub WebDecoy: clearance config, the detect endpoint and telemetry, recording every call. */ +function stubWebDecoy(mode: 'monitor' | 'enforce' = 'monitor', detection: Record = {}): Call[] { + const calls: Call[] = []; + global.fetch = jest.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url; + let body: any; + try { + body = init?.body ? JSON.parse(String(init.body)) : undefined; + } catch { + body = undefined; + } + calls.push({ url, body }); + if (url.includes('/api/v1/clearance/config')) return new Response(JSON.stringify(CONFIG(mode)), { status: 200 }); + if (url.includes('/api/v1/sdk/detect')) { + return new Response( + JSON.stringify({ + decision: 'block', + confidence: 100, + threat_level: 'HIGH', + bot_detected: true, + detection_id: 'det-1', + rule_enforced: false, + ...detection, + }), + { status: 200 } + ); + } + return new Response('{}', { status: 200 }); + }) as unknown as typeof fetch; + return calls; +} + +const detectCalls = (calls: Call[]) => calls.filter((c) => c.url.includes('/api/v1/sdk/detect')); + +/** The request headers Vercel would hand the page, decoded from the middleware's instructions. */ +function forwarded(res: Response | undefined): Headers { + expect(res?.headers.get('x-middleware-next')).toBe('1'); + const out = new Headers(); + for (const name of (res!.headers.get('x-middleware-override-headers') ?? '').split(',').filter(Boolean)) { + out.set(name, res!.headers.get(`x-middleware-request-${name}`) ?? ''); + } + return out; +} + +function setEnv(values: Record) { + for (const [k, v] of Object.entries(values)) process.env[k] = v; +} + +beforeAll(() => { + jest.useFakeTimers({ advanceTimers: true }); +}); + +afterAll(() => { + jest.clearAllTimers(); + jest.useRealTimers(); +}); + +afterEach(() => { + global.fetch = realFetch; + for (const name of ENV_NAMES) delete process.env[name]; +}); + +describe('@webdecoy/node/vercel default export', () => { + it('reports the test trigger as a test detection when WEBDECOY_API_KEY is set, and still serves it in monitor mode', async () => { + const calls = stubWebDecoy('monitor'); + setEnv({ + WEBDECOY_API_KEY: API_KEY, + WEBDECOY_SITE_KEY: GATE.siteKey, + WEBDECOY_SCANNER_ID: GATE.scannerId, + WEBDECOY_SENSOR_KEY: GATE.sensorKey, + }); + + const res = await middleware(new Request(`${site()}/`, { headers: { 'user-agent': TEST_TRIGGER_USER_AGENT } })); + + const reports = detectCalls(calls); + expect(reports).toHaveLength(1); + expect(reports[0].body.request_metadata.user_agent).toBe(TEST_TRIGGER_USER_AGENT); + expect(reports[0].body.local_analysis.flags).toContain('test_trigger'); + + // Monitor: served, with the verdict on the request for the application. + const headers = forwarded(res); + expect(headers.get('x-webdecoy-would-block')).toBe('true'); + expect(headers.get('x-webdecoy-detection-id')).toBe('det-1'); + // The gate ran too: its verdict is there. + expect(headers.get('x-wd-clearance')).toBe('unscoped'); + }); + + it('reports the test trigger with only WEBDECOY_API_KEY set, gate off', async () => { + const calls = stubWebDecoy(); + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + setEnv({ WEBDECOY_API_KEY: API_KEY }); + + const res = await middleware(new Request(`${site()}/`, { headers: { 'user-agent': TEST_TRIGGER_USER_AGENT } })); + + expect(detectCalls(calls)).toHaveLength(1); + expect(calls.some((c) => c.url.includes('/api/v1/clearance/'))).toBe(false); + expect(forwarded(res).get('x-webdecoy-would-block')).toBe('true'); + warn.mockRestore(); + }); + + it('reports an agent the bot registry names even when it sends browser headers', async () => { + const calls = stubWebDecoy(); + const ua = `${BROWSER_UA} ChatGPT-User/1.0`; + const res = await createVercelMiddleware({ ...GATE, apiKey: API_KEY })( + new Request(`${site()}/blog`, { headers: { ...BROWSER_HEADERS, 'user-agent': ua } }) + ); + expect(detectCalls(calls)).toHaveLength(1); + expect(detectCalls(calls)[0].body.request_metadata.user_agent).toBe(ua); + expect(res?.status ?? 200).not.toBe(403); + }); + + it('does not report a plain browser', async () => { + const calls = stubWebDecoy(); + const res = await createVercelMiddleware({ ...GATE, apiKey: API_KEY })( + new Request(`${site()}/blog`, { headers: BROWSER_HEADERS }) + ); + expect(detectCalls(calls)).toHaveLength(0); + expect(forwarded(res).get('x-webdecoy-would-block')).toBe('false'); + }); + + it('strips inbound copies of the detection headers', async () => { + stubWebDecoy(); + const res = await createVercelMiddleware({ ...GATE, apiKey: API_KEY })( + new Request(`${site()}/blog`, { + headers: { ...BROWSER_HEADERS, 'x-webdecoy-would-block': 'false', 'x-webdecoy-detection-id': 'forged' }, + }) + ); + const headers = forwarded(res); + expect(headers.get('x-webdecoy-detection-id')).not.toBe('forged'); + expect(headers.get('x-webdecoy-would-block')).toBe('false'); + }); + + it('without WEBDECOY_API_KEY is exactly the clearance gate: same response, nothing reported', async () => { + const calls = stubWebDecoy('enforce'); + const host = site(); + const make = () => + new Request(`${host}/docs/start`, { headers: { accept: 'text/html', 'user-agent': TEST_TRIGGER_USER_AGENT } }); + + const combined = await createVercelMiddleware(GATE)(make()); + const gateOnly = await clearanceMiddleware(GATE)(make()); + + expect(detectCalls(calls)).toHaveLength(0); + expect(combined?.status).toBe(gateOnly?.status); + expect(combined?.status).toBe(403); + expect(await combined?.text()).toBe(await gateOnly?.text()); + }); + + it('without any environment fails open and never throws', async () => { + const calls = stubWebDecoy(); + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + const res = await middleware( + new Request(`${site()}/docs/start`, { headers: { 'user-agent': TEST_TRIGGER_USER_AGENT } }) + ); + expect(res?.status ?? 200).not.toBe(403); + expect(calls).toHaveLength(0); + warn.mockRestore(); + }); + + it('fails open when WebDecoy is unreachable, with the key set', async () => { + global.fetch = jest.fn(async () => { + throw new TypeError('fetch failed'); + }) as unknown as typeof fetch; + const error = jest.spyOn(console, 'error').mockImplementation(() => undefined); + const res = await createVercelMiddleware({ ...GATE, apiKey: API_KEY })( + new Request(`${site()}/docs/start`, { headers: { accept: 'text/html', 'user-agent': 'python-requests/2.31' } }) + ); + expect(res?.status ?? 200).not.toBe(403); + error.mockRestore(); + }); + + it('fails open on a malformed API key, running the gate alone', async () => { + const calls = stubWebDecoy('enforce'); + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + const res = await createVercelMiddleware({ ...GATE, apiKey: 'not-a-key' })( + new Request(`${site()}/blog`, { headers: { 'user-agent': TEST_TRIGGER_USER_AGENT } }) + ); + expect(detectCalls(calls)).toHaveLength(0); + expect(forwarded(res).get('x-wd-clearance')).toBe('unscoped'); + warn.mockRestore(); + }); + + it('enforce mode answers the test trigger with 403', async () => { + stubWebDecoy(); + const res = await createVercelMiddleware({ ...GATE, apiKey: API_KEY, mode: 'enforce' })( + new Request(`${site()}/`, { headers: { 'user-agent': TEST_TRIGGER_USER_AGENT } }) + ); + expect(res?.status).toBe(403); + }); +}); + +describe('would-block labeling', () => { + it('a monitor-mode refusal reports the match key of the same client and path the detection reported', async () => { + const calls = stubWebDecoy('monitor'); + const pending: Promise[] = []; + const host = site(); + const res = await createVercelMiddleware({ ...GATE, apiKey: API_KEY })( + new Request(`${host}/docs/start?x=1`, { + headers: { accept: 'text/html', 'user-agent': 'python-requests/2.31', 'x-forwarded-for': '198.51.100.23' }, + }), + { waitUntil: (p) => pending.push(p) } + ); + + // Monitor: served, labelled missing, reported as would-block by detection. + const headers = forwarded(res); + expect(headers.get('x-wd-clearance')).toBe('missing'); + + const report = detectCalls(calls)[0].body.request_metadata; + expect(report.ip).toBe('198.51.100.23'); + expect(report.path).toBe('/docs/start'); + + // The gate flushes its verdict telemetry at the end of its time bucket. + jest.advanceTimersByTime(120_000); + await Promise.all(pending); + + const telemetry = calls.filter((c) => c.url.includes('/api/v1/clearance/telemetry')); + const refusals = telemetry.flatMap((c) => c.body?.refusals ?? []); + const expected = createHash('sha256') + .update(`${GATE.siteKey}|${report.ip}|${report.path}`) + .digest('hex') + .slice(0, 24); + expect(refusals.map((r: { k: string }) => r.k)).toContain(expected); + }); +}); + +describe('createDetectAndGate', () => { + it('returns the detection decision alongside the outcome', async () => { + stubWebDecoy(); + const { outcome, decision } = await createDetectAndGate({ ...GATE, apiKey: API_KEY })( + new Request(`${site()}/`, { headers: { 'user-agent': TEST_TRIGGER_USER_AGENT } }) + ); + expect(outcome.action).toBe('continue'); + expect(decision?.allowed).toBe(false); + }); + + it('returns no decision without a key', async () => { + stubWebDecoy(); + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + const { decision } = await createDetectAndGate({})(new Request(`${site()}/`)); + expect(decision).toBeNull(); + warn.mockRestore(); + }); +}); diff --git a/packages/webdecoy/src/detect-and-gate.ts b/packages/webdecoy/src/detect-and-gate.ts new file mode 100644 index 0000000..6355844 --- /dev/null +++ b/packages/webdecoy/src/detect-and-gate.ts @@ -0,0 +1,156 @@ +/** + * Detection and the clearance gate, in one middleware. + * + * A site on Vercel has one middleware file. Detection (what is this client, + * report it) and the clearance gate (does this protected page need a token) + * used to be two separate middlewares with two sets of credentials, so a site + * had to pick one or hand-write a chain. This runs both, for one request, and + * returns one outcome: + * + * - Detection runs when an API key is configured (`apiKey`, else + * `WEBDECOY_API_KEY`). It reports the reserved test trigger + * (`curl -A "WebDecoy-Test/1.0"`), tripwire hits and clients that look like + * bots, including every agent the bot registry names. + * - The gate runs when the site's identity is configured (`siteKey`, + * `scannerId`, `sensorKey`, else the WEBDECOY_* variables), exactly as + * `createClearanceGate()` does on its own. + * + * Without an API key this is the gate alone, unchanged. Without either, every + * request passes. Nothing here throws: a failure in detection or the gate lets + * the request through. + * + * Both halves resolve the client IP the same way and see the same path, so a + * request the gate refuses (or would refuse, in monitor mode) and the + * detection reported for it describe the same client. + */ + +import { createClearanceGate, cleanHeaders, fromEnv } from './clearance'; +import type { ClearanceGateOptions, ClearanceContext, GateOutcome } from './clearance'; +import { createFetchGuard } from './fetch-guard'; +import type { FetchGuard, FetchGuardOptions } from './fetch-guard'; +import { shouldSkipPath } from './adapter-core'; +import type { Decision } from './decision'; + +/** Request headers that carry the detection verdict to the application. */ +const DECISION_HEADER = 'x-webdecoy-decision'; +const DETECTION_ID_HEADER = 'x-webdecoy-detection-id'; +const WOULD_BLOCK_HEADER = 'x-webdecoy-would-block'; + +export interface DetectAndGateOptions + extends ClearanceGateOptions, + Omit { + /** + * The WebDecoy API key. `WEBDECOY_API_KEY` by default. A secret: set it in the + * platform's environment, never in code. Without one, no detection runs and + * this is the clearance gate alone. + */ + apiKey?: string; + + /** + * What a blocking detection verdict does. Defaults to `'monitor'`: the + * request is served and the verdict rides on the request headers + * (`x-webdecoy-decision`, `x-webdecoy-detection-id`, `x-webdecoy-would-block`). + * `'enforce'` answers a blocked request with 403 (or 429 for a rate limit). + * + * This is detection's mode only. Whether the clearance gate monitors or + * enforces is set per site in WebDecoy. + */ + mode?: 'monitor' | 'enforce'; +} + +/** Detection's verdict on a request, when detection ran. */ +export interface DetectAndGateOutcome { + /** What to do with the request. Same shape as the gate's outcome. */ + outcome: GateOutcome; + /** The detection decision, or null when detection did not run or failed. */ + decision: Decision | null; +} + +let warnedBadKey = false; + +/** + * Detection then the clearance gate, bound to one site: call it with each + * request. Options default to the environment. + */ +export function createDetectAndGate( + options: DetectAndGateOptions = {} +): (request: Request, context?: ClearanceContext) => Promise { + const gate = createClearanceGate(options); + const trustProxy = options.trustProxy ?? 1; + + // Built on the first request that has a key, and rebuilt only if the key + // changes, so an install that sets the variable later starts reporting + // without a redeploy of this code. + let guard: FetchGuard | null = null; + let guardKey = ''; + let failedKey = ''; + + function guardFor(apiKey: string): FetchGuard | null { + if (guard && guardKey === apiKey) return guard; + if (failedKey === apiKey) return null; + try { + guard = createFetchGuard({ ...options, apiKey, trustProxy, honeytoken: false, mode: options.mode ?? 'monitor' }); + guardKey = apiKey; + return guard; + } catch (error) { + // A malformed key is a configuration mistake, not a reason to stop + // serving pages. Say so once and run the gate alone. + failedKey = apiKey; + if (!warnedBadKey) { + warnedBadKey = true; + console.warn( + `[WebDecoy] detection is off: ${error instanceof Error ? error.message : 'the API key was rejected'}` + ); + } + return null; + } + } + + async function detect(request: Request, apiKey: string) { + try { + const g = guardFor(apiKey); + if (!g) return null; + if (shouldSkipPath(new URL(request.url).pathname, options.skipPaths)) return null; + return await g.check(request); + } catch { + return null; // fail open + } + } + + async function runGate(request: Request, context?: ClearanceContext): Promise { + try { + return await gate(request, context); + } catch { + return { action: 'continue', headers: null, verdict: null }; + } + } + + return async (request, context) => { + const apiKey = (options.apiKey ?? fromEnv('WEBDECOY_API_KEY')).trim(); + if (!apiKey) return { outcome: await runGate(request, context), decision: null }; + + // Concurrently: neither depends on the other, and the request waits on both. + const [guarded, gated] = await Promise.all([detect(request, apiKey), runGate(request, context)]); + if (!guarded) return { outcome: gated, decision: null }; + + const { decision, response } = guarded; + // Detection first: an enforced detection block answers before the gate's. + if (response) return { outcome: { action: 'respond', response }, decision }; + if (gated.action === 'respond') return { outcome: gated, decision }; + + try { + const headers = gated.headers ? new Headers(gated.headers) : cleanHeaders(request); + // Inbound copies go first: the application must not be told a verdict + // by the client being judged. + headers.delete(DECISION_HEADER); + headers.delete(DETECTION_ID_HEADER); + headers.delete(WOULD_BLOCK_HEADER); + headers.set(DECISION_HEADER, decision.detection?.decision ?? ''); + headers.set(DETECTION_ID_HEADER, decision.detection?.detection_id ?? ''); + headers.set(WOULD_BLOCK_HEADER, String(!decision.allowed)); + return { outcome: { action: 'continue', headers, verdict: gated.verdict }, decision }; + } catch { + return { outcome: gated, decision }; + } + }; +} diff --git a/packages/webdecoy/src/index.ts b/packages/webdecoy/src/index.ts index 2181f51..9eac8cc 100644 --- a/packages/webdecoy/src/index.ts +++ b/packages/webdecoy/src/index.ts @@ -80,6 +80,11 @@ export type { EdgeClass, EdgeVerdict } from './edge'; export { createClearanceGate, resolveGateEnv, CLEARANCE_GATE_BUILD } from './clearance'; export type { ClearanceGateOptions, ClearanceContext, GateEnv, GateOutcome } from './clearance'; +// Detection and the gate in one middleware: what `@webdecoy/node/vercel` and +// `@webdecoy/nextjs/vercel` export by default, each in its framework's shape. +export { createDetectAndGate } from './detect-and-gate'; +export type { DetectAndGateOptions, DetectAndGateOutcome } from './detect-and-gate'; + // Declared-agent classification. Exported as values for the same reason // as readEdgeVerdict: code outside protect() — a route handler deciding whether // to serve a paywall, a robots.txt generator — needs the same answer without diff --git a/packages/webdecoy/src/local-analysis.test.ts b/packages/webdecoy/src/local-analysis.test.ts index 2ab3e30..042e698 100644 --- a/packages/webdecoy/src/local-analysis.test.ts +++ b/packages/webdecoy/src/local-analysis.test.ts @@ -39,6 +39,13 @@ describe('analyzeRequest forwarding decision', () => { expect(a.needs_verification).toBe(true); }); + it('forwards an agent the bot registry names, even with browser headers', () => { + const ua = 'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0 Safari/537.36; ChatGPT-User/1.0'; + const a = analyzeRequest(base({ user_agent: ua })); + expect(a.suspicious_headers).toBe(true); + expect(a.needs_verification).toBe(true); + }); + it('forwards when TLS info is present, for fingerprinting', () => { const a = analyzeRequest(base({ tls_info: { ja3: 'abc' } } as Partial)); expect(a.needs_verification).toBe(true); diff --git a/packages/webdecoy/src/local-analysis.ts b/packages/webdecoy/src/local-analysis.ts index cd1666d..e9be0b3 100644 --- a/packages/webdecoy/src/local-analysis.ts +++ b/packages/webdecoy/src/local-analysis.ts @@ -4,6 +4,7 @@ */ import { LocalAnalysis, RequestMetadata } from './types'; +import { matchUserAgent } from './bots'; /** * Known datacenter IP ranges (CIDR notation) @@ -94,8 +95,13 @@ function hasSuspiciousHeaders(metadata: RequestMetadata): boolean { const userAgent = metadata.user_agent || ''; const headers = metadata.headers || {}; - // Check for bot-like user agents - const hasBotUA = SUSPICIOUS_PATTERNS.userAgents.some((pattern) => pattern.test(userAgent)); + // Check for bot-like user agents. An agent the bot registry names counts + // too: several (ChatGPT-User, Claude-User and other assistants fetching for a + // person) match none of the generic patterns and send browser-like headers, + // and they are exactly the traffic a site installs this to see. + const hasBotUA = + SUSPICIOUS_PATTERNS.userAgents.some((pattern) => pattern.test(userAgent)) || + matchUserAgent(userAgent) !== undefined; // Check for missing common browser headers const missingCommonHeaders = SUSPICIOUS_PATTERNS.missingHeaders.filter( diff --git a/packages/webdecoy/src/vercel.ts b/packages/webdecoy/src/vercel.ts index 9343f31..c46d136 100644 --- a/packages/webdecoy/src/vercel.ts +++ b/packages/webdecoy/src/vercel.ts @@ -1,9 +1,8 @@ /** - * WebDecoy clearance for Vercel Routing Middleware, any framework. + * WebDecoy for Vercel Routing Middleware, any framework. * * Astro, SvelteKit, Nuxt, Remix or a static site on Vercel: put this in - * `middleware.ts` at the project root and set WEBDECOY_SITE_KEY, - * WEBDECOY_SCANNER_ID and WEBDECOY_SENSOR_KEY in the project's environment. + * `middleware.ts` at the project root. * * ```ts * // middleware.ts @@ -15,17 +14,31 @@ * }; * ``` * - * Next.js sites use `withClearance()` from @webdecoy/nextjs instead. + * It reads the project's environment: * - * Starts in whatever mode the site has in WebDecoy, monitor by default, and - * enforces only once it is switched there and paths are protected. + * - `WEBDECOY_API_KEY` turns on detection: the request is classified and bots + * are reported to WebDecoy, including the reserved test trigger + * (`curl -A "WebDecoy-Test/1.0" https://your-site/`). + * - `WEBDECOY_SITE_KEY`, `WEBDECOY_SCANNER_ID` and `WEBDECOY_SENSOR_KEY` turn on + * the clearance gate for the paths the site protects in WebDecoy. + * + * Either half works without the other, and with neither every request passes. + * Detection starts in monitor mode and the gate in whatever mode the site has + * in WebDecoy (monitor by default), so installing this changes no response + * until you choose to enforce. Every failure lets the request through. + * + * Next.js sites use `@webdecoy/nextjs/vercel`, the same middleware in Next's + * types. */ import { createClearanceGate } from './clearance'; import type { ClearanceGateOptions, ClearanceContext } from './clearance'; import type { GateOutcome } from './clearance'; +import { createDetectAndGate } from './detect-and-gate'; +import type { DetectAndGateOptions } from './detect-and-gate'; export type { ClearanceGateOptions, ClearanceContext } from './clearance'; +export type { DetectAndGateOptions } from './detect-and-gate'; /** * Turn the gate's answer into what Vercel middleware returns. @@ -50,7 +63,10 @@ export function toMiddlewareResponse(outcome: GateOutcome): Response | undefined return new Response(null, { headers: instructions }); } -/** Routing Middleware bound to one site. Options default to the environment. */ +/** + * The clearance gate alone, as Routing Middleware. Options default to the + * environment. Reports no detections; {@link createVercelMiddleware} does both. + */ export function clearanceMiddleware( options: ClearanceGateOptions = {} ): (request: Request, context?: ClearanceContext) => Promise { @@ -64,6 +80,37 @@ export function clearanceMiddleware( }; } +/** + * Detection and the clearance gate as Routing Middleware, for customizing + * what the default export does. Options default to the environment. + * + * ```ts + * // middleware.ts + * import { createVercelMiddleware } from '@webdecoy/node/vercel'; + * import { tripwire } from '@webdecoy/node'; + * + * export default createVercelMiddleware({ + * rules: [tripwire({ paths: ['/admin-backup.zip'] })], + * }); + * + * export const config = { matcher: ['/((?!_astro/|favicon.ico).*)'] }; + * ``` + * + * Without an API key it is exactly {@link clearanceMiddleware}. + */ +export function createVercelMiddleware( + options: DetectAndGateOptions = {} +): (request: Request, context?: ClearanceContext) => Promise { + const decide = createDetectAndGate(options); + return async (request, context) => { + try { + return toMiddlewareResponse((await decide(request, context)).outcome); + } catch { + return undefined; // fail open + } + }; +} + /** The middleware configured from WEBDECOY_* environment variables. */ -const middleware = clearanceMiddleware(); +const middleware = createVercelMiddleware(); export default middleware;