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