@webdecoy/node 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { R as Rule, a as RuleContext, b as RuleResult, D as Decision, W as WebDecoy, c as WebDecoyConfig, P as ProtectOptions, d as RuleEngineResult, e as RateLimitConfig, F as FilterConfig, T as TripwireConfig, B as BotRuleConfig, f as BotAgent, g as BotCategory, A as AgentCategory, h as RateLimitStore, i as RateLimitConsume, j as RateLimitOutcome, k as AgentVerifierOptions, l as AgentRequestInput, m as AgentVerdict, S as SignedAgentDirectory } from './sdk-DjeCBrHu.js';
2
- export { n as AgentStatus, o as BOT_CATEGORIES, p as BOT_REGISTRY, q as BotVerdict, C as Characteristic, r as Conclusion, s as DEFAULT_CHARACTERISTICS, t as DecisionCache, u as DecisionCacheOptions, v as DecisionInit, E as EDGE_CLASS_HEADER, w as EDGE_CLEARANCE_HEADER, x as EdgeClass, y as EdgeVerdict, I as IPEnrichmentData, L as LocalAnalysis, z as LogFields, G as Logger, M as MemoryRateLimitStore, H as ProtectResult, J as RequestMetadata, K as RuleOutcome, N as RuleState, O as SDKDetectionRequest, Q as SDKDetectionResponse, U as SyncRateLimitStore, V as TLSInfo, X as ViolationEvent, Y as classifyUserAgent, Z as consoleLogger, _ as deriveKey, $ as fromPino, a0 as matchUserAgent, a1 as newDecisionId, a2 as readEdgeVerdict, a3 as silentLogger } from './sdk-DjeCBrHu.js';
1
+ import { R as Rule, a as RuleContext, b as RuleResult, c as RuleEngineResult, d as RateLimitConfig, F as FilterConfig, T as TripwireConfig, B as BotRuleConfig, e as BotAgent, f as BotCategory, A as AgentCategory, g as RateLimitStore, h as RateLimitConsume, i as RateLimitOutcome, W as WebDecoy, P as ProtectResult, D as Decision, j as WebDecoyConfig, k as ProtectOptions, l as AgentVerifierOptions, m as AgentRequestInput, n as AgentVerdict, S as SignedAgentDirectory } from './sdk-qUjMf8ZX.js';
2
+ export { o as AgentStatus, p as BOT_CATEGORIES, q as BOT_REGISTRY, r as BotVerdict, C as Characteristic, s as Conclusion, t as DEFAULT_CHARACTERISTICS, u as DecisionCache, v as DecisionCacheOptions, w as DecisionInit, E as EDGE_CLASS_HEADER, x as EDGE_CLEARANCE_HEADER, y as EdgeClass, z as EdgeVerdict, I as IPEnrichmentData, L as LocalAnalysis, G as LogFields, H as Logger, M as MemoryRateLimitStore, J as RequestMetadata, K as RuleOutcome, N as RuleState, O as SDKDetectionRequest, Q as SDKDetectionResponse, U as Span, V as SyncRateLimitStore, X as TLSInfo, Y as Tracer, Z as ViolationEvent, _ as classifyUserAgent, $ as consoleLogger, a0 as deriveKey, a1 as fromPino, a2 as matchUserAgent, a3 as newDecisionId, a4 as readEdgeVerdict, a5 as silentLogger } from './sdk-qUjMf8ZX.js';
3
3
 
4
4
  /**
5
5
  * The reserved test trigger.
@@ -634,92 +634,6 @@ declare class ClientSignalRule implements Rule {
634
634
  /** Act on the browser widget's verdict for this session. See {@link ClientSignalConfig}. */
635
635
  declare function clientSignals(config: ClientSignalConfig): Rule;
636
636
 
637
- /**
638
- * One adapter, for every runtime that speaks `Request` and `Response`.
639
- *
640
- * WHY THIS EXISTS
641
- *
642
- * Express, Fastify and Next.js each grew their own copy of the same middleware:
643
- * skip-path matching, monitor-versus-enforce, honeytoken arming, the 429 with a
644
- * `Retry-After`, fail-open error handling. Three copies of a decision tree is
645
- * three places for the branch that matters to be subtly different — and it
646
- * already had been, which is how the leftmost-`X-Forwarded-For` bug survived in
647
- * two adapters after the WordPress plugin fixed it.
648
- *
649
- * It is also the answer to "which framework do you support?". Hono, Bun, Deno,
650
- * Astro, Nitro, SvelteKit and Remix all hand you a WHATWG `Request` and want a
651
- * `Response` back. Written once here, each of those is a translation layer thin
652
- * enough not to need a package — see the README recipe — and `@webdecoy/hono` is
653
- * the one that does, because Hono has a middleware contract worth fitting.
654
- *
655
- * No `node:` imports: this is the code path that has to run on Workers.
656
- */
657
-
658
- interface FetchGuardOptions extends WebDecoyConfig, ProtectOptions {
659
- /**
660
- * Whether a blocking verdict actually blocks. Defaults to `'monitor'`.
661
- *
662
- * Nobody adopts a defence by having it break their site on the first install.
663
- * Watch what it would have done, then switch.
664
- */
665
- mode?: 'monitor' | 'enforce';
666
- /** Paths to skip entirely — health checks, static assets. */
667
- skipPaths?: (string | RegExp)[];
668
- /**
669
- * How much of the `X-Forwarded-For` chain to believe. Defaults to `1` trusted
670
- * hop: a fetch handler has no socket to fall back on, so there is no
671
- * believe-nothing default available. See `resolveClientIp`.
672
- */
673
- trustProxy?: TrustedProxies;
674
- /** Override IP resolution entirely. */
675
- getIP?: (request: Request) => string;
676
- /**
677
- * Inject a hidden honeytoken link into HTML responses, and arm the tripwire it
678
- * points at. Defaults to on when an `apiKey` is present.
679
- */
680
- honeytoken?: boolean;
681
- /** Build the blocking response. Defaults to 403, or 429 for a throttle. */
682
- onBlocked?: (request: Request, decision: Decision) => Response | Promise<Response>;
683
- }
684
- interface GuardOutcome {
685
- /** What the SDK concluded. Always present, in both modes. */
686
- decision: Decision;
687
- /**
688
- * The response to return instead of calling the handler, or undefined to
689
- * carry on. Undefined in monitor mode even when the decision is a denial.
690
- */
691
- response?: Response;
692
- }
693
- interface FetchGuard {
694
- /** Evaluate one request. */
695
- check(request: Request, peer?: string): Promise<GuardOutcome>;
696
- /**
697
- * Rewrite an HTML response to carry the honeytoken link. Returns the response
698
- * unchanged when there is no token yet, or the body is not injectable HTML.
699
- */
700
- decorate(response: Response): Promise<Response>;
701
- /** Whether this path is skipped. */
702
- skips(pathname: string): boolean;
703
- /** The underlying SDK, for `detectBot()` and friends. */
704
- sdk: WebDecoy;
705
- }
706
- /**
707
- * A guard over WHATWG `Request`/`Response`.
708
- *
709
- * ```ts
710
- * const guard = createFetchGuard({ rules: [tripwire()] });
711
- *
712
- * export default {
713
- * async fetch(request) {
714
- * const { response } = await guard.check(request);
715
- * if (response) return response;
716
- * return guard.decorate(await handle(request));
717
- * },
718
- * };
719
- * ```
720
- */
721
- declare function createFetchGuard(options?: FetchGuardOptions): FetchGuard;
722
-
723
637
  /**
724
638
  * Rule Engine
725
639
  * Evaluates rules in order — first DENY/THROTTLE wins
@@ -1398,6 +1312,165 @@ declare function tripwire(config?: TripwireConfig): Rule;
1398
1312
  */
1399
1313
  declare function bots(config?: BotRuleConfig): Rule;
1400
1314
 
1315
+ /**
1316
+ * The parts of a middleware that are the same in every framework.
1317
+ *
1318
+ * WHY THIS EXISTS
1319
+ *
1320
+ * Express, Fastify, Next.js and the fetch guard each grew their own copy of the
1321
+ * same decision tree: skip-path matching, monitor-versus-enforce, honeytoken
1322
+ * arming, the 429 payload, the 403 payload. Four copies of one set of rules.
1323
+ *
1324
+ * That is not a tidiness complaint. The leftmost-`X-Forwarded-For` bug survived
1325
+ * in two adapters after the same class of bug had already been fixed elsewhere,
1326
+ * precisely because there was no one place to fix. Every copy is a place the
1327
+ * next correction can fail to land, and each one reads perfectly sensibly on its
1328
+ * own — which is why review does not catch it.
1329
+ *
1330
+ * WHAT STAYS IN THE ADAPTERS
1331
+ *
1332
+ * Everything that touches the framework: reading metadata off its request
1333
+ * object, writing its response, and injecting the honeytoken link into whatever
1334
+ * that framework calls a body. Response mechanics differ genuinely — Express
1335
+ * intercepts `res.write`/`res.end`, Fastify uses an `onSend` hook, a fetch
1336
+ * handler rebuilds a `Response` — and the detail in each is hard-won. This
1337
+ * module holds the decisions, not the I/O.
1338
+ */
1339
+
1340
+ /** Whether a request path is exempt from protection. */
1341
+ declare function shouldSkipPath(path: string, patterns: readonly (string | RegExp)[] | undefined): boolean;
1342
+ /** A framework-agnostic description of the response a blocked request gets. */
1343
+ interface BlockResponse {
1344
+ status: number;
1345
+ headers: Record<string, string>;
1346
+ body: Record<string, unknown>;
1347
+ }
1348
+ /**
1349
+ * What to answer a request the rules refused.
1350
+ *
1351
+ * Returns null when the decision was not a rule refusal — a server-score block
1352
+ * has no rule to name, and each adapter's `onBlocked` handles that case with its
1353
+ * own default.
1354
+ */
1355
+ declare function ruleBlockResponse(decision: ProtectResult): BlockResponse | null;
1356
+ interface HoneytokenArmingOptions {
1357
+ /** The site honeytoken is derived from this. No key, no token. */
1358
+ apiKey?: string;
1359
+ /** Defaults to on when an apiKey is present. */
1360
+ enabled?: boolean;
1361
+ /** Reported when derivation fails, so a silent absence is at least loggable. */
1362
+ onError?: (error: unknown) => void;
1363
+ }
1364
+ /**
1365
+ * Derive the site honeytoken and arm the tripwire it points at.
1366
+ *
1367
+ * Returns a getter rather than a promise: derivation is async (WebCrypto HMAC,
1368
+ * so this still runs on edge runtimes) and requests served before it settles
1369
+ * simply carry no link. That is a few milliseconds at boot against the
1370
+ * alternative of blocking startup on crypto.
1371
+ *
1372
+ * The token is derived from the API key so every replica computes the same path
1373
+ * without coordinating. A random per-process token would advertise a link whose
1374
+ * tripwire only one replica had armed — bait with no trap behind it.
1375
+ */
1376
+ declare function armSiteHoneytoken(sdk: WebDecoy, options: HoneytokenArmingOptions): () => SiteHoneytoken | null;
1377
+ /**
1378
+ * Derive and arm, awaited.
1379
+ *
1380
+ * For a framework whose registration is already an async boot phase — Fastify's
1381
+ * plugin hook — where waiting costs nothing and removes the window in which
1382
+ * early requests are served without the link. Same logic as
1383
+ * {@link armSiteHoneytoken}; only the timing differs, which is why it is a
1384
+ * second entry point rather than a second implementation.
1385
+ */
1386
+ declare function deriveAndArm(sdk: WebDecoy, options: HoneytokenArmingOptions): Promise<SiteHoneytoken | null>;
1387
+
1388
+ /**
1389
+ * One adapter, for every runtime that speaks `Request` and `Response`.
1390
+ *
1391
+ * WHY THIS EXISTS
1392
+ *
1393
+ * Express, Fastify and Next.js each grew their own copy of the same middleware:
1394
+ * skip-path matching, monitor-versus-enforce, honeytoken arming, the 429 with a
1395
+ * `Retry-After`, fail-open error handling. Three copies of a decision tree is
1396
+ * three places for the branch that matters to be subtly different — and it
1397
+ * already had been, which is how the leftmost-`X-Forwarded-For` bug survived in
1398
+ * two adapters after the WordPress plugin fixed it.
1399
+ *
1400
+ * It is also the answer to "which framework do you support?". Hono, Bun, Deno,
1401
+ * Astro, Nitro, SvelteKit and Remix all hand you a WHATWG `Request` and want a
1402
+ * `Response` back. Written once here, each of those is a translation layer thin
1403
+ * enough not to need a package — see the README recipe — and `@webdecoy/hono` is
1404
+ * the one that does, because Hono has a middleware contract worth fitting.
1405
+ *
1406
+ * No `node:` imports: this is the code path that has to run on Workers.
1407
+ */
1408
+
1409
+ interface FetchGuardOptions extends WebDecoyConfig, ProtectOptions {
1410
+ /**
1411
+ * Whether a blocking verdict actually blocks. Defaults to `'monitor'`.
1412
+ *
1413
+ * Nobody adopts a defence by having it break their site on the first install.
1414
+ * Watch what it would have done, then switch.
1415
+ */
1416
+ mode?: 'monitor' | 'enforce';
1417
+ /** Paths to skip entirely — health checks, static assets. */
1418
+ skipPaths?: (string | RegExp)[];
1419
+ /**
1420
+ * How much of the `X-Forwarded-For` chain to believe. Defaults to `1` trusted
1421
+ * hop: a fetch handler has no socket to fall back on, so there is no
1422
+ * believe-nothing default available. See `resolveClientIp`.
1423
+ */
1424
+ trustProxy?: TrustedProxies;
1425
+ /** Override IP resolution entirely. */
1426
+ getIP?: (request: Request) => string;
1427
+ /**
1428
+ * Inject a hidden honeytoken link into HTML responses, and arm the tripwire it
1429
+ * points at. Defaults to on when an `apiKey` is present.
1430
+ */
1431
+ honeytoken?: boolean;
1432
+ /** Build the blocking response. Defaults to 403, or 429 for a throttle. */
1433
+ onBlocked?: (request: Request, decision: Decision) => Response | Promise<Response>;
1434
+ }
1435
+ interface GuardOutcome {
1436
+ /** What the SDK concluded. Always present, in both modes. */
1437
+ decision: Decision;
1438
+ /**
1439
+ * The response to return instead of calling the handler, or undefined to
1440
+ * carry on. Undefined in monitor mode even when the decision is a denial.
1441
+ */
1442
+ response?: Response;
1443
+ }
1444
+ interface FetchGuard {
1445
+ /** Evaluate one request. */
1446
+ check(request: Request, peer?: string): Promise<GuardOutcome>;
1447
+ /**
1448
+ * Rewrite an HTML response to carry the honeytoken link. Returns the response
1449
+ * unchanged when there is no token yet, or the body is not injectable HTML.
1450
+ */
1451
+ decorate(response: Response): Promise<Response>;
1452
+ /** Whether this path is skipped. */
1453
+ skips(pathname: string): boolean;
1454
+ /** The underlying SDK, for `detectBot()` and friends. */
1455
+ sdk: WebDecoy;
1456
+ }
1457
+ /**
1458
+ * A guard over WHATWG `Request`/`Response`.
1459
+ *
1460
+ * ```ts
1461
+ * const guard = createFetchGuard({ rules: [tripwire()] });
1462
+ *
1463
+ * export default {
1464
+ * async fetch(request) {
1465
+ * const { response } = await guard.check(request);
1466
+ * if (response) return response;
1467
+ * return guard.decorate(await handle(request));
1468
+ * },
1469
+ * };
1470
+ * ```
1471
+ */
1472
+ declare function createFetchGuard(options?: FetchGuardOptions): FetchGuard;
1473
+
1401
1474
  /**
1402
1475
  * AgentVerifier — the public entry point for local Web Bot Auth verification.
1403
1476
  *
@@ -1779,4 +1852,4 @@ declare function createCaptchaEndpoints(options?: CaptchaEndpointsOptions): {
1779
1852
  };
1780
1853
  type CaptchaEndpoints = ReturnType<typeof createCaptchaEndpoints>;
1781
1854
 
1782
- export { ATTACK_SIGNATURE_IDS, AgentCategory, AgentRequestInput, AgentVerdict, AgentVerifier, AgentVerifierOptions, type AttackSignatureConfig, AttackSignatureRule, type BehavioralSignals, BotAgent, BotCategory, BotPolicy, type BotPolicyOptions, BotRule, BotRuleConfig, CLIENT_SESSION_COOKIE, CLIENT_SESSION_HEADER, Captcha, type CaptchaEndpoints, type CaptchaEndpointsOptions, type CaptchaHttpResponse, type CaptchaOptions, type CaptchaRequest, type CategoryScores, type ChallengeData, type ChallengeStore, type ClientSignalConfig, ClientSignalRule, type ClientSignalStore, type ClientVerdict, DEFAULT_SIGNED_AGENT_DIRECTORIES, DEFAULT_TRIPWIRE_PATHS, DEFAULT_WEIGHTS, Decision, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, DirectoryCache, type EnvironmentalSignals, type FetchGuard, type FetchGuardOptions, FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, type GuardOutcome, HONEYTOKEN_BASE_PATH, type HeaderSource, type Honeytoken, type HoneytokenLinkProps, type HoneytokenOptions, InMemoryChallengeStore, InMemoryFingerprintStore, InMemoryRateLimiter, InMemoryTokenStore, MemoryClientSignalStore, type MemoryClientSignalStoreOptions, PoWManager, type PoWManagerOptions, type PoWOutcome, type PoWSolution, type PoWVerification, ProtectOptions, RateLimitConfig, RateLimitConsume, RateLimitOutcome, RateLimitRule, RateLimitStore, type RateLimiter, type Recommendation, type ResolveClientIpOptions, type RobotsTxtOptions, Rule, RuleContext, RuleEngine, RuleEngineResult, RuleResult, type ScoreResult, type Signals, SignedAgentDirectory, type SiteHoneytoken, type SiteHoneytokenOptions, type StoredChallenge, TEST_TRIGGER_UA_PREFIX, TEST_TRIGGER_USER_AGENT, type TemporalSignals, type TextareaKeyboardStats, TokenManager, type TokenManagerOptions, type TokenStore, type TokenVerification, TripwireConfig, TripwireRule, type TrustedProxies, UpstashRateLimitStore, type UpstashStoreOptions, type Verdict, type VerifyInput, type VerifyResult, type WebBotAuthConfig, WebBotAuthRule, WebDecoy, WebDecoyConfig, attackSignatures, botPolicy, bots, calculateCategoryScores, calculateFinalScore, clientSignals, createAgentVerifier, createCaptchaEndpoints, createFetchGuard, filter, honeytoken, injectHoneytokenLink, ipInCidr, isDatacenterIP, isInjectableHtml, isMobileUA, isTestTriggerUserAgent, normalizeIp, parseUserAgent, rateLimit, readClientSession, recommend, resolveClientIp, resolveSecret, siteHoneytoken, tripwire, upstashRateLimitStore, webBotAuth };
1855
+ export { ATTACK_SIGNATURE_IDS, AgentCategory, AgentRequestInput, AgentVerdict, AgentVerifier, AgentVerifierOptions, type AttackSignatureConfig, AttackSignatureRule, type BehavioralSignals, type BlockResponse, BotAgent, BotCategory, BotPolicy, type BotPolicyOptions, BotRule, BotRuleConfig, CLIENT_SESSION_COOKIE, CLIENT_SESSION_HEADER, Captcha, type CaptchaEndpoints, type CaptchaEndpointsOptions, type CaptchaHttpResponse, type CaptchaOptions, type CaptchaRequest, type CategoryScores, type ChallengeData, type ChallengeStore, type ClientSignalConfig, ClientSignalRule, type ClientSignalStore, type ClientVerdict, DEFAULT_SIGNED_AGENT_DIRECTORIES, DEFAULT_TRIPWIRE_PATHS, DEFAULT_WEIGHTS, Decision, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, DirectoryCache, type EnvironmentalSignals, type FetchGuard, type FetchGuardOptions, FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, type GuardOutcome, HONEYTOKEN_BASE_PATH, type HeaderSource, type Honeytoken, type HoneytokenArmingOptions, type HoneytokenLinkProps, type HoneytokenOptions, InMemoryChallengeStore, InMemoryFingerprintStore, InMemoryRateLimiter, InMemoryTokenStore, MemoryClientSignalStore, type MemoryClientSignalStoreOptions, PoWManager, type PoWManagerOptions, type PoWOutcome, type PoWSolution, type PoWVerification, ProtectOptions, ProtectResult, RateLimitConfig, RateLimitConsume, RateLimitOutcome, RateLimitRule, RateLimitStore, type RateLimiter, type Recommendation, type ResolveClientIpOptions, type RobotsTxtOptions, Rule, RuleContext, RuleEngine, RuleEngineResult, RuleResult, type ScoreResult, type Signals, SignedAgentDirectory, type SiteHoneytoken, type SiteHoneytokenOptions, type StoredChallenge, TEST_TRIGGER_UA_PREFIX, TEST_TRIGGER_USER_AGENT, type TemporalSignals, type TextareaKeyboardStats, TokenManager, type TokenManagerOptions, type TokenStore, type TokenVerification, TripwireConfig, TripwireRule, type TrustedProxies, UpstashRateLimitStore, type UpstashStoreOptions, type Verdict, type VerifyInput, type VerifyResult, type WebBotAuthConfig, WebBotAuthRule, WebDecoy, WebDecoyConfig, armSiteHoneytoken, attackSignatures, botPolicy, bots, calculateCategoryScores, calculateFinalScore, clientSignals, createAgentVerifier, createCaptchaEndpoints, createFetchGuard, deriveAndArm, filter, honeytoken, injectHoneytokenLink, ipInCidr, isDatacenterIP, isInjectableHtml, isMobileUA, isTestTriggerUserAgent, normalizeIp, parseUserAgent, rateLimit, readClientSession, recommend, resolveClientIp, resolveSecret, ruleBlockResponse, shouldSkipPath, siteHoneytoken, tripwire, upstashRateLimitStore, webBotAuth };
package/dist/index.js CHANGED
@@ -59,6 +59,7 @@ __export(index_exports, {
59
59
  UpstashRateLimitStore: () => UpstashRateLimitStore,
60
60
  WebBotAuthRule: () => WebBotAuthRule,
61
61
  WebDecoy: () => WebDecoy,
62
+ armSiteHoneytoken: () => armSiteHoneytoken,
62
63
  attackSignatures: () => attackSignatures,
63
64
  botPolicy: () => botPolicy,
64
65
  bots: () => bots,
@@ -70,6 +71,7 @@ __export(index_exports, {
70
71
  createAgentVerifier: () => createAgentVerifier,
71
72
  createCaptchaEndpoints: () => createCaptchaEndpoints,
72
73
  createFetchGuard: () => createFetchGuard,
74
+ deriveAndArm: () => deriveAndArm,
73
75
  deriveKey: () => deriveKey,
74
76
  filter: () => filter,
75
77
  fromPino: () => fromPino,
@@ -90,6 +92,8 @@ __export(index_exports, {
90
92
  recommend: () => recommend,
91
93
  resolveClientIp: () => resolveClientIp,
92
94
  resolveSecret: () => resolveSecret,
95
+ ruleBlockResponse: () => ruleBlockResponse,
96
+ shouldSkipPath: () => shouldSkipPath,
93
97
  silentLogger: () => silentLogger,
94
98
  siteHoneytoken: () => siteHoneytoken,
95
99
  tripwire: () => tripwire,
@@ -329,11 +333,8 @@ function calculateLocalScore(suspiciousHeaders, missingSecCHUA, datacenterIP) {
329
333
  if (datacenterIP) score += 40;
330
334
  return Math.min(score, 100);
331
335
  }
332
- function needsVerification(localScore, hasTLSInfo) {
333
- if (hasTLSInfo) {
334
- return true;
335
- }
336
- return localScore >= 30;
336
+ function needsVerification(suspiciousHeaders, hasTLSInfo) {
337
+ return hasTLSInfo || suspiciousHeaders;
337
338
  }
338
339
  function buildFlags(suspiciousHeaders, missingSecCHUA, datacenterIP, metadata) {
339
340
  const flags = [];
@@ -361,7 +362,7 @@ function analyzeRequest(metadata) {
361
362
  const datacenterIP = isDatacenterIP(metadata.ip);
362
363
  const localScore = calculateLocalScore(suspiciousHeaders, missingSecCHUA, datacenterIP);
363
364
  const hasTLSInfo = Boolean(metadata.tls_info);
364
- const needsVerify = needsVerification(localScore, hasTLSInfo);
365
+ const needsVerify = needsVerification(suspiciousHeaders, hasTLSInfo);
365
366
  const flags = buildFlags(suspiciousHeaders, missingSecCHUA, datacenterIP, metadata);
366
367
  return {
367
368
  suspicious_headers: suspiciousHeaders,
@@ -1238,6 +1239,7 @@ var BOT_CATEGORIES = [
1238
1239
  "none"
1239
1240
  ];
1240
1241
  var BOT_REGISTRY = [
1242
+ { id: "reflectionbot", name: "Reflectionbot", category: "training_crawler", organization: "Reflection AI", baseScore: 70, respectsRobots: true, uaPatterns: ["reflectionbot"] },
1241
1243
  { id: "gptbot", name: "GPTBot", category: "training_crawler", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["gptbot"] },
1242
1244
  { id: "chatgpt-user", name: "ChatGPT-User", category: "training_crawler", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["chatgpt-user", "chatgpt"] },
1243
1245
  { id: "oai-searchbot", name: "OAI-SearchBot", category: "training_crawler", organization: "OpenAI", baseScore: 80, respectsRobots: true, uaPatterns: ["oai-searchbot"] },
@@ -1266,6 +1268,10 @@ var BOT_REGISTRY = [
1266
1268
  { id: "velenpublicwebcrawler", name: "VelenPublicWebCrawler", category: "training_crawler", organization: "Velen", baseScore: 70, respectsRobots: false, uaPatterns: ["velenpublicwebcrawler"] },
1267
1269
  { id: "isscyberriskcrawler", name: "ISSCyberRiskCrawler", category: "training_crawler", organization: "ISS", baseScore: 65, respectsRobots: false, uaPatterns: ["isscyberriskcrawler"] },
1268
1270
  { id: "friendlycrawler", name: "FriendlyCrawler", category: "training_crawler", organization: "Unknown", baseScore: 65, respectsRobots: true, uaPatterns: ["friendlycrawler"] },
1271
+ { id: "duckassistbot", name: "DuckAssistBot", category: "ai_search_crawler", organization: "DuckDuckGo", baseScore: 65, respectsRobots: true, uaPatterns: ["duckassistbot"] },
1272
+ { id: "sofyabot", name: "SofyaBot", category: "ai_search_crawler", organization: "Sofya", baseScore: 65, respectsRobots: true, uaPatterns: ["sofyabot"] },
1273
+ { id: "xai-searchbot", name: "xAI-SearchBot", category: "ai_search_crawler", organization: "xAI", baseScore: 70, respectsRobots: true, uaPatterns: ["xai-searchbot"] },
1274
+ { id: "linkupbot", name: "LinkupBot", category: "ai_search_crawler", organization: "Linkup", baseScore: 65, respectsRobots: true, uaPatterns: ["linkupbot"] },
1269
1275
  { id: "searchgpt", name: "SearchGPT", category: "ai_search_crawler", organization: "OpenAI", baseScore: 75, respectsRobots: true, uaPatterns: ["searchgpt"] },
1270
1276
  { id: "phind", name: "Phind", category: "ai_search_crawler", organization: "Phind", baseScore: 70, respectsRobots: true, uaPatterns: ["phind"] },
1271
1277
  { id: "kagi", name: "Kagi", category: "ai_search_crawler", organization: "Kagi", baseScore: 65, respectsRobots: true, uaPatterns: ["kagi"] },
@@ -1282,6 +1288,7 @@ var BOT_REGISTRY = [
1282
1288
  { id: "browser-use", name: "Browser-Use", category: "ai_agent", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["browser-use"] },
1283
1289
  { id: "stagehand", name: "Stagehand", category: "ai_agent", organization: "Browserbase", baseScore: 70, respectsRobots: false, uaPatterns: ["stagehand"] },
1284
1290
  { id: "multion", name: "MultiOn", category: "ai_agent", organization: "MultiOn", baseScore: 70, respectsRobots: false, uaPatterns: ["multion"] },
1291
+ { id: "iboubot", name: "IbouBot", category: "search_crawler", organization: "Ibou", baseScore: 30, respectsRobots: true, uaPatterns: ["iboubot"] },
1285
1292
  { id: "googlebot", name: "Googlebot", category: "search_crawler", organization: "Google", baseScore: 30, respectsRobots: true, uaPatterns: ["googlebot"] },
1286
1293
  { id: "bingbot", name: "Bingbot", category: "search_crawler", organization: "Microsoft", baseScore: 30, respectsRobots: true, uaPatterns: ["bingbot"] },
1287
1294
  { id: "yandexbot", name: "YandexBot", category: "search_crawler", organization: "Yandex", baseScore: 35, respectsRobots: true, uaPatterns: ["yandexbot"] },
@@ -2759,6 +2766,43 @@ function resolveLogger(provided, debug) {
2759
2766
  return provided ?? consoleLogger(debug);
2760
2767
  }
2761
2768
 
2769
+ // src/tracing.ts
2770
+ var STATUS_ERROR = 2;
2771
+ var NOOP_SPAN = {
2772
+ setAttribute: () => void 0,
2773
+ end: () => void 0
2774
+ };
2775
+ function startSpan(tracer, name) {
2776
+ if (!tracer) return NOOP_SPAN;
2777
+ try {
2778
+ return tracer.startSpan(name) ?? NOOP_SPAN;
2779
+ } catch {
2780
+ return NOOP_SPAN;
2781
+ }
2782
+ }
2783
+ function setAttribute(span, key, value) {
2784
+ try {
2785
+ span.setAttribute(key, value);
2786
+ } catch {
2787
+ }
2788
+ }
2789
+ function recordError(span, error) {
2790
+ try {
2791
+ span.recordException?.(error);
2792
+ span.setStatus?.({
2793
+ code: STATUS_ERROR,
2794
+ message: error instanceof Error ? error.message : String(error)
2795
+ });
2796
+ } catch {
2797
+ }
2798
+ }
2799
+ function endSpan(span) {
2800
+ try {
2801
+ span.end();
2802
+ } catch {
2803
+ }
2804
+ }
2805
+
2762
2806
  // src/decision.ts
2763
2807
  function newDecisionId() {
2764
2808
  return `dec_${randomHex(12)}`;
@@ -2931,7 +2975,7 @@ var WebDecoy = class {
2931
2975
  }
2932
2976
  this.config = {
2933
2977
  apiKey: config.apiKey,
2934
- apiUrl: config.apiUrl || "https://ingest.webdecoy.com",
2978
+ apiUrl: config.apiUrl || "https://in.webdecoy.com",
2935
2979
  enableTLSFingerprinting: config.enableTLSFingerprinting ?? true,
2936
2980
  threatScoreThreshold: config.threatScoreThreshold ?? 80,
2937
2981
  timeout: config.timeout ?? 5e3,
@@ -2939,6 +2983,7 @@ var WebDecoy = class {
2939
2983
  tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
2940
2984
  };
2941
2985
  this.log = resolveLogger(config.logger, this.config.debug);
2986
+ this.tracer = config.tracer;
2942
2987
  if (hasApiKey) {
2943
2988
  this.client = new WebDecoyClient({
2944
2989
  apiKey: config.apiKey,
@@ -3066,7 +3111,13 @@ var WebDecoy = class {
3066
3111
  /** Evaluate rules against a prepared context and report any violations. */
3067
3112
  runRules(context) {
3068
3113
  if (!this.ruleEngine) return null;
3114
+ const span = startSpan(this.tracer, "webdecoy.rules");
3069
3115
  const result = this.ruleEngine.evaluate(context);
3116
+ setAttribute(span, "webdecoy.rules.action", result.action);
3117
+ setAttribute(span, "webdecoy.rules.evaluated", result.results.length);
3118
+ setAttribute(span, "webdecoy.rules.violations", result.violations.length);
3119
+ if (result.rule) setAttribute(span, "webdecoy.rules.deciding", result.rule);
3120
+ endSpan(span);
3070
3121
  if (result.violations.length > 0 && this.violationReporter) {
3071
3122
  this.violationReporter.report(result.violations);
3072
3123
  }
@@ -3134,7 +3185,31 @@ var WebDecoy = class {
3134
3185
  */
3135
3186
  async protect(metadata, options = {}) {
3136
3187
  const edge = readEdgeVerdict(metadata.headers);
3137
- return (await this.decide(metadata, options)).withEdge(edge);
3188
+ const span = startSpan(this.tracer, "webdecoy.protect");
3189
+ try {
3190
+ const decision = (await this.decide(metadata, options)).withEdge(edge);
3191
+ setAttribute(span, "webdecoy.decision.id", decision.id);
3192
+ setAttribute(span, "webdecoy.decision.conclusion", decision.conclusion);
3193
+ setAttribute(span, "webdecoy.decision.allowed", decision.allowed);
3194
+ setAttribute(span, "webdecoy.rules.evaluated", decision.results.length);
3195
+ if (decision.ruleResult?.rule) {
3196
+ setAttribute(span, "webdecoy.decision.rule", decision.ruleResult.rule);
3197
+ }
3198
+ setAttribute(
3199
+ span,
3200
+ "webdecoy.remote",
3201
+ decision.detection.detection_id !== decision.id
3202
+ );
3203
+ if (decision.error) {
3204
+ setAttribute(span, "webdecoy.error", decision.error);
3205
+ }
3206
+ return decision;
3207
+ } catch (error) {
3208
+ recordError(span, error);
3209
+ throw error;
3210
+ } finally {
3211
+ endSpan(span);
3212
+ }
3138
3213
  }
3139
3214
  async decide(metadata, options = {}) {
3140
3215
  const id = newDecisionId();
@@ -3208,7 +3283,7 @@ var WebDecoy = class {
3208
3283
  local_analysis: localAnalysis
3209
3284
  };
3210
3285
  const shouldCallServer = localAnalysis.needs_verification || this.config.enableTLSFingerprinting && metadata.tls_info;
3211
- if (!shouldCallServer && localAnalysis.local_score < 50) {
3286
+ if (!shouldCallServer) {
3212
3287
  return new Decision({
3213
3288
  conclusion: "ALLOW",
3214
3289
  detection: {
@@ -3520,11 +3595,12 @@ function resolveClientIp(options) {
3520
3595
  return normalizeIp(readHeader(headers, "cf-connecting-ip")) ?? peer;
3521
3596
  }
3522
3597
  const chain = forwardedChain(headers);
3598
+ const singleHeaderFallback = () => normalizeIp(readHeader(headers, "x-real-ip")) ?? normalizeIp(readHeader(headers, "x-vercel-forwarded-for")?.split(",").pop()) ?? void 0;
3523
3599
  if (typeof trustProxy === "number") {
3524
3600
  if (!Number.isInteger(trustProxy) || trustProxy < 0) return peer;
3525
3601
  const index = chain.length - trustProxy;
3526
- if (index < 0 || index >= chain.length) return peer;
3527
- return chain[index] ?? peer;
3602
+ if (index < 0 || index >= chain.length) return singleHeaderFallback() ?? peer;
3603
+ return chain[index] ?? singleHeaderFallback() ?? peer;
3528
3604
  }
3529
3605
  const full = peer ? [...chain, peer] : [...chain];
3530
3606
  for (let i = full.length - 1; i >= 0; i--) {
@@ -3532,7 +3608,7 @@ function resolveClientIp(options) {
3532
3608
  if (candidate === null) return peer;
3533
3609
  if (!trustProxy.some((range) => ipInCidr(candidate, range))) return candidate;
3534
3610
  }
3535
- return full[0] ?? void 0 ?? peer;
3611
+ return full[0] ?? void 0 ?? singleHeaderFallback() ?? peer;
3536
3612
  }
3537
3613
 
3538
3614
  // src/client-signals.ts
@@ -3644,41 +3720,72 @@ function clientSignals(config) {
3644
3720
  return new ClientSignalRule(config);
3645
3721
  }
3646
3722
 
3647
- // src/fetch-guard.ts
3648
- function defaultBlocked(_request, decision) {
3649
- const throttled = decision.ruleResult?.action === "THROTTLE";
3650
- const retryAfter = Number(decision.ruleResult?.metadata?.retryAfter ?? 60);
3651
- if (throttled) {
3652
- return new Response(
3653
- JSON.stringify({
3723
+ // src/adapter-core.ts
3724
+ function shouldSkipPath(path, patterns) {
3725
+ if (!patterns || patterns.length === 0) return false;
3726
+ return patterns.some(
3727
+ (pattern) => typeof pattern === "string" ? path === pattern || path.startsWith(pattern) : pattern.test(path)
3728
+ );
3729
+ }
3730
+ function ruleBlockResponse(decision) {
3731
+ const rr = decision.ruleResult;
3732
+ if (decision.allowed || !rr) return null;
3733
+ if (rr.action === "THROTTLE") {
3734
+ const retryAfter = Number(rr.metadata?.retryAfter ?? 60);
3735
+ return {
3736
+ status: 429,
3737
+ headers: { "Retry-After": String(retryAfter) },
3738
+ body: {
3654
3739
  error: "Too Many Requests",
3655
- message: decision.reason ?? "Rate limit exceeded",
3656
- retry_after: retryAfter,
3657
- detection_id: decision.id
3658
- }),
3659
- {
3660
- status: 429,
3661
- headers: {
3662
- "content-type": "application/json",
3663
- "retry-after": String(retryAfter)
3664
- }
3740
+ message: rr.reason || "Rate limit exceeded",
3741
+ retry_after: retryAfter
3665
3742
  }
3666
- );
3743
+ };
3667
3744
  }
3668
- return new Response(
3669
- JSON.stringify({
3670
- error: "Forbidden",
3671
- message: "Access denied by Web Decoy protection",
3672
- detection_id: decision.id
3673
- }),
3674
- { status: 403, headers: { "content-type": "application/json" } }
3675
- );
3745
+ if (rr.action === "DENY") {
3746
+ return {
3747
+ status: 403,
3748
+ headers: {},
3749
+ body: {
3750
+ error: "Forbidden",
3751
+ message: rr.reason || "Access denied by rule",
3752
+ rule: rr.rule
3753
+ }
3754
+ };
3755
+ }
3756
+ return null;
3676
3757
  }
3677
- function matches(pathname, patterns) {
3678
- if (!patterns || patterns.length === 0) return false;
3679
- return patterns.some(
3680
- (p) => typeof p === "string" ? pathname === p || pathname.startsWith(p) : p.test(pathname)
3681
- );
3758
+ function armSiteHoneytoken(sdk, options) {
3759
+ let token = null;
3760
+ void deriveAndArm(sdk, options).then((t) => {
3761
+ token = t;
3762
+ });
3763
+ return () => token;
3764
+ }
3765
+ async function deriveAndArm(sdk, options) {
3766
+ const enabled = (options.enabled ?? true) && Boolean(options.apiKey);
3767
+ if (!enabled) return null;
3768
+ try {
3769
+ const token = await siteHoneytoken({ secret: options.apiKey });
3770
+ sdk.addRule(tripwire({ paths: token.activePaths, includeDefaults: false }));
3771
+ return token;
3772
+ } catch (error) {
3773
+ options.onError?.(error);
3774
+ return null;
3775
+ }
3776
+ }
3777
+
3778
+ // src/fetch-guard.ts
3779
+ function defaultBlocked(_request, decision) {
3780
+ const block = ruleBlockResponse(decision) ?? {
3781
+ status: 403,
3782
+ headers: {},
3783
+ body: { error: "Forbidden", message: "Access denied by Web Decoy protection" }
3784
+ };
3785
+ return new Response(JSON.stringify({ ...block.body, detection_id: decision.id }), {
3786
+ status: block.status,
3787
+ headers: { "content-type": "application/json", ...block.headers }
3788
+ });
3682
3789
  }
3683
3790
  function headerRecord(headers) {
3684
3791
  const out = {};
@@ -3691,14 +3798,10 @@ function createFetchGuard(options = {}) {
3691
3798
  const sdk = new WebDecoy(options);
3692
3799
  const mode = options.mode ?? "monitor";
3693
3800
  const onBlocked = options.onBlocked ?? defaultBlocked;
3694
- let token = null;
3695
- if ((options.honeytoken ?? true) && options.apiKey) {
3696
- void siteHoneytoken({ secret: options.apiKey }).then((t) => {
3697
- token = t;
3698
- sdk.addRule(tripwire({ paths: t.activePaths, includeDefaults: false }));
3699
- }).catch(() => {
3700
- });
3701
- }
3801
+ const getToken = armSiteHoneytoken(sdk, {
3802
+ apiKey: options.apiKey,
3803
+ enabled: options.honeytoken
3804
+ });
3702
3805
  function resolveIP(request, peer) {
3703
3806
  if (options.getIP) return options.getIP(request);
3704
3807
  return resolveClientIp({
@@ -3710,7 +3813,7 @@ function createFetchGuard(options = {}) {
3710
3813
  return {
3711
3814
  sdk,
3712
3815
  skips(pathname) {
3713
- return matches(pathname, options.skipPaths);
3816
+ return shouldSkipPath(pathname, options.skipPaths);
3714
3817
  },
3715
3818
  async check(request, peer) {
3716
3819
  const url = new URL(request.url);
@@ -3732,7 +3835,7 @@ function createFetchGuard(options = {}) {
3732
3835
  return { decision, response: await onBlocked(request, decision) };
3733
3836
  },
3734
3837
  async decorate(response) {
3735
- const current = token;
3838
+ const current = getToken();
3736
3839
  if (!current) return response;
3737
3840
  if (!isInjectableHtml(response.headers.get("content-type"))) return response;
3738
3841
  if (response.bodyUsed) return response;
@@ -5765,6 +5868,7 @@ function createCaptchaEndpoints(options = {}) {
5765
5868
  UpstashRateLimitStore,
5766
5869
  WebBotAuthRule,
5767
5870
  WebDecoy,
5871
+ armSiteHoneytoken,
5768
5872
  attackSignatures,
5769
5873
  botPolicy,
5770
5874
  bots,
@@ -5776,6 +5880,7 @@ function createCaptchaEndpoints(options = {}) {
5776
5880
  createAgentVerifier,
5777
5881
  createCaptchaEndpoints,
5778
5882
  createFetchGuard,
5883
+ deriveAndArm,
5779
5884
  deriveKey,
5780
5885
  filter,
5781
5886
  fromPino,
@@ -5796,6 +5901,8 @@ function createCaptchaEndpoints(options = {}) {
5796
5901
  recommend,
5797
5902
  resolveClientIp,
5798
5903
  resolveSecret,
5904
+ ruleBlockResponse,
5905
+ shouldSkipPath,
5799
5906
  silentLogger,
5800
5907
  siteHoneytoken,
5801
5908
  tripwire,