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
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
48 changes: 44 additions & 4 deletions packages/nextjs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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.

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
18 changes: 15 additions & 3 deletions packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
130 changes: 130 additions & 0 deletions packages/nextjs/src/vercel.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
86 changes: 86 additions & 0 deletions packages/nextjs/src/vercel.ts
Original file line number Diff line number Diff line change
@@ -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<Response> {
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;
Loading
Loading