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