@webdecoy/node 0.5.0 → 0.7.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
@@ -27,6 +27,8 @@ __export(index_exports, {
27
27
  DEFAULT_WEIGHTS: () => DEFAULT_WEIGHTS,
28
28
  DetectionEngine: () => DetectionEngine,
29
29
  DirectoryCache: () => DirectoryCache,
30
+ EDGE_CLASS_HEADER: () => EDGE_CLASS_HEADER,
31
+ EDGE_CLEARANCE_HEADER: () => EDGE_CLEARANCE_HEADER,
30
32
  FilterRule: () => FilterRule,
31
33
  InMemoryChallengeStore: () => InMemoryChallengeStore,
32
34
  InMemoryFingerprintStore: () => InMemoryFingerprintStore,
@@ -49,6 +51,7 @@ __export(index_exports, {
49
51
  isMobileUA: () => isMobileUA,
50
52
  parseUserAgent: () => parseUserAgent,
51
53
  rateLimit: () => rateLimit,
54
+ readEdgeVerdict: () => readEdgeVerdict,
52
55
  recommend: () => recommend,
53
56
  resolveSecret: () => resolveSecret,
54
57
  tripwire: () => tripwire,
@@ -400,1850 +403,1913 @@ var RuleEngine = class {
400
403
  }
401
404
  };
402
405
 
403
- // src/violation-reporter.ts
404
- var ViolationReporter = class {
405
- constructor(client, config = {}) {
406
- this.buffer = [];
407
- this.flushing = false;
408
- this.client = client;
409
- this.maxBufferSize = config.maxBufferSize ?? 50;
410
- this.debug = config.debug ?? false;
411
- const flushInterval = config.flushInterval ?? 5e3;
412
- this.flushTimer = setInterval(() => this.flush(), flushInterval);
413
- if (this.flushTimer.unref) {
414
- this.flushTimer.unref();
406
+ // src/rules/rate-limiter.ts
407
+ var InMemoryRateLimiter = class {
408
+ constructor() {
409
+ this.fixedWindows = /* @__PURE__ */ new Map();
410
+ this.slidingWindows = /* @__PURE__ */ new Map();
411
+ this.cleanupTimer = setInterval(() => this.cleanup(), 6e4);
412
+ if (this.cleanupTimer.unref) {
413
+ this.cleanupTimer.unref();
415
414
  }
416
415
  }
417
416
  /**
418
- * Add violations to the buffer. Auto-flushes when buffer reaches maxBufferSize.
417
+ * Check and increment for fixed window algorithm
418
+ * Returns the current count after increment, and the window reset time
419
419
  */
420
- report(violations) {
421
- this.buffer.push(...violations);
422
- if (this.buffer.length >= this.maxBufferSize) {
423
- this.flush().catch(() => {
424
- });
420
+ checkFixedWindow(key, max, windowMs) {
421
+ const now = Date.now();
422
+ const entry = this.fixedWindows.get(key);
423
+ if (!entry || now - entry.windowStart >= windowMs) {
424
+ this.fixedWindows.set(key, { count: 1, windowStart: now });
425
+ return { allowed: true, current: 1, resetAt: now + windowMs };
425
426
  }
426
- }
427
- /**
428
- * Flush buffered violations to the backend
429
- */
430
- async flush() {
431
- if (this.flushing || this.buffer.length === 0) return;
432
- this.flushing = true;
433
- const events = this.buffer.splice(0, this.buffer.length);
434
- try {
435
- for (let i = 0; i < events.length; i += 100) {
436
- const batch = events.slice(i, i + 100);
437
- await this.client.sendViolations(batch);
438
- if (this.debug) {
439
- console.log(`[WebDecoy] Flushed ${batch.length} violation events`);
440
- }
441
- }
442
- } catch (error) {
443
- if (this.debug) {
444
- console.error("[WebDecoy] Failed to flush violations:", error);
445
- }
446
- } finally {
447
- this.flushing = false;
427
+ entry.count++;
428
+ const resetAt = entry.windowStart + windowMs;
429
+ if (entry.count > max) {
430
+ return { allowed: false, current: entry.count, resetAt };
448
431
  }
432
+ return { allowed: true, current: entry.count, resetAt };
449
433
  }
450
434
  /**
451
- * Flush remaining events and stop the timer
452
- */
453
- async destroy() {
454
- clearInterval(this.flushTimer);
455
- await this.flush();
456
- }
457
- };
458
-
459
- // src/ip-enrichment.ts
460
- var IPEnrichmentClient = class {
461
- constructor(client, ttlMs = 36e5) {
462
- this.cache = /* @__PURE__ */ new Map();
463
- this.pending = /* @__PURE__ */ new Map();
464
- this.client = client;
465
- this.ttlMs = ttlMs;
466
- }
467
- /**
468
- * Get enrichment data for an IP address.
469
- * Returns cached data if available (1h TTL), otherwise fetches from API.
470
- * Returns null if enrichment fails (fail-open).
435
+ * Check and increment for sliding window algorithm
436
+ * Returns the current count after adding the new timestamp
471
437
  */
472
- async enrich(ip) {
473
- const cached = this.cache.get(ip);
474
- if (cached && cached.expiresAt > Date.now()) {
475
- return cached.data;
438
+ checkSlidingWindow(key, max, windowMs) {
439
+ const now = Date.now();
440
+ const cutoff = now - windowMs;
441
+ let timestamps = this.slidingWindows.get(key);
442
+ if (!timestamps) {
443
+ timestamps = [];
444
+ this.slidingWindows.set(key, timestamps);
476
445
  }
477
- const inflight = this.pending.get(ip);
478
- if (inflight) {
479
- return inflight;
446
+ while (timestamps.length > 0 && timestamps[0] <= cutoff) {
447
+ timestamps.shift();
480
448
  }
481
- const promise = this.fetchAndCache(ip);
482
- this.pending.set(ip, promise);
483
- try {
484
- return await promise;
485
- } finally {
486
- this.pending.delete(ip);
449
+ timestamps.push(now);
450
+ const resetAt = timestamps.length > 0 ? timestamps[0] + windowMs : now + windowMs;
451
+ if (timestamps.length > max) {
452
+ return { allowed: false, current: timestamps.length, resetAt };
487
453
  }
454
+ return { allowed: true, current: timestamps.length, resetAt };
488
455
  }
489
- async fetchAndCache(ip) {
490
- const data = await this.client.getIPEnrichment(ip);
491
- if (data) {
492
- this.cache.set(ip, {
493
- data,
494
- expiresAt: Date.now() + this.ttlMs
495
- });
456
+ /**
457
+ * Clean up expired entries from both maps
458
+ */
459
+ cleanup() {
460
+ const now = Date.now();
461
+ for (const [key, entry] of this.fixedWindows) {
462
+ if (now - entry.windowStart > 3e5) {
463
+ this.fixedWindows.delete(key);
464
+ }
465
+ }
466
+ for (const [key, timestamps] of this.slidingWindows) {
467
+ if (timestamps.length === 0) {
468
+ this.slidingWindows.delete(key);
469
+ continue;
470
+ }
471
+ const latest = timestamps[timestamps.length - 1];
472
+ if (now - latest > 3e5) {
473
+ this.slidingWindows.delete(key);
474
+ }
496
475
  }
497
- return data;
498
476
  }
499
477
  /**
500
- * Clear the cache
478
+ * Release resources
501
479
  */
502
- clearCache() {
503
- this.cache.clear();
480
+ destroy() {
481
+ clearInterval(this.cleanupTimer);
482
+ this.fixedWindows.clear();
483
+ this.slidingWindows.clear();
504
484
  }
505
485
  };
506
486
 
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);
487
+ // src/rules/rate-limit-rule.ts
488
+ var RateLimitRule = class {
489
+ constructor(config) {
490
+ this.name = `rate-limit:${config.max}/${config.window}s`;
491
+ this.limiter = new InMemoryRateLimiter();
492
+ this.config = {
493
+ max: config.max,
494
+ window: config.window,
495
+ algorithm: config.algorithm ?? "fixed",
496
+ keyBy: config.keyBy,
497
+ action: config.action ?? "THROTTLE",
498
+ dryRun: config.dryRun ?? false
554
499
  };
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
500
  }
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;
501
+ evaluate(context) {
502
+ const key = this.config.keyBy ? this.config.keyBy(context) : context.ip;
503
+ const windowMs = this.config.window * 1e3;
504
+ const result = this.config.algorithm === "sliding" ? this.limiter.checkSlidingWindow(key, this.config.max, windowMs) : this.limiter.checkFixedWindow(key, this.config.max, windowMs);
505
+ if (!result.allowed) {
506
+ const retryAfter = Math.ceil((result.resetAt - Date.now()) / 1e3);
507
+ return {
508
+ action: this.config.dryRun ? "ALLOW" : this.config.action,
509
+ rule: this.name,
510
+ reason: `Rate limit exceeded: ${result.current}/${this.config.max} requests in ${this.config.window}s window`,
511
+ metadata: {
512
+ current: result.current,
513
+ max: this.config.max,
514
+ window: this.config.window,
515
+ retryAfter: Math.max(retryAfter, 1),
516
+ dryRun: this.config.dryRun
517
+ }
518
+ };
571
519
  }
572
- if (now < this.nextColdRetryAt) return;
573
- await this.refresh();
520
+ return {
521
+ action: "ALLOW",
522
+ rule: this.name,
523
+ metadata: {
524
+ current: result.current,
525
+ max: this.config.max,
526
+ remaining: this.config.max - result.current
527
+ }
528
+ };
574
529
  }
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;
530
+ destroy() {
531
+ this.limiter.destroy();
582
532
  }
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
- }
533
+ };
534
+
535
+ // src/rules/filter/tokenizer.ts
536
+ var KEYWORDS = {
537
+ and: "AND" /* AND */,
538
+ or: "OR" /* OR */,
539
+ not: "NOT" /* NOT */,
540
+ in: "IN" /* IN */,
541
+ matches: "MATCHES" /* MATCHES */,
542
+ true: "BOOL" /* BOOL */,
543
+ false: "BOOL" /* BOOL */
544
+ };
545
+ var Tokenizer = class {
546
+ constructor(source) {
547
+ this.pos = 0;
548
+ this.tokens = [];
549
+ this.source = source;
603
550
  }
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;
551
+ tokenize() {
552
+ while (this.pos < this.source.length) {
553
+ this.skipWhitespace();
554
+ if (this.pos >= this.source.length) break;
555
+ const ch = this.source[this.pos];
556
+ if (ch === ".") {
557
+ this.tokens.push({ type: "DOT" /* DOT */, value: ".", position: this.pos });
558
+ this.pos++;
559
+ continue;
619
560
  }
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;
561
+ if (ch === "(") {
562
+ this.tokens.push({ type: "LPAREN" /* LPAREN */, value: "(", position: this.pos });
563
+ this.pos++;
564
+ continue;
624
565
  }
625
- const out = [];
626
- for (const jwk of body.keys) {
627
- const resolved = await importKey(jwk, src);
628
- if (resolved) out.push(resolved);
566
+ if (ch === ")") {
567
+ this.tokens.push({ type: "RPAREN" /* RPAREN */, value: ")", position: this.pos });
568
+ this.pos++;
569
+ continue;
629
570
  }
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);
571
+ if (ch === "[") {
572
+ this.tokens.push({ type: "LBRACKET" /* LBRACKET */, value: "[", position: this.pos });
573
+ this.pos++;
574
+ continue;
575
+ }
576
+ if (ch === "]") {
577
+ this.tokens.push({ type: "RBRACKET" /* RBRACKET */, value: "]", position: this.pos });
578
+ this.pos++;
579
+ continue;
580
+ }
581
+ if (ch === ",") {
582
+ this.tokens.push({ type: "COMMA" /* COMMA */, value: ",", position: this.pos });
583
+ this.pos++;
584
+ continue;
585
+ }
586
+ if (ch === "=" && this.peek(1) === "=") {
587
+ this.tokens.push({ type: "EQ" /* EQ */, value: "==", position: this.pos });
588
+ this.pos += 2;
589
+ continue;
590
+ }
591
+ if (ch === "!" && this.peek(1) === "=") {
592
+ this.tokens.push({ type: "NEQ" /* NEQ */, value: "!=", position: this.pos });
593
+ this.pos += 2;
594
+ continue;
595
+ }
596
+ if (ch === ">" && this.peek(1) === "=") {
597
+ this.tokens.push({ type: "GTE" /* GTE */, value: ">=", position: this.pos });
598
+ this.pos += 2;
599
+ continue;
600
+ }
601
+ if (ch === "<" && this.peek(1) === "=") {
602
+ this.tokens.push({ type: "LTE" /* LTE */, value: "<=", position: this.pos });
603
+ this.pos += 2;
604
+ continue;
605
+ }
606
+ if (ch === ">") {
607
+ this.tokens.push({ type: "GT" /* GT */, value: ">", position: this.pos });
608
+ this.pos++;
609
+ continue;
610
+ }
611
+ if (ch === "<") {
612
+ this.tokens.push({ type: "LT" /* LT */, value: "<", position: this.pos });
613
+ this.pos++;
614
+ continue;
615
+ }
616
+ if (ch === '"' || ch === "'") {
617
+ this.readString(ch);
618
+ continue;
619
+ }
620
+ if (this.isDigit(ch) || ch === "-" && this.isDigit(this.peek(1))) {
621
+ this.readNumber();
622
+ continue;
623
+ }
624
+ if (this.isIdentStart(ch)) {
625
+ this.readIdent();
626
+ continue;
627
+ }
628
+ throw new Error(`Unexpected character '${ch}' at position ${this.pos}`);
637
629
  }
630
+ this.tokens.push({ type: "EOF" /* EOF */, value: "", position: this.pos });
631
+ return this.tokens;
638
632
  }
639
- debug(msg) {
640
- if (this.opts.debug) console.log(`[WebDecoy][web-bot-auth] ${msg}`);
633
+ peek(offset) {
634
+ const idx = this.pos + offset;
635
+ return idx < this.source.length ? this.source[idx] : "";
641
636
  }
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;
637
+ skipWhitespace() {
638
+ while (this.pos < this.source.length && /\s/.test(this.source[this.pos])) {
639
+ this.pos++;
678
640
  }
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)
641
+ }
642
+ readString(quote) {
643
+ const start = this.pos;
644
+ this.pos++;
645
+ let value = "";
646
+ while (this.pos < this.source.length && this.source[this.pos] !== quote) {
647
+ if (this.source[this.pos] === "\\") {
648
+ this.pos++;
690
649
  }
691
- };
692
- } catch {
693
- return null;
650
+ value += this.source[this.pos];
651
+ this.pos++;
652
+ }
653
+ if (this.pos >= this.source.length) {
654
+ throw new Error(`Unterminated string at position ${start}`);
655
+ }
656
+ this.pos++;
657
+ this.tokens.push({ type: "STRING" /* STRING */, value, position: start });
694
658
  }
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;
659
+ readNumber() {
660
+ const start = this.pos;
661
+ if (this.source[this.pos] === "-") this.pos++;
662
+ while (this.pos < this.source.length && this.isDigit(this.source[this.pos])) {
663
+ this.pos++;
664
+ }
665
+ if (this.pos < this.source.length && this.source[this.pos] === ".") {
666
+ this.pos++;
667
+ while (this.pos < this.source.length && this.isDigit(this.source[this.pos])) {
668
+ this.pos++;
669
+ }
670
+ }
671
+ this.tokens.push({ type: "NUMBER" /* NUMBER */, value: this.source.slice(start, this.pos), position: start });
706
672
  }
707
- eof() {
708
- return this.i >= this.s.length;
673
+ readIdent() {
674
+ const start = this.pos;
675
+ while (this.pos < this.source.length && this.isIdentPart(this.source[this.pos])) {
676
+ this.pos++;
677
+ }
678
+ const value = this.source.slice(start, this.pos);
679
+ const keyword = KEYWORDS[value.toLowerCase()];
680
+ if (keyword) {
681
+ this.tokens.push({ type: keyword, value: value.toLowerCase(), position: start });
682
+ } else {
683
+ this.tokens.push({ type: "IDENT" /* IDENT */, value, position: start });
684
+ }
709
685
  }
710
- peek() {
711
- return this.s[this.i];
686
+ isDigit(ch) {
687
+ return ch >= "0" && ch <= "9";
712
688
  }
713
- skipSP() {
714
- while (!this.eof() && (this.peek() === " " || this.peek() === " ")) this.i++;
689
+ isIdentStart(ch) {
690
+ return /[a-zA-Z_]/.test(ch);
691
+ }
692
+ isIdentPart(ch) {
693
+ return /[a-zA-Z0-9_]/.test(ch);
715
694
  }
716
695
  };
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");
696
+
697
+ // src/rules/filter/parser.ts
698
+ var Parser = class {
699
+ constructor(source) {
700
+ this.pos = 0;
701
+ this.tokens = new Tokenizer(source).tokenize();
747
702
  }
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}`);
703
+ parse() {
704
+ const ast = this.orExpr();
705
+ this.expect("EOF" /* EOF */, "Expected end of expression");
706
+ return ast;
763
707
  }
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;
708
+ orExpr() {
709
+ let left = this.andExpr();
710
+ while (this.match("OR" /* OR */)) {
711
+ const right = this.andExpr();
712
+ left = { kind: "binary", op: "or", left, right };
781
713
  }
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");
714
+ return left;
803
715
  }
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;
716
+ andExpr() {
717
+ let left = this.unary();
718
+ while (this.match("AND" /* AND */)) {
719
+ const right = this.unary();
720
+ left = { kind: "binary", op: "and", left, right };
822
721
  }
722
+ return left;
823
723
  }
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++;
724
+ unary() {
725
+ if (this.match("NOT" /* NOT */)) {
726
+ if (this.check("IN" /* IN */)) {
727
+ this.pos--;
728
+ return this.comparison();
729
+ }
730
+ const operand = this.unary();
731
+ return { kind: "unary", op: "not", operand };
732
+ }
733
+ return this.comparison();
842
734
  }
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" };
735
+ comparison() {
736
+ let left = this.primary();
737
+ if (this.match("EQ" /* EQ */)) return { kind: "binary", op: "==", left, right: this.primary() };
738
+ if (this.match("NEQ" /* NEQ */)) return { kind: "binary", op: "!=", left, right: this.primary() };
739
+ if (this.match("GT" /* GT */)) return { kind: "binary", op: ">", left, right: this.primary() };
740
+ if (this.match("GTE" /* GTE */)) return { kind: "binary", op: ">=", left, right: this.primary() };
741
+ if (this.match("LT" /* LT */)) return { kind: "binary", op: "<", left, right: this.primary() };
742
+ if (this.match("LTE" /* LTE */)) return { kind: "binary", op: "<=", left, right: this.primary() };
743
+ if (this.match("IN" /* IN */)) return { kind: "binary", op: "in", left, right: this.primary() };
744
+ if (this.match("MATCHES" /* MATCHES */)) return { kind: "binary", op: "matches", left, right: this.primary() };
745
+ if (this.check("NOT" /* NOT */) && this.checkAhead("IN" /* IN */)) {
746
+ this.advance();
747
+ this.advance();
748
+ return { kind: "binary", op: "not in", left, right: this.primary() };
749
+ }
750
+ return left;
873
751
  }
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;
752
+ primary() {
753
+ if (this.check("BOOL" /* BOOL */)) {
754
+ const token = this.advance();
755
+ return { kind: "bool", value: token.value === "true" };
888
756
  }
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;
757
+ if (this.check("NUMBER" /* NUMBER */)) {
758
+ const token = this.advance();
759
+ return { kind: "number", value: parseFloat(token.value) };
894
760
  }
895
- if (created !== void 0 && now + toleranceSec < created) {
896
- best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "not-yet-valid" });
897
- continue;
761
+ if (this.check("STRING" /* STRING */)) {
762
+ const token = this.advance();
763
+ return { kind: "string", value: token.value };
898
764
  }
899
- if (key.exp !== void 0 && now > key.exp + toleranceSec) {
900
- best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-expired" });
901
- continue;
765
+ if (this.match("LBRACKET" /* LBRACKET */)) {
766
+ const elements = [];
767
+ if (!this.check("RBRACKET" /* RBRACKET */)) {
768
+ elements.push(this.primary());
769
+ while (this.match("COMMA" /* COMMA */)) {
770
+ elements.push(this.primary());
771
+ }
772
+ }
773
+ this.expect("RBRACKET" /* RBRACKET */, 'Expected "]"');
774
+ return { kind: "array", elements };
902
775
  }
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;
776
+ if (this.match("LPAREN" /* LPAREN */)) {
777
+ const expr = this.orExpr();
778
+ this.expect("RPAREN" /* RPAREN */, 'Expected ")"');
779
+ return expr;
924
780
  }
925
- if (ok) {
926
- return { outcome: "verified", keyId: keyid, key };
781
+ if (this.check("IDENT" /* IDENT */)) {
782
+ const path = [this.advance().value];
783
+ while (this.match("DOT" /* DOT */)) {
784
+ if (!this.check("IDENT" /* IDENT */)) {
785
+ throw new Error(`Expected identifier after "." at position ${this.current().position}`);
786
+ }
787
+ path.push(this.advance().value);
788
+ }
789
+ if (this.match("LPAREN" /* LPAREN */)) {
790
+ const method = path.pop();
791
+ const args = [];
792
+ if (!this.check("RPAREN" /* RPAREN */)) {
793
+ args.push(this.primary());
794
+ while (this.match("COMMA" /* COMMA */)) {
795
+ args.push(this.primary());
796
+ }
797
+ }
798
+ this.expect("RPAREN" /* RPAREN */, 'Expected ")"');
799
+ return { kind: "call", object: path, method, args };
800
+ }
801
+ return { kind: "property", path };
927
802
  }
928
- best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "bad-signature" });
803
+ throw new Error(`Unexpected token "${this.current().value}" at position ${this.current().position}`);
929
804
  }
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)}`);
805
+ // Helper methods
806
+ current() {
807
+ return this.tokens[this.pos];
943
808
  }
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
- }
809
+ advance() {
810
+ return this.tokens[this.pos++];
978
811
  }
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;
812
+ check(type) {
813
+ return this.current().type === type;
986
814
  }
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`);
815
+ checkAhead(type) {
816
+ return this.pos + 1 < this.tokens.length && this.tokens[this.pos + 1].type === type;
817
+ }
818
+ match(type) {
819
+ if (this.check(type)) {
820
+ this.advance();
821
+ return true;
1011
822
  }
1012
- out.set(d.key, d.items[0].bytes);
823
+ return false;
1013
824
  }
1014
- return out;
1015
- }
825
+ expect(type, message) {
826
+ if (this.check(type)) return this.advance();
827
+ throw new Error(`${message}, got "${this.current().value}" at position ${this.current().position}`);
828
+ }
829
+ };
1016
830
 
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
- });
831
+ // src/rules/filter/evaluator.ts
832
+ var MAX_REGEX_LENGTH = 500;
833
+ function evaluate(node, context) {
834
+ switch (node.kind) {
835
+ case "bool":
836
+ return node.value;
837
+ case "number":
838
+ return node.value;
839
+ case "string":
840
+ return node.value;
841
+ case "array":
842
+ return node.elements.map((el) => evaluate(el, context));
843
+ case "property":
844
+ return resolveProperty(node.path, context);
845
+ case "call":
846
+ return resolveCall(node.object, node.method, node.args, context);
847
+ case "unary":
848
+ return evaluateUnary(node.op, node.operand, context);
849
+ case "binary":
850
+ return evaluateBinary(node.op, node.left, node.right, context);
1031
851
  }
1032
- /** Pre-fetch trusted directories so the first request verifies warm. */
1033
- warmup() {
1034
- this.cache.prime();
852
+ }
853
+ function resolveProperty(path, context) {
854
+ const namespace = path[0];
855
+ const prop = path.slice(1).join(".");
856
+ if (namespace === "ip") {
857
+ const e = context.enrichment;
858
+ if (!e) return void 0;
859
+ if (prop === "vpn") return e.security.vpn;
860
+ if (prop === "proxy") return e.security.proxy;
861
+ if (prop === "tor") return e.security.tor;
862
+ if (prop === "relay") return e.security.relay;
863
+ if (prop === "hosting") return e.security.hosting;
864
+ if (prop === "country") return e.location.country;
865
+ if (prop === "country_name") return e.location.country_name;
866
+ if (prop === "city") return e.location.city;
867
+ if (prop === "timezone") return e.location.timezone;
868
+ if (prop === "asn") return e.network.asn;
869
+ if (prop === "asn_org") return e.network.asn_org;
870
+ if (prop === "abuse_score") return e.reputation.abuse_score;
871
+ if (prop === "total_reports") return e.reputation.total_reports;
872
+ if (prop === "is_high_risk") return e.reputation.is_high_risk;
873
+ return void 0;
1035
874
  }
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
- }
875
+ if (namespace === "req") {
876
+ if (prop === "path") return context.path;
877
+ if (prop === "method") return context.method;
878
+ if (prop === "ip") return context.ip;
879
+ if (prop === "user_agent") return context.userAgent;
880
+ return void 0;
1069
881
  }
1070
- /** Cached-key count (diagnostics/tests). */
1071
- get cachedKeyCount() {
1072
- return this.cache.size;
882
+ if (namespace === "edge") {
883
+ const e = context.edge;
884
+ if (!e) return void 0;
885
+ if (prop === "present") return e.present;
886
+ if (prop === "clearance") return e.clearance;
887
+ if (prop === "class") return e.class;
888
+ if (prop === "verified") return e.isVerified;
889
+ if (prop === "crawler") return e.isCrawler;
890
+ if (prop === "script") return e.isScript;
891
+ if (prop === "browser") return e.isBrowser;
892
+ return void 0;
1073
893
  }
1074
- };
1075
- function createAgentVerifier(options = {}) {
1076
- return new AgentVerifier(options);
894
+ if (path.length === 1) return void 0;
895
+ return void 0;
1077
896
  }
1078
- function normalize(input) {
1079
- if (isRequest(input)) {
1080
- return { method: input.method, url: new URL(input.url), headers: input.headers };
897
+ function resolveCall(object, method, args, context) {
898
+ const namespace = object[0];
899
+ if (namespace === "req" && method === "header") {
900
+ if (args.length !== 1) return void 0;
901
+ const headerName = evaluate(args[0], context);
902
+ if (typeof headerName !== "string") return void 0;
903
+ return context.headers[headerName.toLowerCase()];
1081
904
  }
1082
- const headers = input.headers instanceof Headers ? input.headers : toHeaders(input.headers);
1083
- return { method: input.method, url: new URL(input.url), headers };
905
+ return void 0;
1084
906
  }
1085
- function isRequest(input) {
1086
- return typeof Request !== "undefined" && input instanceof Request && typeof input.url === "string";
907
+ function evaluateUnary(op, operand, context) {
908
+ const val = evaluate(operand, context);
909
+ if (op === "not") {
910
+ if (val === void 0) return false;
911
+ return !val;
912
+ }
913
+ return void 0;
1087
914
  }
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));
915
+ function evaluateBinary(op, left, right, context) {
916
+ if (op === "and") {
917
+ const l2 = evaluate(left, context);
918
+ if (l2 === void 0 || l2 === false) return false;
919
+ const r2 = evaluate(right, context);
920
+ if (r2 === void 0) return false;
921
+ return !!r2;
922
+ }
923
+ if (op === "or") {
924
+ const l2 = evaluate(left, context);
925
+ if (l2 === void 0 ? false : !!l2) return true;
926
+ const r2 = evaluate(right, context);
927
+ if (r2 === void 0) return false;
928
+ return !!r2;
929
+ }
930
+ const l = evaluate(left, context);
931
+ const r = evaluate(right, context);
932
+ if (l === void 0 || r === void 0) return false;
933
+ switch (op) {
934
+ case "==":
935
+ return l === r;
936
+ case "!=":
937
+ return l !== r;
938
+ case ">":
939
+ return typeof l === "number" && typeof r === "number" && l > r;
940
+ case ">=":
941
+ return typeof l === "number" && typeof r === "number" && l >= r;
942
+ case "<":
943
+ return typeof l === "number" && typeof r === "number" && l < r;
944
+ case "<=":
945
+ return typeof l === "number" && typeof r === "number" && l <= r;
946
+ case "in": {
947
+ if (!Array.isArray(r)) return false;
948
+ return r.includes(l);
949
+ }
950
+ case "not in": {
951
+ if (!Array.isArray(r)) return false;
952
+ return !r.includes(l);
953
+ }
954
+ case "matches": {
955
+ if (typeof l !== "string" || typeof r !== "string") return false;
956
+ if (r.length > MAX_REGEX_LENGTH) return false;
957
+ try {
958
+ return new RegExp(r).test(l);
959
+ } catch {
960
+ return false;
961
+ }
962
+ }
963
+ default:
964
+ return false;
1092
965
  }
1093
- return h;
1094
966
  }
1095
967
 
1096
- // src/sdk.ts
1097
- var WebDecoy = class {
968
+ // src/rules/filter-rule.ts
969
+ var FilterRule = class {
1098
970
  constructor(config) {
1099
- this.violationReporter = null;
1100
- this.ipEnrichmentClient = null;
1101
- this._hasFilterRules = false;
1102
- this._hasAgentRules = false;
1103
- this.agentVerifier = null;
1104
- const hasApiKey = !!config.apiKey;
1105
- if (hasApiKey) {
1106
- if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
1107
- throw new Error(
1108
- 'Invalid API key format. API key should start with "sk_live_" or "sk_test_".'
1109
- );
1110
- }
971
+ this.expression = config.expression;
972
+ this.action = config.action ?? "DENY";
973
+ this.dryRun = config.dryRun ?? false;
974
+ this.name = `filter:${this.expression.slice(0, 50)}`;
975
+ const parser = new Parser(config.expression);
976
+ this.ast = parser.parse();
977
+ }
978
+ evaluate(context) {
979
+ const result = evaluate(this.ast, context);
980
+ if (result) {
981
+ return {
982
+ action: this.dryRun ? "ALLOW" : this.action,
983
+ rule: this.name,
984
+ reason: `Filter matched: ${this.expression}`,
985
+ metadata: {
986
+ expression: this.expression,
987
+ dryRun: this.dryRun
988
+ }
989
+ };
1111
990
  }
1112
- this.config = {
1113
- apiKey: config.apiKey,
1114
- apiUrl: config.apiUrl || "https://ingest.webdecoy.com",
1115
- enableTLSFingerprinting: config.enableTLSFingerprinting ?? true,
1116
- threatScoreThreshold: config.threatScoreThreshold ?? 80,
1117
- timeout: config.timeout ?? 5e3,
1118
- debug: config.debug ?? false,
1119
- tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
991
+ return {
992
+ action: "ALLOW",
993
+ rule: this.name
1120
994
  };
1121
- if (hasApiKey) {
1122
- this.client = new WebDecoyClient({
1123
- apiKey: config.apiKey,
1124
- apiUrl: this.config.apiUrl,
1125
- timeout: this.config.timeout,
1126
- debug: this.config.debug,
1127
- tlsRejectUnauthorized: this.config.tlsRejectUnauthorized
1128
- });
1129
- } else {
1130
- this.client = null;
1131
- if (this.config.debug) {
1132
- console.log("[WebDecoy] Running in local-only mode (no API key). Rules will still evaluate.");
1133
- }
1134
- }
1135
- this.webBotAuthOptions = config.webBotAuth;
1136
- if (config.rules && config.rules.length > 0) {
1137
- this.ruleEngine = new RuleEngine(config.rules);
1138
- this._hasFilterRules = config.rules.some(
1139
- (r) => r.name.startsWith("filter:")
1140
- );
1141
- this._hasAgentRules = config.rules.some((r) => r.name === "web-bot-auth");
1142
- if (this._hasAgentRules) {
1143
- this.getAgentVerifier().warmup();
1144
- }
1145
- } else {
1146
- this.ruleEngine = null;
995
+ }
996
+ };
997
+
998
+ // src/rules/tripwire-rule.ts
999
+ var DEFAULT_TRIPWIRE_PATHS = [
1000
+ "/.git/config",
1001
+ "/.git/HEAD",
1002
+ "/.env",
1003
+ "/.env.local",
1004
+ "/.env.production",
1005
+ "/wp-config.php",
1006
+ "/config.php",
1007
+ "/.aws/credentials",
1008
+ "/.ssh/id_rsa",
1009
+ "/backup.zip",
1010
+ "/backup.sql",
1011
+ "/database.sql",
1012
+ "/dump.sql",
1013
+ "/.DS_Store",
1014
+ "/phpinfo.php",
1015
+ "/server-status",
1016
+ "/actuator/env",
1017
+ "/.vscode/sftp.json"
1018
+ ];
1019
+ function normalizePath(path) {
1020
+ return path.split("?")[0].split("#")[0];
1021
+ }
1022
+ var TripwireRule = class {
1023
+ constructor(config = {}) {
1024
+ this.name = "tripwire";
1025
+ const paths = [...config.paths ?? []];
1026
+ if (config.includeDefaults ?? true) paths.push(...DEFAULT_TRIPWIRE_PATHS);
1027
+ this.exact = new Set(paths);
1028
+ this.prefixes = config.prefixes ?? [];
1029
+ this.patterns = config.patterns ?? [];
1030
+ this.action = config.action ?? "DENY";
1031
+ this.dryRun = config.dryRun ?? false;
1032
+ }
1033
+ evaluate(context) {
1034
+ const path = normalizePath(context.path);
1035
+ const hit = this.exact.has(path) || this.prefixes.some((prefix) => path.startsWith(prefix)) || this.patterns.some((re) => re.test(path));
1036
+ if (hit) {
1037
+ return {
1038
+ action: this.dryRun ? "ALLOW" : this.action,
1039
+ rule: this.name,
1040
+ reason: `Tripwire hit: ${path} \u2014 hidden honeypot path, deterministic automated-intent signal`,
1041
+ metadata: { path, dryRun: this.dryRun, confidence: 100 }
1042
+ };
1147
1043
  }
1148
- if (this.client && this._hasFilterRules) {
1149
- this.ipEnrichmentClient = new IPEnrichmentClient(this.client);
1044
+ return { action: "ALLOW", rule: this.name };
1045
+ }
1046
+ };
1047
+
1048
+ // src/rules/web-bot-auth-rule.ts
1049
+ var WebBotAuthRule = class {
1050
+ constructor(config = {}) {
1051
+ this.name = "web-bot-auth";
1052
+ this.onImpersonation = config.onImpersonation ?? "DENY";
1053
+ this.onClaimed = config.onClaimed ?? "ALLOW";
1054
+ this.allowCategories = config.allowCategories ? new Set(config.allowCategories) : void 0;
1055
+ this.dryRun = config.dryRun ?? false;
1056
+ }
1057
+ evaluate(context) {
1058
+ const verdict = context.agent;
1059
+ if (!verdict || verdict.status === "none") return this.allow();
1060
+ if (verdict.status === "impersonation") {
1061
+ return this.act(this.onImpersonation, "agent_impersonation", {
1062
+ agentName: verdict.agentName,
1063
+ category: verdict.category,
1064
+ keyId: verdict.keyId,
1065
+ detail: verdict.reason
1066
+ });
1150
1067
  }
1151
- if (this.client && this.ruleEngine) {
1152
- const reporter = new ViolationReporter(this.client, {
1153
- debug: this.config.debug
1068
+ if (verdict.status === "claimed") {
1069
+ return this.act(this.onClaimed, "agent_unverifiable", {
1070
+ keyId: verdict.keyId,
1071
+ detail: verdict.reason
1154
1072
  });
1155
- this.setViolationReporter(reporter);
1156
1073
  }
1157
- if (this.config.debug) {
1158
- console.log("[WebDecoy] Initialized with config:", {
1159
- apiUrl: this.config.apiUrl,
1160
- enableTLSFingerprinting: this.config.enableTLSFingerprinting,
1161
- threatScoreThreshold: this.config.threatScoreThreshold,
1162
- hasApiKey,
1163
- rulesCount: config.rules?.length ?? 0
1074
+ if (this.allowCategories && verdict.category && !this.allowCategories.has(verdict.category)) {
1075
+ return this.act(this.onClaimed, "agent_category_not_allowed", {
1076
+ agentName: verdict.agentName,
1077
+ category: verdict.category,
1078
+ keyId: verdict.keyId
1164
1079
  });
1165
1080
  }
1081
+ return this.allow();
1166
1082
  }
1167
- /**
1168
- * Evaluate rules against request metadata (synchronous).
1169
- * Returns null if no rules are configured.
1170
- */
1171
- evaluateRules(metadata) {
1172
- if (!this.ruleEngine) return null;
1173
- return this.runRules(this.buildContext(metadata));
1083
+ act(action, verdict, detail) {
1084
+ if (action === "ALLOW") return this.allow();
1085
+ return {
1086
+ action: this.dryRun ? "ALLOW" : action,
1087
+ rule: this.name,
1088
+ reason: reasonFor(verdict),
1089
+ metadata: { verdict, dryRun: this.dryRun, ...detail }
1090
+ };
1174
1091
  }
1175
- /**
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.
1179
- */
1180
- async evaluateRulesAsync(metadata) {
1181
- if (!this.ruleEngine) return null;
1182
- const context = await this.buildAsyncContext(metadata);
1183
- return this.runRules(context);
1092
+ allow() {
1093
+ return { action: "ALLOW", rule: this.name };
1184
1094
  }
1185
- /** Build the base (synchronous) rule context from request metadata. */
1186
- buildContext(metadata) {
1187
- return {
1188
- ip: metadata.ip,
1189
- path: metadata.path,
1190
- method: metadata.method,
1191
- userAgent: metadata.user_agent,
1192
- headers: metadata.headers,
1193
- timestamp: metadata.timestamp || Date.now()
1194
- };
1095
+ };
1096
+ function reasonFor(verdict) {
1097
+ switch (verdict) {
1098
+ case "agent_impersonation":
1099
+ return "Web Bot Auth signature failed verification (agent impersonation)";
1100
+ case "agent_unverifiable":
1101
+ return "Web Bot Auth signature could not be verified";
1102
+ case "agent_category_not_allowed":
1103
+ return "Verified agent category is not allowed";
1104
+ default:
1105
+ return "Web Bot Auth rule triggered";
1195
1106
  }
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);
1202
- if (this._hasFilterRules && this.ipEnrichmentClient) {
1203
- const enrichment = await this.ipEnrichmentClient.enrich(metadata.ip);
1204
- if (enrichment) {
1205
- context.enrichment = enrichment;
1206
- }
1207
- }
1208
- if (this._hasAgentRules) {
1209
- context.agent = await this.computeAgentVerdict(metadata);
1210
- }
1211
- return context;
1107
+ }
1108
+ function webBotAuth(config = {}) {
1109
+ return new WebBotAuthRule(config);
1110
+ }
1111
+
1112
+ // src/webcrypto.ts
1113
+ var encoder = new TextEncoder();
1114
+ function toHex(bytes) {
1115
+ let hex = "";
1116
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
1117
+ return hex;
1118
+ }
1119
+ async function sha256Hex(data) {
1120
+ const digest2 = await crypto.subtle.digest("SHA-256", encoder.encode(data));
1121
+ return toHex(new Uint8Array(digest2));
1122
+ }
1123
+ async function hmacSha256Hex(secret, data) {
1124
+ const key = await crypto.subtle.importKey(
1125
+ "raw",
1126
+ encoder.encode(secret),
1127
+ { name: "HMAC", hash: "SHA-256" },
1128
+ false,
1129
+ ["sign"]
1130
+ );
1131
+ const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(data));
1132
+ return toHex(new Uint8Array(sig));
1133
+ }
1134
+ function randomHex(bytes) {
1135
+ const buf = new Uint8Array(bytes);
1136
+ crypto.getRandomValues(buf);
1137
+ return toHex(buf);
1138
+ }
1139
+ function timingSafeEqualStr(a, b) {
1140
+ if (a.length !== b.length) return false;
1141
+ let diff = 0;
1142
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
1143
+ return diff === 0;
1144
+ }
1145
+ function base64urlEncode(data) {
1146
+ const bytes = encoder.encode(data);
1147
+ let binary = "";
1148
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1149
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1150
+ }
1151
+ function base64urlDecode(data) {
1152
+ const b64 = data.replace(/-/g, "+").replace(/_/g, "/");
1153
+ const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
1154
+ const binary = atob(padded);
1155
+ const bytes = new Uint8Array(binary.length);
1156
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1157
+ return new TextDecoder().decode(bytes);
1158
+ }
1159
+ function fnv1a64Hex(data) {
1160
+ const PRIME = 0x100000001b3n;
1161
+ const MASK = 0xffffffffffffffffn;
1162
+ let hash = 0xcbf29ce484222325n;
1163
+ const bytes = encoder.encode(data);
1164
+ for (let i = 0; i < bytes.length; i++) {
1165
+ hash ^= BigInt(bytes[i]);
1166
+ hash = hash * PRIME & MASK;
1212
1167
  }
1213
- /** Evaluate rules against a prepared context and report any violations. */
1214
- runRules(context) {
1215
- if (!this.ruleEngine) return null;
1216
- const result = this.ruleEngine.evaluate(context);
1217
- if (result.violations.length > 0 && this.violationReporter) {
1218
- this.violationReporter.report(result.violations);
1168
+ return hash.toString(16).padStart(16, "0");
1169
+ }
1170
+
1171
+ // src/rules/honeytoken.ts
1172
+ function honeytoken(options = {}) {
1173
+ const base = (options.basePath ?? "/__wd").replace(/\/+$/, "");
1174
+ const token = options.token ?? randomHex(6);
1175
+ const path = `${base}/${token}`;
1176
+ const text = options.text ?? ".";
1177
+ 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>`;
1178
+ return { path, linkHtml };
1179
+ }
1180
+
1181
+ // src/rules/index.ts
1182
+ function rateLimit(config) {
1183
+ return new RateLimitRule(config);
1184
+ }
1185
+ function filter(config) {
1186
+ return new FilterRule(config);
1187
+ }
1188
+ function tripwire(config = {}) {
1189
+ return new TripwireRule(config);
1190
+ }
1191
+
1192
+ // src/violation-reporter.ts
1193
+ var ViolationReporter = class {
1194
+ constructor(client, config = {}) {
1195
+ this.buffer = [];
1196
+ this.flushing = false;
1197
+ this.client = client;
1198
+ this.maxBufferSize = config.maxBufferSize ?? 50;
1199
+ this.debug = config.debug ?? false;
1200
+ const flushInterval = config.flushInterval ?? 5e3;
1201
+ this.flushTimer = setInterval(() => this.flush(), flushInterval);
1202
+ if (this.flushTimer.unref) {
1203
+ this.flushTimer.unref();
1219
1204
  }
1220
- return result;
1221
1205
  }
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
1206
+ /**
1207
+ * Add violations to the buffer. Auto-flushes when buffer reaches maxBufferSize.
1208
+ */
1209
+ report(violations) {
1210
+ this.buffer.push(...violations);
1211
+ if (this.buffer.length >= this.maxBufferSize) {
1212
+ this.flush().catch(() => {
1228
1213
  });
1229
1214
  }
1230
- return this.agentVerifier;
1231
1215
  }
1232
1216
  /**
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).
1217
+ * Flush buffered violations to the backend
1236
1218
  */
1237
- async computeAgentVerdict(metadata) {
1238
- const input = agentInputFromMetadata(metadata);
1239
- if (!input) return void 0;
1240
- return this.getAgentVerifier().verify(input);
1219
+ async flush() {
1220
+ if (this.flushing || this.buffer.length === 0) return;
1221
+ this.flushing = true;
1222
+ const events = this.buffer.splice(0, this.buffer.length);
1223
+ try {
1224
+ for (let i = 0; i < events.length; i += 100) {
1225
+ const batch = events.slice(i, i + 100);
1226
+ await this.client.sendViolations(batch);
1227
+ if (this.debug) {
1228
+ console.log(`[WebDecoy] Flushed ${batch.length} violation events`);
1229
+ }
1230
+ }
1231
+ } catch (error) {
1232
+ if (this.debug) {
1233
+ console.error("[WebDecoy] Failed to flush violations:", error);
1234
+ }
1235
+ } finally {
1236
+ this.flushing = false;
1237
+ }
1241
1238
  }
1242
1239
  /**
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
- * ```
1240
+ * Flush remaining events and stop the timer
1257
1241
  */
1258
- async detectBot(request) {
1259
- return this.getAgentVerifier().verify(request);
1242
+ async destroy() {
1243
+ clearInterval(this.flushTimer);
1244
+ await this.flush();
1260
1245
  }
1261
- /**
1262
- * Whether this SDK instance has filter rules that need async enrichment
1263
- */
1264
- get hasFilterRules() {
1265
- return this._hasFilterRules;
1246
+ };
1247
+
1248
+ // src/ip-enrichment.ts
1249
+ var IPEnrichmentClient = class {
1250
+ constructor(client, ttlMs = 36e5) {
1251
+ this.cache = /* @__PURE__ */ new Map();
1252
+ this.pending = /* @__PURE__ */ new Map();
1253
+ this.client = client;
1254
+ this.ttlMs = ttlMs;
1266
1255
  }
1267
1256
  /**
1268
- * Whether this SDK instance has Web Bot Auth rules that need async
1269
- * verification before evaluation.
1257
+ * Get enrichment data for an IP address.
1258
+ * Returns cached data if available (1h TTL), otherwise fetches from API.
1259
+ * Returns null if enrichment fails (fail-open).
1270
1260
  */
1271
- get hasAgentRules() {
1272
- return this._hasAgentRules;
1261
+ async enrich(ip) {
1262
+ const cached = this.cache.get(ip);
1263
+ if (cached && cached.expiresAt > Date.now()) {
1264
+ return cached.data;
1265
+ }
1266
+ const inflight = this.pending.get(ip);
1267
+ if (inflight) {
1268
+ return inflight;
1269
+ }
1270
+ const promise = this.fetchAndCache(ip);
1271
+ this.pending.set(ip, promise);
1272
+ try {
1273
+ return await promise;
1274
+ } finally {
1275
+ this.pending.delete(ip);
1276
+ }
1277
+ }
1278
+ async fetchAndCache(ip) {
1279
+ const data = await this.client.getIPEnrichment(ip);
1280
+ if (data) {
1281
+ this.cache.set(ip, {
1282
+ data,
1283
+ expiresAt: Date.now() + this.ttlMs
1284
+ });
1285
+ }
1286
+ return data;
1273
1287
  }
1274
1288
  /**
1275
- * Protect a request by checking it against Web Decoy's bot detection
1276
- *
1277
- * @param metadata - Request metadata to analyze
1278
- * @param options - Optional configuration for this specific request
1279
- * @returns Protection result with decision and detection details
1289
+ * Clear the cache
1280
1290
  */
1281
- async protect(metadata, options = {}) {
1282
- try {
1283
- if (!metadata.ip) {
1284
- throw new Error("IP address is required in request metadata");
1285
- }
1286
- if (!metadata.timestamp) {
1287
- metadata.timestamp = Date.now();
1288
- }
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
- }
1298
- if (ruleResult && ruleResult.action === "DENY") {
1299
- return {
1300
- allowed: false,
1301
- detection: {
1302
- decision: "block",
1303
- confidence: 100,
1304
- threat_level: "HIGH",
1305
- bot_detected: false,
1306
- detection_id: "rule_" + Date.now(),
1307
- rule_enforced: true
1308
- },
1309
- ruleResult,
1310
- agent: agentVerdict
1311
- };
1312
- }
1313
- if (ruleResult && ruleResult.action === "THROTTLE") {
1314
- return {
1315
- allowed: false,
1316
- detection: {
1317
- decision: "block",
1318
- confidence: 100,
1319
- threat_level: "MEDIUM",
1320
- bot_detected: false,
1321
- detection_id: "rule_" + Date.now(),
1322
- rule_enforced: true
1323
- },
1324
- ruleResult,
1325
- agent: agentVerdict
1326
- };
1327
- }
1328
- if (!this.client) {
1329
- return {
1330
- allowed: true,
1331
- detection: {
1332
- decision: "allow",
1333
- confidence: 0,
1334
- threat_level: "MINIMAL",
1335
- bot_detected: false,
1336
- detection_id: "local_" + Date.now(),
1337
- rule_enforced: false
1338
- },
1339
- ruleResult: ruleResult ?? void 0,
1340
- agent: agentVerdict
1341
- };
1342
- }
1343
- const localAnalysis = options.skipLocalAnalysis ? {
1344
- suspicious_headers: false,
1345
- missing_sec_ch_ua: false,
1346
- datacenter_ip: false,
1347
- local_score: 0,
1348
- needs_verification: true,
1349
- flags: ["local_analysis_skipped"]
1350
- } : analyzeRequest(metadata);
1351
- if (this.config.debug) {
1352
- console.log("[WebDecoy] Local analysis result:", localAnalysis);
1353
- }
1354
- const detectionRequest = {
1355
- request_metadata: metadata,
1356
- local_analysis: localAnalysis
1357
- };
1358
- const shouldCallServer = localAnalysis.needs_verification || this.config.enableTLSFingerprinting && metadata.tls_info;
1359
- if (!shouldCallServer && localAnalysis.local_score < 50) {
1360
- return {
1361
- allowed: true,
1362
- detection: {
1363
- decision: "allow",
1364
- confidence: 100 - localAnalysis.local_score,
1365
- threat_level: "MINIMAL",
1366
- bot_detected: false,
1367
- detection_id: "local_" + Date.now(),
1368
- rule_enforced: false
1369
- },
1370
- ruleResult: ruleResult ?? void 0,
1371
- agent: agentVerdict
1372
- };
1373
- }
1374
- const detection = await this.client.detect(detectionRequest);
1375
- const threshold = options.threshold ?? this.config.threatScoreThreshold;
1376
- const allowed = detection.decision === "allow" || detection.confidence < threshold;
1377
- if (this.config.debug) {
1378
- console.log("[WebDecoy] Server detection result:", {
1379
- decision: detection.decision,
1380
- confidence: detection.confidence,
1381
- allowed
1382
- });
1383
- }
1384
- return {
1385
- allowed,
1386
- detection,
1387
- ruleResult: ruleResult ?? void 0,
1388
- agent: agentVerdict
1389
- };
1390
- } catch (error) {
1391
- if (this.config.debug) {
1392
- console.error("[WebDecoy] Protection error:", error);
1393
- }
1394
- return {
1395
- allowed: true,
1396
- // Fail open to avoid blocking legitimate users
1397
- detection: {
1398
- decision: "allow",
1399
- confidence: 0,
1400
- threat_level: "MINIMAL",
1401
- bot_detected: false,
1402
- detection_id: "error_" + Date.now(),
1403
- rule_enforced: false
1404
- },
1405
- error: error instanceof Error ? error.message : "Unknown error"
1406
- };
1407
- }
1291
+ clearCache() {
1292
+ this.cache.clear();
1408
1293
  }
1409
- /**
1410
- * Validate the API key configuration
1411
- * Useful for testing integration during setup
1412
- */
1413
- async validateConfig() {
1414
- if (!this.client) {
1415
- return { valid: false, error: "No API key configured" };
1416
- }
1417
- try {
1418
- const isValid = await this.client.validateAPIKey();
1419
- return { valid: isValid };
1420
- } catch (error) {
1421
- return {
1422
- valid: false,
1423
- error: error instanceof Error ? error.message : "Unknown error"
1424
- };
1425
- }
1294
+ };
1295
+
1296
+ // src/agent/thumbprint.ts
1297
+ var encoder2 = new TextEncoder();
1298
+ async function rsaThumbprint(n, e) {
1299
+ return digest(`{"e":${JSON.stringify(e)},"kty":"RSA","n":${JSON.stringify(n)}}`);
1300
+ }
1301
+ async function okpThumbprint(crv, x) {
1302
+ return digest(`{"crv":${JSON.stringify(crv)},"kty":"OKP","x":${JSON.stringify(x)}}`);
1303
+ }
1304
+ async function jwkThumbprint(k) {
1305
+ switch (k.kty) {
1306
+ case "OKP":
1307
+ if (!k.crv || !k.x) throw new Error("thumbprint: OKP JWK missing crv or x");
1308
+ return okpThumbprint(k.crv, k.x);
1309
+ case "RSA":
1310
+ if (!k.n || !k.e) throw new Error("thumbprint: RSA JWK missing n or e");
1311
+ return rsaThumbprint(k.n, k.e);
1312
+ default:
1313
+ throw new Error(`thumbprint: unsupported kty ${JSON.stringify(k.kty)}`);
1426
1314
  }
1427
- /**
1428
- * Attach a violation reporter for sending violations to the backend.
1429
- * Called internally when apiKey is present and rules are configured.
1430
- */
1431
- setViolationReporter(reporter) {
1432
- this.violationReporter = reporter;
1315
+ }
1316
+ async function digest(canonical) {
1317
+ const buf = await crypto.subtle.digest("SHA-256", encoder2.encode(canonical));
1318
+ return base64urlBytes(new Uint8Array(buf));
1319
+ }
1320
+ function base64urlBytes(bytes) {
1321
+ let binary = "";
1322
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1323
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1324
+ }
1325
+
1326
+ // src/agent/directory.ts
1327
+ var WELL_KNOWN = "/.well-known/http-message-signatures-directory";
1328
+ var COLD_RETRY_BACKOFF_MS = 3e4;
1329
+ var DEFAULT_SIGNED_AGENT_DIRECTORIES = [
1330
+ { name: "OpenAI", category: "ai_crawlers", directory: "https://operator.openai.com" },
1331
+ { name: "OpenAI ChatGPT", category: "ai_crawlers", directory: "https://chatgpt.com" }
1332
+ ];
1333
+ var DirectoryCache = class {
1334
+ constructor(opts) {
1335
+ this.keys = /* @__PURE__ */ new Map();
1336
+ this.refreshedAt = 0;
1337
+ this.nextColdRetryAt = 0;
1338
+ this.inflight = null;
1339
+ /** Resolve a keyid to a verification key, fetching/refreshing as needed. */
1340
+ this.resolveKey = async (keyId) => {
1341
+ await this.ensureFresh();
1342
+ return this.keys.get(keyId);
1343
+ };
1344
+ this.opts = opts;
1433
1345
  }
1434
- /**
1435
- * Get the API client (for use by violation reporter, enrichment, etc.)
1436
- */
1437
- getClient() {
1438
- return this.client;
1346
+ /** Kick off a fetch without blocking — call at startup to warm the cache. */
1347
+ prime() {
1348
+ if (this.keys.size === 0 && Date.now() >= this.nextColdRetryAt) void this.refresh();
1439
1349
  }
1440
- /**
1441
- * Get the current configuration
1442
- */
1443
- getConfig() {
1444
- return { ...this.config };
1350
+ /** Number of keys currently cached (diagnostics/tests). */
1351
+ get size() {
1352
+ return this.keys.size;
1445
1353
  }
1446
- /**
1447
- * Clean up resources (timers, flush pending violations)
1448
- */
1449
- async destroy() {
1450
- this.ruleEngine?.destroy();
1451
- if (this.violationReporter) {
1452
- await this.violationReporter.destroy();
1354
+ async ensureFresh() {
1355
+ const now = Date.now();
1356
+ const stale = now - this.refreshedAt > this.opts.cacheTtlMs;
1357
+ if (this.keys.size > 0) {
1358
+ if (stale) void this.refresh();
1359
+ return;
1453
1360
  }
1361
+ if (now < this.nextColdRetryAt) return;
1362
+ await this.refresh();
1454
1363
  }
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;
1364
+ /** Re-fetch every directory. De-duplicated: concurrent callers share one run. */
1365
+ refresh() {
1366
+ if (this.inflight) return this.inflight;
1367
+ this.inflight = this.doRefresh().finally(() => {
1368
+ this.inflight = null;
1369
+ });
1370
+ return this.inflight;
1472
1371
  }
1473
- }
1474
-
1475
- // src/rules/rate-limiter.ts
1476
- var InMemoryRateLimiter = class {
1477
- constructor() {
1478
- this.fixedWindows = /* @__PURE__ */ new Map();
1479
- this.slidingWindows = /* @__PURE__ */ new Map();
1480
- this.cleanupTimer = setInterval(() => this.cleanup(), 6e4);
1481
- if (this.cleanupTimer.unref) {
1482
- this.cleanupTimer.unref();
1483
- }
1484
- }
1485
- /**
1486
- * Check and increment for fixed window algorithm
1487
- * Returns the current count after increment, and the window reset time
1488
- */
1489
- checkFixedWindow(key, max, windowMs) {
1490
- const now = Date.now();
1491
- const entry = this.fixedWindows.get(key);
1492
- if (!entry || now - entry.windowStart >= windowMs) {
1493
- this.fixedWindows.set(key, { count: 1, windowStart: now });
1494
- return { allowed: true, current: 1, resetAt: now + windowMs };
1495
- }
1496
- entry.count++;
1497
- const resetAt = entry.windowStart + windowMs;
1498
- if (entry.count > max) {
1499
- return { allowed: false, current: entry.count, resetAt };
1500
- }
1501
- return { allowed: true, current: entry.count, resetAt };
1502
- }
1503
- /**
1504
- * Check and increment for sliding window algorithm
1505
- * Returns the current count after adding the new timestamp
1506
- */
1507
- checkSlidingWindow(key, max, windowMs) {
1508
- const now = Date.now();
1509
- const cutoff = now - windowMs;
1510
- let timestamps = this.slidingWindows.get(key);
1511
- if (!timestamps) {
1512
- timestamps = [];
1513
- this.slidingWindows.set(key, timestamps);
1514
- }
1515
- while (timestamps.length > 0 && timestamps[0] <= cutoff) {
1516
- timestamps.shift();
1372
+ async doRefresh() {
1373
+ const results = await Promise.all(
1374
+ this.opts.directories.map((src) => this.fetchDirectory(src))
1375
+ );
1376
+ const next = new Map(this.keys);
1377
+ let fetchedAny = false;
1378
+ for (const keys of results) {
1379
+ if (keys === null) continue;
1380
+ fetchedAny = true;
1381
+ for (const k of keys) next.set(k.thumbprint, k.key);
1517
1382
  }
1518
- timestamps.push(now);
1519
- const resetAt = timestamps.length > 0 ? timestamps[0] + windowMs : now + windowMs;
1520
- if (timestamps.length > max) {
1521
- return { allowed: false, current: timestamps.length, resetAt };
1383
+ if (fetchedAny) {
1384
+ this.keys = next;
1385
+ this.refreshedAt = Date.now();
1386
+ this.nextColdRetryAt = 0;
1387
+ this.debug(`refreshed: ${this.keys.size} key(s) across ${this.opts.directories.length} directories`);
1388
+ } else if (this.keys.size === 0) {
1389
+ this.nextColdRetryAt = Date.now() + COLD_RETRY_BACKOFF_MS;
1390
+ this.debug("all directories unreachable; backing off cold retry");
1522
1391
  }
1523
- return { allowed: true, current: timestamps.length, resetAt };
1524
1392
  }
1525
- /**
1526
- * Clean up expired entries from both maps
1527
- */
1528
- cleanup() {
1529
- const now = Date.now();
1530
- for (const [key, entry] of this.fixedWindows) {
1531
- if (now - entry.windowStart > 3e5) {
1532
- this.fixedWindows.delete(key);
1393
+ async fetchDirectory(src) {
1394
+ const url = directoryUrl(src.directory);
1395
+ const controller = new AbortController();
1396
+ const timer = setTimeout(() => controller.abort(), this.opts.fetchTimeoutMs);
1397
+ try {
1398
+ const res = await this.opts.fetchImpl(url, {
1399
+ signal: controller.signal,
1400
+ headers: {
1401
+ Accept: "application/http-message-signatures-directory+json, application/jwk-set+json, application/json"
1402
+ },
1403
+ redirect: "follow"
1404
+ });
1405
+ if (!res.ok) {
1406
+ this.debug(`${src.name}: HTTP ${res.status}`);
1407
+ return null;
1533
1408
  }
1534
- }
1535
- for (const [key, timestamps] of this.slidingWindows) {
1536
- if (timestamps.length === 0) {
1537
- this.slidingWindows.delete(key);
1538
- continue;
1409
+ const body = await res.json();
1410
+ if (!body || !Array.isArray(body.keys)) {
1411
+ this.debug(`${src.name}: no keys in directory`);
1412
+ return null;
1539
1413
  }
1540
- const latest = timestamps[timestamps.length - 1];
1541
- if (now - latest > 3e5) {
1542
- this.slidingWindows.delete(key);
1414
+ const out = [];
1415
+ for (const jwk of body.keys) {
1416
+ const resolved = await importKey(jwk, src);
1417
+ if (resolved) out.push(resolved);
1543
1418
  }
1419
+ this.debug(`${src.name}: ${out.length} key(s)`);
1420
+ return out;
1421
+ } catch (err) {
1422
+ this.debug(`${src.name}: fetch failed \u2014 ${err.message}`);
1423
+ return null;
1424
+ } finally {
1425
+ clearTimeout(timer);
1544
1426
  }
1545
1427
  }
1546
- /**
1547
- * Release resources
1548
- */
1549
- destroy() {
1550
- clearInterval(this.cleanupTimer);
1551
- this.fixedWindows.clear();
1552
- this.slidingWindows.clear();
1428
+ debug(msg) {
1429
+ if (this.opts.debug) console.log(`[WebDecoy][web-bot-auth] ${msg}`);
1553
1430
  }
1554
1431
  };
1555
-
1556
- // src/rules/rate-limit-rule.ts
1557
- var RateLimitRule = class {
1558
- constructor(config) {
1559
- this.name = `rate-limit:${config.max}/${config.window}s`;
1560
- this.limiter = new InMemoryRateLimiter();
1561
- this.config = {
1562
- max: config.max,
1563
- window: config.window,
1564
- algorithm: config.algorithm ?? "fixed",
1565
- keyBy: config.keyBy,
1566
- action: config.action ?? "THROTTLE",
1567
- dryRun: config.dryRun ?? false
1568
- };
1569
- }
1570
- evaluate(context) {
1571
- const key = this.config.keyBy ? this.config.keyBy(context) : context.ip;
1572
- const windowMs = this.config.window * 1e3;
1573
- const result = this.config.algorithm === "sliding" ? this.limiter.checkSlidingWindow(key, this.config.max, windowMs) : this.limiter.checkFixedWindow(key, this.config.max, windowMs);
1574
- if (!result.allowed) {
1575
- const retryAfter = Math.ceil((result.resetAt - Date.now()) / 1e3);
1576
- return {
1577
- action: this.config.dryRun ? "ALLOW" : this.config.action,
1578
- rule: this.name,
1579
- reason: `Rate limit exceeded: ${result.current}/${this.config.max} requests in ${this.config.window}s window`,
1580
- metadata: {
1581
- current: result.current,
1582
- max: this.config.max,
1583
- window: this.config.window,
1584
- retryAfter: Math.max(retryAfter, 1),
1585
- dryRun: this.config.dryRun
1586
- }
1587
- };
1432
+ function directoryUrl(directory) {
1433
+ const u = new URL(directory);
1434
+ if (u.pathname && u.pathname !== "/") return u.toString();
1435
+ u.pathname = WELL_KNOWN;
1436
+ return u.toString();
1437
+ }
1438
+ async function importKey(jwk, src) {
1439
+ try {
1440
+ let cryptoKey;
1441
+ let verifyParams;
1442
+ let algorithm;
1443
+ if (jwk.kty === "OKP") {
1444
+ if (jwk.crv !== "Ed25519" || !jwk.x) return null;
1445
+ cryptoKey = await crypto.subtle.importKey(
1446
+ "jwk",
1447
+ { kty: "OKP", crv: "Ed25519", x: jwk.x },
1448
+ { name: "Ed25519" },
1449
+ false,
1450
+ ["verify"]
1451
+ );
1452
+ verifyParams = { name: "Ed25519" };
1453
+ algorithm = "ed25519";
1454
+ } else if (jwk.kty === "RSA") {
1455
+ if (!jwk.n || !jwk.e) return null;
1456
+ cryptoKey = await crypto.subtle.importKey(
1457
+ "jwk",
1458
+ { kty: "RSA", n: jwk.n, e: jwk.e },
1459
+ { name: "RSA-PSS", hash: "SHA-512" },
1460
+ false,
1461
+ ["verify"]
1462
+ );
1463
+ verifyParams = { name: "RSA-PSS", saltLength: 64 };
1464
+ algorithm = "rsa-pss-sha512";
1465
+ } else {
1466
+ return null;
1588
1467
  }
1468
+ const thumbprint = await jwkThumbprint(jwk);
1589
1469
  return {
1590
- action: "ALLOW",
1591
- rule: this.name,
1592
- metadata: {
1593
- current: result.current,
1594
- max: this.config.max,
1595
- remaining: this.config.max - result.current
1470
+ thumbprint,
1471
+ key: {
1472
+ cryptoKey,
1473
+ verifyParams,
1474
+ algorithm,
1475
+ name: src.name,
1476
+ category: src.category,
1477
+ nbf: normalizeEpoch(jwk.nbf),
1478
+ exp: normalizeEpoch(jwk.exp)
1596
1479
  }
1597
1480
  };
1481
+ } catch {
1482
+ return null;
1598
1483
  }
1599
- destroy() {
1600
- this.limiter.destroy();
1601
- }
1602
- };
1484
+ }
1485
+ function normalizeEpoch(v) {
1486
+ if (v === void 0 || v === 0) return void 0;
1487
+ return v > 1e12 ? Math.floor(v / 1e3) : v;
1488
+ }
1603
1489
 
1604
- // src/rules/filter/tokenizer.ts
1605
- var KEYWORDS = {
1606
- and: "AND" /* AND */,
1607
- or: "OR" /* OR */,
1608
- not: "NOT" /* NOT */,
1609
- in: "IN" /* IN */,
1610
- matches: "MATCHES" /* MATCHES */,
1611
- true: "BOOL" /* BOOL */,
1612
- false: "BOOL" /* BOOL */
1613
- };
1614
- var Tokenizer = class {
1615
- constructor(source) {
1616
- this.pos = 0;
1617
- this.tokens = [];
1618
- this.source = source;
1490
+ // src/agent/sfv.ts
1491
+ var Cursor = class {
1492
+ constructor(s, i = 0) {
1493
+ this.s = s;
1494
+ this.i = i;
1619
1495
  }
1620
- tokenize() {
1621
- while (this.pos < this.source.length) {
1622
- this.skipWhitespace();
1623
- if (this.pos >= this.source.length) break;
1624
- const ch = this.source[this.pos];
1625
- if (ch === ".") {
1626
- this.tokens.push({ type: "DOT" /* DOT */, value: ".", position: this.pos });
1627
- this.pos++;
1628
- continue;
1629
- }
1630
- if (ch === "(") {
1631
- this.tokens.push({ type: "LPAREN" /* LPAREN */, value: "(", position: this.pos });
1632
- this.pos++;
1633
- continue;
1634
- }
1635
- if (ch === ")") {
1636
- this.tokens.push({ type: "RPAREN" /* RPAREN */, value: ")", position: this.pos });
1637
- this.pos++;
1638
- continue;
1639
- }
1640
- if (ch === "[") {
1641
- this.tokens.push({ type: "LBRACKET" /* LBRACKET */, value: "[", position: this.pos });
1642
- this.pos++;
1643
- continue;
1644
- }
1645
- if (ch === "]") {
1646
- this.tokens.push({ type: "RBRACKET" /* RBRACKET */, value: "]", position: this.pos });
1647
- this.pos++;
1648
- continue;
1649
- }
1650
- if (ch === ",") {
1651
- this.tokens.push({ type: "COMMA" /* COMMA */, value: ",", position: this.pos });
1652
- this.pos++;
1653
- continue;
1654
- }
1655
- if (ch === "=" && this.peek(1) === "=") {
1656
- this.tokens.push({ type: "EQ" /* EQ */, value: "==", position: this.pos });
1657
- this.pos += 2;
1658
- continue;
1659
- }
1660
- if (ch === "!" && this.peek(1) === "=") {
1661
- this.tokens.push({ type: "NEQ" /* NEQ */, value: "!=", position: this.pos });
1662
- this.pos += 2;
1663
- continue;
1664
- }
1665
- if (ch === ">" && this.peek(1) === "=") {
1666
- this.tokens.push({ type: "GTE" /* GTE */, value: ">=", position: this.pos });
1667
- this.pos += 2;
1668
- continue;
1669
- }
1670
- if (ch === "<" && this.peek(1) === "=") {
1671
- this.tokens.push({ type: "LTE" /* LTE */, value: "<=", position: this.pos });
1672
- this.pos += 2;
1673
- continue;
1674
- }
1675
- if (ch === ">") {
1676
- this.tokens.push({ type: "GT" /* GT */, value: ">", position: this.pos });
1677
- this.pos++;
1678
- continue;
1679
- }
1680
- if (ch === "<") {
1681
- this.tokens.push({ type: "LT" /* LT */, value: "<", position: this.pos });
1682
- this.pos++;
1683
- continue;
1684
- }
1685
- if (ch === '"' || ch === "'") {
1686
- this.readString(ch);
1687
- continue;
1688
- }
1689
- if (this.isDigit(ch) || ch === "-" && this.isDigit(this.peek(1))) {
1690
- this.readNumber();
1691
- continue;
1692
- }
1693
- if (this.isIdentStart(ch)) {
1694
- this.readIdent();
1695
- continue;
1696
- }
1697
- throw new Error(`Unexpected character '${ch}' at position ${this.pos}`);
1698
- }
1699
- this.tokens.push({ type: "EOF" /* EOF */, value: "", position: this.pos });
1700
- return this.tokens;
1496
+ eof() {
1497
+ return this.i >= this.s.length;
1701
1498
  }
1702
- peek(offset) {
1703
- const idx = this.pos + offset;
1704
- return idx < this.source.length ? this.source[idx] : "";
1499
+ peek() {
1500
+ return this.s[this.i];
1705
1501
  }
1706
- skipWhitespace() {
1707
- while (this.pos < this.source.length && /\s/.test(this.source[this.pos])) {
1708
- this.pos++;
1709
- }
1502
+ skipSP() {
1503
+ while (!this.eof() && (this.peek() === " " || this.peek() === " ")) this.i++;
1710
1504
  }
1711
- readString(quote) {
1712
- const start = this.pos;
1713
- this.pos++;
1714
- let value = "";
1715
- while (this.pos < this.source.length && this.source[this.pos] !== quote) {
1716
- if (this.source[this.pos] === "\\") {
1717
- this.pos++;
1505
+ };
1506
+ function parseDictionary(input) {
1507
+ const p = new Cursor(input);
1508
+ const out = [];
1509
+ p.skipSP();
1510
+ while (!p.eof()) {
1511
+ const key = parseKey(p);
1512
+ const entry = { key, raw: "", isList: false, items: [], params: /* @__PURE__ */ new Map() };
1513
+ if (!p.eof() && p.peek() === "=") {
1514
+ p.i++;
1515
+ const start = p.i;
1516
+ if (!p.eof() && p.peek() === "(") {
1517
+ entry.isList = true;
1518
+ parseInnerList(p, entry);
1519
+ } else {
1520
+ entry.items.push(parseItem(p));
1521
+ entry.params = entry.items[0].params;
1718
1522
  }
1719
- value += this.source[this.pos];
1720
- this.pos++;
1721
- }
1722
- if (this.pos >= this.source.length) {
1723
- throw new Error(`Unterminated string at position ${start}`);
1523
+ entry.raw = input.slice(start, p.i);
1524
+ } else {
1525
+ entry.params = parseParams(p);
1526
+ entry.items.push({ value: true, params: /* @__PURE__ */ new Map() });
1527
+ entry.raw = "?1";
1724
1528
  }
1725
- this.pos++;
1726
- this.tokens.push({ type: "STRING" /* STRING */, value, position: start });
1529
+ out.push(entry);
1530
+ p.skipSP();
1531
+ if (p.eof()) break;
1532
+ if (p.peek() !== ",") throw new Error(`sfv: expected ',' at ${p.i}`);
1533
+ p.i++;
1534
+ p.skipSP();
1535
+ if (p.eof()) throw new Error("sfv: trailing comma");
1727
1536
  }
1728
- readNumber() {
1729
- const start = this.pos;
1730
- if (this.source[this.pos] === "-") this.pos++;
1731
- while (this.pos < this.source.length && this.isDigit(this.source[this.pos])) {
1732
- this.pos++;
1733
- }
1734
- if (this.pos < this.source.length && this.source[this.pos] === ".") {
1735
- this.pos++;
1736
- while (this.pos < this.source.length && this.isDigit(this.source[this.pos])) {
1737
- this.pos++;
1738
- }
1537
+ return out;
1538
+ }
1539
+ function parseInnerList(p, entry) {
1540
+ p.i++;
1541
+ for (; ; ) {
1542
+ p.skipSP();
1543
+ if (p.eof()) throw new Error("sfv: unterminated inner list");
1544
+ if (p.peek() === ")") {
1545
+ p.i++;
1546
+ break;
1739
1547
  }
1740
- this.tokens.push({ type: "NUMBER" /* NUMBER */, value: this.source.slice(start, this.pos), position: start });
1548
+ entry.items.push(parseItem(p));
1549
+ if (p.eof()) throw new Error("sfv: unterminated inner list");
1550
+ const c = p.peek();
1551
+ if (c !== " " && c !== ")") throw new Error(`sfv: bad inner list at ${p.i}`);
1741
1552
  }
1742
- readIdent() {
1743
- const start = this.pos;
1744
- while (this.pos < this.source.length && this.isIdentPart(this.source[this.pos])) {
1745
- this.pos++;
1746
- }
1747
- const value = this.source.slice(start, this.pos);
1748
- const keyword = KEYWORDS[value.toLowerCase()];
1749
- if (keyword) {
1750
- this.tokens.push({ type: keyword, value: value.toLowerCase(), position: start });
1751
- } else {
1752
- this.tokens.push({ type: "IDENT" /* IDENT */, value, position: start });
1553
+ entry.params = parseParams(p);
1554
+ }
1555
+ function parseItem(p) {
1556
+ const { value, bytes } = parseBareItem(p);
1557
+ const params = parseParams(p);
1558
+ return bytes ? { value, params, bytes } : { value, params };
1559
+ }
1560
+ function parseParams(p) {
1561
+ const params = /* @__PURE__ */ new Map();
1562
+ while (!p.eof() && p.peek() === ";") {
1563
+ p.i++;
1564
+ p.skipSP();
1565
+ const key = parseKey(p);
1566
+ let val = true;
1567
+ if (!p.eof() && p.peek() === "=") {
1568
+ p.i++;
1569
+ val = parseBareItem(p).value;
1753
1570
  }
1571
+ params.set(key, val);
1754
1572
  }
1755
- isDigit(ch) {
1756
- return ch >= "0" && ch <= "9";
1573
+ return params;
1574
+ }
1575
+ function parseKey(p) {
1576
+ const c = p.peek();
1577
+ if (!c || !/[a-z*]/.test(c)) throw new Error(`sfv: invalid key at ${p.i}`);
1578
+ const start = p.i;
1579
+ while (!p.eof() && /[a-z0-9_\-.*]/.test(p.peek())) p.i++;
1580
+ return p.s.slice(start, p.i);
1581
+ }
1582
+ function parseBareItem(p) {
1583
+ const c = p.peek();
1584
+ if (c === '"') return { value: parseString(p) };
1585
+ if (c === ":") return { value: "", bytes: parseByteSequence(p) };
1586
+ if (c === "?") {
1587
+ p.i++;
1588
+ const b = p.s[p.i++];
1589
+ if (b === "1") return { value: true };
1590
+ if (b === "0") return { value: false };
1591
+ throw new Error("sfv: bad boolean");
1757
1592
  }
1758
- isIdentStart(ch) {
1759
- return /[a-zA-Z_]/.test(ch);
1593
+ if (c === "-" || /[0-9]/.test(c)) return { value: parseNumber(p) };
1594
+ if (/[a-zA-Z*]/.test(c)) return { value: parseToken(p) };
1595
+ throw new Error(`sfv: invalid bare item at ${p.i}`);
1596
+ }
1597
+ function parseString(p) {
1598
+ p.i++;
1599
+ let out = "";
1600
+ while (!p.eof()) {
1601
+ const c = p.s[p.i++];
1602
+ if (c === '"') return out;
1603
+ if (c === "\\") {
1604
+ const e = p.s[p.i++];
1605
+ if (e !== '"' && e !== "\\") throw new Error("sfv: bad escape");
1606
+ out += e;
1607
+ } else {
1608
+ const code = c.charCodeAt(0);
1609
+ if (code < 32 || code > 126) throw new Error("sfv: bad char in string");
1610
+ out += c;
1611
+ }
1760
1612
  }
1761
- isIdentPart(ch) {
1762
- return /[a-zA-Z0-9_]/.test(ch);
1613
+ throw new Error("sfv: unterminated string");
1614
+ }
1615
+ function parseByteSequence(p) {
1616
+ p.i++;
1617
+ const start = p.i;
1618
+ while (!p.eof() && p.peek() !== ":") p.i++;
1619
+ if (p.eof()) throw new Error("sfv: unterminated byte sequence");
1620
+ const b64 = p.s.slice(start, p.i);
1621
+ p.i++;
1622
+ return base64StdToBytes(b64);
1623
+ }
1624
+ function parseNumber(p) {
1625
+ const start = p.i;
1626
+ if (p.peek() === "-") p.i++;
1627
+ while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
1628
+ if (!p.eof() && p.peek() === ".") {
1629
+ p.i++;
1630
+ while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
1763
1631
  }
1764
- };
1632
+ return Number(p.s.slice(start, p.i));
1633
+ }
1634
+ function parseToken(p) {
1635
+ const start = p.i;
1636
+ p.i++;
1637
+ while (!p.eof() && /[a-zA-Z0-9!#$%&'*+\-.^_`|~:/]/.test(p.peek())) p.i++;
1638
+ return p.s.slice(start, p.i);
1639
+ }
1640
+ function base64StdToBytes(s) {
1641
+ const bin = atob(s);
1642
+ const out = new Uint8Array(bin.length);
1643
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
1644
+ return out;
1645
+ }
1765
1646
 
1766
- // src/rules/filter/parser.ts
1767
- var Parser = class {
1768
- constructor(source) {
1769
- this.pos = 0;
1770
- this.tokens = new Tokenizer(source).tokenize();
1771
- }
1772
- parse() {
1773
- const ast = this.orExpr();
1774
- this.expect("EOF" /* EOF */, "Expected end of expression");
1775
- return ast;
1776
- }
1777
- orExpr() {
1778
- let left = this.andExpr();
1779
- while (this.match("OR" /* OR */)) {
1780
- const right = this.andExpr();
1781
- left = { kind: "binary", op: "or", left, right };
1782
- }
1783
- return left;
1784
- }
1785
- andExpr() {
1786
- let left = this.unary();
1787
- while (this.match("AND" /* AND */)) {
1788
- const right = this.unary();
1789
- left = { kind: "binary", op: "and", left, right };
1790
- }
1791
- return left;
1647
+ // src/agent/signature.ts
1648
+ var TAG = "web-bot-auth";
1649
+ var encoder3 = new TextEncoder();
1650
+ async function verifyWebBotAuth(req, resolveKey, toleranceSec) {
1651
+ const sigInput = req.headers.get("signature-input");
1652
+ const sigHeader = req.headers.get("signature");
1653
+ if (!sigInput && !sigHeader) return { outcome: "none" };
1654
+ if (!sigInput || !sigHeader) return { outcome: "claimed", reason: "incomplete-signature" };
1655
+ let members;
1656
+ let sigs;
1657
+ try {
1658
+ members = parseSignatureInput(sigInput);
1659
+ sigs = parseSignatureBytes(sigHeader);
1660
+ } catch {
1661
+ return { outcome: "claimed", reason: "malformed-signature" };
1792
1662
  }
1793
- unary() {
1794
- if (this.match("NOT" /* NOT */)) {
1795
- if (this.check("IN" /* IN */)) {
1796
- this.pos--;
1797
- return this.comparison();
1798
- }
1799
- const operand = this.unary();
1800
- return { kind: "unary", op: "not", operand };
1663
+ const now = Date.now() / 1e3;
1664
+ let best = { outcome: "none" };
1665
+ for (const m of members) {
1666
+ if (m.params.get("tag") !== TAG) continue;
1667
+ if (best.outcome === "none") best = { outcome: "claimed", reason: "unverifiable" };
1668
+ const sig = sigs.get(m.label);
1669
+ if (!sig) continue;
1670
+ const keyid = m.params.get("keyid");
1671
+ if (typeof keyid !== "string") continue;
1672
+ if (!m.components.some((c) => c.name === "@authority" || c.name === "@target-uri")) continue;
1673
+ const key = await resolveKey(keyid);
1674
+ if (!key) {
1675
+ best = higher(best, { outcome: "claimed", keyId: keyid, reason: "unknown-key" });
1676
+ continue;
1801
1677
  }
1802
- return this.comparison();
1803
- }
1804
- comparison() {
1805
- let left = this.primary();
1806
- if (this.match("EQ" /* EQ */)) return { kind: "binary", op: "==", left, right: this.primary() };
1807
- if (this.match("NEQ" /* NEQ */)) return { kind: "binary", op: "!=", left, right: this.primary() };
1808
- if (this.match("GT" /* GT */)) return { kind: "binary", op: ">", left, right: this.primary() };
1809
- if (this.match("GTE" /* GTE */)) return { kind: "binary", op: ">=", left, right: this.primary() };
1810
- if (this.match("LT" /* LT */)) return { kind: "binary", op: "<", left, right: this.primary() };
1811
- if (this.match("LTE" /* LTE */)) return { kind: "binary", op: "<=", left, right: this.primary() };
1812
- if (this.match("IN" /* IN */)) return { kind: "binary", op: "in", left, right: this.primary() };
1813
- if (this.match("MATCHES" /* MATCHES */)) return { kind: "binary", op: "matches", left, right: this.primary() };
1814
- if (this.check("NOT" /* NOT */) && this.checkAhead("IN" /* IN */)) {
1815
- this.advance();
1816
- this.advance();
1817
- return { kind: "binary", op: "not in", left, right: this.primary() };
1678
+ const created = numeric(m.params.get("created"));
1679
+ const expires = numeric(m.params.get("expires"));
1680
+ if (expires !== void 0 && now > expires + toleranceSec) {
1681
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "expired" });
1682
+ continue;
1818
1683
  }
1819
- return left;
1820
- }
1821
- primary() {
1822
- if (this.check("BOOL" /* BOOL */)) {
1823
- const token = this.advance();
1824
- return { kind: "bool", value: token.value === "true" };
1684
+ if (created !== void 0 && now + toleranceSec < created) {
1685
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "not-yet-valid" });
1686
+ continue;
1825
1687
  }
1826
- if (this.check("NUMBER" /* NUMBER */)) {
1827
- const token = this.advance();
1828
- return { kind: "number", value: parseFloat(token.value) };
1688
+ if (key.exp !== void 0 && now > key.exp + toleranceSec) {
1689
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-expired" });
1690
+ continue;
1829
1691
  }
1830
- if (this.check("STRING" /* STRING */)) {
1831
- const token = this.advance();
1832
- return { kind: "string", value: token.value };
1692
+ if (key.nbf !== void 0 && now + toleranceSec < key.nbf) {
1693
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-not-yet-valid" });
1694
+ continue;
1833
1695
  }
1834
- if (this.match("LBRACKET" /* LBRACKET */)) {
1835
- const elements = [];
1836
- if (!this.check("RBRACKET" /* RBRACKET */)) {
1837
- elements.push(this.primary());
1838
- while (this.match("COMMA" /* COMMA */)) {
1839
- elements.push(this.primary());
1840
- }
1841
- }
1842
- this.expect("RBRACKET" /* RBRACKET */, 'Expected "]"');
1843
- return { kind: "array", elements };
1696
+ let base;
1697
+ try {
1698
+ base = buildSignatureBase(req, m);
1699
+ } catch {
1700
+ best = higher(best, { outcome: "claimed", keyId: keyid, reason: "uncoverable-component" });
1701
+ continue;
1844
1702
  }
1845
- if (this.match("LPAREN" /* LPAREN */)) {
1846
- const expr = this.orExpr();
1847
- this.expect("RPAREN" /* RPAREN */, 'Expected ")"');
1848
- return expr;
1703
+ let ok = false;
1704
+ try {
1705
+ ok = await crypto.subtle.verify(
1706
+ key.verifyParams,
1707
+ key.cryptoKey,
1708
+ sig,
1709
+ encoder3.encode(base)
1710
+ );
1711
+ } catch {
1712
+ ok = false;
1849
1713
  }
1850
- if (this.check("IDENT" /* IDENT */)) {
1851
- const path = [this.advance().value];
1852
- while (this.match("DOT" /* DOT */)) {
1853
- if (!this.check("IDENT" /* IDENT */)) {
1854
- throw new Error(`Expected identifier after "." at position ${this.current().position}`);
1855
- }
1856
- path.push(this.advance().value);
1857
- }
1858
- if (this.match("LPAREN" /* LPAREN */)) {
1859
- const method = path.pop();
1860
- const args = [];
1861
- if (!this.check("RPAREN" /* RPAREN */)) {
1862
- args.push(this.primary());
1863
- while (this.match("COMMA" /* COMMA */)) {
1864
- args.push(this.primary());
1865
- }
1866
- }
1867
- this.expect("RPAREN" /* RPAREN */, 'Expected ")"');
1868
- return { kind: "call", object: path, method, args };
1869
- }
1870
- return { kind: "property", path };
1714
+ if (ok) {
1715
+ return { outcome: "verified", keyId: keyid, key };
1871
1716
  }
1872
- throw new Error(`Unexpected token "${this.current().value}" at position ${this.current().position}`);
1873
- }
1874
- // Helper methods
1875
- current() {
1876
- return this.tokens[this.pos];
1717
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "bad-signature" });
1877
1718
  }
1878
- advance() {
1879
- return this.tokens[this.pos++];
1719
+ return best;
1720
+ }
1721
+ var PRECEDENCE = { none: 0, claimed: 1, impersonation: 2, verified: 3 };
1722
+ function higher(a, b) {
1723
+ return PRECEDENCE[b.outcome] >= PRECEDENCE[a.outcome] ? b : a;
1724
+ }
1725
+ function numeric(v) {
1726
+ return typeof v === "number" ? v : void 0;
1727
+ }
1728
+ function buildSignatureBase(req, m) {
1729
+ const lines = [];
1730
+ for (const c of m.components) {
1731
+ lines.push(`${serializeComponentId(c)}: ${componentValue(req, c)}`);
1880
1732
  }
1881
- check(type) {
1882
- return this.current().type === type;
1733
+ lines.push(`"@signature-params": ${m.raw.trim()}`);
1734
+ return lines.join("\n");
1735
+ }
1736
+ function serializeComponentId(c) {
1737
+ const base = `"${c.name.toLowerCase()}"`;
1738
+ return c.keyParam !== void 0 ? `${base};key="${c.keyParam}"` : base;
1739
+ }
1740
+ function componentValue(req, c) {
1741
+ const name = c.name.toLowerCase();
1742
+ switch (name) {
1743
+ case "@method":
1744
+ return req.method.toUpperCase();
1745
+ case "@authority":
1746
+ return canonicalAuthority(req.url);
1747
+ case "@scheme":
1748
+ return req.url.protocol.replace(/:$/, "").toLowerCase();
1749
+ case "@target-uri":
1750
+ return `${req.url.protocol}//${canonicalAuthority(req.url)}${req.url.pathname}${req.url.search}`;
1751
+ case "@path":
1752
+ return req.url.pathname;
1753
+ case "@query":
1754
+ return req.url.search === "" ? "?" : req.url.search;
1755
+ case "signature-agent": {
1756
+ const header = req.headers.get("signature-agent");
1757
+ if (header === null) throw new Error("signature-agent covered but absent");
1758
+ if (c.keyParam !== void 0) return dictMemberValue(header, c.keyParam);
1759
+ return header.trim().replace(/\s+/g, " ");
1760
+ }
1761
+ default: {
1762
+ if (name.startsWith("@")) throw new Error(`unsupported derived component ${name}`);
1763
+ const header = req.headers.get(name);
1764
+ if (header === null) throw new Error(`covered header ${name} absent`);
1765
+ return header.trim().replace(/\s+/g, " ");
1766
+ }
1883
1767
  }
1884
- checkAhead(type) {
1885
- return this.pos + 1 < this.tokens.length && this.tokens[this.pos + 1].type === type;
1768
+ }
1769
+ function canonicalAuthority(url) {
1770
+ const host = url.hostname.toLowerCase();
1771
+ const port = url.port;
1772
+ if (!port) return host;
1773
+ if (url.protocol === "https:" && port === "443" || url.protocol === "http:" && port === "80") {
1774
+ return host;
1886
1775
  }
1887
- match(type) {
1888
- if (this.check(type)) {
1889
- this.advance();
1890
- return true;
1776
+ return `${host}:${port}`;
1777
+ }
1778
+ function dictMemberValue(header, key) {
1779
+ const dict = parseDictionary(header);
1780
+ const found = dict.find((d) => d.key === key);
1781
+ if (!found) throw new Error(`signature-agent has no member ${key}`);
1782
+ return found.raw;
1783
+ }
1784
+ function parseSignatureInput(value) {
1785
+ return parseDictionary(value).map((d) => {
1786
+ if (!d.isList) throw new Error(`Signature-Input member ${d.key} is not an inner list`);
1787
+ const components = d.items.map((it) => {
1788
+ if (typeof it.value !== "string") throw new Error("component identifier is not a string");
1789
+ const keyParam = it.params.get("key");
1790
+ return { name: it.value, keyParam: typeof keyParam === "string" ? keyParam : void 0 };
1791
+ });
1792
+ return { label: d.key, components, params: d.params, raw: d.raw };
1793
+ });
1794
+ }
1795
+ function parseSignatureBytes(value) {
1796
+ const out = /* @__PURE__ */ new Map();
1797
+ for (const d of parseDictionary(value)) {
1798
+ if (d.isList || d.items.length !== 1 || !d.items[0].bytes) {
1799
+ throw new Error(`Signature member ${d.key} is not a byte sequence`);
1891
1800
  }
1892
- return false;
1893
- }
1894
- expect(type, message) {
1895
- if (this.check(type)) return this.advance();
1896
- throw new Error(`${message}, got "${this.current().value}" at position ${this.current().position}`);
1801
+ out.set(d.key, d.items[0].bytes);
1897
1802
  }
1898
- };
1803
+ return out;
1804
+ }
1899
1805
 
1900
- // src/rules/filter/evaluator.ts
1901
- var MAX_REGEX_LENGTH = 500;
1902
- function evaluate(node, context) {
1903
- switch (node.kind) {
1904
- case "bool":
1905
- return node.value;
1906
- case "number":
1907
- return node.value;
1908
- case "string":
1909
- return node.value;
1910
- case "array":
1911
- return node.elements.map((el) => evaluate(el, context));
1912
- case "property":
1913
- return resolveProperty(node.path, context);
1914
- case "call":
1915
- return resolveCall(node.object, node.method, node.args, context);
1916
- case "unary":
1917
- return evaluateUnary(node.op, node.operand, context);
1918
- case "binary":
1919
- return evaluateBinary(node.op, node.left, node.right, context);
1806
+ // src/agent/verifier.ts
1807
+ var DEFAULT_TTL_MS = 6 * 60 * 60 * 1e3;
1808
+ var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
1809
+ var DEFAULT_TOLERANCE_SEC = 300;
1810
+ var AgentVerifier = class {
1811
+ constructor(options = {}) {
1812
+ this.toleranceSec = options.toleranceSec ?? DEFAULT_TOLERANCE_SEC;
1813
+ this.cache = new DirectoryCache({
1814
+ directories: options.directories ?? DEFAULT_SIGNED_AGENT_DIRECTORIES,
1815
+ cacheTtlMs: options.cacheTtlMs ?? DEFAULT_TTL_MS,
1816
+ fetchTimeoutMs: options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,
1817
+ debug: options.debug ?? false,
1818
+ fetchImpl: options.fetchImpl ?? fetch
1819
+ });
1920
1820
  }
1921
- }
1922
- function resolveProperty(path, context) {
1923
- const namespace = path[0];
1924
- const prop = path.slice(1).join(".");
1925
- if (namespace === "ip") {
1926
- const e = context.enrichment;
1927
- if (!e) return void 0;
1928
- if (prop === "vpn") return e.security.vpn;
1929
- if (prop === "proxy") return e.security.proxy;
1930
- if (prop === "tor") return e.security.tor;
1931
- if (prop === "relay") return e.security.relay;
1932
- if (prop === "hosting") return e.security.hosting;
1933
- if (prop === "country") return e.location.country;
1934
- if (prop === "country_name") return e.location.country_name;
1935
- if (prop === "city") return e.location.city;
1936
- if (prop === "timezone") return e.location.timezone;
1937
- if (prop === "asn") return e.network.asn;
1938
- if (prop === "asn_org") return e.network.asn_org;
1939
- if (prop === "abuse_score") return e.reputation.abuse_score;
1940
- if (prop === "total_reports") return e.reputation.total_reports;
1941
- if (prop === "is_high_risk") return e.reputation.is_high_risk;
1942
- return void 0;
1821
+ /** Pre-fetch trusted directories so the first request verifies warm. */
1822
+ warmup() {
1823
+ this.cache.prime();
1943
1824
  }
1944
- if (namespace === "req") {
1945
- if (prop === "path") return context.path;
1946
- if (prop === "method") return context.method;
1947
- if (prop === "ip") return context.ip;
1948
- if (prop === "user_agent") return context.userAgent;
1949
- return void 0;
1825
+ /** Verify a request's Web Bot Auth signature (if any) locally. */
1826
+ async verify(request) {
1827
+ let req;
1828
+ try {
1829
+ req = normalize(request);
1830
+ } catch {
1831
+ return { status: "none" };
1832
+ }
1833
+ const result = await verifyWebBotAuth(req, this.cache.resolveKey, this.toleranceSec);
1834
+ switch (result.outcome) {
1835
+ case "verified":
1836
+ return {
1837
+ status: "verified",
1838
+ method: "signature",
1839
+ keyId: result.keyId,
1840
+ agentName: result.key?.name,
1841
+ category: result.key?.category,
1842
+ algorithm: result.key?.algorithm
1843
+ };
1844
+ case "impersonation":
1845
+ return {
1846
+ status: "impersonation",
1847
+ method: "signature",
1848
+ keyId: result.keyId,
1849
+ agentName: result.key?.name,
1850
+ category: result.key?.category,
1851
+ reason: result.reason
1852
+ };
1853
+ case "claimed":
1854
+ return { status: "claimed", keyId: result.keyId, reason: result.reason };
1855
+ default:
1856
+ return { status: "none" };
1857
+ }
1950
1858
  }
1951
- if (path.length === 1) return void 0;
1952
- return void 0;
1859
+ /** Cached-key count (diagnostics/tests). */
1860
+ get cachedKeyCount() {
1861
+ return this.cache.size;
1862
+ }
1863
+ };
1864
+ function createAgentVerifier(options = {}) {
1865
+ return new AgentVerifier(options);
1953
1866
  }
1954
- function resolveCall(object, method, args, context) {
1955
- const namespace = object[0];
1956
- if (namespace === "req" && method === "header") {
1957
- if (args.length !== 1) return void 0;
1958
- const headerName = evaluate(args[0], context);
1959
- if (typeof headerName !== "string") return void 0;
1960
- return context.headers[headerName.toLowerCase()];
1867
+ function normalize(input) {
1868
+ if (isRequest(input)) {
1869
+ return { method: input.method, url: new URL(input.url), headers: input.headers };
1961
1870
  }
1962
- return void 0;
1871
+ const headers = input.headers instanceof Headers ? input.headers : toHeaders(input.headers);
1872
+ return { method: input.method, url: new URL(input.url), headers };
1963
1873
  }
1964
- function evaluateUnary(op, operand, context) {
1965
- const val = evaluate(operand, context);
1966
- if (op === "not") {
1967
- if (val === void 0) return false;
1968
- return !val;
1874
+ function isRequest(input) {
1875
+ return typeof Request !== "undefined" && input instanceof Request && typeof input.url === "string";
1876
+ }
1877
+ function toHeaders(record) {
1878
+ const h = new Headers();
1879
+ for (const [k, v] of Object.entries(record)) {
1880
+ if (v !== void 0 && v !== null) h.set(k, String(v));
1969
1881
  }
1970
- return void 0;
1882
+ return h;
1971
1883
  }
1972
- function evaluateBinary(op, left, right, context) {
1973
- if (op === "and") {
1974
- const l2 = evaluate(left, context);
1975
- if (l2 === void 0 || l2 === false) return false;
1976
- const r2 = evaluate(right, context);
1977
- if (r2 === void 0) return false;
1978
- return !!r2;
1884
+
1885
+ // src/edge.ts
1886
+ var EDGE_CLEARANCE_HEADER = "x-wd-clearance";
1887
+ var EDGE_CLASS_HEADER = "x-wd-class";
1888
+ var EDGE_CLASSES = ["verified", "crawler", "script", "browser"];
1889
+ function absent() {
1890
+ return {
1891
+ present: false,
1892
+ isVerified: false,
1893
+ isCrawler: false,
1894
+ isScript: false,
1895
+ isBrowser: false,
1896
+ isUnattestedNonBrowser: false
1897
+ };
1898
+ }
1899
+ function normaliseClass(raw) {
1900
+ if (!raw) return void 0;
1901
+ const v = raw.trim().toLowerCase();
1902
+ return EDGE_CLASSES.includes(v) ? v : void 0;
1903
+ }
1904
+ function readEdgeVerdict(headers) {
1905
+ if (!headers) return absent();
1906
+ let clearanceRaw;
1907
+ let classRaw;
1908
+ for (const key of Object.keys(headers)) {
1909
+ const k = key.toLowerCase();
1910
+ if (k === EDGE_CLEARANCE_HEADER) clearanceRaw = headers[key];
1911
+ else if (k === EDGE_CLASS_HEADER) classRaw = headers[key];
1912
+ }
1913
+ const clearance = clearanceRaw?.trim() || void 0;
1914
+ const cls = normaliseClass(classRaw);
1915
+ if (!clearance && !cls) return absent();
1916
+ return {
1917
+ present: true,
1918
+ clearance,
1919
+ class: cls,
1920
+ isVerified: cls === "verified",
1921
+ isCrawler: cls === "crawler",
1922
+ isScript: cls === "script",
1923
+ isBrowser: cls === "browser",
1924
+ isUnattestedNonBrowser: cls === "script" || cls === "crawler"
1925
+ };
1926
+ }
1927
+
1928
+ // src/sdk.ts
1929
+ var WebDecoy = class {
1930
+ constructor(config) {
1931
+ this.violationReporter = null;
1932
+ this.ipEnrichmentClient = null;
1933
+ this._hasFilterRules = false;
1934
+ this._hasAgentRules = false;
1935
+ this.agentVerifier = null;
1936
+ const hasApiKey = !!config.apiKey;
1937
+ if (hasApiKey) {
1938
+ if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
1939
+ throw new Error(
1940
+ 'Invalid API key format. API key should start with "sk_live_" or "sk_test_".'
1941
+ );
1942
+ }
1943
+ }
1944
+ this.config = {
1945
+ apiKey: config.apiKey,
1946
+ apiUrl: config.apiUrl || "https://ingest.webdecoy.com",
1947
+ enableTLSFingerprinting: config.enableTLSFingerprinting ?? true,
1948
+ threatScoreThreshold: config.threatScoreThreshold ?? 80,
1949
+ timeout: config.timeout ?? 5e3,
1950
+ debug: config.debug ?? false,
1951
+ tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
1952
+ };
1953
+ if (hasApiKey) {
1954
+ this.client = new WebDecoyClient({
1955
+ apiKey: config.apiKey,
1956
+ apiUrl: this.config.apiUrl,
1957
+ timeout: this.config.timeout,
1958
+ debug: this.config.debug,
1959
+ tlsRejectUnauthorized: this.config.tlsRejectUnauthorized
1960
+ });
1961
+ } else {
1962
+ this.client = null;
1963
+ if (this.config.debug) {
1964
+ console.log("[WebDecoy] Running in local-only mode (no API key). Rules will still evaluate.");
1965
+ }
1966
+ }
1967
+ this.webBotAuthOptions = config.webBotAuth;
1968
+ const rules = config.rules ?? [tripwire()];
1969
+ if (rules.length > 0) {
1970
+ this.ruleEngine = new RuleEngine(rules);
1971
+ this._hasFilterRules = rules.some((r) => r.name.startsWith("filter:"));
1972
+ this._hasAgentRules = rules.some((r) => r.name === "web-bot-auth");
1973
+ if (this._hasAgentRules) {
1974
+ this.getAgentVerifier().warmup();
1975
+ }
1976
+ } else {
1977
+ this.ruleEngine = null;
1978
+ }
1979
+ if (this.client && this._hasFilterRules) {
1980
+ this.ipEnrichmentClient = new IPEnrichmentClient(this.client);
1981
+ }
1982
+ if (this.client && this.ruleEngine) {
1983
+ const reporter = new ViolationReporter(this.client, {
1984
+ debug: this.config.debug
1985
+ });
1986
+ this.setViolationReporter(reporter);
1987
+ }
1988
+ if (this.config.debug) {
1989
+ console.log("[WebDecoy] Initialized with config:", {
1990
+ apiUrl: this.config.apiUrl,
1991
+ enableTLSFingerprinting: this.config.enableTLSFingerprinting,
1992
+ threatScoreThreshold: this.config.threatScoreThreshold,
1993
+ hasApiKey,
1994
+ rulesCount: rules.length
1995
+ });
1996
+ }
1979
1997
  }
1980
- if (op === "or") {
1981
- const l2 = evaluate(left, context);
1982
- if (l2 === void 0 ? false : !!l2) return true;
1983
- const r2 = evaluate(right, context);
1984
- if (r2 === void 0) return false;
1985
- return !!r2;
1998
+ /**
1999
+ * Evaluate rules against request metadata (synchronous).
2000
+ * Returns null if no rules are configured.
2001
+ */
2002
+ evaluateRules(metadata) {
2003
+ if (!this.ruleEngine) return null;
2004
+ return this.runRules(this.buildContext(metadata));
1986
2005
  }
1987
- const l = evaluate(left, context);
1988
- const r = evaluate(right, context);
1989
- if (l === void 0 || r === void 0) return false;
1990
- switch (op) {
1991
- case "==":
1992
- return l === r;
1993
- case "!=":
1994
- return l !== r;
1995
- case ">":
1996
- return typeof l === "number" && typeof r === "number" && l > r;
1997
- case ">=":
1998
- return typeof l === "number" && typeof r === "number" && l >= r;
1999
- case "<":
2000
- return typeof l === "number" && typeof r === "number" && l < r;
2001
- case "<=":
2002
- return typeof l === "number" && typeof r === "number" && l <= r;
2003
- case "in": {
2004
- if (!Array.isArray(r)) return false;
2005
- return r.includes(l);
2006
+ /**
2007
+ * Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth
2008
+ * verification). Use this instead of evaluateRules() when filter rules or
2009
+ * webBotAuth() rules are present.
2010
+ */
2011
+ async evaluateRulesAsync(metadata) {
2012
+ if (!this.ruleEngine) return null;
2013
+ const context = await this.buildAsyncContext(metadata);
2014
+ return this.runRules(context);
2015
+ }
2016
+ /** Build the base (synchronous) rule context from request metadata. */
2017
+ buildContext(metadata) {
2018
+ return {
2019
+ ip: metadata.ip,
2020
+ path: metadata.path,
2021
+ method: metadata.method,
2022
+ userAgent: metadata.user_agent,
2023
+ headers: metadata.headers,
2024
+ timestamp: metadata.timestamp || Date.now(),
2025
+ // Parsed synchronously and unconditionally (#481): it is two header reads,
2026
+ // it needs no network, and a rule that has to check whether the edge
2027
+ // verdict was populated is a rule people will get wrong.
2028
+ edge: readEdgeVerdict(metadata.headers)
2029
+ };
2030
+ }
2031
+ /**
2032
+ * Build a rule context with async signals resolved: IP enrichment (for
2033
+ * filter rules) and the Web Bot Auth verdict (for webBotAuth() rules).
2034
+ */
2035
+ async buildAsyncContext(metadata) {
2036
+ const context = this.buildContext(metadata);
2037
+ if (this._hasFilterRules && this.ipEnrichmentClient) {
2038
+ const enrichment = await this.ipEnrichmentClient.enrich(metadata.ip);
2039
+ if (enrichment) {
2040
+ context.enrichment = enrichment;
2041
+ }
2006
2042
  }
2007
- case "not in": {
2008
- if (!Array.isArray(r)) return false;
2009
- return !r.includes(l);
2043
+ if (this._hasAgentRules) {
2044
+ context.agent = await this.computeAgentVerdict(metadata);
2010
2045
  }
2011
- case "matches": {
2012
- if (typeof l !== "string" || typeof r !== "string") return false;
2013
- if (r.length > MAX_REGEX_LENGTH) return false;
2014
- try {
2015
- return new RegExp(r).test(l);
2016
- } catch {
2017
- return false;
2018
- }
2046
+ return context;
2047
+ }
2048
+ /** Evaluate rules against a prepared context and report any violations. */
2049
+ runRules(context) {
2050
+ if (!this.ruleEngine) return null;
2051
+ const result = this.ruleEngine.evaluate(context);
2052
+ if (result.violations.length > 0 && this.violationReporter) {
2053
+ this.violationReporter.report(result.violations);
2019
2054
  }
2020
- default:
2021
- return false;
2055
+ return result;
2022
2056
  }
2023
- }
2024
-
2025
- // src/rules/filter-rule.ts
2026
- var FilterRule = class {
2027
- constructor(config) {
2028
- this.expression = config.expression;
2029
- this.action = config.action ?? "DENY";
2030
- this.dryRun = config.dryRun ?? false;
2031
- this.name = `filter:${this.expression.slice(0, 50)}`;
2032
- const parser = new Parser(config.expression);
2033
- this.ast = parser.parse();
2057
+ /** Lazily construct the shared Web Bot Auth verifier (one directory cache). */
2058
+ getAgentVerifier() {
2059
+ if (!this.agentVerifier) {
2060
+ this.agentVerifier = new AgentVerifier({
2061
+ debug: this.config.debug,
2062
+ ...this.webBotAuthOptions
2063
+ });
2064
+ }
2065
+ return this.agentVerifier;
2034
2066
  }
2035
- evaluate(context) {
2036
- const result = evaluate(this.ast, context);
2037
- if (result) {
2067
+ /**
2068
+ * Verify a request's Web Bot Auth signature locally, deriving the request
2069
+ * URL/authority from its metadata. Returns undefined when the request lacks
2070
+ * the host information needed to verify (verdict is then simply absent).
2071
+ */
2072
+ async computeAgentVerdict(metadata) {
2073
+ const input = agentInputFromMetadata(metadata);
2074
+ if (!input) return void 0;
2075
+ return this.getAgentVerifier().verify(input);
2076
+ }
2077
+ /**
2078
+ * Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag
2079
+ * "web-bot-auth"). Returns whether it is a cryptographically `verified`
2080
+ * agent, an `impersonation` of a known one, an unverifiable `claimed`
2081
+ * signature, or `none`. No network on the warm path.
2082
+ *
2083
+ * Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }`
2084
+ * object (Node).
2085
+ *
2086
+ * @example
2087
+ * ```ts
2088
+ * const verdict = await webdecoy.detectBot(request);
2089
+ * if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 });
2090
+ * if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName);
2091
+ * ```
2092
+ */
2093
+ async detectBot(request) {
2094
+ return this.getAgentVerifier().verify(request);
2095
+ }
2096
+ /**
2097
+ * Whether this SDK instance has filter rules that need async enrichment
2098
+ */
2099
+ get hasFilterRules() {
2100
+ return this._hasFilterRules;
2101
+ }
2102
+ /**
2103
+ * Whether this SDK instance has Web Bot Auth rules that need async
2104
+ * verification before evaluation.
2105
+ */
2106
+ get hasAgentRules() {
2107
+ return this._hasAgentRules;
2108
+ }
2109
+ /**
2110
+ * Protect a request by checking it against Web Decoy's bot detection
2111
+ *
2112
+ * @param metadata - Request metadata to analyze
2113
+ * @param options - Optional configuration for this specific request
2114
+ * @returns Protection result with decision and detection details
2115
+ */
2116
+ async protect(metadata, options = {}) {
2117
+ const edge = readEdgeVerdict(metadata.headers);
2118
+ const result = await this.decide(metadata, options);
2119
+ return { ...result, edge };
2120
+ }
2121
+ async decide(metadata, options = {}) {
2122
+ try {
2123
+ if (!metadata.ip) {
2124
+ throw new Error("IP address is required in request metadata");
2125
+ }
2126
+ if (!metadata.timestamp) {
2127
+ metadata.timestamp = Date.now();
2128
+ }
2129
+ let ruleResult;
2130
+ let agentVerdict;
2131
+ if (this.ruleEngine && (this._hasFilterRules || this._hasAgentRules)) {
2132
+ const context = await this.buildAsyncContext(metadata);
2133
+ agentVerdict = context.agent;
2134
+ ruleResult = this.runRules(context);
2135
+ } else {
2136
+ ruleResult = this.evaluateRules(metadata);
2137
+ }
2138
+ if (ruleResult && ruleResult.action === "DENY") {
2139
+ return {
2140
+ allowed: false,
2141
+ detection: {
2142
+ decision: "block",
2143
+ confidence: 100,
2144
+ threat_level: "HIGH",
2145
+ bot_detected: false,
2146
+ detection_id: "rule_" + Date.now(),
2147
+ rule_enforced: true
2148
+ },
2149
+ ruleResult,
2150
+ agent: agentVerdict
2151
+ };
2152
+ }
2153
+ if (ruleResult && ruleResult.action === "THROTTLE") {
2154
+ return {
2155
+ allowed: false,
2156
+ detection: {
2157
+ decision: "block",
2158
+ confidence: 100,
2159
+ threat_level: "MEDIUM",
2160
+ bot_detected: false,
2161
+ detection_id: "rule_" + Date.now(),
2162
+ rule_enforced: true
2163
+ },
2164
+ ruleResult,
2165
+ agent: agentVerdict
2166
+ };
2167
+ }
2168
+ if (!this.client) {
2169
+ return {
2170
+ allowed: true,
2171
+ detection: {
2172
+ decision: "allow",
2173
+ confidence: 0,
2174
+ threat_level: "MINIMAL",
2175
+ bot_detected: false,
2176
+ detection_id: "local_" + Date.now(),
2177
+ rule_enforced: false
2178
+ },
2179
+ ruleResult: ruleResult ?? void 0,
2180
+ agent: agentVerdict
2181
+ };
2182
+ }
2183
+ const localAnalysis = options.skipLocalAnalysis ? {
2184
+ suspicious_headers: false,
2185
+ missing_sec_ch_ua: false,
2186
+ datacenter_ip: false,
2187
+ local_score: 0,
2188
+ needs_verification: true,
2189
+ flags: ["local_analysis_skipped"]
2190
+ } : analyzeRequest(metadata);
2191
+ if (this.config.debug) {
2192
+ console.log("[WebDecoy] Local analysis result:", localAnalysis);
2193
+ }
2194
+ const detectionRequest = {
2195
+ request_metadata: metadata,
2196
+ local_analysis: localAnalysis
2197
+ };
2198
+ const shouldCallServer = localAnalysis.needs_verification || this.config.enableTLSFingerprinting && metadata.tls_info;
2199
+ if (!shouldCallServer && localAnalysis.local_score < 50) {
2200
+ return {
2201
+ allowed: true,
2202
+ detection: {
2203
+ decision: "allow",
2204
+ confidence: 100 - localAnalysis.local_score,
2205
+ threat_level: "MINIMAL",
2206
+ bot_detected: false,
2207
+ detection_id: "local_" + Date.now(),
2208
+ rule_enforced: false
2209
+ },
2210
+ ruleResult: ruleResult ?? void 0,
2211
+ agent: agentVerdict
2212
+ };
2213
+ }
2214
+ const detection = await this.client.detect(detectionRequest);
2215
+ const threshold = options.threshold ?? this.config.threatScoreThreshold;
2216
+ const allowed = detection.decision === "allow" || detection.confidence < threshold;
2217
+ if (this.config.debug) {
2218
+ console.log("[WebDecoy] Server detection result:", {
2219
+ decision: detection.decision,
2220
+ confidence: detection.confidence,
2221
+ allowed
2222
+ });
2223
+ }
2224
+ return {
2225
+ allowed,
2226
+ detection,
2227
+ ruleResult: ruleResult ?? void 0,
2228
+ agent: agentVerdict
2229
+ };
2230
+ } catch (error) {
2231
+ if (this.config.debug) {
2232
+ console.error("[WebDecoy] Protection error:", error);
2233
+ }
2038
2234
  return {
2039
- action: this.dryRun ? "ALLOW" : this.action,
2040
- rule: this.name,
2041
- reason: `Filter matched: ${this.expression}`,
2042
- metadata: {
2043
- expression: this.expression,
2044
- dryRun: this.dryRun
2045
- }
2235
+ allowed: true,
2236
+ // Fail open to avoid blocking legitimate users
2237
+ detection: {
2238
+ decision: "allow",
2239
+ confidence: 0,
2240
+ threat_level: "MINIMAL",
2241
+ bot_detected: false,
2242
+ detection_id: "error_" + Date.now(),
2243
+ rule_enforced: false
2244
+ },
2245
+ error: error instanceof Error ? error.message : "Unknown error"
2046
2246
  };
2047
2247
  }
2048
- return {
2049
- action: "ALLOW",
2050
- rule: this.name
2051
- };
2052
- }
2053
- };
2054
-
2055
- // src/rules/tripwire-rule.ts
2056
- var DEFAULT_TRIPWIRE_PATHS = [
2057
- "/.git/config",
2058
- "/.git/HEAD",
2059
- "/.env",
2060
- "/.env.local",
2061
- "/.env.production",
2062
- "/wp-config.php",
2063
- "/config.php",
2064
- "/.aws/credentials",
2065
- "/.ssh/id_rsa",
2066
- "/backup.zip",
2067
- "/backup.sql",
2068
- "/database.sql",
2069
- "/dump.sql",
2070
- "/.DS_Store",
2071
- "/phpinfo.php",
2072
- "/server-status",
2073
- "/actuator/env",
2074
- "/.vscode/sftp.json"
2075
- ];
2076
- function normalizePath(path) {
2077
- return path.split("?")[0].split("#")[0];
2078
- }
2079
- var TripwireRule = class {
2080
- constructor(config = {}) {
2081
- this.name = "tripwire";
2082
- const paths = [...config.paths ?? []];
2083
- if (config.includeDefaults ?? true) paths.push(...DEFAULT_TRIPWIRE_PATHS);
2084
- this.exact = new Set(paths);
2085
- this.prefixes = config.prefixes ?? [];
2086
- this.patterns = config.patterns ?? [];
2087
- this.action = config.action ?? "DENY";
2088
- this.dryRun = config.dryRun ?? false;
2089
2248
  }
2090
- evaluate(context) {
2091
- const path = normalizePath(context.path);
2092
- const hit = this.exact.has(path) || this.prefixes.some((prefix) => path.startsWith(prefix)) || this.patterns.some((re) => re.test(path));
2093
- if (hit) {
2249
+ /**
2250
+ * Validate the API key configuration
2251
+ * Useful for testing integration during setup
2252
+ */
2253
+ async validateConfig() {
2254
+ if (!this.client) {
2255
+ return { valid: false, error: "No API key configured" };
2256
+ }
2257
+ try {
2258
+ const isValid = await this.client.validateAPIKey();
2259
+ return { valid: isValid };
2260
+ } catch (error) {
2094
2261
  return {
2095
- action: this.dryRun ? "ALLOW" : this.action,
2096
- rule: this.name,
2097
- reason: `Tripwire hit: ${path} \u2014 hidden honeypot path, deterministic automated-intent signal`,
2098
- metadata: { path, dryRun: this.dryRun, confidence: 100 }
2262
+ valid: false,
2263
+ error: error instanceof Error ? error.message : "Unknown error"
2099
2264
  };
2100
2265
  }
2101
- return { action: "ALLOW", rule: this.name };
2102
2266
  }
2103
- };
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;
2267
+ /**
2268
+ * Attach a violation reporter for sending violations to the backend.
2269
+ * Called internally when apiKey is present and rules are configured.
2270
+ */
2271
+ setViolationReporter(reporter) {
2272
+ this.violationReporter = reporter;
2113
2273
  }
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();
2274
+ /**
2275
+ * Get the API client (for use by violation reporter, enrichment, etc.)
2276
+ */
2277
+ getClient() {
2278
+ return this.client;
2139
2279
  }
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
- };
2280
+ /**
2281
+ * Get the current configuration
2282
+ */
2283
+ getConfig() {
2284
+ return { ...this.config };
2148
2285
  }
2149
- allow() {
2150
- return { action: "ALLOW", rule: this.name };
2286
+ /**
2287
+ * Clean up resources (timers, flush pending violations)
2288
+ */
2289
+ async destroy() {
2290
+ this.ruleEngine?.destroy();
2291
+ if (this.violationReporter) {
2292
+ await this.violationReporter.destroy();
2293
+ }
2151
2294
  }
2152
2295
  };
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;
2296
+ function agentInputFromMetadata(metadata) {
2297
+ const headers = metadata.headers || {};
2298
+ const host = headers["host"] || headers[":authority"] || headers["x-forwarded-host"] || headers["Host"];
2299
+ if (!host) return null;
2300
+ const proto = headers["x-forwarded-proto"] || headers["X-Forwarded-Proto"];
2301
+ const scheme = (proto ? proto.split(",")[0].trim() : "https") || "https";
2302
+ const rawPath = metadata.path || "/";
2303
+ const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
2304
+ try {
2305
+ return {
2306
+ method: metadata.method,
2307
+ url: `${scheme}://${host}${path}`,
2308
+ headers
2309
+ };
2310
+ } catch {
2311
+ return null;
2224
2312
  }
2225
- return hash.toString(16).padStart(16, "0");
2226
- }
2227
-
2228
- // src/rules/honeytoken.ts
2229
- function honeytoken(options = {}) {
2230
- const base = (options.basePath ?? "/__wd").replace(/\/+$/, "");
2231
- const token = options.token ?? randomHex(6);
2232
- const path = `${base}/${token}`;
2233
- const text = options.text ?? ".";
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>`;
2235
- return { path, linkHtml };
2236
- }
2237
-
2238
- // src/rules/index.ts
2239
- function rateLimit(config) {
2240
- return new RateLimitRule(config);
2241
- }
2242
- function filter(config) {
2243
- return new FilterRule(config);
2244
- }
2245
- function tripwire(config = {}) {
2246
- return new TripwireRule(config);
2247
2313
  }
2248
2314
 
2249
2315
  // src/detection/weights.ts
@@ -4212,6 +4278,8 @@ function createCaptchaEndpoints(options = {}) {
4212
4278
  DEFAULT_WEIGHTS,
4213
4279
  DetectionEngine,
4214
4280
  DirectoryCache,
4281
+ EDGE_CLASS_HEADER,
4282
+ EDGE_CLEARANCE_HEADER,
4215
4283
  FilterRule,
4216
4284
  InMemoryChallengeStore,
4217
4285
  InMemoryFingerprintStore,
@@ -4234,6 +4302,7 @@ function createCaptchaEndpoints(options = {}) {
4234
4302
  isMobileUA,
4235
4303
  parseUserAgent,
4236
4304
  rateLimit,
4305
+ readEdgeVerdict,
4237
4306
  recommend,
4238
4307
  resolveSecret,
4239
4308
  tripwire,