@webdecoy/express 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.
package/README.md ADDED
@@ -0,0 +1,123 @@
1
+ # @webdecoy/express
2
+
3
+ Web Decoy middleware for Express.js applications.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @webdecoy/express
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import express from 'express';
15
+ import { webdecoy } from '@webdecoy/express';
16
+
17
+ const app = express();
18
+
19
+ // Add Web Decoy protection
20
+ app.use(
21
+ webdecoy({
22
+ apiKey: process.env.WEBDECOY_API_KEY,
23
+ threatScoreThreshold: 70,
24
+ skipPaths: ['/health'],
25
+ })
26
+ );
27
+
28
+ app.get('/api/data', (req, res) => {
29
+ // Access detection info
30
+ console.log('Bot detected:', req.webdecoy?.bot_detected);
31
+ res.json({ data: 'protected' });
32
+ });
33
+
34
+ app.listen(3000);
35
+ ```
36
+
37
+ ## Middleware Options
38
+
39
+ ```typescript
40
+ interface WebDecoyMiddlewareOptions {
41
+ // Web Decoy SDK config
42
+ apiKey: string;
43
+ apiUrl?: string;
44
+ threatScoreThreshold?: number;
45
+
46
+ // Middleware-specific options
47
+ skipPaths?: string[] | RegExp[];
48
+ getIP?: (req: Request) => string;
49
+ onBlocked?: (req: Request, res: Response, detection: any) => void;
50
+ onError?: (req: Request, res: Response, error: Error) => void;
51
+ }
52
+ ```
53
+
54
+ ## Custom IP Extraction
55
+
56
+ By default, the middleware checks `X-Forwarded-For`, `X-Real-IP`, and `req.ip`. You can customize this:
57
+
58
+ ```typescript
59
+ app.use(
60
+ webdecoy({
61
+ apiKey: process.env.WEBDECOY_API_KEY,
62
+ getIP: (req) => req.headers['cf-connecting-ip'] as string, // Cloudflare
63
+ })
64
+ );
65
+ ```
66
+
67
+ ## Custom Block Handler
68
+
69
+ ```typescript
70
+ app.use(
71
+ webdecoy({
72
+ apiKey: process.env.WEBDECOY_API_KEY,
73
+ onBlocked: (req, res, detection) => {
74
+ res.status(403).render('blocked', {
75
+ detectionId: detection.detection_id,
76
+ threatLevel: detection.threat_level,
77
+ });
78
+ },
79
+ })
80
+ );
81
+ ```
82
+
83
+ ## Skip Specific Paths
84
+
85
+ ```typescript
86
+ app.use(
87
+ webdecoy({
88
+ apiKey: process.env.WEBDECOY_API_KEY,
89
+ skipPaths: [
90
+ '/health',
91
+ '/metrics',
92
+ /^\/static\/.*/, // Regex pattern
93
+ ],
94
+ })
95
+ );
96
+ ```
97
+
98
+ ## Access Detection Info
99
+
100
+ The middleware adds detection info to `req.webdecoy`:
101
+
102
+ ```typescript
103
+ app.get('/api/data', (req, res) => {
104
+ if (req.webdecoy?.bot_detected) {
105
+ // Extra logging for bot requests
106
+ logger.warn('Bot detected', {
107
+ ip: req.ip,
108
+ detectionId: req.webdecoy.detection_id,
109
+ botType: req.webdecoy.bot_type,
110
+ });
111
+ }
112
+
113
+ res.json({ data: 'response' });
114
+ });
115
+ ```
116
+
117
+ ## Documentation
118
+
119
+ See the [main README](../../README.md) for full documentation.
120
+
121
+ ## License
122
+
123
+ MIT
@@ -0,0 +1,72 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import { WebDecoyConfig, ProtectOptions } from '@webdecoy/node';
3
+ export { ProtectResult, RequestMetadata, SDKDetectionResponse, WebDecoyConfig } from '@webdecoy/node';
4
+
5
+ /**
6
+ * Web Decoy Express Middleware
7
+ */
8
+
9
+ interface WebDecoyMiddlewareOptions extends ProtectOptions {
10
+ /**
11
+ * Custom function to extract IP address from request
12
+ * By default, uses req.ip or x-forwarded-for header
13
+ */
14
+ getIP?: (req: Request) => string;
15
+ /**
16
+ * Custom function to handle blocked requests
17
+ * By default, returns 403 Forbidden
18
+ */
19
+ onBlocked?: (req: Request, res: Response, detection: any) => void;
20
+ /**
21
+ * Custom function to handle errors
22
+ * By default, logs error and allows request (fail open)
23
+ */
24
+ onError?: (req: Request, res: Response, error: Error) => void;
25
+ /**
26
+ * Paths to skip protection (e.g., health checks, static assets)
27
+ */
28
+ skipPaths?: string[] | RegExp[];
29
+ /**
30
+ * Enable TLS info extraction from the request
31
+ * Requires proxy or custom setup to expose TLS details
32
+ */
33
+ extractTLS?: boolean;
34
+ }
35
+ /**
36
+ * Create Express middleware for Web Decoy protection
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * import express from 'express';
41
+ * import { webdecoy } from '@webdecoy/express';
42
+ *
43
+ * const app = express();
44
+ *
45
+ * app.use(webdecoy({
46
+ * apiKey: process.env.WEBDECOY_API_KEY,
47
+ * skipPaths: ['/health', '/static'],
48
+ * }));
49
+ * ```
50
+ */
51
+ declare function webdecoy(config: WebDecoyConfig & WebDecoyMiddlewareOptions): (req: Request, res: Response, next: NextFunction) => Promise<void>;
52
+ /**
53
+ * Type augmentation for Express Request
54
+ * Adds webdecoy property to req object
55
+ */
56
+ declare global {
57
+ namespace Express {
58
+ interface Request {
59
+ webdecoy?: {
60
+ decision: string;
61
+ confidence: number;
62
+ threat_level: string;
63
+ bot_detected: boolean;
64
+ bot_type?: string;
65
+ detection_id: string;
66
+ rule_enforced: boolean;
67
+ };
68
+ }
69
+ }
70
+ }
71
+
72
+ export { type WebDecoyMiddlewareOptions, webdecoy };
@@ -0,0 +1,72 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import { WebDecoyConfig, ProtectOptions } from '@webdecoy/node';
3
+ export { ProtectResult, RequestMetadata, SDKDetectionResponse, WebDecoyConfig } from '@webdecoy/node';
4
+
5
+ /**
6
+ * Web Decoy Express Middleware
7
+ */
8
+
9
+ interface WebDecoyMiddlewareOptions extends ProtectOptions {
10
+ /**
11
+ * Custom function to extract IP address from request
12
+ * By default, uses req.ip or x-forwarded-for header
13
+ */
14
+ getIP?: (req: Request) => string;
15
+ /**
16
+ * Custom function to handle blocked requests
17
+ * By default, returns 403 Forbidden
18
+ */
19
+ onBlocked?: (req: Request, res: Response, detection: any) => void;
20
+ /**
21
+ * Custom function to handle errors
22
+ * By default, logs error and allows request (fail open)
23
+ */
24
+ onError?: (req: Request, res: Response, error: Error) => void;
25
+ /**
26
+ * Paths to skip protection (e.g., health checks, static assets)
27
+ */
28
+ skipPaths?: string[] | RegExp[];
29
+ /**
30
+ * Enable TLS info extraction from the request
31
+ * Requires proxy or custom setup to expose TLS details
32
+ */
33
+ extractTLS?: boolean;
34
+ }
35
+ /**
36
+ * Create Express middleware for Web Decoy protection
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * import express from 'express';
41
+ * import { webdecoy } from '@webdecoy/express';
42
+ *
43
+ * const app = express();
44
+ *
45
+ * app.use(webdecoy({
46
+ * apiKey: process.env.WEBDECOY_API_KEY,
47
+ * skipPaths: ['/health', '/static'],
48
+ * }));
49
+ * ```
50
+ */
51
+ declare function webdecoy(config: WebDecoyConfig & WebDecoyMiddlewareOptions): (req: Request, res: Response, next: NextFunction) => Promise<void>;
52
+ /**
53
+ * Type augmentation for Express Request
54
+ * Adds webdecoy property to req object
55
+ */
56
+ declare global {
57
+ namespace Express {
58
+ interface Request {
59
+ webdecoy?: {
60
+ decision: string;
61
+ confidence: number;
62
+ threat_level: string;
63
+ bot_detected: boolean;
64
+ bot_type?: string;
65
+ detection_id: string;
66
+ rule_enforced: boolean;
67
+ };
68
+ }
69
+ }
70
+ }
71
+
72
+ export { type WebDecoyMiddlewareOptions, webdecoy };
package/dist/index.js ADDED
@@ -0,0 +1,101 @@
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
+ webdecoy: () => webdecoy
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+
27
+ // src/middleware.ts
28
+ var import_node = require("@webdecoy/node");
29
+ function defaultGetIP(req) {
30
+ const forwardedFor = req.headers["x-forwarded-for"];
31
+ if (forwardedFor) {
32
+ const ips = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor;
33
+ return ips.split(",")[0].trim();
34
+ }
35
+ const realIP = req.headers["x-real-ip"];
36
+ if (realIP) {
37
+ return Array.isArray(realIP) ? realIP[0] : realIP;
38
+ }
39
+ return req.ip || req.socket.remoteAddress || "127.0.0.1";
40
+ }
41
+ function defaultOnBlocked(req, res, detection) {
42
+ res.status(403).json({
43
+ error: "Forbidden",
44
+ message: "Access denied by Web Decoy protection",
45
+ detection_id: detection.detection_id
46
+ });
47
+ }
48
+ function defaultOnError(req, res, error) {
49
+ console.error("[WebDecoy] Middleware error:", error);
50
+ }
51
+ function shouldSkipPath(path, skipPaths) {
52
+ if (!skipPaths || skipPaths.length === 0) {
53
+ return false;
54
+ }
55
+ return skipPaths.some((pattern) => {
56
+ if (typeof pattern === "string") {
57
+ return path === pattern || path.startsWith(pattern);
58
+ }
59
+ return pattern.test(path);
60
+ });
61
+ }
62
+ function webdecoy(config) {
63
+ const sdk = new import_node.WebDecoy(config);
64
+ const getIP = config.getIP || defaultGetIP;
65
+ const onBlocked = config.onBlocked || defaultOnBlocked;
66
+ const onError = config.onError || defaultOnError;
67
+ const skipPaths = config.skipPaths;
68
+ return async (req, res, next) => {
69
+ try {
70
+ if (shouldSkipPath(req.path, skipPaths)) {
71
+ return next();
72
+ }
73
+ const metadata = {
74
+ method: req.method,
75
+ path: req.path,
76
+ ip: getIP(req),
77
+ user_agent: req.headers["user-agent"],
78
+ headers: req.headers,
79
+ timestamp: Date.now()
80
+ };
81
+ const result = await sdk.protect(metadata, {
82
+ threshold: config.threshold,
83
+ skipLocalAnalysis: config.skipLocalAnalysis,
84
+ metadata: config.metadata
85
+ });
86
+ if (result.allowed) {
87
+ req.webdecoy = result.detection;
88
+ return next();
89
+ } else {
90
+ return onBlocked(req, res, result.detection);
91
+ }
92
+ } catch (error) {
93
+ onError(req, res, error);
94
+ return next();
95
+ }
96
+ };
97
+ }
98
+ // Annotate the CommonJS export names for ESM import in node:
99
+ 0 && (module.exports = {
100
+ webdecoy
101
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,74 @@
1
+ // src/middleware.ts
2
+ import { WebDecoy } from "@webdecoy/node";
3
+ function defaultGetIP(req) {
4
+ const forwardedFor = req.headers["x-forwarded-for"];
5
+ if (forwardedFor) {
6
+ const ips = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor;
7
+ return ips.split(",")[0].trim();
8
+ }
9
+ const realIP = req.headers["x-real-ip"];
10
+ if (realIP) {
11
+ return Array.isArray(realIP) ? realIP[0] : realIP;
12
+ }
13
+ return req.ip || req.socket.remoteAddress || "127.0.0.1";
14
+ }
15
+ function defaultOnBlocked(req, res, detection) {
16
+ res.status(403).json({
17
+ error: "Forbidden",
18
+ message: "Access denied by Web Decoy protection",
19
+ detection_id: detection.detection_id
20
+ });
21
+ }
22
+ function defaultOnError(req, res, error) {
23
+ console.error("[WebDecoy] Middleware error:", error);
24
+ }
25
+ function shouldSkipPath(path, skipPaths) {
26
+ if (!skipPaths || skipPaths.length === 0) {
27
+ return false;
28
+ }
29
+ return skipPaths.some((pattern) => {
30
+ if (typeof pattern === "string") {
31
+ return path === pattern || path.startsWith(pattern);
32
+ }
33
+ return pattern.test(path);
34
+ });
35
+ }
36
+ function webdecoy(config) {
37
+ const sdk = new WebDecoy(config);
38
+ const getIP = config.getIP || defaultGetIP;
39
+ const onBlocked = config.onBlocked || defaultOnBlocked;
40
+ const onError = config.onError || defaultOnError;
41
+ const skipPaths = config.skipPaths;
42
+ return async (req, res, next) => {
43
+ try {
44
+ if (shouldSkipPath(req.path, skipPaths)) {
45
+ return next();
46
+ }
47
+ const metadata = {
48
+ method: req.method,
49
+ path: req.path,
50
+ ip: getIP(req),
51
+ user_agent: req.headers["user-agent"],
52
+ headers: req.headers,
53
+ timestamp: Date.now()
54
+ };
55
+ const result = await sdk.protect(metadata, {
56
+ threshold: config.threshold,
57
+ skipLocalAnalysis: config.skipLocalAnalysis,
58
+ metadata: config.metadata
59
+ });
60
+ if (result.allowed) {
61
+ req.webdecoy = result.detection;
62
+ return next();
63
+ } else {
64
+ return onBlocked(req, res, result.detection);
65
+ }
66
+ } catch (error) {
67
+ onError(req, res, error);
68
+ return next();
69
+ }
70
+ };
71
+ }
72
+ export {
73
+ webdecoy
74
+ };
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@webdecoy/express",
3
+ "version": "0.1.0",
4
+ "description": "Web Decoy middleware for Express.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
+ "express",
27
+ "middleware",
28
+ "bot-detection",
29
+ "security"
30
+ ],
31
+ "author": "Web Decoy",
32
+ "license": "MIT",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/webdecoy/webdecoy-node.git",
36
+ "directory": "packages/express"
37
+ },
38
+ "dependencies": {
39
+ "@webdecoy/node": "*"
40
+ },
41
+ "peerDependencies": {
42
+ "express": "^4.18.0 || ^5.0.0"
43
+ },
44
+ "devDependencies": {
45
+ "@types/express": "^4.17.21",
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
+ "express": "^4.18.2",
52
+ "jest": "^29.7.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
+ }