@webdecoy/nextjs 0.11.1 → 0.13.0

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.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
- import { ProtectOptions, WebDecoyConfig, EdgeVerdict, SiteHoneytoken, CaptchaEndpointsOptions } from '@webdecoy/node';
2
+ import { ProtectOptions, TrustedProxies, SDKDetectionResponse, ProtectResult, WebDecoyConfig, EdgeVerdict, SiteHoneytoken, CaptchaEndpointsOptions } from '@webdecoy/node';
3
3
  export { CaptchaEndpointsOptions, EdgeClass, EdgeVerdict, ProtectResult, RequestMetadata, SDKDetectionResponse, SiteHoneytoken, WebDecoyConfig } from '@webdecoy/node';
4
4
 
5
5
  /**
@@ -20,15 +20,43 @@ interface WebDecoyMiddlewareOptions extends ProtectOptions {
20
20
  */
21
21
  mode?: 'monitor' | 'enforce';
22
22
  /**
23
- * Custom function to extract IP address from request
24
- * By default, uses x-forwarded-for or x-real-ip headers
23
+ * How many proxies sit between the client and this middleware, or which ones.
24
+ * Defaults to `1` — the hosting platform in front of you.
25
+ *
26
+ * THIS CHANGED IN 0.12.0, and it is a behaviour change worth reading.
27
+ *
28
+ * Before, the middleware read the LEFTMOST `X-Forwarded-For` value. That is
29
+ * the one value in the header the client writes itself, so a single
30
+ * `-H 'X-Forwarded-For: 1.2.3.4'` bought a fresh rate-limit bucket per forged
31
+ * address and put an address of the caller's choosing on every detection we
32
+ * reported. It now reads from the right, past the hops you say you have.
33
+ *
34
+ * Edge middleware has no socket to fall back on, so unlike the Express and
35
+ * Fastify adapters there is no safe "believe nothing" default here — `1` is
36
+ * correct on Vercel and on any single-proxy deployment. Behind a CDN in front
37
+ * of your platform, set `2`. Behind Cloudflare with the origin locked to it,
38
+ * `'cloudflare'` is stronger than counting.
39
+ */
40
+ trustProxy?: TrustedProxies;
41
+ /**
42
+ * Custom function to extract IP address from request.
43
+ *
44
+ * Overrides `trustProxy` entirely — you are choosing the address yourself.
25
45
  */
26
46
  getIP?: (req: NextRequest) => string;
27
47
  /**
28
48
  * Custom function to handle blocked requests
29
49
  * By default, returns 403 Forbidden JSON response
30
50
  */
31
- onBlocked?: (req: NextRequest, detection: any) => NextResponse;
51
+ /**
52
+ * Called when a request would be blocked.
53
+ *
54
+ * `detection` is the detection response, as before. `decision` is the full
55
+ * typed verdict — `conclusion`, every rule's outcome including the ones that
56
+ * dry-ran or never ran, and `deniedBy('tripwire')` — for handlers that need to
57
+ * know WHY rather than just THAT.
58
+ */
59
+ onBlocked?: (req: NextRequest, detection: SDKDetectionResponse, decision: ProtectResult) => NextResponse;
32
60
  /**
33
61
  * Custom function to handle errors
34
62
  * By default, logs error and allows request (fail open)
@@ -225,10 +253,17 @@ declare function honeytokenLink(apiKey: string, options?: {
225
253
  * ```
226
254
  */
227
255
 
256
+ interface NextCaptchaOptions extends CaptchaEndpointsOptions {
257
+ /**
258
+ * How many proxies sit between the client and this handler, or which ones.
259
+ * Defaults to `1`. Same meaning as the middleware's option.
260
+ */
261
+ trustProxy?: TrustedProxies;
262
+ }
228
263
  interface NextCaptchaHandlers {
229
264
  GET: (req: Request) => Promise<Response>;
230
265
  POST: (req: Request) => Promise<Response>;
231
266
  }
232
- declare function createCaptchaHandler(options?: CaptchaEndpointsOptions): NextCaptchaHandlers;
267
+ declare function createCaptchaHandler(options?: NextCaptchaOptions): NextCaptchaHandlers;
233
268
 
234
- export { type NextCaptchaHandlers, type WebDecoyMiddlewareOptions, type WithBotProtectionOptions, createCaptchaHandler, getEdgeVerdict, honeytokenLink, withBotProtection, withWebDecoy };
269
+ export { type NextCaptchaHandlers, type NextCaptchaOptions, type WebDecoyMiddlewareOptions, type WithBotProtectionOptions, createCaptchaHandler, getEdgeVerdict, honeytokenLink, withBotProtection, withWebDecoy };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
- import { ProtectOptions, WebDecoyConfig, EdgeVerdict, SiteHoneytoken, CaptchaEndpointsOptions } from '@webdecoy/node';
2
+ import { ProtectOptions, TrustedProxies, SDKDetectionResponse, ProtectResult, WebDecoyConfig, EdgeVerdict, SiteHoneytoken, CaptchaEndpointsOptions } from '@webdecoy/node';
3
3
  export { CaptchaEndpointsOptions, EdgeClass, EdgeVerdict, ProtectResult, RequestMetadata, SDKDetectionResponse, SiteHoneytoken, WebDecoyConfig } from '@webdecoy/node';
4
4
 
5
5
  /**
@@ -20,15 +20,43 @@ interface WebDecoyMiddlewareOptions extends ProtectOptions {
20
20
  */
21
21
  mode?: 'monitor' | 'enforce';
22
22
  /**
23
- * Custom function to extract IP address from request
24
- * By default, uses x-forwarded-for or x-real-ip headers
23
+ * How many proxies sit between the client and this middleware, or which ones.
24
+ * Defaults to `1` — the hosting platform in front of you.
25
+ *
26
+ * THIS CHANGED IN 0.12.0, and it is a behaviour change worth reading.
27
+ *
28
+ * Before, the middleware read the LEFTMOST `X-Forwarded-For` value. That is
29
+ * the one value in the header the client writes itself, so a single
30
+ * `-H 'X-Forwarded-For: 1.2.3.4'` bought a fresh rate-limit bucket per forged
31
+ * address and put an address of the caller's choosing on every detection we
32
+ * reported. It now reads from the right, past the hops you say you have.
33
+ *
34
+ * Edge middleware has no socket to fall back on, so unlike the Express and
35
+ * Fastify adapters there is no safe "believe nothing" default here — `1` is
36
+ * correct on Vercel and on any single-proxy deployment. Behind a CDN in front
37
+ * of your platform, set `2`. Behind Cloudflare with the origin locked to it,
38
+ * `'cloudflare'` is stronger than counting.
39
+ */
40
+ trustProxy?: TrustedProxies;
41
+ /**
42
+ * Custom function to extract IP address from request.
43
+ *
44
+ * Overrides `trustProxy` entirely — you are choosing the address yourself.
25
45
  */
26
46
  getIP?: (req: NextRequest) => string;
27
47
  /**
28
48
  * Custom function to handle blocked requests
29
49
  * By default, returns 403 Forbidden JSON response
30
50
  */
31
- onBlocked?: (req: NextRequest, detection: any) => NextResponse;
51
+ /**
52
+ * Called when a request would be blocked.
53
+ *
54
+ * `detection` is the detection response, as before. `decision` is the full
55
+ * typed verdict — `conclusion`, every rule's outcome including the ones that
56
+ * dry-ran or never ran, and `deniedBy('tripwire')` — for handlers that need to
57
+ * know WHY rather than just THAT.
58
+ */
59
+ onBlocked?: (req: NextRequest, detection: SDKDetectionResponse, decision: ProtectResult) => NextResponse;
32
60
  /**
33
61
  * Custom function to handle errors
34
62
  * By default, logs error and allows request (fail open)
@@ -225,10 +253,17 @@ declare function honeytokenLink(apiKey: string, options?: {
225
253
  * ```
226
254
  */
227
255
 
256
+ interface NextCaptchaOptions extends CaptchaEndpointsOptions {
257
+ /**
258
+ * How many proxies sit between the client and this handler, or which ones.
259
+ * Defaults to `1`. Same meaning as the middleware's option.
260
+ */
261
+ trustProxy?: TrustedProxies;
262
+ }
228
263
  interface NextCaptchaHandlers {
229
264
  GET: (req: Request) => Promise<Response>;
230
265
  POST: (req: Request) => Promise<Response>;
231
266
  }
232
- declare function createCaptchaHandler(options?: CaptchaEndpointsOptions): NextCaptchaHandlers;
267
+ declare function createCaptchaHandler(options?: NextCaptchaOptions): NextCaptchaHandlers;
233
268
 
234
- export { type NextCaptchaHandlers, type WebDecoyMiddlewareOptions, type WithBotProtectionOptions, createCaptchaHandler, getEdgeVerdict, honeytokenLink, withBotProtection, withWebDecoy };
269
+ export { type NextCaptchaHandlers, type NextCaptchaOptions, type WebDecoyMiddlewareOptions, type WithBotProtectionOptions, createCaptchaHandler, getEdgeVerdict, honeytokenLink, withBotProtection, withWebDecoy };
package/dist/index.js CHANGED
@@ -31,20 +31,13 @@ module.exports = __toCommonJS(index_exports);
31
31
  // src/middleware.ts
32
32
  var import_server = require("next/server");
33
33
  var import_node = require("@webdecoy/node");
34
- function defaultGetIP(req) {
35
- const forwardedFor = req.headers.get("x-forwarded-for");
36
- if (forwardedFor) {
37
- return forwardedFor.split(",")[0].trim();
38
- }
39
- const realIP = req.headers.get("x-real-ip");
40
- if (realIP) {
41
- return realIP;
42
- }
43
- const vercelIP = req.headers.get("x-vercel-forwarded-for");
44
- if (vercelIP) {
45
- return vercelIP.split(",")[0].trim();
46
- }
47
- return "127.0.0.1";
34
+ function resolveIP(req, trustProxy) {
35
+ const fromChain = (0, import_node.resolveClientIp)({
36
+ headers: req.headers,
37
+ trustProxy: trustProxy ?? 1
38
+ });
39
+ if (fromChain) return fromChain;
40
+ return (0, import_node.normalizeIp)(req.headers.get("x-real-ip")) ?? (0, import_node.normalizeIp)(req.headers.get("x-vercel-forwarded-for")?.split(",").pop()) ?? "127.0.0.1";
48
41
  }
49
42
  function defaultOnBlocked(req, detection) {
50
43
  return import_server.NextResponse.json(
@@ -73,7 +66,7 @@ function shouldSkipPath(path, skipPaths) {
73
66
  }
74
67
  function withWebDecoy(config) {
75
68
  const sdk = new import_node.WebDecoy(config);
76
- const getIP2 = config.getIP || defaultGetIP;
69
+ const getIP2 = config.getIP || ((req) => resolveIP(req, config.trustProxy));
77
70
  const onBlocked = config.onBlocked || defaultOnBlocked;
78
71
  const mode = config.mode ?? "monitor";
79
72
  const onError = config.onError || defaultOnError;
@@ -94,6 +87,9 @@ function withWebDecoy(config) {
94
87
  ip: getIP2(req),
95
88
  user_agent: req.headers.get("user-agent") || void 0,
96
89
  headers,
90
+ // The query is where injection payloads live, and it is not part of
91
+ // the routed path, so attackSignatures() cannot see it otherwise.
92
+ query: req.nextUrl.search ? req.nextUrl.search.slice(1) : void 0,
97
93
  timestamp: Date.now()
98
94
  };
99
95
  const result = await sdk.protect(metadata, {
@@ -150,7 +146,7 @@ function withWebDecoy(config) {
150
146
  }
151
147
  return import_server.NextResponse.next({ request: { headers: requestHeaders } });
152
148
  } else {
153
- return onBlocked(req, result.detection);
149
+ return onBlocked(req, result.detection, result);
154
150
  }
155
151
  } catch (error) {
156
152
  const errorResponse = onError(req, error);
@@ -167,14 +163,17 @@ function withBotProtection(handler, config) {
167
163
  return (async (...args) => {
168
164
  const [req, res] = args;
169
165
  try {
170
- const forwardedFor = req.headers["x-forwarded-for"];
171
- const ip = forwardedFor ? (Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor).split(",")[0].trim() : req.headers["x-real-ip"] || req.socket?.remoteAddress || "127.0.0.1";
166
+ const peer = req.socket?.remoteAddress;
167
+ const ip = (0, import_node.resolveClientIp)({ headers: req.headers, peer, trustProxy: config.trustProxy }) ?? (0, import_node.normalizeIp)(peer) ?? "127.0.0.1";
172
168
  const metadata = {
173
169
  method: req.method || "GET",
174
170
  path: req.url || "/",
175
- ip: typeof ip === "string" ? ip : "127.0.0.1",
171
+ ip,
176
172
  user_agent: req.headers["user-agent"],
177
173
  headers: req.headers,
174
+ // The query is where injection payloads live, and it is not part of
175
+ // the routed path, so attackSignatures() cannot see it otherwise.
176
+ query: req.url?.includes("?") ? req.url.slice(req.url.indexOf("?") + 1) : void 0,
178
177
  timestamp: Date.now()
179
178
  };
180
179
  const result = await sdk.protect(metadata, {
@@ -198,7 +197,9 @@ function withBotProtection(handler, config) {
198
197
  detection_id: result.detection?.detection_id
199
198
  });
200
199
  }
201
- req.webdecoy = result.detection;
200
+ const annotated = req;
201
+ annotated.webdecoy = result.detection;
202
+ annotated.webdecoyDecision = result;
202
203
  } catch (error) {
203
204
  console.error("[WebDecoy] Protection error:", error);
204
205
  }
@@ -237,10 +238,10 @@ function honeytokenLink(apiKey, options = {}) {
237
238
 
238
239
  // src/captcha.ts
239
240
  var import_node4 = require("@webdecoy/node");
240
- function getIP(headers) {
241
- const forwarded = headers.get("x-forwarded-for");
242
- if (forwarded) return forwarded.split(",")[0].trim();
243
- return headers.get("x-real-ip") || headers.get("x-vercel-forwarded-for") || "127.0.0.1";
241
+ function getIP(headers, trustProxy) {
242
+ const fromChain = (0, import_node4.resolveClientIp)({ headers, trustProxy: trustProxy ?? 1 });
243
+ if (fromChain) return fromChain;
244
+ return (0, import_node4.normalizeIp)(headers.get("x-real-ip")) ?? (0, import_node4.normalizeIp)(headers.get("x-vercel-forwarded-for")?.split(",").pop()) ?? "127.0.0.1";
244
245
  }
245
246
  function headersToRecord(headers) {
246
247
  const out = {};
@@ -272,7 +273,7 @@ function createCaptchaHandler(options) {
272
273
  query,
273
274
  headers,
274
275
  body,
275
- ip: getIP(req.headers)
276
+ ip: getIP(req.headers, options?.trustProxy)
276
277
  });
277
278
  if (!result) {
278
279
  return new Response(JSON.stringify({ error: "not_found" }), {
package/dist/index.mjs CHANGED
@@ -1,20 +1,17 @@
1
1
  // src/middleware.ts
2
2
  import { NextResponse } from "next/server";
3
- import { WebDecoy } from "@webdecoy/node";
4
- function defaultGetIP(req) {
5
- const forwardedFor = req.headers.get("x-forwarded-for");
6
- if (forwardedFor) {
7
- return forwardedFor.split(",")[0].trim();
8
- }
9
- const realIP = req.headers.get("x-real-ip");
10
- if (realIP) {
11
- return realIP;
12
- }
13
- const vercelIP = req.headers.get("x-vercel-forwarded-for");
14
- if (vercelIP) {
15
- return vercelIP.split(",")[0].trim();
16
- }
17
- return "127.0.0.1";
3
+ import {
4
+ WebDecoy,
5
+ resolveClientIp,
6
+ normalizeIp
7
+ } from "@webdecoy/node";
8
+ function resolveIP(req, trustProxy) {
9
+ const fromChain = resolveClientIp({
10
+ headers: req.headers,
11
+ trustProxy: trustProxy ?? 1
12
+ });
13
+ if (fromChain) return fromChain;
14
+ return normalizeIp(req.headers.get("x-real-ip")) ?? normalizeIp(req.headers.get("x-vercel-forwarded-for")?.split(",").pop()) ?? "127.0.0.1";
18
15
  }
19
16
  function defaultOnBlocked(req, detection) {
20
17
  return NextResponse.json(
@@ -43,7 +40,7 @@ function shouldSkipPath(path, skipPaths) {
43
40
  }
44
41
  function withWebDecoy(config) {
45
42
  const sdk = new WebDecoy(config);
46
- const getIP2 = config.getIP || defaultGetIP;
43
+ const getIP2 = config.getIP || ((req) => resolveIP(req, config.trustProxy));
47
44
  const onBlocked = config.onBlocked || defaultOnBlocked;
48
45
  const mode = config.mode ?? "monitor";
49
46
  const onError = config.onError || defaultOnError;
@@ -64,6 +61,9 @@ function withWebDecoy(config) {
64
61
  ip: getIP2(req),
65
62
  user_agent: req.headers.get("user-agent") || void 0,
66
63
  headers,
64
+ // The query is where injection payloads live, and it is not part of
65
+ // the routed path, so attackSignatures() cannot see it otherwise.
66
+ query: req.nextUrl.search ? req.nextUrl.search.slice(1) : void 0,
67
67
  timestamp: Date.now()
68
68
  };
69
69
  const result = await sdk.protect(metadata, {
@@ -120,7 +120,7 @@ function withWebDecoy(config) {
120
120
  }
121
121
  return NextResponse.next({ request: { headers: requestHeaders } });
122
122
  } else {
123
- return onBlocked(req, result.detection);
123
+ return onBlocked(req, result.detection, result);
124
124
  }
125
125
  } catch (error) {
126
126
  const errorResponse = onError(req, error);
@@ -137,14 +137,17 @@ function withBotProtection(handler, config) {
137
137
  return (async (...args) => {
138
138
  const [req, res] = args;
139
139
  try {
140
- const forwardedFor = req.headers["x-forwarded-for"];
141
- const ip = forwardedFor ? (Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor).split(",")[0].trim() : req.headers["x-real-ip"] || req.socket?.remoteAddress || "127.0.0.1";
140
+ const peer = req.socket?.remoteAddress;
141
+ const ip = resolveClientIp({ headers: req.headers, peer, trustProxy: config.trustProxy }) ?? normalizeIp(peer) ?? "127.0.0.1";
142
142
  const metadata = {
143
143
  method: req.method || "GET",
144
144
  path: req.url || "/",
145
- ip: typeof ip === "string" ? ip : "127.0.0.1",
145
+ ip,
146
146
  user_agent: req.headers["user-agent"],
147
147
  headers: req.headers,
148
+ // The query is where injection payloads live, and it is not part of
149
+ // the routed path, so attackSignatures() cannot see it otherwise.
150
+ query: req.url?.includes("?") ? req.url.slice(req.url.indexOf("?") + 1) : void 0,
148
151
  timestamp: Date.now()
149
152
  };
150
153
  const result = await sdk.protect(metadata, {
@@ -168,7 +171,9 @@ function withBotProtection(handler, config) {
168
171
  detection_id: result.detection?.detection_id
169
172
  });
170
173
  }
171
- req.webdecoy = result.detection;
174
+ const annotated = req;
175
+ annotated.webdecoy = result.detection;
176
+ annotated.webdecoyDecision = result;
172
177
  } catch (error) {
173
178
  console.error("[WebDecoy] Protection error:", error);
174
179
  }
@@ -206,11 +211,15 @@ function honeytokenLink(apiKey, options = {}) {
206
211
  }
207
212
 
208
213
  // src/captcha.ts
209
- import { createCaptchaEndpoints } from "@webdecoy/node";
210
- function getIP(headers) {
211
- const forwarded = headers.get("x-forwarded-for");
212
- if (forwarded) return forwarded.split(",")[0].trim();
213
- return headers.get("x-real-ip") || headers.get("x-vercel-forwarded-for") || "127.0.0.1";
214
+ import {
215
+ createCaptchaEndpoints,
216
+ resolveClientIp as resolveClientIp2,
217
+ normalizeIp as normalizeIp2
218
+ } from "@webdecoy/node";
219
+ function getIP(headers, trustProxy) {
220
+ const fromChain = resolveClientIp2({ headers, trustProxy: trustProxy ?? 1 });
221
+ if (fromChain) return fromChain;
222
+ return normalizeIp2(headers.get("x-real-ip")) ?? normalizeIp2(headers.get("x-vercel-forwarded-for")?.split(",").pop()) ?? "127.0.0.1";
214
223
  }
215
224
  function headersToRecord(headers) {
216
225
  const out = {};
@@ -242,7 +251,7 @@ function createCaptchaHandler(options) {
242
251
  query,
243
252
  headers,
244
253
  body,
245
- ip: getIP(req.headers)
254
+ ip: getIP(req.headers, options?.trustProxy)
246
255
  });
247
256
  if (!result) {
248
257
  return new Response(JSON.stringify({ error: "not_found" }), {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webdecoy/nextjs",
3
- "version": "0.11.1",
3
+ "version": "0.13.0",
4
4
  "description": "Web Decoy middleware for Next.js",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -18,7 +18,7 @@
18
18
  "build": "tsup src/index.ts --format cjs,esm --dts --clean",
19
19
  "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
20
20
  "test": "jest --passWithNoTests",
21
- "lint": "eslint src/**/*.ts",
21
+ "lint": "eslint src --max-warnings 2",
22
22
  "clean": "rm -rf dist",
23
23
  "check:edge": "node ../../scripts/check-edge.mjs src/index.ts"
24
24
  },
@@ -42,7 +42,7 @@
42
42
  "url": "https://github.com/WebDecoy/node/issues"
43
43
  },
44
44
  "dependencies": {
45
- "@webdecoy/node": "^0.11.1"
45
+ "@webdecoy/node": "^0.13.0"
46
46
  },
47
47
  "peerDependencies": {
48
48
  "next": ">=13.0.0"
@@ -50,9 +50,6 @@
50
50
  "devDependencies": {
51
51
  "@types/jest": "^29.5.11",
52
52
  "@types/node": "^20.11.0",
53
- "@typescript-eslint/eslint-plugin": "^6.18.1",
54
- "@typescript-eslint/parser": "^6.18.1",
55
- "eslint": "^8.56.0",
56
53
  "jest": "^29.7.0",
57
54
  "next": "^14.0.0",
58
55
  "ts-jest": "^29.1.1",