@webdecoy/node 0.4.1 → 0.6.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/README.md +1 -1
- package/dist/index.d.mts +501 -13
- package/dist/index.d.ts +501 -13
- package/dist/index.js +1033 -138
- package/dist/index.mjs +1022 -126
- package/package.json +6 -8
package/dist/index.mjs
CHANGED
|
@@ -1,90 +1,99 @@
|
|
|
1
1
|
// src/client.ts
|
|
2
|
-
import axios from "axios";
|
|
3
|
-
import https from "https";
|
|
4
2
|
var WebDecoyClient = class {
|
|
5
3
|
constructor(config) {
|
|
6
4
|
this.config = config;
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
5
|
+
this.baseUrl = config.apiUrl.replace(/\/+$/, "");
|
|
6
|
+
this.headers = {
|
|
7
|
+
"Content-Type": "application/json",
|
|
8
|
+
Authorization: `Bearer ${config.apiKey}`,
|
|
9
|
+
"User-Agent": "webdecoy-node-sdk/0.1.0"
|
|
10
|
+
};
|
|
11
|
+
if (config.tlsRejectUnauthorized === false && config.debug) {
|
|
12
|
+
console.warn(
|
|
13
|
+
"[WebDecoy] tlsRejectUnauthorized=false is not supported by the fetch transport and is ignored; for local self-signed certs, trust your CA via NODE_EXTRA_CA_CERTS=/path/to/ca.pem."
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
async request(method, path, body) {
|
|
18
|
+
const controller = new AbortController();
|
|
19
|
+
const timer = setTimeout(() => controller.abort(), this.config.timeout);
|
|
20
|
+
if (typeof timer.unref === "function") {
|
|
21
|
+
timer.unref();
|
|
22
|
+
}
|
|
23
|
+
if (this.config.debug) {
|
|
24
|
+
console.log("[WebDecoy] Request:", { method, url: this.baseUrl + path, data: body });
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
const response = await fetch(this.baseUrl + path, {
|
|
28
|
+
method,
|
|
29
|
+
headers: this.headers,
|
|
30
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
31
|
+
signal: controller.signal
|
|
28
32
|
});
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
},
|
|
37
|
-
(error) => {
|
|
38
|
-
console.error("[WebDecoy] Error:", {
|
|
39
|
-
message: error.message,
|
|
40
|
-
response: error.response?.data
|
|
41
|
-
});
|
|
42
|
-
return Promise.reject(error);
|
|
33
|
+
let data;
|
|
34
|
+
const text = await response.text();
|
|
35
|
+
if (text) {
|
|
36
|
+
try {
|
|
37
|
+
data = JSON.parse(text);
|
|
38
|
+
} catch {
|
|
39
|
+
data = void 0;
|
|
43
40
|
}
|
|
44
|
-
|
|
41
|
+
}
|
|
42
|
+
if (this.config.debug) {
|
|
43
|
+
console.log("[WebDecoy] Response:", { status: response.status, data });
|
|
44
|
+
}
|
|
45
|
+
return { status: response.status, data };
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (this.config.debug) {
|
|
48
|
+
console.error("[WebDecoy] Error:", {
|
|
49
|
+
message: error instanceof Error ? error.message : String(error)
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
throw error;
|
|
53
|
+
} finally {
|
|
54
|
+
clearTimeout(timer);
|
|
45
55
|
}
|
|
46
56
|
}
|
|
47
57
|
/**
|
|
48
58
|
* Send a detection request to the ingest service
|
|
49
59
|
*/
|
|
50
60
|
async detect(request) {
|
|
61
|
+
let response;
|
|
51
62
|
try {
|
|
52
|
-
|
|
63
|
+
response = await this.request(
|
|
64
|
+
"POST",
|
|
53
65
|
"/api/v1/sdk/detect",
|
|
54
66
|
request
|
|
55
67
|
);
|
|
56
|
-
return response.data;
|
|
57
68
|
} catch (error) {
|
|
58
|
-
if (
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
if (axiosError.response?.status === 429) {
|
|
64
|
-
throw new Error("Rate limit exceeded. Please try again later.");
|
|
65
|
-
}
|
|
66
|
-
if (axiosError.response?.data?.error || axiosError.response?.data?.message) {
|
|
67
|
-
throw new Error(
|
|
68
|
-
axiosError.response.data.error || axiosError.response.data.message || "API error"
|
|
69
|
-
);
|
|
70
|
-
}
|
|
71
|
-
if (axiosError.code === "ECONNABORTED") {
|
|
72
|
-
throw new Error("Request timeout. The Web Decoy service did not respond in time.");
|
|
73
|
-
}
|
|
74
|
-
if (axiosError.code === "ENOTFOUND" || axiosError.code === "ECONNREFUSED") {
|
|
75
|
-
throw new Error("Unable to connect to Web Decoy service. Please check your network.");
|
|
76
|
-
}
|
|
77
|
-
throw new Error(`API request failed: ${axiosError.message}`);
|
|
69
|
+
if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) {
|
|
70
|
+
throw new Error("Request timeout. The Web Decoy service did not respond in time.");
|
|
71
|
+
}
|
|
72
|
+
if (error instanceof TypeError) {
|
|
73
|
+
throw new Error("Unable to connect to Web Decoy service. Please check your network.");
|
|
78
74
|
}
|
|
79
75
|
throw error;
|
|
80
76
|
}
|
|
77
|
+
if (response.status === 401) {
|
|
78
|
+
throw new Error("Invalid API key. Please check your Web Decoy configuration.");
|
|
79
|
+
}
|
|
80
|
+
if (response.status === 429) {
|
|
81
|
+
throw new Error("Rate limit exceeded. Please try again later.");
|
|
82
|
+
}
|
|
83
|
+
if (response.status >= 400) {
|
|
84
|
+
if (response.data?.error || response.data?.message) {
|
|
85
|
+
throw new Error(response.data.error || response.data.message || "API error");
|
|
86
|
+
}
|
|
87
|
+
throw new Error(`API request failed: HTTP ${response.status}`);
|
|
88
|
+
}
|
|
89
|
+
return response.data;
|
|
81
90
|
}
|
|
82
91
|
/**
|
|
83
92
|
* Send violation events to the ingest service
|
|
84
93
|
*/
|
|
85
94
|
async sendViolations(events) {
|
|
86
95
|
try {
|
|
87
|
-
await this.
|
|
96
|
+
await this.request("POST", "/api/v1/sdk/violations/batch", { events });
|
|
88
97
|
} catch (error) {
|
|
89
98
|
if (this.config.debug) {
|
|
90
99
|
console.error("[WebDecoy] Failed to send violations:", error);
|
|
@@ -96,10 +105,12 @@ var WebDecoyClient = class {
|
|
|
96
105
|
*/
|
|
97
106
|
async getIPEnrichment(ip) {
|
|
98
107
|
try {
|
|
99
|
-
const response = await this.
|
|
108
|
+
const response = await this.request(
|
|
109
|
+
"GET",
|
|
100
110
|
`/api/v1/sdk/ip/${encodeURIComponent(ip)}/enrichment`
|
|
101
111
|
);
|
|
102
|
-
|
|
112
|
+
if (response.status >= 400) return null;
|
|
113
|
+
return response.data ?? null;
|
|
103
114
|
} catch (error) {
|
|
104
115
|
if (this.config.debug) {
|
|
105
116
|
console.error("[WebDecoy] Failed to get IP enrichment:", error);
|
|
@@ -263,6 +274,18 @@ function analyzeRequest(metadata) {
|
|
|
263
274
|
}
|
|
264
275
|
|
|
265
276
|
// src/rules/rule-engine.ts
|
|
277
|
+
function extractClearance(headers) {
|
|
278
|
+
const cookie = headers["cookie"];
|
|
279
|
+
if (!cookie) return void 0;
|
|
280
|
+
for (const part of cookie.split(";")) {
|
|
281
|
+
const eq = part.indexOf("=");
|
|
282
|
+
if (eq < 0) continue;
|
|
283
|
+
if (part.slice(0, eq).trim() === "wd_clearance") {
|
|
284
|
+
return part.slice(eq + 1).trim() || void 0;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return void 0;
|
|
288
|
+
}
|
|
266
289
|
var RuleEngine = class {
|
|
267
290
|
constructor(rules) {
|
|
268
291
|
this.rules = rules;
|
|
@@ -285,6 +308,7 @@ var RuleEngine = class {
|
|
|
285
308
|
method: context.method,
|
|
286
309
|
userAgent: context.userAgent,
|
|
287
310
|
reason: result.reason,
|
|
311
|
+
clearance: result.rule === "tripwire" ? extractClearance(context.headers) : void 0,
|
|
288
312
|
metadata: result.metadata,
|
|
289
313
|
dryRun: result.metadata?.dryRun === true,
|
|
290
314
|
timestamp: new Date(context.timestamp).toISOString()
|
|
@@ -422,12 +446,646 @@ var IPEnrichmentClient = class {
|
|
|
422
446
|
}
|
|
423
447
|
};
|
|
424
448
|
|
|
449
|
+
// src/agent/thumbprint.ts
|
|
450
|
+
var encoder = new TextEncoder();
|
|
451
|
+
async function rsaThumbprint(n, e) {
|
|
452
|
+
return digest(`{"e":${JSON.stringify(e)},"kty":"RSA","n":${JSON.stringify(n)}}`);
|
|
453
|
+
}
|
|
454
|
+
async function okpThumbprint(crv, x) {
|
|
455
|
+
return digest(`{"crv":${JSON.stringify(crv)},"kty":"OKP","x":${JSON.stringify(x)}}`);
|
|
456
|
+
}
|
|
457
|
+
async function jwkThumbprint(k) {
|
|
458
|
+
switch (k.kty) {
|
|
459
|
+
case "OKP":
|
|
460
|
+
if (!k.crv || !k.x) throw new Error("thumbprint: OKP JWK missing crv or x");
|
|
461
|
+
return okpThumbprint(k.crv, k.x);
|
|
462
|
+
case "RSA":
|
|
463
|
+
if (!k.n || !k.e) throw new Error("thumbprint: RSA JWK missing n or e");
|
|
464
|
+
return rsaThumbprint(k.n, k.e);
|
|
465
|
+
default:
|
|
466
|
+
throw new Error(`thumbprint: unsupported kty ${JSON.stringify(k.kty)}`);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
async function digest(canonical) {
|
|
470
|
+
const buf = await crypto.subtle.digest("SHA-256", encoder.encode(canonical));
|
|
471
|
+
return base64urlBytes(new Uint8Array(buf));
|
|
472
|
+
}
|
|
473
|
+
function base64urlBytes(bytes) {
|
|
474
|
+
let binary = "";
|
|
475
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
|
476
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// src/agent/directory.ts
|
|
480
|
+
var WELL_KNOWN = "/.well-known/http-message-signatures-directory";
|
|
481
|
+
var COLD_RETRY_BACKOFF_MS = 3e4;
|
|
482
|
+
var DEFAULT_SIGNED_AGENT_DIRECTORIES = [
|
|
483
|
+
{ name: "OpenAI", category: "ai_crawlers", directory: "https://operator.openai.com" },
|
|
484
|
+
{ name: "OpenAI ChatGPT", category: "ai_crawlers", directory: "https://chatgpt.com" }
|
|
485
|
+
];
|
|
486
|
+
var DirectoryCache = class {
|
|
487
|
+
constructor(opts) {
|
|
488
|
+
this.keys = /* @__PURE__ */ new Map();
|
|
489
|
+
this.refreshedAt = 0;
|
|
490
|
+
this.nextColdRetryAt = 0;
|
|
491
|
+
this.inflight = null;
|
|
492
|
+
/** Resolve a keyid to a verification key, fetching/refreshing as needed. */
|
|
493
|
+
this.resolveKey = async (keyId) => {
|
|
494
|
+
await this.ensureFresh();
|
|
495
|
+
return this.keys.get(keyId);
|
|
496
|
+
};
|
|
497
|
+
this.opts = opts;
|
|
498
|
+
}
|
|
499
|
+
/** Kick off a fetch without blocking — call at startup to warm the cache. */
|
|
500
|
+
prime() {
|
|
501
|
+
if (this.keys.size === 0 && Date.now() >= this.nextColdRetryAt) void this.refresh();
|
|
502
|
+
}
|
|
503
|
+
/** Number of keys currently cached (diagnostics/tests). */
|
|
504
|
+
get size() {
|
|
505
|
+
return this.keys.size;
|
|
506
|
+
}
|
|
507
|
+
async ensureFresh() {
|
|
508
|
+
const now = Date.now();
|
|
509
|
+
const stale = now - this.refreshedAt > this.opts.cacheTtlMs;
|
|
510
|
+
if (this.keys.size > 0) {
|
|
511
|
+
if (stale) void this.refresh();
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
if (now < this.nextColdRetryAt) return;
|
|
515
|
+
await this.refresh();
|
|
516
|
+
}
|
|
517
|
+
/** Re-fetch every directory. De-duplicated: concurrent callers share one run. */
|
|
518
|
+
refresh() {
|
|
519
|
+
if (this.inflight) return this.inflight;
|
|
520
|
+
this.inflight = this.doRefresh().finally(() => {
|
|
521
|
+
this.inflight = null;
|
|
522
|
+
});
|
|
523
|
+
return this.inflight;
|
|
524
|
+
}
|
|
525
|
+
async doRefresh() {
|
|
526
|
+
const results = await Promise.all(
|
|
527
|
+
this.opts.directories.map((src) => this.fetchDirectory(src))
|
|
528
|
+
);
|
|
529
|
+
const next = new Map(this.keys);
|
|
530
|
+
let fetchedAny = false;
|
|
531
|
+
for (const keys of results) {
|
|
532
|
+
if (keys === null) continue;
|
|
533
|
+
fetchedAny = true;
|
|
534
|
+
for (const k of keys) next.set(k.thumbprint, k.key);
|
|
535
|
+
}
|
|
536
|
+
if (fetchedAny) {
|
|
537
|
+
this.keys = next;
|
|
538
|
+
this.refreshedAt = Date.now();
|
|
539
|
+
this.nextColdRetryAt = 0;
|
|
540
|
+
this.debug(`refreshed: ${this.keys.size} key(s) across ${this.opts.directories.length} directories`);
|
|
541
|
+
} else if (this.keys.size === 0) {
|
|
542
|
+
this.nextColdRetryAt = Date.now() + COLD_RETRY_BACKOFF_MS;
|
|
543
|
+
this.debug("all directories unreachable; backing off cold retry");
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
async fetchDirectory(src) {
|
|
547
|
+
const url = directoryUrl(src.directory);
|
|
548
|
+
const controller = new AbortController();
|
|
549
|
+
const timer = setTimeout(() => controller.abort(), this.opts.fetchTimeoutMs);
|
|
550
|
+
try {
|
|
551
|
+
const res = await this.opts.fetchImpl(url, {
|
|
552
|
+
signal: controller.signal,
|
|
553
|
+
headers: {
|
|
554
|
+
Accept: "application/http-message-signatures-directory+json, application/jwk-set+json, application/json"
|
|
555
|
+
},
|
|
556
|
+
redirect: "follow"
|
|
557
|
+
});
|
|
558
|
+
if (!res.ok) {
|
|
559
|
+
this.debug(`${src.name}: HTTP ${res.status}`);
|
|
560
|
+
return null;
|
|
561
|
+
}
|
|
562
|
+
const body = await res.json();
|
|
563
|
+
if (!body || !Array.isArray(body.keys)) {
|
|
564
|
+
this.debug(`${src.name}: no keys in directory`);
|
|
565
|
+
return null;
|
|
566
|
+
}
|
|
567
|
+
const out = [];
|
|
568
|
+
for (const jwk of body.keys) {
|
|
569
|
+
const resolved = await importKey(jwk, src);
|
|
570
|
+
if (resolved) out.push(resolved);
|
|
571
|
+
}
|
|
572
|
+
this.debug(`${src.name}: ${out.length} key(s)`);
|
|
573
|
+
return out;
|
|
574
|
+
} catch (err) {
|
|
575
|
+
this.debug(`${src.name}: fetch failed \u2014 ${err.message}`);
|
|
576
|
+
return null;
|
|
577
|
+
} finally {
|
|
578
|
+
clearTimeout(timer);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
debug(msg) {
|
|
582
|
+
if (this.opts.debug) console.log(`[WebDecoy][web-bot-auth] ${msg}`);
|
|
583
|
+
}
|
|
584
|
+
};
|
|
585
|
+
function directoryUrl(directory) {
|
|
586
|
+
const u = new URL(directory);
|
|
587
|
+
if (u.pathname && u.pathname !== "/") return u.toString();
|
|
588
|
+
u.pathname = WELL_KNOWN;
|
|
589
|
+
return u.toString();
|
|
590
|
+
}
|
|
591
|
+
async function importKey(jwk, src) {
|
|
592
|
+
try {
|
|
593
|
+
let cryptoKey;
|
|
594
|
+
let verifyParams;
|
|
595
|
+
let algorithm;
|
|
596
|
+
if (jwk.kty === "OKP") {
|
|
597
|
+
if (jwk.crv !== "Ed25519" || !jwk.x) return null;
|
|
598
|
+
cryptoKey = await crypto.subtle.importKey(
|
|
599
|
+
"jwk",
|
|
600
|
+
{ kty: "OKP", crv: "Ed25519", x: jwk.x },
|
|
601
|
+
{ name: "Ed25519" },
|
|
602
|
+
false,
|
|
603
|
+
["verify"]
|
|
604
|
+
);
|
|
605
|
+
verifyParams = { name: "Ed25519" };
|
|
606
|
+
algorithm = "ed25519";
|
|
607
|
+
} else if (jwk.kty === "RSA") {
|
|
608
|
+
if (!jwk.n || !jwk.e) return null;
|
|
609
|
+
cryptoKey = await crypto.subtle.importKey(
|
|
610
|
+
"jwk",
|
|
611
|
+
{ kty: "RSA", n: jwk.n, e: jwk.e },
|
|
612
|
+
{ name: "RSA-PSS", hash: "SHA-512" },
|
|
613
|
+
false,
|
|
614
|
+
["verify"]
|
|
615
|
+
);
|
|
616
|
+
verifyParams = { name: "RSA-PSS", saltLength: 64 };
|
|
617
|
+
algorithm = "rsa-pss-sha512";
|
|
618
|
+
} else {
|
|
619
|
+
return null;
|
|
620
|
+
}
|
|
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
|
+
}
|
|
652
|
+
peek() {
|
|
653
|
+
return this.s[this.i];
|
|
654
|
+
}
|
|
655
|
+
skipSP() {
|
|
656
|
+
while (!this.eof() && (this.peek() === " " || this.peek() === " ")) this.i++;
|
|
657
|
+
}
|
|
658
|
+
};
|
|
659
|
+
function parseDictionary(input) {
|
|
660
|
+
const p = new Cursor(input);
|
|
661
|
+
const out = [];
|
|
662
|
+
p.skipSP();
|
|
663
|
+
while (!p.eof()) {
|
|
664
|
+
const key = parseKey(p);
|
|
665
|
+
const entry = { key, raw: "", isList: false, items: [], params: /* @__PURE__ */ new Map() };
|
|
666
|
+
if (!p.eof() && p.peek() === "=") {
|
|
667
|
+
p.i++;
|
|
668
|
+
const start = p.i;
|
|
669
|
+
if (!p.eof() && p.peek() === "(") {
|
|
670
|
+
entry.isList = true;
|
|
671
|
+
parseInnerList(p, entry);
|
|
672
|
+
} else {
|
|
673
|
+
entry.items.push(parseItem(p));
|
|
674
|
+
entry.params = entry.items[0].params;
|
|
675
|
+
}
|
|
676
|
+
entry.raw = input.slice(start, p.i);
|
|
677
|
+
} else {
|
|
678
|
+
entry.params = parseParams(p);
|
|
679
|
+
entry.items.push({ value: true, params: /* @__PURE__ */ new Map() });
|
|
680
|
+
entry.raw = "?1";
|
|
681
|
+
}
|
|
682
|
+
out.push(entry);
|
|
683
|
+
p.skipSP();
|
|
684
|
+
if (p.eof()) break;
|
|
685
|
+
if (p.peek() !== ",") throw new Error(`sfv: expected ',' at ${p.i}`);
|
|
686
|
+
p.i++;
|
|
687
|
+
p.skipSP();
|
|
688
|
+
if (p.eof()) throw new Error("sfv: trailing comma");
|
|
689
|
+
}
|
|
690
|
+
return out;
|
|
691
|
+
}
|
|
692
|
+
function parseInnerList(p, entry) {
|
|
693
|
+
p.i++;
|
|
694
|
+
for (; ; ) {
|
|
695
|
+
p.skipSP();
|
|
696
|
+
if (p.eof()) throw new Error("sfv: unterminated inner list");
|
|
697
|
+
if (p.peek() === ")") {
|
|
698
|
+
p.i++;
|
|
699
|
+
break;
|
|
700
|
+
}
|
|
701
|
+
entry.items.push(parseItem(p));
|
|
702
|
+
if (p.eof()) throw new Error("sfv: unterminated inner list");
|
|
703
|
+
const c = p.peek();
|
|
704
|
+
if (c !== " " && c !== ")") throw new Error(`sfv: bad inner list at ${p.i}`);
|
|
705
|
+
}
|
|
706
|
+
entry.params = parseParams(p);
|
|
707
|
+
}
|
|
708
|
+
function parseItem(p) {
|
|
709
|
+
const { value, bytes } = parseBareItem(p);
|
|
710
|
+
const params = parseParams(p);
|
|
711
|
+
return bytes ? { value, params, bytes } : { value, params };
|
|
712
|
+
}
|
|
713
|
+
function parseParams(p) {
|
|
714
|
+
const params = /* @__PURE__ */ new Map();
|
|
715
|
+
while (!p.eof() && p.peek() === ";") {
|
|
716
|
+
p.i++;
|
|
717
|
+
p.skipSP();
|
|
718
|
+
const key = parseKey(p);
|
|
719
|
+
let val = true;
|
|
720
|
+
if (!p.eof() && p.peek() === "=") {
|
|
721
|
+
p.i++;
|
|
722
|
+
val = parseBareItem(p).value;
|
|
723
|
+
}
|
|
724
|
+
params.set(key, val);
|
|
725
|
+
}
|
|
726
|
+
return params;
|
|
727
|
+
}
|
|
728
|
+
function parseKey(p) {
|
|
729
|
+
const c = p.peek();
|
|
730
|
+
if (!c || !/[a-z*]/.test(c)) throw new Error(`sfv: invalid key at ${p.i}`);
|
|
731
|
+
const start = p.i;
|
|
732
|
+
while (!p.eof() && /[a-z0-9_\-.*]/.test(p.peek())) p.i++;
|
|
733
|
+
return p.s.slice(start, p.i);
|
|
734
|
+
}
|
|
735
|
+
function parseBareItem(p) {
|
|
736
|
+
const c = p.peek();
|
|
737
|
+
if (c === '"') return { value: parseString(p) };
|
|
738
|
+
if (c === ":") return { value: "", bytes: parseByteSequence(p) };
|
|
739
|
+
if (c === "?") {
|
|
740
|
+
p.i++;
|
|
741
|
+
const b = p.s[p.i++];
|
|
742
|
+
if (b === "1") return { value: true };
|
|
743
|
+
if (b === "0") return { value: false };
|
|
744
|
+
throw new Error("sfv: bad boolean");
|
|
745
|
+
}
|
|
746
|
+
if (c === "-" || /[0-9]/.test(c)) return { value: parseNumber(p) };
|
|
747
|
+
if (/[a-zA-Z*]/.test(c)) return { value: parseToken(p) };
|
|
748
|
+
throw new Error(`sfv: invalid bare item at ${p.i}`);
|
|
749
|
+
}
|
|
750
|
+
function parseString(p) {
|
|
751
|
+
p.i++;
|
|
752
|
+
let out = "";
|
|
753
|
+
while (!p.eof()) {
|
|
754
|
+
const c = p.s[p.i++];
|
|
755
|
+
if (c === '"') return out;
|
|
756
|
+
if (c === "\\") {
|
|
757
|
+
const e = p.s[p.i++];
|
|
758
|
+
if (e !== '"' && e !== "\\") throw new Error("sfv: bad escape");
|
|
759
|
+
out += e;
|
|
760
|
+
} else {
|
|
761
|
+
const code = c.charCodeAt(0);
|
|
762
|
+
if (code < 32 || code > 126) throw new Error("sfv: bad char in string");
|
|
763
|
+
out += c;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
throw new Error("sfv: unterminated string");
|
|
767
|
+
}
|
|
768
|
+
function parseByteSequence(p) {
|
|
769
|
+
p.i++;
|
|
770
|
+
const start = p.i;
|
|
771
|
+
while (!p.eof() && p.peek() !== ":") p.i++;
|
|
772
|
+
if (p.eof()) throw new Error("sfv: unterminated byte sequence");
|
|
773
|
+
const b64 = p.s.slice(start, p.i);
|
|
774
|
+
p.i++;
|
|
775
|
+
return base64StdToBytes(b64);
|
|
776
|
+
}
|
|
777
|
+
function parseNumber(p) {
|
|
778
|
+
const start = p.i;
|
|
779
|
+
if (p.peek() === "-") p.i++;
|
|
780
|
+
while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
|
|
781
|
+
if (!p.eof() && p.peek() === ".") {
|
|
782
|
+
p.i++;
|
|
783
|
+
while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
|
|
784
|
+
}
|
|
785
|
+
return Number(p.s.slice(start, p.i));
|
|
786
|
+
}
|
|
787
|
+
function parseToken(p) {
|
|
788
|
+
const start = p.i;
|
|
789
|
+
p.i++;
|
|
790
|
+
while (!p.eof() && /[a-zA-Z0-9!#$%&'*+\-.^_`|~:/]/.test(p.peek())) p.i++;
|
|
791
|
+
return p.s.slice(start, p.i);
|
|
792
|
+
}
|
|
793
|
+
function base64StdToBytes(s) {
|
|
794
|
+
const bin = atob(s);
|
|
795
|
+
const out = new Uint8Array(bin.length);
|
|
796
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
797
|
+
return out;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// src/agent/signature.ts
|
|
801
|
+
var TAG = "web-bot-auth";
|
|
802
|
+
var encoder2 = new TextEncoder();
|
|
803
|
+
async function verifyWebBotAuth(req, resolveKey, toleranceSec) {
|
|
804
|
+
const sigInput = req.headers.get("signature-input");
|
|
805
|
+
const sigHeader = req.headers.get("signature");
|
|
806
|
+
if (!sigInput && !sigHeader) return { outcome: "none" };
|
|
807
|
+
if (!sigInput || !sigHeader) return { outcome: "claimed", reason: "incomplete-signature" };
|
|
808
|
+
let members;
|
|
809
|
+
let sigs;
|
|
810
|
+
try {
|
|
811
|
+
members = parseSignatureInput(sigInput);
|
|
812
|
+
sigs = parseSignatureBytes(sigHeader);
|
|
813
|
+
} catch {
|
|
814
|
+
return { outcome: "claimed", reason: "malformed-signature" };
|
|
815
|
+
}
|
|
816
|
+
const now = Date.now() / 1e3;
|
|
817
|
+
let best = { outcome: "none" };
|
|
818
|
+
for (const m of members) {
|
|
819
|
+
if (m.params.get("tag") !== TAG) continue;
|
|
820
|
+
if (best.outcome === "none") best = { outcome: "claimed", reason: "unverifiable" };
|
|
821
|
+
const sig = sigs.get(m.label);
|
|
822
|
+
if (!sig) continue;
|
|
823
|
+
const keyid = m.params.get("keyid");
|
|
824
|
+
if (typeof keyid !== "string") continue;
|
|
825
|
+
if (!m.components.some((c) => c.name === "@authority" || c.name === "@target-uri")) continue;
|
|
826
|
+
const key = await resolveKey(keyid);
|
|
827
|
+
if (!key) {
|
|
828
|
+
best = higher(best, { outcome: "claimed", keyId: keyid, reason: "unknown-key" });
|
|
829
|
+
continue;
|
|
830
|
+
}
|
|
831
|
+
const created = numeric(m.params.get("created"));
|
|
832
|
+
const expires = numeric(m.params.get("expires"));
|
|
833
|
+
if (expires !== void 0 && now > expires + toleranceSec) {
|
|
834
|
+
best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "expired" });
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
if (created !== void 0 && now + toleranceSec < created) {
|
|
838
|
+
best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "not-yet-valid" });
|
|
839
|
+
continue;
|
|
840
|
+
}
|
|
841
|
+
if (key.exp !== void 0 && now > key.exp + toleranceSec) {
|
|
842
|
+
best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-expired" });
|
|
843
|
+
continue;
|
|
844
|
+
}
|
|
845
|
+
if (key.nbf !== void 0 && now + toleranceSec < key.nbf) {
|
|
846
|
+
best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-not-yet-valid" });
|
|
847
|
+
continue;
|
|
848
|
+
}
|
|
849
|
+
let base;
|
|
850
|
+
try {
|
|
851
|
+
base = buildSignatureBase(req, m);
|
|
852
|
+
} catch {
|
|
853
|
+
best = higher(best, { outcome: "claimed", keyId: keyid, reason: "uncoverable-component" });
|
|
854
|
+
continue;
|
|
855
|
+
}
|
|
856
|
+
let ok = false;
|
|
857
|
+
try {
|
|
858
|
+
ok = await crypto.subtle.verify(
|
|
859
|
+
key.verifyParams,
|
|
860
|
+
key.cryptoKey,
|
|
861
|
+
sig,
|
|
862
|
+
encoder2.encode(base)
|
|
863
|
+
);
|
|
864
|
+
} catch {
|
|
865
|
+
ok = false;
|
|
866
|
+
}
|
|
867
|
+
if (ok) {
|
|
868
|
+
return { outcome: "verified", keyId: keyid, key };
|
|
869
|
+
}
|
|
870
|
+
best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "bad-signature" });
|
|
871
|
+
}
|
|
872
|
+
return best;
|
|
873
|
+
}
|
|
874
|
+
var PRECEDENCE = { none: 0, claimed: 1, impersonation: 2, verified: 3 };
|
|
875
|
+
function higher(a, b) {
|
|
876
|
+
return PRECEDENCE[b.outcome] >= PRECEDENCE[a.outcome] ? b : a;
|
|
877
|
+
}
|
|
878
|
+
function numeric(v) {
|
|
879
|
+
return typeof v === "number" ? v : void 0;
|
|
880
|
+
}
|
|
881
|
+
function buildSignatureBase(req, m) {
|
|
882
|
+
const lines = [];
|
|
883
|
+
for (const c of m.components) {
|
|
884
|
+
lines.push(`${serializeComponentId(c)}: ${componentValue(req, c)}`);
|
|
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, " ");
|
|
913
|
+
}
|
|
914
|
+
default: {
|
|
915
|
+
if (name.startsWith("@")) throw new Error(`unsupported derived component ${name}`);
|
|
916
|
+
const header = req.headers.get(name);
|
|
917
|
+
if (header === null) throw new Error(`covered header ${name} absent`);
|
|
918
|
+
return header.trim().replace(/\s+/g, " ");
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
function canonicalAuthority(url) {
|
|
923
|
+
const host = url.hostname.toLowerCase();
|
|
924
|
+
const port = url.port;
|
|
925
|
+
if (!port) return host;
|
|
926
|
+
if (url.protocol === "https:" && port === "443" || url.protocol === "http:" && port === "80") {
|
|
927
|
+
return host;
|
|
928
|
+
}
|
|
929
|
+
return `${host}:${port}`;
|
|
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);
|
|
955
|
+
}
|
|
956
|
+
return out;
|
|
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
|
+
});
|
|
973
|
+
}
|
|
974
|
+
/** Pre-fetch trusted directories so the first request verifies warm. */
|
|
975
|
+
warmup() {
|
|
976
|
+
this.cache.prime();
|
|
977
|
+
}
|
|
978
|
+
/** Verify a request's Web Bot Auth signature (if any) locally. */
|
|
979
|
+
async verify(request) {
|
|
980
|
+
let req;
|
|
981
|
+
try {
|
|
982
|
+
req = normalize(request);
|
|
983
|
+
} catch {
|
|
984
|
+
return { status: "none" };
|
|
985
|
+
}
|
|
986
|
+
const result = await verifyWebBotAuth(req, this.cache.resolveKey, this.toleranceSec);
|
|
987
|
+
switch (result.outcome) {
|
|
988
|
+
case "verified":
|
|
989
|
+
return {
|
|
990
|
+
status: "verified",
|
|
991
|
+
method: "signature",
|
|
992
|
+
keyId: result.keyId,
|
|
993
|
+
agentName: result.key?.name,
|
|
994
|
+
category: result.key?.category,
|
|
995
|
+
algorithm: result.key?.algorithm
|
|
996
|
+
};
|
|
997
|
+
case "impersonation":
|
|
998
|
+
return {
|
|
999
|
+
status: "impersonation",
|
|
1000
|
+
method: "signature",
|
|
1001
|
+
keyId: result.keyId,
|
|
1002
|
+
agentName: result.key?.name,
|
|
1003
|
+
category: result.key?.category,
|
|
1004
|
+
reason: result.reason
|
|
1005
|
+
};
|
|
1006
|
+
case "claimed":
|
|
1007
|
+
return { status: "claimed", keyId: result.keyId, reason: result.reason };
|
|
1008
|
+
default:
|
|
1009
|
+
return { status: "none" };
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
/** Cached-key count (diagnostics/tests). */
|
|
1013
|
+
get cachedKeyCount() {
|
|
1014
|
+
return this.cache.size;
|
|
1015
|
+
}
|
|
1016
|
+
};
|
|
1017
|
+
function createAgentVerifier(options = {}) {
|
|
1018
|
+
return new AgentVerifier(options);
|
|
1019
|
+
}
|
|
1020
|
+
function normalize(input) {
|
|
1021
|
+
if (isRequest(input)) {
|
|
1022
|
+
return { method: input.method, url: new URL(input.url), headers: input.headers };
|
|
1023
|
+
}
|
|
1024
|
+
const headers = input.headers instanceof Headers ? input.headers : toHeaders(input.headers);
|
|
1025
|
+
return { method: input.method, url: new URL(input.url), headers };
|
|
1026
|
+
}
|
|
1027
|
+
function isRequest(input) {
|
|
1028
|
+
return typeof Request !== "undefined" && input instanceof Request && typeof input.url === "string";
|
|
1029
|
+
}
|
|
1030
|
+
function toHeaders(record) {
|
|
1031
|
+
const h = new Headers();
|
|
1032
|
+
for (const [k, v] of Object.entries(record)) {
|
|
1033
|
+
if (v !== void 0 && v !== null) h.set(k, String(v));
|
|
1034
|
+
}
|
|
1035
|
+
return h;
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
// src/edge.ts
|
|
1039
|
+
var EDGE_CLEARANCE_HEADER = "x-wd-clearance";
|
|
1040
|
+
var EDGE_CLASS_HEADER = "x-wd-class";
|
|
1041
|
+
var EDGE_CLASSES = ["verified", "crawler", "script", "browser"];
|
|
1042
|
+
function absent() {
|
|
1043
|
+
return {
|
|
1044
|
+
present: false,
|
|
1045
|
+
isVerified: false,
|
|
1046
|
+
isCrawler: false,
|
|
1047
|
+
isScript: false,
|
|
1048
|
+
isBrowser: false,
|
|
1049
|
+
isUnattestedNonBrowser: false
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
function normaliseClass(raw) {
|
|
1053
|
+
if (!raw) return void 0;
|
|
1054
|
+
const v = raw.trim().toLowerCase();
|
|
1055
|
+
return EDGE_CLASSES.includes(v) ? v : void 0;
|
|
1056
|
+
}
|
|
1057
|
+
function readEdgeVerdict(headers) {
|
|
1058
|
+
if (!headers) return absent();
|
|
1059
|
+
let clearanceRaw;
|
|
1060
|
+
let classRaw;
|
|
1061
|
+
for (const key of Object.keys(headers)) {
|
|
1062
|
+
const k = key.toLowerCase();
|
|
1063
|
+
if (k === EDGE_CLEARANCE_HEADER) clearanceRaw = headers[key];
|
|
1064
|
+
else if (k === EDGE_CLASS_HEADER) classRaw = headers[key];
|
|
1065
|
+
}
|
|
1066
|
+
const clearance = clearanceRaw?.trim() || void 0;
|
|
1067
|
+
const cls = normaliseClass(classRaw);
|
|
1068
|
+
if (!clearance && !cls) return absent();
|
|
1069
|
+
return {
|
|
1070
|
+
present: true,
|
|
1071
|
+
clearance,
|
|
1072
|
+
class: cls,
|
|
1073
|
+
isVerified: cls === "verified",
|
|
1074
|
+
isCrawler: cls === "crawler",
|
|
1075
|
+
isScript: cls === "script",
|
|
1076
|
+
isBrowser: cls === "browser",
|
|
1077
|
+
isUnattestedNonBrowser: cls === "script" || cls === "crawler"
|
|
1078
|
+
};
|
|
1079
|
+
}
|
|
1080
|
+
|
|
425
1081
|
// src/sdk.ts
|
|
426
1082
|
var WebDecoy = class {
|
|
427
1083
|
constructor(config) {
|
|
428
1084
|
this.violationReporter = null;
|
|
429
1085
|
this.ipEnrichmentClient = null;
|
|
430
1086
|
this._hasFilterRules = false;
|
|
1087
|
+
this._hasAgentRules = false;
|
|
1088
|
+
this.agentVerifier = null;
|
|
431
1089
|
const hasApiKey = !!config.apiKey;
|
|
432
1090
|
if (hasApiKey) {
|
|
433
1091
|
if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
|
|
@@ -459,11 +1117,16 @@ var WebDecoy = class {
|
|
|
459
1117
|
console.log("[WebDecoy] Running in local-only mode (no API key). Rules will still evaluate.");
|
|
460
1118
|
}
|
|
461
1119
|
}
|
|
1120
|
+
this.webBotAuthOptions = config.webBotAuth;
|
|
462
1121
|
if (config.rules && config.rules.length > 0) {
|
|
463
1122
|
this.ruleEngine = new RuleEngine(config.rules);
|
|
464
1123
|
this._hasFilterRules = config.rules.some(
|
|
465
1124
|
(r) => r.name.startsWith("filter:")
|
|
466
1125
|
);
|
|
1126
|
+
this._hasAgentRules = config.rules.some((r) => r.name === "web-bot-auth");
|
|
1127
|
+
if (this._hasAgentRules) {
|
|
1128
|
+
this.getAgentVerifier().warmup();
|
|
1129
|
+
}
|
|
467
1130
|
} else {
|
|
468
1131
|
this.ruleEngine = null;
|
|
469
1132
|
}
|
|
@@ -492,52 +1155,111 @@ var WebDecoy = class {
|
|
|
492
1155
|
*/
|
|
493
1156
|
evaluateRules(metadata) {
|
|
494
1157
|
if (!this.ruleEngine) return null;
|
|
495
|
-
|
|
496
|
-
ip: metadata.ip,
|
|
497
|
-
path: metadata.path,
|
|
498
|
-
method: metadata.method,
|
|
499
|
-
userAgent: metadata.user_agent,
|
|
500
|
-
headers: metadata.headers,
|
|
501
|
-
timestamp: metadata.timestamp || Date.now()
|
|
502
|
-
};
|
|
503
|
-
const result = this.ruleEngine.evaluate(context);
|
|
504
|
-
if (result.violations.length > 0 && this.violationReporter) {
|
|
505
|
-
this.violationReporter.report(result.violations);
|
|
506
|
-
}
|
|
507
|
-
return result;
|
|
1158
|
+
return this.runRules(this.buildContext(metadata));
|
|
508
1159
|
}
|
|
509
1160
|
/**
|
|
510
|
-
* Evaluate rules with async IP enrichment
|
|
511
|
-
* Use this instead of evaluateRules() when filter rules
|
|
1161
|
+
* Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth
|
|
1162
|
+
* verification). Use this instead of evaluateRules() when filter rules or
|
|
1163
|
+
* webBotAuth() rules are present.
|
|
512
1164
|
*/
|
|
513
1165
|
async evaluateRulesAsync(metadata) {
|
|
514
1166
|
if (!this.ruleEngine) return null;
|
|
515
|
-
const context =
|
|
1167
|
+
const context = await this.buildAsyncContext(metadata);
|
|
1168
|
+
return this.runRules(context);
|
|
1169
|
+
}
|
|
1170
|
+
/** Build the base (synchronous) rule context from request metadata. */
|
|
1171
|
+
buildContext(metadata) {
|
|
1172
|
+
return {
|
|
516
1173
|
ip: metadata.ip,
|
|
517
1174
|
path: metadata.path,
|
|
518
1175
|
method: metadata.method,
|
|
519
1176
|
userAgent: metadata.user_agent,
|
|
520
1177
|
headers: metadata.headers,
|
|
521
|
-
timestamp: metadata.timestamp || Date.now()
|
|
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)
|
|
522
1183
|
};
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Build a rule context with async signals resolved: IP enrichment (for
|
|
1187
|
+
* filter rules) and the Web Bot Auth verdict (for webBotAuth() rules).
|
|
1188
|
+
*/
|
|
1189
|
+
async buildAsyncContext(metadata) {
|
|
1190
|
+
const context = this.buildContext(metadata);
|
|
523
1191
|
if (this._hasFilterRules && this.ipEnrichmentClient) {
|
|
524
1192
|
const enrichment = await this.ipEnrichmentClient.enrich(metadata.ip);
|
|
525
1193
|
if (enrichment) {
|
|
526
1194
|
context.enrichment = enrichment;
|
|
527
1195
|
}
|
|
528
1196
|
}
|
|
1197
|
+
if (this._hasAgentRules) {
|
|
1198
|
+
context.agent = await this.computeAgentVerdict(metadata);
|
|
1199
|
+
}
|
|
1200
|
+
return context;
|
|
1201
|
+
}
|
|
1202
|
+
/** Evaluate rules against a prepared context and report any violations. */
|
|
1203
|
+
runRules(context) {
|
|
1204
|
+
if (!this.ruleEngine) return null;
|
|
529
1205
|
const result = this.ruleEngine.evaluate(context);
|
|
530
1206
|
if (result.violations.length > 0 && this.violationReporter) {
|
|
531
1207
|
this.violationReporter.report(result.violations);
|
|
532
1208
|
}
|
|
533
1209
|
return result;
|
|
534
1210
|
}
|
|
1211
|
+
/** Lazily construct the shared Web Bot Auth verifier (one directory cache). */
|
|
1212
|
+
getAgentVerifier() {
|
|
1213
|
+
if (!this.agentVerifier) {
|
|
1214
|
+
this.agentVerifier = new AgentVerifier({
|
|
1215
|
+
debug: this.config.debug,
|
|
1216
|
+
...this.webBotAuthOptions
|
|
1217
|
+
});
|
|
1218
|
+
}
|
|
1219
|
+
return this.agentVerifier;
|
|
1220
|
+
}
|
|
1221
|
+
/**
|
|
1222
|
+
* Verify a request's Web Bot Auth signature locally, deriving the request
|
|
1223
|
+
* URL/authority from its metadata. Returns undefined when the request lacks
|
|
1224
|
+
* the host information needed to verify (verdict is then simply absent).
|
|
1225
|
+
*/
|
|
1226
|
+
async computeAgentVerdict(metadata) {
|
|
1227
|
+
const input = agentInputFromMetadata(metadata);
|
|
1228
|
+
if (!input) return void 0;
|
|
1229
|
+
return this.getAgentVerifier().verify(input);
|
|
1230
|
+
}
|
|
1231
|
+
/**
|
|
1232
|
+
* Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag
|
|
1233
|
+
* "web-bot-auth"). Returns whether it is a cryptographically `verified`
|
|
1234
|
+
* agent, an `impersonation` of a known one, an unverifiable `claimed`
|
|
1235
|
+
* signature, or `none`. No network on the warm path.
|
|
1236
|
+
*
|
|
1237
|
+
* Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }`
|
|
1238
|
+
* object (Node).
|
|
1239
|
+
*
|
|
1240
|
+
* @example
|
|
1241
|
+
* ```ts
|
|
1242
|
+
* const verdict = await webdecoy.detectBot(request);
|
|
1243
|
+
* if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 });
|
|
1244
|
+
* if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName);
|
|
1245
|
+
* ```
|
|
1246
|
+
*/
|
|
1247
|
+
async detectBot(request) {
|
|
1248
|
+
return this.getAgentVerifier().verify(request);
|
|
1249
|
+
}
|
|
535
1250
|
/**
|
|
536
1251
|
* Whether this SDK instance has filter rules that need async enrichment
|
|
537
1252
|
*/
|
|
538
1253
|
get hasFilterRules() {
|
|
539
1254
|
return this._hasFilterRules;
|
|
540
1255
|
}
|
|
1256
|
+
/**
|
|
1257
|
+
* Whether this SDK instance has Web Bot Auth rules that need async
|
|
1258
|
+
* verification before evaluation.
|
|
1259
|
+
*/
|
|
1260
|
+
get hasAgentRules() {
|
|
1261
|
+
return this._hasAgentRules;
|
|
1262
|
+
}
|
|
541
1263
|
/**
|
|
542
1264
|
* Protect a request by checking it against Web Decoy's bot detection
|
|
543
1265
|
*
|
|
@@ -546,6 +1268,11 @@ var WebDecoy = class {
|
|
|
546
1268
|
* @returns Protection result with decision and detection details
|
|
547
1269
|
*/
|
|
548
1270
|
async protect(metadata, options = {}) {
|
|
1271
|
+
const edge = readEdgeVerdict(metadata.headers);
|
|
1272
|
+
const result = await this.decide(metadata, options);
|
|
1273
|
+
return { ...result, edge };
|
|
1274
|
+
}
|
|
1275
|
+
async decide(metadata, options = {}) {
|
|
549
1276
|
try {
|
|
550
1277
|
if (!metadata.ip) {
|
|
551
1278
|
throw new Error("IP address is required in request metadata");
|
|
@@ -553,7 +1280,15 @@ var WebDecoy = class {
|
|
|
553
1280
|
if (!metadata.timestamp) {
|
|
554
1281
|
metadata.timestamp = Date.now();
|
|
555
1282
|
}
|
|
556
|
-
|
|
1283
|
+
let ruleResult;
|
|
1284
|
+
let agentVerdict;
|
|
1285
|
+
if (this.ruleEngine && (this._hasFilterRules || this._hasAgentRules)) {
|
|
1286
|
+
const context = await this.buildAsyncContext(metadata);
|
|
1287
|
+
agentVerdict = context.agent;
|
|
1288
|
+
ruleResult = this.runRules(context);
|
|
1289
|
+
} else {
|
|
1290
|
+
ruleResult = this.evaluateRules(metadata);
|
|
1291
|
+
}
|
|
557
1292
|
if (ruleResult && ruleResult.action === "DENY") {
|
|
558
1293
|
return {
|
|
559
1294
|
allowed: false,
|
|
@@ -565,7 +1300,8 @@ var WebDecoy = class {
|
|
|
565
1300
|
detection_id: "rule_" + Date.now(),
|
|
566
1301
|
rule_enforced: true
|
|
567
1302
|
},
|
|
568
|
-
ruleResult
|
|
1303
|
+
ruleResult,
|
|
1304
|
+
agent: agentVerdict
|
|
569
1305
|
};
|
|
570
1306
|
}
|
|
571
1307
|
if (ruleResult && ruleResult.action === "THROTTLE") {
|
|
@@ -579,7 +1315,8 @@ var WebDecoy = class {
|
|
|
579
1315
|
detection_id: "rule_" + Date.now(),
|
|
580
1316
|
rule_enforced: true
|
|
581
1317
|
},
|
|
582
|
-
ruleResult
|
|
1318
|
+
ruleResult,
|
|
1319
|
+
agent: agentVerdict
|
|
583
1320
|
};
|
|
584
1321
|
}
|
|
585
1322
|
if (!this.client) {
|
|
@@ -593,7 +1330,8 @@ var WebDecoy = class {
|
|
|
593
1330
|
detection_id: "local_" + Date.now(),
|
|
594
1331
|
rule_enforced: false
|
|
595
1332
|
},
|
|
596
|
-
ruleResult: ruleResult ?? void 0
|
|
1333
|
+
ruleResult: ruleResult ?? void 0,
|
|
1334
|
+
agent: agentVerdict
|
|
597
1335
|
};
|
|
598
1336
|
}
|
|
599
1337
|
const localAnalysis = options.skipLocalAnalysis ? {
|
|
@@ -623,7 +1361,8 @@ var WebDecoy = class {
|
|
|
623
1361
|
detection_id: "local_" + Date.now(),
|
|
624
1362
|
rule_enforced: false
|
|
625
1363
|
},
|
|
626
|
-
ruleResult: ruleResult ?? void 0
|
|
1364
|
+
ruleResult: ruleResult ?? void 0,
|
|
1365
|
+
agent: agentVerdict
|
|
627
1366
|
};
|
|
628
1367
|
}
|
|
629
1368
|
const detection = await this.client.detect(detectionRequest);
|
|
@@ -639,7 +1378,8 @@ var WebDecoy = class {
|
|
|
639
1378
|
return {
|
|
640
1379
|
allowed,
|
|
641
1380
|
detection,
|
|
642
|
-
ruleResult: ruleResult ?? void 0
|
|
1381
|
+
ruleResult: ruleResult ?? void 0,
|
|
1382
|
+
agent: agentVerdict
|
|
643
1383
|
};
|
|
644
1384
|
} catch (error) {
|
|
645
1385
|
if (this.config.debug) {
|
|
@@ -707,6 +1447,24 @@ var WebDecoy = class {
|
|
|
707
1447
|
}
|
|
708
1448
|
}
|
|
709
1449
|
};
|
|
1450
|
+
function agentInputFromMetadata(metadata) {
|
|
1451
|
+
const headers = metadata.headers || {};
|
|
1452
|
+
const host = headers["host"] || headers[":authority"] || headers["x-forwarded-host"] || headers["Host"];
|
|
1453
|
+
if (!host) return null;
|
|
1454
|
+
const proto = headers["x-forwarded-proto"] || headers["X-Forwarded-Proto"];
|
|
1455
|
+
const scheme = (proto ? proto.split(",")[0].trim() : "https") || "https";
|
|
1456
|
+
const rawPath = metadata.path || "/";
|
|
1457
|
+
const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
|
|
1458
|
+
try {
|
|
1459
|
+
return {
|
|
1460
|
+
method: metadata.method,
|
|
1461
|
+
url: `${scheme}://${host}${path}`,
|
|
1462
|
+
headers
|
|
1463
|
+
};
|
|
1464
|
+
} catch {
|
|
1465
|
+
return null;
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
710
1468
|
|
|
711
1469
|
// src/rules/rate-limiter.ts
|
|
712
1470
|
var InMemoryRateLimiter = class {
|
|
@@ -1184,6 +1942,18 @@ function resolveProperty(path, context) {
|
|
|
1184
1942
|
if (prop === "user_agent") return context.userAgent;
|
|
1185
1943
|
return void 0;
|
|
1186
1944
|
}
|
|
1945
|
+
if (namespace === "edge") {
|
|
1946
|
+
const e = context.edge;
|
|
1947
|
+
if (!e) return void 0;
|
|
1948
|
+
if (prop === "present") return e.present;
|
|
1949
|
+
if (prop === "clearance") return e.clearance;
|
|
1950
|
+
if (prop === "class") return e.class;
|
|
1951
|
+
if (prop === "verified") return e.isVerified;
|
|
1952
|
+
if (prop === "crawler") return e.isCrawler;
|
|
1953
|
+
if (prop === "script") return e.isScript;
|
|
1954
|
+
if (prop === "browser") return e.isBrowser;
|
|
1955
|
+
return void 0;
|
|
1956
|
+
}
|
|
1187
1957
|
if (path.length === 1) return void 0;
|
|
1188
1958
|
return void 0;
|
|
1189
1959
|
}
|
|
@@ -1338,11 +2108,133 @@ var TripwireRule = class {
|
|
|
1338
2108
|
}
|
|
1339
2109
|
};
|
|
1340
2110
|
|
|
2111
|
+
// src/rules/web-bot-auth-rule.ts
|
|
2112
|
+
var WebBotAuthRule = class {
|
|
2113
|
+
constructor(config = {}) {
|
|
2114
|
+
this.name = "web-bot-auth";
|
|
2115
|
+
this.onImpersonation = config.onImpersonation ?? "DENY";
|
|
2116
|
+
this.onClaimed = config.onClaimed ?? "ALLOW";
|
|
2117
|
+
this.allowCategories = config.allowCategories ? new Set(config.allowCategories) : void 0;
|
|
2118
|
+
this.dryRun = config.dryRun ?? false;
|
|
2119
|
+
}
|
|
2120
|
+
evaluate(context) {
|
|
2121
|
+
const verdict = context.agent;
|
|
2122
|
+
if (!verdict || verdict.status === "none") return this.allow();
|
|
2123
|
+
if (verdict.status === "impersonation") {
|
|
2124
|
+
return this.act(this.onImpersonation, "agent_impersonation", {
|
|
2125
|
+
agentName: verdict.agentName,
|
|
2126
|
+
category: verdict.category,
|
|
2127
|
+
keyId: verdict.keyId,
|
|
2128
|
+
detail: verdict.reason
|
|
2129
|
+
});
|
|
2130
|
+
}
|
|
2131
|
+
if (verdict.status === "claimed") {
|
|
2132
|
+
return this.act(this.onClaimed, "agent_unverifiable", {
|
|
2133
|
+
keyId: verdict.keyId,
|
|
2134
|
+
detail: verdict.reason
|
|
2135
|
+
});
|
|
2136
|
+
}
|
|
2137
|
+
if (this.allowCategories && verdict.category && !this.allowCategories.has(verdict.category)) {
|
|
2138
|
+
return this.act(this.onClaimed, "agent_category_not_allowed", {
|
|
2139
|
+
agentName: verdict.agentName,
|
|
2140
|
+
category: verdict.category,
|
|
2141
|
+
keyId: verdict.keyId
|
|
2142
|
+
});
|
|
2143
|
+
}
|
|
2144
|
+
return this.allow();
|
|
2145
|
+
}
|
|
2146
|
+
act(action, verdict, detail) {
|
|
2147
|
+
if (action === "ALLOW") return this.allow();
|
|
2148
|
+
return {
|
|
2149
|
+
action: this.dryRun ? "ALLOW" : action,
|
|
2150
|
+
rule: this.name,
|
|
2151
|
+
reason: reasonFor(verdict),
|
|
2152
|
+
metadata: { verdict, dryRun: this.dryRun, ...detail }
|
|
2153
|
+
};
|
|
2154
|
+
}
|
|
2155
|
+
allow() {
|
|
2156
|
+
return { action: "ALLOW", rule: this.name };
|
|
2157
|
+
}
|
|
2158
|
+
};
|
|
2159
|
+
function reasonFor(verdict) {
|
|
2160
|
+
switch (verdict) {
|
|
2161
|
+
case "agent_impersonation":
|
|
2162
|
+
return "Web Bot Auth signature failed verification (agent impersonation)";
|
|
2163
|
+
case "agent_unverifiable":
|
|
2164
|
+
return "Web Bot Auth signature could not be verified";
|
|
2165
|
+
case "agent_category_not_allowed":
|
|
2166
|
+
return "Verified agent category is not allowed";
|
|
2167
|
+
default:
|
|
2168
|
+
return "Web Bot Auth rule triggered";
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
function webBotAuth(config = {}) {
|
|
2172
|
+
return new WebBotAuthRule(config);
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
// src/webcrypto.ts
|
|
2176
|
+
var encoder3 = new TextEncoder();
|
|
2177
|
+
function toHex(bytes) {
|
|
2178
|
+
let hex = "";
|
|
2179
|
+
for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
|
|
2180
|
+
return hex;
|
|
2181
|
+
}
|
|
2182
|
+
async function sha256Hex(data) {
|
|
2183
|
+
const digest2 = await crypto.subtle.digest("SHA-256", encoder3.encode(data));
|
|
2184
|
+
return toHex(new Uint8Array(digest2));
|
|
2185
|
+
}
|
|
2186
|
+
async function hmacSha256Hex(secret, data) {
|
|
2187
|
+
const key = await crypto.subtle.importKey(
|
|
2188
|
+
"raw",
|
|
2189
|
+
encoder3.encode(secret),
|
|
2190
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
2191
|
+
false,
|
|
2192
|
+
["sign"]
|
|
2193
|
+
);
|
|
2194
|
+
const sig = await crypto.subtle.sign("HMAC", key, encoder3.encode(data));
|
|
2195
|
+
return toHex(new Uint8Array(sig));
|
|
2196
|
+
}
|
|
2197
|
+
function randomHex(bytes) {
|
|
2198
|
+
const buf = new Uint8Array(bytes);
|
|
2199
|
+
crypto.getRandomValues(buf);
|
|
2200
|
+
return toHex(buf);
|
|
2201
|
+
}
|
|
2202
|
+
function timingSafeEqualStr(a, b) {
|
|
2203
|
+
if (a.length !== b.length) return false;
|
|
2204
|
+
let diff = 0;
|
|
2205
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
2206
|
+
return diff === 0;
|
|
2207
|
+
}
|
|
2208
|
+
function base64urlEncode(data) {
|
|
2209
|
+
const bytes = encoder3.encode(data);
|
|
2210
|
+
let binary = "";
|
|
2211
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
|
2212
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
2213
|
+
}
|
|
2214
|
+
function base64urlDecode(data) {
|
|
2215
|
+
const b64 = data.replace(/-/g, "+").replace(/_/g, "/");
|
|
2216
|
+
const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
|
|
2217
|
+
const binary = atob(padded);
|
|
2218
|
+
const bytes = new Uint8Array(binary.length);
|
|
2219
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
2220
|
+
return new TextDecoder().decode(bytes);
|
|
2221
|
+
}
|
|
2222
|
+
function fnv1a64Hex(data) {
|
|
2223
|
+
const PRIME = 0x100000001b3n;
|
|
2224
|
+
const MASK = 0xffffffffffffffffn;
|
|
2225
|
+
let hash = 0xcbf29ce484222325n;
|
|
2226
|
+
const bytes = encoder3.encode(data);
|
|
2227
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
2228
|
+
hash ^= BigInt(bytes[i]);
|
|
2229
|
+
hash = hash * PRIME & MASK;
|
|
2230
|
+
}
|
|
2231
|
+
return hash.toString(16).padStart(16, "0");
|
|
2232
|
+
}
|
|
2233
|
+
|
|
1341
2234
|
// src/rules/honeytoken.ts
|
|
1342
|
-
import { randomBytes } from "crypto";
|
|
1343
2235
|
function honeytoken(options = {}) {
|
|
1344
2236
|
const base = (options.basePath ?? "/__wd").replace(/\/+$/, "");
|
|
1345
|
-
const token = options.token ??
|
|
2237
|
+
const token = options.token ?? randomHex(6);
|
|
1346
2238
|
const path = `${base}/${token}`;
|
|
1347
2239
|
const text = options.text ?? ".";
|
|
1348
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>`;
|
|
@@ -1389,7 +2281,10 @@ var AUTOMATION_UA_PATTERNS = [
|
|
|
1389
2281
|
];
|
|
1390
2282
|
|
|
1391
2283
|
// src/detection/ip.ts
|
|
1392
|
-
|
|
2284
|
+
var IPV4_RE = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
|
|
2285
|
+
function isIPv4(ip) {
|
|
2286
|
+
return IPV4_RE.test(ip);
|
|
2287
|
+
}
|
|
1393
2288
|
var DATACENTER_CIDRS = [
|
|
1394
2289
|
// AWS
|
|
1395
2290
|
"3.0.0.0/8",
|
|
@@ -2073,7 +2968,6 @@ function detectTouchKinematics(signals) {
|
|
|
2073
2968
|
}
|
|
2074
2969
|
|
|
2075
2970
|
// src/detection/detectors/fingerprint.ts
|
|
2076
|
-
import { createHash } from "crypto";
|
|
2077
2971
|
function detectFingerprint(signals, ip, siteKey, store) {
|
|
2078
2972
|
const detections = [];
|
|
2079
2973
|
const env = signals.environmental ?? {};
|
|
@@ -2084,7 +2978,7 @@ function detectFingerprint(signals, ip, siteKey, store) {
|
|
|
2084
2978
|
String(automation.platform ?? ""),
|
|
2085
2979
|
String(automation.hardwareConcurrency ?? "")
|
|
2086
2980
|
];
|
|
2087
|
-
const fp =
|
|
2981
|
+
const fp = fnv1a64Hex(components.join("|"));
|
|
2088
2982
|
store.record(fp, ip, siteKey);
|
|
2089
2983
|
if (store.getIpFpCount(ip) > 5) {
|
|
2090
2984
|
detections.push({
|
|
@@ -2966,9 +3860,6 @@ var DetectionEngine = class {
|
|
|
2966
3860
|
}
|
|
2967
3861
|
};
|
|
2968
3862
|
|
|
2969
|
-
// src/captcha/service.ts
|
|
2970
|
-
import { createHash as createHash4 } from "crypto";
|
|
2971
|
-
|
|
2972
3863
|
// src/captcha/secret.ts
|
|
2973
3864
|
var INSECURE_DEFAULT_SECRET = "dev-secret-change-in-production";
|
|
2974
3865
|
function resolveSecret(secret) {
|
|
@@ -2990,7 +3881,6 @@ function resolveSecret(secret) {
|
|
|
2990
3881
|
}
|
|
2991
3882
|
|
|
2992
3883
|
// src/captcha/pow.ts
|
|
2993
|
-
import { createHash as createHash2, createHmac, randomBytes as randomBytes2 } from "crypto";
|
|
2994
3884
|
var EXPIRATION_MS = 5 * 60 * 1e3;
|
|
2995
3885
|
var InMemoryChallengeStore = class {
|
|
2996
3886
|
constructor() {
|
|
@@ -3036,10 +3926,10 @@ var PoWManager = class {
|
|
|
3036
3926
|
return difficulty;
|
|
3037
3927
|
}
|
|
3038
3928
|
/** Generate and store a signed challenge. */
|
|
3039
|
-
generate(siteKey, ip, difficulty) {
|
|
3929
|
+
async generate(siteKey, ip, difficulty) {
|
|
3040
3930
|
const resolvedDifficulty = difficulty ?? this.scaleDifficulty(siteKey, ip);
|
|
3041
|
-
const challengeId =
|
|
3042
|
-
const nonce =
|
|
3931
|
+
const challengeId = randomHex(16);
|
|
3932
|
+
const nonce = randomHex(16);
|
|
3043
3933
|
const timestamp = Date.now();
|
|
3044
3934
|
const expiresAt = timestamp + EXPIRATION_MS;
|
|
3045
3935
|
const challengeData = {
|
|
@@ -3054,12 +3944,12 @@ var PoWManager = class {
|
|
|
3054
3944
|
};
|
|
3055
3945
|
const { sig: _omit, ...toSign } = challengeData;
|
|
3056
3946
|
void _omit;
|
|
3057
|
-
challengeData.sig =
|
|
3947
|
+
challengeData.sig = await hmacSha256Hex(this.secret, JSON.stringify(toSign));
|
|
3058
3948
|
this.store.put({ ...challengeData, ip, createdAt: timestamp });
|
|
3059
3949
|
return challengeData;
|
|
3060
3950
|
}
|
|
3061
3951
|
/** Verify a submitted solution. `signalsHash` binds it to the signals. */
|
|
3062
|
-
verify(solution, siteKey, signalsHash = null) {
|
|
3952
|
+
async verify(solution, siteKey, signalsHash = null) {
|
|
3063
3953
|
const challenge = this.store.get(solution.challengeId);
|
|
3064
3954
|
if (!challenge) return { valid: false, reason: "challenge_not_found" };
|
|
3065
3955
|
if (Date.now() > challenge.expiresAt) {
|
|
@@ -3071,7 +3961,7 @@ var PoWManager = class {
|
|
|
3071
3961
|
}
|
|
3072
3962
|
const solutionKey = `${solution.challengeId}:${solution.nonce}`;
|
|
3073
3963
|
const input = signalsHash ? `${challenge.prefix}:${signalsHash}:${solution.nonce}` : `${challenge.prefix}:${solution.nonce}`;
|
|
3074
|
-
const expectedHash =
|
|
3964
|
+
const expectedHash = await sha256Hex(input);
|
|
3075
3965
|
if (solution.hash !== expectedHash) {
|
|
3076
3966
|
return { valid: false, reason: "invalid_hash" };
|
|
3077
3967
|
}
|
|
@@ -3093,7 +3983,6 @@ var PoWManager = class {
|
|
|
3093
3983
|
};
|
|
3094
3984
|
|
|
3095
3985
|
// src/captcha/token.ts
|
|
3096
|
-
import { createHash as createHash3, createHmac as createHmac2, timingSafeEqual } from "crypto";
|
|
3097
3986
|
var TOKEN_TTL_SECONDS = 300;
|
|
3098
3987
|
var InMemoryTokenStore = class {
|
|
3099
3988
|
constructor() {
|
|
@@ -3115,22 +4004,22 @@ var TokenManager = class {
|
|
|
3115
4004
|
this.store = options.store ?? new InMemoryTokenStore();
|
|
3116
4005
|
}
|
|
3117
4006
|
/** Issue a signed, IP-bound token for a passing request. */
|
|
3118
|
-
issue(ip, siteKey, score) {
|
|
4007
|
+
async issue(ip, siteKey, score) {
|
|
3119
4008
|
const data = {
|
|
3120
4009
|
site_key: siteKey,
|
|
3121
4010
|
timestamp: Math.floor(Date.now() / 1e3),
|
|
3122
4011
|
score: Math.round(score * 1e3) / 1e3,
|
|
3123
|
-
ip_hash:
|
|
4012
|
+
ip_hash: (await sha256Hex(ip)).slice(0, 8)
|
|
3124
4013
|
};
|
|
3125
4014
|
const payload = JSON.stringify(data, Object.keys(data).sort());
|
|
3126
|
-
data.sig =
|
|
3127
|
-
return
|
|
4015
|
+
data.sig = await hmacSha256Hex(this.secret, payload);
|
|
4016
|
+
return base64urlEncode(JSON.stringify(data));
|
|
3128
4017
|
}
|
|
3129
4018
|
/** Verify a token: signature, expiry, replay, and optional IP binding. */
|
|
3130
|
-
verify(token, ip = null) {
|
|
4019
|
+
async verify(token, ip = null) {
|
|
3131
4020
|
let decoded;
|
|
3132
4021
|
try {
|
|
3133
|
-
decoded = JSON.parse(
|
|
4022
|
+
decoded = JSON.parse(base64urlDecode(token));
|
|
3134
4023
|
} catch (e) {
|
|
3135
4024
|
return { valid: false, reason: e instanceof Error ? e.message : "invalid_token" };
|
|
3136
4025
|
}
|
|
@@ -3141,17 +4030,15 @@ var TokenManager = class {
|
|
|
3141
4030
|
if (!sig) return { valid: false, reason: "invalid_signature" };
|
|
3142
4031
|
delete decoded.sig;
|
|
3143
4032
|
const payload = JSON.stringify(decoded, Object.keys(decoded).sort());
|
|
3144
|
-
const expectedSig =
|
|
3145
|
-
|
|
3146
|
-
const expectedBuf = Buffer.from(expectedSig);
|
|
3147
|
-
if (sigBuf.length !== expectedBuf.length || !timingSafeEqual(sigBuf, expectedBuf)) {
|
|
4033
|
+
const expectedSig = await hmacSha256Hex(this.secret, payload);
|
|
4034
|
+
if (!timingSafeEqualStr(sig, expectedSig)) {
|
|
3148
4035
|
return { valid: false, reason: "invalid_signature" };
|
|
3149
4036
|
}
|
|
3150
4037
|
if (this.store.isUsed(sig)) {
|
|
3151
4038
|
return { valid: false, reason: "token_already_used" };
|
|
3152
4039
|
}
|
|
3153
4040
|
if (ip) {
|
|
3154
|
-
const expectedIpHash =
|
|
4041
|
+
const expectedIpHash = (await sha256Hex(ip)).slice(0, 8);
|
|
3155
4042
|
if (decoded.ip_hash !== expectedIpHash) {
|
|
3156
4043
|
return { valid: false, reason: "ip_mismatch" };
|
|
3157
4044
|
}
|
|
@@ -3184,21 +4071,21 @@ var Captcha = class {
|
|
|
3184
4071
|
this.trustedJA4Headers = options.trustedJA4Headers ?? [];
|
|
3185
4072
|
}
|
|
3186
4073
|
/** Issue a PoW challenge for the client to solve (difficulty auto-scaled). */
|
|
3187
|
-
issueChallenge(siteKey, ip, difficulty) {
|
|
4074
|
+
async issueChallenge(siteKey, ip, difficulty) {
|
|
3188
4075
|
return this.pow.generate(siteKey, ip, difficulty);
|
|
3189
4076
|
}
|
|
3190
4077
|
/**
|
|
3191
4078
|
* Verify a submission: checks the signals commitment, verifies PoW, scores the
|
|
3192
4079
|
* signals, and issues a session token on success. Mirrors `runVerification`.
|
|
3193
4080
|
*/
|
|
3194
|
-
verify(input) {
|
|
4081
|
+
async verify(input) {
|
|
3195
4082
|
const { siteKey, ip, userAgent } = input;
|
|
3196
4083
|
const headers = input.headers ?? {};
|
|
3197
4084
|
let signals = input.signals ?? {};
|
|
3198
4085
|
const extraDetections = [];
|
|
3199
4086
|
const clientSignalsHash = input.powSolution?.signalsHash ?? null;
|
|
3200
4087
|
if (input.signalsJson && clientSignalsHash) {
|
|
3201
|
-
const computed =
|
|
4088
|
+
const computed = await sha256Hex(input.signalsJson);
|
|
3202
4089
|
if (computed !== clientSignalsHash) {
|
|
3203
4090
|
extraDetections.push({
|
|
3204
4091
|
category: "bot",
|
|
@@ -3217,7 +4104,7 @@ var Captcha = class {
|
|
|
3217
4104
|
}
|
|
3218
4105
|
let pow;
|
|
3219
4106
|
if (input.powSolution && input.powSolution.challengeId) {
|
|
3220
|
-
const result = this.pow.verify(input.powSolution, siteKey, clientSignalsHash);
|
|
4107
|
+
const result = await this.pow.verify(input.powSolution, siteKey, clientSignalsHash);
|
|
3221
4108
|
pow = {
|
|
3222
4109
|
provided: true,
|
|
3223
4110
|
valid: result.valid,
|
|
@@ -3238,12 +4125,12 @@ var Captcha = class {
|
|
|
3238
4125
|
pow,
|
|
3239
4126
|
extraDetections
|
|
3240
4127
|
});
|
|
3241
|
-
const token = verdict.success ? this.tokens.issue(ip, siteKey, verdict.score) : null;
|
|
4128
|
+
const token = verdict.success ? await this.tokens.issue(ip, siteKey, verdict.score) : null;
|
|
3242
4129
|
return { ...verdict, token };
|
|
3243
4130
|
}
|
|
3244
4131
|
/** Invisible-mode scoring — same pipeline, returns a compact result + action. */
|
|
3245
|
-
score(input) {
|
|
3246
|
-
const result = this.verify(input);
|
|
4132
|
+
async score(input) {
|
|
4133
|
+
const result = await this.verify(input);
|
|
3247
4134
|
return {
|
|
3248
4135
|
success: result.success,
|
|
3249
4136
|
score: result.score,
|
|
@@ -3253,7 +4140,7 @@ var Captcha = class {
|
|
|
3253
4140
|
};
|
|
3254
4141
|
}
|
|
3255
4142
|
/** Verify a previously issued token (single-use, optionally IP-bound). */
|
|
3256
|
-
verifyToken(token, ip = null) {
|
|
4143
|
+
async verifyToken(token, ip = null) {
|
|
3257
4144
|
return this.tokens.verify(token, ip);
|
|
3258
4145
|
}
|
|
3259
4146
|
};
|
|
@@ -3280,11 +4167,11 @@ function createCaptchaEndpoints(options = {}) {
|
|
|
3280
4167
|
const ja3Hash = req.headers["x-ja3-hash"] ?? null;
|
|
3281
4168
|
if (sub === "/challenge" && method === "GET") {
|
|
3282
4169
|
const siteKey = req.query.siteKey ?? "default";
|
|
3283
|
-
return json(200, captcha.issueChallenge(siteKey, req.ip));
|
|
4170
|
+
return json(200, await captcha.issueChallenge(siteKey, req.ip));
|
|
3284
4171
|
}
|
|
3285
4172
|
if (sub === "/verify" && method === "POST") {
|
|
3286
4173
|
const b = req.body ?? {};
|
|
3287
|
-
const result = captcha.verify({
|
|
4174
|
+
const result = await captcha.verify({
|
|
3288
4175
|
siteKey: b.siteKey ?? "default",
|
|
3289
4176
|
ip: req.ip,
|
|
3290
4177
|
userAgent,
|
|
@@ -3299,7 +4186,7 @@ function createCaptchaEndpoints(options = {}) {
|
|
|
3299
4186
|
}
|
|
3300
4187
|
if (sub === "/score" && method === "POST") {
|
|
3301
4188
|
const b = req.body ?? {};
|
|
3302
|
-
const result = captcha.score({
|
|
4189
|
+
const result = await captcha.score({
|
|
3303
4190
|
siteKey: b.siteKey ?? "default",
|
|
3304
4191
|
ip: req.ip,
|
|
3305
4192
|
userAgent,
|
|
@@ -3316,17 +4203,22 @@ function createCaptchaEndpoints(options = {}) {
|
|
|
3316
4203
|
if (sub === "/token/verify" && method === "POST") {
|
|
3317
4204
|
const b = req.body ?? {};
|
|
3318
4205
|
if (!b.token) return json(400, { valid: false, reason: "missing_token" });
|
|
3319
|
-
return json(200, captcha.verifyToken(b.token, req.ip));
|
|
4206
|
+
return json(200, await captcha.verifyToken(b.token, req.ip));
|
|
3320
4207
|
}
|
|
3321
4208
|
return json(404, { error: "not_found" });
|
|
3322
4209
|
}
|
|
3323
4210
|
return { captcha, basePath: base, handle };
|
|
3324
4211
|
}
|
|
3325
4212
|
export {
|
|
4213
|
+
AgentVerifier,
|
|
3326
4214
|
Captcha,
|
|
4215
|
+
DEFAULT_SIGNED_AGENT_DIRECTORIES,
|
|
3327
4216
|
DEFAULT_TRIPWIRE_PATHS,
|
|
3328
4217
|
DEFAULT_WEIGHTS,
|
|
3329
4218
|
DetectionEngine,
|
|
4219
|
+
DirectoryCache,
|
|
4220
|
+
EDGE_CLASS_HEADER,
|
|
4221
|
+
EDGE_CLEARANCE_HEADER,
|
|
3330
4222
|
FilterRule,
|
|
3331
4223
|
InMemoryChallengeStore,
|
|
3332
4224
|
InMemoryFingerprintStore,
|
|
@@ -3337,9 +4229,11 @@ export {
|
|
|
3337
4229
|
RuleEngine,
|
|
3338
4230
|
TokenManager,
|
|
3339
4231
|
TripwireRule,
|
|
4232
|
+
WebBotAuthRule,
|
|
3340
4233
|
WebDecoy,
|
|
3341
4234
|
calculateCategoryScores,
|
|
3342
4235
|
calculateFinalScore,
|
|
4236
|
+
createAgentVerifier,
|
|
3343
4237
|
createCaptchaEndpoints,
|
|
3344
4238
|
filter,
|
|
3345
4239
|
honeytoken,
|
|
@@ -3347,7 +4241,9 @@ export {
|
|
|
3347
4241
|
isMobileUA,
|
|
3348
4242
|
parseUserAgent,
|
|
3349
4243
|
rateLimit,
|
|
4244
|
+
readEdgeVerdict,
|
|
3350
4245
|
recommend,
|
|
3351
4246
|
resolveSecret,
|
|
3352
|
-
tripwire
|
|
4247
|
+
tripwire,
|
|
4248
|
+
webBotAuth
|
|
3353
4249
|
};
|