@webdecoy/node 0.4.1 → 0.6.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,20 @@ 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,
30
+ EDGE_CLASS_HEADER: () => EDGE_CLASS_HEADER,
31
+ EDGE_CLEARANCE_HEADER: () => EDGE_CLEARANCE_HEADER,
37
32
  FilterRule: () => FilterRule,
38
33
  InMemoryChallengeStore: () => InMemoryChallengeStore,
39
34
  InMemoryFingerprintStore: () => InMemoryFingerprintStore,
@@ -44,9 +39,11 @@ __export(index_exports, {
44
39
  RuleEngine: () => RuleEngine,
45
40
  TokenManager: () => TokenManager,
46
41
  TripwireRule: () => TripwireRule,
42
+ WebBotAuthRule: () => WebBotAuthRule,
47
43
  WebDecoy: () => WebDecoy,
48
44
  calculateCategoryScores: () => calculateCategoryScores,
49
45
  calculateFinalScore: () => calculateFinalScore,
46
+ createAgentVerifier: () => createAgentVerifier,
50
47
  createCaptchaEndpoints: () => createCaptchaEndpoints,
51
48
  filter: () => filter,
52
49
  honeytoken: () => honeytoken,
@@ -54,99 +51,110 @@ __export(index_exports, {
54
51
  isMobileUA: () => isMobileUA,
55
52
  parseUserAgent: () => parseUserAgent,
56
53
  rateLimit: () => rateLimit,
54
+ readEdgeVerdict: () => readEdgeVerdict,
57
55
  recommend: () => recommend,
58
56
  resolveSecret: () => resolveSecret,
59
- tripwire: () => tripwire
57
+ tripwire: () => tripwire,
58
+ webBotAuth: () => webBotAuth
60
59
  });
61
60
  module.exports = __toCommonJS(index_exports);
62
61
 
63
62
  // src/client.ts
64
- var import_axios = __toESM(require("axios"));
65
- var import_https = __toESM(require("https"));
66
63
  var WebDecoyClient = class {
67
64
  constructor(config) {
68
65
  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;
66
+ this.baseUrl = config.apiUrl.replace(/\/+$/, "");
67
+ this.headers = {
68
+ "Content-Type": "application/json",
69
+ Authorization: `Bearer ${config.apiKey}`,
70
+ "User-Agent": "webdecoy-node-sdk/0.1.0"
71
+ };
72
+ if (config.tlsRejectUnauthorized === false && config.debug) {
73
+ console.warn(
74
+ "[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."
75
+ );
76
+ }
77
+ }
78
+ async request(method, path, body) {
79
+ const controller = new AbortController();
80
+ const timer = setTimeout(() => controller.abort(), this.config.timeout);
81
+ if (typeof timer.unref === "function") {
82
+ timer.unref();
83
+ }
84
+ if (this.config.debug) {
85
+ console.log("[WebDecoy] Request:", { method, url: this.baseUrl + path, data: body });
86
+ }
87
+ try {
88
+ const response = await fetch(this.baseUrl + path, {
89
+ method,
90
+ headers: this.headers,
91
+ body: body === void 0 ? void 0 : JSON.stringify(body),
92
+ signal: controller.signal
90
93
  });
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);
94
+ let data;
95
+ const text = await response.text();
96
+ if (text) {
97
+ try {
98
+ data = JSON.parse(text);
99
+ } catch {
100
+ data = void 0;
105
101
  }
106
- );
102
+ }
103
+ if (this.config.debug) {
104
+ console.log("[WebDecoy] Response:", { status: response.status, data });
105
+ }
106
+ return { status: response.status, data };
107
+ } catch (error) {
108
+ if (this.config.debug) {
109
+ console.error("[WebDecoy] Error:", {
110
+ message: error instanceof Error ? error.message : String(error)
111
+ });
112
+ }
113
+ throw error;
114
+ } finally {
115
+ clearTimeout(timer);
107
116
  }
108
117
  }
109
118
  /**
110
119
  * Send a detection request to the ingest service
111
120
  */
112
121
  async detect(request) {
122
+ let response;
113
123
  try {
114
- const response = await this.axios.post(
124
+ response = await this.request(
125
+ "POST",
115
126
  "/api/v1/sdk/detect",
116
127
  request
117
128
  );
118
- return response.data;
119
129
  } 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}`);
130
+ if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) {
131
+ throw new Error("Request timeout. The Web Decoy service did not respond in time.");
132
+ }
133
+ if (error instanceof TypeError) {
134
+ throw new Error("Unable to connect to Web Decoy service. Please check your network.");
140
135
  }
141
136
  throw error;
142
137
  }
138
+ if (response.status === 401) {
139
+ throw new Error("Invalid API key. Please check your Web Decoy configuration.");
140
+ }
141
+ if (response.status === 429) {
142
+ throw new Error("Rate limit exceeded. Please try again later.");
143
+ }
144
+ if (response.status >= 400) {
145
+ if (response.data?.error || response.data?.message) {
146
+ throw new Error(response.data.error || response.data.message || "API error");
147
+ }
148
+ throw new Error(`API request failed: HTTP ${response.status}`);
149
+ }
150
+ return response.data;
143
151
  }
144
152
  /**
145
153
  * Send violation events to the ingest service
146
154
  */
147
155
  async sendViolations(events) {
148
156
  try {
149
- await this.axios.post("/api/v1/sdk/violations/batch", { events });
157
+ await this.request("POST", "/api/v1/sdk/violations/batch", { events });
150
158
  } catch (error) {
151
159
  if (this.config.debug) {
152
160
  console.error("[WebDecoy] Failed to send violations:", error);
@@ -158,10 +166,12 @@ var WebDecoyClient = class {
158
166
  */
159
167
  async getIPEnrichment(ip) {
160
168
  try {
161
- const response = await this.axios.get(
169
+ const response = await this.request(
170
+ "GET",
162
171
  `/api/v1/sdk/ip/${encodeURIComponent(ip)}/enrichment`
163
172
  );
164
- return response.data;
173
+ if (response.status >= 400) return null;
174
+ return response.data ?? null;
165
175
  } catch (error) {
166
176
  if (this.config.debug) {
167
177
  console.error("[WebDecoy] Failed to get IP enrichment:", error);
@@ -325,6 +335,18 @@ function analyzeRequest(metadata) {
325
335
  }
326
336
 
327
337
  // src/rules/rule-engine.ts
338
+ function extractClearance(headers) {
339
+ const cookie = headers["cookie"];
340
+ if (!cookie) return void 0;
341
+ for (const part of cookie.split(";")) {
342
+ const eq = part.indexOf("=");
343
+ if (eq < 0) continue;
344
+ if (part.slice(0, eq).trim() === "wd_clearance") {
345
+ return part.slice(eq + 1).trim() || void 0;
346
+ }
347
+ }
348
+ return void 0;
349
+ }
328
350
  var RuleEngine = class {
329
351
  constructor(rules) {
330
352
  this.rules = rules;
@@ -347,6 +369,7 @@ var RuleEngine = class {
347
369
  method: context.method,
348
370
  userAgent: context.userAgent,
349
371
  reason: result.reason,
372
+ clearance: result.rule === "tripwire" ? extractClearance(context.headers) : void 0,
350
373
  metadata: result.metadata,
351
374
  dryRun: result.metadata?.dryRun === true,
352
375
  timestamp: new Date(context.timestamp).toISOString()
@@ -484,12 +507,646 @@ var IPEnrichmentClient = class {
484
507
  }
485
508
  };
486
509
 
510
+ // src/agent/thumbprint.ts
511
+ var encoder = new TextEncoder();
512
+ async function rsaThumbprint(n, e) {
513
+ return digest(`{"e":${JSON.stringify(e)},"kty":"RSA","n":${JSON.stringify(n)}}`);
514
+ }
515
+ async function okpThumbprint(crv, x) {
516
+ return digest(`{"crv":${JSON.stringify(crv)},"kty":"OKP","x":${JSON.stringify(x)}}`);
517
+ }
518
+ async function jwkThumbprint(k) {
519
+ switch (k.kty) {
520
+ case "OKP":
521
+ if (!k.crv || !k.x) throw new Error("thumbprint: OKP JWK missing crv or x");
522
+ return okpThumbprint(k.crv, k.x);
523
+ case "RSA":
524
+ if (!k.n || !k.e) throw new Error("thumbprint: RSA JWK missing n or e");
525
+ return rsaThumbprint(k.n, k.e);
526
+ default:
527
+ throw new Error(`thumbprint: unsupported kty ${JSON.stringify(k.kty)}`);
528
+ }
529
+ }
530
+ async function digest(canonical) {
531
+ const buf = await crypto.subtle.digest("SHA-256", encoder.encode(canonical));
532
+ return base64urlBytes(new Uint8Array(buf));
533
+ }
534
+ function base64urlBytes(bytes) {
535
+ let binary = "";
536
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
537
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
538
+ }
539
+
540
+ // src/agent/directory.ts
541
+ var WELL_KNOWN = "/.well-known/http-message-signatures-directory";
542
+ var COLD_RETRY_BACKOFF_MS = 3e4;
543
+ var DEFAULT_SIGNED_AGENT_DIRECTORIES = [
544
+ { name: "OpenAI", category: "ai_crawlers", directory: "https://operator.openai.com" },
545
+ { name: "OpenAI ChatGPT", category: "ai_crawlers", directory: "https://chatgpt.com" }
546
+ ];
547
+ var DirectoryCache = class {
548
+ constructor(opts) {
549
+ this.keys = /* @__PURE__ */ new Map();
550
+ this.refreshedAt = 0;
551
+ this.nextColdRetryAt = 0;
552
+ this.inflight = null;
553
+ /** Resolve a keyid to a verification key, fetching/refreshing as needed. */
554
+ this.resolveKey = async (keyId) => {
555
+ await this.ensureFresh();
556
+ return this.keys.get(keyId);
557
+ };
558
+ this.opts = opts;
559
+ }
560
+ /** Kick off a fetch without blocking — call at startup to warm the cache. */
561
+ prime() {
562
+ if (this.keys.size === 0 && Date.now() >= this.nextColdRetryAt) void this.refresh();
563
+ }
564
+ /** Number of keys currently cached (diagnostics/tests). */
565
+ get size() {
566
+ return this.keys.size;
567
+ }
568
+ async ensureFresh() {
569
+ const now = Date.now();
570
+ const stale = now - this.refreshedAt > this.opts.cacheTtlMs;
571
+ if (this.keys.size > 0) {
572
+ if (stale) void this.refresh();
573
+ return;
574
+ }
575
+ if (now < this.nextColdRetryAt) return;
576
+ await this.refresh();
577
+ }
578
+ /** Re-fetch every directory. De-duplicated: concurrent callers share one run. */
579
+ refresh() {
580
+ if (this.inflight) return this.inflight;
581
+ this.inflight = this.doRefresh().finally(() => {
582
+ this.inflight = null;
583
+ });
584
+ return this.inflight;
585
+ }
586
+ async doRefresh() {
587
+ const results = await Promise.all(
588
+ this.opts.directories.map((src) => this.fetchDirectory(src))
589
+ );
590
+ const next = new Map(this.keys);
591
+ let fetchedAny = false;
592
+ for (const keys of results) {
593
+ if (keys === null) continue;
594
+ fetchedAny = true;
595
+ for (const k of keys) next.set(k.thumbprint, k.key);
596
+ }
597
+ if (fetchedAny) {
598
+ this.keys = next;
599
+ this.refreshedAt = Date.now();
600
+ this.nextColdRetryAt = 0;
601
+ this.debug(`refreshed: ${this.keys.size} key(s) across ${this.opts.directories.length} directories`);
602
+ } else if (this.keys.size === 0) {
603
+ this.nextColdRetryAt = Date.now() + COLD_RETRY_BACKOFF_MS;
604
+ this.debug("all directories unreachable; backing off cold retry");
605
+ }
606
+ }
607
+ async fetchDirectory(src) {
608
+ const url = directoryUrl(src.directory);
609
+ const controller = new AbortController();
610
+ const timer = setTimeout(() => controller.abort(), this.opts.fetchTimeoutMs);
611
+ try {
612
+ const res = await this.opts.fetchImpl(url, {
613
+ signal: controller.signal,
614
+ headers: {
615
+ Accept: "application/http-message-signatures-directory+json, application/jwk-set+json, application/json"
616
+ },
617
+ redirect: "follow"
618
+ });
619
+ if (!res.ok) {
620
+ this.debug(`${src.name}: HTTP ${res.status}`);
621
+ return null;
622
+ }
623
+ const body = await res.json();
624
+ if (!body || !Array.isArray(body.keys)) {
625
+ this.debug(`${src.name}: no keys in directory`);
626
+ return null;
627
+ }
628
+ const out = [];
629
+ for (const jwk of body.keys) {
630
+ const resolved = await importKey(jwk, src);
631
+ if (resolved) out.push(resolved);
632
+ }
633
+ this.debug(`${src.name}: ${out.length} key(s)`);
634
+ return out;
635
+ } catch (err) {
636
+ this.debug(`${src.name}: fetch failed \u2014 ${err.message}`);
637
+ return null;
638
+ } finally {
639
+ clearTimeout(timer);
640
+ }
641
+ }
642
+ debug(msg) {
643
+ if (this.opts.debug) console.log(`[WebDecoy][web-bot-auth] ${msg}`);
644
+ }
645
+ };
646
+ function directoryUrl(directory) {
647
+ const u = new URL(directory);
648
+ if (u.pathname && u.pathname !== "/") return u.toString();
649
+ u.pathname = WELL_KNOWN;
650
+ return u.toString();
651
+ }
652
+ async function importKey(jwk, src) {
653
+ try {
654
+ let cryptoKey;
655
+ let verifyParams;
656
+ let algorithm;
657
+ if (jwk.kty === "OKP") {
658
+ if (jwk.crv !== "Ed25519" || !jwk.x) return null;
659
+ cryptoKey = await crypto.subtle.importKey(
660
+ "jwk",
661
+ { kty: "OKP", crv: "Ed25519", x: jwk.x },
662
+ { name: "Ed25519" },
663
+ false,
664
+ ["verify"]
665
+ );
666
+ verifyParams = { name: "Ed25519" };
667
+ algorithm = "ed25519";
668
+ } else if (jwk.kty === "RSA") {
669
+ if (!jwk.n || !jwk.e) return null;
670
+ cryptoKey = await crypto.subtle.importKey(
671
+ "jwk",
672
+ { kty: "RSA", n: jwk.n, e: jwk.e },
673
+ { name: "RSA-PSS", hash: "SHA-512" },
674
+ false,
675
+ ["verify"]
676
+ );
677
+ verifyParams = { name: "RSA-PSS", saltLength: 64 };
678
+ algorithm = "rsa-pss-sha512";
679
+ } else {
680
+ return null;
681
+ }
682
+ const thumbprint = await jwkThumbprint(jwk);
683
+ return {
684
+ thumbprint,
685
+ key: {
686
+ cryptoKey,
687
+ verifyParams,
688
+ algorithm,
689
+ name: src.name,
690
+ category: src.category,
691
+ nbf: normalizeEpoch(jwk.nbf),
692
+ exp: normalizeEpoch(jwk.exp)
693
+ }
694
+ };
695
+ } catch {
696
+ return null;
697
+ }
698
+ }
699
+ function normalizeEpoch(v) {
700
+ if (v === void 0 || v === 0) return void 0;
701
+ return v > 1e12 ? Math.floor(v / 1e3) : v;
702
+ }
703
+
704
+ // src/agent/sfv.ts
705
+ var Cursor = class {
706
+ constructor(s, i = 0) {
707
+ this.s = s;
708
+ this.i = i;
709
+ }
710
+ eof() {
711
+ return this.i >= this.s.length;
712
+ }
713
+ peek() {
714
+ return this.s[this.i];
715
+ }
716
+ skipSP() {
717
+ while (!this.eof() && (this.peek() === " " || this.peek() === " ")) this.i++;
718
+ }
719
+ };
720
+ function parseDictionary(input) {
721
+ const p = new Cursor(input);
722
+ const out = [];
723
+ p.skipSP();
724
+ while (!p.eof()) {
725
+ const key = parseKey(p);
726
+ const entry = { key, raw: "", isList: false, items: [], params: /* @__PURE__ */ new Map() };
727
+ if (!p.eof() && p.peek() === "=") {
728
+ p.i++;
729
+ const start = p.i;
730
+ if (!p.eof() && p.peek() === "(") {
731
+ entry.isList = true;
732
+ parseInnerList(p, entry);
733
+ } else {
734
+ entry.items.push(parseItem(p));
735
+ entry.params = entry.items[0].params;
736
+ }
737
+ entry.raw = input.slice(start, p.i);
738
+ } else {
739
+ entry.params = parseParams(p);
740
+ entry.items.push({ value: true, params: /* @__PURE__ */ new Map() });
741
+ entry.raw = "?1";
742
+ }
743
+ out.push(entry);
744
+ p.skipSP();
745
+ if (p.eof()) break;
746
+ if (p.peek() !== ",") throw new Error(`sfv: expected ',' at ${p.i}`);
747
+ p.i++;
748
+ p.skipSP();
749
+ if (p.eof()) throw new Error("sfv: trailing comma");
750
+ }
751
+ return out;
752
+ }
753
+ function parseInnerList(p, entry) {
754
+ p.i++;
755
+ for (; ; ) {
756
+ p.skipSP();
757
+ if (p.eof()) throw new Error("sfv: unterminated inner list");
758
+ if (p.peek() === ")") {
759
+ p.i++;
760
+ break;
761
+ }
762
+ entry.items.push(parseItem(p));
763
+ if (p.eof()) throw new Error("sfv: unterminated inner list");
764
+ const c = p.peek();
765
+ if (c !== " " && c !== ")") throw new Error(`sfv: bad inner list at ${p.i}`);
766
+ }
767
+ entry.params = parseParams(p);
768
+ }
769
+ function parseItem(p) {
770
+ const { value, bytes } = parseBareItem(p);
771
+ const params = parseParams(p);
772
+ return bytes ? { value, params, bytes } : { value, params };
773
+ }
774
+ function parseParams(p) {
775
+ const params = /* @__PURE__ */ new Map();
776
+ while (!p.eof() && p.peek() === ";") {
777
+ p.i++;
778
+ p.skipSP();
779
+ const key = parseKey(p);
780
+ let val = true;
781
+ if (!p.eof() && p.peek() === "=") {
782
+ p.i++;
783
+ val = parseBareItem(p).value;
784
+ }
785
+ params.set(key, val);
786
+ }
787
+ return params;
788
+ }
789
+ function parseKey(p) {
790
+ const c = p.peek();
791
+ if (!c || !/[a-z*]/.test(c)) throw new Error(`sfv: invalid key at ${p.i}`);
792
+ const start = p.i;
793
+ while (!p.eof() && /[a-z0-9_\-.*]/.test(p.peek())) p.i++;
794
+ return p.s.slice(start, p.i);
795
+ }
796
+ function parseBareItem(p) {
797
+ const c = p.peek();
798
+ if (c === '"') return { value: parseString(p) };
799
+ if (c === ":") return { value: "", bytes: parseByteSequence(p) };
800
+ if (c === "?") {
801
+ p.i++;
802
+ const b = p.s[p.i++];
803
+ if (b === "1") return { value: true };
804
+ if (b === "0") return { value: false };
805
+ throw new Error("sfv: bad boolean");
806
+ }
807
+ if (c === "-" || /[0-9]/.test(c)) return { value: parseNumber(p) };
808
+ if (/[a-zA-Z*]/.test(c)) return { value: parseToken(p) };
809
+ throw new Error(`sfv: invalid bare item at ${p.i}`);
810
+ }
811
+ function parseString(p) {
812
+ p.i++;
813
+ let out = "";
814
+ while (!p.eof()) {
815
+ const c = p.s[p.i++];
816
+ if (c === '"') return out;
817
+ if (c === "\\") {
818
+ const e = p.s[p.i++];
819
+ if (e !== '"' && e !== "\\") throw new Error("sfv: bad escape");
820
+ out += e;
821
+ } else {
822
+ const code = c.charCodeAt(0);
823
+ if (code < 32 || code > 126) throw new Error("sfv: bad char in string");
824
+ out += c;
825
+ }
826
+ }
827
+ throw new Error("sfv: unterminated string");
828
+ }
829
+ function parseByteSequence(p) {
830
+ p.i++;
831
+ const start = p.i;
832
+ while (!p.eof() && p.peek() !== ":") p.i++;
833
+ if (p.eof()) throw new Error("sfv: unterminated byte sequence");
834
+ const b64 = p.s.slice(start, p.i);
835
+ p.i++;
836
+ return base64StdToBytes(b64);
837
+ }
838
+ function parseNumber(p) {
839
+ const start = p.i;
840
+ if (p.peek() === "-") p.i++;
841
+ while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
842
+ if (!p.eof() && p.peek() === ".") {
843
+ p.i++;
844
+ while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
845
+ }
846
+ return Number(p.s.slice(start, p.i));
847
+ }
848
+ function parseToken(p) {
849
+ const start = p.i;
850
+ p.i++;
851
+ while (!p.eof() && /[a-zA-Z0-9!#$%&'*+\-.^_`|~:/]/.test(p.peek())) p.i++;
852
+ return p.s.slice(start, p.i);
853
+ }
854
+ function base64StdToBytes(s) {
855
+ const bin = atob(s);
856
+ const out = new Uint8Array(bin.length);
857
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
858
+ return out;
859
+ }
860
+
861
+ // src/agent/signature.ts
862
+ var TAG = "web-bot-auth";
863
+ var encoder2 = new TextEncoder();
864
+ async function verifyWebBotAuth(req, resolveKey, toleranceSec) {
865
+ const sigInput = req.headers.get("signature-input");
866
+ const sigHeader = req.headers.get("signature");
867
+ if (!sigInput && !sigHeader) return { outcome: "none" };
868
+ if (!sigInput || !sigHeader) return { outcome: "claimed", reason: "incomplete-signature" };
869
+ let members;
870
+ let sigs;
871
+ try {
872
+ members = parseSignatureInput(sigInput);
873
+ sigs = parseSignatureBytes(sigHeader);
874
+ } catch {
875
+ return { outcome: "claimed", reason: "malformed-signature" };
876
+ }
877
+ const now = Date.now() / 1e3;
878
+ let best = { outcome: "none" };
879
+ for (const m of members) {
880
+ if (m.params.get("tag") !== TAG) continue;
881
+ if (best.outcome === "none") best = { outcome: "claimed", reason: "unverifiable" };
882
+ const sig = sigs.get(m.label);
883
+ if (!sig) continue;
884
+ const keyid = m.params.get("keyid");
885
+ if (typeof keyid !== "string") continue;
886
+ if (!m.components.some((c) => c.name === "@authority" || c.name === "@target-uri")) continue;
887
+ const key = await resolveKey(keyid);
888
+ if (!key) {
889
+ best = higher(best, { outcome: "claimed", keyId: keyid, reason: "unknown-key" });
890
+ continue;
891
+ }
892
+ const created = numeric(m.params.get("created"));
893
+ const expires = numeric(m.params.get("expires"));
894
+ if (expires !== void 0 && now > expires + toleranceSec) {
895
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "expired" });
896
+ continue;
897
+ }
898
+ if (created !== void 0 && now + toleranceSec < created) {
899
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "not-yet-valid" });
900
+ continue;
901
+ }
902
+ if (key.exp !== void 0 && now > key.exp + toleranceSec) {
903
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-expired" });
904
+ continue;
905
+ }
906
+ if (key.nbf !== void 0 && now + toleranceSec < key.nbf) {
907
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-not-yet-valid" });
908
+ continue;
909
+ }
910
+ let base;
911
+ try {
912
+ base = buildSignatureBase(req, m);
913
+ } catch {
914
+ best = higher(best, { outcome: "claimed", keyId: keyid, reason: "uncoverable-component" });
915
+ continue;
916
+ }
917
+ let ok = false;
918
+ try {
919
+ ok = await crypto.subtle.verify(
920
+ key.verifyParams,
921
+ key.cryptoKey,
922
+ sig,
923
+ encoder2.encode(base)
924
+ );
925
+ } catch {
926
+ ok = false;
927
+ }
928
+ if (ok) {
929
+ return { outcome: "verified", keyId: keyid, key };
930
+ }
931
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "bad-signature" });
932
+ }
933
+ return best;
934
+ }
935
+ var PRECEDENCE = { none: 0, claimed: 1, impersonation: 2, verified: 3 };
936
+ function higher(a, b) {
937
+ return PRECEDENCE[b.outcome] >= PRECEDENCE[a.outcome] ? b : a;
938
+ }
939
+ function numeric(v) {
940
+ return typeof v === "number" ? v : void 0;
941
+ }
942
+ function buildSignatureBase(req, m) {
943
+ const lines = [];
944
+ for (const c of m.components) {
945
+ lines.push(`${serializeComponentId(c)}: ${componentValue(req, c)}`);
946
+ }
947
+ lines.push(`"@signature-params": ${m.raw.trim()}`);
948
+ return lines.join("\n");
949
+ }
950
+ function serializeComponentId(c) {
951
+ const base = `"${c.name.toLowerCase()}"`;
952
+ return c.keyParam !== void 0 ? `${base};key="${c.keyParam}"` : base;
953
+ }
954
+ function componentValue(req, c) {
955
+ const name = c.name.toLowerCase();
956
+ switch (name) {
957
+ case "@method":
958
+ return req.method.toUpperCase();
959
+ case "@authority":
960
+ return canonicalAuthority(req.url);
961
+ case "@scheme":
962
+ return req.url.protocol.replace(/:$/, "").toLowerCase();
963
+ case "@target-uri":
964
+ return `${req.url.protocol}//${canonicalAuthority(req.url)}${req.url.pathname}${req.url.search}`;
965
+ case "@path":
966
+ return req.url.pathname;
967
+ case "@query":
968
+ return req.url.search === "" ? "?" : req.url.search;
969
+ case "signature-agent": {
970
+ const header = req.headers.get("signature-agent");
971
+ if (header === null) throw new Error("signature-agent covered but absent");
972
+ if (c.keyParam !== void 0) return dictMemberValue(header, c.keyParam);
973
+ return header.trim().replace(/\s+/g, " ");
974
+ }
975
+ default: {
976
+ if (name.startsWith("@")) throw new Error(`unsupported derived component ${name}`);
977
+ const header = req.headers.get(name);
978
+ if (header === null) throw new Error(`covered header ${name} absent`);
979
+ return header.trim().replace(/\s+/g, " ");
980
+ }
981
+ }
982
+ }
983
+ function canonicalAuthority(url) {
984
+ const host = url.hostname.toLowerCase();
985
+ const port = url.port;
986
+ if (!port) return host;
987
+ if (url.protocol === "https:" && port === "443" || url.protocol === "http:" && port === "80") {
988
+ return host;
989
+ }
990
+ return `${host}:${port}`;
991
+ }
992
+ function dictMemberValue(header, key) {
993
+ const dict = parseDictionary(header);
994
+ const found = dict.find((d) => d.key === key);
995
+ if (!found) throw new Error(`signature-agent has no member ${key}`);
996
+ return found.raw;
997
+ }
998
+ function parseSignatureInput(value) {
999
+ return parseDictionary(value).map((d) => {
1000
+ if (!d.isList) throw new Error(`Signature-Input member ${d.key} is not an inner list`);
1001
+ const components = d.items.map((it) => {
1002
+ if (typeof it.value !== "string") throw new Error("component identifier is not a string");
1003
+ const keyParam = it.params.get("key");
1004
+ return { name: it.value, keyParam: typeof keyParam === "string" ? keyParam : void 0 };
1005
+ });
1006
+ return { label: d.key, components, params: d.params, raw: d.raw };
1007
+ });
1008
+ }
1009
+ function parseSignatureBytes(value) {
1010
+ const out = /* @__PURE__ */ new Map();
1011
+ for (const d of parseDictionary(value)) {
1012
+ if (d.isList || d.items.length !== 1 || !d.items[0].bytes) {
1013
+ throw new Error(`Signature member ${d.key} is not a byte sequence`);
1014
+ }
1015
+ out.set(d.key, d.items[0].bytes);
1016
+ }
1017
+ return out;
1018
+ }
1019
+
1020
+ // src/agent/verifier.ts
1021
+ var DEFAULT_TTL_MS = 6 * 60 * 60 * 1e3;
1022
+ var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
1023
+ var DEFAULT_TOLERANCE_SEC = 300;
1024
+ var AgentVerifier = class {
1025
+ constructor(options = {}) {
1026
+ this.toleranceSec = options.toleranceSec ?? DEFAULT_TOLERANCE_SEC;
1027
+ this.cache = new DirectoryCache({
1028
+ directories: options.directories ?? DEFAULT_SIGNED_AGENT_DIRECTORIES,
1029
+ cacheTtlMs: options.cacheTtlMs ?? DEFAULT_TTL_MS,
1030
+ fetchTimeoutMs: options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,
1031
+ debug: options.debug ?? false,
1032
+ fetchImpl: options.fetchImpl ?? fetch
1033
+ });
1034
+ }
1035
+ /** Pre-fetch trusted directories so the first request verifies warm. */
1036
+ warmup() {
1037
+ this.cache.prime();
1038
+ }
1039
+ /** Verify a request's Web Bot Auth signature (if any) locally. */
1040
+ async verify(request) {
1041
+ let req;
1042
+ try {
1043
+ req = normalize(request);
1044
+ } catch {
1045
+ return { status: "none" };
1046
+ }
1047
+ const result = await verifyWebBotAuth(req, this.cache.resolveKey, this.toleranceSec);
1048
+ switch (result.outcome) {
1049
+ case "verified":
1050
+ return {
1051
+ status: "verified",
1052
+ method: "signature",
1053
+ keyId: result.keyId,
1054
+ agentName: result.key?.name,
1055
+ category: result.key?.category,
1056
+ algorithm: result.key?.algorithm
1057
+ };
1058
+ case "impersonation":
1059
+ return {
1060
+ status: "impersonation",
1061
+ method: "signature",
1062
+ keyId: result.keyId,
1063
+ agentName: result.key?.name,
1064
+ category: result.key?.category,
1065
+ reason: result.reason
1066
+ };
1067
+ case "claimed":
1068
+ return { status: "claimed", keyId: result.keyId, reason: result.reason };
1069
+ default:
1070
+ return { status: "none" };
1071
+ }
1072
+ }
1073
+ /** Cached-key count (diagnostics/tests). */
1074
+ get cachedKeyCount() {
1075
+ return this.cache.size;
1076
+ }
1077
+ };
1078
+ function createAgentVerifier(options = {}) {
1079
+ return new AgentVerifier(options);
1080
+ }
1081
+ function normalize(input) {
1082
+ if (isRequest(input)) {
1083
+ return { method: input.method, url: new URL(input.url), headers: input.headers };
1084
+ }
1085
+ const headers = input.headers instanceof Headers ? input.headers : toHeaders(input.headers);
1086
+ return { method: input.method, url: new URL(input.url), headers };
1087
+ }
1088
+ function isRequest(input) {
1089
+ return typeof Request !== "undefined" && input instanceof Request && typeof input.url === "string";
1090
+ }
1091
+ function toHeaders(record) {
1092
+ const h = new Headers();
1093
+ for (const [k, v] of Object.entries(record)) {
1094
+ if (v !== void 0 && v !== null) h.set(k, String(v));
1095
+ }
1096
+ return h;
1097
+ }
1098
+
1099
+ // src/edge.ts
1100
+ var EDGE_CLEARANCE_HEADER = "x-wd-clearance";
1101
+ var EDGE_CLASS_HEADER = "x-wd-class";
1102
+ var EDGE_CLASSES = ["verified", "crawler", "script", "browser"];
1103
+ function absent() {
1104
+ return {
1105
+ present: false,
1106
+ isVerified: false,
1107
+ isCrawler: false,
1108
+ isScript: false,
1109
+ isBrowser: false,
1110
+ isUnattestedNonBrowser: false
1111
+ };
1112
+ }
1113
+ function normaliseClass(raw) {
1114
+ if (!raw) return void 0;
1115
+ const v = raw.trim().toLowerCase();
1116
+ return EDGE_CLASSES.includes(v) ? v : void 0;
1117
+ }
1118
+ function readEdgeVerdict(headers) {
1119
+ if (!headers) return absent();
1120
+ let clearanceRaw;
1121
+ let classRaw;
1122
+ for (const key of Object.keys(headers)) {
1123
+ const k = key.toLowerCase();
1124
+ if (k === EDGE_CLEARANCE_HEADER) clearanceRaw = headers[key];
1125
+ else if (k === EDGE_CLASS_HEADER) classRaw = headers[key];
1126
+ }
1127
+ const clearance = clearanceRaw?.trim() || void 0;
1128
+ const cls = normaliseClass(classRaw);
1129
+ if (!clearance && !cls) return absent();
1130
+ return {
1131
+ present: true,
1132
+ clearance,
1133
+ class: cls,
1134
+ isVerified: cls === "verified",
1135
+ isCrawler: cls === "crawler",
1136
+ isScript: cls === "script",
1137
+ isBrowser: cls === "browser",
1138
+ isUnattestedNonBrowser: cls === "script" || cls === "crawler"
1139
+ };
1140
+ }
1141
+
487
1142
  // src/sdk.ts
488
1143
  var WebDecoy = class {
489
1144
  constructor(config) {
490
1145
  this.violationReporter = null;
491
1146
  this.ipEnrichmentClient = null;
492
1147
  this._hasFilterRules = false;
1148
+ this._hasAgentRules = false;
1149
+ this.agentVerifier = null;
493
1150
  const hasApiKey = !!config.apiKey;
494
1151
  if (hasApiKey) {
495
1152
  if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
@@ -521,11 +1178,16 @@ var WebDecoy = class {
521
1178
  console.log("[WebDecoy] Running in local-only mode (no API key). Rules will still evaluate.");
522
1179
  }
523
1180
  }
1181
+ this.webBotAuthOptions = config.webBotAuth;
524
1182
  if (config.rules && config.rules.length > 0) {
525
1183
  this.ruleEngine = new RuleEngine(config.rules);
526
1184
  this._hasFilterRules = config.rules.some(
527
1185
  (r) => r.name.startsWith("filter:")
528
1186
  );
1187
+ this._hasAgentRules = config.rules.some((r) => r.name === "web-bot-auth");
1188
+ if (this._hasAgentRules) {
1189
+ this.getAgentVerifier().warmup();
1190
+ }
529
1191
  } else {
530
1192
  this.ruleEngine = null;
531
1193
  }
@@ -554,52 +1216,111 @@ var WebDecoy = class {
554
1216
  */
555
1217
  evaluateRules(metadata) {
556
1218
  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;
1219
+ return this.runRules(this.buildContext(metadata));
570
1220
  }
571
1221
  /**
572
- * Evaluate rules with async IP enrichment pre-fetch.
573
- * Use this instead of evaluateRules() when filter rules are present.
1222
+ * Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth
1223
+ * verification). Use this instead of evaluateRules() when filter rules or
1224
+ * webBotAuth() rules are present.
574
1225
  */
575
1226
  async evaluateRulesAsync(metadata) {
576
1227
  if (!this.ruleEngine) return null;
577
- const context = {
1228
+ const context = await this.buildAsyncContext(metadata);
1229
+ return this.runRules(context);
1230
+ }
1231
+ /** Build the base (synchronous) rule context from request metadata. */
1232
+ buildContext(metadata) {
1233
+ return {
578
1234
  ip: metadata.ip,
579
1235
  path: metadata.path,
580
1236
  method: metadata.method,
581
1237
  userAgent: metadata.user_agent,
582
1238
  headers: metadata.headers,
583
- timestamp: metadata.timestamp || Date.now()
1239
+ timestamp: metadata.timestamp || Date.now(),
1240
+ // Parsed synchronously and unconditionally (#481): it is two header reads,
1241
+ // it needs no network, and a rule that has to check whether the edge
1242
+ // verdict was populated is a rule people will get wrong.
1243
+ edge: readEdgeVerdict(metadata.headers)
584
1244
  };
1245
+ }
1246
+ /**
1247
+ * Build a rule context with async signals resolved: IP enrichment (for
1248
+ * filter rules) and the Web Bot Auth verdict (for webBotAuth() rules).
1249
+ */
1250
+ async buildAsyncContext(metadata) {
1251
+ const context = this.buildContext(metadata);
585
1252
  if (this._hasFilterRules && this.ipEnrichmentClient) {
586
1253
  const enrichment = await this.ipEnrichmentClient.enrich(metadata.ip);
587
1254
  if (enrichment) {
588
1255
  context.enrichment = enrichment;
589
1256
  }
590
1257
  }
1258
+ if (this._hasAgentRules) {
1259
+ context.agent = await this.computeAgentVerdict(metadata);
1260
+ }
1261
+ return context;
1262
+ }
1263
+ /** Evaluate rules against a prepared context and report any violations. */
1264
+ runRules(context) {
1265
+ if (!this.ruleEngine) return null;
591
1266
  const result = this.ruleEngine.evaluate(context);
592
1267
  if (result.violations.length > 0 && this.violationReporter) {
593
1268
  this.violationReporter.report(result.violations);
594
1269
  }
595
1270
  return result;
596
1271
  }
1272
+ /** Lazily construct the shared Web Bot Auth verifier (one directory cache). */
1273
+ getAgentVerifier() {
1274
+ if (!this.agentVerifier) {
1275
+ this.agentVerifier = new AgentVerifier({
1276
+ debug: this.config.debug,
1277
+ ...this.webBotAuthOptions
1278
+ });
1279
+ }
1280
+ return this.agentVerifier;
1281
+ }
1282
+ /**
1283
+ * Verify a request's Web Bot Auth signature locally, deriving the request
1284
+ * URL/authority from its metadata. Returns undefined when the request lacks
1285
+ * the host information needed to verify (verdict is then simply absent).
1286
+ */
1287
+ async computeAgentVerdict(metadata) {
1288
+ const input = agentInputFromMetadata(metadata);
1289
+ if (!input) return void 0;
1290
+ return this.getAgentVerifier().verify(input);
1291
+ }
1292
+ /**
1293
+ * Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag
1294
+ * "web-bot-auth"). Returns whether it is a cryptographically `verified`
1295
+ * agent, an `impersonation` of a known one, an unverifiable `claimed`
1296
+ * signature, or `none`. No network on the warm path.
1297
+ *
1298
+ * Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }`
1299
+ * object (Node).
1300
+ *
1301
+ * @example
1302
+ * ```ts
1303
+ * const verdict = await webdecoy.detectBot(request);
1304
+ * if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 });
1305
+ * if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName);
1306
+ * ```
1307
+ */
1308
+ async detectBot(request) {
1309
+ return this.getAgentVerifier().verify(request);
1310
+ }
597
1311
  /**
598
1312
  * Whether this SDK instance has filter rules that need async enrichment
599
1313
  */
600
1314
  get hasFilterRules() {
601
1315
  return this._hasFilterRules;
602
1316
  }
1317
+ /**
1318
+ * Whether this SDK instance has Web Bot Auth rules that need async
1319
+ * verification before evaluation.
1320
+ */
1321
+ get hasAgentRules() {
1322
+ return this._hasAgentRules;
1323
+ }
603
1324
  /**
604
1325
  * Protect a request by checking it against Web Decoy's bot detection
605
1326
  *
@@ -608,6 +1329,11 @@ var WebDecoy = class {
608
1329
  * @returns Protection result with decision and detection details
609
1330
  */
610
1331
  async protect(metadata, options = {}) {
1332
+ const edge = readEdgeVerdict(metadata.headers);
1333
+ const result = await this.decide(metadata, options);
1334
+ return { ...result, edge };
1335
+ }
1336
+ async decide(metadata, options = {}) {
611
1337
  try {
612
1338
  if (!metadata.ip) {
613
1339
  throw new Error("IP address is required in request metadata");
@@ -615,7 +1341,15 @@ var WebDecoy = class {
615
1341
  if (!metadata.timestamp) {
616
1342
  metadata.timestamp = Date.now();
617
1343
  }
618
- const ruleResult = this._hasFilterRules ? await this.evaluateRulesAsync(metadata) : this.evaluateRules(metadata);
1344
+ let ruleResult;
1345
+ let agentVerdict;
1346
+ if (this.ruleEngine && (this._hasFilterRules || this._hasAgentRules)) {
1347
+ const context = await this.buildAsyncContext(metadata);
1348
+ agentVerdict = context.agent;
1349
+ ruleResult = this.runRules(context);
1350
+ } else {
1351
+ ruleResult = this.evaluateRules(metadata);
1352
+ }
619
1353
  if (ruleResult && ruleResult.action === "DENY") {
620
1354
  return {
621
1355
  allowed: false,
@@ -627,7 +1361,8 @@ var WebDecoy = class {
627
1361
  detection_id: "rule_" + Date.now(),
628
1362
  rule_enforced: true
629
1363
  },
630
- ruleResult
1364
+ ruleResult,
1365
+ agent: agentVerdict
631
1366
  };
632
1367
  }
633
1368
  if (ruleResult && ruleResult.action === "THROTTLE") {
@@ -641,7 +1376,8 @@ var WebDecoy = class {
641
1376
  detection_id: "rule_" + Date.now(),
642
1377
  rule_enforced: true
643
1378
  },
644
- ruleResult
1379
+ ruleResult,
1380
+ agent: agentVerdict
645
1381
  };
646
1382
  }
647
1383
  if (!this.client) {
@@ -655,7 +1391,8 @@ var WebDecoy = class {
655
1391
  detection_id: "local_" + Date.now(),
656
1392
  rule_enforced: false
657
1393
  },
658
- ruleResult: ruleResult ?? void 0
1394
+ ruleResult: ruleResult ?? void 0,
1395
+ agent: agentVerdict
659
1396
  };
660
1397
  }
661
1398
  const localAnalysis = options.skipLocalAnalysis ? {
@@ -685,7 +1422,8 @@ var WebDecoy = class {
685
1422
  detection_id: "local_" + Date.now(),
686
1423
  rule_enforced: false
687
1424
  },
688
- ruleResult: ruleResult ?? void 0
1425
+ ruleResult: ruleResult ?? void 0,
1426
+ agent: agentVerdict
689
1427
  };
690
1428
  }
691
1429
  const detection = await this.client.detect(detectionRequest);
@@ -701,7 +1439,8 @@ var WebDecoy = class {
701
1439
  return {
702
1440
  allowed,
703
1441
  detection,
704
- ruleResult: ruleResult ?? void 0
1442
+ ruleResult: ruleResult ?? void 0,
1443
+ agent: agentVerdict
705
1444
  };
706
1445
  } catch (error) {
707
1446
  if (this.config.debug) {
@@ -769,6 +1508,24 @@ var WebDecoy = class {
769
1508
  }
770
1509
  }
771
1510
  };
1511
+ function agentInputFromMetadata(metadata) {
1512
+ const headers = metadata.headers || {};
1513
+ const host = headers["host"] || headers[":authority"] || headers["x-forwarded-host"] || headers["Host"];
1514
+ if (!host) return null;
1515
+ const proto = headers["x-forwarded-proto"] || headers["X-Forwarded-Proto"];
1516
+ const scheme = (proto ? proto.split(",")[0].trim() : "https") || "https";
1517
+ const rawPath = metadata.path || "/";
1518
+ const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
1519
+ try {
1520
+ return {
1521
+ method: metadata.method,
1522
+ url: `${scheme}://${host}${path}`,
1523
+ headers
1524
+ };
1525
+ } catch {
1526
+ return null;
1527
+ }
1528
+ }
772
1529
 
773
1530
  // src/rules/rate-limiter.ts
774
1531
  var InMemoryRateLimiter = class {
@@ -1246,6 +2003,18 @@ function resolveProperty(path, context) {
1246
2003
  if (prop === "user_agent") return context.userAgent;
1247
2004
  return void 0;
1248
2005
  }
2006
+ if (namespace === "edge") {
2007
+ const e = context.edge;
2008
+ if (!e) return void 0;
2009
+ if (prop === "present") return e.present;
2010
+ if (prop === "clearance") return e.clearance;
2011
+ if (prop === "class") return e.class;
2012
+ if (prop === "verified") return e.isVerified;
2013
+ if (prop === "crawler") return e.isCrawler;
2014
+ if (prop === "script") return e.isScript;
2015
+ if (prop === "browser") return e.isBrowser;
2016
+ return void 0;
2017
+ }
1249
2018
  if (path.length === 1) return void 0;
1250
2019
  return void 0;
1251
2020
  }
@@ -1400,11 +2169,133 @@ var TripwireRule = class {
1400
2169
  }
1401
2170
  };
1402
2171
 
2172
+ // src/rules/web-bot-auth-rule.ts
2173
+ var WebBotAuthRule = class {
2174
+ constructor(config = {}) {
2175
+ this.name = "web-bot-auth";
2176
+ this.onImpersonation = config.onImpersonation ?? "DENY";
2177
+ this.onClaimed = config.onClaimed ?? "ALLOW";
2178
+ this.allowCategories = config.allowCategories ? new Set(config.allowCategories) : void 0;
2179
+ this.dryRun = config.dryRun ?? false;
2180
+ }
2181
+ evaluate(context) {
2182
+ const verdict = context.agent;
2183
+ if (!verdict || verdict.status === "none") return this.allow();
2184
+ if (verdict.status === "impersonation") {
2185
+ return this.act(this.onImpersonation, "agent_impersonation", {
2186
+ agentName: verdict.agentName,
2187
+ category: verdict.category,
2188
+ keyId: verdict.keyId,
2189
+ detail: verdict.reason
2190
+ });
2191
+ }
2192
+ if (verdict.status === "claimed") {
2193
+ return this.act(this.onClaimed, "agent_unverifiable", {
2194
+ keyId: verdict.keyId,
2195
+ detail: verdict.reason
2196
+ });
2197
+ }
2198
+ if (this.allowCategories && verdict.category && !this.allowCategories.has(verdict.category)) {
2199
+ return this.act(this.onClaimed, "agent_category_not_allowed", {
2200
+ agentName: verdict.agentName,
2201
+ category: verdict.category,
2202
+ keyId: verdict.keyId
2203
+ });
2204
+ }
2205
+ return this.allow();
2206
+ }
2207
+ act(action, verdict, detail) {
2208
+ if (action === "ALLOW") return this.allow();
2209
+ return {
2210
+ action: this.dryRun ? "ALLOW" : action,
2211
+ rule: this.name,
2212
+ reason: reasonFor(verdict),
2213
+ metadata: { verdict, dryRun: this.dryRun, ...detail }
2214
+ };
2215
+ }
2216
+ allow() {
2217
+ return { action: "ALLOW", rule: this.name };
2218
+ }
2219
+ };
2220
+ function reasonFor(verdict) {
2221
+ switch (verdict) {
2222
+ case "agent_impersonation":
2223
+ return "Web Bot Auth signature failed verification (agent impersonation)";
2224
+ case "agent_unverifiable":
2225
+ return "Web Bot Auth signature could not be verified";
2226
+ case "agent_category_not_allowed":
2227
+ return "Verified agent category is not allowed";
2228
+ default:
2229
+ return "Web Bot Auth rule triggered";
2230
+ }
2231
+ }
2232
+ function webBotAuth(config = {}) {
2233
+ return new WebBotAuthRule(config);
2234
+ }
2235
+
2236
+ // src/webcrypto.ts
2237
+ var encoder3 = new TextEncoder();
2238
+ function toHex(bytes) {
2239
+ let hex = "";
2240
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
2241
+ return hex;
2242
+ }
2243
+ async function sha256Hex(data) {
2244
+ const digest2 = await crypto.subtle.digest("SHA-256", encoder3.encode(data));
2245
+ return toHex(new Uint8Array(digest2));
2246
+ }
2247
+ async function hmacSha256Hex(secret, data) {
2248
+ const key = await crypto.subtle.importKey(
2249
+ "raw",
2250
+ encoder3.encode(secret),
2251
+ { name: "HMAC", hash: "SHA-256" },
2252
+ false,
2253
+ ["sign"]
2254
+ );
2255
+ const sig = await crypto.subtle.sign("HMAC", key, encoder3.encode(data));
2256
+ return toHex(new Uint8Array(sig));
2257
+ }
2258
+ function randomHex(bytes) {
2259
+ const buf = new Uint8Array(bytes);
2260
+ crypto.getRandomValues(buf);
2261
+ return toHex(buf);
2262
+ }
2263
+ function timingSafeEqualStr(a, b) {
2264
+ if (a.length !== b.length) return false;
2265
+ let diff = 0;
2266
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
2267
+ return diff === 0;
2268
+ }
2269
+ function base64urlEncode(data) {
2270
+ const bytes = encoder3.encode(data);
2271
+ let binary = "";
2272
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
2273
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2274
+ }
2275
+ function base64urlDecode(data) {
2276
+ const b64 = data.replace(/-/g, "+").replace(/_/g, "/");
2277
+ const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
2278
+ const binary = atob(padded);
2279
+ const bytes = new Uint8Array(binary.length);
2280
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
2281
+ return new TextDecoder().decode(bytes);
2282
+ }
2283
+ function fnv1a64Hex(data) {
2284
+ const PRIME = 0x100000001b3n;
2285
+ const MASK = 0xffffffffffffffffn;
2286
+ let hash = 0xcbf29ce484222325n;
2287
+ const bytes = encoder3.encode(data);
2288
+ for (let i = 0; i < bytes.length; i++) {
2289
+ hash ^= BigInt(bytes[i]);
2290
+ hash = hash * PRIME & MASK;
2291
+ }
2292
+ return hash.toString(16).padStart(16, "0");
2293
+ }
2294
+
1403
2295
  // src/rules/honeytoken.ts
1404
- var import_crypto = require("crypto");
1405
2296
  function honeytoken(options = {}) {
1406
2297
  const base = (options.basePath ?? "/__wd").replace(/\/+$/, "");
1407
- const token = options.token ?? (0, import_crypto.randomBytes)(6).toString("hex");
2298
+ const token = options.token ?? randomHex(6);
1408
2299
  const path = `${base}/${token}`;
1409
2300
  const text = options.text ?? ".";
1410
2301
  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 +2342,10 @@ var AUTOMATION_UA_PATTERNS = [
1451
2342
  ];
1452
2343
 
1453
2344
  // src/detection/ip.ts
1454
- var import_net = require("net");
2345
+ 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}$/;
2346
+ function isIPv4(ip) {
2347
+ return IPV4_RE.test(ip);
2348
+ }
1455
2349
  var DATACENTER_CIDRS = [
1456
2350
  // AWS
1457
2351
  "3.0.0.0/8",
@@ -1519,7 +2413,7 @@ function cidrContains(cidr, ip) {
1519
2413
  return (ipLong & mask) === rangeStart;
1520
2414
  }
1521
2415
  function isDatacenterIP2(ip) {
1522
- if (!(0, import_net.isIPv4)(ip)) return false;
2416
+ if (!isIPv4(ip)) return false;
1523
2417
  return DATACENTER_CIDRS.some((cidr) => cidrContains(cidr, ip));
1524
2418
  }
1525
2419
 
@@ -2135,7 +3029,6 @@ function detectTouchKinematics(signals) {
2135
3029
  }
2136
3030
 
2137
3031
  // src/detection/detectors/fingerprint.ts
2138
- var import_crypto2 = require("crypto");
2139
3032
  function detectFingerprint(signals, ip, siteKey, store) {
2140
3033
  const detections = [];
2141
3034
  const env = signals.environmental ?? {};
@@ -2146,7 +3039,7 @@ function detectFingerprint(signals, ip, siteKey, store) {
2146
3039
  String(automation.platform ?? ""),
2147
3040
  String(automation.hardwareConcurrency ?? "")
2148
3041
  ];
2149
- const fp = (0, import_crypto2.createHash)("sha256").update(components.join("|")).digest("hex").slice(0, 16);
3042
+ const fp = fnv1a64Hex(components.join("|"));
2150
3043
  store.record(fp, ip, siteKey);
2151
3044
  if (store.getIpFpCount(ip) > 5) {
2152
3045
  detections.push({
@@ -3028,9 +3921,6 @@ var DetectionEngine = class {
3028
3921
  }
3029
3922
  };
3030
3923
 
3031
- // src/captcha/service.ts
3032
- var import_crypto5 = require("crypto");
3033
-
3034
3924
  // src/captcha/secret.ts
3035
3925
  var INSECURE_DEFAULT_SECRET = "dev-secret-change-in-production";
3036
3926
  function resolveSecret(secret) {
@@ -3052,7 +3942,6 @@ function resolveSecret(secret) {
3052
3942
  }
3053
3943
 
3054
3944
  // src/captcha/pow.ts
3055
- var import_crypto3 = require("crypto");
3056
3945
  var EXPIRATION_MS = 5 * 60 * 1e3;
3057
3946
  var InMemoryChallengeStore = class {
3058
3947
  constructor() {
@@ -3098,10 +3987,10 @@ var PoWManager = class {
3098
3987
  return difficulty;
3099
3988
  }
3100
3989
  /** Generate and store a signed challenge. */
3101
- generate(siteKey, ip, difficulty) {
3990
+ async generate(siteKey, ip, difficulty) {
3102
3991
  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");
3992
+ const challengeId = randomHex(16);
3993
+ const nonce = randomHex(16);
3105
3994
  const timestamp = Date.now();
3106
3995
  const expiresAt = timestamp + EXPIRATION_MS;
3107
3996
  const challengeData = {
@@ -3116,12 +4005,12 @@ var PoWManager = class {
3116
4005
  };
3117
4006
  const { sig: _omit, ...toSign } = challengeData;
3118
4007
  void _omit;
3119
- challengeData.sig = (0, import_crypto3.createHmac)("sha256", this.secret).update(JSON.stringify(toSign)).digest("hex");
4008
+ challengeData.sig = await hmacSha256Hex(this.secret, JSON.stringify(toSign));
3120
4009
  this.store.put({ ...challengeData, ip, createdAt: timestamp });
3121
4010
  return challengeData;
3122
4011
  }
3123
4012
  /** Verify a submitted solution. `signalsHash` binds it to the signals. */
3124
- verify(solution, siteKey, signalsHash = null) {
4013
+ async verify(solution, siteKey, signalsHash = null) {
3125
4014
  const challenge = this.store.get(solution.challengeId);
3126
4015
  if (!challenge) return { valid: false, reason: "challenge_not_found" };
3127
4016
  if (Date.now() > challenge.expiresAt) {
@@ -3133,7 +4022,7 @@ var PoWManager = class {
3133
4022
  }
3134
4023
  const solutionKey = `${solution.challengeId}:${solution.nonce}`;
3135
4024
  const input = signalsHash ? `${challenge.prefix}:${signalsHash}:${solution.nonce}` : `${challenge.prefix}:${solution.nonce}`;
3136
- const expectedHash = (0, import_crypto3.createHash)("sha256").update(input).digest("hex");
4025
+ const expectedHash = await sha256Hex(input);
3137
4026
  if (solution.hash !== expectedHash) {
3138
4027
  return { valid: false, reason: "invalid_hash" };
3139
4028
  }
@@ -3155,7 +4044,6 @@ var PoWManager = class {
3155
4044
  };
3156
4045
 
3157
4046
  // src/captcha/token.ts
3158
- var import_crypto4 = require("crypto");
3159
4047
  var TOKEN_TTL_SECONDS = 300;
3160
4048
  var InMemoryTokenStore = class {
3161
4049
  constructor() {
@@ -3177,22 +4065,22 @@ var TokenManager = class {
3177
4065
  this.store = options.store ?? new InMemoryTokenStore();
3178
4066
  }
3179
4067
  /** Issue a signed, IP-bound token for a passing request. */
3180
- issue(ip, siteKey, score) {
4068
+ async issue(ip, siteKey, score) {
3181
4069
  const data = {
3182
4070
  site_key: siteKey,
3183
4071
  timestamp: Math.floor(Date.now() / 1e3),
3184
4072
  score: Math.round(score * 1e3) / 1e3,
3185
- ip_hash: (0, import_crypto4.createHash)("sha256").update(ip).digest("hex").slice(0, 8)
4073
+ ip_hash: (await sha256Hex(ip)).slice(0, 8)
3186
4074
  };
3187
4075
  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");
4076
+ data.sig = await hmacSha256Hex(this.secret, payload);
4077
+ return base64urlEncode(JSON.stringify(data));
3190
4078
  }
3191
4079
  /** Verify a token: signature, expiry, replay, and optional IP binding. */
3192
- verify(token, ip = null) {
4080
+ async verify(token, ip = null) {
3193
4081
  let decoded;
3194
4082
  try {
3195
- decoded = JSON.parse(Buffer.from(token, "base64url").toString());
4083
+ decoded = JSON.parse(base64urlDecode(token));
3196
4084
  } catch (e) {
3197
4085
  return { valid: false, reason: e instanceof Error ? e.message : "invalid_token" };
3198
4086
  }
@@ -3203,17 +4091,15 @@ var TokenManager = class {
3203
4091
  if (!sig) return { valid: false, reason: "invalid_signature" };
3204
4092
  delete decoded.sig;
3205
4093
  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)) {
4094
+ const expectedSig = await hmacSha256Hex(this.secret, payload);
4095
+ if (!timingSafeEqualStr(sig, expectedSig)) {
3210
4096
  return { valid: false, reason: "invalid_signature" };
3211
4097
  }
3212
4098
  if (this.store.isUsed(sig)) {
3213
4099
  return { valid: false, reason: "token_already_used" };
3214
4100
  }
3215
4101
  if (ip) {
3216
- const expectedIpHash = (0, import_crypto4.createHash)("sha256").update(ip).digest("hex").slice(0, 8);
4102
+ const expectedIpHash = (await sha256Hex(ip)).slice(0, 8);
3217
4103
  if (decoded.ip_hash !== expectedIpHash) {
3218
4104
  return { valid: false, reason: "ip_mismatch" };
3219
4105
  }
@@ -3246,21 +4132,21 @@ var Captcha = class {
3246
4132
  this.trustedJA4Headers = options.trustedJA4Headers ?? [];
3247
4133
  }
3248
4134
  /** Issue a PoW challenge for the client to solve (difficulty auto-scaled). */
3249
- issueChallenge(siteKey, ip, difficulty) {
4135
+ async issueChallenge(siteKey, ip, difficulty) {
3250
4136
  return this.pow.generate(siteKey, ip, difficulty);
3251
4137
  }
3252
4138
  /**
3253
4139
  * Verify a submission: checks the signals commitment, verifies PoW, scores the
3254
4140
  * signals, and issues a session token on success. Mirrors `runVerification`.
3255
4141
  */
3256
- verify(input) {
4142
+ async verify(input) {
3257
4143
  const { siteKey, ip, userAgent } = input;
3258
4144
  const headers = input.headers ?? {};
3259
4145
  let signals = input.signals ?? {};
3260
4146
  const extraDetections = [];
3261
4147
  const clientSignalsHash = input.powSolution?.signalsHash ?? null;
3262
4148
  if (input.signalsJson && clientSignalsHash) {
3263
- const computed = (0, import_crypto5.createHash)("sha256").update(input.signalsJson).digest("hex");
4149
+ const computed = await sha256Hex(input.signalsJson);
3264
4150
  if (computed !== clientSignalsHash) {
3265
4151
  extraDetections.push({
3266
4152
  category: "bot",
@@ -3279,7 +4165,7 @@ var Captcha = class {
3279
4165
  }
3280
4166
  let pow;
3281
4167
  if (input.powSolution && input.powSolution.challengeId) {
3282
- const result = this.pow.verify(input.powSolution, siteKey, clientSignalsHash);
4168
+ const result = await this.pow.verify(input.powSolution, siteKey, clientSignalsHash);
3283
4169
  pow = {
3284
4170
  provided: true,
3285
4171
  valid: result.valid,
@@ -3300,12 +4186,12 @@ var Captcha = class {
3300
4186
  pow,
3301
4187
  extraDetections
3302
4188
  });
3303
- const token = verdict.success ? this.tokens.issue(ip, siteKey, verdict.score) : null;
4189
+ const token = verdict.success ? await this.tokens.issue(ip, siteKey, verdict.score) : null;
3304
4190
  return { ...verdict, token };
3305
4191
  }
3306
4192
  /** Invisible-mode scoring — same pipeline, returns a compact result + action. */
3307
- score(input) {
3308
- const result = this.verify(input);
4193
+ async score(input) {
4194
+ const result = await this.verify(input);
3309
4195
  return {
3310
4196
  success: result.success,
3311
4197
  score: result.score,
@@ -3315,7 +4201,7 @@ var Captcha = class {
3315
4201
  };
3316
4202
  }
3317
4203
  /** Verify a previously issued token (single-use, optionally IP-bound). */
3318
- verifyToken(token, ip = null) {
4204
+ async verifyToken(token, ip = null) {
3319
4205
  return this.tokens.verify(token, ip);
3320
4206
  }
3321
4207
  };
@@ -3342,11 +4228,11 @@ function createCaptchaEndpoints(options = {}) {
3342
4228
  const ja3Hash = req.headers["x-ja3-hash"] ?? null;
3343
4229
  if (sub === "/challenge" && method === "GET") {
3344
4230
  const siteKey = req.query.siteKey ?? "default";
3345
- return json(200, captcha.issueChallenge(siteKey, req.ip));
4231
+ return json(200, await captcha.issueChallenge(siteKey, req.ip));
3346
4232
  }
3347
4233
  if (sub === "/verify" && method === "POST") {
3348
4234
  const b = req.body ?? {};
3349
- const result = captcha.verify({
4235
+ const result = await captcha.verify({
3350
4236
  siteKey: b.siteKey ?? "default",
3351
4237
  ip: req.ip,
3352
4238
  userAgent,
@@ -3361,7 +4247,7 @@ function createCaptchaEndpoints(options = {}) {
3361
4247
  }
3362
4248
  if (sub === "/score" && method === "POST") {
3363
4249
  const b = req.body ?? {};
3364
- const result = captcha.score({
4250
+ const result = await captcha.score({
3365
4251
  siteKey: b.siteKey ?? "default",
3366
4252
  ip: req.ip,
3367
4253
  userAgent,
@@ -3378,7 +4264,7 @@ function createCaptchaEndpoints(options = {}) {
3378
4264
  if (sub === "/token/verify" && method === "POST") {
3379
4265
  const b = req.body ?? {};
3380
4266
  if (!b.token) return json(400, { valid: false, reason: "missing_token" });
3381
- return json(200, captcha.verifyToken(b.token, req.ip));
4267
+ return json(200, await captcha.verifyToken(b.token, req.ip));
3382
4268
  }
3383
4269
  return json(404, { error: "not_found" });
3384
4270
  }
@@ -3386,10 +4272,15 @@ function createCaptchaEndpoints(options = {}) {
3386
4272
  }
3387
4273
  // Annotate the CommonJS export names for ESM import in node:
3388
4274
  0 && (module.exports = {
4275
+ AgentVerifier,
3389
4276
  Captcha,
4277
+ DEFAULT_SIGNED_AGENT_DIRECTORIES,
3390
4278
  DEFAULT_TRIPWIRE_PATHS,
3391
4279
  DEFAULT_WEIGHTS,
3392
4280
  DetectionEngine,
4281
+ DirectoryCache,
4282
+ EDGE_CLASS_HEADER,
4283
+ EDGE_CLEARANCE_HEADER,
3393
4284
  FilterRule,
3394
4285
  InMemoryChallengeStore,
3395
4286
  InMemoryFingerprintStore,
@@ -3400,9 +4291,11 @@ function createCaptchaEndpoints(options = {}) {
3400
4291
  RuleEngine,
3401
4292
  TokenManager,
3402
4293
  TripwireRule,
4294
+ WebBotAuthRule,
3403
4295
  WebDecoy,
3404
4296
  calculateCategoryScores,
3405
4297
  calculateFinalScore,
4298
+ createAgentVerifier,
3406
4299
  createCaptchaEndpoints,
3407
4300
  filter,
3408
4301
  honeytoken,
@@ -3410,7 +4303,9 @@ function createCaptchaEndpoints(options = {}) {
3410
4303
  isMobileUA,
3411
4304
  parseUserAgent,
3412
4305
  rateLimit,
4306
+ readEdgeVerdict,
3413
4307
  recommend,
3414
4308
  resolveSecret,
3415
- tripwire
4309
+ tripwire,
4310
+ webBotAuth
3416
4311
  });