@webdecoy/node 0.28.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.
@@ -1470,12 +1470,14 @@ function createFetchGuard(options = {}) {
1470
1470
  },
1471
1471
  async check(request, peer) {
1472
1472
  const url = new URL(request.url);
1473
+ const headers = headerRecord(request.headers);
1474
+ if (!headers.host && !headers[":authority"]) headers.host = url.host;
1473
1475
  const metadata = {
1474
1476
  method: request.method,
1475
1477
  path: url.pathname,
1476
1478
  ip: resolveIP(request, peer),
1477
1479
  user_agent: request.headers.get("user-agent") ?? void 0,
1478
- headers: headerRecord(request.headers),
1480
+ headers,
1479
1481
  query: url.search ? url.search.slice(1) : void 0,
1480
1482
  timestamp: Date.now()
1481
1483
  };
package/dist/index.d.mts CHANGED
@@ -64,6 +64,10 @@ interface BehavioralSignals {
64
64
  touchEvents?: number;
65
65
  pointerHasNonMouseType?: boolean;
66
66
  keyEvents?: number;
67
+ /** Number of completed key holds in the browser's timing summary. */
68
+ keyHoldSamples?: number;
69
+ /** Average hold duration in milliseconds for those samples. */
70
+ keyHoldAvg?: number;
67
71
  /** Count of recent scroll events and largest CSS pixel step between them. */
68
72
  scrollMorphology?: {
69
73
  samples?: number;
@@ -499,8 +503,14 @@ declare function parseUserAgent(ua: string): UserAgentInfo;
499
503
 
500
504
  /** The engine's verdict on one browser session. */
501
505
  interface ClientVerdict {
502
- /** Session id supplied by the browser widget. */
506
+ /** Identifier used by the store. */
503
507
  sessionId: string;
508
+ /** Scope of a receipt issued by the embedded score endpoint. */
509
+ receipt?: {
510
+ host: string;
511
+ siteKey: string;
512
+ expiresAt: number;
513
+ };
504
514
  /** 0–1, higher is more bot-like. */
505
515
  score: number;
506
516
  /** What the engine recommends doing about it. */
@@ -536,14 +546,16 @@ declare class MemoryClientSignalStore implements ClientSignalStore {
536
546
  set(verdict: ClientVerdict): void;
537
547
  get size(): number;
538
548
  }
539
- /** The cookie the widget sets, and the header it will also accept. */
549
+ /** Session references supplied by an existing application integration. */
540
550
  declare const CLIENT_SESSION_COOKIE = "wd_cs";
541
551
  declare const CLIENT_SESSION_HEADER = "x-wd-session";
542
- /** Read the browser session id off a request, cookie first then header. */
552
+ /** Read the server receipt or an application-supplied legacy session id. */
543
553
  declare function readClientSession(headers: Record<string, string>): string | undefined;
544
554
  interface ClientSignalConfig {
545
555
  /** Where verdicts are read from. Must be the store `/score` writes to. */
546
556
  store: ClientSignalStore;
557
+ /** Site key expected by this rule when several site keys share a request host. */
558
+ siteKey?: string;
547
559
  /**
548
560
  * Deny at or above this score, 0–1. The engine's own `recommendation` is used
549
561
  * when this is omitted.
@@ -563,6 +575,7 @@ interface ClientSignalConfig {
563
575
  declare class ClientSignalRule implements Rule {
564
576
  readonly name = "client-signals";
565
577
  private readonly store;
578
+ private readonly siteKey?;
566
579
  private readonly minScore?;
567
580
  private readonly action;
568
581
  private readonly dryRun;
@@ -1667,6 +1680,13 @@ declare class Captcha {
1667
1680
  score(input: VerifyInput & {
1668
1681
  action?: string;
1669
1682
  }): Promise<ScoreResult>;
1683
+ /** @internal Return the score and whether the server verified the committed signals. */
1684
+ scoreForSession(input: VerifyInput & {
1685
+ action?: string;
1686
+ }): Promise<{
1687
+ result: ScoreResult;
1688
+ verifiedSignals: boolean;
1689
+ }>;
1670
1690
  /** Verify a previously issued token (single-use, optionally IP-bound). */
1671
1691
  verifyToken(token: string, ip?: string | null): Promise<TokenVerification>;
1672
1692
  }
package/dist/index.d.ts CHANGED
@@ -64,6 +64,10 @@ interface BehavioralSignals {
64
64
  touchEvents?: number;
65
65
  pointerHasNonMouseType?: boolean;
66
66
  keyEvents?: number;
67
+ /** Number of completed key holds in the browser's timing summary. */
68
+ keyHoldSamples?: number;
69
+ /** Average hold duration in milliseconds for those samples. */
70
+ keyHoldAvg?: number;
67
71
  /** Count of recent scroll events and largest CSS pixel step between them. */
68
72
  scrollMorphology?: {
69
73
  samples?: number;
@@ -499,8 +503,14 @@ declare function parseUserAgent(ua: string): UserAgentInfo;
499
503
 
500
504
  /** The engine's verdict on one browser session. */
501
505
  interface ClientVerdict {
502
- /** Session id supplied by the browser widget. */
506
+ /** Identifier used by the store. */
503
507
  sessionId: string;
508
+ /** Scope of a receipt issued by the embedded score endpoint. */
509
+ receipt?: {
510
+ host: string;
511
+ siteKey: string;
512
+ expiresAt: number;
513
+ };
504
514
  /** 0–1, higher is more bot-like. */
505
515
  score: number;
506
516
  /** What the engine recommends doing about it. */
@@ -536,14 +546,16 @@ declare class MemoryClientSignalStore implements ClientSignalStore {
536
546
  set(verdict: ClientVerdict): void;
537
547
  get size(): number;
538
548
  }
539
- /** The cookie the widget sets, and the header it will also accept. */
549
+ /** Session references supplied by an existing application integration. */
540
550
  declare const CLIENT_SESSION_COOKIE = "wd_cs";
541
551
  declare const CLIENT_SESSION_HEADER = "x-wd-session";
542
- /** Read the browser session id off a request, cookie first then header. */
552
+ /** Read the server receipt or an application-supplied legacy session id. */
543
553
  declare function readClientSession(headers: Record<string, string>): string | undefined;
544
554
  interface ClientSignalConfig {
545
555
  /** Where verdicts are read from. Must be the store `/score` writes to. */
546
556
  store: ClientSignalStore;
557
+ /** Site key expected by this rule when several site keys share a request host. */
558
+ siteKey?: string;
547
559
  /**
548
560
  * Deny at or above this score, 0–1. The engine's own `recommendation` is used
549
561
  * when this is omitted.
@@ -563,6 +575,7 @@ interface ClientSignalConfig {
563
575
  declare class ClientSignalRule implements Rule {
564
576
  readonly name = "client-signals";
565
577
  private readonly store;
578
+ private readonly siteKey?;
566
579
  private readonly minScore?;
567
580
  private readonly action;
568
581
  private readonly dryRun;
@@ -1667,6 +1680,13 @@ declare class Captcha {
1667
1680
  score(input: VerifyInput & {
1668
1681
  action?: string;
1669
1682
  }): Promise<ScoreResult>;
1683
+ /** @internal Return the score and whether the server verified the committed signals. */
1684
+ scoreForSession(input: VerifyInput & {
1685
+ action?: string;
1686
+ }): Promise<{
1687
+ result: ScoreResult;
1688
+ verifiedSignals: boolean;
1689
+ }>;
1670
1690
  /** Verify a previously issued token (single-use, optionally IP-bound). */
1671
1691
  verifyToken(token: string, ip?: string | null): Promise<TokenVerification>;
1672
1692
  }
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
  };
@@ -6129,6 +6152,33 @@ function recommend(finalScore) {
6129
6152
  return "block";
6130
6153
  }
6131
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
+
6132
6182
  // src/detection/detectors/pointer-evidence.ts
6133
6183
  function isTouchModality(behavioral) {
6134
6184
  const touchEvents = behavioral.touchEvents ?? 0;
@@ -6151,7 +6201,7 @@ function detectVisionAI(signals, widgetInteraction = true) {
6151
6201
  const trajectory = b.trajectoryLength ?? 0;
6152
6202
  const approachPts = b.approachPoints ?? 0;
6153
6203
  const isTouchUser = isTouchModality(b);
6154
- const isKeyboardUser = (b.keyEvents ?? 0) >= 2 && totalPoints === 0;
6204
+ const isKeyboardUser = classifyKeyboardInput(signals) === "keyboard-only";
6155
6205
  const usesMouse = !isTouchUser && !isKeyboardUser;
6156
6206
  if (totalPoints < 5 && trajectory < 10 && usesMouse) {
6157
6207
  detections.push({
@@ -6398,16 +6448,23 @@ function detectBehavioral(signals, widgetInteraction = true) {
6398
6448
  const totalPoints = b.totalPoints ?? 0;
6399
6449
  const trajectory = b.trajectoryLength ?? 0;
6400
6450
  const isTouchUser = isTouchModality(b);
6401
- const isKeyboardUser = (b.keyEvents ?? 0) >= 2 && totalPoints === 0;
6451
+ const keyboard = classifyKeyboardInput(signals);
6402
6452
  const humanMovement = hasHumanMovementMarkers(b);
6403
- if (totalPoints === 0 && !isTouchUser && !isKeyboardUser) {
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) {
6404
6461
  detections.push({
6405
6462
  category: "behavioral",
6406
6463
  score: 0.8,
6407
6464
  confidence: 0.9,
6408
6465
  reason: "Zero mouse, touch, or keyboard events recorded"
6409
6466
  });
6410
- } else if (totalPoints < 10 && !isTouchUser && !isKeyboardUser && trajectory < 30) {
6467
+ } else if (totalPoints < 10 && !isTouchUser && keyboard === null && trajectory < 30) {
6411
6468
  detections.push({
6412
6469
  category: "behavioral",
6413
6470
  score: 0.6,
@@ -7763,13 +7820,14 @@ var Captcha = class {
7763
7820
  * signals, and issues a session token on success. Mirrors `runVerification`.
7764
7821
  */
7765
7822
  async verify(input) {
7766
- return this.verifySubmission(input, true);
7823
+ return (await this.verifySubmission(input, true)).result;
7767
7824
  }
7768
7825
  async verifySubmission(input, widgetInteraction) {
7769
7826
  const { siteKey, ip, userAgent } = input;
7770
7827
  const headers = input.headers ?? {};
7771
7828
  let signals = input.signals ?? {};
7772
7829
  const extraDetections = [];
7830
+ let committedSignals = false;
7773
7831
  const clientSignalsHash = input.powSolution?.signalsHash ?? null;
7774
7832
  if (input.signalsJson && clientSignalsHash) {
7775
7833
  const computed = await sha256Hex(input.signalsJson);
@@ -7782,7 +7840,11 @@ var Captcha = class {
7782
7840
  });
7783
7841
  }
7784
7842
  try {
7785
- 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
+ }
7786
7848
  } catch {
7787
7849
  }
7788
7850
  }
@@ -7817,18 +7879,28 @@ var Captcha = class {
7817
7879
  const success = proofVerified && verdict.success;
7818
7880
  const token = success ? await this.tokens.issue(ip, siteKey, verdict.score) : null;
7819
7881
  const recommendation = !proofVerified && verdict.recommendation === "allow" ? "challenge" : verdict.recommendation;
7820
- return { ...verdict, success, recommendation, token };
7882
+ return {
7883
+ result: { ...verdict, success, recommendation, token },
7884
+ verifiedSignals: proofVerified && committedSignals && !!pow.nonce && signals.meta?.challengeNonce === pow.nonce
7885
+ };
7821
7886
  }
7822
7887
  /** Invisible-mode scoring — same pipeline, returns a compact result + action. */
7823
7888
  async score(input) {
7824
- const result = await this.verifySubmission(input, false);
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);
7825
7894
  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 } : {}
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
7832
7904
  };
7833
7905
  }
7834
7906
  /** Verify a previously issued token (single-use, optionally IP-bound). */
@@ -7878,8 +7950,9 @@ function createCaptchaEndpoints(options = {}) {
7878
7950
  }
7879
7951
  if (sub === "/score" && method === "POST") {
7880
7952
  const b = req.body ?? {};
7881
- const result = await captcha.score({
7882
- siteKey: b.siteKey ?? "default",
7953
+ const siteKey = b.siteKey ?? "default";
7954
+ const { result, verifiedSignals } = await captcha.scoreForSession({
7955
+ siteKey,
7883
7956
  ip: req.ip,
7884
7957
  userAgent,
7885
7958
  headers: req.headers,
@@ -7890,20 +7963,28 @@ function createCaptchaEndpoints(options = {}) {
7890
7963
  ja3Hash,
7891
7964
  action: b.action
7892
7965
  });
7893
- 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);
7894
7979
  await signalStore.set({
7895
- sessionId: b.sessionId,
7896
- score: result.score,
7897
- recommendation: result.recommendation,
7898
- at: Date.now()
7980
+ ...verdict,
7981
+ sessionId: CLIENT_RECEIPT_PREFIX + receipt,
7982
+ receipt: { host, siteKey, expiresAt: at2 + CLIENT_RECEIPT_TTL_MS }
7899
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";
7900
7986
  }
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
- });
7987
+ return response;
7907
7988
  }
7908
7989
  if (sub === "/token/verify" && method === "POST") {
7909
7990
  const b = req.body ?? {};
package/dist/index.mjs CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  resolveGateEnv,
12
12
  ruleBlockResponse,
13
13
  shouldSkipPath
14
- } from "./chunk-P6IWJ7K5.mjs";
14
+ } from "./chunk-VPPTUL5K.mjs";
15
15
  import {
16
16
  ATTACK_SIGNATURE_IDS,
17
17
  AgentVerifier,
@@ -103,25 +103,43 @@ var MemoryClientSignalStore = class {
103
103
  };
104
104
  var CLIENT_SESSION_COOKIE = "wd_cs";
105
105
  var CLIENT_SESSION_HEADER = "x-wd-session";
106
- function readClientSession(headers) {
107
- const cookie = headers["cookie"];
108
- if (cookie) {
109
- for (const part of cookie.split(";")) {
110
- const eq = part.indexOf("=");
111
- if (eq < 0) continue;
112
- if (part.slice(0, eq).trim() === CLIENT_SESSION_COOKIE) {
113
- const value = part.slice(eq + 1).trim();
114
- if (value) return value;
115
- }
106
+ var CLIENT_RECEIPT_COOKIE = "__Host-wd_cs";
107
+ var CLIENT_RECEIPT_PREFIX = "receipt:";
108
+ var CLIENT_RECEIPT_TTL_MS = 15 * 6e4;
109
+ function getClientSignalHost(headers) {
110
+ const value = headers.host ?? headers[":authority"];
111
+ if (typeof value !== "string" || value.length > 255 || !/^[a-z0-9.:[\]-]+$/i.test(value)) {
112
+ return void 0;
113
+ }
114
+ try {
115
+ return new URL("https://" + value).host || void 0;
116
+ } catch {
117
+ return void 0;
118
+ }
119
+ }
120
+ function readCookie(header, name) {
121
+ if (!header) return void 0;
122
+ for (const part of header.split(";")) {
123
+ const eq = part.indexOf("=");
124
+ if (eq >= 0 && part.slice(0, eq).trim() === name) {
125
+ return part.slice(eq + 1).trim();
116
126
  }
117
127
  }
118
- const header = headers[CLIENT_SESSION_HEADER];
119
- return header || void 0;
128
+ return void 0;
129
+ }
130
+ function readClientSession(headers) {
131
+ const receipt = readCookie(headers.cookie, CLIENT_RECEIPT_COOKIE);
132
+ if (receipt !== void 0) {
133
+ return /^[0-9a-f]{48}$/.test(receipt) ? CLIENT_RECEIPT_PREFIX + receipt : void 0;
134
+ }
135
+ const legacy = readCookie(headers.cookie, CLIENT_SESSION_COOKIE) || headers[CLIENT_SESSION_HEADER];
136
+ return legacy && !legacy.startsWith(CLIENT_RECEIPT_PREFIX) ? legacy : void 0;
120
137
  }
121
138
  var ClientSignalRule = class {
122
139
  constructor(config) {
123
140
  this.name = "client-signals";
124
141
  this.store = config.store;
142
+ this.siteKey = config.siteKey;
125
143
  this.minScore = config.minScore;
126
144
  this.action = config.action ?? "DENY";
127
145
  this.dryRun = config.dryRun ?? false;
@@ -147,7 +165,10 @@ var ClientSignalRule = class {
147
165
  };
148
166
  }
149
167
  const verdict = this.store.sync ? this.store.get(sessionId) : context.prepared?.[this.name];
150
- if (!verdict) {
168
+ const issuedReceipt = sessionId.startsWith(CLIENT_RECEIPT_PREFIX);
169
+ const receipt = verdict?.receipt;
170
+ const usableReceipt = receipt && Date.now() < receipt.expiresAt && getClientSignalHost(context.headers) === receipt.host && (this.siteKey === void 0 || this.siteKey === receipt.siteKey);
171
+ if (!verdict || verdict.sessionId !== sessionId || (issuedReceipt || this.siteKey !== void 0) && !usableReceipt) {
151
172
  return {
152
173
  action: "ALLOW",
153
174
  rule: this.name,
@@ -170,7 +191,7 @@ var ClientSignalRule = class {
170
191
  metadata: {
171
192
  score: verdict.score,
172
193
  recommendation: verdict.recommendation,
173
- sessionId,
194
+ ...issuedReceipt ? {} : { sessionId },
174
195
  dryRun: this.dryRun
175
196
  }
176
197
  };
@@ -382,6 +403,33 @@ function recommend(finalScore) {
382
403
  return "block";
383
404
  }
384
405
 
406
+ // src/detection/detectors/keyboard-input.ts
407
+ var MIN_KEY_HOLD_SAMPLES = 3;
408
+ var MAX_KEY_HOLD_SAMPLES = 200;
409
+ var SHORT_KEY_HOLD_MS = 20;
410
+ var MAX_KEY_HOLD_MS = 2e3;
411
+ function classifyKeyboardInput(signals) {
412
+ const behavioral = signals.behavioral ?? {};
413
+ const keyEvents = behavioral.keyEvents ?? 0;
414
+ if (!Number.isFinite(keyEvents) || keyEvents < 2 || (behavioral.totalPoints ?? 0) !== 0) {
415
+ return null;
416
+ }
417
+ const { keyHoldSamples = 0, keyHoldAvg = 0 } = behavioral;
418
+ 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;
419
+ let count = validSummary ? keyHoldSamples : 0;
420
+ let duration = count > 0 ? count * keyHoldAvg : 0;
421
+ for (const field of Object.values(signals.formAnalysis?.textareaKeyboard ?? {})) {
422
+ if (!Array.isArray(field?.dwellTimes)) continue;
423
+ for (const dwell of field.dwellTimes) {
424
+ if (typeof dwell === "number" && dwell > 0 && dwell < MAX_KEY_HOLD_MS) {
425
+ count++;
426
+ duration += dwell;
427
+ }
428
+ }
429
+ }
430
+ return count >= MIN_KEY_HOLD_SAMPLES && duration / count < SHORT_KEY_HOLD_MS ? "short-key-holds" : "keyboard-only";
431
+ }
432
+
385
433
  // src/detection/detectors/pointer-evidence.ts
386
434
  function isTouchModality(behavioral) {
387
435
  const touchEvents = behavioral.touchEvents ?? 0;
@@ -404,7 +452,7 @@ function detectVisionAI(signals, widgetInteraction = true) {
404
452
  const trajectory = b.trajectoryLength ?? 0;
405
453
  const approachPts = b.approachPoints ?? 0;
406
454
  const isTouchUser = isTouchModality(b);
407
- const isKeyboardUser = (b.keyEvents ?? 0) >= 2 && totalPoints === 0;
455
+ const isKeyboardUser = classifyKeyboardInput(signals) === "keyboard-only";
408
456
  const usesMouse = !isTouchUser && !isKeyboardUser;
409
457
  if (totalPoints < 5 && trajectory < 10 && usesMouse) {
410
458
  detections.push({
@@ -651,16 +699,23 @@ function detectBehavioral(signals, widgetInteraction = true) {
651
699
  const totalPoints = b.totalPoints ?? 0;
652
700
  const trajectory = b.trajectoryLength ?? 0;
653
701
  const isTouchUser = isTouchModality(b);
654
- const isKeyboardUser = (b.keyEvents ?? 0) >= 2 && totalPoints === 0;
702
+ const keyboard = classifyKeyboardInput(signals);
655
703
  const humanMovement = hasHumanMovementMarkers(b);
656
- if (totalPoints === 0 && !isTouchUser && !isKeyboardUser) {
704
+ if (keyboard === "short-key-holds" && !isTouchUser) {
705
+ detections.push({
706
+ category: "behavioral",
707
+ score: 0.8,
708
+ confidence: 0.9,
709
+ reason: "Keyboard-only input has unusually short key holds"
710
+ });
711
+ } else if (totalPoints === 0 && !isTouchUser && keyboard === null) {
657
712
  detections.push({
658
713
  category: "behavioral",
659
714
  score: 0.8,
660
715
  confidence: 0.9,
661
716
  reason: "Zero mouse, touch, or keyboard events recorded"
662
717
  });
663
- } else if (totalPoints < 10 && !isTouchUser && !isKeyboardUser && trajectory < 30) {
718
+ } else if (totalPoints < 10 && !isTouchUser && keyboard === null && trajectory < 30) {
664
719
  detections.push({
665
720
  category: "behavioral",
666
721
  score: 0.6,
@@ -2016,13 +2071,14 @@ var Captcha = class {
2016
2071
  * signals, and issues a session token on success. Mirrors `runVerification`.
2017
2072
  */
2018
2073
  async verify(input) {
2019
- return this.verifySubmission(input, true);
2074
+ return (await this.verifySubmission(input, true)).result;
2020
2075
  }
2021
2076
  async verifySubmission(input, widgetInteraction) {
2022
2077
  const { siteKey, ip, userAgent } = input;
2023
2078
  const headers = input.headers ?? {};
2024
2079
  let signals = input.signals ?? {};
2025
2080
  const extraDetections = [];
2081
+ let committedSignals = false;
2026
2082
  const clientSignalsHash = input.powSolution?.signalsHash ?? null;
2027
2083
  if (input.signalsJson && clientSignalsHash) {
2028
2084
  const computed = await sha256Hex(input.signalsJson);
@@ -2035,7 +2091,11 @@ var Captcha = class {
2035
2091
  });
2036
2092
  }
2037
2093
  try {
2038
- signals = JSON.parse(input.signalsJson);
2094
+ const parsed = JSON.parse(input.signalsJson);
2095
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
2096
+ signals = parsed;
2097
+ committedSignals = computed === clientSignalsHash;
2098
+ }
2039
2099
  } catch {
2040
2100
  }
2041
2101
  }
@@ -2070,18 +2130,28 @@ var Captcha = class {
2070
2130
  const success = proofVerified && verdict.success;
2071
2131
  const token = success ? await this.tokens.issue(ip, siteKey, verdict.score) : null;
2072
2132
  const recommendation = !proofVerified && verdict.recommendation === "allow" ? "challenge" : verdict.recommendation;
2073
- return { ...verdict, success, recommendation, token };
2133
+ return {
2134
+ result: { ...verdict, success, recommendation, token },
2135
+ verifiedSignals: proofVerified && committedSignals && !!pow.nonce && signals.meta?.challengeNonce === pow.nonce
2136
+ };
2074
2137
  }
2075
2138
  /** Invisible-mode scoring — same pipeline, returns a compact result + action. */
2076
2139
  async score(input) {
2077
- const result = await this.verifySubmission(input, false);
2140
+ return (await this.scoreForSession(input)).result;
2141
+ }
2142
+ /** @internal Return the score and whether the server verified the committed signals. */
2143
+ async scoreForSession(input) {
2144
+ const { result, verifiedSignals } = await this.verifySubmission(input, false);
2078
2145
  return {
2079
- success: result.success,
2080
- score: result.score,
2081
- token: result.token,
2082
- action: input.action ?? "",
2083
- recommendation: result.recommendation,
2084
- ...result.observations ? { observations: result.observations } : {}
2146
+ result: {
2147
+ success: result.success,
2148
+ score: result.score,
2149
+ token: result.token,
2150
+ action: input.action ?? "",
2151
+ recommendation: result.recommendation,
2152
+ ...result.observations ? { observations: result.observations } : {}
2153
+ },
2154
+ verifiedSignals
2085
2155
  };
2086
2156
  }
2087
2157
  /** Verify a previously issued token (single-use, optionally IP-bound). */
@@ -2131,8 +2201,9 @@ function createCaptchaEndpoints(options = {}) {
2131
2201
  }
2132
2202
  if (sub === "/score" && method === "POST") {
2133
2203
  const b = req.body ?? {};
2134
- const result = await captcha.score({
2135
- siteKey: b.siteKey ?? "default",
2204
+ const siteKey = b.siteKey ?? "default";
2205
+ const { result, verifiedSignals } = await captcha.scoreForSession({
2206
+ siteKey,
2136
2207
  ip: req.ip,
2137
2208
  userAgent,
2138
2209
  headers: req.headers,
@@ -2143,20 +2214,28 @@ function createCaptchaEndpoints(options = {}) {
2143
2214
  ja3Hash,
2144
2215
  action: b.action
2145
2216
  });
2146
- if (signalStore && b.sessionId) {
2217
+ const legacyId = typeof b.sessionId === "string" && !b.sessionId.startsWith(CLIENT_RECEIPT_PREFIX) ? b.sessionId || null : null;
2218
+ const response = json(200, { ...result, sessionId: legacyId });
2219
+ if (!signalStore) return response;
2220
+ const at = Date.now();
2221
+ const verdict = { score: result.score, recommendation: result.recommendation, at };
2222
+ if (legacyId) {
2223
+ await signalStore.set({ ...verdict, sessionId: legacyId });
2224
+ return response;
2225
+ }
2226
+ const host = getClientSignalHost(req.headers);
2227
+ const origin = req.headers.origin;
2228
+ if (verifiedSignals && host && (!origin || origin === "https://" + host) && typeof siteKey === "string" && siteKey.length <= 128) {
2229
+ const receipt = randomHex(24);
2147
2230
  await signalStore.set({
2148
- sessionId: b.sessionId,
2149
- score: result.score,
2150
- recommendation: result.recommendation,
2151
- at: Date.now()
2231
+ ...verdict,
2232
+ sessionId: CLIENT_RECEIPT_PREFIX + receipt,
2233
+ receipt: { host, siteKey, expiresAt: at + CLIENT_RECEIPT_TTL_MS }
2152
2234
  });
2235
+ response.headers["set-cookie"] = `${CLIENT_RECEIPT_COOKIE}=${receipt}; Path=/; Max-Age=${CLIENT_RECEIPT_TTL_MS / 1e3}; Secure; HttpOnly; SameSite=Lax`;
2236
+ response.headers["cache-control"] = "private, no-store";
2153
2237
  }
2154
- return json(200, {
2155
- ...result,
2156
- // Echoed so the widget can set the cookie the rule reads, without the
2157
- // developer wiring a second endpoint to hand it one.
2158
- sessionId: b.sessionId ?? null
2159
- });
2238
+ return response;
2160
2239
  }
2161
2240
  if (sub === "/token/verify" && method === "POST") {
2162
2241
  const b = req.body ?? {};
package/dist/vercel.js CHANGED
@@ -4524,12 +4524,14 @@ function createFetchGuard(options = {}) {
4524
4524
  },
4525
4525
  async check(request, peer) {
4526
4526
  const url = new URL(request.url);
4527
+ const headers = headerRecord(request.headers);
4528
+ if (!headers.host && !headers[":authority"]) headers.host = url.host;
4527
4529
  const metadata = {
4528
4530
  method: request.method,
4529
4531
  path: url.pathname,
4530
4532
  ip: resolveIP(request, peer),
4531
4533
  user_agent: request.headers.get("user-agent") ?? void 0,
4532
- headers: headerRecord(request.headers),
4534
+ headers,
4533
4535
  query: url.search ? url.search.slice(1) : void 0,
4534
4536
  timestamp: Date.now()
4535
4537
  };
package/dist/vercel.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createClearanceGate,
3
3
  createDetectAndGate
4
- } from "./chunk-P6IWJ7K5.mjs";
4
+ } from "./chunk-VPPTUL5K.mjs";
5
5
  import "./chunk-32TEUD5K.mjs";
6
6
 
7
7
  // src/vercel.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webdecoy/node",
3
- "version": "0.28.0",
3
+ "version": "0.29.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",