@webdecoy/node 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,41 @@
1
+ # @webdecoy/node
2
+
3
+ Core Web Decoy SDK for Node.js applications.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @webdecoy/node
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import { WebDecoy } from '@webdecoy/node';
15
+
16
+ const webdecoy = new WebDecoy({
17
+ apiKey: process.env.WEBDECOY_API_KEY,
18
+ });
19
+
20
+ const result = await webdecoy.protect({
21
+ method: 'GET',
22
+ path: '/api/data',
23
+ ip: '203.0.113.42',
24
+ user_agent: 'Mozilla/5.0...',
25
+ headers: { /* request headers */ },
26
+ timestamp: Date.now(),
27
+ });
28
+
29
+ if (!result.allowed) {
30
+ // Block the request
31
+ throw new Error('Access denied');
32
+ }
33
+ ```
34
+
35
+ ## Documentation
36
+
37
+ See the [main README](../../README.md) for full documentation.
38
+
39
+ ## License
40
+
41
+ MIT
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Web Decoy SDK Types
3
+ * Based on the ingest service API contract
4
+ */
5
+ /**
6
+ * Configuration options for the Web Decoy SDK
7
+ */
8
+ interface WebDecoyConfig {
9
+ /**
10
+ * API key for authentication (sk_live_xxxxx format)
11
+ * Get this from your Web Decoy dashboard
12
+ */
13
+ apiKey: string;
14
+ /**
15
+ * API URL for the Web Decoy ingest service
16
+ * @default 'https://api.webdecoy.com'
17
+ */
18
+ apiUrl?: string;
19
+ /**
20
+ * Enable TLS fingerprinting for advanced bot detection
21
+ * @default true
22
+ */
23
+ enableTLSFingerprinting?: boolean;
24
+ /**
25
+ * Threat score threshold for blocking (0-100)
26
+ * Requests with scores above this will be blocked
27
+ * @default 80
28
+ */
29
+ threatScoreThreshold?: number;
30
+ /**
31
+ * Timeout for API requests in milliseconds
32
+ * @default 5000
33
+ */
34
+ timeout?: number;
35
+ /**
36
+ * Enable debug logging
37
+ * @default false
38
+ */
39
+ debug?: boolean;
40
+ /**
41
+ * Whether to reject unauthorized TLS certificates
42
+ * Set to false for development/testing with self-signed certificates
43
+ * @default true
44
+ */
45
+ tlsRejectUnauthorized?: boolean;
46
+ }
47
+ /**
48
+ * TLS connection information from the request
49
+ */
50
+ interface TLSInfo {
51
+ /** TLS version (e.g., 771 for TLS 1.2, 772 for TLS 1.3) */
52
+ version?: number;
53
+ /** List of cipher suites supported by the client */
54
+ cipher_suites?: number[];
55
+ /** List of TLS extensions */
56
+ extensions?: number[];
57
+ /** Elliptic curves supported */
58
+ supported_groups?: number[];
59
+ /** EC point formats */
60
+ ec_point_formats?: number[];
61
+ /** Signature algorithms */
62
+ signature_algorithms?: number[];
63
+ /** Server name indication */
64
+ server_name?: string;
65
+ /** ALPN protocols */
66
+ alpn_protocols?: string[];
67
+ }
68
+ /**
69
+ * Request metadata sent to the detection service
70
+ */
71
+ interface RequestMetadata {
72
+ /** HTTP method (GET, POST, etc.) */
73
+ method: string;
74
+ /** Request path */
75
+ path: string;
76
+ /** Client IP address (REQUIRED) */
77
+ ip: string;
78
+ /** User-Agent header */
79
+ user_agent?: string;
80
+ /** All request headers */
81
+ headers: Record<string, string>;
82
+ /** TLS connection information */
83
+ tls_info?: TLSInfo;
84
+ /** Request timestamp (Unix milliseconds) */
85
+ timestamp: number;
86
+ }
87
+ /**
88
+ * Local analysis performed by the SDK
89
+ */
90
+ interface LocalAnalysis {
91
+ /** True if suspicious headers detected */
92
+ suspicious_headers: boolean;
93
+ /** True if Sec-CH-UA header is missing */
94
+ missing_sec_ch_ua: boolean;
95
+ /** True if IP is from a known datacenter */
96
+ datacenter_ip: boolean;
97
+ /** Local threat score (0-100) */
98
+ local_score: number;
99
+ /** True if server-side verification is needed */
100
+ needs_verification: boolean;
101
+ /** Detection flags */
102
+ flags: string[];
103
+ }
104
+ /**
105
+ * Detection request sent to the ingest service
106
+ */
107
+ interface SDKDetectionRequest {
108
+ request_metadata: RequestMetadata;
109
+ local_analysis: LocalAnalysis;
110
+ }
111
+ /**
112
+ * Detection response from the ingest service
113
+ */
114
+ interface SDKDetectionResponse {
115
+ /** Decision: "allow", "block", or "challenge" */
116
+ decision: 'allow' | 'block' | 'challenge';
117
+ /** Confidence score (0-100) */
118
+ confidence: number;
119
+ /** Threat level classification */
120
+ threat_level: 'MINIMAL' | 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
121
+ /** True if a bot was detected */
122
+ bot_detected: boolean;
123
+ /** Type of bot detected (if any) */
124
+ bot_type?: string;
125
+ /** Unique detection ID */
126
+ detection_id: string;
127
+ /** True if a response rule was enforced */
128
+ rule_enforced: boolean;
129
+ }
130
+ /**
131
+ * Result of the protect() method
132
+ */
133
+ interface ProtectResult {
134
+ /** Whether to allow the request */
135
+ allowed: boolean;
136
+ /** Detection response from the service */
137
+ detection: SDKDetectionResponse;
138
+ /** Error message if the request failed */
139
+ error?: string;
140
+ }
141
+ /**
142
+ * Options for the protect() method
143
+ */
144
+ interface ProtectOptions {
145
+ /** Custom threat score threshold for this request */
146
+ threshold?: number;
147
+ /** Skip local analysis and only use server-side detection */
148
+ skipLocalAnalysis?: boolean;
149
+ /** Additional metadata to include in the detection */
150
+ metadata?: Record<string, any>;
151
+ }
152
+
153
+ /**
154
+ * Web Decoy SDK
155
+ * Main SDK class for bot detection and protection
156
+ */
157
+
158
+ declare class WebDecoy {
159
+ private client;
160
+ private config;
161
+ constructor(config: WebDecoyConfig);
162
+ /**
163
+ * Protect a request by checking it against Web Decoy's bot detection
164
+ *
165
+ * @param metadata - Request metadata to analyze
166
+ * @param options - Optional configuration for this specific request
167
+ * @returns Protection result with decision and detection details
168
+ */
169
+ protect(metadata: RequestMetadata, options?: ProtectOptions): Promise<ProtectResult>;
170
+ /**
171
+ * Validate the API key configuration
172
+ * Useful for testing integration during setup
173
+ */
174
+ validateConfig(): Promise<{
175
+ valid: boolean;
176
+ error?: string;
177
+ }>;
178
+ /**
179
+ * Get the current configuration
180
+ */
181
+ getConfig(): Readonly<Required<WebDecoyConfig>>;
182
+ }
183
+
184
+ export { type LocalAnalysis, type ProtectOptions, type ProtectResult, type RequestMetadata, type SDKDetectionRequest, type SDKDetectionResponse, type TLSInfo, WebDecoy, type WebDecoyConfig };
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Web Decoy SDK Types
3
+ * Based on the ingest service API contract
4
+ */
5
+ /**
6
+ * Configuration options for the Web Decoy SDK
7
+ */
8
+ interface WebDecoyConfig {
9
+ /**
10
+ * API key for authentication (sk_live_xxxxx format)
11
+ * Get this from your Web Decoy dashboard
12
+ */
13
+ apiKey: string;
14
+ /**
15
+ * API URL for the Web Decoy ingest service
16
+ * @default 'https://api.webdecoy.com'
17
+ */
18
+ apiUrl?: string;
19
+ /**
20
+ * Enable TLS fingerprinting for advanced bot detection
21
+ * @default true
22
+ */
23
+ enableTLSFingerprinting?: boolean;
24
+ /**
25
+ * Threat score threshold for blocking (0-100)
26
+ * Requests with scores above this will be blocked
27
+ * @default 80
28
+ */
29
+ threatScoreThreshold?: number;
30
+ /**
31
+ * Timeout for API requests in milliseconds
32
+ * @default 5000
33
+ */
34
+ timeout?: number;
35
+ /**
36
+ * Enable debug logging
37
+ * @default false
38
+ */
39
+ debug?: boolean;
40
+ /**
41
+ * Whether to reject unauthorized TLS certificates
42
+ * Set to false for development/testing with self-signed certificates
43
+ * @default true
44
+ */
45
+ tlsRejectUnauthorized?: boolean;
46
+ }
47
+ /**
48
+ * TLS connection information from the request
49
+ */
50
+ interface TLSInfo {
51
+ /** TLS version (e.g., 771 for TLS 1.2, 772 for TLS 1.3) */
52
+ version?: number;
53
+ /** List of cipher suites supported by the client */
54
+ cipher_suites?: number[];
55
+ /** List of TLS extensions */
56
+ extensions?: number[];
57
+ /** Elliptic curves supported */
58
+ supported_groups?: number[];
59
+ /** EC point formats */
60
+ ec_point_formats?: number[];
61
+ /** Signature algorithms */
62
+ signature_algorithms?: number[];
63
+ /** Server name indication */
64
+ server_name?: string;
65
+ /** ALPN protocols */
66
+ alpn_protocols?: string[];
67
+ }
68
+ /**
69
+ * Request metadata sent to the detection service
70
+ */
71
+ interface RequestMetadata {
72
+ /** HTTP method (GET, POST, etc.) */
73
+ method: string;
74
+ /** Request path */
75
+ path: string;
76
+ /** Client IP address (REQUIRED) */
77
+ ip: string;
78
+ /** User-Agent header */
79
+ user_agent?: string;
80
+ /** All request headers */
81
+ headers: Record<string, string>;
82
+ /** TLS connection information */
83
+ tls_info?: TLSInfo;
84
+ /** Request timestamp (Unix milliseconds) */
85
+ timestamp: number;
86
+ }
87
+ /**
88
+ * Local analysis performed by the SDK
89
+ */
90
+ interface LocalAnalysis {
91
+ /** True if suspicious headers detected */
92
+ suspicious_headers: boolean;
93
+ /** True if Sec-CH-UA header is missing */
94
+ missing_sec_ch_ua: boolean;
95
+ /** True if IP is from a known datacenter */
96
+ datacenter_ip: boolean;
97
+ /** Local threat score (0-100) */
98
+ local_score: number;
99
+ /** True if server-side verification is needed */
100
+ needs_verification: boolean;
101
+ /** Detection flags */
102
+ flags: string[];
103
+ }
104
+ /**
105
+ * Detection request sent to the ingest service
106
+ */
107
+ interface SDKDetectionRequest {
108
+ request_metadata: RequestMetadata;
109
+ local_analysis: LocalAnalysis;
110
+ }
111
+ /**
112
+ * Detection response from the ingest service
113
+ */
114
+ interface SDKDetectionResponse {
115
+ /** Decision: "allow", "block", or "challenge" */
116
+ decision: 'allow' | 'block' | 'challenge';
117
+ /** Confidence score (0-100) */
118
+ confidence: number;
119
+ /** Threat level classification */
120
+ threat_level: 'MINIMAL' | 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
121
+ /** True if a bot was detected */
122
+ bot_detected: boolean;
123
+ /** Type of bot detected (if any) */
124
+ bot_type?: string;
125
+ /** Unique detection ID */
126
+ detection_id: string;
127
+ /** True if a response rule was enforced */
128
+ rule_enforced: boolean;
129
+ }
130
+ /**
131
+ * Result of the protect() method
132
+ */
133
+ interface ProtectResult {
134
+ /** Whether to allow the request */
135
+ allowed: boolean;
136
+ /** Detection response from the service */
137
+ detection: SDKDetectionResponse;
138
+ /** Error message if the request failed */
139
+ error?: string;
140
+ }
141
+ /**
142
+ * Options for the protect() method
143
+ */
144
+ interface ProtectOptions {
145
+ /** Custom threat score threshold for this request */
146
+ threshold?: number;
147
+ /** Skip local analysis and only use server-side detection */
148
+ skipLocalAnalysis?: boolean;
149
+ /** Additional metadata to include in the detection */
150
+ metadata?: Record<string, any>;
151
+ }
152
+
153
+ /**
154
+ * Web Decoy SDK
155
+ * Main SDK class for bot detection and protection
156
+ */
157
+
158
+ declare class WebDecoy {
159
+ private client;
160
+ private config;
161
+ constructor(config: WebDecoyConfig);
162
+ /**
163
+ * Protect a request by checking it against Web Decoy's bot detection
164
+ *
165
+ * @param metadata - Request metadata to analyze
166
+ * @param options - Optional configuration for this specific request
167
+ * @returns Protection result with decision and detection details
168
+ */
169
+ protect(metadata: RequestMetadata, options?: ProtectOptions): Promise<ProtectResult>;
170
+ /**
171
+ * Validate the API key configuration
172
+ * Useful for testing integration during setup
173
+ */
174
+ validateConfig(): Promise<{
175
+ valid: boolean;
176
+ error?: string;
177
+ }>;
178
+ /**
179
+ * Get the current configuration
180
+ */
181
+ getConfig(): Readonly<Required<WebDecoyConfig>>;
182
+ }
183
+
184
+ export { type LocalAnalysis, type ProtectOptions, type ProtectResult, type RequestMetadata, type SDKDetectionRequest, type SDKDetectionResponse, type TLSInfo, WebDecoy, type WebDecoyConfig };
package/dist/index.js ADDED
@@ -0,0 +1,410 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ WebDecoy: () => WebDecoy
34
+ });
35
+ module.exports = __toCommonJS(index_exports);
36
+
37
+ // src/client.ts
38
+ var import_axios = __toESM(require("axios"));
39
+ var import_https = __toESM(require("https"));
40
+ var WebDecoyClient = class {
41
+ constructor(config) {
42
+ this.config = config;
43
+ const httpsAgent = new import_https.default.Agent({
44
+ rejectUnauthorized: config.tlsRejectUnauthorized
45
+ });
46
+ this.axios = import_axios.default.create({
47
+ baseURL: config.apiUrl,
48
+ timeout: config.timeout,
49
+ headers: {
50
+ "Content-Type": "application/json",
51
+ Authorization: `Bearer ${config.apiKey}`,
52
+ "User-Agent": "webdecoy-node-sdk/0.1.0"
53
+ },
54
+ httpsAgent
55
+ });
56
+ if (config.debug) {
57
+ this.axios.interceptors.request.use((request) => {
58
+ console.log("[WebDecoy] Request:", {
59
+ method: request.method,
60
+ url: request.url,
61
+ data: request.data
62
+ });
63
+ return request;
64
+ });
65
+ this.axios.interceptors.response.use(
66
+ (response) => {
67
+ console.log("[WebDecoy] Response:", {
68
+ status: response.status,
69
+ data: response.data
70
+ });
71
+ return response;
72
+ },
73
+ (error) => {
74
+ console.error("[WebDecoy] Error:", {
75
+ message: error.message,
76
+ response: error.response?.data
77
+ });
78
+ return Promise.reject(error);
79
+ }
80
+ );
81
+ }
82
+ }
83
+ /**
84
+ * Send a detection request to the ingest service
85
+ */
86
+ async detect(request) {
87
+ try {
88
+ const response = await this.axios.post(
89
+ "/api/v1/sdk/detect",
90
+ request
91
+ );
92
+ return response.data;
93
+ } catch (error) {
94
+ if (import_axios.default.isAxiosError(error)) {
95
+ const axiosError = error;
96
+ if (axiosError.response?.status === 401) {
97
+ throw new Error("Invalid API key. Please check your Web Decoy configuration.");
98
+ }
99
+ if (axiosError.response?.status === 429) {
100
+ throw new Error("Rate limit exceeded. Please try again later.");
101
+ }
102
+ if (axiosError.response?.data?.error || axiosError.response?.data?.message) {
103
+ throw new Error(
104
+ axiosError.response.data.error || axiosError.response.data.message || "API error"
105
+ );
106
+ }
107
+ if (axiosError.code === "ECONNABORTED") {
108
+ throw new Error("Request timeout. The Web Decoy service did not respond in time.");
109
+ }
110
+ if (axiosError.code === "ENOTFOUND" || axiosError.code === "ECONNREFUSED") {
111
+ throw new Error("Unable to connect to Web Decoy service. Please check your network.");
112
+ }
113
+ throw new Error(`API request failed: ${axiosError.message}`);
114
+ }
115
+ throw error;
116
+ }
117
+ }
118
+ /**
119
+ * Validate the API key by making a test request
120
+ */
121
+ async validateAPIKey() {
122
+ try {
123
+ const testRequest = {
124
+ request_metadata: {
125
+ method: "GET",
126
+ path: "/__webdecoy_test__",
127
+ ip: "127.0.0.1",
128
+ headers: {},
129
+ timestamp: Date.now()
130
+ },
131
+ local_analysis: {
132
+ suspicious_headers: false,
133
+ missing_sec_ch_ua: false,
134
+ datacenter_ip: false,
135
+ local_score: 0,
136
+ needs_verification: false,
137
+ flags: ["api_key_validation"]
138
+ }
139
+ };
140
+ await this.detect(testRequest);
141
+ return true;
142
+ } catch (error) {
143
+ if (error instanceof Error && error.message.includes("Invalid API key")) {
144
+ return false;
145
+ }
146
+ return true;
147
+ }
148
+ }
149
+ };
150
+
151
+ // src/local-analysis.ts
152
+ var DATACENTER_RANGES = [
153
+ // AWS
154
+ "3.0.0.0/8",
155
+ "13.0.0.0/8",
156
+ "18.0.0.0/8",
157
+ "52.0.0.0/8",
158
+ "54.0.0.0/8",
159
+ // Google Cloud
160
+ "34.0.0.0/8",
161
+ "35.0.0.0/8",
162
+ // Azure
163
+ "13.64.0.0/11",
164
+ "20.0.0.0/8",
165
+ "40.0.0.0/8",
166
+ "104.0.0.0/8",
167
+ // DigitalOcean
168
+ "159.65.0.0/16",
169
+ "178.62.0.0/16",
170
+ // Hetzner
171
+ "88.99.0.0/16",
172
+ "116.203.0.0/16"
173
+ ];
174
+ var SUSPICIOUS_PATTERNS = {
175
+ userAgents: [
176
+ /bot/i,
177
+ /crawler/i,
178
+ /spider/i,
179
+ /scraper/i,
180
+ /curl/i,
181
+ /wget/i,
182
+ /python/i,
183
+ /java/i,
184
+ /go-http-client/i,
185
+ /axios/i,
186
+ /okhttp/i
187
+ ],
188
+ missingHeaders: [
189
+ "accept",
190
+ "accept-language",
191
+ "accept-encoding"
192
+ ]
193
+ };
194
+ function isIPInRange(ip, cidr) {
195
+ const ipParts = ip.split(".").map(Number);
196
+ const [range, bits] = cidr.split("/");
197
+ const rangeParts = range.split(".").map(Number);
198
+ const mask = ~(2 ** (32 - parseInt(bits)) - 1);
199
+ const ipNum = (ipParts[0] << 24) + (ipParts[1] << 16) + (ipParts[2] << 8) + ipParts[3];
200
+ const rangeNum = (rangeParts[0] << 24) + (rangeParts[1] << 16) + (rangeParts[2] << 8) + rangeParts[3];
201
+ return (ipNum & mask) === (rangeNum & mask);
202
+ }
203
+ function isDatacenterIP(ip) {
204
+ if (ip.includes(":")) {
205
+ return false;
206
+ }
207
+ return DATACENTER_RANGES.some((range) => isIPInRange(ip, range));
208
+ }
209
+ function hasSuspiciousHeaders(metadata) {
210
+ const userAgent = metadata.user_agent || "";
211
+ const headers = metadata.headers || {};
212
+ const hasBotUA = SUSPICIOUS_PATTERNS.userAgents.some((pattern) => pattern.test(userAgent));
213
+ const missingCommonHeaders = SUSPICIOUS_PATTERNS.missingHeaders.filter(
214
+ (header) => !headers[header] && !headers[header.toLowerCase()]
215
+ );
216
+ return hasBotUA || missingCommonHeaders.length > 0;
217
+ }
218
+ function isMissingSecCHUA(metadata) {
219
+ const headers = metadata.headers || {};
220
+ return !headers["sec-ch-ua"] && !headers["Sec-CH-UA"];
221
+ }
222
+ function calculateLocalScore(suspiciousHeaders, missingSecCHUA, datacenterIP) {
223
+ let score = 0;
224
+ if (suspiciousHeaders) score += 30;
225
+ if (missingSecCHUA) score += 20;
226
+ if (datacenterIP) score += 40;
227
+ return Math.min(score, 100);
228
+ }
229
+ function needsVerification(localScore, hasTLSInfo) {
230
+ if (hasTLSInfo) {
231
+ return true;
232
+ }
233
+ return localScore >= 30;
234
+ }
235
+ function buildFlags(suspiciousHeaders, missingSecCHUA, datacenterIP, metadata) {
236
+ const flags = [];
237
+ if (suspiciousHeaders) {
238
+ flags.push("suspicious_headers");
239
+ }
240
+ if (missingSecCHUA) {
241
+ flags.push("missing_sec_ch_ua");
242
+ }
243
+ if (datacenterIP) {
244
+ flags.push("datacenter_ip");
245
+ }
246
+ const headerCount = Object.keys(metadata.headers || {}).length;
247
+ if (headerCount < 5) {
248
+ flags.push("minimal_headers");
249
+ }
250
+ if (!metadata.headers?.referer && !metadata.headers?.Referer) {
251
+ flags.push("missing_referer");
252
+ }
253
+ return flags;
254
+ }
255
+ function analyzeRequest(metadata) {
256
+ const suspiciousHeaders = hasSuspiciousHeaders(metadata);
257
+ const missingSecCHUA = isMissingSecCHUA(metadata);
258
+ const datacenterIP = isDatacenterIP(metadata.ip);
259
+ const localScore = calculateLocalScore(suspiciousHeaders, missingSecCHUA, datacenterIP);
260
+ const hasTLSInfo = Boolean(metadata.tls_info);
261
+ const needsVerify = needsVerification(localScore, hasTLSInfo);
262
+ const flags = buildFlags(suspiciousHeaders, missingSecCHUA, datacenterIP, metadata);
263
+ return {
264
+ suspicious_headers: suspiciousHeaders,
265
+ missing_sec_ch_ua: missingSecCHUA,
266
+ datacenter_ip: datacenterIP,
267
+ local_score: localScore,
268
+ needs_verification: needsVerify,
269
+ flags
270
+ };
271
+ }
272
+
273
+ // src/sdk.ts
274
+ var WebDecoy = class {
275
+ constructor(config) {
276
+ if (!config.apiKey) {
277
+ throw new Error("API key is required. Please provide a valid Web Decoy API key.");
278
+ }
279
+ if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
280
+ throw new Error(
281
+ 'Invalid API key format. API key should start with "sk_live_" or "sk_test_".'
282
+ );
283
+ }
284
+ this.config = {
285
+ apiKey: config.apiKey,
286
+ apiUrl: config.apiUrl || "https://api.webdecoy.com",
287
+ enableTLSFingerprinting: config.enableTLSFingerprinting ?? true,
288
+ threatScoreThreshold: config.threatScoreThreshold ?? 80,
289
+ timeout: config.timeout ?? 5e3,
290
+ debug: config.debug ?? false,
291
+ tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
292
+ };
293
+ this.client = new WebDecoyClient({
294
+ apiKey: this.config.apiKey,
295
+ apiUrl: this.config.apiUrl,
296
+ timeout: this.config.timeout,
297
+ debug: this.config.debug,
298
+ tlsRejectUnauthorized: this.config.tlsRejectUnauthorized
299
+ });
300
+ if (this.config.debug) {
301
+ console.log("[WebDecoy] Initialized with config:", {
302
+ apiUrl: this.config.apiUrl,
303
+ enableTLSFingerprinting: this.config.enableTLSFingerprinting,
304
+ threatScoreThreshold: this.config.threatScoreThreshold
305
+ });
306
+ }
307
+ }
308
+ /**
309
+ * Protect a request by checking it against Web Decoy's bot detection
310
+ *
311
+ * @param metadata - Request metadata to analyze
312
+ * @param options - Optional configuration for this specific request
313
+ * @returns Protection result with decision and detection details
314
+ */
315
+ async protect(metadata, options = {}) {
316
+ try {
317
+ if (!metadata.ip) {
318
+ throw new Error("IP address is required in request metadata");
319
+ }
320
+ if (!metadata.timestamp) {
321
+ metadata.timestamp = Date.now();
322
+ }
323
+ const localAnalysis = options.skipLocalAnalysis ? {
324
+ suspicious_headers: false,
325
+ missing_sec_ch_ua: false,
326
+ datacenter_ip: false,
327
+ local_score: 0,
328
+ needs_verification: true,
329
+ flags: ["local_analysis_skipped"]
330
+ } : analyzeRequest(metadata);
331
+ if (this.config.debug) {
332
+ console.log("[WebDecoy] Local analysis result:", localAnalysis);
333
+ }
334
+ const detectionRequest = {
335
+ request_metadata: metadata,
336
+ local_analysis: localAnalysis
337
+ };
338
+ const shouldCallServer = localAnalysis.needs_verification || this.config.enableTLSFingerprinting && metadata.tls_info;
339
+ if (!shouldCallServer && localAnalysis.local_score < 50) {
340
+ return {
341
+ allowed: true,
342
+ detection: {
343
+ decision: "allow",
344
+ confidence: 100 - localAnalysis.local_score,
345
+ threat_level: "MINIMAL",
346
+ bot_detected: false,
347
+ detection_id: "local_" + Date.now(),
348
+ rule_enforced: false
349
+ }
350
+ };
351
+ }
352
+ const detection = await this.client.detect(detectionRequest);
353
+ const threshold = options.threshold ?? this.config.threatScoreThreshold;
354
+ const allowed = detection.decision === "allow" || detection.confidence < threshold;
355
+ if (this.config.debug) {
356
+ console.log("[WebDecoy] Server detection result:", {
357
+ decision: detection.decision,
358
+ confidence: detection.confidence,
359
+ allowed
360
+ });
361
+ }
362
+ return {
363
+ allowed,
364
+ detection
365
+ };
366
+ } catch (error) {
367
+ if (this.config.debug) {
368
+ console.error("[WebDecoy] Protection error:", error);
369
+ }
370
+ return {
371
+ allowed: true,
372
+ // Fail open to avoid blocking legitimate users
373
+ detection: {
374
+ decision: "allow",
375
+ confidence: 0,
376
+ threat_level: "MINIMAL",
377
+ bot_detected: false,
378
+ detection_id: "error_" + Date.now(),
379
+ rule_enforced: false
380
+ },
381
+ error: error instanceof Error ? error.message : "Unknown error"
382
+ };
383
+ }
384
+ }
385
+ /**
386
+ * Validate the API key configuration
387
+ * Useful for testing integration during setup
388
+ */
389
+ async validateConfig() {
390
+ try {
391
+ const isValid = await this.client.validateAPIKey();
392
+ return { valid: isValid };
393
+ } catch (error) {
394
+ return {
395
+ valid: false,
396
+ error: error instanceof Error ? error.message : "Unknown error"
397
+ };
398
+ }
399
+ }
400
+ /**
401
+ * Get the current configuration
402
+ */
403
+ getConfig() {
404
+ return { ...this.config };
405
+ }
406
+ };
407
+ // Annotate the CommonJS export names for ESM import in node:
408
+ 0 && (module.exports = {
409
+ WebDecoy
410
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,373 @@
1
+ // src/client.ts
2
+ import axios from "axios";
3
+ import https from "https";
4
+ var WebDecoyClient = class {
5
+ constructor(config) {
6
+ this.config = config;
7
+ const httpsAgent = new https.Agent({
8
+ rejectUnauthorized: config.tlsRejectUnauthorized
9
+ });
10
+ this.axios = axios.create({
11
+ baseURL: config.apiUrl,
12
+ timeout: config.timeout,
13
+ headers: {
14
+ "Content-Type": "application/json",
15
+ Authorization: `Bearer ${config.apiKey}`,
16
+ "User-Agent": "webdecoy-node-sdk/0.1.0"
17
+ },
18
+ httpsAgent
19
+ });
20
+ if (config.debug) {
21
+ this.axios.interceptors.request.use((request) => {
22
+ console.log("[WebDecoy] Request:", {
23
+ method: request.method,
24
+ url: request.url,
25
+ data: request.data
26
+ });
27
+ return request;
28
+ });
29
+ this.axios.interceptors.response.use(
30
+ (response) => {
31
+ console.log("[WebDecoy] Response:", {
32
+ status: response.status,
33
+ data: response.data
34
+ });
35
+ return response;
36
+ },
37
+ (error) => {
38
+ console.error("[WebDecoy] Error:", {
39
+ message: error.message,
40
+ response: error.response?.data
41
+ });
42
+ return Promise.reject(error);
43
+ }
44
+ );
45
+ }
46
+ }
47
+ /**
48
+ * Send a detection request to the ingest service
49
+ */
50
+ async detect(request) {
51
+ try {
52
+ const response = await this.axios.post(
53
+ "/api/v1/sdk/detect",
54
+ request
55
+ );
56
+ return response.data;
57
+ } catch (error) {
58
+ if (axios.isAxiosError(error)) {
59
+ const axiosError = error;
60
+ if (axiosError.response?.status === 401) {
61
+ throw new Error("Invalid API key. Please check your Web Decoy configuration.");
62
+ }
63
+ if (axiosError.response?.status === 429) {
64
+ throw new Error("Rate limit exceeded. Please try again later.");
65
+ }
66
+ if (axiosError.response?.data?.error || axiosError.response?.data?.message) {
67
+ throw new Error(
68
+ axiosError.response.data.error || axiosError.response.data.message || "API error"
69
+ );
70
+ }
71
+ if (axiosError.code === "ECONNABORTED") {
72
+ throw new Error("Request timeout. The Web Decoy service did not respond in time.");
73
+ }
74
+ if (axiosError.code === "ENOTFOUND" || axiosError.code === "ECONNREFUSED") {
75
+ throw new Error("Unable to connect to Web Decoy service. Please check your network.");
76
+ }
77
+ throw new Error(`API request failed: ${axiosError.message}`);
78
+ }
79
+ throw error;
80
+ }
81
+ }
82
+ /**
83
+ * Validate the API key by making a test request
84
+ */
85
+ async validateAPIKey() {
86
+ try {
87
+ const testRequest = {
88
+ request_metadata: {
89
+ method: "GET",
90
+ path: "/__webdecoy_test__",
91
+ ip: "127.0.0.1",
92
+ headers: {},
93
+ timestamp: Date.now()
94
+ },
95
+ local_analysis: {
96
+ suspicious_headers: false,
97
+ missing_sec_ch_ua: false,
98
+ datacenter_ip: false,
99
+ local_score: 0,
100
+ needs_verification: false,
101
+ flags: ["api_key_validation"]
102
+ }
103
+ };
104
+ await this.detect(testRequest);
105
+ return true;
106
+ } catch (error) {
107
+ if (error instanceof Error && error.message.includes("Invalid API key")) {
108
+ return false;
109
+ }
110
+ return true;
111
+ }
112
+ }
113
+ };
114
+
115
+ // src/local-analysis.ts
116
+ var DATACENTER_RANGES = [
117
+ // AWS
118
+ "3.0.0.0/8",
119
+ "13.0.0.0/8",
120
+ "18.0.0.0/8",
121
+ "52.0.0.0/8",
122
+ "54.0.0.0/8",
123
+ // Google Cloud
124
+ "34.0.0.0/8",
125
+ "35.0.0.0/8",
126
+ // Azure
127
+ "13.64.0.0/11",
128
+ "20.0.0.0/8",
129
+ "40.0.0.0/8",
130
+ "104.0.0.0/8",
131
+ // DigitalOcean
132
+ "159.65.0.0/16",
133
+ "178.62.0.0/16",
134
+ // Hetzner
135
+ "88.99.0.0/16",
136
+ "116.203.0.0/16"
137
+ ];
138
+ var SUSPICIOUS_PATTERNS = {
139
+ userAgents: [
140
+ /bot/i,
141
+ /crawler/i,
142
+ /spider/i,
143
+ /scraper/i,
144
+ /curl/i,
145
+ /wget/i,
146
+ /python/i,
147
+ /java/i,
148
+ /go-http-client/i,
149
+ /axios/i,
150
+ /okhttp/i
151
+ ],
152
+ missingHeaders: [
153
+ "accept",
154
+ "accept-language",
155
+ "accept-encoding"
156
+ ]
157
+ };
158
+ function isIPInRange(ip, cidr) {
159
+ const ipParts = ip.split(".").map(Number);
160
+ const [range, bits] = cidr.split("/");
161
+ const rangeParts = range.split(".").map(Number);
162
+ const mask = ~(2 ** (32 - parseInt(bits)) - 1);
163
+ const ipNum = (ipParts[0] << 24) + (ipParts[1] << 16) + (ipParts[2] << 8) + ipParts[3];
164
+ const rangeNum = (rangeParts[0] << 24) + (rangeParts[1] << 16) + (rangeParts[2] << 8) + rangeParts[3];
165
+ return (ipNum & mask) === (rangeNum & mask);
166
+ }
167
+ function isDatacenterIP(ip) {
168
+ if (ip.includes(":")) {
169
+ return false;
170
+ }
171
+ return DATACENTER_RANGES.some((range) => isIPInRange(ip, range));
172
+ }
173
+ function hasSuspiciousHeaders(metadata) {
174
+ const userAgent = metadata.user_agent || "";
175
+ const headers = metadata.headers || {};
176
+ const hasBotUA = SUSPICIOUS_PATTERNS.userAgents.some((pattern) => pattern.test(userAgent));
177
+ const missingCommonHeaders = SUSPICIOUS_PATTERNS.missingHeaders.filter(
178
+ (header) => !headers[header] && !headers[header.toLowerCase()]
179
+ );
180
+ return hasBotUA || missingCommonHeaders.length > 0;
181
+ }
182
+ function isMissingSecCHUA(metadata) {
183
+ const headers = metadata.headers || {};
184
+ return !headers["sec-ch-ua"] && !headers["Sec-CH-UA"];
185
+ }
186
+ function calculateLocalScore(suspiciousHeaders, missingSecCHUA, datacenterIP) {
187
+ let score = 0;
188
+ if (suspiciousHeaders) score += 30;
189
+ if (missingSecCHUA) score += 20;
190
+ if (datacenterIP) score += 40;
191
+ return Math.min(score, 100);
192
+ }
193
+ function needsVerification(localScore, hasTLSInfo) {
194
+ if (hasTLSInfo) {
195
+ return true;
196
+ }
197
+ return localScore >= 30;
198
+ }
199
+ function buildFlags(suspiciousHeaders, missingSecCHUA, datacenterIP, metadata) {
200
+ const flags = [];
201
+ if (suspiciousHeaders) {
202
+ flags.push("suspicious_headers");
203
+ }
204
+ if (missingSecCHUA) {
205
+ flags.push("missing_sec_ch_ua");
206
+ }
207
+ if (datacenterIP) {
208
+ flags.push("datacenter_ip");
209
+ }
210
+ const headerCount = Object.keys(metadata.headers || {}).length;
211
+ if (headerCount < 5) {
212
+ flags.push("minimal_headers");
213
+ }
214
+ if (!metadata.headers?.referer && !metadata.headers?.Referer) {
215
+ flags.push("missing_referer");
216
+ }
217
+ return flags;
218
+ }
219
+ function analyzeRequest(metadata) {
220
+ const suspiciousHeaders = hasSuspiciousHeaders(metadata);
221
+ const missingSecCHUA = isMissingSecCHUA(metadata);
222
+ const datacenterIP = isDatacenterIP(metadata.ip);
223
+ const localScore = calculateLocalScore(suspiciousHeaders, missingSecCHUA, datacenterIP);
224
+ const hasTLSInfo = Boolean(metadata.tls_info);
225
+ const needsVerify = needsVerification(localScore, hasTLSInfo);
226
+ const flags = buildFlags(suspiciousHeaders, missingSecCHUA, datacenterIP, metadata);
227
+ return {
228
+ suspicious_headers: suspiciousHeaders,
229
+ missing_sec_ch_ua: missingSecCHUA,
230
+ datacenter_ip: datacenterIP,
231
+ local_score: localScore,
232
+ needs_verification: needsVerify,
233
+ flags
234
+ };
235
+ }
236
+
237
+ // src/sdk.ts
238
+ var WebDecoy = class {
239
+ constructor(config) {
240
+ if (!config.apiKey) {
241
+ throw new Error("API key is required. Please provide a valid Web Decoy API key.");
242
+ }
243
+ if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
244
+ throw new Error(
245
+ 'Invalid API key format. API key should start with "sk_live_" or "sk_test_".'
246
+ );
247
+ }
248
+ this.config = {
249
+ apiKey: config.apiKey,
250
+ apiUrl: config.apiUrl || "https://api.webdecoy.com",
251
+ enableTLSFingerprinting: config.enableTLSFingerprinting ?? true,
252
+ threatScoreThreshold: config.threatScoreThreshold ?? 80,
253
+ timeout: config.timeout ?? 5e3,
254
+ debug: config.debug ?? false,
255
+ tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
256
+ };
257
+ this.client = new WebDecoyClient({
258
+ apiKey: this.config.apiKey,
259
+ apiUrl: this.config.apiUrl,
260
+ timeout: this.config.timeout,
261
+ debug: this.config.debug,
262
+ tlsRejectUnauthorized: this.config.tlsRejectUnauthorized
263
+ });
264
+ if (this.config.debug) {
265
+ console.log("[WebDecoy] Initialized with config:", {
266
+ apiUrl: this.config.apiUrl,
267
+ enableTLSFingerprinting: this.config.enableTLSFingerprinting,
268
+ threatScoreThreshold: this.config.threatScoreThreshold
269
+ });
270
+ }
271
+ }
272
+ /**
273
+ * Protect a request by checking it against Web Decoy's bot detection
274
+ *
275
+ * @param metadata - Request metadata to analyze
276
+ * @param options - Optional configuration for this specific request
277
+ * @returns Protection result with decision and detection details
278
+ */
279
+ async protect(metadata, options = {}) {
280
+ try {
281
+ if (!metadata.ip) {
282
+ throw new Error("IP address is required in request metadata");
283
+ }
284
+ if (!metadata.timestamp) {
285
+ metadata.timestamp = Date.now();
286
+ }
287
+ const localAnalysis = options.skipLocalAnalysis ? {
288
+ suspicious_headers: false,
289
+ missing_sec_ch_ua: false,
290
+ datacenter_ip: false,
291
+ local_score: 0,
292
+ needs_verification: true,
293
+ flags: ["local_analysis_skipped"]
294
+ } : analyzeRequest(metadata);
295
+ if (this.config.debug) {
296
+ console.log("[WebDecoy] Local analysis result:", localAnalysis);
297
+ }
298
+ const detectionRequest = {
299
+ request_metadata: metadata,
300
+ local_analysis: localAnalysis
301
+ };
302
+ const shouldCallServer = localAnalysis.needs_verification || this.config.enableTLSFingerprinting && metadata.tls_info;
303
+ if (!shouldCallServer && localAnalysis.local_score < 50) {
304
+ return {
305
+ allowed: true,
306
+ detection: {
307
+ decision: "allow",
308
+ confidence: 100 - localAnalysis.local_score,
309
+ threat_level: "MINIMAL",
310
+ bot_detected: false,
311
+ detection_id: "local_" + Date.now(),
312
+ rule_enforced: false
313
+ }
314
+ };
315
+ }
316
+ const detection = await this.client.detect(detectionRequest);
317
+ const threshold = options.threshold ?? this.config.threatScoreThreshold;
318
+ const allowed = detection.decision === "allow" || detection.confidence < threshold;
319
+ if (this.config.debug) {
320
+ console.log("[WebDecoy] Server detection result:", {
321
+ decision: detection.decision,
322
+ confidence: detection.confidence,
323
+ allowed
324
+ });
325
+ }
326
+ return {
327
+ allowed,
328
+ detection
329
+ };
330
+ } catch (error) {
331
+ if (this.config.debug) {
332
+ console.error("[WebDecoy] Protection error:", error);
333
+ }
334
+ return {
335
+ allowed: true,
336
+ // Fail open to avoid blocking legitimate users
337
+ detection: {
338
+ decision: "allow",
339
+ confidence: 0,
340
+ threat_level: "MINIMAL",
341
+ bot_detected: false,
342
+ detection_id: "error_" + Date.now(),
343
+ rule_enforced: false
344
+ },
345
+ error: error instanceof Error ? error.message : "Unknown error"
346
+ };
347
+ }
348
+ }
349
+ /**
350
+ * Validate the API key configuration
351
+ * Useful for testing integration during setup
352
+ */
353
+ async validateConfig() {
354
+ try {
355
+ const isValid = await this.client.validateAPIKey();
356
+ return { valid: isValid };
357
+ } catch (error) {
358
+ return {
359
+ valid: false,
360
+ error: error instanceof Error ? error.message : "Unknown error"
361
+ };
362
+ }
363
+ }
364
+ /**
365
+ * Get the current configuration
366
+ */
367
+ getConfig() {
368
+ return { ...this.config };
369
+ }
370
+ };
371
+ export {
372
+ WebDecoy
373
+ };
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@webdecoy/node",
3
+ "version": "0.1.0",
4
+ "description": "Web Decoy SDK for Node.js - Bot detection with TLS fingerprinting",
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
+ "bot-detection",
27
+ "tls-fingerprinting",
28
+ "ja3",
29
+ "ja4",
30
+ "security",
31
+ "middleware"
32
+ ],
33
+ "author": "Web Decoy",
34
+ "license": "MIT",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "https://github.com/webdecoy/webdecoy-node.git",
38
+ "directory": "packages/webdecoy"
39
+ },
40
+ "dependencies": {
41
+ "axios": "^1.6.5"
42
+ },
43
+ "devDependencies": {
44
+ "@types/jest": "^29.5.11",
45
+ "@types/node": "^20.11.0",
46
+ "@typescript-eslint/eslint-plugin": "^6.18.1",
47
+ "@typescript-eslint/parser": "^6.18.1",
48
+ "eslint": "^8.56.0",
49
+ "jest": "^29.7.0",
50
+ "ts-jest": "^29.1.1",
51
+ "tsup": "^8.0.1",
52
+ "typescript": "^5.3.3"
53
+ },
54
+ "engines": {
55
+ "node": ">=18.0.0"
56
+ }
57
+ }