@webdecoy/node 0.4.0 → 0.5.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
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,23 +15,18 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
20
  // src/index.ts
31
21
  var index_exports = {};
32
22
  __export(index_exports, {
23
+ AgentVerifier: () => AgentVerifier,
33
24
  Captcha: () => Captcha,
25
+ DEFAULT_SIGNED_AGENT_DIRECTORIES: () => DEFAULT_SIGNED_AGENT_DIRECTORIES,
34
26
  DEFAULT_TRIPWIRE_PATHS: () => DEFAULT_TRIPWIRE_PATHS,
35
27
  DEFAULT_WEIGHTS: () => DEFAULT_WEIGHTS,
36
28
  DetectionEngine: () => DetectionEngine,
29
+ DirectoryCache: () => DirectoryCache,
37
30
  FilterRule: () => FilterRule,
38
31
  InMemoryChallengeStore: () => InMemoryChallengeStore,
39
32
  InMemoryFingerprintStore: () => InMemoryFingerprintStore,
@@ -44,9 +37,11 @@ __export(index_exports, {
44
37
  RuleEngine: () => RuleEngine,
45
38
  TokenManager: () => TokenManager,
46
39
  TripwireRule: () => TripwireRule,
40
+ WebBotAuthRule: () => WebBotAuthRule,
47
41
  WebDecoy: () => WebDecoy,
48
42
  calculateCategoryScores: () => calculateCategoryScores,
49
43
  calculateFinalScore: () => calculateFinalScore,
44
+ createAgentVerifier: () => createAgentVerifier,
50
45
  createCaptchaEndpoints: () => createCaptchaEndpoints,
51
46
  filter: () => filter,
52
47
  honeytoken: () => honeytoken,
@@ -56,97 +51,107 @@ __export(index_exports, {
56
51
  rateLimit: () => rateLimit,
57
52
  recommend: () => recommend,
58
53
  resolveSecret: () => resolveSecret,
59
- tripwire: () => tripwire
54
+ tripwire: () => tripwire,
55
+ webBotAuth: () => webBotAuth
60
56
  });
61
57
  module.exports = __toCommonJS(index_exports);
62
58
 
63
59
  // src/client.ts
64
- var import_axios = __toESM(require("axios"));
65
- var import_https = __toESM(require("https"));
66
60
  var WebDecoyClient = class {
67
61
  constructor(config) {
68
62
  this.config = config;
69
- const httpsAgent = new import_https.default.Agent({
70
- rejectUnauthorized: config.tlsRejectUnauthorized
71
- });
72
- this.axios = import_axios.default.create({
73
- baseURL: config.apiUrl,
74
- timeout: config.timeout,
75
- headers: {
76
- "Content-Type": "application/json",
77
- Authorization: `Bearer ${config.apiKey}`,
78
- "User-Agent": "webdecoy-node-sdk/0.1.0"
79
- },
80
- httpsAgent
81
- });
82
- if (config.debug) {
83
- this.axios.interceptors.request.use((request) => {
84
- console.log("[WebDecoy] Request:", {
85
- method: request.method,
86
- url: request.url,
87
- data: request.data
88
- });
89
- return request;
63
+ this.baseUrl = config.apiUrl.replace(/\/+$/, "");
64
+ this.headers = {
65
+ "Content-Type": "application/json",
66
+ Authorization: `Bearer ${config.apiKey}`,
67
+ "User-Agent": "webdecoy-node-sdk/0.1.0"
68
+ };
69
+ if (config.tlsRejectUnauthorized === false && config.debug) {
70
+ console.warn(
71
+ "[WebDecoy] tlsRejectUnauthorized=false is not supported by the fetch transport and is ignored; for local self-signed certs, trust your CA via NODE_EXTRA_CA_CERTS=/path/to/ca.pem."
72
+ );
73
+ }
74
+ }
75
+ async request(method, path, body) {
76
+ const controller = new AbortController();
77
+ const timer = setTimeout(() => controller.abort(), this.config.timeout);
78
+ if (typeof timer.unref === "function") {
79
+ timer.unref();
80
+ }
81
+ if (this.config.debug) {
82
+ console.log("[WebDecoy] Request:", { method, url: this.baseUrl + path, data: body });
83
+ }
84
+ try {
85
+ const response = await fetch(this.baseUrl + path, {
86
+ method,
87
+ headers: this.headers,
88
+ body: body === void 0 ? void 0 : JSON.stringify(body),
89
+ signal: controller.signal
90
90
  });
91
- this.axios.interceptors.response.use(
92
- (response) => {
93
- console.log("[WebDecoy] Response:", {
94
- status: response.status,
95
- data: response.data
96
- });
97
- return response;
98
- },
99
- (error) => {
100
- console.error("[WebDecoy] Error:", {
101
- message: error.message,
102
- response: error.response?.data
103
- });
104
- return Promise.reject(error);
91
+ let data;
92
+ const text = await response.text();
93
+ if (text) {
94
+ try {
95
+ data = JSON.parse(text);
96
+ } catch {
97
+ data = void 0;
105
98
  }
106
- );
99
+ }
100
+ if (this.config.debug) {
101
+ console.log("[WebDecoy] Response:", { status: response.status, data });
102
+ }
103
+ return { status: response.status, data };
104
+ } catch (error) {
105
+ if (this.config.debug) {
106
+ console.error("[WebDecoy] Error:", {
107
+ message: error instanceof Error ? error.message : String(error)
108
+ });
109
+ }
110
+ throw error;
111
+ } finally {
112
+ clearTimeout(timer);
107
113
  }
108
114
  }
109
115
  /**
110
116
  * Send a detection request to the ingest service
111
117
  */
112
118
  async detect(request) {
119
+ let response;
113
120
  try {
114
- const response = await this.axios.post(
121
+ response = await this.request(
122
+ "POST",
115
123
  "/api/v1/sdk/detect",
116
124
  request
117
125
  );
118
- return response.data;
119
126
  } catch (error) {
120
- if (import_axios.default.isAxiosError(error)) {
121
- const axiosError = error;
122
- if (axiosError.response?.status === 401) {
123
- throw new Error("Invalid API key. Please check your Web Decoy configuration.");
124
- }
125
- if (axiosError.response?.status === 429) {
126
- throw new Error("Rate limit exceeded. Please try again later.");
127
- }
128
- if (axiosError.response?.data?.error || axiosError.response?.data?.message) {
129
- throw new Error(
130
- axiosError.response.data.error || axiosError.response.data.message || "API error"
131
- );
132
- }
133
- if (axiosError.code === "ECONNABORTED") {
134
- throw new Error("Request timeout. The Web Decoy service did not respond in time.");
135
- }
136
- if (axiosError.code === "ENOTFOUND" || axiosError.code === "ECONNREFUSED") {
137
- throw new Error("Unable to connect to Web Decoy service. Please check your network.");
138
- }
139
- throw new Error(`API request failed: ${axiosError.message}`);
127
+ if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) {
128
+ throw new Error("Request timeout. The Web Decoy service did not respond in time.");
129
+ }
130
+ if (error instanceof TypeError) {
131
+ throw new Error("Unable to connect to Web Decoy service. Please check your network.");
140
132
  }
141
133
  throw error;
142
134
  }
135
+ if (response.status === 401) {
136
+ throw new Error("Invalid API key. Please check your Web Decoy configuration.");
137
+ }
138
+ if (response.status === 429) {
139
+ throw new Error("Rate limit exceeded. Please try again later.");
140
+ }
141
+ if (response.status >= 400) {
142
+ if (response.data?.error || response.data?.message) {
143
+ throw new Error(response.data.error || response.data.message || "API error");
144
+ }
145
+ throw new Error(`API request failed: HTTP ${response.status}`);
146
+ }
147
+ return response.data;
143
148
  }
144
149
  /**
145
150
  * Send violation events to the ingest service
146
151
  */
147
152
  async sendViolations(events) {
148
153
  try {
149
- await this.axios.post("/api/v1/sdk/violations/batch", { events });
154
+ await this.request("POST", "/api/v1/sdk/violations/batch", { events });
150
155
  } catch (error) {
151
156
  if (this.config.debug) {
152
157
  console.error("[WebDecoy] Failed to send violations:", error);
@@ -158,10 +163,12 @@ var WebDecoyClient = class {
158
163
  */
159
164
  async getIPEnrichment(ip) {
160
165
  try {
161
- const response = await this.axios.get(
166
+ const response = await this.request(
167
+ "GET",
162
168
  `/api/v1/sdk/ip/${encodeURIComponent(ip)}/enrichment`
163
169
  );
164
- return response.data;
170
+ if (response.status >= 400) return null;
171
+ return response.data ?? null;
165
172
  } catch (error) {
166
173
  if (this.config.debug) {
167
174
  console.error("[WebDecoy] Failed to get IP enrichment:", error);
@@ -325,6 +332,18 @@ function analyzeRequest(metadata) {
325
332
  }
326
333
 
327
334
  // src/rules/rule-engine.ts
335
+ function extractClearance(headers) {
336
+ const cookie = headers["cookie"];
337
+ if (!cookie) return void 0;
338
+ for (const part of cookie.split(";")) {
339
+ const eq = part.indexOf("=");
340
+ if (eq < 0) continue;
341
+ if (part.slice(0, eq).trim() === "wd_clearance") {
342
+ return part.slice(eq + 1).trim() || void 0;
343
+ }
344
+ }
345
+ return void 0;
346
+ }
328
347
  var RuleEngine = class {
329
348
  constructor(rules) {
330
349
  this.rules = rules;
@@ -347,6 +366,7 @@ var RuleEngine = class {
347
366
  method: context.method,
348
367
  userAgent: context.userAgent,
349
368
  reason: result.reason,
369
+ clearance: result.rule === "tripwire" ? extractClearance(context.headers) : void 0,
350
370
  metadata: result.metadata,
351
371
  dryRun: result.metadata?.dryRun === true,
352
372
  timestamp: new Date(context.timestamp).toISOString()
@@ -484,12 +504,603 @@ var IPEnrichmentClient = class {
484
504
  }
485
505
  };
486
506
 
507
+ // src/agent/thumbprint.ts
508
+ var encoder = new TextEncoder();
509
+ async function rsaThumbprint(n, e) {
510
+ return digest(`{"e":${JSON.stringify(e)},"kty":"RSA","n":${JSON.stringify(n)}}`);
511
+ }
512
+ async function okpThumbprint(crv, x) {
513
+ return digest(`{"crv":${JSON.stringify(crv)},"kty":"OKP","x":${JSON.stringify(x)}}`);
514
+ }
515
+ async function jwkThumbprint(k) {
516
+ switch (k.kty) {
517
+ case "OKP":
518
+ if (!k.crv || !k.x) throw new Error("thumbprint: OKP JWK missing crv or x");
519
+ return okpThumbprint(k.crv, k.x);
520
+ case "RSA":
521
+ if (!k.n || !k.e) throw new Error("thumbprint: RSA JWK missing n or e");
522
+ return rsaThumbprint(k.n, k.e);
523
+ default:
524
+ throw new Error(`thumbprint: unsupported kty ${JSON.stringify(k.kty)}`);
525
+ }
526
+ }
527
+ async function digest(canonical) {
528
+ const buf = await crypto.subtle.digest("SHA-256", encoder.encode(canonical));
529
+ return base64urlBytes(new Uint8Array(buf));
530
+ }
531
+ function base64urlBytes(bytes) {
532
+ let binary = "";
533
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
534
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
535
+ }
536
+
537
+ // src/agent/directory.ts
538
+ var WELL_KNOWN = "/.well-known/http-message-signatures-directory";
539
+ var COLD_RETRY_BACKOFF_MS = 3e4;
540
+ var DEFAULT_SIGNED_AGENT_DIRECTORIES = [
541
+ { name: "OpenAI", category: "ai_crawlers", directory: "https://operator.openai.com" },
542
+ { name: "OpenAI ChatGPT", category: "ai_crawlers", directory: "https://chatgpt.com" }
543
+ ];
544
+ var DirectoryCache = class {
545
+ constructor(opts) {
546
+ this.keys = /* @__PURE__ */ new Map();
547
+ this.refreshedAt = 0;
548
+ this.nextColdRetryAt = 0;
549
+ this.inflight = null;
550
+ /** Resolve a keyid to a verification key, fetching/refreshing as needed. */
551
+ this.resolveKey = async (keyId) => {
552
+ await this.ensureFresh();
553
+ return this.keys.get(keyId);
554
+ };
555
+ this.opts = opts;
556
+ }
557
+ /** Kick off a fetch without blocking — call at startup to warm the cache. */
558
+ prime() {
559
+ if (this.keys.size === 0 && Date.now() >= this.nextColdRetryAt) void this.refresh();
560
+ }
561
+ /** Number of keys currently cached (diagnostics/tests). */
562
+ get size() {
563
+ return this.keys.size;
564
+ }
565
+ async ensureFresh() {
566
+ const now = Date.now();
567
+ const stale = now - this.refreshedAt > this.opts.cacheTtlMs;
568
+ if (this.keys.size > 0) {
569
+ if (stale) void this.refresh();
570
+ return;
571
+ }
572
+ if (now < this.nextColdRetryAt) return;
573
+ await this.refresh();
574
+ }
575
+ /** Re-fetch every directory. De-duplicated: concurrent callers share one run. */
576
+ refresh() {
577
+ if (this.inflight) return this.inflight;
578
+ this.inflight = this.doRefresh().finally(() => {
579
+ this.inflight = null;
580
+ });
581
+ return this.inflight;
582
+ }
583
+ async doRefresh() {
584
+ const results = await Promise.all(
585
+ this.opts.directories.map((src) => this.fetchDirectory(src))
586
+ );
587
+ const next = new Map(this.keys);
588
+ let fetchedAny = false;
589
+ for (const keys of results) {
590
+ if (keys === null) continue;
591
+ fetchedAny = true;
592
+ for (const k of keys) next.set(k.thumbprint, k.key);
593
+ }
594
+ if (fetchedAny) {
595
+ this.keys = next;
596
+ this.refreshedAt = Date.now();
597
+ this.nextColdRetryAt = 0;
598
+ this.debug(`refreshed: ${this.keys.size} key(s) across ${this.opts.directories.length} directories`);
599
+ } else if (this.keys.size === 0) {
600
+ this.nextColdRetryAt = Date.now() + COLD_RETRY_BACKOFF_MS;
601
+ this.debug("all directories unreachable; backing off cold retry");
602
+ }
603
+ }
604
+ async fetchDirectory(src) {
605
+ const url = directoryUrl(src.directory);
606
+ const controller = new AbortController();
607
+ const timer = setTimeout(() => controller.abort(), this.opts.fetchTimeoutMs);
608
+ try {
609
+ const res = await this.opts.fetchImpl(url, {
610
+ signal: controller.signal,
611
+ headers: {
612
+ Accept: "application/http-message-signatures-directory+json, application/jwk-set+json, application/json"
613
+ },
614
+ redirect: "follow"
615
+ });
616
+ if (!res.ok) {
617
+ this.debug(`${src.name}: HTTP ${res.status}`);
618
+ return null;
619
+ }
620
+ const body = await res.json();
621
+ if (!body || !Array.isArray(body.keys)) {
622
+ this.debug(`${src.name}: no keys in directory`);
623
+ return null;
624
+ }
625
+ const out = [];
626
+ for (const jwk of body.keys) {
627
+ const resolved = await importKey(jwk, src);
628
+ if (resolved) out.push(resolved);
629
+ }
630
+ this.debug(`${src.name}: ${out.length} key(s)`);
631
+ return out;
632
+ } catch (err) {
633
+ this.debug(`${src.name}: fetch failed \u2014 ${err.message}`);
634
+ return null;
635
+ } finally {
636
+ clearTimeout(timer);
637
+ }
638
+ }
639
+ debug(msg) {
640
+ if (this.opts.debug) console.log(`[WebDecoy][web-bot-auth] ${msg}`);
641
+ }
642
+ };
643
+ function directoryUrl(directory) {
644
+ const u = new URL(directory);
645
+ if (u.pathname && u.pathname !== "/") return u.toString();
646
+ u.pathname = WELL_KNOWN;
647
+ return u.toString();
648
+ }
649
+ async function importKey(jwk, src) {
650
+ try {
651
+ let cryptoKey;
652
+ let verifyParams;
653
+ let algorithm;
654
+ if (jwk.kty === "OKP") {
655
+ if (jwk.crv !== "Ed25519" || !jwk.x) return null;
656
+ cryptoKey = await crypto.subtle.importKey(
657
+ "jwk",
658
+ { kty: "OKP", crv: "Ed25519", x: jwk.x },
659
+ { name: "Ed25519" },
660
+ false,
661
+ ["verify"]
662
+ );
663
+ verifyParams = { name: "Ed25519" };
664
+ algorithm = "ed25519";
665
+ } else if (jwk.kty === "RSA") {
666
+ if (!jwk.n || !jwk.e) return null;
667
+ cryptoKey = await crypto.subtle.importKey(
668
+ "jwk",
669
+ { kty: "RSA", n: jwk.n, e: jwk.e },
670
+ { name: "RSA-PSS", hash: "SHA-512" },
671
+ false,
672
+ ["verify"]
673
+ );
674
+ verifyParams = { name: "RSA-PSS", saltLength: 64 };
675
+ algorithm = "rsa-pss-sha512";
676
+ } else {
677
+ return null;
678
+ }
679
+ const thumbprint = await jwkThumbprint(jwk);
680
+ return {
681
+ thumbprint,
682
+ key: {
683
+ cryptoKey,
684
+ verifyParams,
685
+ algorithm,
686
+ name: src.name,
687
+ category: src.category,
688
+ nbf: normalizeEpoch(jwk.nbf),
689
+ exp: normalizeEpoch(jwk.exp)
690
+ }
691
+ };
692
+ } catch {
693
+ return null;
694
+ }
695
+ }
696
+ function normalizeEpoch(v) {
697
+ if (v === void 0 || v === 0) return void 0;
698
+ return v > 1e12 ? Math.floor(v / 1e3) : v;
699
+ }
700
+
701
+ // src/agent/sfv.ts
702
+ var Cursor = class {
703
+ constructor(s, i = 0) {
704
+ this.s = s;
705
+ this.i = i;
706
+ }
707
+ eof() {
708
+ return this.i >= this.s.length;
709
+ }
710
+ peek() {
711
+ return this.s[this.i];
712
+ }
713
+ skipSP() {
714
+ while (!this.eof() && (this.peek() === " " || this.peek() === " ")) this.i++;
715
+ }
716
+ };
717
+ function parseDictionary(input) {
718
+ const p = new Cursor(input);
719
+ const out = [];
720
+ p.skipSP();
721
+ while (!p.eof()) {
722
+ const key = parseKey(p);
723
+ const entry = { key, raw: "", isList: false, items: [], params: /* @__PURE__ */ new Map() };
724
+ if (!p.eof() && p.peek() === "=") {
725
+ p.i++;
726
+ const start = p.i;
727
+ if (!p.eof() && p.peek() === "(") {
728
+ entry.isList = true;
729
+ parseInnerList(p, entry);
730
+ } else {
731
+ entry.items.push(parseItem(p));
732
+ entry.params = entry.items[0].params;
733
+ }
734
+ entry.raw = input.slice(start, p.i);
735
+ } else {
736
+ entry.params = parseParams(p);
737
+ entry.items.push({ value: true, params: /* @__PURE__ */ new Map() });
738
+ entry.raw = "?1";
739
+ }
740
+ out.push(entry);
741
+ p.skipSP();
742
+ if (p.eof()) break;
743
+ if (p.peek() !== ",") throw new Error(`sfv: expected ',' at ${p.i}`);
744
+ p.i++;
745
+ p.skipSP();
746
+ if (p.eof()) throw new Error("sfv: trailing comma");
747
+ }
748
+ return out;
749
+ }
750
+ function parseInnerList(p, entry) {
751
+ p.i++;
752
+ for (; ; ) {
753
+ p.skipSP();
754
+ if (p.eof()) throw new Error("sfv: unterminated inner list");
755
+ if (p.peek() === ")") {
756
+ p.i++;
757
+ break;
758
+ }
759
+ entry.items.push(parseItem(p));
760
+ if (p.eof()) throw new Error("sfv: unterminated inner list");
761
+ const c = p.peek();
762
+ if (c !== " " && c !== ")") throw new Error(`sfv: bad inner list at ${p.i}`);
763
+ }
764
+ entry.params = parseParams(p);
765
+ }
766
+ function parseItem(p) {
767
+ const { value, bytes } = parseBareItem(p);
768
+ const params = parseParams(p);
769
+ return bytes ? { value, params, bytes } : { value, params };
770
+ }
771
+ function parseParams(p) {
772
+ const params = /* @__PURE__ */ new Map();
773
+ while (!p.eof() && p.peek() === ";") {
774
+ p.i++;
775
+ p.skipSP();
776
+ const key = parseKey(p);
777
+ let val = true;
778
+ if (!p.eof() && p.peek() === "=") {
779
+ p.i++;
780
+ val = parseBareItem(p).value;
781
+ }
782
+ params.set(key, val);
783
+ }
784
+ return params;
785
+ }
786
+ function parseKey(p) {
787
+ const c = p.peek();
788
+ if (!c || !/[a-z*]/.test(c)) throw new Error(`sfv: invalid key at ${p.i}`);
789
+ const start = p.i;
790
+ while (!p.eof() && /[a-z0-9_\-.*]/.test(p.peek())) p.i++;
791
+ return p.s.slice(start, p.i);
792
+ }
793
+ function parseBareItem(p) {
794
+ const c = p.peek();
795
+ if (c === '"') return { value: parseString(p) };
796
+ if (c === ":") return { value: "", bytes: parseByteSequence(p) };
797
+ if (c === "?") {
798
+ p.i++;
799
+ const b = p.s[p.i++];
800
+ if (b === "1") return { value: true };
801
+ if (b === "0") return { value: false };
802
+ throw new Error("sfv: bad boolean");
803
+ }
804
+ if (c === "-" || /[0-9]/.test(c)) return { value: parseNumber(p) };
805
+ if (/[a-zA-Z*]/.test(c)) return { value: parseToken(p) };
806
+ throw new Error(`sfv: invalid bare item at ${p.i}`);
807
+ }
808
+ function parseString(p) {
809
+ p.i++;
810
+ let out = "";
811
+ while (!p.eof()) {
812
+ const c = p.s[p.i++];
813
+ if (c === '"') return out;
814
+ if (c === "\\") {
815
+ const e = p.s[p.i++];
816
+ if (e !== '"' && e !== "\\") throw new Error("sfv: bad escape");
817
+ out += e;
818
+ } else {
819
+ const code = c.charCodeAt(0);
820
+ if (code < 32 || code > 126) throw new Error("sfv: bad char in string");
821
+ out += c;
822
+ }
823
+ }
824
+ throw new Error("sfv: unterminated string");
825
+ }
826
+ function parseByteSequence(p) {
827
+ p.i++;
828
+ const start = p.i;
829
+ while (!p.eof() && p.peek() !== ":") p.i++;
830
+ if (p.eof()) throw new Error("sfv: unterminated byte sequence");
831
+ const b64 = p.s.slice(start, p.i);
832
+ p.i++;
833
+ return base64StdToBytes(b64);
834
+ }
835
+ function parseNumber(p) {
836
+ const start = p.i;
837
+ if (p.peek() === "-") p.i++;
838
+ while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
839
+ if (!p.eof() && p.peek() === ".") {
840
+ p.i++;
841
+ while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
842
+ }
843
+ return Number(p.s.slice(start, p.i));
844
+ }
845
+ function parseToken(p) {
846
+ const start = p.i;
847
+ p.i++;
848
+ while (!p.eof() && /[a-zA-Z0-9!#$%&'*+\-.^_`|~:/]/.test(p.peek())) p.i++;
849
+ return p.s.slice(start, p.i);
850
+ }
851
+ function base64StdToBytes(s) {
852
+ const bin = atob(s);
853
+ const out = new Uint8Array(bin.length);
854
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
855
+ return out;
856
+ }
857
+
858
+ // src/agent/signature.ts
859
+ var TAG = "web-bot-auth";
860
+ var encoder2 = new TextEncoder();
861
+ async function verifyWebBotAuth(req, resolveKey, toleranceSec) {
862
+ const sigInput = req.headers.get("signature-input");
863
+ const sigHeader = req.headers.get("signature");
864
+ if (!sigInput && !sigHeader) return { outcome: "none" };
865
+ if (!sigInput || !sigHeader) return { outcome: "claimed", reason: "incomplete-signature" };
866
+ let members;
867
+ let sigs;
868
+ try {
869
+ members = parseSignatureInput(sigInput);
870
+ sigs = parseSignatureBytes(sigHeader);
871
+ } catch {
872
+ return { outcome: "claimed", reason: "malformed-signature" };
873
+ }
874
+ const now = Date.now() / 1e3;
875
+ let best = { outcome: "none" };
876
+ for (const m of members) {
877
+ if (m.params.get("tag") !== TAG) continue;
878
+ if (best.outcome === "none") best = { outcome: "claimed", reason: "unverifiable" };
879
+ const sig = sigs.get(m.label);
880
+ if (!sig) continue;
881
+ const keyid = m.params.get("keyid");
882
+ if (typeof keyid !== "string") continue;
883
+ if (!m.components.some((c) => c.name === "@authority" || c.name === "@target-uri")) continue;
884
+ const key = await resolveKey(keyid);
885
+ if (!key) {
886
+ best = higher(best, { outcome: "claimed", keyId: keyid, reason: "unknown-key" });
887
+ continue;
888
+ }
889
+ const created = numeric(m.params.get("created"));
890
+ const expires = numeric(m.params.get("expires"));
891
+ if (expires !== void 0 && now > expires + toleranceSec) {
892
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "expired" });
893
+ continue;
894
+ }
895
+ if (created !== void 0 && now + toleranceSec < created) {
896
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "not-yet-valid" });
897
+ continue;
898
+ }
899
+ if (key.exp !== void 0 && now > key.exp + toleranceSec) {
900
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-expired" });
901
+ continue;
902
+ }
903
+ if (key.nbf !== void 0 && now + toleranceSec < key.nbf) {
904
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-not-yet-valid" });
905
+ continue;
906
+ }
907
+ let base;
908
+ try {
909
+ base = buildSignatureBase(req, m);
910
+ } catch {
911
+ best = higher(best, { outcome: "claimed", keyId: keyid, reason: "uncoverable-component" });
912
+ continue;
913
+ }
914
+ let ok = false;
915
+ try {
916
+ ok = await crypto.subtle.verify(
917
+ key.verifyParams,
918
+ key.cryptoKey,
919
+ sig,
920
+ encoder2.encode(base)
921
+ );
922
+ } catch {
923
+ ok = false;
924
+ }
925
+ if (ok) {
926
+ return { outcome: "verified", keyId: keyid, key };
927
+ }
928
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "bad-signature" });
929
+ }
930
+ return best;
931
+ }
932
+ var PRECEDENCE = { none: 0, claimed: 1, impersonation: 2, verified: 3 };
933
+ function higher(a, b) {
934
+ return PRECEDENCE[b.outcome] >= PRECEDENCE[a.outcome] ? b : a;
935
+ }
936
+ function numeric(v) {
937
+ return typeof v === "number" ? v : void 0;
938
+ }
939
+ function buildSignatureBase(req, m) {
940
+ const lines = [];
941
+ for (const c of m.components) {
942
+ lines.push(`${serializeComponentId(c)}: ${componentValue(req, c)}`);
943
+ }
944
+ lines.push(`"@signature-params": ${m.raw.trim()}`);
945
+ return lines.join("\n");
946
+ }
947
+ function serializeComponentId(c) {
948
+ const base = `"${c.name.toLowerCase()}"`;
949
+ return c.keyParam !== void 0 ? `${base};key="${c.keyParam}"` : base;
950
+ }
951
+ function componentValue(req, c) {
952
+ const name = c.name.toLowerCase();
953
+ switch (name) {
954
+ case "@method":
955
+ return req.method.toUpperCase();
956
+ case "@authority":
957
+ return canonicalAuthority(req.url);
958
+ case "@scheme":
959
+ return req.url.protocol.replace(/:$/, "").toLowerCase();
960
+ case "@target-uri":
961
+ return `${req.url.protocol}//${canonicalAuthority(req.url)}${req.url.pathname}${req.url.search}`;
962
+ case "@path":
963
+ return req.url.pathname;
964
+ case "@query":
965
+ return req.url.search === "" ? "?" : req.url.search;
966
+ case "signature-agent": {
967
+ const header = req.headers.get("signature-agent");
968
+ if (header === null) throw new Error("signature-agent covered but absent");
969
+ if (c.keyParam !== void 0) return dictMemberValue(header, c.keyParam);
970
+ return header.trim().replace(/\s+/g, " ");
971
+ }
972
+ default: {
973
+ if (name.startsWith("@")) throw new Error(`unsupported derived component ${name}`);
974
+ const header = req.headers.get(name);
975
+ if (header === null) throw new Error(`covered header ${name} absent`);
976
+ return header.trim().replace(/\s+/g, " ");
977
+ }
978
+ }
979
+ }
980
+ function canonicalAuthority(url) {
981
+ const host = url.hostname.toLowerCase();
982
+ const port = url.port;
983
+ if (!port) return host;
984
+ if (url.protocol === "https:" && port === "443" || url.protocol === "http:" && port === "80") {
985
+ return host;
986
+ }
987
+ return `${host}:${port}`;
988
+ }
989
+ function dictMemberValue(header, key) {
990
+ const dict = parseDictionary(header);
991
+ const found = dict.find((d) => d.key === key);
992
+ if (!found) throw new Error(`signature-agent has no member ${key}`);
993
+ return found.raw;
994
+ }
995
+ function parseSignatureInput(value) {
996
+ return parseDictionary(value).map((d) => {
997
+ if (!d.isList) throw new Error(`Signature-Input member ${d.key} is not an inner list`);
998
+ const components = d.items.map((it) => {
999
+ if (typeof it.value !== "string") throw new Error("component identifier is not a string");
1000
+ const keyParam = it.params.get("key");
1001
+ return { name: it.value, keyParam: typeof keyParam === "string" ? keyParam : void 0 };
1002
+ });
1003
+ return { label: d.key, components, params: d.params, raw: d.raw };
1004
+ });
1005
+ }
1006
+ function parseSignatureBytes(value) {
1007
+ const out = /* @__PURE__ */ new Map();
1008
+ for (const d of parseDictionary(value)) {
1009
+ if (d.isList || d.items.length !== 1 || !d.items[0].bytes) {
1010
+ throw new Error(`Signature member ${d.key} is not a byte sequence`);
1011
+ }
1012
+ out.set(d.key, d.items[0].bytes);
1013
+ }
1014
+ return out;
1015
+ }
1016
+
1017
+ // src/agent/verifier.ts
1018
+ var DEFAULT_TTL_MS = 6 * 60 * 60 * 1e3;
1019
+ var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
1020
+ var DEFAULT_TOLERANCE_SEC = 300;
1021
+ var AgentVerifier = class {
1022
+ constructor(options = {}) {
1023
+ this.toleranceSec = options.toleranceSec ?? DEFAULT_TOLERANCE_SEC;
1024
+ this.cache = new DirectoryCache({
1025
+ directories: options.directories ?? DEFAULT_SIGNED_AGENT_DIRECTORIES,
1026
+ cacheTtlMs: options.cacheTtlMs ?? DEFAULT_TTL_MS,
1027
+ fetchTimeoutMs: options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,
1028
+ debug: options.debug ?? false,
1029
+ fetchImpl: options.fetchImpl ?? fetch
1030
+ });
1031
+ }
1032
+ /** Pre-fetch trusted directories so the first request verifies warm. */
1033
+ warmup() {
1034
+ this.cache.prime();
1035
+ }
1036
+ /** Verify a request's Web Bot Auth signature (if any) locally. */
1037
+ async verify(request) {
1038
+ let req;
1039
+ try {
1040
+ req = normalize(request);
1041
+ } catch {
1042
+ return { status: "none" };
1043
+ }
1044
+ const result = await verifyWebBotAuth(req, this.cache.resolveKey, this.toleranceSec);
1045
+ switch (result.outcome) {
1046
+ case "verified":
1047
+ return {
1048
+ status: "verified",
1049
+ method: "signature",
1050
+ keyId: result.keyId,
1051
+ agentName: result.key?.name,
1052
+ category: result.key?.category,
1053
+ algorithm: result.key?.algorithm
1054
+ };
1055
+ case "impersonation":
1056
+ return {
1057
+ status: "impersonation",
1058
+ method: "signature",
1059
+ keyId: result.keyId,
1060
+ agentName: result.key?.name,
1061
+ category: result.key?.category,
1062
+ reason: result.reason
1063
+ };
1064
+ case "claimed":
1065
+ return { status: "claimed", keyId: result.keyId, reason: result.reason };
1066
+ default:
1067
+ return { status: "none" };
1068
+ }
1069
+ }
1070
+ /** Cached-key count (diagnostics/tests). */
1071
+ get cachedKeyCount() {
1072
+ return this.cache.size;
1073
+ }
1074
+ };
1075
+ function createAgentVerifier(options = {}) {
1076
+ return new AgentVerifier(options);
1077
+ }
1078
+ function normalize(input) {
1079
+ if (isRequest(input)) {
1080
+ return { method: input.method, url: new URL(input.url), headers: input.headers };
1081
+ }
1082
+ const headers = input.headers instanceof Headers ? input.headers : toHeaders(input.headers);
1083
+ return { method: input.method, url: new URL(input.url), headers };
1084
+ }
1085
+ function isRequest(input) {
1086
+ return typeof Request !== "undefined" && input instanceof Request && typeof input.url === "string";
1087
+ }
1088
+ function toHeaders(record) {
1089
+ const h = new Headers();
1090
+ for (const [k, v] of Object.entries(record)) {
1091
+ if (v !== void 0 && v !== null) h.set(k, String(v));
1092
+ }
1093
+ return h;
1094
+ }
1095
+
487
1096
  // src/sdk.ts
488
1097
  var WebDecoy = class {
489
1098
  constructor(config) {
490
1099
  this.violationReporter = null;
491
1100
  this.ipEnrichmentClient = null;
492
1101
  this._hasFilterRules = false;
1102
+ this._hasAgentRules = false;
1103
+ this.agentVerifier = null;
493
1104
  const hasApiKey = !!config.apiKey;
494
1105
  if (hasApiKey) {
495
1106
  if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
@@ -500,7 +1111,7 @@ var WebDecoy = class {
500
1111
  }
501
1112
  this.config = {
502
1113
  apiKey: config.apiKey,
503
- apiUrl: config.apiUrl || "https://api.webdecoy.com",
1114
+ apiUrl: config.apiUrl || "https://ingest.webdecoy.com",
504
1115
  enableTLSFingerprinting: config.enableTLSFingerprinting ?? true,
505
1116
  threatScoreThreshold: config.threatScoreThreshold ?? 80,
506
1117
  timeout: config.timeout ?? 5e3,
@@ -521,11 +1132,16 @@ var WebDecoy = class {
521
1132
  console.log("[WebDecoy] Running in local-only mode (no API key). Rules will still evaluate.");
522
1133
  }
523
1134
  }
1135
+ this.webBotAuthOptions = config.webBotAuth;
524
1136
  if (config.rules && config.rules.length > 0) {
525
1137
  this.ruleEngine = new RuleEngine(config.rules);
526
1138
  this._hasFilterRules = config.rules.some(
527
1139
  (r) => r.name.startsWith("filter:")
528
1140
  );
1141
+ this._hasAgentRules = config.rules.some((r) => r.name === "web-bot-auth");
1142
+ if (this._hasAgentRules) {
1143
+ this.getAgentVerifier().warmup();
1144
+ }
529
1145
  } else {
530
1146
  this.ruleEngine = null;
531
1147
  }
@@ -554,27 +1170,21 @@ var WebDecoy = class {
554
1170
  */
555
1171
  evaluateRules(metadata) {
556
1172
  if (!this.ruleEngine) return null;
557
- const context = {
558
- ip: metadata.ip,
559
- path: metadata.path,
560
- method: metadata.method,
561
- userAgent: metadata.user_agent,
562
- headers: metadata.headers,
563
- timestamp: metadata.timestamp || Date.now()
564
- };
565
- const result = this.ruleEngine.evaluate(context);
566
- if (result.violations.length > 0 && this.violationReporter) {
567
- this.violationReporter.report(result.violations);
568
- }
569
- return result;
1173
+ return this.runRules(this.buildContext(metadata));
570
1174
  }
571
1175
  /**
572
- * Evaluate rules with async IP enrichment pre-fetch.
573
- * Use this instead of evaluateRules() when filter rules are present.
1176
+ * Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth
1177
+ * verification). Use this instead of evaluateRules() when filter rules or
1178
+ * webBotAuth() rules are present.
574
1179
  */
575
1180
  async evaluateRulesAsync(metadata) {
576
1181
  if (!this.ruleEngine) return null;
577
- const context = {
1182
+ const context = await this.buildAsyncContext(metadata);
1183
+ return this.runRules(context);
1184
+ }
1185
+ /** Build the base (synchronous) rule context from request metadata. */
1186
+ buildContext(metadata) {
1187
+ return {
578
1188
  ip: metadata.ip,
579
1189
  path: metadata.path,
580
1190
  method: metadata.method,
@@ -582,24 +1192,85 @@ var WebDecoy = class {
582
1192
  headers: metadata.headers,
583
1193
  timestamp: metadata.timestamp || Date.now()
584
1194
  };
1195
+ }
1196
+ /**
1197
+ * Build a rule context with async signals resolved: IP enrichment (for
1198
+ * filter rules) and the Web Bot Auth verdict (for webBotAuth() rules).
1199
+ */
1200
+ async buildAsyncContext(metadata) {
1201
+ const context = this.buildContext(metadata);
585
1202
  if (this._hasFilterRules && this.ipEnrichmentClient) {
586
1203
  const enrichment = await this.ipEnrichmentClient.enrich(metadata.ip);
587
1204
  if (enrichment) {
588
1205
  context.enrichment = enrichment;
589
1206
  }
590
1207
  }
1208
+ if (this._hasAgentRules) {
1209
+ context.agent = await this.computeAgentVerdict(metadata);
1210
+ }
1211
+ return context;
1212
+ }
1213
+ /** Evaluate rules against a prepared context and report any violations. */
1214
+ runRules(context) {
1215
+ if (!this.ruleEngine) return null;
591
1216
  const result = this.ruleEngine.evaluate(context);
592
1217
  if (result.violations.length > 0 && this.violationReporter) {
593
1218
  this.violationReporter.report(result.violations);
594
1219
  }
595
1220
  return result;
596
1221
  }
1222
+ /** Lazily construct the shared Web Bot Auth verifier (one directory cache). */
1223
+ getAgentVerifier() {
1224
+ if (!this.agentVerifier) {
1225
+ this.agentVerifier = new AgentVerifier({
1226
+ debug: this.config.debug,
1227
+ ...this.webBotAuthOptions
1228
+ });
1229
+ }
1230
+ return this.agentVerifier;
1231
+ }
1232
+ /**
1233
+ * Verify a request's Web Bot Auth signature locally, deriving the request
1234
+ * URL/authority from its metadata. Returns undefined when the request lacks
1235
+ * the host information needed to verify (verdict is then simply absent).
1236
+ */
1237
+ async computeAgentVerdict(metadata) {
1238
+ const input = agentInputFromMetadata(metadata);
1239
+ if (!input) return void 0;
1240
+ return this.getAgentVerifier().verify(input);
1241
+ }
1242
+ /**
1243
+ * Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag
1244
+ * "web-bot-auth"). Returns whether it is a cryptographically `verified`
1245
+ * agent, an `impersonation` of a known one, an unverifiable `claimed`
1246
+ * signature, or `none`. No network on the warm path.
1247
+ *
1248
+ * Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }`
1249
+ * object (Node).
1250
+ *
1251
+ * @example
1252
+ * ```ts
1253
+ * const verdict = await webdecoy.detectBot(request);
1254
+ * if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 });
1255
+ * if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName);
1256
+ * ```
1257
+ */
1258
+ async detectBot(request) {
1259
+ return this.getAgentVerifier().verify(request);
1260
+ }
597
1261
  /**
598
1262
  * Whether this SDK instance has filter rules that need async enrichment
599
1263
  */
600
1264
  get hasFilterRules() {
601
1265
  return this._hasFilterRules;
602
1266
  }
1267
+ /**
1268
+ * Whether this SDK instance has Web Bot Auth rules that need async
1269
+ * verification before evaluation.
1270
+ */
1271
+ get hasAgentRules() {
1272
+ return this._hasAgentRules;
1273
+ }
603
1274
  /**
604
1275
  * Protect a request by checking it against Web Decoy's bot detection
605
1276
  *
@@ -615,7 +1286,15 @@ var WebDecoy = class {
615
1286
  if (!metadata.timestamp) {
616
1287
  metadata.timestamp = Date.now();
617
1288
  }
618
- const ruleResult = this._hasFilterRules ? await this.evaluateRulesAsync(metadata) : this.evaluateRules(metadata);
1289
+ let ruleResult;
1290
+ let agentVerdict;
1291
+ if (this.ruleEngine && (this._hasFilterRules || this._hasAgentRules)) {
1292
+ const context = await this.buildAsyncContext(metadata);
1293
+ agentVerdict = context.agent;
1294
+ ruleResult = this.runRules(context);
1295
+ } else {
1296
+ ruleResult = this.evaluateRules(metadata);
1297
+ }
619
1298
  if (ruleResult && ruleResult.action === "DENY") {
620
1299
  return {
621
1300
  allowed: false,
@@ -627,7 +1306,8 @@ var WebDecoy = class {
627
1306
  detection_id: "rule_" + Date.now(),
628
1307
  rule_enforced: true
629
1308
  },
630
- ruleResult
1309
+ ruleResult,
1310
+ agent: agentVerdict
631
1311
  };
632
1312
  }
633
1313
  if (ruleResult && ruleResult.action === "THROTTLE") {
@@ -641,7 +1321,8 @@ var WebDecoy = class {
641
1321
  detection_id: "rule_" + Date.now(),
642
1322
  rule_enforced: true
643
1323
  },
644
- ruleResult
1324
+ ruleResult,
1325
+ agent: agentVerdict
645
1326
  };
646
1327
  }
647
1328
  if (!this.client) {
@@ -655,7 +1336,8 @@ var WebDecoy = class {
655
1336
  detection_id: "local_" + Date.now(),
656
1337
  rule_enforced: false
657
1338
  },
658
- ruleResult: ruleResult ?? void 0
1339
+ ruleResult: ruleResult ?? void 0,
1340
+ agent: agentVerdict
659
1341
  };
660
1342
  }
661
1343
  const localAnalysis = options.skipLocalAnalysis ? {
@@ -685,7 +1367,8 @@ var WebDecoy = class {
685
1367
  detection_id: "local_" + Date.now(),
686
1368
  rule_enforced: false
687
1369
  },
688
- ruleResult: ruleResult ?? void 0
1370
+ ruleResult: ruleResult ?? void 0,
1371
+ agent: agentVerdict
689
1372
  };
690
1373
  }
691
1374
  const detection = await this.client.detect(detectionRequest);
@@ -701,7 +1384,8 @@ var WebDecoy = class {
701
1384
  return {
702
1385
  allowed,
703
1386
  detection,
704
- ruleResult: ruleResult ?? void 0
1387
+ ruleResult: ruleResult ?? void 0,
1388
+ agent: agentVerdict
705
1389
  };
706
1390
  } catch (error) {
707
1391
  if (this.config.debug) {
@@ -769,6 +1453,24 @@ var WebDecoy = class {
769
1453
  }
770
1454
  }
771
1455
  };
1456
+ function agentInputFromMetadata(metadata) {
1457
+ const headers = metadata.headers || {};
1458
+ const host = headers["host"] || headers[":authority"] || headers["x-forwarded-host"] || headers["Host"];
1459
+ if (!host) return null;
1460
+ const proto = headers["x-forwarded-proto"] || headers["X-Forwarded-Proto"];
1461
+ const scheme = (proto ? proto.split(",")[0].trim() : "https") || "https";
1462
+ const rawPath = metadata.path || "/";
1463
+ const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
1464
+ try {
1465
+ return {
1466
+ method: metadata.method,
1467
+ url: `${scheme}://${host}${path}`,
1468
+ headers
1469
+ };
1470
+ } catch {
1471
+ return null;
1472
+ }
1473
+ }
772
1474
 
773
1475
  // src/rules/rate-limiter.ts
774
1476
  var InMemoryRateLimiter = class {
@@ -1400,11 +2102,133 @@ var TripwireRule = class {
1400
2102
  }
1401
2103
  };
1402
2104
 
2105
+ // src/rules/web-bot-auth-rule.ts
2106
+ var WebBotAuthRule = class {
2107
+ constructor(config = {}) {
2108
+ this.name = "web-bot-auth";
2109
+ this.onImpersonation = config.onImpersonation ?? "DENY";
2110
+ this.onClaimed = config.onClaimed ?? "ALLOW";
2111
+ this.allowCategories = config.allowCategories ? new Set(config.allowCategories) : void 0;
2112
+ this.dryRun = config.dryRun ?? false;
2113
+ }
2114
+ evaluate(context) {
2115
+ const verdict = context.agent;
2116
+ if (!verdict || verdict.status === "none") return this.allow();
2117
+ if (verdict.status === "impersonation") {
2118
+ return this.act(this.onImpersonation, "agent_impersonation", {
2119
+ agentName: verdict.agentName,
2120
+ category: verdict.category,
2121
+ keyId: verdict.keyId,
2122
+ detail: verdict.reason
2123
+ });
2124
+ }
2125
+ if (verdict.status === "claimed") {
2126
+ return this.act(this.onClaimed, "agent_unverifiable", {
2127
+ keyId: verdict.keyId,
2128
+ detail: verdict.reason
2129
+ });
2130
+ }
2131
+ if (this.allowCategories && verdict.category && !this.allowCategories.has(verdict.category)) {
2132
+ return this.act(this.onClaimed, "agent_category_not_allowed", {
2133
+ agentName: verdict.agentName,
2134
+ category: verdict.category,
2135
+ keyId: verdict.keyId
2136
+ });
2137
+ }
2138
+ return this.allow();
2139
+ }
2140
+ act(action, verdict, detail) {
2141
+ if (action === "ALLOW") return this.allow();
2142
+ return {
2143
+ action: this.dryRun ? "ALLOW" : action,
2144
+ rule: this.name,
2145
+ reason: reasonFor(verdict),
2146
+ metadata: { verdict, dryRun: this.dryRun, ...detail }
2147
+ };
2148
+ }
2149
+ allow() {
2150
+ return { action: "ALLOW", rule: this.name };
2151
+ }
2152
+ };
2153
+ function reasonFor(verdict) {
2154
+ switch (verdict) {
2155
+ case "agent_impersonation":
2156
+ return "Web Bot Auth signature failed verification (agent impersonation)";
2157
+ case "agent_unverifiable":
2158
+ return "Web Bot Auth signature could not be verified";
2159
+ case "agent_category_not_allowed":
2160
+ return "Verified agent category is not allowed";
2161
+ default:
2162
+ return "Web Bot Auth rule triggered";
2163
+ }
2164
+ }
2165
+ function webBotAuth(config = {}) {
2166
+ return new WebBotAuthRule(config);
2167
+ }
2168
+
2169
+ // src/webcrypto.ts
2170
+ var encoder3 = new TextEncoder();
2171
+ function toHex(bytes) {
2172
+ let hex = "";
2173
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
2174
+ return hex;
2175
+ }
2176
+ async function sha256Hex(data) {
2177
+ const digest2 = await crypto.subtle.digest("SHA-256", encoder3.encode(data));
2178
+ return toHex(new Uint8Array(digest2));
2179
+ }
2180
+ async function hmacSha256Hex(secret, data) {
2181
+ const key = await crypto.subtle.importKey(
2182
+ "raw",
2183
+ encoder3.encode(secret),
2184
+ { name: "HMAC", hash: "SHA-256" },
2185
+ false,
2186
+ ["sign"]
2187
+ );
2188
+ const sig = await crypto.subtle.sign("HMAC", key, encoder3.encode(data));
2189
+ return toHex(new Uint8Array(sig));
2190
+ }
2191
+ function randomHex(bytes) {
2192
+ const buf = new Uint8Array(bytes);
2193
+ crypto.getRandomValues(buf);
2194
+ return toHex(buf);
2195
+ }
2196
+ function timingSafeEqualStr(a, b) {
2197
+ if (a.length !== b.length) return false;
2198
+ let diff = 0;
2199
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
2200
+ return diff === 0;
2201
+ }
2202
+ function base64urlEncode(data) {
2203
+ const bytes = encoder3.encode(data);
2204
+ let binary = "";
2205
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
2206
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2207
+ }
2208
+ function base64urlDecode(data) {
2209
+ const b64 = data.replace(/-/g, "+").replace(/_/g, "/");
2210
+ const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
2211
+ const binary = atob(padded);
2212
+ const bytes = new Uint8Array(binary.length);
2213
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
2214
+ return new TextDecoder().decode(bytes);
2215
+ }
2216
+ function fnv1a64Hex(data) {
2217
+ const PRIME = 0x100000001b3n;
2218
+ const MASK = 0xffffffffffffffffn;
2219
+ let hash = 0xcbf29ce484222325n;
2220
+ const bytes = encoder3.encode(data);
2221
+ for (let i = 0; i < bytes.length; i++) {
2222
+ hash ^= BigInt(bytes[i]);
2223
+ hash = hash * PRIME & MASK;
2224
+ }
2225
+ return hash.toString(16).padStart(16, "0");
2226
+ }
2227
+
1403
2228
  // src/rules/honeytoken.ts
1404
- var import_crypto = require("crypto");
1405
2229
  function honeytoken(options = {}) {
1406
2230
  const base = (options.basePath ?? "/__wd").replace(/\/+$/, "");
1407
- const token = options.token ?? (0, import_crypto.randomBytes)(6).toString("hex");
2231
+ const token = options.token ?? randomHex(6);
1408
2232
  const path = `${base}/${token}`;
1409
2233
  const text = options.text ?? ".";
1410
2234
  const linkHtml = `<a href="${path}" aria-hidden="true" tabindex="-1" rel="nofollow noindex" style="position:absolute;left:-9999px;top:auto;width:1px;height:1px;overflow:hidden">${text}</a>`;
@@ -1451,7 +2275,10 @@ var AUTOMATION_UA_PATTERNS = [
1451
2275
  ];
1452
2276
 
1453
2277
  // src/detection/ip.ts
1454
- var import_net = require("net");
2278
+ 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}$/;
2279
+ function isIPv4(ip) {
2280
+ return IPV4_RE.test(ip);
2281
+ }
1455
2282
  var DATACENTER_CIDRS = [
1456
2283
  // AWS
1457
2284
  "3.0.0.0/8",
@@ -1519,7 +2346,7 @@ function cidrContains(cidr, ip) {
1519
2346
  return (ipLong & mask) === rangeStart;
1520
2347
  }
1521
2348
  function isDatacenterIP2(ip) {
1522
- if (!(0, import_net.isIPv4)(ip)) return false;
2349
+ if (!isIPv4(ip)) return false;
1523
2350
  return DATACENTER_CIDRS.some((cidr) => cidrContains(cidr, ip));
1524
2351
  }
1525
2352
 
@@ -2135,7 +2962,6 @@ function detectTouchKinematics(signals) {
2135
2962
  }
2136
2963
 
2137
2964
  // src/detection/detectors/fingerprint.ts
2138
- var import_crypto2 = require("crypto");
2139
2965
  function detectFingerprint(signals, ip, siteKey, store) {
2140
2966
  const detections = [];
2141
2967
  const env = signals.environmental ?? {};
@@ -2146,7 +2972,7 @@ function detectFingerprint(signals, ip, siteKey, store) {
2146
2972
  String(automation.platform ?? ""),
2147
2973
  String(automation.hardwareConcurrency ?? "")
2148
2974
  ];
2149
- const fp = (0, import_crypto2.createHash)("sha256").update(components.join("|")).digest("hex").slice(0, 16);
2975
+ const fp = fnv1a64Hex(components.join("|"));
2150
2976
  store.record(fp, ip, siteKey);
2151
2977
  if (store.getIpFpCount(ip) > 5) {
2152
2978
  detections.push({
@@ -3028,9 +3854,6 @@ var DetectionEngine = class {
3028
3854
  }
3029
3855
  };
3030
3856
 
3031
- // src/captcha/service.ts
3032
- var import_crypto5 = require("crypto");
3033
-
3034
3857
  // src/captcha/secret.ts
3035
3858
  var INSECURE_DEFAULT_SECRET = "dev-secret-change-in-production";
3036
3859
  function resolveSecret(secret) {
@@ -3052,7 +3875,6 @@ function resolveSecret(secret) {
3052
3875
  }
3053
3876
 
3054
3877
  // src/captcha/pow.ts
3055
- var import_crypto3 = require("crypto");
3056
3878
  var EXPIRATION_MS = 5 * 60 * 1e3;
3057
3879
  var InMemoryChallengeStore = class {
3058
3880
  constructor() {
@@ -3098,10 +3920,10 @@ var PoWManager = class {
3098
3920
  return difficulty;
3099
3921
  }
3100
3922
  /** Generate and store a signed challenge. */
3101
- generate(siteKey, ip, difficulty) {
3923
+ async generate(siteKey, ip, difficulty) {
3102
3924
  const resolvedDifficulty = difficulty ?? this.scaleDifficulty(siteKey, ip);
3103
- const challengeId = (0, import_crypto3.randomBytes)(16).toString("hex");
3104
- const nonce = (0, import_crypto3.randomBytes)(16).toString("hex");
3925
+ const challengeId = randomHex(16);
3926
+ const nonce = randomHex(16);
3105
3927
  const timestamp = Date.now();
3106
3928
  const expiresAt = timestamp + EXPIRATION_MS;
3107
3929
  const challengeData = {
@@ -3116,12 +3938,12 @@ var PoWManager = class {
3116
3938
  };
3117
3939
  const { sig: _omit, ...toSign } = challengeData;
3118
3940
  void _omit;
3119
- challengeData.sig = (0, import_crypto3.createHmac)("sha256", this.secret).update(JSON.stringify(toSign)).digest("hex");
3941
+ challengeData.sig = await hmacSha256Hex(this.secret, JSON.stringify(toSign));
3120
3942
  this.store.put({ ...challengeData, ip, createdAt: timestamp });
3121
3943
  return challengeData;
3122
3944
  }
3123
3945
  /** Verify a submitted solution. `signalsHash` binds it to the signals. */
3124
- verify(solution, siteKey, signalsHash = null) {
3946
+ async verify(solution, siteKey, signalsHash = null) {
3125
3947
  const challenge = this.store.get(solution.challengeId);
3126
3948
  if (!challenge) return { valid: false, reason: "challenge_not_found" };
3127
3949
  if (Date.now() > challenge.expiresAt) {
@@ -3133,7 +3955,7 @@ var PoWManager = class {
3133
3955
  }
3134
3956
  const solutionKey = `${solution.challengeId}:${solution.nonce}`;
3135
3957
  const input = signalsHash ? `${challenge.prefix}:${signalsHash}:${solution.nonce}` : `${challenge.prefix}:${solution.nonce}`;
3136
- const expectedHash = (0, import_crypto3.createHash)("sha256").update(input).digest("hex");
3958
+ const expectedHash = await sha256Hex(input);
3137
3959
  if (solution.hash !== expectedHash) {
3138
3960
  return { valid: false, reason: "invalid_hash" };
3139
3961
  }
@@ -3155,7 +3977,6 @@ var PoWManager = class {
3155
3977
  };
3156
3978
 
3157
3979
  // src/captcha/token.ts
3158
- var import_crypto4 = require("crypto");
3159
3980
  var TOKEN_TTL_SECONDS = 300;
3160
3981
  var InMemoryTokenStore = class {
3161
3982
  constructor() {
@@ -3177,22 +3998,22 @@ var TokenManager = class {
3177
3998
  this.store = options.store ?? new InMemoryTokenStore();
3178
3999
  }
3179
4000
  /** Issue a signed, IP-bound token for a passing request. */
3180
- issue(ip, siteKey, score) {
4001
+ async issue(ip, siteKey, score) {
3181
4002
  const data = {
3182
4003
  site_key: siteKey,
3183
4004
  timestamp: Math.floor(Date.now() / 1e3),
3184
4005
  score: Math.round(score * 1e3) / 1e3,
3185
- ip_hash: (0, import_crypto4.createHash)("sha256").update(ip).digest("hex").slice(0, 8)
4006
+ ip_hash: (await sha256Hex(ip)).slice(0, 8)
3186
4007
  };
3187
4008
  const payload = JSON.stringify(data, Object.keys(data).sort());
3188
- data.sig = (0, import_crypto4.createHmac)("sha256", this.secret).update(payload).digest("hex");
3189
- return Buffer.from(JSON.stringify(data)).toString("base64url");
4009
+ data.sig = await hmacSha256Hex(this.secret, payload);
4010
+ return base64urlEncode(JSON.stringify(data));
3190
4011
  }
3191
4012
  /** Verify a token: signature, expiry, replay, and optional IP binding. */
3192
- verify(token, ip = null) {
4013
+ async verify(token, ip = null) {
3193
4014
  let decoded;
3194
4015
  try {
3195
- decoded = JSON.parse(Buffer.from(token, "base64url").toString());
4016
+ decoded = JSON.parse(base64urlDecode(token));
3196
4017
  } catch (e) {
3197
4018
  return { valid: false, reason: e instanceof Error ? e.message : "invalid_token" };
3198
4019
  }
@@ -3203,17 +4024,15 @@ var TokenManager = class {
3203
4024
  if (!sig) return { valid: false, reason: "invalid_signature" };
3204
4025
  delete decoded.sig;
3205
4026
  const payload = JSON.stringify(decoded, Object.keys(decoded).sort());
3206
- const expectedSig = (0, import_crypto4.createHmac)("sha256", this.secret).update(payload).digest("hex");
3207
- const sigBuf = Buffer.from(sig);
3208
- const expectedBuf = Buffer.from(expectedSig);
3209
- if (sigBuf.length !== expectedBuf.length || !(0, import_crypto4.timingSafeEqual)(sigBuf, expectedBuf)) {
4027
+ const expectedSig = await hmacSha256Hex(this.secret, payload);
4028
+ if (!timingSafeEqualStr(sig, expectedSig)) {
3210
4029
  return { valid: false, reason: "invalid_signature" };
3211
4030
  }
3212
4031
  if (this.store.isUsed(sig)) {
3213
4032
  return { valid: false, reason: "token_already_used" };
3214
4033
  }
3215
4034
  if (ip) {
3216
- const expectedIpHash = (0, import_crypto4.createHash)("sha256").update(ip).digest("hex").slice(0, 8);
4035
+ const expectedIpHash = (await sha256Hex(ip)).slice(0, 8);
3217
4036
  if (decoded.ip_hash !== expectedIpHash) {
3218
4037
  return { valid: false, reason: "ip_mismatch" };
3219
4038
  }
@@ -3246,21 +4065,21 @@ var Captcha = class {
3246
4065
  this.trustedJA4Headers = options.trustedJA4Headers ?? [];
3247
4066
  }
3248
4067
  /** Issue a PoW challenge for the client to solve (difficulty auto-scaled). */
3249
- issueChallenge(siteKey, ip, difficulty) {
4068
+ async issueChallenge(siteKey, ip, difficulty) {
3250
4069
  return this.pow.generate(siteKey, ip, difficulty);
3251
4070
  }
3252
4071
  /**
3253
4072
  * Verify a submission: checks the signals commitment, verifies PoW, scores the
3254
4073
  * signals, and issues a session token on success. Mirrors `runVerification`.
3255
4074
  */
3256
- verify(input) {
4075
+ async verify(input) {
3257
4076
  const { siteKey, ip, userAgent } = input;
3258
4077
  const headers = input.headers ?? {};
3259
4078
  let signals = input.signals ?? {};
3260
4079
  const extraDetections = [];
3261
4080
  const clientSignalsHash = input.powSolution?.signalsHash ?? null;
3262
4081
  if (input.signalsJson && clientSignalsHash) {
3263
- const computed = (0, import_crypto5.createHash)("sha256").update(input.signalsJson).digest("hex");
4082
+ const computed = await sha256Hex(input.signalsJson);
3264
4083
  if (computed !== clientSignalsHash) {
3265
4084
  extraDetections.push({
3266
4085
  category: "bot",
@@ -3279,7 +4098,7 @@ var Captcha = class {
3279
4098
  }
3280
4099
  let pow;
3281
4100
  if (input.powSolution && input.powSolution.challengeId) {
3282
- const result = this.pow.verify(input.powSolution, siteKey, clientSignalsHash);
4101
+ const result = await this.pow.verify(input.powSolution, siteKey, clientSignalsHash);
3283
4102
  pow = {
3284
4103
  provided: true,
3285
4104
  valid: result.valid,
@@ -3300,12 +4119,12 @@ var Captcha = class {
3300
4119
  pow,
3301
4120
  extraDetections
3302
4121
  });
3303
- const token = verdict.success ? this.tokens.issue(ip, siteKey, verdict.score) : null;
4122
+ const token = verdict.success ? await this.tokens.issue(ip, siteKey, verdict.score) : null;
3304
4123
  return { ...verdict, token };
3305
4124
  }
3306
4125
  /** Invisible-mode scoring — same pipeline, returns a compact result + action. */
3307
- score(input) {
3308
- const result = this.verify(input);
4126
+ async score(input) {
4127
+ const result = await this.verify(input);
3309
4128
  return {
3310
4129
  success: result.success,
3311
4130
  score: result.score,
@@ -3315,7 +4134,7 @@ var Captcha = class {
3315
4134
  };
3316
4135
  }
3317
4136
  /** Verify a previously issued token (single-use, optionally IP-bound). */
3318
- verifyToken(token, ip = null) {
4137
+ async verifyToken(token, ip = null) {
3319
4138
  return this.tokens.verify(token, ip);
3320
4139
  }
3321
4140
  };
@@ -3342,11 +4161,11 @@ function createCaptchaEndpoints(options = {}) {
3342
4161
  const ja3Hash = req.headers["x-ja3-hash"] ?? null;
3343
4162
  if (sub === "/challenge" && method === "GET") {
3344
4163
  const siteKey = req.query.siteKey ?? "default";
3345
- return json(200, captcha.issueChallenge(siteKey, req.ip));
4164
+ return json(200, await captcha.issueChallenge(siteKey, req.ip));
3346
4165
  }
3347
4166
  if (sub === "/verify" && method === "POST") {
3348
4167
  const b = req.body ?? {};
3349
- const result = captcha.verify({
4168
+ const result = await captcha.verify({
3350
4169
  siteKey: b.siteKey ?? "default",
3351
4170
  ip: req.ip,
3352
4171
  userAgent,
@@ -3361,7 +4180,7 @@ function createCaptchaEndpoints(options = {}) {
3361
4180
  }
3362
4181
  if (sub === "/score" && method === "POST") {
3363
4182
  const b = req.body ?? {};
3364
- const result = captcha.score({
4183
+ const result = await captcha.score({
3365
4184
  siteKey: b.siteKey ?? "default",
3366
4185
  ip: req.ip,
3367
4186
  userAgent,
@@ -3378,7 +4197,7 @@ function createCaptchaEndpoints(options = {}) {
3378
4197
  if (sub === "/token/verify" && method === "POST") {
3379
4198
  const b = req.body ?? {};
3380
4199
  if (!b.token) return json(400, { valid: false, reason: "missing_token" });
3381
- return json(200, captcha.verifyToken(b.token, req.ip));
4200
+ return json(200, await captcha.verifyToken(b.token, req.ip));
3382
4201
  }
3383
4202
  return json(404, { error: "not_found" });
3384
4203
  }
@@ -3386,10 +4205,13 @@ function createCaptchaEndpoints(options = {}) {
3386
4205
  }
3387
4206
  // Annotate the CommonJS export names for ESM import in node:
3388
4207
  0 && (module.exports = {
4208
+ AgentVerifier,
3389
4209
  Captcha,
4210
+ DEFAULT_SIGNED_AGENT_DIRECTORIES,
3390
4211
  DEFAULT_TRIPWIRE_PATHS,
3391
4212
  DEFAULT_WEIGHTS,
3392
4213
  DetectionEngine,
4214
+ DirectoryCache,
3393
4215
  FilterRule,
3394
4216
  InMemoryChallengeStore,
3395
4217
  InMemoryFingerprintStore,
@@ -3400,9 +4222,11 @@ function createCaptchaEndpoints(options = {}) {
3400
4222
  RuleEngine,
3401
4223
  TokenManager,
3402
4224
  TripwireRule,
4225
+ WebBotAuthRule,
3403
4226
  WebDecoy,
3404
4227
  calculateCategoryScores,
3405
4228
  calculateFinalScore,
4229
+ createAgentVerifier,
3406
4230
  createCaptchaEndpoints,
3407
4231
  filter,
3408
4232
  honeytoken,
@@ -3412,5 +4236,6 @@ function createCaptchaEndpoints(options = {}) {
3412
4236
  rateLimit,
3413
4237
  recommend,
3414
4238
  resolveSecret,
3415
- tripwire
4239
+ tripwire,
4240
+ webBotAuth
3416
4241
  });