@webdecoy/node 0.28.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/dist/index.js CHANGED
@@ -5708,12 +5708,14 @@ function createFetchGuard(options = {}) {
5708
5708
  },
5709
5709
  async check(request, peer) {
5710
5710
  const url = new URL(request.url);
5711
+ const headers = headerRecord(request.headers);
5712
+ if (!headers.host && !headers[":authority"]) headers.host = url.host;
5711
5713
  const metadata = {
5712
5714
  method: request.method,
5713
5715
  path: url.pathname,
5714
5716
  ip: resolveIP(request, peer),
5715
5717
  user_agent: request.headers.get("user-agent") ?? void 0,
5716
- headers: headerRecord(request.headers),
5718
+ headers,
5717
5719
  query: url.search ? url.search.slice(1) : void 0,
5718
5720
  timestamp: Date.now()
5719
5721
  };
@@ -5850,25 +5852,43 @@ var MemoryClientSignalStore = class {
5850
5852
  };
5851
5853
  var CLIENT_SESSION_COOKIE = "wd_cs";
5852
5854
  var CLIENT_SESSION_HEADER = "x-wd-session";
5853
- function readClientSession(headers) {
5854
- const cookie = headers["cookie"];
5855
- if (cookie) {
5856
- for (const part of cookie.split(";")) {
5857
- const eq = part.indexOf("=");
5858
- if (eq < 0) continue;
5859
- if (part.slice(0, eq).trim() === CLIENT_SESSION_COOKIE) {
5860
- const value = part.slice(eq + 1).trim();
5861
- if (value) return value;
5862
- }
5855
+ var CLIENT_RECEIPT_COOKIE = "__Host-wd_cs";
5856
+ var CLIENT_RECEIPT_PREFIX = "receipt:";
5857
+ var CLIENT_RECEIPT_TTL_MS = 15 * 6e4;
5858
+ function getClientSignalHost(headers) {
5859
+ const value = headers.host ?? headers[":authority"];
5860
+ if (typeof value !== "string" || value.length > 255 || !/^[a-z0-9.:[\]-]+$/i.test(value)) {
5861
+ return void 0;
5862
+ }
5863
+ try {
5864
+ return new URL("https://" + value).host || void 0;
5865
+ } catch {
5866
+ return void 0;
5867
+ }
5868
+ }
5869
+ function readCookie(header2, name) {
5870
+ if (!header2) return void 0;
5871
+ for (const part of header2.split(";")) {
5872
+ const eq = part.indexOf("=");
5873
+ if (eq >= 0 && part.slice(0, eq).trim() === name) {
5874
+ return part.slice(eq + 1).trim();
5863
5875
  }
5864
5876
  }
5865
- const header2 = headers[CLIENT_SESSION_HEADER];
5866
- return header2 || void 0;
5877
+ return void 0;
5878
+ }
5879
+ function readClientSession(headers) {
5880
+ const receipt = readCookie(headers.cookie, CLIENT_RECEIPT_COOKIE);
5881
+ if (receipt !== void 0) {
5882
+ return /^[0-9a-f]{48}$/.test(receipt) ? CLIENT_RECEIPT_PREFIX + receipt : void 0;
5883
+ }
5884
+ const legacy = readCookie(headers.cookie, CLIENT_SESSION_COOKIE) || headers[CLIENT_SESSION_HEADER];
5885
+ return legacy && !legacy.startsWith(CLIENT_RECEIPT_PREFIX) ? legacy : void 0;
5867
5886
  }
5868
5887
  var ClientSignalRule = class {
5869
5888
  constructor(config) {
5870
5889
  this.name = "client-signals";
5871
5890
  this.store = config.store;
5891
+ this.siteKey = config.siteKey;
5872
5892
  this.minScore = config.minScore;
5873
5893
  this.action = config.action ?? "DENY";
5874
5894
  this.dryRun = config.dryRun ?? false;
@@ -5894,7 +5914,10 @@ var ClientSignalRule = class {
5894
5914
  };
5895
5915
  }
5896
5916
  const verdict = this.store.sync ? this.store.get(sessionId) : context.prepared?.[this.name];
5897
- if (!verdict) {
5917
+ const issuedReceipt = sessionId.startsWith(CLIENT_RECEIPT_PREFIX);
5918
+ const receipt = verdict?.receipt;
5919
+ const usableReceipt = receipt && Date.now() < receipt.expiresAt && getClientSignalHost(context.headers) === receipt.host && (this.siteKey === void 0 || this.siteKey === receipt.siteKey);
5920
+ if (!verdict || verdict.sessionId !== sessionId || (issuedReceipt || this.siteKey !== void 0) && !usableReceipt) {
5898
5921
  return {
5899
5922
  action: "ALLOW",
5900
5923
  rule: this.name,
@@ -5917,7 +5940,7 @@ var ClientSignalRule = class {
5917
5940
  metadata: {
5918
5941
  score: verdict.score,
5919
5942
  recommendation: verdict.recommendation,
5920
- sessionId,
5943
+ ...issuedReceipt ? {} : { sessionId },
5921
5944
  dryRun: this.dryRun
5922
5945
  }
5923
5946
  };
@@ -6094,7 +6117,67 @@ var InMemoryRateLimiter2 = class {
6094
6117
  }
6095
6118
  };
6096
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
+
6097
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
+ }
6098
6181
  function calculateCategoryScores(detections, weights) {
6099
6182
  var _a;
6100
6183
  const categoryData = {};
@@ -6116,6 +6199,19 @@ function calculateCategoryScores(detections, weights) {
6116
6199
  }
6117
6200
  return result;
6118
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
+ }
6119
6215
  function calculateFinalScore(categoryScores, weights) {
6120
6216
  let total = 0;
6121
6217
  for (const [cat, weight] of Object.entries(weights)) {
@@ -6129,6 +6225,39 @@ function recommend(finalScore) {
6129
6225
  return "block";
6130
6226
  }
6131
6227
 
6228
+ // src/detection/detectors/corroborating-detection.ts
6229
+ function addCorroboratingDetection(detections, corroborating, detection) {
6230
+ detections.push(detection);
6231
+ corroborating?.push(detection);
6232
+ }
6233
+
6234
+ // src/detection/detectors/keyboard-input.ts
6235
+ var MIN_KEY_HOLD_SAMPLES = 3;
6236
+ var MAX_KEY_HOLD_SAMPLES = 200;
6237
+ var SHORT_KEY_HOLD_MS = 20;
6238
+ var MAX_KEY_HOLD_MS = 2e3;
6239
+ function classifyKeyboardInput(signals) {
6240
+ const behavioral = signals.behavioral ?? {};
6241
+ const keyEvents = behavioral.keyEvents ?? 0;
6242
+ if (!Number.isFinite(keyEvents) || keyEvents < 2 || (behavioral.totalPoints ?? 0) !== 0) {
6243
+ return null;
6244
+ }
6245
+ const { keyHoldSamples = 0, keyHoldAvg = 0 } = behavioral;
6246
+ const validSummary = Number.isInteger(keyHoldSamples) && keyHoldSamples > 0 && keyHoldSamples <= Math.min(MAX_KEY_HOLD_SAMPLES, Math.floor(keyEvents / 2)) && Number.isFinite(keyHoldAvg) && keyHoldAvg > 0 && keyHoldAvg < MAX_KEY_HOLD_MS;
6247
+ let count = validSummary ? keyHoldSamples : 0;
6248
+ let duration = count > 0 ? count * keyHoldAvg : 0;
6249
+ for (const field of Object.values(signals.formAnalysis?.textareaKeyboard ?? {})) {
6250
+ if (!Array.isArray(field?.dwellTimes)) continue;
6251
+ for (const dwell of field.dwellTimes) {
6252
+ if (typeof dwell === "number" && dwell > 0 && dwell < MAX_KEY_HOLD_MS) {
6253
+ count++;
6254
+ duration += dwell;
6255
+ }
6256
+ }
6257
+ }
6258
+ return count >= MIN_KEY_HOLD_SAMPLES && duration / count < SHORT_KEY_HOLD_MS ? "short-key-holds" : "keyboard-only";
6259
+ }
6260
+
6132
6261
  // src/detection/detectors/pointer-evidence.ts
6133
6262
  function isTouchModality(behavioral) {
6134
6263
  const touchEvents = behavioral.touchEvents ?? 0;
@@ -6136,14 +6265,14 @@ function isTouchModality(behavioral) {
6136
6265
  return touchEvents >= 3 || hasTouchSample && behavioral.pointerHasNonMouseType === true;
6137
6266
  }
6138
6267
  function hasHumanMovementMarkers(behavioral) {
6139
- const tremor = behavioral.microTremorScore ?? 0;
6268
+ const tremor = behavioral.microTremorScore ?? 0.5;
6140
6269
  const corrections = behavioral.overshootCorrections ?? 0;
6141
6270
  const changes = behavioral.directionChanges ?? 0;
6142
6271
  return tremor >= 0.5 && (corrections >= 1 || changes >= 10);
6143
6272
  }
6144
6273
 
6145
6274
  // src/detection/detectors/vision-ai.ts
6146
- function detectVisionAI(signals, widgetInteraction = true) {
6275
+ function detectVisionAI(signals, widgetInteraction = true, corroborating) {
6147
6276
  const detections = [];
6148
6277
  const b = signals.behavioral ?? {};
6149
6278
  const t = signals.temporal ?? {};
@@ -6151,7 +6280,7 @@ function detectVisionAI(signals, widgetInteraction = true) {
6151
6280
  const trajectory = b.trajectoryLength ?? 0;
6152
6281
  const approachPts = b.approachPoints ?? 0;
6153
6282
  const isTouchUser = isTouchModality(b);
6154
- const isKeyboardUser = (b.keyEvents ?? 0) >= 2 && totalPoints === 0;
6283
+ const isKeyboardUser = classifyKeyboardInput(signals) === "keyboard-only";
6155
6284
  const usesMouse = !isTouchUser && !isKeyboardUser;
6156
6285
  if (totalPoints < 5 && trajectory < 10 && usesMouse) {
6157
6286
  detections.push({
@@ -6191,7 +6320,7 @@ function detectVisionAI(signals, widgetInteraction = true) {
6191
6320
  }
6192
6321
  const microTremor = b.microTremorScore ?? 0.5;
6193
6322
  if (usesMouse && totalPoints >= 5 && microTremor < 0.15) {
6194
- detections.push({
6323
+ addCorroboratingDetection(detections, corroborating, {
6195
6324
  category: "vision_ai",
6196
6325
  score: 0.7,
6197
6326
  confidence: 0.6,
@@ -6199,7 +6328,7 @@ function detectVisionAI(signals, widgetInteraction = true) {
6199
6328
  });
6200
6329
  }
6201
6330
  if (widgetInteraction && usesMouse && approachPts >= 5 && (b.approachDirectness ?? 0) > 0.95 && !hasHumanMovementMarkers(b)) {
6202
- detections.push({
6331
+ addCorroboratingDetection(detections, corroborating, {
6203
6332
  category: "vision_ai",
6204
6333
  score: 0.5,
6205
6334
  confidence: 0.5,
@@ -6208,7 +6337,7 @@ function detectVisionAI(signals, widgetInteraction = true) {
6208
6337
  }
6209
6338
  const exploration = b.explorationRatio ?? 0.3;
6210
6339
  if (widgetInteraction && exploration < 0.05 && trajectory > 50) {
6211
- detections.push({
6340
+ addCorroboratingDetection(detections, corroborating, {
6212
6341
  category: "vision_ai",
6213
6342
  score: 0.4,
6214
6343
  confidence: 0.4,
@@ -6356,58 +6485,31 @@ function detectAutomation(signals) {
6356
6485
  return detections;
6357
6486
  }
6358
6487
 
6359
- // src/detection/detectors/cdp.ts
6360
- var HIGH_CONFIDENCE_SIGNALS = ["chromedriver_cdc", "puppeteer_eval", "cdp_script_injection"];
6361
- function detectCDP(signals) {
6362
- const detections = [];
6363
- const cdp = signals.environmental?.cdp ?? {};
6364
- if (!cdp.detected) return detections;
6365
- const signalList = cdp.signals ?? [];
6366
- const signalCount = signalList.length;
6367
- const hasHighConf = signalList.some((s) => HIGH_CONFIDENCE_SIGNALS.includes(s));
6368
- if (hasHighConf) {
6369
- detections.push({
6370
- category: "cdp",
6371
- score: 0.9,
6372
- confidence: 0.95,
6373
- reason: `CDP automation detected: ${signalList.join(", ")}`
6374
- });
6375
- } else if (signalCount >= 2) {
6376
- detections.push({
6377
- category: "cdp",
6378
- score: 0.8,
6379
- confidence: 0.85,
6380
- reason: `Multiple CDP indicators: ${signalList.join(", ")}`
6381
- });
6382
- } else if (signalCount === 1) {
6383
- detections.push({
6384
- category: "cdp",
6385
- score: 0.6,
6386
- confidence: 0.7,
6387
- reason: `CDP indicator: ${signalList.join(", ")}`
6388
- });
6389
- }
6390
- return detections;
6391
- }
6392
-
6393
6488
  // src/detection/detectors/behavioral.ts
6394
- function detectBehavioral(signals, widgetInteraction = true) {
6489
+ function detectBehavioral(signals, widgetInteraction = true, corroborating) {
6395
6490
  const detections = [];
6396
6491
  const b = signals.behavioral ?? {};
6397
6492
  const t = signals.temporal ?? {};
6398
6493
  const totalPoints = b.totalPoints ?? 0;
6399
6494
  const trajectory = b.trajectoryLength ?? 0;
6400
6495
  const isTouchUser = isTouchModality(b);
6401
- const isKeyboardUser = (b.keyEvents ?? 0) >= 2 && totalPoints === 0;
6496
+ const keyboard = classifyKeyboardInput(signals);
6402
6497
  const humanMovement = hasHumanMovementMarkers(b);
6403
- if (totalPoints === 0 && !isTouchUser && !isKeyboardUser) {
6498
+ if (keyboard === "short-key-holds" && !isTouchUser) {
6499
+ addCorroboratingDetection(detections, corroborating, {
6500
+ category: "behavioral",
6501
+ score: 0.8,
6502
+ confidence: 0.9,
6503
+ reason: "Keyboard-only input has unusually short key holds"
6504
+ });
6505
+ } else if (totalPoints === 0 && !isTouchUser && keyboard === null) {
6404
6506
  detections.push({
6405
6507
  category: "behavioral",
6406
6508
  score: 0.8,
6407
6509
  confidence: 0.9,
6408
6510
  reason: "Zero mouse, touch, or keyboard events recorded"
6409
6511
  });
6410
- } else if (totalPoints < 10 && !isTouchUser && !isKeyboardUser && trajectory < 30) {
6512
+ } else if (totalPoints < 10 && !isTouchUser && keyboard === null && trajectory < 30) {
6411
6513
  detections.push({
6412
6514
  category: "behavioral",
6413
6515
  score: 0.6,
@@ -6417,7 +6519,7 @@ function detectBehavioral(signals, widgetInteraction = true) {
6417
6519
  }
6418
6520
  const velVar = b.velocityVariance ?? 1;
6419
6521
  if (velVar < 0.02 && trajectory > 50 && !humanMovement) {
6420
- detections.push({
6522
+ addCorroboratingDetection(detections, corroborating, {
6421
6523
  category: "behavioral",
6422
6524
  score: 0.6,
6423
6525
  confidence: 0.6,
@@ -6476,7 +6578,7 @@ function detectBehavioral(signals, widgetInteraction = true) {
6476
6578
  }
6477
6579
  const straight = b.straightLineRatio ?? 0;
6478
6580
  if (straight > 0.8 && trajectory > 100) {
6479
- detections.push({
6581
+ addCorroboratingDetection(detections, corroborating, {
6480
6582
  category: "behavioral",
6481
6583
  score: 0.5,
6482
6584
  confidence: 0.5,
@@ -6485,7 +6587,7 @@ function detectBehavioral(signals, widgetInteraction = true) {
6485
6587
  }
6486
6588
  const dirChanges = b.directionChanges ?? 10;
6487
6589
  if (totalPoints > 50 && dirChanges < 3) {
6488
- detections.push({
6590
+ addCorroboratingDetection(detections, corroborating, {
6489
6591
  category: "behavioral",
6490
6592
  score: 0.4,
6491
6593
  confidence: 0.4,
@@ -7447,16 +7549,24 @@ function analyzeAdvancedSignals(signals) {
7447
7549
  // src/detection/engine.ts
7448
7550
  var DetectionEngine = class {
7449
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
+ }
7450
7555
  this.weights = options.weights ?? DEFAULT_WEIGHTS;
7556
+ this.scoringPolicy = options.scoringPolicy ?? "weighted-mean-v1";
7451
7557
  this.requirePoW = options.requirePoW ?? true;
7452
7558
  this.fingerprintStore = options.fingerprintStore ?? new InMemoryFingerprintStore();
7453
7559
  this.rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter2();
7560
+ this.onScoringComparison = options.onScoringComparison;
7454
7561
  }
7455
7562
  /** Score `signals` for the given request context and return a verdict. */
7456
7563
  score(signals, context) {
7457
7564
  const { ip, siteKey, userAgent } = context;
7458
7565
  const headers = context.headers ?? {};
7459
7566
  const detections = [];
7567
+ const onScoringComparison = this.onScoringComparison;
7568
+ const useCandidate = this.scoringPolicy === "noisy-or-floors-v1";
7569
+ const corroborating = onScoringComparison || useCandidate ? [] : void 0;
7460
7570
  if (context.extraDetections) detections.push(...context.extraDetections);
7461
7571
  const pow = context.pow;
7462
7572
  if (pow && pow.provided) {
@@ -7497,11 +7607,11 @@ var DetectionEngine = class {
7497
7607
  }
7498
7608
  const widgetInteraction = context.widgetInteraction !== false;
7499
7609
  detections.push(
7500
- ...detectVisionAI(signals, widgetInteraction),
7610
+ ...detectVisionAI(signals, widgetInteraction, corroborating),
7501
7611
  ...detectHeadless(signals, userAgent),
7502
7612
  ...detectAutomation(signals),
7503
- ...detectCDP(signals),
7504
- ...detectBehavioral(signals, widgetInteraction),
7613
+ ...detectCDP(signals, corroborating),
7614
+ ...detectBehavioral(signals, widgetInteraction, corroborating),
7505
7615
  ...detectTouchAuthenticity(signals, userAgent),
7506
7616
  ...detectSensorEntropy(signals, userAgent),
7507
7617
  ...detectTouchKinematics(signals),
@@ -7529,13 +7639,42 @@ var DetectionEngine = class {
7529
7639
  detections.push(...analyzeFormInteraction(signals.formAnalysis, signals.behavioral));
7530
7640
  }
7531
7641
  detections.push(...analyzeAdvancedSignals(signals));
7532
- const categoryScores = calculateCategoryScores(detections, this.weights);
7533
- 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);
7534
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;
7535
7674
  return {
7536
7675
  success: score < 0.5,
7537
7676
  score,
7538
- recommendation: recommend(score),
7677
+ recommendation,
7539
7678
  categoryScores,
7540
7679
  detections,
7541
7680
  ...scrollObservation ? { observations: [scrollObservation] } : {},
@@ -7746,9 +7885,11 @@ var Captcha = class {
7746
7885
  const fingerprintStore = options.fingerprintStore ?? new InMemoryFingerprintStore();
7747
7886
  this.engine = new DetectionEngine({
7748
7887
  weights: options.weights,
7888
+ scoringPolicy: options.scoringPolicy,
7749
7889
  requirePoW: true,
7750
7890
  fingerprintStore,
7751
- rateLimiter
7891
+ rateLimiter,
7892
+ onScoringComparison: options.onScoringComparison
7752
7893
  });
7753
7894
  this.pow = new PoWManager({ secret, store: options.challengeStore, rateLimiter });
7754
7895
  this.tokens = new TokenManager({ secret, store: options.tokenStore });
@@ -7763,13 +7904,14 @@ var Captcha = class {
7763
7904
  * signals, and issues a session token on success. Mirrors `runVerification`.
7764
7905
  */
7765
7906
  async verify(input) {
7766
- return this.verifySubmission(input, true);
7907
+ return (await this.verifySubmission(input, true)).result;
7767
7908
  }
7768
7909
  async verifySubmission(input, widgetInteraction) {
7769
7910
  const { siteKey, ip, userAgent } = input;
7770
7911
  const headers = input.headers ?? {};
7771
7912
  let signals = input.signals ?? {};
7772
7913
  const extraDetections = [];
7914
+ let committedSignals = false;
7773
7915
  const clientSignalsHash = input.powSolution?.signalsHash ?? null;
7774
7916
  if (input.signalsJson && clientSignalsHash) {
7775
7917
  const computed = await sha256Hex(input.signalsJson);
@@ -7782,7 +7924,11 @@ var Captcha = class {
7782
7924
  });
7783
7925
  }
7784
7926
  try {
7785
- signals = JSON.parse(input.signalsJson);
7927
+ const parsed = JSON.parse(input.signalsJson);
7928
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
7929
+ signals = parsed;
7930
+ committedSignals = computed === clientSignalsHash;
7931
+ }
7786
7932
  } catch {
7787
7933
  }
7788
7934
  }
@@ -7817,18 +7963,28 @@ var Captcha = class {
7817
7963
  const success = proofVerified && verdict.success;
7818
7964
  const token = success ? await this.tokens.issue(ip, siteKey, verdict.score) : null;
7819
7965
  const recommendation = !proofVerified && verdict.recommendation === "allow" ? "challenge" : verdict.recommendation;
7820
- return { ...verdict, success, recommendation, token };
7966
+ return {
7967
+ result: { ...verdict, success, recommendation, token },
7968
+ verifiedSignals: proofVerified && committedSignals && !!pow.nonce && signals.meta?.challengeNonce === pow.nonce
7969
+ };
7821
7970
  }
7822
7971
  /** Invisible-mode scoring — same pipeline, returns a compact result + action. */
7823
7972
  async score(input) {
7824
- const result = await this.verifySubmission(input, false);
7973
+ return (await this.scoreForSession(input)).result;
7974
+ }
7975
+ /** @internal Return the score and whether the server verified the committed signals. */
7976
+ async scoreForSession(input) {
7977
+ const { result, verifiedSignals } = await this.verifySubmission(input, false);
7825
7978
  return {
7826
- success: result.success,
7827
- score: result.score,
7828
- token: result.token,
7829
- action: input.action ?? "",
7830
- recommendation: result.recommendation,
7831
- ...result.observations ? { observations: result.observations } : {}
7979
+ result: {
7980
+ success: result.success,
7981
+ score: result.score,
7982
+ token: result.token,
7983
+ action: input.action ?? "",
7984
+ recommendation: result.recommendation,
7985
+ ...result.observations ? { observations: result.observations } : {}
7986
+ },
7987
+ verifiedSignals
7832
7988
  };
7833
7989
  }
7834
7990
  /** Verify a previously issued token (single-use, optionally IP-bound). */
@@ -7878,8 +8034,9 @@ function createCaptchaEndpoints(options = {}) {
7878
8034
  }
7879
8035
  if (sub === "/score" && method === "POST") {
7880
8036
  const b = req.body ?? {};
7881
- const result = await captcha.score({
7882
- siteKey: b.siteKey ?? "default",
8037
+ const siteKey = b.siteKey ?? "default";
8038
+ const { result, verifiedSignals } = await captcha.scoreForSession({
8039
+ siteKey,
7883
8040
  ip: req.ip,
7884
8041
  userAgent,
7885
8042
  headers: req.headers,
@@ -7890,20 +8047,28 @@ function createCaptchaEndpoints(options = {}) {
7890
8047
  ja3Hash,
7891
8048
  action: b.action
7892
8049
  });
7893
- if (signalStore && b.sessionId) {
8050
+ const legacyId = typeof b.sessionId === "string" && !b.sessionId.startsWith(CLIENT_RECEIPT_PREFIX) ? b.sessionId || null : null;
8051
+ const response = json(200, { ...result, sessionId: legacyId });
8052
+ if (!signalStore) return response;
8053
+ const at2 = Date.now();
8054
+ const verdict = { score: result.score, recommendation: result.recommendation, at: at2 };
8055
+ if (legacyId) {
8056
+ await signalStore.set({ ...verdict, sessionId: legacyId });
8057
+ return response;
8058
+ }
8059
+ const host = getClientSignalHost(req.headers);
8060
+ const origin = req.headers.origin;
8061
+ if (verifiedSignals && host && (!origin || origin === "https://" + host) && typeof siteKey === "string" && siteKey.length <= 128) {
8062
+ const receipt = randomHex(24);
7894
8063
  await signalStore.set({
7895
- sessionId: b.sessionId,
7896
- score: result.score,
7897
- recommendation: result.recommendation,
7898
- at: Date.now()
8064
+ ...verdict,
8065
+ sessionId: CLIENT_RECEIPT_PREFIX + receipt,
8066
+ receipt: { host, siteKey, expiresAt: at2 + CLIENT_RECEIPT_TTL_MS }
7899
8067
  });
8068
+ response.headers["set-cookie"] = `${CLIENT_RECEIPT_COOKIE}=${receipt}; Path=/; Max-Age=${CLIENT_RECEIPT_TTL_MS / 1e3}; Secure; HttpOnly; SameSite=Lax`;
8069
+ response.headers["cache-control"] = "private, no-store";
7900
8070
  }
7901
- return json(200, {
7902
- ...result,
7903
- // Echoed so the widget can set the cookie the rule reads, without the
7904
- // developer wiring a second endpoint to hand it one.
7905
- sessionId: b.sessionId ?? null
7906
- });
8071
+ return response;
7907
8072
  }
7908
8073
  if (sub === "/token/verify" && method === "POST") {
7909
8074
  const b = req.body ?? {};