@webdecoy/node 0.4.1 → 0.5.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 +382 -13
- package/dist/index.d.ts +382 -13
- package/dist/index.js +962 -137
- package/dist/index.mjs +954 -125
- 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,603 @@ 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
|
+
|
|
425
1038
|
// src/sdk.ts
|
|
426
1039
|
var WebDecoy = class {
|
|
427
1040
|
constructor(config) {
|
|
428
1041
|
this.violationReporter = null;
|
|
429
1042
|
this.ipEnrichmentClient = null;
|
|
430
1043
|
this._hasFilterRules = false;
|
|
1044
|
+
this._hasAgentRules = false;
|
|
1045
|
+
this.agentVerifier = null;
|
|
431
1046
|
const hasApiKey = !!config.apiKey;
|
|
432
1047
|
if (hasApiKey) {
|
|
433
1048
|
if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
|
|
@@ -459,11 +1074,16 @@ var WebDecoy = class {
|
|
|
459
1074
|
console.log("[WebDecoy] Running in local-only mode (no API key). Rules will still evaluate.");
|
|
460
1075
|
}
|
|
461
1076
|
}
|
|
1077
|
+
this.webBotAuthOptions = config.webBotAuth;
|
|
462
1078
|
if (config.rules && config.rules.length > 0) {
|
|
463
1079
|
this.ruleEngine = new RuleEngine(config.rules);
|
|
464
1080
|
this._hasFilterRules = config.rules.some(
|
|
465
1081
|
(r) => r.name.startsWith("filter:")
|
|
466
1082
|
);
|
|
1083
|
+
this._hasAgentRules = config.rules.some((r) => r.name === "web-bot-auth");
|
|
1084
|
+
if (this._hasAgentRules) {
|
|
1085
|
+
this.getAgentVerifier().warmup();
|
|
1086
|
+
}
|
|
467
1087
|
} else {
|
|
468
1088
|
this.ruleEngine = null;
|
|
469
1089
|
}
|
|
@@ -492,27 +1112,21 @@ var WebDecoy = class {
|
|
|
492
1112
|
*/
|
|
493
1113
|
evaluateRules(metadata) {
|
|
494
1114
|
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;
|
|
1115
|
+
return this.runRules(this.buildContext(metadata));
|
|
508
1116
|
}
|
|
509
1117
|
/**
|
|
510
|
-
* Evaluate rules with async IP enrichment
|
|
511
|
-
* Use this instead of evaluateRules() when filter rules
|
|
1118
|
+
* Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth
|
|
1119
|
+
* verification). Use this instead of evaluateRules() when filter rules or
|
|
1120
|
+
* webBotAuth() rules are present.
|
|
512
1121
|
*/
|
|
513
1122
|
async evaluateRulesAsync(metadata) {
|
|
514
1123
|
if (!this.ruleEngine) return null;
|
|
515
|
-
const context =
|
|
1124
|
+
const context = await this.buildAsyncContext(metadata);
|
|
1125
|
+
return this.runRules(context);
|
|
1126
|
+
}
|
|
1127
|
+
/** Build the base (synchronous) rule context from request metadata. */
|
|
1128
|
+
buildContext(metadata) {
|
|
1129
|
+
return {
|
|
516
1130
|
ip: metadata.ip,
|
|
517
1131
|
path: metadata.path,
|
|
518
1132
|
method: metadata.method,
|
|
@@ -520,24 +1134,85 @@ var WebDecoy = class {
|
|
|
520
1134
|
headers: metadata.headers,
|
|
521
1135
|
timestamp: metadata.timestamp || Date.now()
|
|
522
1136
|
};
|
|
1137
|
+
}
|
|
1138
|
+
/**
|
|
1139
|
+
* Build a rule context with async signals resolved: IP enrichment (for
|
|
1140
|
+
* filter rules) and the Web Bot Auth verdict (for webBotAuth() rules).
|
|
1141
|
+
*/
|
|
1142
|
+
async buildAsyncContext(metadata) {
|
|
1143
|
+
const context = this.buildContext(metadata);
|
|
523
1144
|
if (this._hasFilterRules && this.ipEnrichmentClient) {
|
|
524
1145
|
const enrichment = await this.ipEnrichmentClient.enrich(metadata.ip);
|
|
525
1146
|
if (enrichment) {
|
|
526
1147
|
context.enrichment = enrichment;
|
|
527
1148
|
}
|
|
528
1149
|
}
|
|
1150
|
+
if (this._hasAgentRules) {
|
|
1151
|
+
context.agent = await this.computeAgentVerdict(metadata);
|
|
1152
|
+
}
|
|
1153
|
+
return context;
|
|
1154
|
+
}
|
|
1155
|
+
/** Evaluate rules against a prepared context and report any violations. */
|
|
1156
|
+
runRules(context) {
|
|
1157
|
+
if (!this.ruleEngine) return null;
|
|
529
1158
|
const result = this.ruleEngine.evaluate(context);
|
|
530
1159
|
if (result.violations.length > 0 && this.violationReporter) {
|
|
531
1160
|
this.violationReporter.report(result.violations);
|
|
532
1161
|
}
|
|
533
1162
|
return result;
|
|
534
1163
|
}
|
|
1164
|
+
/** Lazily construct the shared Web Bot Auth verifier (one directory cache). */
|
|
1165
|
+
getAgentVerifier() {
|
|
1166
|
+
if (!this.agentVerifier) {
|
|
1167
|
+
this.agentVerifier = new AgentVerifier({
|
|
1168
|
+
debug: this.config.debug,
|
|
1169
|
+
...this.webBotAuthOptions
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
return this.agentVerifier;
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* Verify a request's Web Bot Auth signature locally, deriving the request
|
|
1176
|
+
* URL/authority from its metadata. Returns undefined when the request lacks
|
|
1177
|
+
* the host information needed to verify (verdict is then simply absent).
|
|
1178
|
+
*/
|
|
1179
|
+
async computeAgentVerdict(metadata) {
|
|
1180
|
+
const input = agentInputFromMetadata(metadata);
|
|
1181
|
+
if (!input) return void 0;
|
|
1182
|
+
return this.getAgentVerifier().verify(input);
|
|
1183
|
+
}
|
|
1184
|
+
/**
|
|
1185
|
+
* Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag
|
|
1186
|
+
* "web-bot-auth"). Returns whether it is a cryptographically `verified`
|
|
1187
|
+
* agent, an `impersonation` of a known one, an unverifiable `claimed`
|
|
1188
|
+
* signature, or `none`. No network on the warm path.
|
|
1189
|
+
*
|
|
1190
|
+
* Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }`
|
|
1191
|
+
* object (Node).
|
|
1192
|
+
*
|
|
1193
|
+
* @example
|
|
1194
|
+
* ```ts
|
|
1195
|
+
* const verdict = await webdecoy.detectBot(request);
|
|
1196
|
+
* if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 });
|
|
1197
|
+
* if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName);
|
|
1198
|
+
* ```
|
|
1199
|
+
*/
|
|
1200
|
+
async detectBot(request) {
|
|
1201
|
+
return this.getAgentVerifier().verify(request);
|
|
1202
|
+
}
|
|
535
1203
|
/**
|
|
536
1204
|
* Whether this SDK instance has filter rules that need async enrichment
|
|
537
1205
|
*/
|
|
538
1206
|
get hasFilterRules() {
|
|
539
1207
|
return this._hasFilterRules;
|
|
540
1208
|
}
|
|
1209
|
+
/**
|
|
1210
|
+
* Whether this SDK instance has Web Bot Auth rules that need async
|
|
1211
|
+
* verification before evaluation.
|
|
1212
|
+
*/
|
|
1213
|
+
get hasAgentRules() {
|
|
1214
|
+
return this._hasAgentRules;
|
|
1215
|
+
}
|
|
541
1216
|
/**
|
|
542
1217
|
* Protect a request by checking it against Web Decoy's bot detection
|
|
543
1218
|
*
|
|
@@ -553,7 +1228,15 @@ var WebDecoy = class {
|
|
|
553
1228
|
if (!metadata.timestamp) {
|
|
554
1229
|
metadata.timestamp = Date.now();
|
|
555
1230
|
}
|
|
556
|
-
|
|
1231
|
+
let ruleResult;
|
|
1232
|
+
let agentVerdict;
|
|
1233
|
+
if (this.ruleEngine && (this._hasFilterRules || this._hasAgentRules)) {
|
|
1234
|
+
const context = await this.buildAsyncContext(metadata);
|
|
1235
|
+
agentVerdict = context.agent;
|
|
1236
|
+
ruleResult = this.runRules(context);
|
|
1237
|
+
} else {
|
|
1238
|
+
ruleResult = this.evaluateRules(metadata);
|
|
1239
|
+
}
|
|
557
1240
|
if (ruleResult && ruleResult.action === "DENY") {
|
|
558
1241
|
return {
|
|
559
1242
|
allowed: false,
|
|
@@ -565,7 +1248,8 @@ var WebDecoy = class {
|
|
|
565
1248
|
detection_id: "rule_" + Date.now(),
|
|
566
1249
|
rule_enforced: true
|
|
567
1250
|
},
|
|
568
|
-
ruleResult
|
|
1251
|
+
ruleResult,
|
|
1252
|
+
agent: agentVerdict
|
|
569
1253
|
};
|
|
570
1254
|
}
|
|
571
1255
|
if (ruleResult && ruleResult.action === "THROTTLE") {
|
|
@@ -579,7 +1263,8 @@ var WebDecoy = class {
|
|
|
579
1263
|
detection_id: "rule_" + Date.now(),
|
|
580
1264
|
rule_enforced: true
|
|
581
1265
|
},
|
|
582
|
-
ruleResult
|
|
1266
|
+
ruleResult,
|
|
1267
|
+
agent: agentVerdict
|
|
583
1268
|
};
|
|
584
1269
|
}
|
|
585
1270
|
if (!this.client) {
|
|
@@ -593,7 +1278,8 @@ var WebDecoy = class {
|
|
|
593
1278
|
detection_id: "local_" + Date.now(),
|
|
594
1279
|
rule_enforced: false
|
|
595
1280
|
},
|
|
596
|
-
ruleResult: ruleResult ?? void 0
|
|
1281
|
+
ruleResult: ruleResult ?? void 0,
|
|
1282
|
+
agent: agentVerdict
|
|
597
1283
|
};
|
|
598
1284
|
}
|
|
599
1285
|
const localAnalysis = options.skipLocalAnalysis ? {
|
|
@@ -623,7 +1309,8 @@ var WebDecoy = class {
|
|
|
623
1309
|
detection_id: "local_" + Date.now(),
|
|
624
1310
|
rule_enforced: false
|
|
625
1311
|
},
|
|
626
|
-
ruleResult: ruleResult ?? void 0
|
|
1312
|
+
ruleResult: ruleResult ?? void 0,
|
|
1313
|
+
agent: agentVerdict
|
|
627
1314
|
};
|
|
628
1315
|
}
|
|
629
1316
|
const detection = await this.client.detect(detectionRequest);
|
|
@@ -639,7 +1326,8 @@ var WebDecoy = class {
|
|
|
639
1326
|
return {
|
|
640
1327
|
allowed,
|
|
641
1328
|
detection,
|
|
642
|
-
ruleResult: ruleResult ?? void 0
|
|
1329
|
+
ruleResult: ruleResult ?? void 0,
|
|
1330
|
+
agent: agentVerdict
|
|
643
1331
|
};
|
|
644
1332
|
} catch (error) {
|
|
645
1333
|
if (this.config.debug) {
|
|
@@ -707,6 +1395,24 @@ var WebDecoy = class {
|
|
|
707
1395
|
}
|
|
708
1396
|
}
|
|
709
1397
|
};
|
|
1398
|
+
function agentInputFromMetadata(metadata) {
|
|
1399
|
+
const headers = metadata.headers || {};
|
|
1400
|
+
const host = headers["host"] || headers[":authority"] || headers["x-forwarded-host"] || headers["Host"];
|
|
1401
|
+
if (!host) return null;
|
|
1402
|
+
const proto = headers["x-forwarded-proto"] || headers["X-Forwarded-Proto"];
|
|
1403
|
+
const scheme = (proto ? proto.split(",")[0].trim() : "https") || "https";
|
|
1404
|
+
const rawPath = metadata.path || "/";
|
|
1405
|
+
const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
|
|
1406
|
+
try {
|
|
1407
|
+
return {
|
|
1408
|
+
method: metadata.method,
|
|
1409
|
+
url: `${scheme}://${host}${path}`,
|
|
1410
|
+
headers
|
|
1411
|
+
};
|
|
1412
|
+
} catch {
|
|
1413
|
+
return null;
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
710
1416
|
|
|
711
1417
|
// src/rules/rate-limiter.ts
|
|
712
1418
|
var InMemoryRateLimiter = class {
|
|
@@ -1338,11 +2044,133 @@ var TripwireRule = class {
|
|
|
1338
2044
|
}
|
|
1339
2045
|
};
|
|
1340
2046
|
|
|
2047
|
+
// src/rules/web-bot-auth-rule.ts
|
|
2048
|
+
var WebBotAuthRule = class {
|
|
2049
|
+
constructor(config = {}) {
|
|
2050
|
+
this.name = "web-bot-auth";
|
|
2051
|
+
this.onImpersonation = config.onImpersonation ?? "DENY";
|
|
2052
|
+
this.onClaimed = config.onClaimed ?? "ALLOW";
|
|
2053
|
+
this.allowCategories = config.allowCategories ? new Set(config.allowCategories) : void 0;
|
|
2054
|
+
this.dryRun = config.dryRun ?? false;
|
|
2055
|
+
}
|
|
2056
|
+
evaluate(context) {
|
|
2057
|
+
const verdict = context.agent;
|
|
2058
|
+
if (!verdict || verdict.status === "none") return this.allow();
|
|
2059
|
+
if (verdict.status === "impersonation") {
|
|
2060
|
+
return this.act(this.onImpersonation, "agent_impersonation", {
|
|
2061
|
+
agentName: verdict.agentName,
|
|
2062
|
+
category: verdict.category,
|
|
2063
|
+
keyId: verdict.keyId,
|
|
2064
|
+
detail: verdict.reason
|
|
2065
|
+
});
|
|
2066
|
+
}
|
|
2067
|
+
if (verdict.status === "claimed") {
|
|
2068
|
+
return this.act(this.onClaimed, "agent_unverifiable", {
|
|
2069
|
+
keyId: verdict.keyId,
|
|
2070
|
+
detail: verdict.reason
|
|
2071
|
+
});
|
|
2072
|
+
}
|
|
2073
|
+
if (this.allowCategories && verdict.category && !this.allowCategories.has(verdict.category)) {
|
|
2074
|
+
return this.act(this.onClaimed, "agent_category_not_allowed", {
|
|
2075
|
+
agentName: verdict.agentName,
|
|
2076
|
+
category: verdict.category,
|
|
2077
|
+
keyId: verdict.keyId
|
|
2078
|
+
});
|
|
2079
|
+
}
|
|
2080
|
+
return this.allow();
|
|
2081
|
+
}
|
|
2082
|
+
act(action, verdict, detail) {
|
|
2083
|
+
if (action === "ALLOW") return this.allow();
|
|
2084
|
+
return {
|
|
2085
|
+
action: this.dryRun ? "ALLOW" : action,
|
|
2086
|
+
rule: this.name,
|
|
2087
|
+
reason: reasonFor(verdict),
|
|
2088
|
+
metadata: { verdict, dryRun: this.dryRun, ...detail }
|
|
2089
|
+
};
|
|
2090
|
+
}
|
|
2091
|
+
allow() {
|
|
2092
|
+
return { action: "ALLOW", rule: this.name };
|
|
2093
|
+
}
|
|
2094
|
+
};
|
|
2095
|
+
function reasonFor(verdict) {
|
|
2096
|
+
switch (verdict) {
|
|
2097
|
+
case "agent_impersonation":
|
|
2098
|
+
return "Web Bot Auth signature failed verification (agent impersonation)";
|
|
2099
|
+
case "agent_unverifiable":
|
|
2100
|
+
return "Web Bot Auth signature could not be verified";
|
|
2101
|
+
case "agent_category_not_allowed":
|
|
2102
|
+
return "Verified agent category is not allowed";
|
|
2103
|
+
default:
|
|
2104
|
+
return "Web Bot Auth rule triggered";
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
function webBotAuth(config = {}) {
|
|
2108
|
+
return new WebBotAuthRule(config);
|
|
2109
|
+
}
|
|
2110
|
+
|
|
2111
|
+
// src/webcrypto.ts
|
|
2112
|
+
var encoder3 = new TextEncoder();
|
|
2113
|
+
function toHex(bytes) {
|
|
2114
|
+
let hex = "";
|
|
2115
|
+
for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
|
|
2116
|
+
return hex;
|
|
2117
|
+
}
|
|
2118
|
+
async function sha256Hex(data) {
|
|
2119
|
+
const digest2 = await crypto.subtle.digest("SHA-256", encoder3.encode(data));
|
|
2120
|
+
return toHex(new Uint8Array(digest2));
|
|
2121
|
+
}
|
|
2122
|
+
async function hmacSha256Hex(secret, data) {
|
|
2123
|
+
const key = await crypto.subtle.importKey(
|
|
2124
|
+
"raw",
|
|
2125
|
+
encoder3.encode(secret),
|
|
2126
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
2127
|
+
false,
|
|
2128
|
+
["sign"]
|
|
2129
|
+
);
|
|
2130
|
+
const sig = await crypto.subtle.sign("HMAC", key, encoder3.encode(data));
|
|
2131
|
+
return toHex(new Uint8Array(sig));
|
|
2132
|
+
}
|
|
2133
|
+
function randomHex(bytes) {
|
|
2134
|
+
const buf = new Uint8Array(bytes);
|
|
2135
|
+
crypto.getRandomValues(buf);
|
|
2136
|
+
return toHex(buf);
|
|
2137
|
+
}
|
|
2138
|
+
function timingSafeEqualStr(a, b) {
|
|
2139
|
+
if (a.length !== b.length) return false;
|
|
2140
|
+
let diff = 0;
|
|
2141
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
2142
|
+
return diff === 0;
|
|
2143
|
+
}
|
|
2144
|
+
function base64urlEncode(data) {
|
|
2145
|
+
const bytes = encoder3.encode(data);
|
|
2146
|
+
let binary = "";
|
|
2147
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
|
2148
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
2149
|
+
}
|
|
2150
|
+
function base64urlDecode(data) {
|
|
2151
|
+
const b64 = data.replace(/-/g, "+").replace(/_/g, "/");
|
|
2152
|
+
const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
|
|
2153
|
+
const binary = atob(padded);
|
|
2154
|
+
const bytes = new Uint8Array(binary.length);
|
|
2155
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
2156
|
+
return new TextDecoder().decode(bytes);
|
|
2157
|
+
}
|
|
2158
|
+
function fnv1a64Hex(data) {
|
|
2159
|
+
const PRIME = 0x100000001b3n;
|
|
2160
|
+
const MASK = 0xffffffffffffffffn;
|
|
2161
|
+
let hash = 0xcbf29ce484222325n;
|
|
2162
|
+
const bytes = encoder3.encode(data);
|
|
2163
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
2164
|
+
hash ^= BigInt(bytes[i]);
|
|
2165
|
+
hash = hash * PRIME & MASK;
|
|
2166
|
+
}
|
|
2167
|
+
return hash.toString(16).padStart(16, "0");
|
|
2168
|
+
}
|
|
2169
|
+
|
|
1341
2170
|
// src/rules/honeytoken.ts
|
|
1342
|
-
import { randomBytes } from "crypto";
|
|
1343
2171
|
function honeytoken(options = {}) {
|
|
1344
2172
|
const base = (options.basePath ?? "/__wd").replace(/\/+$/, "");
|
|
1345
|
-
const token = options.token ??
|
|
2173
|
+
const token = options.token ?? randomHex(6);
|
|
1346
2174
|
const path = `${base}/${token}`;
|
|
1347
2175
|
const text = options.text ?? ".";
|
|
1348
2176
|
const linkHtml = `<a href="${path}" aria-hidden="true" tabindex="-1" rel="nofollow noindex" style="position:absolute;left:-9999px;top:auto;width:1px;height:1px;overflow:hidden">${text}</a>`;
|
|
@@ -1389,7 +2217,10 @@ var AUTOMATION_UA_PATTERNS = [
|
|
|
1389
2217
|
];
|
|
1390
2218
|
|
|
1391
2219
|
// src/detection/ip.ts
|
|
1392
|
-
|
|
2220
|
+
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}$/;
|
|
2221
|
+
function isIPv4(ip) {
|
|
2222
|
+
return IPV4_RE.test(ip);
|
|
2223
|
+
}
|
|
1393
2224
|
var DATACENTER_CIDRS = [
|
|
1394
2225
|
// AWS
|
|
1395
2226
|
"3.0.0.0/8",
|
|
@@ -2073,7 +2904,6 @@ function detectTouchKinematics(signals) {
|
|
|
2073
2904
|
}
|
|
2074
2905
|
|
|
2075
2906
|
// src/detection/detectors/fingerprint.ts
|
|
2076
|
-
import { createHash } from "crypto";
|
|
2077
2907
|
function detectFingerprint(signals, ip, siteKey, store) {
|
|
2078
2908
|
const detections = [];
|
|
2079
2909
|
const env = signals.environmental ?? {};
|
|
@@ -2084,7 +2914,7 @@ function detectFingerprint(signals, ip, siteKey, store) {
|
|
|
2084
2914
|
String(automation.platform ?? ""),
|
|
2085
2915
|
String(automation.hardwareConcurrency ?? "")
|
|
2086
2916
|
];
|
|
2087
|
-
const fp =
|
|
2917
|
+
const fp = fnv1a64Hex(components.join("|"));
|
|
2088
2918
|
store.record(fp, ip, siteKey);
|
|
2089
2919
|
if (store.getIpFpCount(ip) > 5) {
|
|
2090
2920
|
detections.push({
|
|
@@ -2966,9 +3796,6 @@ var DetectionEngine = class {
|
|
|
2966
3796
|
}
|
|
2967
3797
|
};
|
|
2968
3798
|
|
|
2969
|
-
// src/captcha/service.ts
|
|
2970
|
-
import { createHash as createHash4 } from "crypto";
|
|
2971
|
-
|
|
2972
3799
|
// src/captcha/secret.ts
|
|
2973
3800
|
var INSECURE_DEFAULT_SECRET = "dev-secret-change-in-production";
|
|
2974
3801
|
function resolveSecret(secret) {
|
|
@@ -2990,7 +3817,6 @@ function resolveSecret(secret) {
|
|
|
2990
3817
|
}
|
|
2991
3818
|
|
|
2992
3819
|
// src/captcha/pow.ts
|
|
2993
|
-
import { createHash as createHash2, createHmac, randomBytes as randomBytes2 } from "crypto";
|
|
2994
3820
|
var EXPIRATION_MS = 5 * 60 * 1e3;
|
|
2995
3821
|
var InMemoryChallengeStore = class {
|
|
2996
3822
|
constructor() {
|
|
@@ -3036,10 +3862,10 @@ var PoWManager = class {
|
|
|
3036
3862
|
return difficulty;
|
|
3037
3863
|
}
|
|
3038
3864
|
/** Generate and store a signed challenge. */
|
|
3039
|
-
generate(siteKey, ip, difficulty) {
|
|
3865
|
+
async generate(siteKey, ip, difficulty) {
|
|
3040
3866
|
const resolvedDifficulty = difficulty ?? this.scaleDifficulty(siteKey, ip);
|
|
3041
|
-
const challengeId =
|
|
3042
|
-
const nonce =
|
|
3867
|
+
const challengeId = randomHex(16);
|
|
3868
|
+
const nonce = randomHex(16);
|
|
3043
3869
|
const timestamp = Date.now();
|
|
3044
3870
|
const expiresAt = timestamp + EXPIRATION_MS;
|
|
3045
3871
|
const challengeData = {
|
|
@@ -3054,12 +3880,12 @@ var PoWManager = class {
|
|
|
3054
3880
|
};
|
|
3055
3881
|
const { sig: _omit, ...toSign } = challengeData;
|
|
3056
3882
|
void _omit;
|
|
3057
|
-
challengeData.sig =
|
|
3883
|
+
challengeData.sig = await hmacSha256Hex(this.secret, JSON.stringify(toSign));
|
|
3058
3884
|
this.store.put({ ...challengeData, ip, createdAt: timestamp });
|
|
3059
3885
|
return challengeData;
|
|
3060
3886
|
}
|
|
3061
3887
|
/** Verify a submitted solution. `signalsHash` binds it to the signals. */
|
|
3062
|
-
verify(solution, siteKey, signalsHash = null) {
|
|
3888
|
+
async verify(solution, siteKey, signalsHash = null) {
|
|
3063
3889
|
const challenge = this.store.get(solution.challengeId);
|
|
3064
3890
|
if (!challenge) return { valid: false, reason: "challenge_not_found" };
|
|
3065
3891
|
if (Date.now() > challenge.expiresAt) {
|
|
@@ -3071,7 +3897,7 @@ var PoWManager = class {
|
|
|
3071
3897
|
}
|
|
3072
3898
|
const solutionKey = `${solution.challengeId}:${solution.nonce}`;
|
|
3073
3899
|
const input = signalsHash ? `${challenge.prefix}:${signalsHash}:${solution.nonce}` : `${challenge.prefix}:${solution.nonce}`;
|
|
3074
|
-
const expectedHash =
|
|
3900
|
+
const expectedHash = await sha256Hex(input);
|
|
3075
3901
|
if (solution.hash !== expectedHash) {
|
|
3076
3902
|
return { valid: false, reason: "invalid_hash" };
|
|
3077
3903
|
}
|
|
@@ -3093,7 +3919,6 @@ var PoWManager = class {
|
|
|
3093
3919
|
};
|
|
3094
3920
|
|
|
3095
3921
|
// src/captcha/token.ts
|
|
3096
|
-
import { createHash as createHash3, createHmac as createHmac2, timingSafeEqual } from "crypto";
|
|
3097
3922
|
var TOKEN_TTL_SECONDS = 300;
|
|
3098
3923
|
var InMemoryTokenStore = class {
|
|
3099
3924
|
constructor() {
|
|
@@ -3115,22 +3940,22 @@ var TokenManager = class {
|
|
|
3115
3940
|
this.store = options.store ?? new InMemoryTokenStore();
|
|
3116
3941
|
}
|
|
3117
3942
|
/** Issue a signed, IP-bound token for a passing request. */
|
|
3118
|
-
issue(ip, siteKey, score) {
|
|
3943
|
+
async issue(ip, siteKey, score) {
|
|
3119
3944
|
const data = {
|
|
3120
3945
|
site_key: siteKey,
|
|
3121
3946
|
timestamp: Math.floor(Date.now() / 1e3),
|
|
3122
3947
|
score: Math.round(score * 1e3) / 1e3,
|
|
3123
|
-
ip_hash:
|
|
3948
|
+
ip_hash: (await sha256Hex(ip)).slice(0, 8)
|
|
3124
3949
|
};
|
|
3125
3950
|
const payload = JSON.stringify(data, Object.keys(data).sort());
|
|
3126
|
-
data.sig =
|
|
3127
|
-
return
|
|
3951
|
+
data.sig = await hmacSha256Hex(this.secret, payload);
|
|
3952
|
+
return base64urlEncode(JSON.stringify(data));
|
|
3128
3953
|
}
|
|
3129
3954
|
/** Verify a token: signature, expiry, replay, and optional IP binding. */
|
|
3130
|
-
verify(token, ip = null) {
|
|
3955
|
+
async verify(token, ip = null) {
|
|
3131
3956
|
let decoded;
|
|
3132
3957
|
try {
|
|
3133
|
-
decoded = JSON.parse(
|
|
3958
|
+
decoded = JSON.parse(base64urlDecode(token));
|
|
3134
3959
|
} catch (e) {
|
|
3135
3960
|
return { valid: false, reason: e instanceof Error ? e.message : "invalid_token" };
|
|
3136
3961
|
}
|
|
@@ -3141,17 +3966,15 @@ var TokenManager = class {
|
|
|
3141
3966
|
if (!sig) return { valid: false, reason: "invalid_signature" };
|
|
3142
3967
|
delete decoded.sig;
|
|
3143
3968
|
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)) {
|
|
3969
|
+
const expectedSig = await hmacSha256Hex(this.secret, payload);
|
|
3970
|
+
if (!timingSafeEqualStr(sig, expectedSig)) {
|
|
3148
3971
|
return { valid: false, reason: "invalid_signature" };
|
|
3149
3972
|
}
|
|
3150
3973
|
if (this.store.isUsed(sig)) {
|
|
3151
3974
|
return { valid: false, reason: "token_already_used" };
|
|
3152
3975
|
}
|
|
3153
3976
|
if (ip) {
|
|
3154
|
-
const expectedIpHash =
|
|
3977
|
+
const expectedIpHash = (await sha256Hex(ip)).slice(0, 8);
|
|
3155
3978
|
if (decoded.ip_hash !== expectedIpHash) {
|
|
3156
3979
|
return { valid: false, reason: "ip_mismatch" };
|
|
3157
3980
|
}
|
|
@@ -3184,21 +4007,21 @@ var Captcha = class {
|
|
|
3184
4007
|
this.trustedJA4Headers = options.trustedJA4Headers ?? [];
|
|
3185
4008
|
}
|
|
3186
4009
|
/** Issue a PoW challenge for the client to solve (difficulty auto-scaled). */
|
|
3187
|
-
issueChallenge(siteKey, ip, difficulty) {
|
|
4010
|
+
async issueChallenge(siteKey, ip, difficulty) {
|
|
3188
4011
|
return this.pow.generate(siteKey, ip, difficulty);
|
|
3189
4012
|
}
|
|
3190
4013
|
/**
|
|
3191
4014
|
* Verify a submission: checks the signals commitment, verifies PoW, scores the
|
|
3192
4015
|
* signals, and issues a session token on success. Mirrors `runVerification`.
|
|
3193
4016
|
*/
|
|
3194
|
-
verify(input) {
|
|
4017
|
+
async verify(input) {
|
|
3195
4018
|
const { siteKey, ip, userAgent } = input;
|
|
3196
4019
|
const headers = input.headers ?? {};
|
|
3197
4020
|
let signals = input.signals ?? {};
|
|
3198
4021
|
const extraDetections = [];
|
|
3199
4022
|
const clientSignalsHash = input.powSolution?.signalsHash ?? null;
|
|
3200
4023
|
if (input.signalsJson && clientSignalsHash) {
|
|
3201
|
-
const computed =
|
|
4024
|
+
const computed = await sha256Hex(input.signalsJson);
|
|
3202
4025
|
if (computed !== clientSignalsHash) {
|
|
3203
4026
|
extraDetections.push({
|
|
3204
4027
|
category: "bot",
|
|
@@ -3217,7 +4040,7 @@ var Captcha = class {
|
|
|
3217
4040
|
}
|
|
3218
4041
|
let pow;
|
|
3219
4042
|
if (input.powSolution && input.powSolution.challengeId) {
|
|
3220
|
-
const result = this.pow.verify(input.powSolution, siteKey, clientSignalsHash);
|
|
4043
|
+
const result = await this.pow.verify(input.powSolution, siteKey, clientSignalsHash);
|
|
3221
4044
|
pow = {
|
|
3222
4045
|
provided: true,
|
|
3223
4046
|
valid: result.valid,
|
|
@@ -3238,12 +4061,12 @@ var Captcha = class {
|
|
|
3238
4061
|
pow,
|
|
3239
4062
|
extraDetections
|
|
3240
4063
|
});
|
|
3241
|
-
const token = verdict.success ? this.tokens.issue(ip, siteKey, verdict.score) : null;
|
|
4064
|
+
const token = verdict.success ? await this.tokens.issue(ip, siteKey, verdict.score) : null;
|
|
3242
4065
|
return { ...verdict, token };
|
|
3243
4066
|
}
|
|
3244
4067
|
/** Invisible-mode scoring — same pipeline, returns a compact result + action. */
|
|
3245
|
-
score(input) {
|
|
3246
|
-
const result = this.verify(input);
|
|
4068
|
+
async score(input) {
|
|
4069
|
+
const result = await this.verify(input);
|
|
3247
4070
|
return {
|
|
3248
4071
|
success: result.success,
|
|
3249
4072
|
score: result.score,
|
|
@@ -3253,7 +4076,7 @@ var Captcha = class {
|
|
|
3253
4076
|
};
|
|
3254
4077
|
}
|
|
3255
4078
|
/** Verify a previously issued token (single-use, optionally IP-bound). */
|
|
3256
|
-
verifyToken(token, ip = null) {
|
|
4079
|
+
async verifyToken(token, ip = null) {
|
|
3257
4080
|
return this.tokens.verify(token, ip);
|
|
3258
4081
|
}
|
|
3259
4082
|
};
|
|
@@ -3280,11 +4103,11 @@ function createCaptchaEndpoints(options = {}) {
|
|
|
3280
4103
|
const ja3Hash = req.headers["x-ja3-hash"] ?? null;
|
|
3281
4104
|
if (sub === "/challenge" && method === "GET") {
|
|
3282
4105
|
const siteKey = req.query.siteKey ?? "default";
|
|
3283
|
-
return json(200, captcha.issueChallenge(siteKey, req.ip));
|
|
4106
|
+
return json(200, await captcha.issueChallenge(siteKey, req.ip));
|
|
3284
4107
|
}
|
|
3285
4108
|
if (sub === "/verify" && method === "POST") {
|
|
3286
4109
|
const b = req.body ?? {};
|
|
3287
|
-
const result = captcha.verify({
|
|
4110
|
+
const result = await captcha.verify({
|
|
3288
4111
|
siteKey: b.siteKey ?? "default",
|
|
3289
4112
|
ip: req.ip,
|
|
3290
4113
|
userAgent,
|
|
@@ -3299,7 +4122,7 @@ function createCaptchaEndpoints(options = {}) {
|
|
|
3299
4122
|
}
|
|
3300
4123
|
if (sub === "/score" && method === "POST") {
|
|
3301
4124
|
const b = req.body ?? {};
|
|
3302
|
-
const result = captcha.score({
|
|
4125
|
+
const result = await captcha.score({
|
|
3303
4126
|
siteKey: b.siteKey ?? "default",
|
|
3304
4127
|
ip: req.ip,
|
|
3305
4128
|
userAgent,
|
|
@@ -3316,17 +4139,20 @@ function createCaptchaEndpoints(options = {}) {
|
|
|
3316
4139
|
if (sub === "/token/verify" && method === "POST") {
|
|
3317
4140
|
const b = req.body ?? {};
|
|
3318
4141
|
if (!b.token) return json(400, { valid: false, reason: "missing_token" });
|
|
3319
|
-
return json(200, captcha.verifyToken(b.token, req.ip));
|
|
4142
|
+
return json(200, await captcha.verifyToken(b.token, req.ip));
|
|
3320
4143
|
}
|
|
3321
4144
|
return json(404, { error: "not_found" });
|
|
3322
4145
|
}
|
|
3323
4146
|
return { captcha, basePath: base, handle };
|
|
3324
4147
|
}
|
|
3325
4148
|
export {
|
|
4149
|
+
AgentVerifier,
|
|
3326
4150
|
Captcha,
|
|
4151
|
+
DEFAULT_SIGNED_AGENT_DIRECTORIES,
|
|
3327
4152
|
DEFAULT_TRIPWIRE_PATHS,
|
|
3328
4153
|
DEFAULT_WEIGHTS,
|
|
3329
4154
|
DetectionEngine,
|
|
4155
|
+
DirectoryCache,
|
|
3330
4156
|
FilterRule,
|
|
3331
4157
|
InMemoryChallengeStore,
|
|
3332
4158
|
InMemoryFingerprintStore,
|
|
@@ -3337,9 +4163,11 @@ export {
|
|
|
3337
4163
|
RuleEngine,
|
|
3338
4164
|
TokenManager,
|
|
3339
4165
|
TripwireRule,
|
|
4166
|
+
WebBotAuthRule,
|
|
3340
4167
|
WebDecoy,
|
|
3341
4168
|
calculateCategoryScores,
|
|
3342
4169
|
calculateFinalScore,
|
|
4170
|
+
createAgentVerifier,
|
|
3343
4171
|
createCaptchaEndpoints,
|
|
3344
4172
|
filter,
|
|
3345
4173
|
honeytoken,
|
|
@@ -3349,5 +4177,6 @@ export {
|
|
|
3349
4177
|
rateLimit,
|
|
3350
4178
|
recommend,
|
|
3351
4179
|
resolveSecret,
|
|
3352
|
-
tripwire
|
|
4180
|
+
tripwire,
|
|
4181
|
+
webBotAuth
|
|
3353
4182
|
};
|