@webdecoy/node 0.6.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.
Files changed (3) hide show
  1. package/dist/index.js +1716 -1717
  2. package/dist/index.mjs +1716 -1717
  3. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -342,1914 +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, " ");
748
+ advance() {
749
+ return this.tokens[this.pos++];
750
+ }
751
+ check(type) {
752
+ return this.current().type === type;
753
+ }
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;
919
761
  }
762
+ return false;
920
763
  }
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;
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
+ };
769
+
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);
928
790
  }
929
- return `${host}:${port}`;
930
791
  }
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;
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;
813
+ }
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;
820
+ }
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;
832
+ }
833
+ if (path.length === 1) return void 0;
834
+ return void 0;
936
835
  }
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
- });
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()];
843
+ }
844
+ return void 0;
947
845
  }
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`);
953
- }
954
- out.set(d.key, d.items[0].bytes);
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;
955
851
  }
956
- return out;
852
+ return void 0;
957
853
  }
958
-
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
- });
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;
973
861
  }
974
- /** Pre-fetch trusted directories so the first request verifies warm. */
975
- warmup() {
976
- this.cache.prime();
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;
977
868
  }
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" };
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);
985
888
  }
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" };
889
+ case "not in": {
890
+ if (!Array.isArray(r)) return false;
891
+ return !r.includes(l);
1010
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;
1011
904
  }
1012
- /** Cached-key count (diagnostics/tests). */
1013
- get cachedKeyCount() {
1014
- return this.cache.size;
1015
- }
1016
- };
1017
- function createAgentVerifier(options = {}) {
1018
- return new AgentVerifier(options);
1019
905
  }
1020
- function normalize(input) {
1021
- if (isRequest(input)) {
1022
- return { method: input.method, url: new URL(input.url), headers: input.headers };
906
+
907
+ // src/rules/filter-rule.ts
908
+ var FilterRule = class {
909
+ constructor(config) {
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();
1023
916
  }
1024
- const headers = input.headers instanceof Headers ? input.headers : toHeaders(input.headers);
1025
- return { method: input.method, url: new URL(input.url), headers };
1026
- }
1027
- function isRequest(input) {
1028
- return typeof Request !== "undefined" && input instanceof Request && typeof input.url === "string";
1029
- }
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));
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
+ };
929
+ }
930
+ return {
931
+ action: "ALLOW",
932
+ rule: this.name
933
+ };
1034
934
  }
1035
- return h;
1036
- }
935
+ };
1037
936
 
1038
- // src/edge.ts
1039
- var EDGE_CLEARANCE_HEADER = "x-wd-clearance";
1040
- var EDGE_CLASS_HEADER = "x-wd-class";
1041
- var EDGE_CLASSES = ["verified", "crawler", "script", "browser"];
1042
- function absent() {
1043
- return {
1044
- present: false,
1045
- isVerified: false,
1046
- isCrawler: false,
1047
- isScript: false,
1048
- isBrowser: false,
1049
- isUnattestedNonBrowser: false
1050
- };
1051
- }
1052
- function normaliseClass(raw) {
1053
- if (!raw) return void 0;
1054
- const v = raw.trim().toLowerCase();
1055
- return EDGE_CLASSES.includes(v) ? v : void 0;
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];
1056
960
  }
1057
- function readEdgeVerdict(headers) {
1058
- if (!headers) return absent();
1059
- let clearanceRaw;
1060
- let classRaw;
1061
- for (const key of Object.keys(headers)) {
1062
- const k = key.toLowerCase();
1063
- if (k === EDGE_CLEARANCE_HEADER) clearanceRaw = headers[key];
1064
- else if (k === EDGE_CLASS_HEADER) classRaw = headers[key];
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;
1065
971
  }
1066
- const clearance = clearanceRaw?.trim() || void 0;
1067
- const cls = normaliseClass(classRaw);
1068
- if (!clearance && !cls) return absent();
1069
- return {
1070
- present: true,
1071
- clearance,
1072
- class: cls,
1073
- isVerified: cls === "verified",
1074
- isCrawler: cls === "crawler",
1075
- isScript: cls === "script",
1076
- isBrowser: cls === "browser",
1077
- isUnattestedNonBrowser: cls === "script" || cls === "crawler"
1078
- };
1079
- }
1080
-
1081
- // src/sdk.ts
1082
- var WebDecoy = class {
1083
- constructor(config) {
1084
- this.violationReporter = null;
1085
- this.ipEnrichmentClient = null;
1086
- this._hasFilterRules = false;
1087
- this._hasAgentRules = false;
1088
- this.agentVerifier = null;
1089
- const hasApiKey = !!config.apiKey;
1090
- if (hasApiKey) {
1091
- if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
1092
- throw new Error(
1093
- 'Invalid API key format. API key should start with "sk_live_" or "sk_test_".'
1094
- );
1095
- }
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
+ };
1096
982
  }
1097
- this.config = {
1098
- apiKey: config.apiKey,
1099
- apiUrl: config.apiUrl || "https://ingest.webdecoy.com",
1100
- enableTLSFingerprinting: config.enableTLSFingerprinting ?? true,
1101
- threatScoreThreshold: config.threatScoreThreshold ?? 80,
1102
- timeout: config.timeout ?? 5e3,
1103
- debug: config.debug ?? false,
1104
- tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
1105
- };
1106
- if (hasApiKey) {
1107
- this.client = new WebDecoyClient({
1108
- apiKey: config.apiKey,
1109
- apiUrl: this.config.apiUrl,
1110
- timeout: this.config.timeout,
1111
- debug: this.config.debug,
1112
- tlsRejectUnauthorized: this.config.tlsRejectUnauthorized
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
1113
1005
  });
1114
- } else {
1115
- this.client = null;
1116
- if (this.config.debug) {
1117
- console.log("[WebDecoy] Running in local-only mode (no API key). Rules will still evaluate.");
1118
- }
1119
1006
  }
1120
- this.webBotAuthOptions = config.webBotAuth;
1121
- if (config.rules && config.rules.length > 0) {
1122
- this.ruleEngine = new RuleEngine(config.rules);
1123
- this._hasFilterRules = config.rules.some(
1124
- (r) => r.name.startsWith("filter:")
1125
- );
1126
- this._hasAgentRules = config.rules.some((r) => r.name === "web-bot-auth");
1127
- if (this._hasAgentRules) {
1128
- this.getAgentVerifier().warmup();
1129
- }
1130
- } else {
1131
- this.ruleEngine = null;
1132
- }
1133
- if (this.client && this._hasFilterRules) {
1134
- this.ipEnrichmentClient = new IPEnrichmentClient(this.client);
1135
- }
1136
- if (this.client && this.ruleEngine) {
1137
- const reporter = new ViolationReporter(this.client, {
1138
- 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
1139
1011
  });
1140
- this.setViolationReporter(reporter);
1141
1012
  }
1142
- if (this.config.debug) {
1143
- console.log("[WebDecoy] Initialized with config:", {
1144
- apiUrl: this.config.apiUrl,
1145
- enableTLSFingerprinting: this.config.enableTLSFingerprinting,
1146
- threatScoreThreshold: this.config.threatScoreThreshold,
1147
- hasApiKey,
1148
- 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
1149
1018
  });
1150
1019
  }
1020
+ return this.allow();
1151
1021
  }
1152
- /**
1153
- * Evaluate rules against request metadata (synchronous).
1154
- * Returns null if no rules are configured.
1155
- */
1156
- evaluateRules(metadata) {
1157
- if (!this.ruleEngine) return null;
1158
- return this.runRules(this.buildContext(metadata));
1159
- }
1160
- /**
1161
- * Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth
1162
- * verification). Use this instead of evaluateRules() when filter rules or
1163
- * webBotAuth() rules are present.
1164
- */
1165
- async evaluateRulesAsync(metadata) {
1166
- if (!this.ruleEngine) return null;
1167
- const context = await this.buildAsyncContext(metadata);
1168
- return this.runRules(context);
1169
- }
1170
- /** Build the base (synchronous) rule context from request metadata. */
1171
- buildContext(metadata) {
1022
+ act(action, verdict, detail) {
1023
+ if (action === "ALLOW") return this.allow();
1172
1024
  return {
1173
- ip: metadata.ip,
1174
- path: metadata.path,
1175
- method: metadata.method,
1176
- userAgent: metadata.user_agent,
1177
- headers: metadata.headers,
1178
- timestamp: metadata.timestamp || Date.now(),
1179
- // Parsed synchronously and unconditionally (#481): it is two header reads,
1180
- // it needs no network, and a rule that has to check whether the edge
1181
- // verdict was populated is a rule people will get wrong.
1182
- edge: readEdgeVerdict(metadata.headers)
1025
+ action: this.dryRun ? "ALLOW" : action,
1026
+ rule: this.name,
1027
+ reason: reasonFor(verdict),
1028
+ metadata: { verdict, dryRun: this.dryRun, ...detail }
1183
1029
  };
1184
1030
  }
1185
- /**
1186
- * Build a rule context with async signals resolved: IP enrichment (for
1187
- * filter rules) and the Web Bot Auth verdict (for webBotAuth() rules).
1188
- */
1189
- async buildAsyncContext(metadata) {
1190
- const context = this.buildContext(metadata);
1191
- if (this._hasFilterRules && this.ipEnrichmentClient) {
1192
- const enrichment = await this.ipEnrichmentClient.enrich(metadata.ip);
1193
- if (enrichment) {
1194
- context.enrichment = enrichment;
1195
- }
1196
- }
1197
- if (this._hasAgentRules) {
1198
- context.agent = await this.computeAgentVerdict(metadata);
1199
- }
1200
- return context;
1031
+ allow() {
1032
+ return { action: "ALLOW", rule: this.name };
1201
1033
  }
1202
- /** Evaluate rules against a prepared context and report any violations. */
1203
- runRules(context) {
1204
- if (!this.ruleEngine) return null;
1205
- const result = this.ruleEngine.evaluate(context);
1206
- if (result.violations.length > 0 && this.violationReporter) {
1207
- this.violationReporter.report(result.violations);
1208
- }
1209
- return result;
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";
1210
1045
  }
1211
- /** Lazily construct the shared Web Bot Auth verifier (one directory cache). */
1212
- getAgentVerifier() {
1213
- if (!this.agentVerifier) {
1214
- this.agentVerifier = new AgentVerifier({
1215
- debug: this.config.debug,
1216
- ...this.webBotAuthOptions
1217
- });
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;
1106
+ }
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();
1218
1143
  }
1219
- return this.agentVerifier;
1220
1144
  }
1221
1145
  /**
1222
- * Verify a request's Web Bot Auth signature locally, deriving the request
1223
- * URL/authority from its metadata. Returns undefined when the request lacks
1224
- * the host information needed to verify (verdict is then simply absent).
1146
+ * Add violations to the buffer. Auto-flushes when buffer reaches maxBufferSize.
1225
1147
  */
1226
- async computeAgentVerdict(metadata) {
1227
- const input = agentInputFromMetadata(metadata);
1228
- if (!input) return void 0;
1229
- return this.getAgentVerifier().verify(input);
1148
+ report(violations) {
1149
+ this.buffer.push(...violations);
1150
+ if (this.buffer.length >= this.maxBufferSize) {
1151
+ this.flush().catch(() => {
1152
+ });
1153
+ }
1230
1154
  }
1231
1155
  /**
1232
- * Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag
1233
- * "web-bot-auth"). Returns whether it is a cryptographically `verified`
1234
- * agent, an `impersonation` of a known one, an unverifiable `claimed`
1235
- * signature, or `none`. No network on the warm path.
1236
- *
1237
- * Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }`
1238
- * object (Node).
1239
- *
1240
- * @example
1241
- * ```ts
1242
- * const verdict = await webdecoy.detectBot(request);
1243
- * if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 });
1244
- * if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName);
1245
- * ```
1156
+ * Flush buffered violations to the backend
1246
1157
  */
1247
- async detectBot(request) {
1248
- return this.getAgentVerifier().verify(request);
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
+ }
1249
1177
  }
1250
1178
  /**
1251
- * Whether this SDK instance has filter rules that need async enrichment
1179
+ * Flush remaining events and stop the timer
1252
1180
  */
1253
- get hasFilterRules() {
1254
- return this._hasFilterRules;
1181
+ async destroy() {
1182
+ clearInterval(this.flushTimer);
1183
+ await this.flush();
1255
1184
  }
1256
- /**
1257
- * Whether this SDK instance has Web Bot Auth rules that need async
1258
- * verification before evaluation.
1259
- */
1260
- get hasAgentRules() {
1261
- return this._hasAgentRules;
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;
1262
1194
  }
1263
1195
  /**
1264
- * Protect a request by checking it against Web Decoy's bot detection
1265
- *
1266
- * @param metadata - Request metadata to analyze
1267
- * @param options - Optional configuration for this specific request
1268
- * @returns Protection result with decision and detection details
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).
1269
1199
  */
1270
- async protect(metadata, options = {}) {
1271
- const edge = readEdgeVerdict(metadata.headers);
1272
- const result = await this.decide(metadata, options);
1273
- return { ...result, edge };
1274
- }
1275
- async decide(metadata, options = {}) {
1276
- try {
1277
- if (!metadata.ip) {
1278
- throw new Error("IP address is required in request metadata");
1279
- }
1280
- if (!metadata.timestamp) {
1281
- metadata.timestamp = Date.now();
1282
- }
1283
- let ruleResult;
1284
- let agentVerdict;
1285
- if (this.ruleEngine && (this._hasFilterRules || this._hasAgentRules)) {
1286
- const context = await this.buildAsyncContext(metadata);
1287
- agentVerdict = context.agent;
1288
- ruleResult = this.runRules(context);
1289
- } else {
1290
- ruleResult = this.evaluateRules(metadata);
1291
- }
1292
- if (ruleResult && ruleResult.action === "DENY") {
1293
- return {
1294
- allowed: false,
1295
- detection: {
1296
- decision: "block",
1297
- confidence: 100,
1298
- threat_level: "HIGH",
1299
- bot_detected: false,
1300
- detection_id: "rule_" + Date.now(),
1301
- rule_enforced: true
1302
- },
1303
- ruleResult,
1304
- agent: agentVerdict
1305
- };
1306
- }
1307
- if (ruleResult && ruleResult.action === "THROTTLE") {
1308
- return {
1309
- allowed: false,
1310
- detection: {
1311
- decision: "block",
1312
- confidence: 100,
1313
- threat_level: "MEDIUM",
1314
- bot_detected: false,
1315
- detection_id: "rule_" + Date.now(),
1316
- rule_enforced: true
1317
- },
1318
- ruleResult,
1319
- agent: agentVerdict
1320
- };
1321
- }
1322
- if (!this.client) {
1323
- return {
1324
- allowed: true,
1325
- detection: {
1326
- decision: "allow",
1327
- confidence: 0,
1328
- threat_level: "MINIMAL",
1329
- bot_detected: false,
1330
- detection_id: "local_" + Date.now(),
1331
- rule_enforced: false
1332
- },
1333
- ruleResult: ruleResult ?? void 0,
1334
- agent: agentVerdict
1335
- };
1336
- }
1337
- const localAnalysis = options.skipLocalAnalysis ? {
1338
- suspicious_headers: false,
1339
- missing_sec_ch_ua: false,
1340
- datacenter_ip: false,
1341
- local_score: 0,
1342
- needs_verification: true,
1343
- flags: ["local_analysis_skipped"]
1344
- } : analyzeRequest(metadata);
1345
- if (this.config.debug) {
1346
- console.log("[WebDecoy] Local analysis result:", localAnalysis);
1347
- }
1348
- const detectionRequest = {
1349
- request_metadata: metadata,
1350
- local_analysis: localAnalysis
1351
- };
1352
- const shouldCallServer = localAnalysis.needs_verification || this.config.enableTLSFingerprinting && metadata.tls_info;
1353
- if (!shouldCallServer && localAnalysis.local_score < 50) {
1354
- return {
1355
- allowed: true,
1356
- detection: {
1357
- decision: "allow",
1358
- confidence: 100 - localAnalysis.local_score,
1359
- threat_level: "MINIMAL",
1360
- bot_detected: false,
1361
- detection_id: "local_" + Date.now(),
1362
- rule_enforced: false
1363
- },
1364
- ruleResult: ruleResult ?? void 0,
1365
- agent: agentVerdict
1366
- };
1367
- }
1368
- const detection = await this.client.detect(detectionRequest);
1369
- const threshold = options.threshold ?? this.config.threatScoreThreshold;
1370
- const allowed = detection.decision === "allow" || detection.confidence < threshold;
1371
- if (this.config.debug) {
1372
- console.log("[WebDecoy] Server detection result:", {
1373
- decision: detection.decision,
1374
- confidence: detection.confidence,
1375
- allowed
1376
- });
1377
- }
1378
- return {
1379
- allowed,
1380
- detection,
1381
- ruleResult: ruleResult ?? void 0,
1382
- agent: agentVerdict
1383
- };
1384
- } catch (error) {
1385
- if (this.config.debug) {
1386
- console.error("[WebDecoy] Protection error:", error);
1387
- }
1388
- return {
1389
- allowed: true,
1390
- // Fail open to avoid blocking legitimate users
1391
- detection: {
1392
- decision: "allow",
1393
- confidence: 0,
1394
- threat_level: "MINIMAL",
1395
- bot_detected: false,
1396
- detection_id: "error_" + Date.now(),
1397
- rule_enforced: false
1398
- },
1399
- error: error instanceof Error ? error.message : "Unknown error"
1400
- };
1200
+ async enrich(ip) {
1201
+ const cached = this.cache.get(ip);
1202
+ if (cached && cached.expiresAt > Date.now()) {
1203
+ return cached.data;
1401
1204
  }
1402
- }
1403
- /**
1404
- * Validate the API key configuration
1405
- * Useful for testing integration during setup
1406
- */
1407
- async validateConfig() {
1408
- if (!this.client) {
1409
- return { valid: false, error: "No API key configured" };
1205
+ const inflight = this.pending.get(ip);
1206
+ if (inflight) {
1207
+ return inflight;
1410
1208
  }
1209
+ const promise = this.fetchAndCache(ip);
1210
+ this.pending.set(ip, promise);
1411
1211
  try {
1412
- const isValid = await this.client.validateAPIKey();
1413
- return { valid: isValid };
1414
- } catch (error) {
1415
- return {
1416
- valid: false,
1417
- error: error instanceof Error ? error.message : "Unknown error"
1418
- };
1212
+ return await promise;
1213
+ } finally {
1214
+ this.pending.delete(ip);
1419
1215
  }
1420
1216
  }
1421
- /**
1422
- * Attach a violation reporter for sending violations to the backend.
1423
- * Called internally when apiKey is present and rules are configured.
1424
- */
1425
- setViolationReporter(reporter) {
1426
- this.violationReporter = reporter;
1427
- }
1428
- /**
1429
- * Get the API client (for use by violation reporter, enrichment, etc.)
1430
- */
1431
- getClient() {
1432
- return this.client;
1433
- }
1434
- /**
1435
- * Get the current configuration
1436
- */
1437
- getConfig() {
1438
- return { ...this.config };
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;
1439
1226
  }
1440
1227
  /**
1441
- * Clean up resources (timers, flush pending violations)
1228
+ * Clear the cache
1442
1229
  */
1443
- async destroy() {
1444
- this.ruleEngine?.destroy();
1445
- if (this.violationReporter) {
1446
- await this.violationReporter.destroy();
1447
- }
1230
+ clearCache() {
1231
+ this.cache.clear();
1448
1232
  }
1449
1233
  };
1450
- function agentInputFromMetadata(metadata) {
1451
- const headers = metadata.headers || {};
1452
- const host = headers["host"] || headers[":authority"] || headers["x-forwarded-host"] || headers["Host"];
1453
- if (!host) return null;
1454
- const proto = headers["x-forwarded-proto"] || headers["X-Forwarded-Proto"];
1455
- const scheme = (proto ? proto.split(",")[0].trim() : "https") || "https";
1456
- const rawPath = metadata.path || "/";
1457
- const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
1458
- try {
1459
- return {
1460
- method: metadata.method,
1461
- url: `${scheme}://${host}${path}`,
1462
- headers
1463
- };
1464
- } catch {
1465
- return null;
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)}`);
1466
1253
  }
1467
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
+ }
1468
1264
 
1469
- // src/rules/rate-limiter.ts
1470
- var InMemoryRateLimiter = class {
1471
- constructor() {
1472
- this.fixedWindows = /* @__PURE__ */ new Map();
1473
- this.slidingWindows = /* @__PURE__ */ new Map();
1474
- this.cleanupTimer = setInterval(() => this.cleanup(), 6e4);
1475
- if (this.cleanupTimer.unref) {
1476
- this.cleanupTimer.unref();
1477
- }
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;
1478
1284
  }
1479
- /**
1480
- * Check and increment for fixed window algorithm
1481
- * Returns the current count after increment, and the window reset time
1482
- */
1483
- checkFixedWindow(key, max, windowMs) {
1484
- const now = Date.now();
1485
- const entry = this.fixedWindows.get(key);
1486
- if (!entry || now - entry.windowStart >= windowMs) {
1487
- this.fixedWindows.set(key, { count: 1, windowStart: now });
1488
- return { allowed: true, current: 1, resetAt: now + windowMs };
1489
- }
1490
- entry.count++;
1491
- const resetAt = entry.windowStart + windowMs;
1492
- if (entry.count > max) {
1493
- return { allowed: false, current: entry.count, resetAt };
1494
- }
1495
- return { allowed: true, current: entry.count, resetAt };
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();
1496
1288
  }
1497
- /**
1498
- * Check and increment for sliding window algorithm
1499
- * Returns the current count after adding the new timestamp
1500
- */
1501
- checkSlidingWindow(key, max, windowMs) {
1289
+ /** Number of keys currently cached (diagnostics/tests). */
1290
+ get size() {
1291
+ return this.keys.size;
1292
+ }
1293
+ async ensureFresh() {
1502
1294
  const now = Date.now();
1503
- const cutoff = now - windowMs;
1504
- let timestamps = this.slidingWindows.get(key);
1505
- if (!timestamps) {
1506
- timestamps = [];
1507
- this.slidingWindows.set(key, timestamps);
1295
+ const stale = now - this.refreshedAt > this.opts.cacheTtlMs;
1296
+ if (this.keys.size > 0) {
1297
+ if (stale) void this.refresh();
1298
+ return;
1508
1299
  }
1509
- while (timestamps.length > 0 && timestamps[0] <= cutoff) {
1510
- timestamps.shift();
1300
+ if (now < this.nextColdRetryAt) return;
1301
+ await this.refresh();
1302
+ }
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;
1310
+ }
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);
1511
1321
  }
1512
- timestamps.push(now);
1513
- const resetAt = timestamps.length > 0 ? timestamps[0] + windowMs : now + windowMs;
1514
- if (timestamps.length > max) {
1515
- 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");
1516
1330
  }
1517
- return { allowed: true, current: timestamps.length, resetAt };
1518
1331
  }
1519
- /**
1520
- * Clean up expired entries from both maps
1521
- */
1522
- cleanup() {
1523
- const now = Date.now();
1524
- for (const [key, entry] of this.fixedWindows) {
1525
- if (now - entry.windowStart > 3e5) {
1526
- 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;
1527
1347
  }
1528
- }
1529
- for (const [key, timestamps] of this.slidingWindows) {
1530
- if (timestamps.length === 0) {
1531
- this.slidingWindows.delete(key);
1532
- 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;
1533
1352
  }
1534
- const latest = timestamps[timestamps.length - 1];
1535
- if (now - latest > 3e5) {
1536
- 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);
1537
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);
1538
1365
  }
1539
1366
  }
1540
- /**
1541
- * Release resources
1542
- */
1543
- destroy() {
1544
- clearInterval(this.cleanupTimer);
1545
- this.fixedWindows.clear();
1546
- this.slidingWindows.clear();
1367
+ debug(msg) {
1368
+ if (this.opts.debug) console.log(`[WebDecoy][web-bot-auth] ${msg}`);
1547
1369
  }
1548
1370
  };
1549
-
1550
- // src/rules/rate-limit-rule.ts
1551
- var RateLimitRule = class {
1552
- constructor(config) {
1553
- this.name = `rate-limit:${config.max}/${config.window}s`;
1554
- this.limiter = new InMemoryRateLimiter();
1555
- this.config = {
1556
- max: config.max,
1557
- window: config.window,
1558
- algorithm: config.algorithm ?? "fixed",
1559
- keyBy: config.keyBy,
1560
- action: config.action ?? "THROTTLE",
1561
- dryRun: config.dryRun ?? false
1562
- };
1563
- }
1564
- evaluate(context) {
1565
- const key = this.config.keyBy ? this.config.keyBy(context) : context.ip;
1566
- const windowMs = this.config.window * 1e3;
1567
- const result = this.config.algorithm === "sliding" ? this.limiter.checkSlidingWindow(key, this.config.max, windowMs) : this.limiter.checkFixedWindow(key, this.config.max, windowMs);
1568
- if (!result.allowed) {
1569
- const retryAfter = Math.ceil((result.resetAt - Date.now()) / 1e3);
1570
- return {
1571
- action: this.config.dryRun ? "ALLOW" : this.config.action,
1572
- rule: this.name,
1573
- reason: `Rate limit exceeded: ${result.current}/${this.config.max} requests in ${this.config.window}s window`,
1574
- metadata: {
1575
- current: result.current,
1576
- max: this.config.max,
1577
- window: this.config.window,
1578
- retryAfter: Math.max(retryAfter, 1),
1579
- dryRun: this.config.dryRun
1580
- }
1581
- };
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;
1582
1406
  }
1407
+ const thumbprint = await jwkThumbprint(jwk);
1583
1408
  return {
1584
- action: "ALLOW",
1585
- rule: this.name,
1586
- metadata: {
1587
- current: result.current,
1588
- max: this.config.max,
1589
- 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)
1590
1418
  }
1591
1419
  };
1420
+ } catch {
1421
+ return null;
1592
1422
  }
1593
- destroy() {
1594
- this.limiter.destroy();
1595
- }
1596
- };
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
+ }
1597
1428
 
1598
- // src/rules/filter/tokenizer.ts
1599
- var KEYWORDS = {
1600
- and: "AND" /* AND */,
1601
- or: "OR" /* OR */,
1602
- not: "NOT" /* NOT */,
1603
- in: "IN" /* IN */,
1604
- matches: "MATCHES" /* MATCHES */,
1605
- true: "BOOL" /* BOOL */,
1606
- false: "BOOL" /* BOOL */
1607
- };
1608
- var Tokenizer = class {
1609
- constructor(source) {
1610
- this.pos = 0;
1611
- this.tokens = [];
1612
- 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;
1613
1434
  }
1614
- tokenize() {
1615
- while (this.pos < this.source.length) {
1616
- this.skipWhitespace();
1617
- if (this.pos >= this.source.length) break;
1618
- const ch = this.source[this.pos];
1619
- if (ch === ".") {
1620
- this.tokens.push({ type: "DOT" /* DOT */, value: ".", position: this.pos });
1621
- this.pos++;
1622
- continue;
1623
- }
1624
- if (ch === "(") {
1625
- this.tokens.push({ type: "LPAREN" /* LPAREN */, value: "(", position: this.pos });
1626
- this.pos++;
1627
- continue;
1628
- }
1629
- if (ch === ")") {
1630
- this.tokens.push({ type: "RPAREN" /* RPAREN */, value: ")", position: this.pos });
1631
- this.pos++;
1632
- continue;
1633
- }
1634
- if (ch === "[") {
1635
- this.tokens.push({ type: "LBRACKET" /* LBRACKET */, value: "[", position: this.pos });
1636
- this.pos++;
1637
- continue;
1638
- }
1639
- if (ch === "]") {
1640
- this.tokens.push({ type: "RBRACKET" /* RBRACKET */, value: "]", position: this.pos });
1641
- this.pos++;
1642
- continue;
1643
- }
1644
- if (ch === ",") {
1645
- this.tokens.push({ type: "COMMA" /* COMMA */, value: ",", position: this.pos });
1646
- this.pos++;
1647
- continue;
1648
- }
1649
- if (ch === "=" && this.peek(1) === "=") {
1650
- this.tokens.push({ type: "EQ" /* EQ */, value: "==", position: this.pos });
1651
- this.pos += 2;
1652
- continue;
1653
- }
1654
- if (ch === "!" && this.peek(1) === "=") {
1655
- this.tokens.push({ type: "NEQ" /* NEQ */, value: "!=", position: this.pos });
1656
- this.pos += 2;
1657
- continue;
1658
- }
1659
- if (ch === ">" && this.peek(1) === "=") {
1660
- this.tokens.push({ type: "GTE" /* GTE */, value: ">=", position: this.pos });
1661
- this.pos += 2;
1662
- continue;
1663
- }
1664
- if (ch === "<" && this.peek(1) === "=") {
1665
- this.tokens.push({ type: "LTE" /* LTE */, value: "<=", position: this.pos });
1666
- this.pos += 2;
1667
- continue;
1668
- }
1669
- if (ch === ">") {
1670
- this.tokens.push({ type: "GT" /* GT */, value: ">", position: this.pos });
1671
- this.pos++;
1672
- continue;
1673
- }
1674
- if (ch === "<") {
1675
- this.tokens.push({ type: "LT" /* LT */, value: "<", position: this.pos });
1676
- this.pos++;
1677
- continue;
1678
- }
1679
- if (ch === '"' || ch === "'") {
1680
- this.readString(ch);
1681
- continue;
1682
- }
1683
- if (this.isDigit(ch) || ch === "-" && this.isDigit(this.peek(1))) {
1684
- this.readNumber();
1685
- continue;
1686
- }
1687
- if (this.isIdentStart(ch)) {
1688
- this.readIdent();
1689
- continue;
1690
- }
1691
- throw new Error(`Unexpected character '${ch}' at position ${this.pos}`);
1692
- }
1693
- this.tokens.push({ type: "EOF" /* EOF */, value: "", position: this.pos });
1694
- return this.tokens;
1435
+ eof() {
1436
+ return this.i >= this.s.length;
1695
1437
  }
1696
- peek(offset) {
1697
- const idx = this.pos + offset;
1698
- return idx < this.source.length ? this.source[idx] : "";
1438
+ peek() {
1439
+ return this.s[this.i];
1699
1440
  }
1700
- skipWhitespace() {
1701
- while (this.pos < this.source.length && /\s/.test(this.source[this.pos])) {
1702
- this.pos++;
1703
- }
1441
+ skipSP() {
1442
+ while (!this.eof() && (this.peek() === " " || this.peek() === " ")) this.i++;
1704
1443
  }
1705
- readString(quote) {
1706
- const start = this.pos;
1707
- this.pos++;
1708
- let value = "";
1709
- while (this.pos < this.source.length && this.source[this.pos] !== quote) {
1710
- if (this.source[this.pos] === "\\") {
1711
- 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;
1712
1461
  }
1713
- value += this.source[this.pos];
1714
- this.pos++;
1715
- }
1716
- if (this.pos >= this.source.length) {
1717
- 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";
1718
1467
  }
1719
- this.pos++;
1720
- 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");
1721
1475
  }
1722
- readNumber() {
1723
- const start = this.pos;
1724
- if (this.source[this.pos] === "-") this.pos++;
1725
- while (this.pos < this.source.length && this.isDigit(this.source[this.pos])) {
1726
- this.pos++;
1727
- }
1728
- if (this.pos < this.source.length && this.source[this.pos] === ".") {
1729
- this.pos++;
1730
- while (this.pos < this.source.length && this.isDigit(this.source[this.pos])) {
1731
- this.pos++;
1732
- }
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;
1733
1486
  }
1734
- 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}`);
1735
1491
  }
1736
- readIdent() {
1737
- const start = this.pos;
1738
- while (this.pos < this.source.length && this.isIdentPart(this.source[this.pos])) {
1739
- this.pos++;
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;
1740
1509
  }
1741
- const value = this.source.slice(start, this.pos);
1742
- const keyword = KEYWORDS[value.toLowerCase()];
1743
- if (keyword) {
1744
- this.tokens.push({ type: keyword, value: value.toLowerCase(), position: start });
1510
+ params.set(key, val);
1511
+ }
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");
1531
+ }
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;
1745
1546
  } else {
1746
- this.tokens.push({ type: "IDENT" /* IDENT */, value, position: start });
1547
+ const code = c.charCodeAt(0);
1548
+ if (code < 32 || code > 126) throw new Error("sfv: bad char in string");
1549
+ out += c;
1747
1550
  }
1748
1551
  }
1749
- isDigit(ch) {
1750
- return ch >= "0" && ch <= "9";
1751
- }
1752
- isIdentStart(ch) {
1753
- return /[a-zA-Z_]/.test(ch);
1754
- }
1755
- isIdentPart(ch) {
1756
- 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++;
1757
1570
  }
1758
- };
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
+ }
1759
1585
 
1760
- // src/rules/filter/parser.ts
1761
- var Parser = class {
1762
- constructor(source) {
1763
- this.pos = 0;
1764
- this.tokens = new Tokenizer(source).tokenize();
1765
- }
1766
- parse() {
1767
- const ast = this.orExpr();
1768
- this.expect("EOF" /* EOF */, "Expected end of expression");
1769
- return ast;
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" };
1770
1601
  }
1771
- orExpr() {
1772
- let left = this.andExpr();
1773
- while (this.match("OR" /* OR */)) {
1774
- const right = this.andExpr();
1775
- left = { kind: "binary", op: "or", left, right };
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;
1776
1616
  }
1777
- return left;
1778
- }
1779
- andExpr() {
1780
- let left = this.unary();
1781
- while (this.match("AND" /* AND */)) {
1782
- const right = this.unary();
1783
- left = { kind: "binary", op: "and", left, right };
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;
1784
1622
  }
1785
- return left;
1786
- }
1787
- unary() {
1788
- if (this.match("NOT" /* NOT */)) {
1789
- if (this.check("IN" /* IN */)) {
1790
- this.pos--;
1791
- return this.comparison();
1792
- }
1793
- const operand = this.unary();
1794
- return { kind: "unary", op: "not", operand };
1623
+ if (created !== void 0 && now + toleranceSec < created) {
1624
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "not-yet-valid" });
1625
+ continue;
1795
1626
  }
1796
- return this.comparison();
1797
- }
1798
- comparison() {
1799
- let left = this.primary();
1800
- if (this.match("EQ" /* EQ */)) return { kind: "binary", op: "==", left, right: this.primary() };
1801
- if (this.match("NEQ" /* NEQ */)) return { kind: "binary", op: "!=", left, right: this.primary() };
1802
- if (this.match("GT" /* GT */)) return { kind: "binary", op: ">", left, right: this.primary() };
1803
- if (this.match("GTE" /* GTE */)) return { kind: "binary", op: ">=", left, right: this.primary() };
1804
- if (this.match("LT" /* LT */)) return { kind: "binary", op: "<", left, right: this.primary() };
1805
- if (this.match("LTE" /* LTE */)) return { kind: "binary", op: "<=", left, right: this.primary() };
1806
- if (this.match("IN" /* IN */)) return { kind: "binary", op: "in", left, right: this.primary() };
1807
- if (this.match("MATCHES" /* MATCHES */)) return { kind: "binary", op: "matches", left, right: this.primary() };
1808
- if (this.check("NOT" /* NOT */) && this.checkAhead("IN" /* IN */)) {
1809
- this.advance();
1810
- this.advance();
1811
- return { kind: "binary", op: "not in", left, right: this.primary() };
1627
+ if (key.exp !== void 0 && now > key.exp + toleranceSec) {
1628
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-expired" });
1629
+ continue;
1812
1630
  }
1813
- return left;
1814
- }
1815
- primary() {
1816
- if (this.check("BOOL" /* BOOL */)) {
1817
- const token = this.advance();
1818
- return { kind: "bool", value: token.value === "true" };
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;
1819
1634
  }
1820
- if (this.check("NUMBER" /* NUMBER */)) {
1821
- const token = this.advance();
1822
- return { kind: "number", value: parseFloat(token.value) };
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;
1823
1641
  }
1824
- if (this.check("STRING" /* STRING */)) {
1825
- const token = this.advance();
1826
- return { kind: "string", value: token.value };
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;
1827
1652
  }
1828
- if (this.match("LBRACKET" /* LBRACKET */)) {
1829
- const elements = [];
1830
- if (!this.check("RBRACKET" /* RBRACKET */)) {
1831
- elements.push(this.primary());
1832
- while (this.match("COMMA" /* COMMA */)) {
1833
- elements.push(this.primary());
1834
- }
1835
- }
1836
- this.expect("RBRACKET" /* RBRACKET */, 'Expected "]"');
1837
- return { kind: "array", elements };
1653
+ if (ok) {
1654
+ return { outcome: "verified", keyId: keyid, key };
1838
1655
  }
1839
- if (this.match("LPAREN" /* LPAREN */)) {
1840
- const expr = this.orExpr();
1841
- this.expect("RPAREN" /* RPAREN */, 'Expected ")"');
1842
- return expr;
1656
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "bad-signature" });
1657
+ }
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)}`);
1671
+ }
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, " ");
1843
1699
  }
1844
- if (this.check("IDENT" /* IDENT */)) {
1845
- const path = [this.advance().value];
1846
- while (this.match("DOT" /* DOT */)) {
1847
- if (!this.check("IDENT" /* IDENT */)) {
1848
- throw new Error(`Expected identifier after "." at position ${this.current().position}`);
1849
- }
1850
- path.push(this.advance().value);
1851
- }
1852
- if (this.match("LPAREN" /* LPAREN */)) {
1853
- const method = path.pop();
1854
- const args = [];
1855
- if (!this.check("RPAREN" /* RPAREN */)) {
1856
- args.push(this.primary());
1857
- while (this.match("COMMA" /* COMMA */)) {
1858
- args.push(this.primary());
1859
- }
1860
- }
1861
- this.expect("RPAREN" /* RPAREN */, 'Expected ")"');
1862
- return { kind: "call", object: path, method, args };
1863
- }
1864
- return { kind: "property", path };
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, " ");
1865
1705
  }
1866
- throw new Error(`Unexpected token "${this.current().value}" at position ${this.current().position}`);
1867
- }
1868
- // Helper methods
1869
- current() {
1870
- return this.tokens[this.pos];
1871
1706
  }
1872
- advance() {
1873
- return this.tokens[this.pos++];
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;
1874
1714
  }
1875
- check(type) {
1876
- return this.current().type === type;
1877
- }
1878
- checkAhead(type) {
1879
- return this.pos + 1 < this.tokens.length && this.tokens[this.pos + 1].type === type;
1880
- }
1881
- match(type) {
1882
- if (this.check(type)) {
1883
- this.advance();
1884
- 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`);
1885
1739
  }
1886
- return false;
1887
- }
1888
- expect(type, message) {
1889
- if (this.check(type)) return this.advance();
1890
- throw new Error(`${message}, got "${this.current().value}" at position ${this.current().position}`);
1740
+ out.set(d.key, d.items[0].bytes);
1891
1741
  }
1892
- };
1742
+ return out;
1743
+ }
1893
1744
 
1894
- // src/rules/filter/evaluator.ts
1895
- var MAX_REGEX_LENGTH = 500;
1896
- function evaluate(node, context) {
1897
- switch (node.kind) {
1898
- case "bool":
1899
- return node.value;
1900
- case "number":
1901
- return node.value;
1902
- case "string":
1903
- return node.value;
1904
- case "array":
1905
- return node.elements.map((el) => evaluate(el, context));
1906
- case "property":
1907
- return resolveProperty(node.path, context);
1908
- case "call":
1909
- return resolveCall(node.object, node.method, node.args, context);
1910
- case "unary":
1911
- return evaluateUnary(node.op, node.operand, context);
1912
- case "binary":
1913
- 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
+ });
1914
1759
  }
1915
- }
1916
- function resolveProperty(path, context) {
1917
- const namespace = path[0];
1918
- const prop = path.slice(1).join(".");
1919
- if (namespace === "ip") {
1920
- const e = context.enrichment;
1921
- if (!e) return void 0;
1922
- if (prop === "vpn") return e.security.vpn;
1923
- if (prop === "proxy") return e.security.proxy;
1924
- if (prop === "tor") return e.security.tor;
1925
- if (prop === "relay") return e.security.relay;
1926
- if (prop === "hosting") return e.security.hosting;
1927
- if (prop === "country") return e.location.country;
1928
- if (prop === "country_name") return e.location.country_name;
1929
- if (prop === "city") return e.location.city;
1930
- if (prop === "timezone") return e.location.timezone;
1931
- if (prop === "asn") return e.network.asn;
1932
- if (prop === "asn_org") return e.network.asn_org;
1933
- if (prop === "abuse_score") return e.reputation.abuse_score;
1934
- if (prop === "total_reports") return e.reputation.total_reports;
1935
- if (prop === "is_high_risk") return e.reputation.is_high_risk;
1936
- return void 0;
1760
+ /** Pre-fetch trusted directories so the first request verifies warm. */
1761
+ warmup() {
1762
+ this.cache.prime();
1937
1763
  }
1938
- if (namespace === "req") {
1939
- if (prop === "path") return context.path;
1940
- if (prop === "method") return context.method;
1941
- if (prop === "ip") return context.ip;
1942
- if (prop === "user_agent") return context.userAgent;
1943
- 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
+ }
1944
1797
  }
1945
- if (namespace === "edge") {
1946
- const e = context.edge;
1947
- if (!e) return void 0;
1948
- if (prop === "present") return e.present;
1949
- if (prop === "clearance") return e.clearance;
1950
- if (prop === "class") return e.class;
1951
- if (prop === "verified") return e.isVerified;
1952
- if (prop === "crawler") return e.isCrawler;
1953
- if (prop === "script") return e.isScript;
1954
- if (prop === "browser") return e.isBrowser;
1955
- return void 0;
1798
+ /** Cached-key count (diagnostics/tests). */
1799
+ get cachedKeyCount() {
1800
+ return this.cache.size;
1956
1801
  }
1957
- if (path.length === 1) return void 0;
1958
- return void 0;
1802
+ };
1803
+ function createAgentVerifier(options = {}) {
1804
+ return new AgentVerifier(options);
1959
1805
  }
1960
- function resolveCall(object, method, args, context) {
1961
- const namespace = object[0];
1962
- if (namespace === "req" && method === "header") {
1963
- if (args.length !== 1) return void 0;
1964
- const headerName = evaluate(args[0], context);
1965
- if (typeof headerName !== "string") return void 0;
1966
- 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 };
1967
1809
  }
1968
- 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 };
1969
1812
  }
1970
- function evaluateUnary(op, operand, context) {
1971
- const val = evaluate(operand, context);
1972
- if (op === "not") {
1973
- if (val === void 0) return false;
1974
- return !val;
1975
- }
1976
- return void 0;
1813
+ function isRequest(input) {
1814
+ return typeof Request !== "undefined" && input instanceof Request && typeof input.url === "string";
1977
1815
  }
1978
- function evaluateBinary(op, left, right, context) {
1979
- if (op === "and") {
1980
- const l2 = evaluate(left, context);
1981
- if (l2 === void 0 || l2 === false) return false;
1982
- const r2 = evaluate(right, context);
1983
- if (r2 === void 0) return false;
1984
- return !!r2;
1985
- }
1986
- if (op === "or") {
1987
- const l2 = evaluate(left, context);
1988
- if (l2 === void 0 ? false : !!l2) return true;
1989
- const r2 = evaluate(right, context);
1990
- if (r2 === void 0) return false;
1991
- return !!r2;
1992
- }
1993
- const l = evaluate(left, context);
1994
- const r = evaluate(right, context);
1995
- if (l === void 0 || r === void 0) return false;
1996
- switch (op) {
1997
- case "==":
1998
- return l === r;
1999
- case "!=":
2000
- return l !== r;
2001
- case ">":
2002
- return typeof l === "number" && typeof r === "number" && l > r;
2003
- case ">=":
2004
- return typeof l === "number" && typeof r === "number" && l >= r;
2005
- case "<":
2006
- return typeof l === "number" && typeof r === "number" && l < r;
2007
- case "<=":
2008
- return typeof l === "number" && typeof r === "number" && l <= r;
2009
- case "in": {
2010
- if (!Array.isArray(r)) return false;
2011
- return r.includes(l);
2012
- }
2013
- case "not in": {
2014
- if (!Array.isArray(r)) return false;
2015
- return !r.includes(l);
2016
- }
2017
- case "matches": {
2018
- if (typeof l !== "string" || typeof r !== "string") return false;
2019
- if (r.length > MAX_REGEX_LENGTH) return false;
2020
- try {
2021
- return new RegExp(r).test(l);
2022
- } catch {
2023
- return false;
2024
- }
2025
- }
2026
- default:
2027
- return false;
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));
2028
1820
  }
1821
+ return h;
2029
1822
  }
2030
1823
 
2031
- // src/rules/filter-rule.ts
2032
- var FilterRule = class {
2033
- constructor(config) {
2034
- this.expression = config.expression;
2035
- this.action = config.action ?? "DENY";
2036
- this.dryRun = config.dryRun ?? false;
2037
- this.name = `filter:${this.expression.slice(0, 50)}`;
2038
- const parser = new Parser(config.expression);
2039
- this.ast = parser.parse();
2040
- }
2041
- evaluate(context) {
2042
- const result = evaluate(this.ast, context);
2043
- if (result) {
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
+ }
1936
+ }
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));
1944
+ }
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
+ }
1981
+ }
1982
+ if (this._hasAgentRules) {
1983
+ context.agent = await this.computeAgentVerdict(metadata);
1984
+ }
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);
1993
+ }
1994
+ return result;
1995
+ }
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;
2005
+ }
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
+ }
2044
2173
  return {
2045
- action: this.dryRun ? "ALLOW" : this.action,
2046
- rule: this.name,
2047
- reason: `Filter matched: ${this.expression}`,
2048
- metadata: {
2049
- expression: this.expression,
2050
- dryRun: this.dryRun
2051
- }
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"
2052
2185
  };
2053
2186
  }
2054
- return {
2055
- action: "ALLOW",
2056
- rule: this.name
2057
- };
2058
- }
2059
- };
2060
-
2061
- // src/rules/tripwire-rule.ts
2062
- var DEFAULT_TRIPWIRE_PATHS = [
2063
- "/.git/config",
2064
- "/.git/HEAD",
2065
- "/.env",
2066
- "/.env.local",
2067
- "/.env.production",
2068
- "/wp-config.php",
2069
- "/config.php",
2070
- "/.aws/credentials",
2071
- "/.ssh/id_rsa",
2072
- "/backup.zip",
2073
- "/backup.sql",
2074
- "/database.sql",
2075
- "/dump.sql",
2076
- "/.DS_Store",
2077
- "/phpinfo.php",
2078
- "/server-status",
2079
- "/actuator/env",
2080
- "/.vscode/sftp.json"
2081
- ];
2082
- function normalizePath(path) {
2083
- return path.split("?")[0].split("#")[0];
2084
- }
2085
- var TripwireRule = class {
2086
- constructor(config = {}) {
2087
- this.name = "tripwire";
2088
- const paths = [...config.paths ?? []];
2089
- if (config.includeDefaults ?? true) paths.push(...DEFAULT_TRIPWIRE_PATHS);
2090
- this.exact = new Set(paths);
2091
- this.prefixes = config.prefixes ?? [];
2092
- this.patterns = config.patterns ?? [];
2093
- this.action = config.action ?? "DENY";
2094
- this.dryRun = config.dryRun ?? false;
2095
2187
  }
2096
- evaluate(context) {
2097
- const path = normalizePath(context.path);
2098
- const hit = this.exact.has(path) || this.prefixes.some((prefix) => path.startsWith(prefix)) || this.patterns.some((re) => re.test(path));
2099
- 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) {
2100
2200
  return {
2101
- action: this.dryRun ? "ALLOW" : this.action,
2102
- rule: this.name,
2103
- reason: `Tripwire hit: ${path} \u2014 hidden honeypot path, deterministic automated-intent signal`,
2104
- metadata: { path, dryRun: this.dryRun, confidence: 100 }
2201
+ valid: false,
2202
+ error: error instanceof Error ? error.message : "Unknown error"
2105
2203
  };
2106
2204
  }
2107
- return { action: "ALLOW", rule: this.name };
2108
2205
  }
2109
- };
2110
-
2111
- // src/rules/web-bot-auth-rule.ts
2112
- var WebBotAuthRule = class {
2113
- constructor(config = {}) {
2114
- this.name = "web-bot-auth";
2115
- this.onImpersonation = config.onImpersonation ?? "DENY";
2116
- this.onClaimed = config.onClaimed ?? "ALLOW";
2117
- this.allowCategories = config.allowCategories ? new Set(config.allowCategories) : void 0;
2118
- 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;
2119
2212
  }
2120
- evaluate(context) {
2121
- const verdict = context.agent;
2122
- if (!verdict || verdict.status === "none") return this.allow();
2123
- if (verdict.status === "impersonation") {
2124
- return this.act(this.onImpersonation, "agent_impersonation", {
2125
- agentName: verdict.agentName,
2126
- category: verdict.category,
2127
- keyId: verdict.keyId,
2128
- detail: verdict.reason
2129
- });
2130
- }
2131
- if (verdict.status === "claimed") {
2132
- return this.act(this.onClaimed, "agent_unverifiable", {
2133
- keyId: verdict.keyId,
2134
- detail: verdict.reason
2135
- });
2136
- }
2137
- if (this.allowCategories && verdict.category && !this.allowCategories.has(verdict.category)) {
2138
- return this.act(this.onClaimed, "agent_category_not_allowed", {
2139
- agentName: verdict.agentName,
2140
- category: verdict.category,
2141
- keyId: verdict.keyId
2142
- });
2143
- }
2144
- return this.allow();
2213
+ /**
2214
+ * Get the API client (for use by violation reporter, enrichment, etc.)
2215
+ */
2216
+ getClient() {
2217
+ return this.client;
2145
2218
  }
2146
- act(action, verdict, detail) {
2147
- if (action === "ALLOW") return this.allow();
2148
- return {
2149
- action: this.dryRun ? "ALLOW" : action,
2150
- rule: this.name,
2151
- reason: reasonFor(verdict),
2152
- metadata: { verdict, dryRun: this.dryRun, ...detail }
2153
- };
2219
+ /**
2220
+ * Get the current configuration
2221
+ */
2222
+ getConfig() {
2223
+ return { ...this.config };
2154
2224
  }
2155
- allow() {
2156
- 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
+ }
2157
2233
  }
2158
2234
  };
2159
- function reasonFor(verdict) {
2160
- switch (verdict) {
2161
- case "agent_impersonation":
2162
- return "Web Bot Auth signature failed verification (agent impersonation)";
2163
- case "agent_unverifiable":
2164
- return "Web Bot Auth signature could not be verified";
2165
- case "agent_category_not_allowed":
2166
- return "Verified agent category is not allowed";
2167
- default:
2168
- return "Web Bot Auth rule triggered";
2169
- }
2170
- }
2171
- function webBotAuth(config = {}) {
2172
- return new WebBotAuthRule(config);
2173
- }
2174
-
2175
- // src/webcrypto.ts
2176
- var encoder3 = new TextEncoder();
2177
- function toHex(bytes) {
2178
- let hex = "";
2179
- for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
2180
- return hex;
2181
- }
2182
- async function sha256Hex(data) {
2183
- const digest2 = await crypto.subtle.digest("SHA-256", encoder3.encode(data));
2184
- return toHex(new Uint8Array(digest2));
2185
- }
2186
- async function hmacSha256Hex(secret, data) {
2187
- const key = await crypto.subtle.importKey(
2188
- "raw",
2189
- encoder3.encode(secret),
2190
- { name: "HMAC", hash: "SHA-256" },
2191
- false,
2192
- ["sign"]
2193
- );
2194
- const sig = await crypto.subtle.sign("HMAC", key, encoder3.encode(data));
2195
- return toHex(new Uint8Array(sig));
2196
- }
2197
- function randomHex(bytes) {
2198
- const buf = new Uint8Array(bytes);
2199
- crypto.getRandomValues(buf);
2200
- return toHex(buf);
2201
- }
2202
- function timingSafeEqualStr(a, b) {
2203
- if (a.length !== b.length) return false;
2204
- let diff = 0;
2205
- for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
2206
- return diff === 0;
2207
- }
2208
- function base64urlEncode(data) {
2209
- const bytes = encoder3.encode(data);
2210
- let binary = "";
2211
- for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
2212
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2213
- }
2214
- function base64urlDecode(data) {
2215
- const b64 = data.replace(/-/g, "+").replace(/_/g, "/");
2216
- const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
2217
- const binary = atob(padded);
2218
- const bytes = new Uint8Array(binary.length);
2219
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
2220
- return new TextDecoder().decode(bytes);
2221
- }
2222
- function fnv1a64Hex(data) {
2223
- const PRIME = 0x100000001b3n;
2224
- const MASK = 0xffffffffffffffffn;
2225
- let hash = 0xcbf29ce484222325n;
2226
- const bytes = encoder3.encode(data);
2227
- for (let i = 0; i < bytes.length; i++) {
2228
- hash ^= BigInt(bytes[i]);
2229
- 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;
2230
2251
  }
2231
- return hash.toString(16).padStart(16, "0");
2232
- }
2233
-
2234
- // src/rules/honeytoken.ts
2235
- function honeytoken(options = {}) {
2236
- const base = (options.basePath ?? "/__wd").replace(/\/+$/, "");
2237
- const token = options.token ?? randomHex(6);
2238
- const path = `${base}/${token}`;
2239
- const text = options.text ?? ".";
2240
- 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>`;
2241
- return { path, linkHtml };
2242
- }
2243
-
2244
- // src/rules/index.ts
2245
- function rateLimit(config) {
2246
- return new RateLimitRule(config);
2247
- }
2248
- function filter(config) {
2249
- return new FilterRule(config);
2250
- }
2251
- function tripwire(config = {}) {
2252
- return new TripwireRule(config);
2253
2252
  }
2254
2253
 
2255
2254
  // src/detection/weights.ts