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