@webdecoy/nextjs 0.21.1 → 0.21.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +164 -0
  2. package/package.json +2 -2
package/README.md ADDED
@@ -0,0 +1,164 @@
1
+ # @webdecoy/nextjs
2
+
3
+ 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.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@webdecoy/nextjs.svg)](https://www.npmjs.com/package/@webdecoy/nextjs)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ npm install @webdecoy/nextjs @webdecoy/node
12
+ ```
13
+
14
+ `@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.
15
+
16
+ ## Quick start: detection middleware
17
+
18
+ ```ts
19
+ // middleware.ts (project root, or src/ if you use it)
20
+ import { withWebDecoy } from '@webdecoy/nextjs';
21
+
22
+ export default withWebDecoy({
23
+ apiKey: process.env.WEBDECOY_API_KEY!,
24
+ });
25
+
26
+ // Protect the routes that matter and leave static assets alone.
27
+ export const config = {
28
+ matcher: ['/api/:path*', '/checkout/:path*'],
29
+ };
30
+ ```
31
+
32
+ ### API key
33
+
34
+ `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.
35
+
36
+ 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.
37
+
38
+ ### Monitor mode
39
+
40
+ `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:
41
+
42
+ | Request header | Value |
43
+ |---|---|
44
+ | `x-webdecoy-decision` | The detection's `decision` (`allow`, `block` or `challenge`). |
45
+ | `x-webdecoy-detection-id` | The detection id. |
46
+ | `x-webdecoy-would-block` | `true` when enforce mode would have refused the request. |
47
+
48
+ 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`).
49
+
50
+ ## Local rules
51
+
52
+ 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:
53
+
54
+ ```ts
55
+ // middleware.ts
56
+ import { withWebDecoy } from '@webdecoy/nextjs';
57
+ import { tripwire, rateLimit } from '@webdecoy/node';
58
+
59
+ export default withWebDecoy({
60
+ apiKey: process.env.WEBDECOY_API_KEY,
61
+ rules: [
62
+ tripwire({ paths: ['/admin-backup.zip'] }),
63
+ rateLimit({ max: 100, window: 60 }),
64
+ ],
65
+ });
66
+ ```
67
+
68
+ `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.
69
+
70
+ ## Options
71
+
72
+ `withWebDecoy` accepts every core SDK option (`apiKey`, `rules`, `apiUrl`, `threatScoreThreshold`, `timeout`, `debug`, ...) and the per-request options `threshold`, `skipLocalAnalysis` and `metadata`, plus:
73
+
74
+ | Option | Default | Description |
75
+ |---|---|---|
76
+ | `mode` | `'monitor'` | `'monitor'` records and serves every request; `'enforce'` blocks. |
77
+ | `skipPaths` | none | Paths to skip, as strings or regular expressions. |
78
+ | `trustProxy` | `1` | How much of `X-Forwarded-For` to believe: a hop count, `'cloudflare'`, `'railway'`, or your proxies' CIDRs. `1` is right on Vercel. |
79
+ | `getIP` | derived from `trustProxy` | `(req) => string`. Overrides `trustProxy`. |
80
+ | `onBlocked` | `403` JSON | `(req, detection, decision) => NextResponse`. Enforce mode, server-score blocks. |
81
+ | `onError` | log and continue | `(req, error) => NextResponse \| null`. The middleware fails open. |
82
+
83
+ Use Next's own `export const config = { matcher }` to choose which routes the middleware runs on.
84
+
85
+ ## Clearance enforcement on Vercel
86
+
87
+ 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.
88
+
89
+ ```ts
90
+ // middleware.ts
91
+ import { withClearance } from '@webdecoy/nextjs';
92
+
93
+ export default withClearance();
94
+
95
+ export const config = {
96
+ // Everything but static assets. Keep /.well-known: the challenge uses it.
97
+ matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
98
+ };
99
+ ```
100
+
101
+ `withClearance()` reads these environment variables (or the matching options `siteKey`, `scannerId`, `sensorKey`, `ingest`):
102
+
103
+ | Variable | Where it comes from | Secret? |
104
+ |---|---|---|
105
+ | `WEBDECOY_SITE_KEY` | **Enforcement, Setup** in the dashboard | No |
106
+ | `WEBDECOY_SCANNER_ID` | **Enforcement, Setup** in the dashboard | No |
107
+ | `WEBDECOY_SENSOR_KEY` | **Enforcement, Setup** in the dashboard | Yes |
108
+ | `WEBDECOY_INGEST` | Optional override of the ingest endpoint | No |
109
+
110
+ 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/).
111
+
112
+ A project has one `middleware.ts`, so choose `withWebDecoy` or `withClearance` for it.
113
+
114
+ ## Pages Router API routes
115
+
116
+ `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`.
117
+
118
+ ```ts
119
+ // pages/api/protected.ts
120
+ import type { NextApiRequest, NextApiResponse } from 'next';
121
+ import { withBotProtection } from '@webdecoy/nextjs';
122
+
123
+ async function handler(req: NextApiRequest, res: NextApiResponse) {
124
+ res.json({ data: 'protected' });
125
+ }
126
+
127
+ export default withBotProtection(handler, {
128
+ apiKey: process.env.WEBDECOY_API_KEY,
129
+ blockThreshold: 80, // default
130
+ });
131
+ ```
132
+
133
+ It reads the socket address and trusts no forwarding header unless you pass `trustProxy`.
134
+
135
+ ## Other helpers
136
+
137
+ - `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.
138
+ - `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.
139
+ - `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`.
140
+
141
+ ## Environment variables
142
+
143
+ Only `withClearance()` reads environment variables (table above). `WEBDECOY_API_KEY` and `WEBDECOY_SECRET` are naming conventions: pass their values as `apiKey` and `secret`.
144
+
145
+ ## Verify the install
146
+
147
+ With an `apiKey` configured, send one request with the reserved test User-Agent to a path your `matcher` covers:
148
+
149
+ ```bash
150
+ curl -A "WebDecoy-Test/1.0" http://localhost:3000/api/health
151
+ ```
152
+
153
+ A detection labeled **Test** appears on the **Detections** page within a few seconds.
154
+
155
+ ## Documentation
156
+
157
+ - [Next.js middleware](https://docs.webdecoy.com/sdk-plugins/nextjs/)
158
+ - [Vercel middleware (clearance)](https://docs.webdecoy.com/installation/vercel-middleware/)
159
+ - [Install with an AI assistant](https://docs.webdecoy.com/installation/install-with-ai/): copy-paste snippets for every stack
160
+ - [Verify your install](https://docs.webdecoy.com/getting-started/verify-installation/)
161
+
162
+ ## License
163
+
164
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webdecoy/nextjs",
3
- "version": "0.21.1",
3
+ "version": "0.21.3",
4
4
  "description": "Web Decoy middleware for Next.js",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -42,7 +42,7 @@
42
42
  "url": "https://github.com/WebDecoy/node/issues"
43
43
  },
44
44
  "dependencies": {
45
- "@webdecoy/node": "^0.21.1"
45
+ "@webdecoy/node": "^0.21.3"
46
46
  },
47
47
  "peerDependencies": {
48
48
  "next": ">=13.0.0"