@webdecoy/nextjs 0.1.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.
@@ -0,0 +1,81 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { WebDecoyConfig, ProtectOptions } from '@webdecoy/node';
3
+ export { ProtectResult, RequestMetadata, SDKDetectionResponse, WebDecoyConfig } from '@webdecoy/node';
4
+
5
+ /**
6
+ * Web Decoy Next.js Middleware
7
+ */
8
+
9
+ interface WebDecoyMiddlewareOptions extends ProtectOptions {
10
+ /**
11
+ * Custom function to extract IP address from request
12
+ * By default, uses x-forwarded-for or x-real-ip headers
13
+ */
14
+ getIP?: (req: NextRequest) => string;
15
+ /**
16
+ * Custom function to handle blocked requests
17
+ * By default, returns 403 Forbidden JSON response
18
+ */
19
+ onBlocked?: (req: NextRequest, detection: any) => NextResponse;
20
+ /**
21
+ * Custom function to handle errors
22
+ * By default, logs error and allows request (fail open)
23
+ */
24
+ onError?: (req: NextRequest, error: Error) => NextResponse | null;
25
+ /**
26
+ * Paths to skip protection (e.g., health checks, static assets)
27
+ */
28
+ skipPaths?: string[] | RegExp[];
29
+ /**
30
+ * Path patterns to match for protection
31
+ * Uses Next.js matcher syntax
32
+ */
33
+ matcher?: string[];
34
+ }
35
+ /**
36
+ * Create Next.js middleware for Web Decoy protection
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * // middleware.ts
41
+ * import { withWebDecoy } from '@webdecoy/nextjs';
42
+ *
43
+ * export default withWebDecoy({
44
+ * apiKey: process.env.WEBDECOY_API_KEY!,
45
+ * skipPaths: ['/_next', '/favicon.ico'],
46
+ * });
47
+ *
48
+ * export const config = {
49
+ * matcher: ['/api/:path*', '/protected/:path*'],
50
+ * };
51
+ * ```
52
+ */
53
+ declare function withWebDecoy(config: WebDecoyConfig & WebDecoyMiddlewareOptions): (req: NextRequest) => Promise<NextResponse>;
54
+ interface WithBotProtectionOptions extends WebDecoyMiddlewareOptions {
55
+ /**
56
+ * Block threshold (0-100). Requests with scores above this are blocked.
57
+ * Default: 80
58
+ */
59
+ blockThreshold?: number;
60
+ }
61
+ /**
62
+ * Higher-order function to wrap API route handlers with bot protection
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * // pages/api/protected.ts
67
+ * import { withBotProtection } from '@webdecoy/nextjs';
68
+ *
69
+ * async function handler(req: NextApiRequest, res: NextApiResponse) {
70
+ * res.json({ data: 'protected' });
71
+ * }
72
+ *
73
+ * export default withBotProtection(handler, {
74
+ * apiKey: process.env.WEBDECOY_API_KEY!,
75
+ * blockThreshold: 70,
76
+ * });
77
+ * ```
78
+ */
79
+ declare function withBotProtection<T extends (...args: any[]) => any>(handler: T, config: WebDecoyConfig & WithBotProtectionOptions): T;
80
+
81
+ export { type WebDecoyMiddlewareOptions, type WithBotProtectionOptions, withBotProtection, withWebDecoy };
@@ -0,0 +1,81 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { WebDecoyConfig, ProtectOptions } from '@webdecoy/node';
3
+ export { ProtectResult, RequestMetadata, SDKDetectionResponse, WebDecoyConfig } from '@webdecoy/node';
4
+
5
+ /**
6
+ * Web Decoy Next.js Middleware
7
+ */
8
+
9
+ interface WebDecoyMiddlewareOptions extends ProtectOptions {
10
+ /**
11
+ * Custom function to extract IP address from request
12
+ * By default, uses x-forwarded-for or x-real-ip headers
13
+ */
14
+ getIP?: (req: NextRequest) => string;
15
+ /**
16
+ * Custom function to handle blocked requests
17
+ * By default, returns 403 Forbidden JSON response
18
+ */
19
+ onBlocked?: (req: NextRequest, detection: any) => NextResponse;
20
+ /**
21
+ * Custom function to handle errors
22
+ * By default, logs error and allows request (fail open)
23
+ */
24
+ onError?: (req: NextRequest, error: Error) => NextResponse | null;
25
+ /**
26
+ * Paths to skip protection (e.g., health checks, static assets)
27
+ */
28
+ skipPaths?: string[] | RegExp[];
29
+ /**
30
+ * Path patterns to match for protection
31
+ * Uses Next.js matcher syntax
32
+ */
33
+ matcher?: string[];
34
+ }
35
+ /**
36
+ * Create Next.js middleware for Web Decoy protection
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * // middleware.ts
41
+ * import { withWebDecoy } from '@webdecoy/nextjs';
42
+ *
43
+ * export default withWebDecoy({
44
+ * apiKey: process.env.WEBDECOY_API_KEY!,
45
+ * skipPaths: ['/_next', '/favicon.ico'],
46
+ * });
47
+ *
48
+ * export const config = {
49
+ * matcher: ['/api/:path*', '/protected/:path*'],
50
+ * };
51
+ * ```
52
+ */
53
+ declare function withWebDecoy(config: WebDecoyConfig & WebDecoyMiddlewareOptions): (req: NextRequest) => Promise<NextResponse>;
54
+ interface WithBotProtectionOptions extends WebDecoyMiddlewareOptions {
55
+ /**
56
+ * Block threshold (0-100). Requests with scores above this are blocked.
57
+ * Default: 80
58
+ */
59
+ blockThreshold?: number;
60
+ }
61
+ /**
62
+ * Higher-order function to wrap API route handlers with bot protection
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * // pages/api/protected.ts
67
+ * import { withBotProtection } from '@webdecoy/nextjs';
68
+ *
69
+ * async function handler(req: NextApiRequest, res: NextApiResponse) {
70
+ * res.json({ data: 'protected' });
71
+ * }
72
+ *
73
+ * export default withBotProtection(handler, {
74
+ * apiKey: process.env.WEBDECOY_API_KEY!,
75
+ * blockThreshold: 70,
76
+ * });
77
+ * ```
78
+ */
79
+ declare function withBotProtection<T extends (...args: any[]) => any>(handler: T, config: WebDecoyConfig & WithBotProtectionOptions): T;
80
+
81
+ export { type WebDecoyMiddlewareOptions, type WithBotProtectionOptions, withBotProtection, withWebDecoy };
package/dist/index.js ADDED
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ withBotProtection: () => withBotProtection,
24
+ withWebDecoy: () => withWebDecoy
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/middleware.ts
29
+ var import_server = require("next/server");
30
+ var import_node = require("@webdecoy/node");
31
+ function defaultGetIP(req) {
32
+ const forwardedFor = req.headers.get("x-forwarded-for");
33
+ if (forwardedFor) {
34
+ return forwardedFor.split(",")[0].trim();
35
+ }
36
+ const realIP = req.headers.get("x-real-ip");
37
+ if (realIP) {
38
+ return realIP;
39
+ }
40
+ const vercelIP = req.headers.get("x-vercel-forwarded-for");
41
+ if (vercelIP) {
42
+ return vercelIP.split(",")[0].trim();
43
+ }
44
+ return "127.0.0.1";
45
+ }
46
+ function defaultOnBlocked(req, detection) {
47
+ return import_server.NextResponse.json(
48
+ {
49
+ error: "Forbidden",
50
+ message: "Access denied by Web Decoy protection",
51
+ detection_id: detection.detection_id
52
+ },
53
+ { status: 403 }
54
+ );
55
+ }
56
+ function defaultOnError(req, error) {
57
+ console.error("[WebDecoy] Middleware error:", error);
58
+ return null;
59
+ }
60
+ function shouldSkipPath(path, skipPaths) {
61
+ if (!skipPaths || skipPaths.length === 0) {
62
+ return false;
63
+ }
64
+ return skipPaths.some((pattern) => {
65
+ if (typeof pattern === "string") {
66
+ return path === pattern || path.startsWith(pattern);
67
+ }
68
+ return pattern.test(path);
69
+ });
70
+ }
71
+ function withWebDecoy(config) {
72
+ const sdk = new import_node.WebDecoy(config);
73
+ const getIP = config.getIP || defaultGetIP;
74
+ const onBlocked = config.onBlocked || defaultOnBlocked;
75
+ const onError = config.onError || defaultOnError;
76
+ const skipPaths = config.skipPaths;
77
+ return async (req) => {
78
+ try {
79
+ const pathname = req.nextUrl.pathname;
80
+ if (shouldSkipPath(pathname, skipPaths)) {
81
+ return import_server.NextResponse.next();
82
+ }
83
+ const headers = {};
84
+ req.headers.forEach((value, key) => {
85
+ headers[key] = value;
86
+ });
87
+ const metadata = {
88
+ method: req.method,
89
+ path: pathname,
90
+ ip: getIP(req),
91
+ user_agent: req.headers.get("user-agent") || void 0,
92
+ headers,
93
+ timestamp: Date.now()
94
+ };
95
+ const result = await sdk.protect(metadata, {
96
+ threshold: config.threshold,
97
+ skipLocalAnalysis: config.skipLocalAnalysis,
98
+ metadata: config.metadata
99
+ });
100
+ if (result.allowed) {
101
+ const response = import_server.NextResponse.next();
102
+ if (result.detection) {
103
+ response.headers.set("x-webdecoy-decision", result.detection.decision || "");
104
+ response.headers.set("x-webdecoy-detection-id", result.detection.detection_id || "");
105
+ }
106
+ return response;
107
+ } else {
108
+ return onBlocked(req, result.detection);
109
+ }
110
+ } catch (error) {
111
+ const errorResponse = onError(req, error);
112
+ if (errorResponse) {
113
+ return errorResponse;
114
+ }
115
+ return import_server.NextResponse.next();
116
+ }
117
+ };
118
+ }
119
+ function withBotProtection(handler, config) {
120
+ const sdk = new import_node.WebDecoy(config);
121
+ const threshold = config.blockThreshold ?? 80;
122
+ return (async (...args) => {
123
+ const [req, res] = args;
124
+ try {
125
+ const forwardedFor = req.headers["x-forwarded-for"];
126
+ const ip = forwardedFor ? (Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor).split(",")[0].trim() : req.headers["x-real-ip"] || req.socket?.remoteAddress || "127.0.0.1";
127
+ const metadata = {
128
+ method: req.method || "GET",
129
+ path: req.url || "/",
130
+ ip: typeof ip === "string" ? ip : "127.0.0.1",
131
+ user_agent: req.headers["user-agent"],
132
+ headers: req.headers,
133
+ timestamp: Date.now()
134
+ };
135
+ const result = await sdk.protect(metadata, {
136
+ threshold,
137
+ skipLocalAnalysis: config.skipLocalAnalysis,
138
+ metadata: config.metadata
139
+ });
140
+ if (!result.allowed) {
141
+ return res.status(403).json({
142
+ error: "Forbidden",
143
+ message: "Access denied by Web Decoy protection",
144
+ detection_id: result.detection?.detection_id
145
+ });
146
+ }
147
+ req.webdecoy = result.detection;
148
+ } catch (error) {
149
+ console.error("[WebDecoy] Protection error:", error);
150
+ }
151
+ return handler(...args);
152
+ });
153
+ }
154
+ // Annotate the CommonJS export names for ESM import in node:
155
+ 0 && (module.exports = {
156
+ withBotProtection,
157
+ withWebDecoy
158
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,130 @@
1
+ // src/middleware.ts
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";
18
+ }
19
+ function defaultOnBlocked(req, detection) {
20
+ return NextResponse.json(
21
+ {
22
+ error: "Forbidden",
23
+ message: "Access denied by Web Decoy protection",
24
+ detection_id: detection.detection_id
25
+ },
26
+ { status: 403 }
27
+ );
28
+ }
29
+ function defaultOnError(req, error) {
30
+ console.error("[WebDecoy] Middleware error:", error);
31
+ return null;
32
+ }
33
+ function shouldSkipPath(path, skipPaths) {
34
+ if (!skipPaths || skipPaths.length === 0) {
35
+ return false;
36
+ }
37
+ return skipPaths.some((pattern) => {
38
+ if (typeof pattern === "string") {
39
+ return path === pattern || path.startsWith(pattern);
40
+ }
41
+ return pattern.test(path);
42
+ });
43
+ }
44
+ function withWebDecoy(config) {
45
+ const sdk = new WebDecoy(config);
46
+ const getIP = config.getIP || defaultGetIP;
47
+ const onBlocked = config.onBlocked || defaultOnBlocked;
48
+ const onError = config.onError || defaultOnError;
49
+ const skipPaths = config.skipPaths;
50
+ return async (req) => {
51
+ try {
52
+ const pathname = req.nextUrl.pathname;
53
+ if (shouldSkipPath(pathname, skipPaths)) {
54
+ return NextResponse.next();
55
+ }
56
+ const headers = {};
57
+ req.headers.forEach((value, key) => {
58
+ headers[key] = value;
59
+ });
60
+ const metadata = {
61
+ method: req.method,
62
+ path: pathname,
63
+ ip: getIP(req),
64
+ user_agent: req.headers.get("user-agent") || void 0,
65
+ headers,
66
+ timestamp: Date.now()
67
+ };
68
+ const result = await sdk.protect(metadata, {
69
+ threshold: config.threshold,
70
+ skipLocalAnalysis: config.skipLocalAnalysis,
71
+ metadata: config.metadata
72
+ });
73
+ if (result.allowed) {
74
+ const response = NextResponse.next();
75
+ if (result.detection) {
76
+ response.headers.set("x-webdecoy-decision", result.detection.decision || "");
77
+ response.headers.set("x-webdecoy-detection-id", result.detection.detection_id || "");
78
+ }
79
+ return response;
80
+ } else {
81
+ return onBlocked(req, result.detection);
82
+ }
83
+ } catch (error) {
84
+ const errorResponse = onError(req, error);
85
+ if (errorResponse) {
86
+ return errorResponse;
87
+ }
88
+ return NextResponse.next();
89
+ }
90
+ };
91
+ }
92
+ function withBotProtection(handler, config) {
93
+ const sdk = new WebDecoy(config);
94
+ const threshold = config.blockThreshold ?? 80;
95
+ return (async (...args) => {
96
+ const [req, res] = args;
97
+ try {
98
+ const forwardedFor = req.headers["x-forwarded-for"];
99
+ const ip = forwardedFor ? (Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor).split(",")[0].trim() : req.headers["x-real-ip"] || req.socket?.remoteAddress || "127.0.0.1";
100
+ const metadata = {
101
+ method: req.method || "GET",
102
+ path: req.url || "/",
103
+ ip: typeof ip === "string" ? ip : "127.0.0.1",
104
+ user_agent: req.headers["user-agent"],
105
+ headers: req.headers,
106
+ timestamp: Date.now()
107
+ };
108
+ const result = await sdk.protect(metadata, {
109
+ threshold,
110
+ skipLocalAnalysis: config.skipLocalAnalysis,
111
+ metadata: config.metadata
112
+ });
113
+ if (!result.allowed) {
114
+ return res.status(403).json({
115
+ error: "Forbidden",
116
+ message: "Access denied by Web Decoy protection",
117
+ detection_id: result.detection?.detection_id
118
+ });
119
+ }
120
+ req.webdecoy = result.detection;
121
+ } catch (error) {
122
+ console.error("[WebDecoy] Protection error:", error);
123
+ }
124
+ return handler(...args);
125
+ });
126
+ }
127
+ export {
128
+ withBotProtection,
129
+ withWebDecoy
130
+ };
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@webdecoy/nextjs",
3
+ "version": "0.1.0",
4
+ "description": "Web Decoy middleware for Next.js",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "require": "./dist/index.js",
10
+ "import": "./dist/index.mjs",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean",
19
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
20
+ "test": "jest",
21
+ "lint": "eslint src/**/*.ts",
22
+ "clean": "rm -rf dist"
23
+ },
24
+ "keywords": [
25
+ "web-decoy",
26
+ "nextjs",
27
+ "next",
28
+ "middleware",
29
+ "bot-detection",
30
+ "security"
31
+ ],
32
+ "author": "Web Decoy",
33
+ "license": "MIT",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "https://github.com/webdecoy/webdecoy-node.git",
37
+ "directory": "packages/nextjs"
38
+ },
39
+ "dependencies": {
40
+ "@webdecoy/node": "*"
41
+ },
42
+ "peerDependencies": {
43
+ "next": ">=13.0.0"
44
+ },
45
+ "devDependencies": {
46
+ "@types/jest": "^29.5.11",
47
+ "@types/node": "^20.11.0",
48
+ "@typescript-eslint/eslint-plugin": "^6.18.1",
49
+ "@typescript-eslint/parser": "^6.18.1",
50
+ "eslint": "^8.56.0",
51
+ "jest": "^29.7.0",
52
+ "next": "^14.0.0",
53
+ "ts-jest": "^29.1.1",
54
+ "tsup": "^8.0.1",
55
+ "typescript": "^5.3.3"
56
+ },
57
+ "engines": {
58
+ "node": ">=18.0.0"
59
+ }
60
+ }