@webdecoy/node 0.29.0 → 0.30.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 CHANGED
@@ -318,6 +318,10 @@ Mount the endpoints with your adapter (`webdecoyCaptcha` in Express, `webdecoyCa
318
318
 
319
319
  When the browser provides usable scroll samples, `/verify` and `/score` return an `observations` entry with the ID `large-scroll-step-v1`. It summarizes the sample count and largest step in CSS pixels for diagnostics.
320
320
 
321
+ The default `weighted-mean-v1` policy preserves the original SDK behavior. Pass `onScoringComparison` to the server adapter, `Captcha`, or `DetectionEngine` to receive that baseline and the `noisy-or-floors-v1` score and recommendation on the server. Both scores use your configured category weights. The noisy-OR policy applies a decisive score floor to explicit WebDriver declarations and known driver injection signals in enabled categories. It also applies a corroboration floor when measured interaction and known driver findings agree.
322
+
323
+ After validating the comparison in your traffic, pass `scoringPolicy: 'noisy-or-floors-v1'` to enforce it for verification and token issuance. The option is available on `DetectionEngine`, `Captcha`, and every CAPTCHA server adapter; unknown policy names throw instead of silently falling back.
324
+
321
325
  ```ts
322
326
  import express from 'express';
323
327
  import { webdecoyCaptcha } from '@webdecoy/express';
@@ -336,6 +340,15 @@ app.post('/login', async (req, res) => {
336
340
  });
337
341
  ```
338
342
 
343
+ To enforce the noisy-OR policy, replace the adapter registration above with:
344
+
345
+ ```ts
346
+ app.use(webdecoyCaptcha({
347
+ secret: process.env.WEBDECOY_SECRET,
348
+ scoringPolicy: 'noisy-or-floors-v1',
349
+ }));
350
+ ```
351
+
339
352
  `WEBDECOY_SECRET` is just the variable name used here; pass the value as `secret`. Generate one with `openssl rand -hex 32`. Challenge and token stores are in memory by default; for serverless or multi-instance deployments, pass shared `challengeStore` and `tokenStore` implementations.
340
353
 
341
354
  To score signals yourself, use `new DetectionEngine(options).score(signals, context)`.
package/dist/index.d.mts CHANGED
@@ -119,6 +119,8 @@ interface EnvironmentalSignals {
119
119
  [key: string]: unknown;
120
120
  };
121
121
  automationFlags?: {
122
+ /** Explicit browser-declared WebDriver flag from navigator.webdriver. */
123
+ webdriver?: boolean;
122
124
  plugins?: number;
123
125
  languages?: boolean;
124
126
  chrome?: boolean;
@@ -341,9 +343,9 @@ interface ScrollJumpObservation {
341
343
  }
342
344
  /** Final verdict returned by {@link DetectionEngine.score}. */
343
345
  interface Verdict {
344
- /** True when the weighted score is below the success threshold (< 0.5). */
346
+ /** True when the selected policy's score is below the success threshold (< 0.5). */
345
347
  success: boolean;
346
- /** Weighted final score, 0..1. */
348
+ /** Selected policy's final score, 0..1. */
347
349
  score: number;
348
350
  /** Recommended action. */
349
351
  recommendation: Recommendation;
@@ -398,9 +400,27 @@ declare class InMemoryRateLimiter implements RateLimiter {
398
400
  * supplies a {@link PoWOutcome} and the engine emits the matching detections.
399
401
  */
400
402
 
403
+ type DetectionScoringPolicy = 'weighted-mean-v1' | 'noisy-or-floors-v1';
404
+ interface ScoringComparison {
405
+ policy: 'noisy-or-floors-v1';
406
+ current: {
407
+ score: number;
408
+ recommendation: Recommendation;
409
+ };
410
+ candidate: {
411
+ score: number;
412
+ recommendation: Recommendation;
413
+ };
414
+ }
401
415
  interface DetectionEngineOptions {
402
416
  /** Override the per-category weights (defaults to {@link DEFAULT_WEIGHTS}). */
403
417
  weights?: Record<string, number>;
418
+ /**
419
+ * Aggregation policy used for the returned verdict and CAPTCHA token decision.
420
+ * Defaults to `weighted-mean-v1`; opt in to `noisy-or-floors-v1` to enforce
421
+ * the FCaptcha-aligned noisy-OR, decisive-floor, and corroboration-floor policy.
422
+ */
423
+ scoringPolicy?: DetectionScoringPolicy;
404
424
  /**
405
425
  * When true (default), a request with no PoW outcome emits a hard-fail "No PoW
406
426
  * solution provided" detection — matching the reference server. Set false to
@@ -411,18 +431,22 @@ interface DetectionEngineOptions {
411
431
  fingerprintStore?: FingerprintStore;
412
432
  /** Rate limiter for rate-abuse detection (defaults to in-memory). */
413
433
  rateLimiter?: RateLimiter;
434
+ /** Receive a server-side comparison of the two aggregation methods using the same weights. */
435
+ onScoringComparison?: (comparison: ScoringComparison) => void | Promise<void>;
414
436
  }
415
437
  declare class DetectionEngine {
416
438
  private readonly weights;
439
+ private readonly scoringPolicy;
417
440
  private readonly requirePoW;
418
441
  private readonly fingerprintStore;
419
442
  private readonly rateLimiter;
443
+ private readonly onScoringComparison;
420
444
  constructor(options?: DetectionEngineOptions);
421
445
  /** Score `signals` for the given request context and return a verdict. */
422
446
  score(signals: Signals, context: DetectionContext): Verdict;
423
447
  }
424
448
 
425
- /** Score aggregation: per-category confidence-weighted means → weighted total. */
449
+ /** Per-category score aggregation and weighted totals. */
426
450
 
427
451
  /**
428
452
  * Aggregate detections into per-category scores. Each category's score is the
@@ -1646,6 +1670,10 @@ interface CaptchaOptions {
1646
1670
  secret?: string;
1647
1671
  /** Override per-category detection weights. */
1648
1672
  weights?: Record<string, number>;
1673
+ /** Aggregation policy used for scoring, verification, and token issuance. */
1674
+ scoringPolicy?: DetectionEngineOptions['scoringPolicy'];
1675
+ /** Receive score and recommendation comparisons on the server without affecting verification. */
1676
+ onScoringComparison?: DetectionEngineOptions['onScoringComparison'];
1649
1677
  /**
1650
1678
  * Trusted reverse-proxy header names carrying a JA4 fingerprint, matched
1651
1679
  * against the lower-cased request header keys (e.g. `['x-ja4']`).
@@ -1753,4 +1781,4 @@ declare function createCaptchaEndpoints(options?: CaptchaEndpointsOptions): {
1753
1781
  };
1754
1782
  type CaptchaEndpoints = ReturnType<typeof createCaptchaEndpoints>;
1755
1783
 
1756
- 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, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, DirectoryCache, type EnvironmentalSignals, FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, HONEYTOKEN_BASE_PATH, type Honeytoken, type HoneytokenArmingOptions, type HoneytokenLinkProps, type HoneytokenOptions, InMemoryChallengeStore, InMemoryFingerprintStore, InMemoryRateLimiter, InMemoryTokenStore, MemoryClientSignalStore, type MemoryClientSignalStoreOptions, PoWManager, type PoWManagerOptions, type PoWOutcome, type PoWSolution, type PoWVerification, ProtectResult, RateLimitConfig, RateLimitConsume, RateLimitOutcome, RateLimitRule, RateLimitStore, type RateLimiter, type Recommendation, type RobotsTxtOptions, Rule, RuleContext, RuleEngine, RuleEngineResult, RuleResult, type ScoreResult, type ScrollJumpObservation, 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, UpstashRateLimitStore, type UpstashStoreOptions, type Verdict, type VerifyInput, type VerifyResult, type WebBotAuthConfig, WebBotAuthRule, WebDecoy, armSiteHoneytoken, attackSignatures, botPolicy, bots, calculateCategoryScores, calculateFinalScore, clientSignals, createAgentVerifier, createCaptchaEndpoints, deriveAndArm, filter, honeytoken, injectHoneytokenLink, isDatacenterIP, isInjectableHtml, isMobileUA, isTestTriggerUserAgent, parseUserAgent, rateLimit, readClientSession, recommend, resolveSecret, ruleBlockResponse, shouldSkipPath, siteHoneytoken, tripwire, upstashRateLimitStore, webBotAuth };
1784
+ 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, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, type DetectionScoringPolicy, DirectoryCache, type EnvironmentalSignals, FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, HONEYTOKEN_BASE_PATH, type Honeytoken, type HoneytokenArmingOptions, type HoneytokenLinkProps, type HoneytokenOptions, InMemoryChallengeStore, InMemoryFingerprintStore, InMemoryRateLimiter, InMemoryTokenStore, MemoryClientSignalStore, type MemoryClientSignalStoreOptions, PoWManager, type PoWManagerOptions, type PoWOutcome, type PoWSolution, type PoWVerification, ProtectResult, RateLimitConfig, RateLimitConsume, RateLimitOutcome, RateLimitRule, RateLimitStore, type RateLimiter, type Recommendation, type RobotsTxtOptions, Rule, RuleContext, RuleEngine, RuleEngineResult, RuleResult, type ScoreResult, type ScoringComparison, type ScrollJumpObservation, 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, UpstashRateLimitStore, type UpstashStoreOptions, type Verdict, type VerifyInput, type VerifyResult, type WebBotAuthConfig, WebBotAuthRule, WebDecoy, armSiteHoneytoken, attackSignatures, botPolicy, bots, calculateCategoryScores, calculateFinalScore, clientSignals, createAgentVerifier, createCaptchaEndpoints, deriveAndArm, filter, honeytoken, injectHoneytokenLink, isDatacenterIP, isInjectableHtml, isMobileUA, isTestTriggerUserAgent, parseUserAgent, rateLimit, readClientSession, recommend, resolveSecret, ruleBlockResponse, shouldSkipPath, siteHoneytoken, tripwire, upstashRateLimitStore, webBotAuth };
package/dist/index.d.ts CHANGED
@@ -119,6 +119,8 @@ interface EnvironmentalSignals {
119
119
  [key: string]: unknown;
120
120
  };
121
121
  automationFlags?: {
122
+ /** Explicit browser-declared WebDriver flag from navigator.webdriver. */
123
+ webdriver?: boolean;
122
124
  plugins?: number;
123
125
  languages?: boolean;
124
126
  chrome?: boolean;
@@ -341,9 +343,9 @@ interface ScrollJumpObservation {
341
343
  }
342
344
  /** Final verdict returned by {@link DetectionEngine.score}. */
343
345
  interface Verdict {
344
- /** True when the weighted score is below the success threshold (< 0.5). */
346
+ /** True when the selected policy's score is below the success threshold (< 0.5). */
345
347
  success: boolean;
346
- /** Weighted final score, 0..1. */
348
+ /** Selected policy's final score, 0..1. */
347
349
  score: number;
348
350
  /** Recommended action. */
349
351
  recommendation: Recommendation;
@@ -398,9 +400,27 @@ declare class InMemoryRateLimiter implements RateLimiter {
398
400
  * supplies a {@link PoWOutcome} and the engine emits the matching detections.
399
401
  */
400
402
 
403
+ type DetectionScoringPolicy = 'weighted-mean-v1' | 'noisy-or-floors-v1';
404
+ interface ScoringComparison {
405
+ policy: 'noisy-or-floors-v1';
406
+ current: {
407
+ score: number;
408
+ recommendation: Recommendation;
409
+ };
410
+ candidate: {
411
+ score: number;
412
+ recommendation: Recommendation;
413
+ };
414
+ }
401
415
  interface DetectionEngineOptions {
402
416
  /** Override the per-category weights (defaults to {@link DEFAULT_WEIGHTS}). */
403
417
  weights?: Record<string, number>;
418
+ /**
419
+ * Aggregation policy used for the returned verdict and CAPTCHA token decision.
420
+ * Defaults to `weighted-mean-v1`; opt in to `noisy-or-floors-v1` to enforce
421
+ * the FCaptcha-aligned noisy-OR, decisive-floor, and corroboration-floor policy.
422
+ */
423
+ scoringPolicy?: DetectionScoringPolicy;
404
424
  /**
405
425
  * When true (default), a request with no PoW outcome emits a hard-fail "No PoW
406
426
  * solution provided" detection — matching the reference server. Set false to
@@ -411,18 +431,22 @@ interface DetectionEngineOptions {
411
431
  fingerprintStore?: FingerprintStore;
412
432
  /** Rate limiter for rate-abuse detection (defaults to in-memory). */
413
433
  rateLimiter?: RateLimiter;
434
+ /** Receive a server-side comparison of the two aggregation methods using the same weights. */
435
+ onScoringComparison?: (comparison: ScoringComparison) => void | Promise<void>;
414
436
  }
415
437
  declare class DetectionEngine {
416
438
  private readonly weights;
439
+ private readonly scoringPolicy;
417
440
  private readonly requirePoW;
418
441
  private readonly fingerprintStore;
419
442
  private readonly rateLimiter;
443
+ private readonly onScoringComparison;
420
444
  constructor(options?: DetectionEngineOptions);
421
445
  /** Score `signals` for the given request context and return a verdict. */
422
446
  score(signals: Signals, context: DetectionContext): Verdict;
423
447
  }
424
448
 
425
- /** Score aggregation: per-category confidence-weighted means → weighted total. */
449
+ /** Per-category score aggregation and weighted totals. */
426
450
 
427
451
  /**
428
452
  * Aggregate detections into per-category scores. Each category's score is the
@@ -1646,6 +1670,10 @@ interface CaptchaOptions {
1646
1670
  secret?: string;
1647
1671
  /** Override per-category detection weights. */
1648
1672
  weights?: Record<string, number>;
1673
+ /** Aggregation policy used for scoring, verification, and token issuance. */
1674
+ scoringPolicy?: DetectionEngineOptions['scoringPolicy'];
1675
+ /** Receive score and recommendation comparisons on the server without affecting verification. */
1676
+ onScoringComparison?: DetectionEngineOptions['onScoringComparison'];
1649
1677
  /**
1650
1678
  * Trusted reverse-proxy header names carrying a JA4 fingerprint, matched
1651
1679
  * against the lower-cased request header keys (e.g. `['x-ja4']`).
@@ -1753,4 +1781,4 @@ declare function createCaptchaEndpoints(options?: CaptchaEndpointsOptions): {
1753
1781
  };
1754
1782
  type CaptchaEndpoints = ReturnType<typeof createCaptchaEndpoints>;
1755
1783
 
1756
- 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, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, DirectoryCache, type EnvironmentalSignals, FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, HONEYTOKEN_BASE_PATH, type Honeytoken, type HoneytokenArmingOptions, type HoneytokenLinkProps, type HoneytokenOptions, InMemoryChallengeStore, InMemoryFingerprintStore, InMemoryRateLimiter, InMemoryTokenStore, MemoryClientSignalStore, type MemoryClientSignalStoreOptions, PoWManager, type PoWManagerOptions, type PoWOutcome, type PoWSolution, type PoWVerification, ProtectResult, RateLimitConfig, RateLimitConsume, RateLimitOutcome, RateLimitRule, RateLimitStore, type RateLimiter, type Recommendation, type RobotsTxtOptions, Rule, RuleContext, RuleEngine, RuleEngineResult, RuleResult, type ScoreResult, type ScrollJumpObservation, 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, UpstashRateLimitStore, type UpstashStoreOptions, type Verdict, type VerifyInput, type VerifyResult, type WebBotAuthConfig, WebBotAuthRule, WebDecoy, armSiteHoneytoken, attackSignatures, botPolicy, bots, calculateCategoryScores, calculateFinalScore, clientSignals, createAgentVerifier, createCaptchaEndpoints, deriveAndArm, filter, honeytoken, injectHoneytokenLink, isDatacenterIP, isInjectableHtml, isMobileUA, isTestTriggerUserAgent, parseUserAgent, rateLimit, readClientSession, recommend, resolveSecret, ruleBlockResponse, shouldSkipPath, siteHoneytoken, tripwire, upstashRateLimitStore, webBotAuth };
1784
+ 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, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, type DetectionScoringPolicy, DirectoryCache, type EnvironmentalSignals, FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, HONEYTOKEN_BASE_PATH, type Honeytoken, type HoneytokenArmingOptions, type HoneytokenLinkProps, type HoneytokenOptions, InMemoryChallengeStore, InMemoryFingerprintStore, InMemoryRateLimiter, InMemoryTokenStore, MemoryClientSignalStore, type MemoryClientSignalStoreOptions, PoWManager, type PoWManagerOptions, type PoWOutcome, type PoWSolution, type PoWVerification, ProtectResult, RateLimitConfig, RateLimitConsume, RateLimitOutcome, RateLimitRule, RateLimitStore, type RateLimiter, type Recommendation, type RobotsTxtOptions, Rule, RuleContext, RuleEngine, RuleEngineResult, RuleResult, type ScoreResult, type ScoringComparison, type ScrollJumpObservation, 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, UpstashRateLimitStore, type UpstashStoreOptions, type Verdict, type VerifyInput, type VerifyResult, type WebBotAuthConfig, WebBotAuthRule, WebDecoy, armSiteHoneytoken, attackSignatures, botPolicy, bots, calculateCategoryScores, calculateFinalScore, clientSignals, createAgentVerifier, createCaptchaEndpoints, deriveAndArm, filter, honeytoken, injectHoneytokenLink, isDatacenterIP, isInjectableHtml, isMobileUA, isTestTriggerUserAgent, parseUserAgent, rateLimit, readClientSession, recommend, resolveSecret, ruleBlockResponse, shouldSkipPath, siteHoneytoken, tripwire, upstashRateLimitStore, webBotAuth };
package/dist/index.js CHANGED
@@ -6117,7 +6117,67 @@ var InMemoryRateLimiter2 = class {
6117
6117
  }
6118
6118
  };
6119
6119
 
6120
+ // src/detection/detectors/cdp.ts
6121
+ var HIGH_CONFIDENCE_SIGNALS = ["chromedriver_cdc", "puppeteer_eval", "cdp_script_injection"];
6122
+ var CORROBORATING_DRIVER_SIGNALS = /* @__PURE__ */ new Set([
6123
+ ...HIGH_CONFIDENCE_SIGNALS,
6124
+ "selenium_evaluate",
6125
+ "selenium_driver_evaluate",
6126
+ "selenium_unwrapped",
6127
+ "selenium_driver_unwrapped",
6128
+ "selenium_direct",
6129
+ "firefox_driver",
6130
+ "firefox_driver_unwrapped"
6131
+ ]);
6132
+ function hasDriverInjection(signals) {
6133
+ return signals.some((signal) => HIGH_CONFIDENCE_SIGNALS.includes(signal));
6134
+ }
6135
+ function detectCDP(signals, corroborating) {
6136
+ const detections = [];
6137
+ const cdp = signals.environmental?.cdp ?? {};
6138
+ if (!cdp.detected) return detections;
6139
+ const signalList = cdp.signals ?? [];
6140
+ const signalCount = signalList.length;
6141
+ if (hasDriverInjection(signalList)) {
6142
+ detections.push({
6143
+ category: "cdp",
6144
+ score: 0.9,
6145
+ confidence: 0.95,
6146
+ reason: `CDP automation detected: ${signalList.join(", ")}`
6147
+ });
6148
+ } else if (signalCount >= 2) {
6149
+ detections.push({
6150
+ category: "cdp",
6151
+ score: 0.8,
6152
+ confidence: 0.85,
6153
+ reason: `Multiple CDP indicators: ${signalList.join(", ")}`
6154
+ });
6155
+ } else if (signalCount === 1) {
6156
+ detections.push({
6157
+ category: "cdp",
6158
+ score: 0.6,
6159
+ confidence: 0.7,
6160
+ reason: `CDP indicator: ${signalList.join(", ")}`
6161
+ });
6162
+ }
6163
+ if (corroborating && signalList.every((signal) => CORROBORATING_DRIVER_SIGNALS.has(signal))) {
6164
+ corroborating.push(...detections);
6165
+ }
6166
+ return detections;
6167
+ }
6168
+
6120
6169
  // src/detection/scoring.ts
6170
+ function applyDecisiveScoreFloor(score, env, weights) {
6171
+ const declaresWebDriver = (weights.headless ?? 0) > 0 && env?.webdriver === true && env.automationFlags?.webdriver === true;
6172
+ const hasInjectedDriver = (weights.cdp ?? 0) > 0 && env?.cdp?.detected === true && hasDriverInjection(env.cdp.signals ?? []);
6173
+ return declaresWebDriver || hasInjectedDriver ? Math.max(0.9, score) : score;
6174
+ }
6175
+ function applyCorroborationScoreFloor(score, detections, weights) {
6176
+ if (score >= 0.6 || detections.length < 2) return score;
6177
+ const support = calculateNoisyOrCategoryScores(detections, weights);
6178
+ const agrees = (category) => (weights[category] ?? 0) > 0 && (support[category] ?? 0) >= 0.4 - 1e-9;
6179
+ return agrees("cdp") && (agrees("vision_ai") || agrees("behavioral")) ? 0.6 : score;
6180
+ }
6121
6181
  function calculateCategoryScores(detections, weights) {
6122
6182
  var _a;
6123
6183
  const categoryData = {};
@@ -6139,6 +6199,19 @@ function calculateCategoryScores(detections, weights) {
6139
6199
  }
6140
6200
  return result;
6141
6201
  }
6202
+ function calculateNoisyOrCategoryScores(detections, weights) {
6203
+ const remaining = /* @__PURE__ */ new Map();
6204
+ for (const { category, score, confidence } of detections) {
6205
+ if (!Number.isFinite(score) || !Number.isFinite(confidence) || score <= 0 || confidence <= 0) {
6206
+ continue;
6207
+ }
6208
+ const evidence = Math.min(1, score * confidence);
6209
+ remaining.set(category, (remaining.get(category) ?? 1) * (1 - evidence));
6210
+ }
6211
+ return Object.fromEntries(
6212
+ Object.keys(weights).map((category) => [category, 1 - (remaining.get(category) ?? 1)])
6213
+ );
6214
+ }
6142
6215
  function calculateFinalScore(categoryScores, weights) {
6143
6216
  let total = 0;
6144
6217
  for (const [cat, weight] of Object.entries(weights)) {
@@ -6152,6 +6225,12 @@ function recommend(finalScore) {
6152
6225
  return "block";
6153
6226
  }
6154
6227
 
6228
+ // src/detection/detectors/corroborating-detection.ts
6229
+ function addCorroboratingDetection(detections, corroborating, detection) {
6230
+ detections.push(detection);
6231
+ corroborating?.push(detection);
6232
+ }
6233
+
6155
6234
  // src/detection/detectors/keyboard-input.ts
6156
6235
  var MIN_KEY_HOLD_SAMPLES = 3;
6157
6236
  var MAX_KEY_HOLD_SAMPLES = 200;
@@ -6186,14 +6265,14 @@ function isTouchModality(behavioral) {
6186
6265
  return touchEvents >= 3 || hasTouchSample && behavioral.pointerHasNonMouseType === true;
6187
6266
  }
6188
6267
  function hasHumanMovementMarkers(behavioral) {
6189
- const tremor = behavioral.microTremorScore ?? 0;
6268
+ const tremor = behavioral.microTremorScore ?? 0.5;
6190
6269
  const corrections = behavioral.overshootCorrections ?? 0;
6191
6270
  const changes = behavioral.directionChanges ?? 0;
6192
6271
  return tremor >= 0.5 && (corrections >= 1 || changes >= 10);
6193
6272
  }
6194
6273
 
6195
6274
  // src/detection/detectors/vision-ai.ts
6196
- function detectVisionAI(signals, widgetInteraction = true) {
6275
+ function detectVisionAI(signals, widgetInteraction = true, corroborating) {
6197
6276
  const detections = [];
6198
6277
  const b = signals.behavioral ?? {};
6199
6278
  const t = signals.temporal ?? {};
@@ -6241,7 +6320,7 @@ function detectVisionAI(signals, widgetInteraction = true) {
6241
6320
  }
6242
6321
  const microTremor = b.microTremorScore ?? 0.5;
6243
6322
  if (usesMouse && totalPoints >= 5 && microTremor < 0.15) {
6244
- detections.push({
6323
+ addCorroboratingDetection(detections, corroborating, {
6245
6324
  category: "vision_ai",
6246
6325
  score: 0.7,
6247
6326
  confidence: 0.6,
@@ -6249,7 +6328,7 @@ function detectVisionAI(signals, widgetInteraction = true) {
6249
6328
  });
6250
6329
  }
6251
6330
  if (widgetInteraction && usesMouse && approachPts >= 5 && (b.approachDirectness ?? 0) > 0.95 && !hasHumanMovementMarkers(b)) {
6252
- detections.push({
6331
+ addCorroboratingDetection(detections, corroborating, {
6253
6332
  category: "vision_ai",
6254
6333
  score: 0.5,
6255
6334
  confidence: 0.5,
@@ -6258,7 +6337,7 @@ function detectVisionAI(signals, widgetInteraction = true) {
6258
6337
  }
6259
6338
  const exploration = b.explorationRatio ?? 0.3;
6260
6339
  if (widgetInteraction && exploration < 0.05 && trajectory > 50) {
6261
- detections.push({
6340
+ addCorroboratingDetection(detections, corroborating, {
6262
6341
  category: "vision_ai",
6263
6342
  score: 0.4,
6264
6343
  confidence: 0.4,
@@ -6406,42 +6485,8 @@ function detectAutomation(signals) {
6406
6485
  return detections;
6407
6486
  }
6408
6487
 
6409
- // src/detection/detectors/cdp.ts
6410
- var HIGH_CONFIDENCE_SIGNALS = ["chromedriver_cdc", "puppeteer_eval", "cdp_script_injection"];
6411
- function detectCDP(signals) {
6412
- const detections = [];
6413
- const cdp = signals.environmental?.cdp ?? {};
6414
- if (!cdp.detected) return detections;
6415
- const signalList = cdp.signals ?? [];
6416
- const signalCount = signalList.length;
6417
- const hasHighConf = signalList.some((s) => HIGH_CONFIDENCE_SIGNALS.includes(s));
6418
- if (hasHighConf) {
6419
- detections.push({
6420
- category: "cdp",
6421
- score: 0.9,
6422
- confidence: 0.95,
6423
- reason: `CDP automation detected: ${signalList.join(", ")}`
6424
- });
6425
- } else if (signalCount >= 2) {
6426
- detections.push({
6427
- category: "cdp",
6428
- score: 0.8,
6429
- confidence: 0.85,
6430
- reason: `Multiple CDP indicators: ${signalList.join(", ")}`
6431
- });
6432
- } else if (signalCount === 1) {
6433
- detections.push({
6434
- category: "cdp",
6435
- score: 0.6,
6436
- confidence: 0.7,
6437
- reason: `CDP indicator: ${signalList.join(", ")}`
6438
- });
6439
- }
6440
- return detections;
6441
- }
6442
-
6443
6488
  // src/detection/detectors/behavioral.ts
6444
- function detectBehavioral(signals, widgetInteraction = true) {
6489
+ function detectBehavioral(signals, widgetInteraction = true, corroborating) {
6445
6490
  const detections = [];
6446
6491
  const b = signals.behavioral ?? {};
6447
6492
  const t = signals.temporal ?? {};
@@ -6451,7 +6496,7 @@ function detectBehavioral(signals, widgetInteraction = true) {
6451
6496
  const keyboard = classifyKeyboardInput(signals);
6452
6497
  const humanMovement = hasHumanMovementMarkers(b);
6453
6498
  if (keyboard === "short-key-holds" && !isTouchUser) {
6454
- detections.push({
6499
+ addCorroboratingDetection(detections, corroborating, {
6455
6500
  category: "behavioral",
6456
6501
  score: 0.8,
6457
6502
  confidence: 0.9,
@@ -6474,7 +6519,7 @@ function detectBehavioral(signals, widgetInteraction = true) {
6474
6519
  }
6475
6520
  const velVar = b.velocityVariance ?? 1;
6476
6521
  if (velVar < 0.02 && trajectory > 50 && !humanMovement) {
6477
- detections.push({
6522
+ addCorroboratingDetection(detections, corroborating, {
6478
6523
  category: "behavioral",
6479
6524
  score: 0.6,
6480
6525
  confidence: 0.6,
@@ -6533,7 +6578,7 @@ function detectBehavioral(signals, widgetInteraction = true) {
6533
6578
  }
6534
6579
  const straight = b.straightLineRatio ?? 0;
6535
6580
  if (straight > 0.8 && trajectory > 100) {
6536
- detections.push({
6581
+ addCorroboratingDetection(detections, corroborating, {
6537
6582
  category: "behavioral",
6538
6583
  score: 0.5,
6539
6584
  confidence: 0.5,
@@ -6542,7 +6587,7 @@ function detectBehavioral(signals, widgetInteraction = true) {
6542
6587
  }
6543
6588
  const dirChanges = b.directionChanges ?? 10;
6544
6589
  if (totalPoints > 50 && dirChanges < 3) {
6545
- detections.push({
6590
+ addCorroboratingDetection(detections, corroborating, {
6546
6591
  category: "behavioral",
6547
6592
  score: 0.4,
6548
6593
  confidence: 0.4,
@@ -7504,16 +7549,24 @@ function analyzeAdvancedSignals(signals) {
7504
7549
  // src/detection/engine.ts
7505
7550
  var DetectionEngine = class {
7506
7551
  constructor(options = {}) {
7552
+ if (options.scoringPolicy !== void 0 && options.scoringPolicy !== "weighted-mean-v1" && options.scoringPolicy !== "noisy-or-floors-v1") {
7553
+ throw new TypeError("Unknown detection scoring policy: " + String(options.scoringPolicy));
7554
+ }
7507
7555
  this.weights = options.weights ?? DEFAULT_WEIGHTS;
7556
+ this.scoringPolicy = options.scoringPolicy ?? "weighted-mean-v1";
7508
7557
  this.requirePoW = options.requirePoW ?? true;
7509
7558
  this.fingerprintStore = options.fingerprintStore ?? new InMemoryFingerprintStore();
7510
7559
  this.rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter2();
7560
+ this.onScoringComparison = options.onScoringComparison;
7511
7561
  }
7512
7562
  /** Score `signals` for the given request context and return a verdict. */
7513
7563
  score(signals, context) {
7514
7564
  const { ip, siteKey, userAgent } = context;
7515
7565
  const headers = context.headers ?? {};
7516
7566
  const detections = [];
7567
+ const onScoringComparison = this.onScoringComparison;
7568
+ const useCandidate = this.scoringPolicy === "noisy-or-floors-v1";
7569
+ const corroborating = onScoringComparison || useCandidate ? [] : void 0;
7517
7570
  if (context.extraDetections) detections.push(...context.extraDetections);
7518
7571
  const pow = context.pow;
7519
7572
  if (pow && pow.provided) {
@@ -7554,11 +7607,11 @@ var DetectionEngine = class {
7554
7607
  }
7555
7608
  const widgetInteraction = context.widgetInteraction !== false;
7556
7609
  detections.push(
7557
- ...detectVisionAI(signals, widgetInteraction),
7610
+ ...detectVisionAI(signals, widgetInteraction, corroborating),
7558
7611
  ...detectHeadless(signals, userAgent),
7559
7612
  ...detectAutomation(signals),
7560
- ...detectCDP(signals),
7561
- ...detectBehavioral(signals, widgetInteraction),
7613
+ ...detectCDP(signals, corroborating),
7614
+ ...detectBehavioral(signals, widgetInteraction, corroborating),
7562
7615
  ...detectTouchAuthenticity(signals, userAgent),
7563
7616
  ...detectSensorEntropy(signals, userAgent),
7564
7617
  ...detectTouchKinematics(signals),
@@ -7586,13 +7639,42 @@ var DetectionEngine = class {
7586
7639
  detections.push(...analyzeFormInteraction(signals.formAnalysis, signals.behavioral));
7587
7640
  }
7588
7641
  detections.push(...analyzeAdvancedSignals(signals));
7589
- const categoryScores = calculateCategoryScores(detections, this.weights);
7590
- const score = calculateFinalScore(categoryScores, this.weights);
7642
+ const currentCategoryScores = calculateCategoryScores(detections, this.weights);
7643
+ const currentScore = calculateFinalScore(currentCategoryScores, this.weights);
7644
+ const currentRecommendation = recommend(currentScore);
7591
7645
  const scrollObservation = observeScrollJump(signals.behavioral);
7646
+ let candidateCategoryScores;
7647
+ let candidateScore;
7648
+ let candidateRecommendation;
7649
+ if (corroborating) {
7650
+ candidateCategoryScores = calculateNoisyOrCategoryScores(detections, this.weights);
7651
+ const decisiveScore = applyDecisiveScoreFloor(
7652
+ calculateFinalScore(candidateCategoryScores, this.weights),
7653
+ signals.environmental,
7654
+ this.weights
7655
+ );
7656
+ candidateScore = applyCorroborationScoreFloor(decisiveScore, corroborating, this.weights);
7657
+ candidateRecommendation = recommend(candidateScore);
7658
+ }
7659
+ if (onScoringComparison && candidateScore !== void 0 && candidateRecommendation !== void 0) {
7660
+ try {
7661
+ const pending = onScoringComparison({
7662
+ policy: "noisy-or-floors-v1",
7663
+ current: { score: currentScore, recommendation: currentRecommendation },
7664
+ candidate: { score: candidateScore, recommendation: candidateRecommendation }
7665
+ });
7666
+ void pending?.catch(() => {
7667
+ });
7668
+ } catch {
7669
+ }
7670
+ }
7671
+ const categoryScores = useCandidate ? candidateCategoryScores : currentCategoryScores;
7672
+ const score = useCandidate ? candidateScore : currentScore;
7673
+ const recommendation = useCandidate ? candidateRecommendation : currentRecommendation;
7592
7674
  return {
7593
7675
  success: score < 0.5,
7594
7676
  score,
7595
- recommendation: recommend(score),
7677
+ recommendation,
7596
7678
  categoryScores,
7597
7679
  detections,
7598
7680
  ...scrollObservation ? { observations: [scrollObservation] } : {},
@@ -7803,9 +7885,11 @@ var Captcha = class {
7803
7885
  const fingerprintStore = options.fingerprintStore ?? new InMemoryFingerprintStore();
7804
7886
  this.engine = new DetectionEngine({
7805
7887
  weights: options.weights,
7888
+ scoringPolicy: options.scoringPolicy,
7806
7889
  requirePoW: true,
7807
7890
  fingerprintStore,
7808
- rateLimiter
7891
+ rateLimiter,
7892
+ onScoringComparison: options.onScoringComparison
7809
7893
  });
7810
7894
  this.pow = new PoWManager({ secret, store: options.challengeStore, rateLimiter });
7811
7895
  this.tokens = new TokenManager({ secret, store: options.tokenStore });
package/dist/index.mjs CHANGED
@@ -368,7 +368,67 @@ var InMemoryRateLimiter = class {
368
368
  }
369
369
  };
370
370
 
371
+ // src/detection/detectors/cdp.ts
372
+ var HIGH_CONFIDENCE_SIGNALS = ["chromedriver_cdc", "puppeteer_eval", "cdp_script_injection"];
373
+ var CORROBORATING_DRIVER_SIGNALS = /* @__PURE__ */ new Set([
374
+ ...HIGH_CONFIDENCE_SIGNALS,
375
+ "selenium_evaluate",
376
+ "selenium_driver_evaluate",
377
+ "selenium_unwrapped",
378
+ "selenium_driver_unwrapped",
379
+ "selenium_direct",
380
+ "firefox_driver",
381
+ "firefox_driver_unwrapped"
382
+ ]);
383
+ function hasDriverInjection(signals) {
384
+ return signals.some((signal) => HIGH_CONFIDENCE_SIGNALS.includes(signal));
385
+ }
386
+ function detectCDP(signals, corroborating) {
387
+ const detections = [];
388
+ const cdp = signals.environmental?.cdp ?? {};
389
+ if (!cdp.detected) return detections;
390
+ const signalList = cdp.signals ?? [];
391
+ const signalCount = signalList.length;
392
+ if (hasDriverInjection(signalList)) {
393
+ detections.push({
394
+ category: "cdp",
395
+ score: 0.9,
396
+ confidence: 0.95,
397
+ reason: `CDP automation detected: ${signalList.join(", ")}`
398
+ });
399
+ } else if (signalCount >= 2) {
400
+ detections.push({
401
+ category: "cdp",
402
+ score: 0.8,
403
+ confidence: 0.85,
404
+ reason: `Multiple CDP indicators: ${signalList.join(", ")}`
405
+ });
406
+ } else if (signalCount === 1) {
407
+ detections.push({
408
+ category: "cdp",
409
+ score: 0.6,
410
+ confidence: 0.7,
411
+ reason: `CDP indicator: ${signalList.join(", ")}`
412
+ });
413
+ }
414
+ if (corroborating && signalList.every((signal) => CORROBORATING_DRIVER_SIGNALS.has(signal))) {
415
+ corroborating.push(...detections);
416
+ }
417
+ return detections;
418
+ }
419
+
371
420
  // src/detection/scoring.ts
421
+ function applyDecisiveScoreFloor(score, env, weights) {
422
+ const declaresWebDriver = (weights.headless ?? 0) > 0 && env?.webdriver === true && env.automationFlags?.webdriver === true;
423
+ const hasInjectedDriver = (weights.cdp ?? 0) > 0 && env?.cdp?.detected === true && hasDriverInjection(env.cdp.signals ?? []);
424
+ return declaresWebDriver || hasInjectedDriver ? Math.max(0.9, score) : score;
425
+ }
426
+ function applyCorroborationScoreFloor(score, detections, weights) {
427
+ if (score >= 0.6 || detections.length < 2) return score;
428
+ const support = calculateNoisyOrCategoryScores(detections, weights);
429
+ const agrees = (category) => (weights[category] ?? 0) > 0 && (support[category] ?? 0) >= 0.4 - 1e-9;
430
+ return agrees("cdp") && (agrees("vision_ai") || agrees("behavioral")) ? 0.6 : score;
431
+ }
372
432
  function calculateCategoryScores(detections, weights) {
373
433
  var _a;
374
434
  const categoryData = {};
@@ -390,6 +450,19 @@ function calculateCategoryScores(detections, weights) {
390
450
  }
391
451
  return result;
392
452
  }
453
+ function calculateNoisyOrCategoryScores(detections, weights) {
454
+ const remaining = /* @__PURE__ */ new Map();
455
+ for (const { category, score, confidence } of detections) {
456
+ if (!Number.isFinite(score) || !Number.isFinite(confidence) || score <= 0 || confidence <= 0) {
457
+ continue;
458
+ }
459
+ const evidence = Math.min(1, score * confidence);
460
+ remaining.set(category, (remaining.get(category) ?? 1) * (1 - evidence));
461
+ }
462
+ return Object.fromEntries(
463
+ Object.keys(weights).map((category) => [category, 1 - (remaining.get(category) ?? 1)])
464
+ );
465
+ }
393
466
  function calculateFinalScore(categoryScores, weights) {
394
467
  let total = 0;
395
468
  for (const [cat, weight] of Object.entries(weights)) {
@@ -403,6 +476,12 @@ function recommend(finalScore) {
403
476
  return "block";
404
477
  }
405
478
 
479
+ // src/detection/detectors/corroborating-detection.ts
480
+ function addCorroboratingDetection(detections, corroborating, detection) {
481
+ detections.push(detection);
482
+ corroborating?.push(detection);
483
+ }
484
+
406
485
  // src/detection/detectors/keyboard-input.ts
407
486
  var MIN_KEY_HOLD_SAMPLES = 3;
408
487
  var MAX_KEY_HOLD_SAMPLES = 200;
@@ -437,14 +516,14 @@ function isTouchModality(behavioral) {
437
516
  return touchEvents >= 3 || hasTouchSample && behavioral.pointerHasNonMouseType === true;
438
517
  }
439
518
  function hasHumanMovementMarkers(behavioral) {
440
- const tremor = behavioral.microTremorScore ?? 0;
519
+ const tremor = behavioral.microTremorScore ?? 0.5;
441
520
  const corrections = behavioral.overshootCorrections ?? 0;
442
521
  const changes = behavioral.directionChanges ?? 0;
443
522
  return tremor >= 0.5 && (corrections >= 1 || changes >= 10);
444
523
  }
445
524
 
446
525
  // src/detection/detectors/vision-ai.ts
447
- function detectVisionAI(signals, widgetInteraction = true) {
526
+ function detectVisionAI(signals, widgetInteraction = true, corroborating) {
448
527
  const detections = [];
449
528
  const b = signals.behavioral ?? {};
450
529
  const t = signals.temporal ?? {};
@@ -492,7 +571,7 @@ function detectVisionAI(signals, widgetInteraction = true) {
492
571
  }
493
572
  const microTremor = b.microTremorScore ?? 0.5;
494
573
  if (usesMouse && totalPoints >= 5 && microTremor < 0.15) {
495
- detections.push({
574
+ addCorroboratingDetection(detections, corroborating, {
496
575
  category: "vision_ai",
497
576
  score: 0.7,
498
577
  confidence: 0.6,
@@ -500,7 +579,7 @@ function detectVisionAI(signals, widgetInteraction = true) {
500
579
  });
501
580
  }
502
581
  if (widgetInteraction && usesMouse && approachPts >= 5 && (b.approachDirectness ?? 0) > 0.95 && !hasHumanMovementMarkers(b)) {
503
- detections.push({
582
+ addCorroboratingDetection(detections, corroborating, {
504
583
  category: "vision_ai",
505
584
  score: 0.5,
506
585
  confidence: 0.5,
@@ -509,7 +588,7 @@ function detectVisionAI(signals, widgetInteraction = true) {
509
588
  }
510
589
  const exploration = b.explorationRatio ?? 0.3;
511
590
  if (widgetInteraction && exploration < 0.05 && trajectory > 50) {
512
- detections.push({
591
+ addCorroboratingDetection(detections, corroborating, {
513
592
  category: "vision_ai",
514
593
  score: 0.4,
515
594
  confidence: 0.4,
@@ -657,42 +736,8 @@ function detectAutomation(signals) {
657
736
  return detections;
658
737
  }
659
738
 
660
- // src/detection/detectors/cdp.ts
661
- var HIGH_CONFIDENCE_SIGNALS = ["chromedriver_cdc", "puppeteer_eval", "cdp_script_injection"];
662
- function detectCDP(signals) {
663
- const detections = [];
664
- const cdp = signals.environmental?.cdp ?? {};
665
- if (!cdp.detected) return detections;
666
- const signalList = cdp.signals ?? [];
667
- const signalCount = signalList.length;
668
- const hasHighConf = signalList.some((s) => HIGH_CONFIDENCE_SIGNALS.includes(s));
669
- if (hasHighConf) {
670
- detections.push({
671
- category: "cdp",
672
- score: 0.9,
673
- confidence: 0.95,
674
- reason: `CDP automation detected: ${signalList.join(", ")}`
675
- });
676
- } else if (signalCount >= 2) {
677
- detections.push({
678
- category: "cdp",
679
- score: 0.8,
680
- confidence: 0.85,
681
- reason: `Multiple CDP indicators: ${signalList.join(", ")}`
682
- });
683
- } else if (signalCount === 1) {
684
- detections.push({
685
- category: "cdp",
686
- score: 0.6,
687
- confidence: 0.7,
688
- reason: `CDP indicator: ${signalList.join(", ")}`
689
- });
690
- }
691
- return detections;
692
- }
693
-
694
739
  // src/detection/detectors/behavioral.ts
695
- function detectBehavioral(signals, widgetInteraction = true) {
740
+ function detectBehavioral(signals, widgetInteraction = true, corroborating) {
696
741
  const detections = [];
697
742
  const b = signals.behavioral ?? {};
698
743
  const t = signals.temporal ?? {};
@@ -702,7 +747,7 @@ function detectBehavioral(signals, widgetInteraction = true) {
702
747
  const keyboard = classifyKeyboardInput(signals);
703
748
  const humanMovement = hasHumanMovementMarkers(b);
704
749
  if (keyboard === "short-key-holds" && !isTouchUser) {
705
- detections.push({
750
+ addCorroboratingDetection(detections, corroborating, {
706
751
  category: "behavioral",
707
752
  score: 0.8,
708
753
  confidence: 0.9,
@@ -725,7 +770,7 @@ function detectBehavioral(signals, widgetInteraction = true) {
725
770
  }
726
771
  const velVar = b.velocityVariance ?? 1;
727
772
  if (velVar < 0.02 && trajectory > 50 && !humanMovement) {
728
- detections.push({
773
+ addCorroboratingDetection(detections, corroborating, {
729
774
  category: "behavioral",
730
775
  score: 0.6,
731
776
  confidence: 0.6,
@@ -784,7 +829,7 @@ function detectBehavioral(signals, widgetInteraction = true) {
784
829
  }
785
830
  const straight = b.straightLineRatio ?? 0;
786
831
  if (straight > 0.8 && trajectory > 100) {
787
- detections.push({
832
+ addCorroboratingDetection(detections, corroborating, {
788
833
  category: "behavioral",
789
834
  score: 0.5,
790
835
  confidence: 0.5,
@@ -793,7 +838,7 @@ function detectBehavioral(signals, widgetInteraction = true) {
793
838
  }
794
839
  const dirChanges = b.directionChanges ?? 10;
795
840
  if (totalPoints > 50 && dirChanges < 3) {
796
- detections.push({
841
+ addCorroboratingDetection(detections, corroborating, {
797
842
  category: "behavioral",
798
843
  score: 0.4,
799
844
  confidence: 0.4,
@@ -1755,16 +1800,24 @@ function analyzeAdvancedSignals(signals) {
1755
1800
  // src/detection/engine.ts
1756
1801
  var DetectionEngine = class {
1757
1802
  constructor(options = {}) {
1803
+ if (options.scoringPolicy !== void 0 && options.scoringPolicy !== "weighted-mean-v1" && options.scoringPolicy !== "noisy-or-floors-v1") {
1804
+ throw new TypeError("Unknown detection scoring policy: " + String(options.scoringPolicy));
1805
+ }
1758
1806
  this.weights = options.weights ?? DEFAULT_WEIGHTS;
1807
+ this.scoringPolicy = options.scoringPolicy ?? "weighted-mean-v1";
1759
1808
  this.requirePoW = options.requirePoW ?? true;
1760
1809
  this.fingerprintStore = options.fingerprintStore ?? new InMemoryFingerprintStore();
1761
1810
  this.rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter();
1811
+ this.onScoringComparison = options.onScoringComparison;
1762
1812
  }
1763
1813
  /** Score `signals` for the given request context and return a verdict. */
1764
1814
  score(signals, context) {
1765
1815
  const { ip, siteKey, userAgent } = context;
1766
1816
  const headers = context.headers ?? {};
1767
1817
  const detections = [];
1818
+ const onScoringComparison = this.onScoringComparison;
1819
+ const useCandidate = this.scoringPolicy === "noisy-or-floors-v1";
1820
+ const corroborating = onScoringComparison || useCandidate ? [] : void 0;
1768
1821
  if (context.extraDetections) detections.push(...context.extraDetections);
1769
1822
  const pow = context.pow;
1770
1823
  if (pow && pow.provided) {
@@ -1805,11 +1858,11 @@ var DetectionEngine = class {
1805
1858
  }
1806
1859
  const widgetInteraction = context.widgetInteraction !== false;
1807
1860
  detections.push(
1808
- ...detectVisionAI(signals, widgetInteraction),
1861
+ ...detectVisionAI(signals, widgetInteraction, corroborating),
1809
1862
  ...detectHeadless(signals, userAgent),
1810
1863
  ...detectAutomation(signals),
1811
- ...detectCDP(signals),
1812
- ...detectBehavioral(signals, widgetInteraction),
1864
+ ...detectCDP(signals, corroborating),
1865
+ ...detectBehavioral(signals, widgetInteraction, corroborating),
1813
1866
  ...detectTouchAuthenticity(signals, userAgent),
1814
1867
  ...detectSensorEntropy(signals, userAgent),
1815
1868
  ...detectTouchKinematics(signals),
@@ -1837,13 +1890,42 @@ var DetectionEngine = class {
1837
1890
  detections.push(...analyzeFormInteraction(signals.formAnalysis, signals.behavioral));
1838
1891
  }
1839
1892
  detections.push(...analyzeAdvancedSignals(signals));
1840
- const categoryScores = calculateCategoryScores(detections, this.weights);
1841
- const score = calculateFinalScore(categoryScores, this.weights);
1893
+ const currentCategoryScores = calculateCategoryScores(detections, this.weights);
1894
+ const currentScore = calculateFinalScore(currentCategoryScores, this.weights);
1895
+ const currentRecommendation = recommend(currentScore);
1842
1896
  const scrollObservation = observeScrollJump(signals.behavioral);
1897
+ let candidateCategoryScores;
1898
+ let candidateScore;
1899
+ let candidateRecommendation;
1900
+ if (corroborating) {
1901
+ candidateCategoryScores = calculateNoisyOrCategoryScores(detections, this.weights);
1902
+ const decisiveScore = applyDecisiveScoreFloor(
1903
+ calculateFinalScore(candidateCategoryScores, this.weights),
1904
+ signals.environmental,
1905
+ this.weights
1906
+ );
1907
+ candidateScore = applyCorroborationScoreFloor(decisiveScore, corroborating, this.weights);
1908
+ candidateRecommendation = recommend(candidateScore);
1909
+ }
1910
+ if (onScoringComparison && candidateScore !== void 0 && candidateRecommendation !== void 0) {
1911
+ try {
1912
+ const pending = onScoringComparison({
1913
+ policy: "noisy-or-floors-v1",
1914
+ current: { score: currentScore, recommendation: currentRecommendation },
1915
+ candidate: { score: candidateScore, recommendation: candidateRecommendation }
1916
+ });
1917
+ void pending?.catch(() => {
1918
+ });
1919
+ } catch {
1920
+ }
1921
+ }
1922
+ const categoryScores = useCandidate ? candidateCategoryScores : currentCategoryScores;
1923
+ const score = useCandidate ? candidateScore : currentScore;
1924
+ const recommendation = useCandidate ? candidateRecommendation : currentRecommendation;
1843
1925
  return {
1844
1926
  success: score < 0.5,
1845
1927
  score,
1846
- recommendation: recommend(score),
1928
+ recommendation,
1847
1929
  categoryScores,
1848
1930
  detections,
1849
1931
  ...scrollObservation ? { observations: [scrollObservation] } : {},
@@ -2054,9 +2136,11 @@ var Captcha = class {
2054
2136
  const fingerprintStore = options.fingerprintStore ?? new InMemoryFingerprintStore();
2055
2137
  this.engine = new DetectionEngine({
2056
2138
  weights: options.weights,
2139
+ scoringPolicy: options.scoringPolicy,
2057
2140
  requirePoW: true,
2058
2141
  fingerprintStore,
2059
- rateLimiter
2142
+ rateLimiter,
2143
+ onScoringComparison: options.onScoringComparison
2060
2144
  });
2061
2145
  this.pow = new PoWManager({ secret, store: options.challengeStore, rateLimiter });
2062
2146
  this.tokens = new TokenManager({ secret, store: options.tokenStore });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webdecoy/node",
3
- "version": "0.29.0",
3
+ "version": "0.30.0",
4
4
  "description": "Bot detection and AI agent verification for Node.js and edge runtimes. Local honeypot tripwires, rate limiting and AI crawler policies, with optional WebDecoy dashboard reporting.",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",