@webdecoy/node 0.27.0 → 0.29.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
  };
@@ -5955,6 +5978,21 @@ var AUTOMATION_UA_PATTERNS = [
5955
5978
  /chromium.*headless/i
5956
5979
  ];
5957
5980
 
5981
+ // src/detection/scroll-observation.ts
5982
+ var MAX_SCROLL_SAMPLES = 100;
5983
+ var LARGE_SCROLL_STEP_PX = 400;
5984
+ function observeScrollJump(behavioral) {
5985
+ const { samples, maxStep } = behavioral?.scrollMorphology ?? {};
5986
+ if (typeof samples !== "number" || !Number.isInteger(samples) || samples < 2 || samples > MAX_SCROLL_SAMPLES || typeof maxStep !== "number" || !Number.isFinite(maxStep) || maxStep < 0 || (behavioral?.keyEvents ?? 0) > 0 || (behavioral?.touchEvents ?? 0) > 0) return void 0;
5987
+ return {
5988
+ id: "large-scroll-step-v1",
5989
+ mode: "observe",
5990
+ status: maxStep > LARGE_SCROLL_STEP_PX ? "detected" : "clear",
5991
+ samples,
5992
+ maxStep
5993
+ };
5994
+ }
5995
+
5958
5996
  // src/detection/ip.ts
5959
5997
  var IPV4_RE = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
5960
5998
  function isIPv4(ip) {
@@ -6114,19 +6152,58 @@ function recommend(finalScore) {
6114
6152
  return "block";
6115
6153
  }
6116
6154
 
6155
+ // src/detection/detectors/keyboard-input.ts
6156
+ var MIN_KEY_HOLD_SAMPLES = 3;
6157
+ var MAX_KEY_HOLD_SAMPLES = 200;
6158
+ var SHORT_KEY_HOLD_MS = 20;
6159
+ var MAX_KEY_HOLD_MS = 2e3;
6160
+ function classifyKeyboardInput(signals) {
6161
+ const behavioral = signals.behavioral ?? {};
6162
+ const keyEvents = behavioral.keyEvents ?? 0;
6163
+ if (!Number.isFinite(keyEvents) || keyEvents < 2 || (behavioral.totalPoints ?? 0) !== 0) {
6164
+ return null;
6165
+ }
6166
+ const { keyHoldSamples = 0, keyHoldAvg = 0 } = behavioral;
6167
+ 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;
6168
+ let count = validSummary ? keyHoldSamples : 0;
6169
+ let duration = count > 0 ? count * keyHoldAvg : 0;
6170
+ for (const field of Object.values(signals.formAnalysis?.textareaKeyboard ?? {})) {
6171
+ if (!Array.isArray(field?.dwellTimes)) continue;
6172
+ for (const dwell of field.dwellTimes) {
6173
+ if (typeof dwell === "number" && dwell > 0 && dwell < MAX_KEY_HOLD_MS) {
6174
+ count++;
6175
+ duration += dwell;
6176
+ }
6177
+ }
6178
+ }
6179
+ return count >= MIN_KEY_HOLD_SAMPLES && duration / count < SHORT_KEY_HOLD_MS ? "short-key-holds" : "keyboard-only";
6180
+ }
6181
+
6182
+ // src/detection/detectors/pointer-evidence.ts
6183
+ function isTouchModality(behavioral) {
6184
+ const touchEvents = behavioral.touchEvents ?? 0;
6185
+ const hasTouchSample = touchEvents > 0 || (behavioral.touchTotalPoints ?? 0) > 0;
6186
+ return touchEvents >= 3 || hasTouchSample && behavioral.pointerHasNonMouseType === true;
6187
+ }
6188
+ function hasHumanMovementMarkers(behavioral) {
6189
+ const tremor = behavioral.microTremorScore ?? 0;
6190
+ const corrections = behavioral.overshootCorrections ?? 0;
6191
+ const changes = behavioral.directionChanges ?? 0;
6192
+ return tremor >= 0.5 && (corrections >= 1 || changes >= 10);
6193
+ }
6194
+
6117
6195
  // src/detection/detectors/vision-ai.ts
6118
- function detectVisionAI(signals) {
6196
+ function detectVisionAI(signals, widgetInteraction = true) {
6119
6197
  const detections = [];
6120
6198
  const b = signals.behavioral ?? {};
6121
6199
  const t = signals.temporal ?? {};
6122
6200
  const totalPoints = b.totalPoints ?? 0;
6123
6201
  const trajectory = b.trajectoryLength ?? 0;
6124
6202
  const approachPts = b.approachPoints ?? 0;
6125
- const touchEvents = b.touchEvents ?? 0;
6126
- const keyEvents = b.keyEvents ?? 0;
6127
- const isTouchUser = touchEvents >= 3;
6128
- const isKeyboardUser = keyEvents >= 2 && totalPoints === 0;
6129
- if (totalPoints < 5 && trajectory < 10 && !isTouchUser && !isKeyboardUser) {
6203
+ const isTouchUser = isTouchModality(b);
6204
+ const isKeyboardUser = classifyKeyboardInput(signals) === "keyboard-only";
6205
+ const usesMouse = !isTouchUser && !isKeyboardUser;
6206
+ if (totalPoints < 5 && trajectory < 10 && usesMouse) {
6130
6207
  detections.push({
6131
6208
  category: "vision_ai",
6132
6209
  score: 0.9,
@@ -6134,7 +6211,7 @@ function detectVisionAI(signals) {
6134
6211
  reason: "No mouse movement detected before click (AI agent pattern)"
6135
6212
  });
6136
6213
  }
6137
- if (approachPts === 0 && !isTouchUser && !isKeyboardUser) {
6214
+ if (widgetInteraction && approachPts === 0 && usesMouse) {
6138
6215
  detections.push({
6139
6216
  category: "vision_ai",
6140
6217
  score: 0.7,
@@ -6163,7 +6240,7 @@ function detectVisionAI(signals) {
6163
6240
  }
6164
6241
  }
6165
6242
  const microTremor = b.microTremorScore ?? 0.5;
6166
- if (microTremor < 0.15) {
6243
+ if (usesMouse && totalPoints >= 5 && microTremor < 0.15) {
6167
6244
  detections.push({
6168
6245
  category: "vision_ai",
6169
6246
  score: 0.7,
@@ -6171,7 +6248,7 @@ function detectVisionAI(signals) {
6171
6248
  reason: "Mouse movement lacks natural micro-tremor"
6172
6249
  });
6173
6250
  }
6174
- if ((b.approachDirectness ?? 0) > 0.95) {
6251
+ if (widgetInteraction && usesMouse && approachPts >= 5 && (b.approachDirectness ?? 0) > 0.95 && !hasHumanMovementMarkers(b)) {
6175
6252
  detections.push({
6176
6253
  category: "vision_ai",
6177
6254
  score: 0.5,
@@ -6179,17 +6256,8 @@ function detectVisionAI(signals) {
6179
6256
  reason: "Mouse path to target is unnaturally direct"
6180
6257
  });
6181
6258
  }
6182
- const precision = b.clickPrecision ?? 10;
6183
- if (precision > 0 && precision < 2) {
6184
- detections.push({
6185
- category: "vision_ai",
6186
- score: 0.4,
6187
- confidence: 0.5,
6188
- reason: "Click precision is unnaturally accurate"
6189
- });
6190
- }
6191
6259
  const exploration = b.explorationRatio ?? 0.3;
6192
- if (exploration < 0.05 && trajectory > 50) {
6260
+ if (widgetInteraction && exploration < 0.05 && trajectory > 50) {
6193
6261
  detections.push({
6194
6262
  category: "vision_ai",
6195
6263
  score: 0.4,
@@ -6373,24 +6441,30 @@ function detectCDP(signals) {
6373
6441
  }
6374
6442
 
6375
6443
  // src/detection/detectors/behavioral.ts
6376
- function detectBehavioral(signals) {
6444
+ function detectBehavioral(signals, widgetInteraction = true) {
6377
6445
  const detections = [];
6378
6446
  const b = signals.behavioral ?? {};
6379
6447
  const t = signals.temporal ?? {};
6380
6448
  const totalPoints = b.totalPoints ?? 0;
6381
6449
  const trajectory = b.trajectoryLength ?? 0;
6382
- const touchEvts = b.touchEvents ?? 0;
6383
- const keyEvts = b.keyEvents ?? 0;
6384
- const isTouchUsr = touchEvts >= 3;
6385
- const isKbdUser = keyEvts >= 2 && totalPoints === 0;
6386
- if (totalPoints === 0 && !isTouchUsr && !isKbdUser) {
6450
+ const isTouchUser = isTouchModality(b);
6451
+ const keyboard = classifyKeyboardInput(signals);
6452
+ const humanMovement = hasHumanMovementMarkers(b);
6453
+ if (keyboard === "short-key-holds" && !isTouchUser) {
6454
+ detections.push({
6455
+ category: "behavioral",
6456
+ score: 0.8,
6457
+ confidence: 0.9,
6458
+ reason: "Keyboard-only input has unusually short key holds"
6459
+ });
6460
+ } else if (totalPoints === 0 && !isTouchUser && keyboard === null) {
6387
6461
  detections.push({
6388
6462
  category: "behavioral",
6389
6463
  score: 0.8,
6390
6464
  confidence: 0.9,
6391
6465
  reason: "Zero mouse, touch, or keyboard events recorded"
6392
6466
  });
6393
- } else if (totalPoints < 10 && !isTouchUsr && !isKbdUser && trajectory < 30) {
6467
+ } else if (totalPoints < 10 && !isTouchUser && keyboard === null && trajectory < 30) {
6394
6468
  detections.push({
6395
6469
  category: "behavioral",
6396
6470
  score: 0.6,
@@ -6399,7 +6473,7 @@ function detectBehavioral(signals) {
6399
6473
  });
6400
6474
  }
6401
6475
  const velVar = b.velocityVariance ?? 1;
6402
- if (velVar < 0.02 && trajectory > 50) {
6476
+ if (velVar < 0.02 && trajectory > 50 && !humanMovement) {
6403
6477
  detections.push({
6404
6478
  category: "behavioral",
6405
6479
  score: 0.6,
@@ -6408,7 +6482,7 @@ function detectBehavioral(signals) {
6408
6482
  });
6409
6483
  }
6410
6484
  const overshoots = b.overshootCorrections ?? 0;
6411
- if (overshoots === 0 && trajectory > 200) {
6485
+ if (widgetInteraction && overshoots === 0 && trajectory > 200 && !humanMovement) {
6412
6486
  detections.push({
6413
6487
  category: "behavioral",
6414
6488
  score: 0.4,
@@ -6424,7 +6498,7 @@ function detectBehavioral(signals) {
6424
6498
  confidence: 0.7,
6425
6499
  reason: "Interaction completed too quickly"
6426
6500
  });
6427
- } else if (interactionTime > 6e4) {
6501
+ } else if (widgetInteraction && interactionTime > 6e4) {
6428
6502
  detections.push({
6429
6503
  category: "captcha_farm",
6430
6504
  score: 0.3,
@@ -6449,7 +6523,7 @@ function detectBehavioral(signals) {
6449
6523
  confidence: 0.5,
6450
6524
  reason: "Mouse event rate abnormally high"
6451
6525
  });
6452
- } else if (eventRate > 0 && eventRate < 10) {
6526
+ } else if (eventRate > 0 && eventRate < 10 && !humanMovement) {
6453
6527
  detections.push({
6454
6528
  category: "behavioral",
6455
6529
  score: 0.4,
@@ -7139,7 +7213,7 @@ function analyzeKeystrokeCadence(stats) {
7139
7213
  }
7140
7214
 
7141
7215
  // src/detection/detectors/form.ts
7142
- function analyzeFormInteraction(formAnalysis) {
7216
+ function analyzeFormInteraction(formAnalysis, behavioral) {
7143
7217
  if (!formAnalysis) return [];
7144
7218
  const detections = [];
7145
7219
  const submit = formAnalysis.submit ?? {};
@@ -7186,13 +7260,14 @@ function analyzeFormInteraction(formAnalysis) {
7186
7260
  }
7187
7261
  const textareaData = formAnalysis.textareaKeyboard;
7188
7262
  if (textareaData) {
7263
+ const hasPointerOrTouch = (behavioral?.totalPoints ?? 0) >= 5 || (behavioral?.touchEvents ?? 0) > 0;
7189
7264
  for (const [fieldId, stats] of Object.entries(textareaData)) {
7190
7265
  const keyCount = stats.keyCount ?? 0;
7191
7266
  const pasteCount = stats.pasteCount ?? 0;
7192
7267
  const avgKeyInterval = stats.avgKeyInterval ?? 0;
7193
7268
  const keyIntervalVariance = stats.keyIntervalVariance ?? 0;
7194
7269
  const keydownUpRatio = stats.keydownUpRatio ?? 1;
7195
- if (pasteCount > 0 && keyCount < 5) {
7270
+ if (pasteCount > 0 && keyCount < 5 && !hasPointerOrTouch) {
7196
7271
  detections.push({
7197
7272
  category: "bot",
7198
7273
  score: 0.6,
@@ -7224,7 +7299,7 @@ function analyzeFormInteraction(formAnalysis) {
7224
7299
  reason: `Textarea "${fieldId}" has abnormal keydown/keyup ratio (${keydownUpRatio.toFixed(2)})`
7225
7300
  });
7226
7301
  }
7227
- if (stats.noKeyboardEvents && (stats.contentLength ?? 0) > 0) {
7302
+ if (stats.noKeyboardEvents && keyCount === 0 && pasteCount === 0 && (stats.contentLength ?? 0) > 0) {
7228
7303
  detections.push({
7229
7304
  category: "bot",
7230
7305
  score: 0.75,
@@ -7336,44 +7411,32 @@ function analyzeCSSMediaQueries(cssMedia, signals) {
7336
7411
  }
7337
7412
  return detections;
7338
7413
  }
7339
- function analyzeFonts(fontsInfo, userAgent) {
7340
- if (!fontsInfo || !fontsInfo.supported) return [];
7341
- const detections = [];
7414
+ function analyzeFonts(fontsInfo, platform) {
7342
7415
  const count = fontsInfo.count ?? 0;
7343
- if (count < 3) {
7344
- detections.push({
7345
- category: "headless",
7416
+ if (fontsInfo.supported !== true || !Number.isInteger(count) || count < 3 || typeof platform !== "string") {
7417
+ return [];
7418
+ }
7419
+ const hasWindowsFonts = fontsInfo.hasSegoeUI === true || fontsInfo.hasCalibri === true;
7420
+ const hasMacFonts = fontsInfo.hasSFPro === true || fontsInfo.hasMenlo === true;
7421
+ const noWindowsFonts = fontsInfo.hasSegoeUI === false && fontsInfo.hasCalibri === false;
7422
+ const noMacFonts = fontsInfo.hasSFPro === false && fontsInfo.hasMenlo === false;
7423
+ if (/^(mac|iphone|ipad|ipod)/i.test(platform) && hasWindowsFonts && noMacFonts) {
7424
+ return [{
7425
+ category: "automation",
7346
7426
  score: 0.5,
7347
7427
  confidence: 0.5,
7348
- reason: `Very few fonts detected (${count})`
7349
- });
7428
+ reason: `Font set contradicts platform (Windows faces while claiming ${platform})`
7429
+ }];
7350
7430
  }
7351
- const ua = (userAgent || "").toLowerCase();
7352
- if (ua.includes("windows") && fontsInfo.hasSegoeUI === false && count > 5) {
7353
- detections.push({
7354
- category: "bot",
7431
+ if (/^win/i.test(platform) && hasMacFonts && noWindowsFonts) {
7432
+ return [{
7433
+ category: "automation",
7355
7434
  score: 0.5,
7356
- confidence: 0.6,
7357
- reason: "Windows UA but Segoe UI font not detected"
7358
- });
7359
- }
7360
- if ((ua.includes("mac os x") || ua.includes("macintosh")) && fontsInfo.hasSFPro === false && !ua.includes("10_15") && !ua.includes("10_14") && count > 5) {
7361
- detections.push({
7362
- category: "bot",
7363
- score: 0.3,
7364
- confidence: 0.4,
7365
- reason: "Modern macOS UA but SF Pro font not detected"
7366
- });
7367
- }
7368
- if (ua.includes("linux") && !ua.includes("android") && fontsInfo.hasDejaVuSans === false && count > 5) {
7369
- detections.push({
7370
- category: "bot",
7371
- score: 0.4,
7372
7435
  confidence: 0.5,
7373
- reason: "Linux UA but DejaVu Sans font not detected"
7374
- });
7436
+ reason: `Font set contradicts platform (macOS faces while claiming ${platform})`
7437
+ }];
7375
7438
  }
7376
- return detections;
7439
+ return [];
7377
7440
  }
7378
7441
  var PERMISSION_API_KEYS = [
7379
7442
  "hasPermissionsAPI",
@@ -7423,14 +7486,14 @@ function analyzeDOMRect(domRectInfo) {
7423
7486
  }
7424
7487
  return detections;
7425
7488
  }
7426
- function analyzeAdvancedSignals(signals, userAgent) {
7489
+ function analyzeAdvancedSignals(signals) {
7427
7490
  const detections = [];
7428
7491
  const env = signals.environmental ?? {};
7429
7492
  if (env.webrtcInfo) detections.push(...analyzeWebRTC(env.webrtcInfo));
7430
7493
  if (env.speechInfo) detections.push(...analyzeSpeechAPI(env.speechInfo));
7431
7494
  if (env.workerConsistency) detections.push(...analyzeWorkerConsistency(env.workerConsistency));
7432
7495
  if (env.cssMediaQueries) detections.push(...analyzeCSSMediaQueries(env.cssMediaQueries, signals));
7433
- if (env.fontsInfo) detections.push(...analyzeFonts(env.fontsInfo, userAgent));
7496
+ if (env.fontsInfo) detections.push(...analyzeFonts(env.fontsInfo, env.navigator?.platform));
7434
7497
  if (env.permissionsInfo) detections.push(...analyzePermissions(env.permissionsInfo));
7435
7498
  if (env.domRectFingerprint) detections.push(...analyzeDOMRect(env.domRectFingerprint));
7436
7499
  if (env.audioInfo) detections.push(...analyzeAudioContext(env.audioInfo));
@@ -7489,12 +7552,13 @@ var DetectionEngine = class {
7489
7552
  reason: "No PoW solution provided"
7490
7553
  });
7491
7554
  }
7555
+ const widgetInteraction = context.widgetInteraction !== false;
7492
7556
  detections.push(
7493
- ...detectVisionAI(signals),
7557
+ ...detectVisionAI(signals, widgetInteraction),
7494
7558
  ...detectHeadless(signals, userAgent),
7495
7559
  ...detectAutomation(signals),
7496
7560
  ...detectCDP(signals),
7497
- ...detectBehavioral(signals),
7561
+ ...detectBehavioral(signals, widgetInteraction),
7498
7562
  ...detectTouchAuthenticity(signals, userAgent),
7499
7563
  ...detectSensorEntropy(signals, userAgent),
7500
7564
  ...detectTouchKinematics(signals),
@@ -7519,17 +7583,19 @@ var DetectionEngine = class {
7519
7583
  if (ja4) detections.push(...checkJA4Fingerprint(ja4));
7520
7584
  }
7521
7585
  if (signals.formAnalysis) {
7522
- detections.push(...analyzeFormInteraction(signals.formAnalysis));
7586
+ detections.push(...analyzeFormInteraction(signals.formAnalysis, signals.behavioral));
7523
7587
  }
7524
- detections.push(...analyzeAdvancedSignals(signals, userAgent));
7588
+ detections.push(...analyzeAdvancedSignals(signals));
7525
7589
  const categoryScores = calculateCategoryScores(detections, this.weights);
7526
7590
  const score = calculateFinalScore(categoryScores, this.weights);
7591
+ const scrollObservation = observeScrollJump(signals.behavioral);
7527
7592
  return {
7528
7593
  success: score < 0.5,
7529
7594
  score,
7530
7595
  recommendation: recommend(score),
7531
7596
  categoryScores,
7532
7597
  detections,
7598
+ ...scrollObservation ? { observations: [scrollObservation] } : {},
7533
7599
  timestamp: Math.floor(Date.now() / 1e3)
7534
7600
  };
7535
7601
  }
@@ -7754,10 +7820,14 @@ var Captcha = class {
7754
7820
  * signals, and issues a session token on success. Mirrors `runVerification`.
7755
7821
  */
7756
7822
  async verify(input) {
7823
+ return (await this.verifySubmission(input, true)).result;
7824
+ }
7825
+ async verifySubmission(input, widgetInteraction) {
7757
7826
  const { siteKey, ip, userAgent } = input;
7758
7827
  const headers = input.headers ?? {};
7759
7828
  let signals = input.signals ?? {};
7760
7829
  const extraDetections = [];
7830
+ let committedSignals = false;
7761
7831
  const clientSignalsHash = input.powSolution?.signalsHash ?? null;
7762
7832
  if (input.signalsJson && clientSignalsHash) {
7763
7833
  const computed = await sha256Hex(input.signalsJson);
@@ -7770,7 +7840,11 @@ var Captcha = class {
7770
7840
  });
7771
7841
  }
7772
7842
  try {
7773
- signals = JSON.parse(input.signalsJson);
7843
+ const parsed = JSON.parse(input.signalsJson);
7844
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
7845
+ signals = parsed;
7846
+ committedSignals = computed === clientSignalsHash;
7847
+ }
7774
7848
  } catch {
7775
7849
  }
7776
7850
  }
@@ -7797,21 +7871,36 @@ var Captcha = class {
7797
7871
  headers,
7798
7872
  ja3Hash: input.ja3Hash ?? null,
7799
7873
  trustedJA4Headers: this.trustedJA4Headers,
7874
+ widgetInteraction,
7800
7875
  pow,
7801
7876
  extraDetections
7802
7877
  });
7803
- const token = verdict.success ? await this.tokens.issue(ip, siteKey, verdict.score) : null;
7804
- return { ...verdict, token };
7878
+ const proofVerified = pow.valid === true;
7879
+ const success = proofVerified && verdict.success;
7880
+ const token = success ? await this.tokens.issue(ip, siteKey, verdict.score) : null;
7881
+ const recommendation = !proofVerified && verdict.recommendation === "allow" ? "challenge" : verdict.recommendation;
7882
+ return {
7883
+ result: { ...verdict, success, recommendation, token },
7884
+ verifiedSignals: proofVerified && committedSignals && !!pow.nonce && signals.meta?.challengeNonce === pow.nonce
7885
+ };
7805
7886
  }
7806
7887
  /** Invisible-mode scoring — same pipeline, returns a compact result + action. */
7807
7888
  async score(input) {
7808
- const result = await this.verify(input);
7889
+ return (await this.scoreForSession(input)).result;
7890
+ }
7891
+ /** @internal Return the score and whether the server verified the committed signals. */
7892
+ async scoreForSession(input) {
7893
+ const { result, verifiedSignals } = await this.verifySubmission(input, false);
7809
7894
  return {
7810
- success: result.success,
7811
- score: result.score,
7812
- token: result.token,
7813
- action: input.action ?? "",
7814
- recommendation: result.recommendation
7895
+ result: {
7896
+ success: result.success,
7897
+ score: result.score,
7898
+ token: result.token,
7899
+ action: input.action ?? "",
7900
+ recommendation: result.recommendation,
7901
+ ...result.observations ? { observations: result.observations } : {}
7902
+ },
7903
+ verifiedSignals
7815
7904
  };
7816
7905
  }
7817
7906
  /** Verify a previously issued token (single-use, optionally IP-bound). */
@@ -7861,8 +7950,9 @@ function createCaptchaEndpoints(options = {}) {
7861
7950
  }
7862
7951
  if (sub === "/score" && method === "POST") {
7863
7952
  const b = req.body ?? {};
7864
- const result = await captcha.score({
7865
- siteKey: b.siteKey ?? "default",
7953
+ const siteKey = b.siteKey ?? "default";
7954
+ const { result, verifiedSignals } = await captcha.scoreForSession({
7955
+ siteKey,
7866
7956
  ip: req.ip,
7867
7957
  userAgent,
7868
7958
  headers: req.headers,
@@ -7873,20 +7963,28 @@ function createCaptchaEndpoints(options = {}) {
7873
7963
  ja3Hash,
7874
7964
  action: b.action
7875
7965
  });
7876
- if (signalStore && b.sessionId) {
7966
+ const legacyId = typeof b.sessionId === "string" && !b.sessionId.startsWith(CLIENT_RECEIPT_PREFIX) ? b.sessionId || null : null;
7967
+ const response = json(200, { ...result, sessionId: legacyId });
7968
+ if (!signalStore) return response;
7969
+ const at2 = Date.now();
7970
+ const verdict = { score: result.score, recommendation: result.recommendation, at: at2 };
7971
+ if (legacyId) {
7972
+ await signalStore.set({ ...verdict, sessionId: legacyId });
7973
+ return response;
7974
+ }
7975
+ const host = getClientSignalHost(req.headers);
7976
+ const origin = req.headers.origin;
7977
+ if (verifiedSignals && host && (!origin || origin === "https://" + host) && typeof siteKey === "string" && siteKey.length <= 128) {
7978
+ const receipt = randomHex(24);
7877
7979
  await signalStore.set({
7878
- sessionId: b.sessionId,
7879
- score: result.score,
7880
- recommendation: result.recommendation,
7881
- at: Date.now()
7980
+ ...verdict,
7981
+ sessionId: CLIENT_RECEIPT_PREFIX + receipt,
7982
+ receipt: { host, siteKey, expiresAt: at2 + CLIENT_RECEIPT_TTL_MS }
7882
7983
  });
7984
+ response.headers["set-cookie"] = `${CLIENT_RECEIPT_COOKIE}=${receipt}; Path=/; Max-Age=${CLIENT_RECEIPT_TTL_MS / 1e3}; Secure; HttpOnly; SameSite=Lax`;
7985
+ response.headers["cache-control"] = "private, no-store";
7883
7986
  }
7884
- return json(200, {
7885
- ...result,
7886
- // Echoed so the widget can set the cookie the rule reads, without the
7887
- // developer wiring a second endpoint to hand it one.
7888
- sessionId: b.sessionId ?? null
7889
- });
7987
+ return response;
7890
7988
  }
7891
7989
  if (sub === "/token/verify" && method === "POST") {
7892
7990
  const b = req.body ?? {};