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