diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f3cebd..8dcfbf2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Documentation + +- **`@webdecoy/fastify`, `@webdecoy/nextjs` and `@webdecoy/hono` now ship a README**, so their npm pages show install steps, a working snippet, options, monitor mode and the environment variables each one reads. +- **The `@webdecoy/node` README describes the current API.** `apiKey` is optional (local rules only without it), `protect()` returns a decision with `conclusion`, `results` and `deniedBy()`, adapters start in monitor mode, and `WEBDECOY_API_KEY` is not read automatically. API keys are created on the **API Keys** page. +- **Install snippets add `@webdecoy/node` next to each adapter**, since rules such as `tripwire()` are imported from it. +- **The documented `apiUrl` default is `https://in.webdecoy.com`**, matching the code. `new WebDecoy()` with no argument in two examples is now `new WebDecoy({})`: the constructor requires a config object. + ## [0.21.2] - 2026-11-10 ### Changed diff --git a/README.md b/README.md index 0a49ebf..2e4166a 100644 --- a/README.md +++ b/README.md @@ -69,9 +69,13 @@ The middleware evaluates tripwires and other [local rules](#more-local-rules). T ### Express ```bash -npm install @webdecoy/express +npm install @webdecoy/express @webdecoy/node ``` +Install `@webdecoy/node` alongside every adapter: `tripwire()`, `rateLimit()` and the other rules are imported from it. + +The SDK and adapters do not read `WEBDECOY_API_KEY` from the environment. Without an `apiKey` option they run local rules only; to report to the dashboard, pass `apiKey: process.env.WEBDECOY_API_KEY`. + ```typescript import express from 'express'; import { webdecoy } from '@webdecoy/express'; @@ -109,7 +113,7 @@ Need the cloud dashboard? [Create a WebDecoy account](https://app.webdecoy.com/? ### Hono — Workers, Bun, Deno ```bash -npm install @webdecoy/hono +npm install @webdecoy/hono @webdecoy/node ``` ```typescript @@ -177,7 +181,7 @@ from someone forging its identity. ```typescript import { WebDecoy } from '@webdecoy/node'; -const wd = new WebDecoy(); +const wd = new WebDecoy({}); const verdict = await wd.detectBot(request); // a WHATWG Request, or { method, url, headers } // verdict.status: 'verified' | 'impersonation' | 'claimed' | 'none' @@ -220,7 +224,7 @@ The honest rule of thumb: enforce tripwires you control the surface of, and use ## Optional: the WebDecoy platform (API key) -Everything above runs locally and free, forever. Add an API key to turn on the hosted platform when you want deeper detection and visibility: +The local rules above run without an account. Add an API key to turn on the hosted platform when you want deeper detection and visibility: - **`protect()`** — full server-side analysis (a threat score + allow/block/challenge decision), not just local rules. - **TLS fingerprinting** — when you pass the client's TLS ClientHello details in `tls_info`, the server computes a JA3 fingerprint, matches it against known automation (curl, wget, Selenium, …) and checks it against the claimed browser (TLS↔UA mismatch). The adapters do not fill `tls_info`, because Node does not expose the client's ClientHello; this applies when your own TLS terminator can supply it. @@ -231,7 +235,7 @@ Everything above runs locally and free, forever. Add an API key to turn on the h import { WebDecoy } from '@webdecoy/node'; const wd = new WebDecoy({ - apiKey: process.env.WEBDECOY_API_KEY, // from app.webdecoy.com + apiKey: process.env.WEBDECOY_API_KEY, // not read automatically: pass it }); const result = await wd.protect({ @@ -243,6 +247,8 @@ const result = await wd.protect({ timestamp: Date.now(), }); +// result.conclusion: 'ALLOW' | 'DENY' | 'CHALLENGE' | 'ERROR'. +// protect() blocks nothing itself; refuse only once you have reviewed decisions. if (!result.allowed) { return res.status(403).json({ error: 'Access denied' }); } @@ -251,14 +257,14 @@ if (!result.allowed) { ### Getting an API key 1. Sign up at [app.webdecoy.com](https://app.webdecoy.com) -2. Create an organization and a property for your app -3. Generate an API key in Settings (`sk_live_` for production, `sk_test_` for testing) +2. Add your site +3. Create an API key on the **API Keys** page (`sk_live_` for production, `sk_test_` for testing) ## How it works | Tier | What | Needs a key? | |------|------|:---:| -| **0 — Tripwires** | Requests for hidden honeypot paths are blocked immediately, before any scoring. Deterministic, zero-FP. | No | +| **0 — Tripwires** | Requests for decoy and scanner-bait paths match before any scoring (recorded in monitor mode, refused in enforce mode). Deterministic matching; see [false positives](#what-counts-as-a-false-positive). | No | | **1 — Local analysis** | Fast on-server heuristics: suspicious/missing headers, datacenter IPs, known bot user-agents, missing `Sec-CH-UA`. | No | | **2 — Server verification** | Known-bot database, IP reputation, GeoIP (Tor/VPN/proxy), and JA3 TLS fingerprinting with TLS↔UA mismatch when `tls_info` is supplied. | Yes | @@ -437,8 +443,8 @@ The same option is accepted by `webdecoyCaptcha()` / `createCaptchaHandler()`, a ```typescript const wd = new WebDecoy({ - apiKey: 'sk_live_xxxxx', // optional — only for platform features - apiUrl: 'https://ingest.webdecoy.com', // optional (defaults to production) + apiKey: process.env.WEBDECOY_API_KEY, // optional — only for platform features + apiUrl: 'https://in.webdecoy.com', // optional (this is the default) enableTLSFingerprinting: true, // optional (default: true) threatScoreThreshold: 70, // optional, 0–100 (default: 80) timeout: 5000, // optional, ms (default: 5000) @@ -582,7 +588,7 @@ See [examples](./examples) for complete working setups — e.g. [express-basic]( ## FAQ -**Will this slow down my app?** Local rules (tripwires, rate limiting) add <1ms and make no network calls. Server verification (with a key) typically takes 50–200ms and runs asynchronously for low-risk requests. +**Will this slow down my app?** Local rules (tripwires, in-memory rate limiting) run in-process and make no network calls. With an API key, a request goes to WebDecoy only when local analysis flags it for verification; that call is awaited, bounded by `timeout` (default 5000 ms), and fails open. Requests local analysis does not flag make no call. **What if the WebDecoy service is down?** Local rules are unaffected (they never call out). Platform `protect()` fails open by default, so requests continue. diff --git a/docs/verify-ai-agents-web-bot-auth.md b/docs/verify-ai-agents-web-bot-auth.md index 3c2d1e5..f87c285 100644 --- a/docs/verify-ai-agents-web-bot-auth.md +++ b/docs/verify-ai-agents-web-bot-auth.md @@ -42,7 +42,7 @@ you decide what to do: import { NextRequest, NextResponse } from 'next/server'; import { WebDecoy } from '@webdecoy/node'; -const wd = new WebDecoy(); // no API key needed for local verification +const wd = new WebDecoy({}); // no API key needed for local verification export async function middleware(req: NextRequest) { const verdict = await wd.detectBot(req); diff --git a/packages/express/README.md b/packages/express/README.md index b447fdc..9896375 100644 --- a/packages/express/README.md +++ b/packages/express/README.md @@ -1,6 +1,6 @@ # @webdecoy/express -Web Decoy middleware for Express.js applications - Advanced bot detection with TLS fingerprinting. +WebDecoy middleware for Express: tripwires, rate limits and other local rules, plus optional server-side bot detection reported to your WebDecoy dashboard. Starts in monitor mode. [![npm version](https://img.shields.io/npm/v/@webdecoy/express.svg)](https://www.npmjs.com/package/@webdecoy/express) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) @@ -8,11 +8,11 @@ Web Decoy middleware for Express.js applications - Advanced bot detection with T ## Installation ```bash -npm install @webdecoy/express -# or -yarn add @webdecoy/express +npm install @webdecoy/express @webdecoy/node ``` +`@webdecoy/node` is the core SDK. This package depends on it, but install it directly too: `tripwire()`, `rateLimit()` and the other rules are imported from `@webdecoy/node`, and relying on a transitive dependency for your own imports breaks under strict package managers such as pnpm. + ## Quick Start ```typescript @@ -30,7 +30,7 @@ app.use( ); app.get('/api/data', (req, res) => { - // Access detection info + // req.webdecoy carries the detection (decision, confidence, threat_level, bot_detected) console.log('Bot detected:', req.webdecoy?.bot_detected); res.json({ data: 'protected' }); }); @@ -38,10 +38,44 @@ app.get('/api/data', (req, res) => { app.listen(3000); ``` +Mount it before your routes. + The SDK does not read `WEBDECOY_API_KEY` by itself: pass it as `apiKey`. Without one, the middleware runs local rules only and nothing reports to your dashboard. It starts in **monitor** mode: detections are recorded and every request is still served. Watch what it would have blocked, then set `mode: 'enforce'`. +## Local rules (no API key needed) + +With no `rules` option the middleware arms `tripwire()` with its built-in scanner-bait paths (`/.env`, `/wp-config.php` and similar). Add your own rules from `@webdecoy/node`: + +```typescript +import express from 'express'; +import { webdecoy } from '@webdecoy/express'; +import { tripwire, rateLimit } from '@webdecoy/node'; + +const app = express(); + +app.use( + webdecoy({ + apiKey: process.env.WEBDECOY_API_KEY, // optional + rules: [ + tripwire({ paths: ['/admin-backup.zip'] }), + rateLimit({ max: 100, window: 60 }), + ], + skipPaths: ['/health'], + }) +); + +app.get('/', (req, res) => { + // The full typed decision, set in monitor mode too. + const decision = req.webdecoyDecision; + if (decision?.deniedBy('tripwire')) console.log('tripwire hit', decision.id); + res.send('ok'); +}); +``` + +`req.webdecoyDecision` has `conclusion` (`'ALLOW'`, `'DENY'`, `'CHALLENGE'` or `'ERROR'`), `allowed`, `results` (every rule and what it concluded) and `deniedBy(rule)`. In monitor mode it is the only place a verdict surfaces. See the [@webdecoy/node README](https://www.npmjs.com/package/@webdecoy/node) for every rule. + ## Middleware Options ```typescript @@ -60,7 +94,8 @@ interface WebDecoyMiddlewareOptions { // Inject a hidden honeytoken link into HTML responses (default: on with an apiKey) honeytoken?: boolean; - // Local rules such as tripwire() and rate limits, evaluated first + // Local rules from @webdecoy/node, evaluated first. + // Default: [tripwire()]. Pass [] to opt out. rules?: Rule[]; // How much of X-Forwarded-For to trust: hop count, 'cloudflare', or proxy CIDRs. @@ -73,7 +108,9 @@ interface WebDecoyMiddlewareOptions { // Paths to skip protection skipPaths?: string[] | RegExp[]; - // Called when a request would be blocked. Call next() to serve it anyway. + // Enforce mode: called when the server-side score blocks a request. + // Call next() to serve it anyway. Rule refusals (tripwire, rateLimit, ...) + // answer directly: 403 with the rule name, or 429 with Retry-After. onBlocked?: (req, res, detection, next, decision) => void; // Custom error handler (default: log and allow, fail open) @@ -142,7 +179,7 @@ app.use( ## Access Detection Info -The middleware adds detection info to `req.webdecoy`: +The middleware adds detection info to `req.webdecoy`, and the full typed decision to `req.webdecoyDecision`: ```typescript app.get('/api/data', (req, res) => { @@ -186,6 +223,16 @@ app.get('/api/data', (req: Request, res) => { }); ``` +## Verify the install + +With an `apiKey` configured, send one request with the reserved test User-Agent: + +```bash +curl -A "WebDecoy-Test/1.0" http://localhost:3000/ +``` + +A detection labeled **Test** appears on the **Detections** page within a few seconds. See [Verify your install](https://docs.webdecoy.com/getting-started/verify-installation/). + ## Core SDK This package uses [@webdecoy/node](https://www.npmjs.com/package/@webdecoy/node) under the hood. For non-Express applications or custom integrations, use the core SDK directly. @@ -200,7 +247,7 @@ API keys start with `sk_live_` for production or `sk_test_` for testing. ## Documentation -Full documentation: [docs.webdecoy.com/sdk-plugins/express](https://docs.webdecoy.com/sdk-plugins/express/). +Full documentation: [docs.webdecoy.com/sdk-plugins/express](https://docs.webdecoy.com/sdk-plugins/express/). Install snippets for every stack: [docs.webdecoy.com/installation/install-with-ai](https://docs.webdecoy.com/installation/install-with-ai/). ## License diff --git a/packages/fastify/README.md b/packages/fastify/README.md new file mode 100644 index 0000000..33d4f8c --- /dev/null +++ b/packages/fastify/README.md @@ -0,0 +1,153 @@ +# @webdecoy/fastify + +WebDecoy plugin for Fastify 4 and 5: tripwires, rate limits and other local rules, plus optional server-side bot detection reported to your WebDecoy dashboard. Starts in monitor mode. + +[![npm version](https://img.shields.io/npm/v/@webdecoy/fastify.svg)](https://www.npmjs.com/package/@webdecoy/fastify) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) + +## Installation + +```bash +npm install @webdecoy/fastify @webdecoy/node +``` + +`@webdecoy/node` is the core SDK. Install it directly: rules such as `tripwire()` and `rateLimit()` are imported from it. + +## Quick start + +```js +import Fastify from 'fastify'; +import webdecoy from '@webdecoy/fastify'; + +const app = Fastify(); + +await app.register(webdecoy, { + apiKey: process.env.WEBDECOY_API_KEY, + skipPaths: ['/health'], +}); + +app.get('/', async (request) => { + // request.webdecoy carries the detection (decision, confidence, threat_level, bot_detected) + // request.webdecoyDecision carries the full typed decision + return { ok: true }; +}); + +await app.listen({ port: 3000 }); +``` + +The plugin hooks every route (it is registered with `fastify-plugin`, so it is not scoped to an encapsulation context). The default export and the named export `webdecoyPlugin` are the same plugin. + +### API key + +`apiKey` is optional. Without it the plugin runs local rules only (the built-in tripwire paths by default) and nothing reports to your dashboard. The plugin does **not** read `WEBDECOY_API_KEY` from the environment by itself: 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_` or `sk_test_`. Keep it in your server environment, never in committed code. + +### Monitor mode + +The plugin starts in **monitor mode**: it records the decision on the request and serves every request, even one it would have blocked. Review what it would have blocked, then opt in: + +```js +await app.register(webdecoy, { + apiKey: process.env.WEBDECOY_API_KEY, + mode: 'enforce', +}); +``` + +In enforce mode a rule refusal answers `403` (naming the rule), a rate-limit throttle answers `429` with `Retry-After`, and a request blocked by the server-side score goes to `onBlocked` (default `403`). + +## Local rules + +With no `rules` option the plugin arms `tripwire()` with its built-in scanner-bait paths (`/.env`, `/wp-config.php` and similar). Pass `rules: []` to opt out, or add your own: + +```js +import { tripwire, rateLimit } from '@webdecoy/node'; + +await app.register(webdecoy, { + rules: [ + tripwire({ paths: ['/admin-backup.zip'] }), + rateLimit({ max: 100, window: 60 }), + ], +}); + +app.addHook('onResponse', async (request) => { + if (request.webdecoyDecision?.deniedBy('tripwire')) { + request.log.warn({ decision: request.webdecoyDecision.id }, 'tripwire hit'); + } +}); +``` + +See the [@webdecoy/node README](https://www.npmjs.com/package/@webdecoy/node) for every rule and the decision shape (`conclusion`, `allowed`, `results`, `deniedBy()`). + +## Options + +The plugin accepts every core SDK option (`apiKey`, `rules`, `apiUrl`, `threatScoreThreshold`, `timeout`, `debug`, ...) and the per-request options `threshold`, `skipLocalAnalysis` and `metadata`, plus: + +| Option | Default | Description | +|---|---|---| +| `mode` | `'monitor'` | `'monitor'` records and serves every request; `'enforce'` blocks. | +| `skipPaths` | none | Paths to skip, as strings or regular expressions. | +| `trustProxy` | unset: uses `request.ip` | How much of `X-Forwarded-For` to believe: a hop count, `'cloudflare'`, `'railway'`, or your proxies' CIDRs. | +| `getIP` | derived from `trustProxy` | `(request) => string`. Overrides `trustProxy`. | +| `honeytoken` | on when `apiKey` is set | Inject a hidden trap link into HTML replies and arm the tripwire it points at. | +| `onBlocked` | `403` JSON | `(request, reply, detection, decision) => void`. Enforce mode, server-score blocks. | +| `onError` | log and allow | `(request, reply, error) => void`. The plugin fails open. | + +### Request properties + +| Property | What it is | +|---|---| +| `request.webdecoy` | The detection: `decision`, `confidence`, `threat_level`, `bot_detected`, `bot_type`, `detection_id`, `rule_enforced`. | +| `request.webdecoyDecision` | The full decision: `conclusion`, `allowed`, `results`, `deniedBy(rule)`, `id`. In monitor mode this is the only place a verdict surfaces. | +| `request.webdecoyEdge` | What a WebDecoy edge validator said about the request, when one fronts your app. | + +### Client IP behind a proxy + +Unset, the plugin uses `request.ip`, which follows Fastify's own `trustProxy` server option and otherwise is the socket address. Behind a load balancer or platform proxy, set `trustProxy` on the WebDecoy plugin rather than relying on Fastify's numeric server option: + +```js +await app.register(webdecoy, { + apiKey: process.env.WEBDECOY_API_KEY, + trustProxy: 1, // or 'cloudflare', 'railway', or ['10.0.0.0/8'] +}); +``` + +### Honeytoken injection + +With an `apiKey`, the plugin injects a hidden link into buffered HTML replies (`reply.send(html)`, `@fastify/view`) and arms a tripwire on its path. Streamed replies are left untouched and a warning is logged once. + +## Self-hosted captcha + +`webdecoyCaptchaPlugin` mounts the captcha endpoints (`/__webdecoy/challenge`, `/verify`, `/score`, `/token/verify`) used by [`@webdecoy/client`](https://www.npmjs.com/package/@webdecoy/client): + +```js +import { webdecoyCaptchaPlugin } from '@webdecoy/fastify'; + +await app.register(webdecoyCaptchaPlugin, { secret: process.env.WEBDECOY_SECRET }); +``` + +`secret` is required when `NODE_ENV` is `production`. Generate one with `openssl rand -hex 32`. + +## Environment variables + +None are read automatically. `WEBDECOY_API_KEY` and `WEBDECOY_SECRET` above are naming conventions: pass their values as `apiKey` and `secret`. + +## Verify the install + +With an `apiKey` configured, send one request with the reserved test User-Agent: + +```bash +curl -A "WebDecoy-Test/1.0" http://localhost:3000/ +``` + +A detection labeled **Test** appears on the **Detections** page within a few seconds. If nothing appears, check that the plugin is registered before your routes and that `apiKey` is passed. + +## Documentation + +- [Fastify plugin](https://docs.webdecoy.com/sdk-plugins/fastify/) +- [Install with an AI assistant](https://docs.webdecoy.com/installation/install-with-ai/): copy-paste snippets for every stack +- [Verify your install](https://docs.webdecoy.com/getting-started/verify-installation/) + +## License + +MIT diff --git a/packages/hono/README.md b/packages/hono/README.md new file mode 100644 index 0000000..7b341dd --- /dev/null +++ b/packages/hono/README.md @@ -0,0 +1,131 @@ +# @webdecoy/hono + +WebDecoy middleware for Hono on Cloudflare Workers, Bun, Deno and Node: tripwires, rate limits and other local rules, plus optional server-side bot detection reported to your WebDecoy dashboard. Starts in monitor mode. + +[![npm version](https://img.shields.io/npm/v/@webdecoy/hono.svg)](https://www.npmjs.com/package/@webdecoy/hono) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) + +## Installation + +```bash +npm install @webdecoy/hono @webdecoy/node +``` + +`@webdecoy/node` is the core SDK. Install it directly: rules such as `tripwire()` and `rateLimit()` are imported from it. Requires Hono 4. + +## Quick start + +```ts +import { Hono } from 'hono'; +import { webdecoy } from '@webdecoy/hono'; + +const app = new Hono(); + +app.use('*', webdecoy({ + apiKey: process.env.WEBDECOY_API_KEY, + skipPaths: ['/health'], +})); + +app.get('/', (c) => { + // c.get('webdecoy') carries the decision; in monitor mode this is where it surfaces + return c.text('ok'); +}); + +export default app; +``` + +On Cloudflare Workers, `process.env` needs the `nodejs_compat` compatibility flag and a recent compatibility date. Behind Cloudflare, `trustProxy: 'cloudflare'` is stronger than the default of one trusted hop. + +### 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. + +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_`. Store it as a secret in your runtime's environment (for example `wrangler secret put WEBDECOY_API_KEY`), never in committed code. + +### Monitor mode + +The middleware starts in **monitor mode**: it stores the decision on the context and serves every request, even one it would have blocked. Review what it would have blocked, then opt in with `mode: 'enforce'`. In enforce mode a rule refusal answers `403`, a rate-limit throttle answers `429` with `Retry-After`, and a server-score block answers `403`, unless you pass `onBlocked`. + +## Reading the decision + +```ts +app.get('/', (c) => { + const decision = c.get('webdecoy'); // also available as c.get('webdecoyDecision') + if (decision?.deniedBy('tripwire')) console.log('tripwire hit', decision.id); + return c.text('ok'); +}); +``` + +The decision has `conclusion` (`'ALLOW'`, `'DENY'`, `'CHALLENGE'` or `'ERROR'`), `allowed`, `results` (every rule and what it concluded), `deniedBy(rule)`, `id` and `detection`. See the [@webdecoy/node README](https://www.npmjs.com/package/@webdecoy/node) for the full shape. + +## Local rules + +With no `rules` option the middleware arms `tripwire()` with its built-in scanner-bait paths (`/.env`, `/wp-config.php` and similar). Pass `rules: []` to opt out, or add your own: + +```ts +import { tripwire, rateLimit } from '@webdecoy/node'; + +app.use('*', webdecoy({ + rules: [ + tripwire({ paths: ['/admin-backup.zip'] }), + rateLimit({ max: 100, window: 60 }), + ], +})); +``` + +`rateLimit()` counts in memory per isolate or process. On Workers or any multi-instance deployment, pass a shared store such as `upstashRateLimitStore()` from `@webdecoy/node`. + +## Options + +`webdecoy()` accepts every core SDK option (`apiKey`, `rules`, `apiUrl`, `threatScoreThreshold`, `timeout`, `debug`, ...) and the per-request options `threshold`, `skipLocalAnalysis` and `metadata`, plus: + +| Option | Default | Description | +|---|---|---| +| `mode` | `'monitor'` | `'monitor'` records and serves every request; `'enforce'` blocks. | +| `skipPaths` | none | Paths to skip, as strings or regular expressions. | +| `trustProxy` | `1` | How much of `X-Forwarded-For` to believe: a hop count, `'cloudflare'`, `'railway'`, or your proxies' CIDRs. | +| `getIP` | derived from `trustProxy` | `(request: Request) => string`. Overrides `trustProxy`. | +| `honeytoken` | on when `apiKey` is set | Inject a hidden trap link into full HTML responses and arm the tripwire it points at. | +| `onBlocked` | `403`, or `429` for a throttle | `(c, decision) => Response`. Enforce mode only; replaces the default response for every block. | + +## Without Hono + +For Bun, Deno, Astro, SvelteKit, Remix or a bare Workers `fetch` handler, `createFetchGuard()` from `@webdecoy/node` is the same implementation this middleware wraps: + +```ts +import { createFetchGuard } from '@webdecoy/node'; + +const guard = createFetchGuard({ apiKey: process.env.WEBDECOY_API_KEY }); + +export default { + async fetch(request: Request): Promise { + const { response } = await guard.check(request); + if (response) return response; // only ever set in enforce mode + return guard.decorate(await handle(request)); // handle() is your app + }, +}; +``` + +## Environment variables + +None are read automatically. `WEBDECOY_API_KEY` above is a naming convention: pass its value as `apiKey`. + +## Verify the install + +With an `apiKey` configured, send one request with the reserved test User-Agent: + +```bash +curl -A "WebDecoy-Test/1.0" http://localhost:8787/ +``` + +Use your dev server's port. A detection labeled **Test** appears on the **Detections** page within a few seconds. + +## Documentation + +- [Install with an AI assistant](https://docs.webdecoy.com/installation/install-with-ai/#hono): copy-paste snippets for every stack +- [Node.js SDK](https://docs.webdecoy.com/sdk-plugins/node-sdk/) +- [Verify your install](https://docs.webdecoy.com/getting-started/verify-installation/) + +## License + +MIT diff --git a/packages/nextjs/README.md b/packages/nextjs/README.md new file mode 100644 index 0000000..d2f2c7b --- /dev/null +++ b/packages/nextjs/README.md @@ -0,0 +1,164 @@ +# @webdecoy/nextjs + +WebDecoy for Next.js: bot-detection middleware with tripwires and rate limits, clearance-token enforcement on Vercel, and helpers for route handlers. Starts in monitor mode. + +[![npm version](https://img.shields.io/npm/v/@webdecoy/nextjs.svg)](https://www.npmjs.com/package/@webdecoy/nextjs) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) + +## Installation + +```bash +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 + +```ts +// middleware.ts (project root, or src/ if you use it) +import { withWebDecoy } from '@webdecoy/nextjs'; + +export default withWebDecoy({ + apiKey: process.env.WEBDECOY_API_KEY!, +}); + +// Protect the routes that matter and leave static assets alone. +export const config = { + matcher: ['/api/:path*', '/checkout/:path*'], +}; +``` + +### 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. + +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. + +### Monitor mode + +`withWebDecoy` starts in **monitor mode**: it serves every request and passes the verdict to your app as request headers, which route handlers and server components can read: + +| Request header | Value | +|---|---| +| `x-webdecoy-decision` | The detection's `decision` (`allow`, `block` or `challenge`). | +| `x-webdecoy-detection-id` | The detection id. | +| `x-webdecoy-would-block` | `true` when enforce mode would have refused the request. | + +Inbound copies of these headers are stripped first, so a client cannot set them. Review what would have been blocked, then set `mode: 'enforce'`. In enforce mode a rule refusal answers `403` (naming the rule), a rate-limit throttle answers `429` with `Retry-After`, and a request blocked by the server-side score goes to `onBlocked` (default `403`). + +## Local rules + +With no `rules` option the middleware arms `tripwire()` with its built-in scanner-bait paths (`/.env`, `/wp-config.php` and similar). Pass `rules: []` to opt out, or add your own: + +```ts +// middleware.ts +import { withWebDecoy } from '@webdecoy/nextjs'; +import { tripwire, rateLimit } from '@webdecoy/node'; + +export default withWebDecoy({ + apiKey: process.env.WEBDECOY_API_KEY, + rules: [ + tripwire({ paths: ['/admin-backup.zip'] }), + rateLimit({ max: 100, window: 60 }), + ], +}); +``` + +`rateLimit()` counts in memory per instance. On Vercel or any multi-instance deployment, pass a shared store such as `upstashRateLimitStore()` from `@webdecoy/node`. See the [@webdecoy/node README](https://www.npmjs.com/package/@webdecoy/node) for every rule. + +## Options + +`withWebDecoy` accepts every core SDK option (`apiKey`, `rules`, `apiUrl`, `threatScoreThreshold`, `timeout`, `debug`, ...) and the per-request options `threshold`, `skipLocalAnalysis` and `metadata`, plus: + +| Option | Default | Description | +|---|---|---| +| `mode` | `'monitor'` | `'monitor'` records and serves every request; `'enforce'` blocks. | +| `skipPaths` | none | Paths to skip, as strings or regular expressions. | +| `trustProxy` | `1` | How much of `X-Forwarded-For` to believe: a hop count, `'cloudflare'`, `'railway'`, or your proxies' CIDRs. `1` is right on Vercel. | +| `getIP` | derived from `trustProxy` | `(req) => string`. Overrides `trustProxy`. | +| `onBlocked` | `403` JSON | `(req, detection, decision) => NextResponse`. Enforce mode, server-score blocks. | +| `onError` | log and continue | `(req, error) => NextResponse \| null`. The middleware fails open. | + +Use Next's own `export const config = { matcher }` to choose which routes the middleware runs on. + +## Clearance enforcement on Vercel + +With a WebDecoy account, the paths you protect in WebDecoy can require a clearance token, checked in middleware before the page renders. A real browser earns one automatically; a client that never runs JavaScript does not get the page. It follows the site's mode in WebDecoy (monitor until you switch it) and fails open. + +```ts +// middleware.ts +import { withClearance } from '@webdecoy/nextjs'; + +export default withClearance(); + +export const config = { + // Everything but static assets. Keep /.well-known: the challenge uses it. + matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'], +}; +``` + +`withClearance()` reads these environment variables (or the matching options `siteKey`, `scannerId`, `sensorKey`, `ingest`): + +| Variable | Where it comes from | Secret? | +|---|---|---| +| `WEBDECOY_SITE_KEY` | **Enforcement, Setup** in the dashboard | No | +| `WEBDECOY_SCANNER_ID` | **Enforcement, Setup** in the dashboard | No | +| `WEBDECOY_SENSOR_KEY` | **Enforcement, Setup** in the dashboard | Yes | +| `WEBDECOY_INGEST` | Optional override of the ingest endpoint | No | + +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. + +## Pages Router API routes + +`withBotProtection` wraps a Pages Router API handler. Like the middleware it defaults to monitor mode; the handler always runs and receives `req.webdecoy` and `req.webdecoyDecision`. + +```ts +// pages/api/protected.ts +import type { NextApiRequest, NextApiResponse } from 'next'; +import { withBotProtection } from '@webdecoy/nextjs'; + +async function handler(req: NextApiRequest, res: NextApiResponse) { + res.json({ data: 'protected' }); +} + +export default withBotProtection(handler, { + apiKey: process.env.WEBDECOY_API_KEY, + blockThreshold: 80, // default +}); +``` + +It reads the socket address and trusts no forwarding header unless you pass `trustProxy`. + +## Other helpers + +- `getEdgeVerdict(req)`: what a WebDecoy edge validator (the clearance middleware or the Cloudflare edge sensor) said about a request, readable in a route handler or server component. `present: false` means no validator fronted the request. +- `honeytokenLink(apiKey)`: the site's hidden trap link (`linkProps`, `activePaths`). Render the link in your root layout and arm it with `tripwire({ paths: bait.activePaths })`. The middleware cannot inject it automatically because App Router responses stream. +- `createCaptchaHandler({ secret })`: route handlers for the self-hosted captcha used by [`@webdecoy/client`](https://www.npmjs.com/package/@webdecoy/client). Mount at `app/__webdecoy/[...webdecoy]/route.ts` as `export const { GET, POST } = createCaptchaHandler({ secret: process.env.WEBDECOY_SECRET });`. `secret` is required when `NODE_ENV` is `production`. + +## 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`. + +## Verify the install + +With an `apiKey` configured, send one request with the reserved test User-Agent to a path your `matcher` covers: + +```bash +curl -A "WebDecoy-Test/1.0" http://localhost:3000/api/health +``` + +A detection labeled **Test** appears on the **Detections** page within a few seconds. + +## Documentation + +- [Next.js middleware](https://docs.webdecoy.com/sdk-plugins/nextjs/) +- [Vercel middleware (clearance)](https://docs.webdecoy.com/installation/vercel-middleware/) +- [Install with an AI assistant](https://docs.webdecoy.com/installation/install-with-ai/): copy-paste snippets for every stack +- [Verify your install](https://docs.webdecoy.com/getting-started/verify-installation/) + +## License + +MIT diff --git a/packages/webdecoy/README.md b/packages/webdecoy/README.md index 9b51e8a..39a9b3f 100644 --- a/packages/webdecoy/README.md +++ b/packages/webdecoy/README.md @@ -1,172 +1,226 @@ # @webdecoy/node -Core Web Decoy SDK for Node.js applications - Advanced bot detection with TLS fingerprinting. +The core WebDecoy SDK for Node.js and edge runtimes: tripwires, rate limits and other local rules, plus optional server-side bot detection reported to your WebDecoy dashboard. [![npm version](https://img.shields.io/npm/v/@webdecoy/node.svg)](https://www.npmjs.com/package/@webdecoy/node) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +Full documentation: [docs.webdecoy.com/sdk-plugins/node-sdk](https://docs.webdecoy.com/sdk-plugins/node-sdk/). Copy-paste install snippets for every stack: [docs.webdecoy.com/installation/install-with-ai](https://docs.webdecoy.com/installation/install-with-ai/). + +## Using a framework? Install its adapter + +Most apps should install a framework adapter alongside this package. The adapters handle request mapping, client IP, monitor mode and honeytoken injection for you. Install `@webdecoy/node` too: it is where `tripwire()`, `rateLimit()` and the other rules are imported from. + +| Framework | Install | +|---|---| +| Express | `npm install @webdecoy/express @webdecoy/node` ([README](https://www.npmjs.com/package/@webdecoy/express)) | +| Fastify | `npm install @webdecoy/fastify @webdecoy/node` ([README](https://www.npmjs.com/package/@webdecoy/fastify)) | +| Next.js | `npm install @webdecoy/nextjs @webdecoy/node` ([README](https://www.npmjs.com/package/@webdecoy/nextjs)) | +| Hono (Workers, Bun, Deno, Node) | `npm install @webdecoy/hono @webdecoy/node` ([README](https://www.npmjs.com/package/@webdecoy/hono)) | +| Any other server or fetch runtime | `npm install @webdecoy/node` (this page) | + ## Installation ```bash npm install @webdecoy/node -# or -yarn add @webdecoy/node ``` -## Quick Start +## Quick start -```typescript +```js +import http from 'node:http'; import { WebDecoy } from '@webdecoy/node'; -const webdecoy = new WebDecoy({ - apiKey: process.env.WEBDECOY_API_KEY, -}); +const wd = new WebDecoy({ apiKey: process.env.WEBDECOY_API_KEY }); + +http.createServer(async (req, res) => { + const decision = await wd.protect({ + method: req.method, + path: new URL(req.url, 'http://localhost').pathname, + ip: req.socket.remoteAddress ?? '', + user_agent: req.headers['user-agent'], + headers: Object.fromEntries( + Object.entries(req.headers).map(([name, value]) => [name, String(value)]) + ), + timestamp: Date.now(), + }); + + // protect() returns a decision and blocks nothing itself. + // Log decision.conclusion ('ALLOW', 'DENY', 'CHALLENGE' or 'ERROR') first; + // refuse with a 403 when decision.allowed is false only once you are ready. + res.end('ok'); +}).listen(3000); +``` -const result = await webdecoy.protect({ - method: 'GET', - path: '/api/data', - ip: '203.0.113.42', - user_agent: req.headers['user-agent'], - headers: req.headers, - timestamp: Date.now(), -}); +Behind a proxy, `req.socket.remoteAddress` is the proxy. Use `resolveClientIp()` from this package to read the real client address (see [Client IP behind a proxy](#client-ip-behind-a-proxy)). + +### The API key is optional + +`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. + +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. -if (!result.allowed) { - // Block the request - return res.status(403).json({ error: 'Access denied' }); -} +### Monitor first + +`protect()` only returns a decision. It never writes a response, so nothing is blocked until your code acts on `decision.allowed`. The framework adapters and `createFetchGuard()` follow the same rule: they start in **monitor mode** (`mode: 'monitor'`), record the decision and serve every request. Set `mode: 'enforce'` only after you have reviewed what would have been blocked. + +## The decision + +`protect(metadata, options?)` returns a `Decision`: + +```ts +const decision = await wd.protect(metadata); + +decision.conclusion // 'ALLOW' | 'DENY' | 'CHALLENGE' | 'ERROR' +decision.allowed // true for ALLOW and ERROR (fails open), false for DENY and CHALLENGE +decision.id // 'dec_...' +decision.isDenied() // also isAllowed(), isChallenged(), isErrored() +decision.deniedBy('tripwire') // whether a named rule denied the request +decision.results // every configured rule, its state and its conclusion +decision.reason // the deciding reason, when there is one +decision.detection // { decision, confidence, threat_level, bot_detected, bot_type?, detection_id, rule_enforced } +decision.error // set when conclusion is 'ERROR' +decision.edge // what a WebDecoy edge validator said about this request, if one fronted it ``` -## Configuration Options +Each entry in `results` has a `state`: -```typescript -const webdecoy = new WebDecoy({ - // Required: Your API key from the dashboard - apiKey: 'sk_live_xxxxx', +| `state` | Meaning | +|---|---| +| `RUN` | Evaluated, and its conclusion counts. | +| `DRY_RUN` | Evaluated; the conclusion is recorded but not enforced. | +| `NOT_RUN` | Could not evaluate because a signal it needs was absent (for example a `filter()` rule with no IP enrichment). | +| `CACHED` | Not evaluated; a prior decision for this key was reused. | - // Optional: API endpoint (defaults to production) - apiUrl: 'https://in.webdecoy.com', +`ERROR` is not a denial. It means no verdict was reached (for example WebDecoy could not be reached, or the request had no IP), and `allowed` is `true`. - // Optional: Enable TLS fingerprinting (default: true) - enableTLSFingerprinting: true, +`ProtectResult` is the exported interface type for this decision. - // Optional: Threat score threshold for blocking (default: 80) - threatScoreThreshold: 70, +## Local rules - // Optional: Request timeout in milliseconds (default: 5000) - timeout: 5000, +Rules run in-process, in order, before any server call. The first `DENY` or `THROTTLE` decides. When you pass no `rules`, the SDK arms `tripwire()` with its built-in scanner-bait paths; pass `rules: []` to opt out. - // Optional: Enable debug logging (default: false) - debug: false, +```ts +import { WebDecoy, tripwire, rateLimit, filter } from '@webdecoy/node'; - // Optional: Reject unauthorized TLS certificates (default: true) - tlsRejectUnauthorized: true, +const wd = new WebDecoy({ + rules: [ + tripwire({ paths: ['/admin-backup.zip'] }), // plus built-in paths such as /.env + rateLimit({ max: 100, window: 60 }), // 100 requests per 60 s per IP + filter({ expression: 'ip.tor or ip.vpn' }), // needs an apiKey (IP enrichment) + ], }); ``` -## API Reference +| Rule | What it does | Needs an API key? | +|---|---|---| +| `tripwire({ paths?, prefixes?, patterns?, includeDefaults?, action?, dryRun? })` | Matches requests for decoy and scanner-bait paths. | No | +| `honeytoken()` | Returns `{ path, linkHtml }`: a hidden decoy link and the path to arm with `tripwire({ paths: [path] })`. | No | +| `rateLimit({ max, window, algorithm?, keyBy?, store?, action?, dryRun? })` | Fixed or sliding window, keyed by IP by default. In-memory unless you pass a shared `store` (for example `upstashRateLimitStore()`). | No | +| `attackSignatures({ inspect?, exclude?, action?, dryRun? })` | Denies requests carrying unambiguous injection payloads. | No | +| `webBotAuth()` | Verifies Web Bot Auth (RFC 9421) agent signatures and denies impersonators of known agents. | No | +| `botPolicy({ deny, allow })` | One crawler policy that produces both your `robots.txt` and the rule that enforces it. | No | +| `filter({ expression, action?, dryRun? })` | Expressions over IP reputation and geo, such as `ip.tor` or `ip.country in ["CN", "RU"]`. | Yes | -### `WebDecoy` +A tripwire match is evidence, not proof of intent: link prefetchers, preview bots and your own security scanners can request a hidden or scanner-bait path. Use `dryRun: true` on a rule to observe it before enforcing. -Main SDK class for bot detection. +## Fetch runtimes (Bun, Deno, Workers, Astro, SvelteKit, Remix) -#### `protect(metadata: RequestMetadata, options?: ProtectOptions): Promise` +`createFetchGuard()` wraps the SDK for any runtime that hands you a WHATWG `Request`. It is the same implementation `@webdecoy/hono` uses. -Analyze and protect a request. +```ts +import { createFetchGuard } from '@webdecoy/node'; -```typescript -const result = await webdecoy.protect({ - method: 'GET', - path: '/api/data', - ip: '203.0.113.42', - user_agent: 'Mozilla/5.0...', - headers: { /* request headers */ }, - timestamp: Date.now(), -}); +const guard = createFetchGuard({ apiKey: process.env.WEBDECOY_API_KEY }); + +export default { + async fetch(request: Request): Promise { + const { response } = await guard.check(request); + if (response) return response; // only ever set in enforce mode + return guard.decorate(await handle(request)); // handle() is your app + }, +}; ``` -**Returns:** -```typescript -interface ProtectResult { - allowed: boolean; - detection: { - decision: 'allow' | 'block' | 'challenge'; - confidence: number; // 0-100 threat score - threat_level: 'MINIMAL' | 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'; - bot_detected: boolean; - bot_type?: string; - detection_id: string; - rule_enforced: boolean; - }; - error?: string; -} +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 + +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. + +```ts +// middleware.ts (Astro, SvelteKit, Nuxt, Remix or a static site) +export { default } from '@webdecoy/node/vercel'; ``` -#### `validateConfig(): Promise<{ valid: boolean; error?: string }>` +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/). -Validate your API key and configuration. +## Environment variables -#### `getConfig(): Readonly>` +The SDK reads only these, and only in the features named: -Get the current configuration. +| Variable | Read by | +|---|---| +| `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. | -## Types +`WEBDECOY_API_KEY` is a naming convention used in these docs, not something the SDK reads. -All TypeScript types are exported: +## Configuration -```typescript -import type { - WebDecoyConfig, - RequestMetadata, - SDKDetectionResponse, - ProtectResult, - ProtectOptions, - TLSInfo, - LocalAnalysis, - SDKDetectionRequest, -} from '@webdecoy/node'; +```ts +const wd = new WebDecoy({ + apiKey: process.env.WEBDECOY_API_KEY, // optional; without it, local rules only + rules: [tripwire()], // optional; default [tripwire()], [] to opt out + apiUrl: 'https://in.webdecoy.com', // optional (default shown) + threatScoreThreshold: 80, // optional, 0-100 (default 80) + timeout: 5000, // optional, ms (default 5000) + enableTLSFingerprinting: true, // optional (default true) + tlsRejectUnauthorized: true, // optional (default true) + countAIReferrals: true, // optional (default true; aggregate counts, only with an apiKey) + debug: false, // optional (default false) +}); ``` -## Self-Hosted Captcha & Detection Engine +Also accepted: `characteristics` (what identifies the same caller for rate limits and caching; default the client IP), `decisionCache`, `webBotAuth`, `logger` (any object with `debug`/`info`/`warn`/`error`; `fromPino()` adapts pino) and `tracer` (an OpenTelemetry tracer). -In addition to the API-backed `protect()` flow above, the SDK ships a fully -**in-process** bot-detection engine and captcha — no remote call required. It -scores ~40 behavioral, environmental, and fingerprint signals collected by the -[`@webdecoy/client`](https://www.npmjs.com/package/@webdecoy/client) browser -widget, verifies a SHA-256 proof-of-work, and issues a signed session token. +`protect()` also takes per-request options: `threshold`, `skipLocalAnalysis` and `metadata`. -``` -Browser (@webdecoy/client) Your server (@webdecoy/node) - collect signals + solve PoW ──▶ Captcha.verify() - ├─ verify proof-of-work - ├─ score signals (in-process engine) - └─ issue session token on success +Without an API key no request leaves your server. With one, a request goes to WebDecoy only when local analysis flags it as needing verification (or carries TLS details); that call is awaited, bounded by `timeout`, and fails open on error. + +## Client IP behind a proxy + +Rate limits and detections are keyed on the client address. `X-Forwarded-For` is partly written by the client, so read it only as far as your own infrastructure wrote it: + +```ts +import { resolveClientIp } from '@webdecoy/node'; + +const ip = resolveClientIp({ + headers: req.headers, + peer: req.socket.remoteAddress, + trustProxy: 1, // proxies in front of this app; or 'cloudflare', 'railway', or your proxies' CIDRs +}); ``` -### Mounting the endpoints +`trustProxy` defaults to `false` here (believe no forwarding header). The adapters accept the same option. -Use your framework adapter (or `createCaptchaEndpoints` directly). The handler -serves `GET /__webdecoy/challenge`, `POST /__webdecoy/verify`, `POST -/__webdecoy/score`, and `POST /__webdecoy/token/verify`. +## Self-hosted captcha and detection engine -```typescript +The SDK also ships an in-process captcha: it scores behavioral, environmental and fingerprint signals collected by [`@webdecoy/client`](https://www.npmjs.com/package/@webdecoy/client), verifies a SHA-256 proof of work, and issues a signed session token. No remote call is needed. + +Mount the endpoints with your adapter (`webdecoyCaptcha` in Express, `webdecoyCaptchaPlugin` in Fastify, `createCaptchaHandler` in Next.js) or with `createCaptchaEndpoints()`. They serve `GET /__webdecoy/challenge`, `POST /__webdecoy/verify`, `POST /__webdecoy/score` and `POST /__webdecoy/token/verify`. + +```ts import express from 'express'; import { webdecoyCaptcha } from '@webdecoy/express'; +import { Captcha } from '@webdecoy/node'; const app = express(); app.use(express.json()); - -app.use( - webdecoyCaptcha({ - secret: process.env.WEBDECOY_SECRET, // required in production - }), -); -``` - -Then verify the token your form receives on a protected route: - -```typescript -import { Captcha } from '@webdecoy/node'; +app.use(webdecoyCaptcha({ secret: process.env.WEBDECOY_SECRET })); // required in production const captcha = new Captcha({ secret: process.env.WEBDECOY_SECRET }); @@ -177,61 +231,35 @@ app.post('/login', async (req, res) => { }); ``` -### Using the engine directly +`WEBDECOY_SECRET` is just the variable name used here; pass the value as `secret`. Generate one with `openssl rand -hex 32`. Challenge and token stores are in memory by default; for serverless or multi-instance deployments, pass shared `challengeStore` and `tokenStore` implementations. -For full control, score raw signals yourself: +To score signals yourself, use `new DetectionEngine(options).score(signals, context)`. -```typescript -import { DetectionEngine } from '@webdecoy/node'; +## Testing your rules -const engine = new DetectionEngine({ requirePoW: false }); -const verdict = engine.score(signals, { - ip, - siteKey: 'site', - userAgent, - headers, -}); -// verdict: { success, score, recommendation: 'allow'|'challenge'|'block', categoryScores, detections } -``` +```ts +import { createTestHarness, get, expectDenied, expectAllowed } from '@webdecoy/node/testing'; +import { tripwire } from '@webdecoy/node'; -> **Note on the scoring model:** the verdict is a confidence-weighted blend -> across categories, so no single signal can cross the block threshold alone — -> a missing proof-of-work on an otherwise-clean request yields `challenge`, not -> `block`. Tune category weights via the `weights` option. +const wd = createTestHarness({ rules: [tripwire()] }); -### Security & deployment notes +test('a scanner is denied and a visitor is not', async () => { + expectDenied(await wd.protect(get('/.env')), { rule: 'tripwire' }); + expectAllowed(await wd.protect(get('/'))); +}); +``` -- **`secret`** signs challenges and tokens. It is **required in production** - (`NODE_ENV=production`); a missing or default secret throws. Generate one with - `openssl rand -hex 32`. -- Challenge/token/fingerprint stores are **in-memory** by default. For - serverless or multi-instance deployments, supply a shared store via the - `challengeStore` / `tokenStore` options (the `ChallengeStore` / `TokenStore` - interfaces are the seam for Redis). -- IP reputation (VPN/proxy/Tor, abuse score, geo) is still served by - `api.webdecoy.com` via the SDK's IP-enrichment client. +The harness is offline by default: it drops any `apiKey` unless you pass `allowNetwork: true`. -## Framework Integrations +## Verify the install -For Express.js, use the dedicated middleware package: +With an `apiKey` configured, send one request with the reserved test User-Agent: ```bash -npm install @webdecoy/express +curl -A "WebDecoy-Test/1.0" http://localhost:3000/ ``` -See [@webdecoy/express](https://www.npmjs.com/package/@webdecoy/express) for details. - -## Getting an API Key - -1. Sign up at [app.webdecoy.com](https://app.webdecoy.com) -2. Create a new organization and property -3. Generate an API key in Settings - -API keys start with `sk_live_` for production or `sk_test_` for testing. - -## Documentation - -For full documentation, visit the [GitHub repository](https://github.com/WebDecoy/node). +A detection labeled **Test** appears on the **Detections** page within a few seconds. Without an `apiKey` nothing is reported; the decision's `error` says so. See [Verify your install](https://docs.webdecoy.com/getting-started/verify-installation/). ## License diff --git a/packages/webdecoy/src/decision.test.ts b/packages/webdecoy/src/decision.test.ts index 7f348c9..6f23e30 100644 --- a/packages/webdecoy/src/decision.test.ts +++ b/packages/webdecoy/src/decision.test.ts @@ -26,6 +26,12 @@ const ctx = (over: Partial = {}): RuleContext => ({ }); describe('the decision the SDK returns', () => { + it('constructs with no config at all', async () => { + const wd = new WebDecoy(); + const d = await wd.protect(req({ path: '/.env' })); + expect(d.deniedBy('tripwire')).toBe(true); + }); + it('keeps `allowed` meaning what it meant before', async () => { const wd = new WebDecoy({ rules: [] }); const d = await wd.protect(req()); diff --git a/packages/webdecoy/src/sdk.ts b/packages/webdecoy/src/sdk.ts index 05e829a..3f032fd 100644 --- a/packages/webdecoy/src/sdk.ts +++ b/packages/webdecoy/src/sdk.ts @@ -56,7 +56,7 @@ export class WebDecoy { private readonly tracer?: Tracer; private readonly decisionCache: DecisionCache | null; - constructor(config: WebDecoyConfig) { + constructor(config: WebDecoyConfig = {}) { const hasApiKey = !!config.apiKey; // Validate API key format if provided