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