@webdecoy/node 0.13.0 → 0.14.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.mjs CHANGED
@@ -54,7 +54,7 @@ import {
54
54
  tripwire,
55
55
  upstashRateLimitStore,
56
56
  webBotAuth
57
- } from "./chunk-CIRFOOMU.mjs";
57
+ } from "./chunk-4QKKW7GN.mjs";
58
58
 
59
59
  // src/client-ip.ts
60
60
  var IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
@@ -184,11 +184,12 @@ function resolveClientIp(options) {
184
184
  return normalizeIp(readHeader(headers, "cf-connecting-ip")) ?? peer;
185
185
  }
186
186
  const chain = forwardedChain(headers);
187
+ const singleHeaderFallback = () => normalizeIp(readHeader(headers, "x-real-ip")) ?? normalizeIp(readHeader(headers, "x-vercel-forwarded-for")?.split(",").pop()) ?? void 0;
187
188
  if (typeof trustProxy === "number") {
188
189
  if (!Number.isInteger(trustProxy) || trustProxy < 0) return peer;
189
190
  const index = chain.length - trustProxy;
190
- if (index < 0 || index >= chain.length) return peer;
191
- return chain[index] ?? peer;
191
+ if (index < 0 || index >= chain.length) return singleHeaderFallback() ?? peer;
192
+ return chain[index] ?? singleHeaderFallback() ?? peer;
192
193
  }
193
194
  const full = peer ? [...chain, peer] : [...chain];
194
195
  for (let i = full.length - 1; i >= 0; i--) {
@@ -196,7 +197,7 @@ function resolveClientIp(options) {
196
197
  if (candidate === null) return peer;
197
198
  if (!trustProxy.some((range) => ipInCidr(candidate, range))) return candidate;
198
199
  }
199
- return full[0] ?? void 0 ?? peer;
200
+ return full[0] ?? void 0 ?? singleHeaderFallback() ?? peer;
200
201
  }
201
202
 
202
203
  // src/client-signals.ts
@@ -308,41 +309,72 @@ function clientSignals(config) {
308
309
  return new ClientSignalRule(config);
309
310
  }
310
311
 
311
- // src/fetch-guard.ts
312
- function defaultBlocked(_request, decision) {
313
- const throttled = decision.ruleResult?.action === "THROTTLE";
314
- const retryAfter = Number(decision.ruleResult?.metadata?.retryAfter ?? 60);
315
- if (throttled) {
316
- return new Response(
317
- JSON.stringify({
312
+ // src/adapter-core.ts
313
+ function shouldSkipPath(path, patterns) {
314
+ if (!patterns || patterns.length === 0) return false;
315
+ return patterns.some(
316
+ (pattern) => typeof pattern === "string" ? path === pattern || path.startsWith(pattern) : pattern.test(path)
317
+ );
318
+ }
319
+ function ruleBlockResponse(decision) {
320
+ const rr = decision.ruleResult;
321
+ if (decision.allowed || !rr) return null;
322
+ if (rr.action === "THROTTLE") {
323
+ const retryAfter = Number(rr.metadata?.retryAfter ?? 60);
324
+ return {
325
+ status: 429,
326
+ headers: { "Retry-After": String(retryAfter) },
327
+ body: {
318
328
  error: "Too Many Requests",
319
- message: decision.reason ?? "Rate limit exceeded",
320
- retry_after: retryAfter,
321
- detection_id: decision.id
322
- }),
323
- {
324
- status: 429,
325
- headers: {
326
- "content-type": "application/json",
327
- "retry-after": String(retryAfter)
328
- }
329
+ message: rr.reason || "Rate limit exceeded",
330
+ retry_after: retryAfter
329
331
  }
330
- );
332
+ };
331
333
  }
332
- return new Response(
333
- JSON.stringify({
334
- error: "Forbidden",
335
- message: "Access denied by Web Decoy protection",
336
- detection_id: decision.id
337
- }),
338
- { status: 403, headers: { "content-type": "application/json" } }
339
- );
334
+ if (rr.action === "DENY") {
335
+ return {
336
+ status: 403,
337
+ headers: {},
338
+ body: {
339
+ error: "Forbidden",
340
+ message: rr.reason || "Access denied by rule",
341
+ rule: rr.rule
342
+ }
343
+ };
344
+ }
345
+ return null;
340
346
  }
341
- function matches(pathname, patterns) {
342
- if (!patterns || patterns.length === 0) return false;
343
- return patterns.some(
344
- (p) => typeof p === "string" ? pathname === p || pathname.startsWith(p) : p.test(pathname)
345
- );
347
+ function armSiteHoneytoken(sdk, options) {
348
+ let token = null;
349
+ void deriveAndArm(sdk, options).then((t) => {
350
+ token = t;
351
+ });
352
+ return () => token;
353
+ }
354
+ async function deriveAndArm(sdk, options) {
355
+ const enabled = (options.enabled ?? true) && Boolean(options.apiKey);
356
+ if (!enabled) return null;
357
+ try {
358
+ const token = await siteHoneytoken({ secret: options.apiKey });
359
+ sdk.addRule(tripwire({ paths: token.activePaths, includeDefaults: false }));
360
+ return token;
361
+ } catch (error) {
362
+ options.onError?.(error);
363
+ return null;
364
+ }
365
+ }
366
+
367
+ // src/fetch-guard.ts
368
+ function defaultBlocked(_request, decision) {
369
+ const block = ruleBlockResponse(decision) ?? {
370
+ status: 403,
371
+ headers: {},
372
+ body: { error: "Forbidden", message: "Access denied by Web Decoy protection" }
373
+ };
374
+ return new Response(JSON.stringify({ ...block.body, detection_id: decision.id }), {
375
+ status: block.status,
376
+ headers: { "content-type": "application/json", ...block.headers }
377
+ });
346
378
  }
347
379
  function headerRecord(headers) {
348
380
  const out = {};
@@ -355,14 +387,10 @@ function createFetchGuard(options = {}) {
355
387
  const sdk = new WebDecoy(options);
356
388
  const mode = options.mode ?? "monitor";
357
389
  const onBlocked = options.onBlocked ?? defaultBlocked;
358
- let token = null;
359
- if ((options.honeytoken ?? true) && options.apiKey) {
360
- void siteHoneytoken({ secret: options.apiKey }).then((t) => {
361
- token = t;
362
- sdk.addRule(tripwire({ paths: t.activePaths, includeDefaults: false }));
363
- }).catch(() => {
364
- });
365
- }
390
+ const getToken = armSiteHoneytoken(sdk, {
391
+ apiKey: options.apiKey,
392
+ enabled: options.honeytoken
393
+ });
366
394
  function resolveIP(request, peer) {
367
395
  if (options.getIP) return options.getIP(request);
368
396
  return resolveClientIp({
@@ -374,7 +402,7 @@ function createFetchGuard(options = {}) {
374
402
  return {
375
403
  sdk,
376
404
  skips(pathname) {
377
- return matches(pathname, options.skipPaths);
405
+ return shouldSkipPath(pathname, options.skipPaths);
378
406
  },
379
407
  async check(request, peer) {
380
408
  const url = new URL(request.url);
@@ -396,7 +424,7 @@ function createFetchGuard(options = {}) {
396
424
  return { decision, response: await onBlocked(request, decision) };
397
425
  },
398
426
  async decorate(response) {
399
- const current = token;
427
+ const current = getToken();
400
428
  if (!current) return response;
401
429
  if (!isInjectableHtml(response.headers.get("content-type"))) return response;
402
430
  if (response.bodyUsed) return response;
@@ -2428,6 +2456,7 @@ export {
2428
2456
  UpstashRateLimitStore,
2429
2457
  WebBotAuthRule,
2430
2458
  WebDecoy,
2459
+ armSiteHoneytoken,
2431
2460
  attackSignatures,
2432
2461
  botPolicy,
2433
2462
  bots,
@@ -2439,6 +2468,7 @@ export {
2439
2468
  createAgentVerifier,
2440
2469
  createCaptchaEndpoints,
2441
2470
  createFetchGuard,
2471
+ deriveAndArm,
2442
2472
  deriveKey,
2443
2473
  filter,
2444
2474
  fromPino,
@@ -2459,6 +2489,8 @@ export {
2459
2489
  recommend,
2460
2490
  resolveClientIp,
2461
2491
  resolveSecret,
2492
+ ruleBlockResponse,
2493
+ shouldSkipPath,
2462
2494
  silentLogger,
2463
2495
  siteHoneytoken,
2464
2496
  tripwire,
@@ -310,7 +310,7 @@ declare function readEdgeVerdict(headers: Record<string, string> | undefined): E
310
310
  * agents share User-Agent substrings, so sorting this array changes how real
311
311
  * traffic is classified.
312
312
  *
313
- * 169 agents across 15 categories.
313
+ * 175 agents across 15 categories.
314
314
  */
315
315
  /**
316
316
  * Classification categories, mirroring `agents.Category` in Go.
@@ -551,6 +551,45 @@ declare function fromPino(pino: {
551
551
  error(fields: LogFields, message: string): void;
552
552
  }): Logger;
553
553
 
554
+ /**
555
+ * OpenTelemetry spans, without depending on OpenTelemetry.
556
+ *
557
+ * WHY INJECTED RATHER THAN IMPORTED
558
+ *
559
+ * An optional peer dependency was the obvious route and the wrong one. This
560
+ * package is dependency-free and passes an edge-compatibility gate, and most of
561
+ * the runtimes it targets — Workers, Vercel Edge — are exactly where a stray
562
+ * transitive import hurts. A conditional `import('@opentelemetry/api')` also
563
+ * bundles badly: the bundler either resolves it, adding weight for the majority
564
+ * who do not use it, or fails on a module that is legitimately absent.
565
+ *
566
+ * So the tracer is passed in. The interface below is a structural subset of
567
+ * OpenTelemetry's, which means `trace.getTracer('webdecoy')` satisfies it
568
+ * directly with no adapter:
569
+ *
570
+ * ```ts
571
+ * import { trace } from '@opentelemetry/api';
572
+ * new WebDecoy({ tracer: trace.getTracer('webdecoy') });
573
+ * ```
574
+ *
575
+ * An app that passes nothing gets no spans, no dependency, and no behaviour
576
+ * change — which is the majority, and they should not pay for this.
577
+ */
578
+ /** A span, structurally compatible with OpenTelemetry's. */
579
+ interface Span {
580
+ setAttribute(key: string, value: string | number | boolean): unknown;
581
+ recordException?(error: unknown): unknown;
582
+ setStatus?(status: {
583
+ code: number;
584
+ message?: string;
585
+ }): unknown;
586
+ end(): unknown;
587
+ }
588
+ /** A tracer, structurally compatible with OpenTelemetry's. */
589
+ interface Tracer {
590
+ startSpan(name: string): Span;
591
+ }
592
+
554
593
  /**
555
594
  * Web Decoy SDK Types
556
595
  * Based on the ingest service API contract
@@ -567,8 +606,10 @@ interface WebDecoyConfig {
567
606
  */
568
607
  apiKey?: string;
569
608
  /**
570
- * API URL for the Web Decoy ingest service
571
- * @default 'https://ingest.webdecoy.com'
609
+ * API URL for the Web Decoy ingest service. Server-to-server traffic
610
+ * fronts through Cloudflare at in.webdecoy.com; only the browser tag
611
+ * stays on the direct hostname.
612
+ * @default 'https://in.webdecoy.com'
572
613
  */
573
614
  apiUrl?: string;
574
615
  /**
@@ -643,6 +684,20 @@ interface WebDecoyConfig {
643
684
  * silently drops every structured field.
644
685
  */
645
686
  logger?: Logger;
687
+ /**
688
+ * An OpenTelemetry tracer, if you run one.
689
+ *
690
+ * Injected rather than imported so this package stays dependency-free and
691
+ * edge-safe. The interface is a structural subset of OpenTelemetry's, so
692
+ * `trace.getTracer('webdecoy')` works directly:
693
+ *
694
+ * ```ts
695
+ * new WebDecoy({ tracer: trace.getTracer('webdecoy') });
696
+ * ```
697
+ *
698
+ * Omit it and there are no spans, no dependency and no behaviour change.
699
+ */
700
+ tracer?: Tracer;
646
701
  }
647
702
  /**
648
703
  * TLS connection information from the request
@@ -1226,6 +1281,8 @@ declare class WebDecoy {
1226
1281
  private readonly characteristics;
1227
1282
  /** Where diagnostics go. Never console directly — see logger.ts. */
1228
1283
  readonly log: Logger;
1284
+ /** Optional OpenTelemetry tracer. Absent means no spans and no cost. */
1285
+ private readonly tracer?;
1229
1286
  private readonly decisionCache;
1230
1287
  constructor(config: WebDecoyConfig);
1231
1288
  /**
@@ -1344,4 +1401,4 @@ declare class WebDecoy {
1344
1401
  destroy(): Promise<void>;
1345
1402
  }
1346
1403
 
1347
- export { fromPino as $, type AgentCategory as A, type BotRuleConfig as B, type Characteristic as C, Decision as D, EDGE_CLASS_HEADER as E, type FilterConfig as F, type Logger as G, type ProtectResult as H, type IPEnrichmentData as I, type RequestMetadata as J, type RuleOutcome as K, type LocalAnalysis as L, MemoryRateLimitStore as M, type RuleState as N, type SDKDetectionRequest as O, type ProtectOptions as P, type SDKDetectionResponse as Q, type Rule as R, type SignedAgentDirectory as S, type TripwireConfig as T, type SyncRateLimitStore as U, type TLSInfo as V, WebDecoy as W, type ViolationEvent as X, classifyUserAgent as Y, consoleLogger as Z, deriveKey as _, type RuleContext as a, matchUserAgent as a0, newDecisionId as a1, readEdgeVerdict as a2, silentLogger as a3, type RuleResult as b, type WebDecoyConfig as c, type RuleEngineResult as d, type RateLimitConfig as e, type BotAgent as f, type BotCategory as g, type RateLimitStore as h, type RateLimitConsume as i, type RateLimitOutcome as j, type AgentVerifierOptions as k, type AgentRequestInput as l, type AgentVerdict as m, type AgentStatus as n, BOT_CATEGORIES as o, BOT_REGISTRY as p, type BotVerdict as q, type Conclusion as r, DEFAULT_CHARACTERISTICS as s, DecisionCache as t, type DecisionCacheOptions as u, type DecisionInit as v, EDGE_CLEARANCE_HEADER as w, type EdgeClass as x, type EdgeVerdict as y, type LogFields as z };
1404
+ export { consoleLogger as $, type AgentCategory as A, type BotRuleConfig as B, type Characteristic as C, Decision as D, EDGE_CLASS_HEADER as E, type FilterConfig as F, type LogFields as G, type Logger as H, type IPEnrichmentData as I, type RequestMetadata as J, type RuleOutcome as K, type LocalAnalysis as L, MemoryRateLimitStore as M, type RuleState as N, type SDKDetectionRequest as O, type ProtectResult as P, type SDKDetectionResponse as Q, type Rule as R, type SignedAgentDirectory as S, type TripwireConfig as T, type Span as U, type SyncRateLimitStore as V, WebDecoy as W, type TLSInfo as X, type Tracer as Y, type ViolationEvent as Z, classifyUserAgent as _, type RuleContext as a, deriveKey as a0, fromPino as a1, matchUserAgent as a2, newDecisionId as a3, readEdgeVerdict as a4, silentLogger as a5, type RuleResult as b, type RuleEngineResult as c, type RateLimitConfig as d, type BotAgent as e, type BotCategory as f, type RateLimitStore as g, type RateLimitConsume as h, type RateLimitOutcome as i, type WebDecoyConfig as j, type ProtectOptions as k, type AgentVerifierOptions as l, type AgentRequestInput as m, type AgentVerdict as n, type AgentStatus as o, BOT_CATEGORIES as p, BOT_REGISTRY as q, type BotVerdict as r, type Conclusion as s, DEFAULT_CHARACTERISTICS as t, DecisionCache as u, type DecisionCacheOptions as v, type DecisionInit as w, EDGE_CLEARANCE_HEADER as x, type EdgeClass as y, type EdgeVerdict as z };
@@ -310,7 +310,7 @@ declare function readEdgeVerdict(headers: Record<string, string> | undefined): E
310
310
  * agents share User-Agent substrings, so sorting this array changes how real
311
311
  * traffic is classified.
312
312
  *
313
- * 169 agents across 15 categories.
313
+ * 175 agents across 15 categories.
314
314
  */
315
315
  /**
316
316
  * Classification categories, mirroring `agents.Category` in Go.
@@ -551,6 +551,45 @@ declare function fromPino(pino: {
551
551
  error(fields: LogFields, message: string): void;
552
552
  }): Logger;
553
553
 
554
+ /**
555
+ * OpenTelemetry spans, without depending on OpenTelemetry.
556
+ *
557
+ * WHY INJECTED RATHER THAN IMPORTED
558
+ *
559
+ * An optional peer dependency was the obvious route and the wrong one. This
560
+ * package is dependency-free and passes an edge-compatibility gate, and most of
561
+ * the runtimes it targets — Workers, Vercel Edge — are exactly where a stray
562
+ * transitive import hurts. A conditional `import('@opentelemetry/api')` also
563
+ * bundles badly: the bundler either resolves it, adding weight for the majority
564
+ * who do not use it, or fails on a module that is legitimately absent.
565
+ *
566
+ * So the tracer is passed in. The interface below is a structural subset of
567
+ * OpenTelemetry's, which means `trace.getTracer('webdecoy')` satisfies it
568
+ * directly with no adapter:
569
+ *
570
+ * ```ts
571
+ * import { trace } from '@opentelemetry/api';
572
+ * new WebDecoy({ tracer: trace.getTracer('webdecoy') });
573
+ * ```
574
+ *
575
+ * An app that passes nothing gets no spans, no dependency, and no behaviour
576
+ * change — which is the majority, and they should not pay for this.
577
+ */
578
+ /** A span, structurally compatible with OpenTelemetry's. */
579
+ interface Span {
580
+ setAttribute(key: string, value: string | number | boolean): unknown;
581
+ recordException?(error: unknown): unknown;
582
+ setStatus?(status: {
583
+ code: number;
584
+ message?: string;
585
+ }): unknown;
586
+ end(): unknown;
587
+ }
588
+ /** A tracer, structurally compatible with OpenTelemetry's. */
589
+ interface Tracer {
590
+ startSpan(name: string): Span;
591
+ }
592
+
554
593
  /**
555
594
  * Web Decoy SDK Types
556
595
  * Based on the ingest service API contract
@@ -567,8 +606,10 @@ interface WebDecoyConfig {
567
606
  */
568
607
  apiKey?: string;
569
608
  /**
570
- * API URL for the Web Decoy ingest service
571
- * @default 'https://ingest.webdecoy.com'
609
+ * API URL for the Web Decoy ingest service. Server-to-server traffic
610
+ * fronts through Cloudflare at in.webdecoy.com; only the browser tag
611
+ * stays on the direct hostname.
612
+ * @default 'https://in.webdecoy.com'
572
613
  */
573
614
  apiUrl?: string;
574
615
  /**
@@ -643,6 +684,20 @@ interface WebDecoyConfig {
643
684
  * silently drops every structured field.
644
685
  */
645
686
  logger?: Logger;
687
+ /**
688
+ * An OpenTelemetry tracer, if you run one.
689
+ *
690
+ * Injected rather than imported so this package stays dependency-free and
691
+ * edge-safe. The interface is a structural subset of OpenTelemetry's, so
692
+ * `trace.getTracer('webdecoy')` works directly:
693
+ *
694
+ * ```ts
695
+ * new WebDecoy({ tracer: trace.getTracer('webdecoy') });
696
+ * ```
697
+ *
698
+ * Omit it and there are no spans, no dependency and no behaviour change.
699
+ */
700
+ tracer?: Tracer;
646
701
  }
647
702
  /**
648
703
  * TLS connection information from the request
@@ -1226,6 +1281,8 @@ declare class WebDecoy {
1226
1281
  private readonly characteristics;
1227
1282
  /** Where diagnostics go. Never console directly — see logger.ts. */
1228
1283
  readonly log: Logger;
1284
+ /** Optional OpenTelemetry tracer. Absent means no spans and no cost. */
1285
+ private readonly tracer?;
1229
1286
  private readonly decisionCache;
1230
1287
  constructor(config: WebDecoyConfig);
1231
1288
  /**
@@ -1344,4 +1401,4 @@ declare class WebDecoy {
1344
1401
  destroy(): Promise<void>;
1345
1402
  }
1346
1403
 
1347
- export { fromPino as $, type AgentCategory as A, type BotRuleConfig as B, type Characteristic as C, Decision as D, EDGE_CLASS_HEADER as E, type FilterConfig as F, type Logger as G, type ProtectResult as H, type IPEnrichmentData as I, type RequestMetadata as J, type RuleOutcome as K, type LocalAnalysis as L, MemoryRateLimitStore as M, type RuleState as N, type SDKDetectionRequest as O, type ProtectOptions as P, type SDKDetectionResponse as Q, type Rule as R, type SignedAgentDirectory as S, type TripwireConfig as T, type SyncRateLimitStore as U, type TLSInfo as V, WebDecoy as W, type ViolationEvent as X, classifyUserAgent as Y, consoleLogger as Z, deriveKey as _, type RuleContext as a, matchUserAgent as a0, newDecisionId as a1, readEdgeVerdict as a2, silentLogger as a3, type RuleResult as b, type WebDecoyConfig as c, type RuleEngineResult as d, type RateLimitConfig as e, type BotAgent as f, type BotCategory as g, type RateLimitStore as h, type RateLimitConsume as i, type RateLimitOutcome as j, type AgentVerifierOptions as k, type AgentRequestInput as l, type AgentVerdict as m, type AgentStatus as n, BOT_CATEGORIES as o, BOT_REGISTRY as p, type BotVerdict as q, type Conclusion as r, DEFAULT_CHARACTERISTICS as s, DecisionCache as t, type DecisionCacheOptions as u, type DecisionInit as v, EDGE_CLEARANCE_HEADER as w, type EdgeClass as x, type EdgeVerdict as y, type LogFields as z };
1404
+ export { consoleLogger as $, type AgentCategory as A, type BotRuleConfig as B, type Characteristic as C, Decision as D, EDGE_CLASS_HEADER as E, type FilterConfig as F, type LogFields as G, type Logger as H, type IPEnrichmentData as I, type RequestMetadata as J, type RuleOutcome as K, type LocalAnalysis as L, MemoryRateLimitStore as M, type RuleState as N, type SDKDetectionRequest as O, type ProtectResult as P, type SDKDetectionResponse as Q, type Rule as R, type SignedAgentDirectory as S, type TripwireConfig as T, type Span as U, type SyncRateLimitStore as V, WebDecoy as W, type TLSInfo as X, type Tracer as Y, type ViolationEvent as Z, classifyUserAgent as _, type RuleContext as a, deriveKey as a0, fromPino as a1, matchUserAgent as a2, newDecisionId as a3, readEdgeVerdict as a4, silentLogger as a5, type RuleResult as b, type RuleEngineResult as c, type RateLimitConfig as d, type BotAgent as e, type BotCategory as f, type RateLimitStore as g, type RateLimitConsume as h, type RateLimitOutcome as i, type WebDecoyConfig as j, type ProtectOptions as k, type AgentVerifierOptions as l, type AgentRequestInput as m, type AgentVerdict as n, type AgentStatus as o, BOT_CATEGORIES as p, BOT_REGISTRY as q, type BotVerdict as r, type Conclusion as s, DEFAULT_CHARACTERISTICS as t, DecisionCache as u, type DecisionCacheOptions as v, type DecisionInit as w, EDGE_CLEARANCE_HEADER as x, type EdgeClass as y, type EdgeVerdict as z };
@@ -1,4 +1,4 @@
1
- import { c as WebDecoyConfig, J as RequestMetadata, W as WebDecoy, H as ProtectResult, N as RuleState } from './sdk-DjeCBrHu.mjs';
1
+ import { j as WebDecoyConfig, J as RequestMetadata, W as WebDecoy, P as ProtectResult, N as RuleState } from './sdk-qUjMf8ZX.mjs';
2
2
 
3
3
  /**
4
4
  * Testing utilities, for the application's test suite rather than ours.
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { c as WebDecoyConfig, J as RequestMetadata, W as WebDecoy, H as ProtectResult, N as RuleState } from './sdk-DjeCBrHu.js';
1
+ import { j as WebDecoyConfig, J as RequestMetadata, W as WebDecoy, P as ProtectResult, N as RuleState } from './sdk-qUjMf8ZX.js';
2
2
 
3
3
  /**
4
4
  * Testing utilities, for the application's test suite rather than ours.
package/dist/testing.js CHANGED
@@ -450,6 +450,7 @@ var TripwireRule = class {
450
450
 
451
451
  // src/bots/registry.generated.ts
452
452
  var BOT_REGISTRY = [
453
+ { id: "reflectionbot", name: "Reflectionbot", category: "training_crawler", organization: "Reflection AI", baseScore: 70, respectsRobots: true, uaPatterns: ["reflectionbot"] },
453
454
  { id: "gptbot", name: "GPTBot", category: "training_crawler", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["gptbot"] },
454
455
  { id: "chatgpt-user", name: "ChatGPT-User", category: "training_crawler", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["chatgpt-user", "chatgpt"] },
455
456
  { id: "oai-searchbot", name: "OAI-SearchBot", category: "training_crawler", organization: "OpenAI", baseScore: 80, respectsRobots: true, uaPatterns: ["oai-searchbot"] },
@@ -478,6 +479,10 @@ var BOT_REGISTRY = [
478
479
  { id: "velenpublicwebcrawler", name: "VelenPublicWebCrawler", category: "training_crawler", organization: "Velen", baseScore: 70, respectsRobots: false, uaPatterns: ["velenpublicwebcrawler"] },
479
480
  { id: "isscyberriskcrawler", name: "ISSCyberRiskCrawler", category: "training_crawler", organization: "ISS", baseScore: 65, respectsRobots: false, uaPatterns: ["isscyberriskcrawler"] },
480
481
  { id: "friendlycrawler", name: "FriendlyCrawler", category: "training_crawler", organization: "Unknown", baseScore: 65, respectsRobots: true, uaPatterns: ["friendlycrawler"] },
482
+ { id: "duckassistbot", name: "DuckAssistBot", category: "ai_search_crawler", organization: "DuckDuckGo", baseScore: 65, respectsRobots: true, uaPatterns: ["duckassistbot"] },
483
+ { id: "sofyabot", name: "SofyaBot", category: "ai_search_crawler", organization: "Sofya", baseScore: 65, respectsRobots: true, uaPatterns: ["sofyabot"] },
484
+ { id: "xai-searchbot", name: "xAI-SearchBot", category: "ai_search_crawler", organization: "xAI", baseScore: 70, respectsRobots: true, uaPatterns: ["xai-searchbot"] },
485
+ { id: "linkupbot", name: "LinkupBot", category: "ai_search_crawler", organization: "Linkup", baseScore: 65, respectsRobots: true, uaPatterns: ["linkupbot"] },
481
486
  { id: "searchgpt", name: "SearchGPT", category: "ai_search_crawler", organization: "OpenAI", baseScore: 75, respectsRobots: true, uaPatterns: ["searchgpt"] },
482
487
  { id: "phind", name: "Phind", category: "ai_search_crawler", organization: "Phind", baseScore: 70, respectsRobots: true, uaPatterns: ["phind"] },
483
488
  { id: "kagi", name: "Kagi", category: "ai_search_crawler", organization: "Kagi", baseScore: 65, respectsRobots: true, uaPatterns: ["kagi"] },
@@ -494,6 +499,7 @@ var BOT_REGISTRY = [
494
499
  { id: "browser-use", name: "Browser-Use", category: "ai_agent", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["browser-use"] },
495
500
  { id: "stagehand", name: "Stagehand", category: "ai_agent", organization: "Browserbase", baseScore: 70, respectsRobots: false, uaPatterns: ["stagehand"] },
496
501
  { id: "multion", name: "MultiOn", category: "ai_agent", organization: "MultiOn", baseScore: 70, respectsRobots: false, uaPatterns: ["multion"] },
502
+ { id: "iboubot", name: "IbouBot", category: "search_crawler", organization: "Ibou", baseScore: 30, respectsRobots: true, uaPatterns: ["iboubot"] },
497
503
  { id: "googlebot", name: "Googlebot", category: "search_crawler", organization: "Google", baseScore: 30, respectsRobots: true, uaPatterns: ["googlebot"] },
498
504
  { id: "bingbot", name: "Bingbot", category: "search_crawler", organization: "Microsoft", baseScore: 30, respectsRobots: true, uaPatterns: ["bingbot"] },
499
505
  { id: "yandexbot", name: "YandexBot", category: "search_crawler", organization: "Yandex", baseScore: 35, respectsRobots: true, uaPatterns: ["yandexbot"] },
@@ -1507,6 +1513,43 @@ function resolveLogger(provided, debug) {
1507
1513
  return provided ?? consoleLogger(debug);
1508
1514
  }
1509
1515
 
1516
+ // src/tracing.ts
1517
+ var STATUS_ERROR = 2;
1518
+ var NOOP_SPAN = {
1519
+ setAttribute: () => void 0,
1520
+ end: () => void 0
1521
+ };
1522
+ function startSpan(tracer, name) {
1523
+ if (!tracer) return NOOP_SPAN;
1524
+ try {
1525
+ return tracer.startSpan(name) ?? NOOP_SPAN;
1526
+ } catch {
1527
+ return NOOP_SPAN;
1528
+ }
1529
+ }
1530
+ function setAttribute(span, key, value) {
1531
+ try {
1532
+ span.setAttribute(key, value);
1533
+ } catch {
1534
+ }
1535
+ }
1536
+ function recordError(span, error) {
1537
+ try {
1538
+ span.recordException?.(error);
1539
+ span.setStatus?.({
1540
+ code: STATUS_ERROR,
1541
+ message: error instanceof Error ? error.message : String(error)
1542
+ });
1543
+ } catch {
1544
+ }
1545
+ }
1546
+ function endSpan(span) {
1547
+ try {
1548
+ span.end();
1549
+ } catch {
1550
+ }
1551
+ }
1552
+
1510
1553
  // src/decision.ts
1511
1554
  function newDecisionId() {
1512
1555
  return `dec_${randomHex(12)}`;
@@ -1678,7 +1721,7 @@ var WebDecoy = class {
1678
1721
  }
1679
1722
  this.config = {
1680
1723
  apiKey: config.apiKey,
1681
- apiUrl: config.apiUrl || "https://ingest.webdecoy.com",
1724
+ apiUrl: config.apiUrl || "https://in.webdecoy.com",
1682
1725
  enableTLSFingerprinting: config.enableTLSFingerprinting ?? true,
1683
1726
  threatScoreThreshold: config.threatScoreThreshold ?? 80,
1684
1727
  timeout: config.timeout ?? 5e3,
@@ -1686,6 +1729,7 @@ var WebDecoy = class {
1686
1729
  tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
1687
1730
  };
1688
1731
  this.log = resolveLogger(config.logger, this.config.debug);
1732
+ this.tracer = config.tracer;
1689
1733
  if (hasApiKey) {
1690
1734
  this.client = new WebDecoyClient({
1691
1735
  apiKey: config.apiKey,
@@ -1813,7 +1857,13 @@ var WebDecoy = class {
1813
1857
  /** Evaluate rules against a prepared context and report any violations. */
1814
1858
  runRules(context) {
1815
1859
  if (!this.ruleEngine) return null;
1860
+ const span = startSpan(this.tracer, "webdecoy.rules");
1816
1861
  const result = this.ruleEngine.evaluate(context);
1862
+ setAttribute(span, "webdecoy.rules.action", result.action);
1863
+ setAttribute(span, "webdecoy.rules.evaluated", result.results.length);
1864
+ setAttribute(span, "webdecoy.rules.violations", result.violations.length);
1865
+ if (result.rule) setAttribute(span, "webdecoy.rules.deciding", result.rule);
1866
+ endSpan(span);
1817
1867
  if (result.violations.length > 0 && this.violationReporter) {
1818
1868
  this.violationReporter.report(result.violations);
1819
1869
  }
@@ -1881,7 +1931,31 @@ var WebDecoy = class {
1881
1931
  */
1882
1932
  async protect(metadata, options = {}) {
1883
1933
  const edge = readEdgeVerdict(metadata.headers);
1884
- return (await this.decide(metadata, options)).withEdge(edge);
1934
+ const span = startSpan(this.tracer, "webdecoy.protect");
1935
+ try {
1936
+ const decision = (await this.decide(metadata, options)).withEdge(edge);
1937
+ setAttribute(span, "webdecoy.decision.id", decision.id);
1938
+ setAttribute(span, "webdecoy.decision.conclusion", decision.conclusion);
1939
+ setAttribute(span, "webdecoy.decision.allowed", decision.allowed);
1940
+ setAttribute(span, "webdecoy.rules.evaluated", decision.results.length);
1941
+ if (decision.ruleResult?.rule) {
1942
+ setAttribute(span, "webdecoy.decision.rule", decision.ruleResult.rule);
1943
+ }
1944
+ setAttribute(
1945
+ span,
1946
+ "webdecoy.remote",
1947
+ decision.detection.detection_id !== decision.id
1948
+ );
1949
+ if (decision.error) {
1950
+ setAttribute(span, "webdecoy.error", decision.error);
1951
+ }
1952
+ return decision;
1953
+ } catch (error) {
1954
+ recordError(span, error);
1955
+ throw error;
1956
+ } finally {
1957
+ endSpan(span);
1958
+ }
1885
1959
  }
1886
1960
  async decide(metadata, options = {}) {
1887
1961
  const id = newDecisionId();
package/dist/testing.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  WebDecoy,
3
3
  silentLogger
4
- } from "./chunk-CIRFOOMU.mjs";
4
+ } from "./chunk-4QKKW7GN.mjs";
5
5
 
6
6
  // src/testing.ts
7
7
  function request(over = {}) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webdecoy/node",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "Web Decoy SDK for Node.js - Bot detection with TLS fingerprinting",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",