@valiron/crawler-protection 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +112 -4
- package/dist/cf.d.ts +27 -0
- package/dist/cf.js +53 -0
- package/dist/configuration.d.ts +1 -0
- package/dist/configuration.js +3 -2
- package/dist/controls.d.ts +90 -0
- package/dist/controls.js +339 -0
- package/dist/directory-fetch.d.ts +37 -0
- package/dist/directory-fetch.js +231 -0
- package/dist/guard.d.ts +2 -0
- package/dist/guard.js +16 -8
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/onboarding.d.ts +1 -1
- package/dist/request-log.d.ts +52 -0
- package/dist/request-log.js +128 -0
- package/dist/runtime.d.ts +29 -0
- package/dist/runtime.js +5 -1
- package/dist/telemetry.js +3 -1
- package/dist/verification.d.ts +12 -0
- package/dist/verification.js +18 -2
- package/dist/webbotauth.d.ts +23 -5
- package/dist/webbotauth.js +47 -0
- package/gateway/README.md +6 -2
- package/gateway/service.cjs +8 -4
- package/package.json +6 -2
package/dist/controls.js
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateCrawlerControls = validateCrawlerControls;
|
|
4
|
+
exports.defaultCrawlerControls = defaultCrawlerControls;
|
|
5
|
+
exports.createCrawlerDecisionBuffer = createCrawlerDecisionBuffer;
|
|
6
|
+
exports.createCrawlerControlClient = createCrawlerControlClient;
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const configuration_1 = require("./configuration");
|
|
9
|
+
const label = /^[a-zA-Z0-9_-]{1,64}$/;
|
|
10
|
+
function object(v, keys, name) {
|
|
11
|
+
if (!v ||
|
|
12
|
+
typeof v !== "object" ||
|
|
13
|
+
Array.isArray(v) ||
|
|
14
|
+
Object.keys(v).some((k) => !keys.includes(k)))
|
|
15
|
+
throw Error("Invalid " + name);
|
|
16
|
+
}
|
|
17
|
+
/** Dashboard controls cannot increase locally installed request ceilings or alter work pools. */
|
|
18
|
+
function validateCrawlerControls(raw, policy) {
|
|
19
|
+
(0, configuration_1.assertCrawlerJsonData)(raw);
|
|
20
|
+
const encoded = JSON.stringify(raw);
|
|
21
|
+
if (!encoded || Buffer.byteLength(encoded) > 32768)
|
|
22
|
+
throw Error("Controls too large");
|
|
23
|
+
const c = JSON.parse(encoded);
|
|
24
|
+
object(c, [
|
|
25
|
+
"mode",
|
|
26
|
+
"enforceGroups",
|
|
27
|
+
"defaultAction",
|
|
28
|
+
"unverifiedAction",
|
|
29
|
+
"rules",
|
|
30
|
+
"rates",
|
|
31
|
+
"logging",
|
|
32
|
+
], "controls");
|
|
33
|
+
if (!["observe", "enforce"].includes(c.mode) ||
|
|
34
|
+
!["budget", "deny"].includes(c.defaultAction) ||
|
|
35
|
+
!["budget", "deny"].includes(c.unverifiedAction) ||
|
|
36
|
+
typeof c.logging !== "boolean")
|
|
37
|
+
throw Error("Invalid control defaults");
|
|
38
|
+
if (c.enforceGroups !== undefined &&
|
|
39
|
+
(c.mode !== "enforce" ||
|
|
40
|
+
!Array.isArray(c.enforceGroups) ||
|
|
41
|
+
!c.enforceGroups.length ||
|
|
42
|
+
c.enforceGroups.length > 128 ||
|
|
43
|
+
new Set(c.enforceGroups).size !== c.enforceGroups.length ||
|
|
44
|
+
c.enforceGroups.some((g) => typeof g !== "string" || !Object.hasOwn(policy.routes, g))))
|
|
45
|
+
throw Error("Invalid enforcement groups");
|
|
46
|
+
if (!Array.isArray(c.rules) || c.rules.length > 128)
|
|
47
|
+
throw Error("Invalid crawler rules");
|
|
48
|
+
const seen = new Set();
|
|
49
|
+
for (const r of c.rules) {
|
|
50
|
+
object(r, ["provider", "crawlerClass", "groups", "action"], "rule");
|
|
51
|
+
if (typeof r.provider !== "string" ||
|
|
52
|
+
typeof r.crawlerClass !== "string" ||
|
|
53
|
+
!label.test(r.provider) ||
|
|
54
|
+
!label.test(r.crawlerClass) ||
|
|
55
|
+
(r.action !== "deny" &&
|
|
56
|
+
(!Object.hasOwn(policy.providers, r.provider) ||
|
|
57
|
+
!Object.hasOwn(policy.providers[r.provider].classes, r.crawlerClass))) ||
|
|
58
|
+
!["budget", "deny"].includes(r.action) ||
|
|
59
|
+
!Array.isArray(r.groups) ||
|
|
60
|
+
!r.groups.length ||
|
|
61
|
+
r.groups.length > 128 ||
|
|
62
|
+
new Set(r.groups).size !== r.groups.length)
|
|
63
|
+
throw Error("Unknown crawler or invalid rule");
|
|
64
|
+
for (const group of r.groups) {
|
|
65
|
+
if (typeof group !== "string" || !Object.hasOwn(policy.routes, group))
|
|
66
|
+
throw Error("Unknown route group");
|
|
67
|
+
const id = JSON.stringify([r.provider, r.crawlerClass, group]);
|
|
68
|
+
if (seen.has(id))
|
|
69
|
+
throw Error("Duplicate crawler rule");
|
|
70
|
+
seen.add(id);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
object(c.rates, ["global", "unknown", "perIp", "routes", "providers"], "rates");
|
|
74
|
+
const maxCost = Math.max(...Object.values(policy.routes).map((r) => r.cost));
|
|
75
|
+
const check = (r, ceiling, minimumCost = maxCost) => {
|
|
76
|
+
object(r, ["capacity", "refillPerSecond"], "rate");
|
|
77
|
+
if (!Number.isFinite(r.capacity) ||
|
|
78
|
+
r.capacity < minimumCost ||
|
|
79
|
+
!Number.isFinite(r.refillPerSecond) ||
|
|
80
|
+
r.refillPerSecond <= 0 ||
|
|
81
|
+
r.capacity > ceiling.capacity ||
|
|
82
|
+
r.refillPerSecond > ceiling.refillPerSecond ||
|
|
83
|
+
r.capacity / r.refillPerSecond > 86400)
|
|
84
|
+
throw Error("Rate exceeds installed ceiling or is invalid");
|
|
85
|
+
};
|
|
86
|
+
for (const [key, ceiling] of Object.entries({
|
|
87
|
+
global: policy.globalRate,
|
|
88
|
+
unknown: policy.unknownRate,
|
|
89
|
+
perIp: policy.perIpRate,
|
|
90
|
+
}))
|
|
91
|
+
if (c.rates[key] !== undefined)
|
|
92
|
+
check(c.rates[key], ceiling);
|
|
93
|
+
for (const key of ["routes", "providers"])
|
|
94
|
+
if (c.rates[key] !== undefined) {
|
|
95
|
+
const allowed = key === "routes" ? policy.routes : policy.providers;
|
|
96
|
+
object(c.rates[key], Object.keys(allowed), key);
|
|
97
|
+
for (const [id, r] of Object.entries(c.rates[key])) {
|
|
98
|
+
if (!label.test(id))
|
|
99
|
+
throw Error("Invalid rate identity");
|
|
100
|
+
check(r, allowed[id].rate, key === "routes" ? policy.routes[id].cost : maxCost);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
function freeze(v) {
|
|
104
|
+
if (v && typeof v === "object") {
|
|
105
|
+
Object.values(v).forEach(freeze);
|
|
106
|
+
Object.freeze(v);
|
|
107
|
+
}
|
|
108
|
+
return v;
|
|
109
|
+
}
|
|
110
|
+
return freeze(c);
|
|
111
|
+
}
|
|
112
|
+
function defaultCrawlerControls(configuration) {
|
|
113
|
+
return validateCrawlerControls({
|
|
114
|
+
mode: configuration.rollout?.mode ?? "observe",
|
|
115
|
+
...(configuration.rollout?.mode === "enforce" &&
|
|
116
|
+
configuration.rollout.enforceGroups &&
|
|
117
|
+
configuration.rollout.enforceGroups.length <
|
|
118
|
+
Object.keys(configuration.policy.routes).length
|
|
119
|
+
? { enforceGroups: configuration.rollout.enforceGroups }
|
|
120
|
+
: {}),
|
|
121
|
+
defaultAction: configuration.crawlerAccessDefault ?? "budget",
|
|
122
|
+
unverifiedAction: configuration.unverifiedAccess ?? "budget",
|
|
123
|
+
rules: configuration.crawlerAccess ?? [],
|
|
124
|
+
rates: {},
|
|
125
|
+
logging: false,
|
|
126
|
+
}, configuration.policy);
|
|
127
|
+
}
|
|
128
|
+
/** Separate opt-in bounded log buffer; never retains IP, URL, user agent or caller request IDs. */
|
|
129
|
+
function createCrawlerDecisionBuffer(policy, enabled, now = Date.now) {
|
|
130
|
+
const rows = [];
|
|
131
|
+
let dropped = 0;
|
|
132
|
+
return {
|
|
133
|
+
record(decision, evidence, details) {
|
|
134
|
+
if (!enabled() ||
|
|
135
|
+
!details?.routeGroup ||
|
|
136
|
+
!Object.hasOwn(policy.routes, details.routeGroup))
|
|
137
|
+
return;
|
|
138
|
+
const provider = evidence?.state === "verified" &&
|
|
139
|
+
evidence.provider &&
|
|
140
|
+
Object.hasOwn(policy.providers, evidence.provider)
|
|
141
|
+
? evidence.provider
|
|
142
|
+
: "other";
|
|
143
|
+
const crawlerClass = provider !== "other" &&
|
|
144
|
+
evidence?.crawlerClass &&
|
|
145
|
+
Object.hasOwn(policy.providers[provider].classes, evidence.crawlerClass)
|
|
146
|
+
? evidence.crawlerClass
|
|
147
|
+
: "other";
|
|
148
|
+
if (rows.length >= 1000) {
|
|
149
|
+
dropped++;
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
rows.push({
|
|
153
|
+
id: (0, node_crypto_1.randomUUID)(),
|
|
154
|
+
at: now(),
|
|
155
|
+
group: details.routeGroup,
|
|
156
|
+
provider,
|
|
157
|
+
crawlerClass,
|
|
158
|
+
action: ["allow", "block", "limit", "unavailable"].includes(decision.action)
|
|
159
|
+
? decision.action
|
|
160
|
+
: "unavailable",
|
|
161
|
+
reason: [
|
|
162
|
+
"within_budget",
|
|
163
|
+
"observation_within_safety",
|
|
164
|
+
"crawler_policy_denied",
|
|
165
|
+
"safety_budget_exhausted",
|
|
166
|
+
"rate_budget_exhausted",
|
|
167
|
+
"admission_unavailable",
|
|
168
|
+
].includes(decision.reason)
|
|
169
|
+
? decision.reason
|
|
170
|
+
: "other",
|
|
171
|
+
verification: evidence &&
|
|
172
|
+
[
|
|
173
|
+
"verified",
|
|
174
|
+
"unverified",
|
|
175
|
+
"claim_mismatch",
|
|
176
|
+
"verification_unavailable",
|
|
177
|
+
].includes(evidence.state)
|
|
178
|
+
? evidence.state
|
|
179
|
+
: "verification_unavailable",
|
|
180
|
+
mode: details.mode === "observe" ? "observe" : "enforce",
|
|
181
|
+
});
|
|
182
|
+
},
|
|
183
|
+
batch() {
|
|
184
|
+
return rows.slice(0, 100);
|
|
185
|
+
},
|
|
186
|
+
ack(ids) {
|
|
187
|
+
const set = new Set(ids);
|
|
188
|
+
for (let i = rows.length - 1; i >= 0; i--)
|
|
189
|
+
if (set.has(rows[i].id))
|
|
190
|
+
rows.splice(i, 1);
|
|
191
|
+
},
|
|
192
|
+
clear() {
|
|
193
|
+
rows.length = 0;
|
|
194
|
+
},
|
|
195
|
+
dropped() {
|
|
196
|
+
return dropped;
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/** Memory-only short lease. Dashboard sessions alone publish; requests use cached controls. */
|
|
201
|
+
function createCrawlerControlClient(input) {
|
|
202
|
+
const compiled = (0, configuration_1.compileCrawlerConfiguration)(input.configuration, (input.now ?? Date.now)());
|
|
203
|
+
if (!/^val_op_[a-zA-Z0-9_-]{1,200}$/.test(input.apiKey) ||
|
|
204
|
+
!label.test(input.site))
|
|
205
|
+
throw Error("Invalid control identity");
|
|
206
|
+
const url = new URL(input.endpoint ??
|
|
207
|
+
"https://valiron-edge-proxy.onrender.com/operator/crawlers/control/runtime");
|
|
208
|
+
if ((url.protocol !== "https:" &&
|
|
209
|
+
!(url.protocol === "http:" &&
|
|
210
|
+
["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))) ||
|
|
211
|
+
url.pathname !== "/operator/crawlers/control/runtime" ||
|
|
212
|
+
url.username ||
|
|
213
|
+
url.password ||
|
|
214
|
+
url.search ||
|
|
215
|
+
url.hash)
|
|
216
|
+
throw Error("Invalid control endpoint");
|
|
217
|
+
const instance = (0, node_crypto_1.randomUUID)();
|
|
218
|
+
let lastMode = compiled.configuration.rollout.mode;
|
|
219
|
+
let value, revision = 0, expiresAt = 0, deadline = 0, busy = false, stopped = false, error;
|
|
220
|
+
const now = input.now ?? Date.now;
|
|
221
|
+
const logs = createCrawlerDecisionBuffer(compiled.policy, () => active() && !!value?.logging, now);
|
|
222
|
+
const active = () => !!value && expiresAt > now() && deadline > performance.now() && !stopped;
|
|
223
|
+
async function refresh() {
|
|
224
|
+
if (busy || stopped)
|
|
225
|
+
return;
|
|
226
|
+
busy = true;
|
|
227
|
+
const sent = performance.now();
|
|
228
|
+
const batch = logs.batch();
|
|
229
|
+
try {
|
|
230
|
+
const response = await (input.fetch ?? fetch)(url, {
|
|
231
|
+
method: "POST",
|
|
232
|
+
headers: {
|
|
233
|
+
Authorization: "Bearer " + input.apiKey,
|
|
234
|
+
"Content-Type": "application/json",
|
|
235
|
+
},
|
|
236
|
+
body: JSON.stringify({
|
|
237
|
+
site: input.site,
|
|
238
|
+
instance,
|
|
239
|
+
configuration: compiled.configuration,
|
|
240
|
+
configurationId: compiled.fingerprint,
|
|
241
|
+
revision: active() ? revision : 0,
|
|
242
|
+
logs: batch,
|
|
243
|
+
dropped: logs.dropped(),
|
|
244
|
+
}),
|
|
245
|
+
redirect: "error",
|
|
246
|
+
signal: AbortSignal.timeout(5000),
|
|
247
|
+
});
|
|
248
|
+
if (!response.ok) {
|
|
249
|
+
if ([401, 403, 404, 409].includes(response.status)) {
|
|
250
|
+
value = undefined;
|
|
251
|
+
expiresAt = 0;
|
|
252
|
+
}
|
|
253
|
+
await response.body?.cancel();
|
|
254
|
+
throw Error();
|
|
255
|
+
}
|
|
256
|
+
const reader = response.body?.getReader();
|
|
257
|
+
if (!reader)
|
|
258
|
+
throw Error();
|
|
259
|
+
let size = 0;
|
|
260
|
+
const chunks = [];
|
|
261
|
+
try {
|
|
262
|
+
for (;;) {
|
|
263
|
+
const part = await reader.read();
|
|
264
|
+
if (part.done)
|
|
265
|
+
break;
|
|
266
|
+
size += part.value.length;
|
|
267
|
+
if (size > 65536)
|
|
268
|
+
throw Error();
|
|
269
|
+
chunks.push(part.value);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
finally {
|
|
273
|
+
await reader.cancel().catch(() => { });
|
|
274
|
+
reader.releaseLock();
|
|
275
|
+
}
|
|
276
|
+
const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
277
|
+
object(body, ["revision", "configurationId", "expiresAt", "settings"], "control response");
|
|
278
|
+
if (body.configurationId !== compiled.fingerprint ||
|
|
279
|
+
!Number.isSafeInteger(body.revision) ||
|
|
280
|
+
body.revision < revision ||
|
|
281
|
+
body.revision < 1 ||
|
|
282
|
+
!Number.isSafeInteger(body.expiresAt) ||
|
|
283
|
+
body.expiresAt <= now() ||
|
|
284
|
+
body.expiresAt > now() + 300000)
|
|
285
|
+
throw Error();
|
|
286
|
+
const checked = validateCrawlerControls(body.settings, compiled.policy);
|
|
287
|
+
if (value &&
|
|
288
|
+
body.revision === revision &&
|
|
289
|
+
JSON.stringify(checked) !== JSON.stringify(value))
|
|
290
|
+
throw Error();
|
|
291
|
+
if (stopped)
|
|
292
|
+
return;
|
|
293
|
+
value = checked;
|
|
294
|
+
lastMode = checked.mode;
|
|
295
|
+
revision = body.revision;
|
|
296
|
+
expiresAt = body.expiresAt;
|
|
297
|
+
deadline = sent + Math.min(300000, expiresAt - now());
|
|
298
|
+
error = undefined;
|
|
299
|
+
logs.ack(batch.map((row) => row.id));
|
|
300
|
+
if (!checked.logging)
|
|
301
|
+
logs.clear();
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
error = value ? "rejected" : "unavailable";
|
|
305
|
+
}
|
|
306
|
+
finally {
|
|
307
|
+
busy = false;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return {
|
|
311
|
+
configurationId: compiled.fingerprint,
|
|
312
|
+
refresh,
|
|
313
|
+
record: logs.record,
|
|
314
|
+
current() {
|
|
315
|
+
if (!active())
|
|
316
|
+
throw Error("Crawler controls unavailable");
|
|
317
|
+
return value;
|
|
318
|
+
},
|
|
319
|
+
status() {
|
|
320
|
+
return {
|
|
321
|
+
revision,
|
|
322
|
+
mode: lastMode,
|
|
323
|
+
active: active(),
|
|
324
|
+
...(error ? { error } : {}),
|
|
325
|
+
};
|
|
326
|
+
},
|
|
327
|
+
start() {
|
|
328
|
+
const timer = setInterval(() => void refresh(), 30000);
|
|
329
|
+
timer.unref();
|
|
330
|
+
if (!value)
|
|
331
|
+
void refresh();
|
|
332
|
+
return () => {
|
|
333
|
+
stopped = true;
|
|
334
|
+
logs.clear();
|
|
335
|
+
clearInterval(timer);
|
|
336
|
+
};
|
|
337
|
+
},
|
|
338
|
+
};
|
|
339
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export type ResolvedAddress = Readonly<{
|
|
2
|
+
address: string;
|
|
3
|
+
family: number;
|
|
4
|
+
}>;
|
|
5
|
+
export type DirectoryDnsLookup = (hostname: string) => Promise<readonly ResolvedAddress[]>;
|
|
6
|
+
export type HttpGet = (url: URL, options: {
|
|
7
|
+
addresses: readonly ResolvedAddress[];
|
|
8
|
+
timeoutMs: number;
|
|
9
|
+
maxBytes: number;
|
|
10
|
+
}) => Promise<{
|
|
11
|
+
status: number;
|
|
12
|
+
body: string;
|
|
13
|
+
}>;
|
|
14
|
+
export declare function isPublicIpAddress(address: string): boolean;
|
|
15
|
+
export declare const defaultDnsLookup: DirectoryDnsLookup;
|
|
16
|
+
/** Real transport: connects only to the pre-validated address set, no redirects. */
|
|
17
|
+
export declare const defaultHttpGet: HttpGet;
|
|
18
|
+
export type DirectoryFetchOptions = Readonly<{
|
|
19
|
+
dnsLookup?: DirectoryDnsLookup;
|
|
20
|
+
httpGet?: HttpGet;
|
|
21
|
+
timeoutMs?: number;
|
|
22
|
+
maxBytes?: number;
|
|
23
|
+
}>;
|
|
24
|
+
/**
|
|
25
|
+
* Fetch and structurally validate a signer's key directory.
|
|
26
|
+
* Returns the JWK array, or undefined on any network, policy, or shape failure.
|
|
27
|
+
* Never throws: a hostile or broken directory degrades to "unpinned signer".
|
|
28
|
+
*/
|
|
29
|
+
export declare function fetchDirectoryKeys(agentUrl: string, options?: DirectoryFetchOptions): Promise<readonly unknown[] | undefined>;
|
|
30
|
+
/** URL-keyed cache over fetchDirectoryKeys: one in-flight or fresh entry per signer URL. */
|
|
31
|
+
export declare function createCachingDirectoryResolver(options?: DirectoryFetchOptions & {
|
|
32
|
+
cacheTtlMs?: number;
|
|
33
|
+
now?: () => number;
|
|
34
|
+
}): {
|
|
35
|
+
resolve: (agentUrl: string) => Promise<readonly unknown[] | undefined>;
|
|
36
|
+
size: () => number;
|
|
37
|
+
};
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.defaultHttpGet = exports.defaultDnsLookup = void 0;
|
|
7
|
+
exports.isPublicIpAddress = isPublicIpAddress;
|
|
8
|
+
exports.fetchDirectoryKeys = fetchDirectoryKeys;
|
|
9
|
+
exports.createCachingDirectoryResolver = createCachingDirectoryResolver;
|
|
10
|
+
const node_dns_1 = __importDefault(require("node:dns"));
|
|
11
|
+
const node_https_1 = __importDefault(require("node:https"));
|
|
12
|
+
const node_net_1 = __importDefault(require("node:net"));
|
|
13
|
+
/**
|
|
14
|
+
* Opt-in dynamic key resolution for Web Bot Auth signer directories.
|
|
15
|
+
*
|
|
16
|
+
* The pinned-key model in webbotauth.ts never touches the network, so a request
|
|
17
|
+
* can never steer this process into contacting an attacker-chosen URL. This
|
|
18
|
+
* module relaxes that deliberately and only under these bounds:
|
|
19
|
+
*
|
|
20
|
+
* - HTTPS only; no redirects; the exact configured URL is the only origin.
|
|
21
|
+
* - Every resolved IP address is validated before connecting: any private,
|
|
22
|
+
* loopback, link-local, CGNAT, multicast, reserved, or IPv4-mapped/private
|
|
23
|
+
* IPv6 result aborts the fetch. All addresses are checked, so DNS returning
|
|
24
|
+
* one public decoy alongside an internal target fails closed. The validated
|
|
25
|
+
* address set is pinned into the TLS connect, so a re-resolution between
|
|
26
|
+
* validation and connect cannot change the destination (no TOCTOU rebinding).
|
|
27
|
+
* - 5s total timeout, 64KB response cap, at most 16 keys per directory.
|
|
28
|
+
* - Results are cached per URL; callers key trust by JWK thumbprint downstream.
|
|
29
|
+
* - A dynamically resolved signer is registered WITHOUT promotion: a valid
|
|
30
|
+
* signature authenticates the signer URL, it never produces verified
|
|
31
|
+
* evidence on first sight. Promotion stays an operator decision.
|
|
32
|
+
*/
|
|
33
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
34
|
+
const MAX_TIMEOUT_MS = 10000;
|
|
35
|
+
const DEFAULT_MAX_BYTES = 64 * 1024;
|
|
36
|
+
const HARD_MAX_BYTES = 128 * 1024;
|
|
37
|
+
const MAX_KEYS = 16;
|
|
38
|
+
const DEFAULT_CACHE_TTL_MS = 5 * 60 * 1000;
|
|
39
|
+
const MAX_CACHE_ENTRIES = 2000;
|
|
40
|
+
function isPublicIpAddress(address) {
|
|
41
|
+
const family = node_net_1.default.isIP(address);
|
|
42
|
+
if (family === 4)
|
|
43
|
+
return isPublicIpv4(address);
|
|
44
|
+
if (family === 6)
|
|
45
|
+
return isPublicIpv6(address);
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
function isPublicIpv4(address) {
|
|
49
|
+
const parts = address.split('.').map(part => Number(part));
|
|
50
|
+
if (parts.length !== 4 || parts.some(part => !Number.isInteger(part) || part < 0 || part > 255))
|
|
51
|
+
return false;
|
|
52
|
+
const [a, b] = parts;
|
|
53
|
+
if (a === 0 || a === 10 || a === 127)
|
|
54
|
+
return false; // current-net, private, loopback
|
|
55
|
+
if (a === 100 && b >= 64 && b <= 127)
|
|
56
|
+
return false; // CGNAT 100.64/10
|
|
57
|
+
if (a === 169 && b === 254)
|
|
58
|
+
return false; // link-local
|
|
59
|
+
if (a === 172 && b >= 16 && b <= 31)
|
|
60
|
+
return false; // private 172.16/12
|
|
61
|
+
if (a === 192 && b === 168)
|
|
62
|
+
return false; // private
|
|
63
|
+
if (a === 192 && b === 0)
|
|
64
|
+
return false; // IETF protocol assignments (incl. TEST-NET-1)
|
|
65
|
+
if (a === 198 && (b === 18 || b === 19))
|
|
66
|
+
return false; // benchmarking
|
|
67
|
+
if (a === 198 && b === 51 && parts[2] === 100)
|
|
68
|
+
return false; // TEST-NET-2
|
|
69
|
+
if (a === 203 && b === 0 && parts[2] === 113)
|
|
70
|
+
return false; // TEST-NET-3
|
|
71
|
+
if (a >= 224)
|
|
72
|
+
return false; // multicast + reserved + broadcast
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
function isPublicIpv6(address) {
|
|
76
|
+
const n = address.toLowerCase();
|
|
77
|
+
// IPv4-mapped forms: validate the embedded address; hex-form mapped is rejected.
|
|
78
|
+
const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(n);
|
|
79
|
+
if (mapped)
|
|
80
|
+
return isPublicIpv4(mapped[1]);
|
|
81
|
+
if (n.startsWith('::ffff:'))
|
|
82
|
+
return false;
|
|
83
|
+
// Allow only global unicast 2000::/3, minus ranges that embed or stand in for non-public space.
|
|
84
|
+
if (!/^[23]/.test(n))
|
|
85
|
+
return false;
|
|
86
|
+
if (/^2001:0{0,4}:/.test(n))
|
|
87
|
+
return false; // 2001::/32 TEREDO embeds IPv4
|
|
88
|
+
if (/^2001:0{0,3}db8/.test(n))
|
|
89
|
+
return false; // 2001:db8::/32 documentation
|
|
90
|
+
if (n.startsWith('2002:'))
|
|
91
|
+
return false; // 6to4 embeds IPv4
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
const defaultDnsLookup = async (hostname) => {
|
|
95
|
+
const results = await node_dns_1.default.promises.lookup(hostname, { all: true, verbatim: true });
|
|
96
|
+
return results.map(({ address, family }) => ({ address, family }));
|
|
97
|
+
};
|
|
98
|
+
exports.defaultDnsLookup = defaultDnsLookup;
|
|
99
|
+
/** Real transport: connects only to the pre-validated address set, no redirects. */
|
|
100
|
+
const defaultHttpGet = (url, { addresses, timeoutMs, maxBytes }) => new Promise((resolve, reject) => {
|
|
101
|
+
let settled = false;
|
|
102
|
+
const fail = (error) => { if (!settled) {
|
|
103
|
+
settled = true;
|
|
104
|
+
request.destroy();
|
|
105
|
+
reject(error);
|
|
106
|
+
} };
|
|
107
|
+
let index = 0;
|
|
108
|
+
const attempt = () => {
|
|
109
|
+
const target = addresses[index];
|
|
110
|
+
request = node_https_1.default.request({
|
|
111
|
+
protocol: 'https:', host: url.hostname, port: url.port || 443,
|
|
112
|
+
path: url.pathname + url.search, method: 'GET',
|
|
113
|
+
servername: url.hostname, // SNI keeps the real hostname; the IP is pinned below.
|
|
114
|
+
lookup: (_hostname, _options, callback) => callback(null, target.address, target.family),
|
|
115
|
+
timeout: timeoutMs,
|
|
116
|
+
headers: { accept: 'application/json', 'user-agent': 'valiron-crawler-protection/1' },
|
|
117
|
+
}, response => {
|
|
118
|
+
const chunks = [];
|
|
119
|
+
let received = 0;
|
|
120
|
+
response.on('data', (chunk) => {
|
|
121
|
+
received += chunk.length;
|
|
122
|
+
if (received > maxBytes) {
|
|
123
|
+
fail(new Error('Directory response too large'));
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
chunks.push(chunk);
|
|
127
|
+
});
|
|
128
|
+
response.on('end', () => {
|
|
129
|
+
if (settled)
|
|
130
|
+
return;
|
|
131
|
+
settled = true;
|
|
132
|
+
resolve({ status: response.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8') });
|
|
133
|
+
});
|
|
134
|
+
response.on('error', fail);
|
|
135
|
+
});
|
|
136
|
+
request.on('timeout', () => fail(new Error('Directory fetch timed out')));
|
|
137
|
+
request.on('error', () => {
|
|
138
|
+
index += 1;
|
|
139
|
+
if (index < addresses.length)
|
|
140
|
+
attempt();
|
|
141
|
+
else
|
|
142
|
+
fail(new Error('Directory fetch failed'));
|
|
143
|
+
});
|
|
144
|
+
request.end();
|
|
145
|
+
};
|
|
146
|
+
let request;
|
|
147
|
+
attempt();
|
|
148
|
+
});
|
|
149
|
+
exports.defaultHttpGet = defaultHttpGet;
|
|
150
|
+
/**
|
|
151
|
+
* Fetch and structurally validate a signer's key directory.
|
|
152
|
+
* Returns the JWK array, or undefined on any network, policy, or shape failure.
|
|
153
|
+
* Never throws: a hostile or broken directory degrades to "unpinned signer".
|
|
154
|
+
*/
|
|
155
|
+
async function fetchDirectoryKeys(agentUrl, options) {
|
|
156
|
+
if (typeof agentUrl !== 'string' || agentUrl.length > 2048)
|
|
157
|
+
return undefined;
|
|
158
|
+
let url;
|
|
159
|
+
try {
|
|
160
|
+
url = new URL(agentUrl);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
if (url.protocol !== 'https:' || url.username || url.password)
|
|
166
|
+
return undefined;
|
|
167
|
+
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
168
|
+
const maxBytes = options?.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
169
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 500 || timeoutMs > MAX_TIMEOUT_MS ||
|
|
170
|
+
!Number.isSafeInteger(maxBytes) || maxBytes < 1024 || maxBytes > HARD_MAX_BYTES)
|
|
171
|
+
return undefined;
|
|
172
|
+
const dnsLookup = options?.dnsLookup ?? exports.defaultDnsLookup;
|
|
173
|
+
const httpGet = options?.httpGet ?? exports.defaultHttpGet;
|
|
174
|
+
try {
|
|
175
|
+
const addresses = await dnsLookup(url.hostname);
|
|
176
|
+
if (!addresses.length || addresses.length > 32)
|
|
177
|
+
return undefined;
|
|
178
|
+
if (addresses.some(({ address, family }) => (family !== 4 && family !== 6) || !isPublicIpAddress(address))) {
|
|
179
|
+
return undefined; // any private/special address fails the whole fetch
|
|
180
|
+
}
|
|
181
|
+
const response = await httpGet(url, { addresses, timeoutMs, maxBytes });
|
|
182
|
+
if (response.status !== 200 || response.body.length > maxBytes)
|
|
183
|
+
return undefined; // redirects never followed
|
|
184
|
+
const parsed = JSON.parse(response.body);
|
|
185
|
+
const keys = parsed.keys;
|
|
186
|
+
if (!Array.isArray(keys) || !keys.length || keys.length > MAX_KEYS)
|
|
187
|
+
return undefined;
|
|
188
|
+
for (const candidate of keys) {
|
|
189
|
+
const jwk = candidate;
|
|
190
|
+
if (!jwk || jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.x !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(jwk.x)) {
|
|
191
|
+
return undefined; // one bad key poisons the directory
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return Object.freeze(keys.slice());
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
return undefined;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/** URL-keyed cache over fetchDirectoryKeys: one in-flight or fresh entry per signer URL. */
|
|
201
|
+
function createCachingDirectoryResolver(options) {
|
|
202
|
+
const now = options?.now ?? Date.now;
|
|
203
|
+
const cacheTtlMs = options?.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
|
|
204
|
+
if (!Number.isSafeInteger(cacheTtlMs) || cacheTtlMs < 1000 || cacheTtlMs > 3600000) {
|
|
205
|
+
throw new Error('Invalid directory cache TTL');
|
|
206
|
+
}
|
|
207
|
+
const cache = new Map();
|
|
208
|
+
const inflight = new Map();
|
|
209
|
+
return {
|
|
210
|
+
resolve(agentUrl) {
|
|
211
|
+
const cached = cache.get(agentUrl);
|
|
212
|
+
if (cached && cached.expiresAt > now())
|
|
213
|
+
return Promise.resolve(cached.keys);
|
|
214
|
+
const pending = inflight.get(agentUrl);
|
|
215
|
+
if (pending)
|
|
216
|
+
return pending;
|
|
217
|
+
const task = fetchDirectoryKeys(agentUrl, options).then(keys => {
|
|
218
|
+
inflight.delete(agentUrl);
|
|
219
|
+
if (keys) {
|
|
220
|
+
if (cache.size >= MAX_CACHE_ENTRIES)
|
|
221
|
+
cache.clear();
|
|
222
|
+
cache.set(agentUrl, { keys, expiresAt: now() + cacheTtlMs });
|
|
223
|
+
}
|
|
224
|
+
return keys;
|
|
225
|
+
}, () => { inflight.delete(agentUrl); return undefined; });
|
|
226
|
+
inflight.set(agentUrl, task);
|
|
227
|
+
return task;
|
|
228
|
+
},
|
|
229
|
+
size: () => cache.size,
|
|
230
|
+
};
|
|
231
|
+
}
|
package/dist/guard.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { CrawlerControls } from './controls';
|
|
1
2
|
import { InternalAdmission, type InternalTarget } from './internal';
|
|
2
3
|
import { type CrawlerActivation } from './activation';
|
|
3
4
|
import { BingVerifier, CrawlerRegistry, type CrawlerEvidence } from './verification';
|
|
@@ -91,6 +92,7 @@ export declare class CrawlerGuard {
|
|
|
91
92
|
wires in here so signed crawlers outside the approved lists get a verification
|
|
92
93
|
path without taking precedence over established source verification. */
|
|
93
94
|
fallbackEvidence?: (request: unknown, ip: string, userAgent: string) => CrawlerEvidence | undefined;
|
|
95
|
+
controls?: () => CrawlerControls;
|
|
94
96
|
unverifiedAccess?: 'budget' | 'deny';
|
|
95
97
|
crawlerAccess?: (evidence: CrawlerEvidence, routeGroup: string) => 'budget' | 'deny';
|
|
96
98
|
onDecision?: (decision: Readonly<Decision>, evidence?: CrawlerEvidence, details?: DecisionDetails) => void;
|
package/dist/guard.js
CHANGED
|
@@ -118,10 +118,14 @@ class CrawlerGuard {
|
|
|
118
118
|
throw new Error('Invalid customer grant');
|
|
119
119
|
if (customer?.lane === 'checkout' && this.policy.routes[input.routeGroup].customerLane !== 'checkout')
|
|
120
120
|
customer = { ...customer, lane: 'shopper' };
|
|
121
|
+
const controls = customer ? undefined : this.config.controls?.();
|
|
121
122
|
const lane = customer?.lane ?? 'catalog';
|
|
122
123
|
const rollout = this.policy.rollout;
|
|
123
|
-
const
|
|
124
|
+
const originalMode = customer || !rollout || (rollout.mode === 'enforce' && rollout.enforceGroups.includes(input.routeGroup)) ? 'enforce' : 'observe';
|
|
125
|
+
const mode = customer ? 'enforce' : controls ? (controls.mode === 'enforce' && (!controls.enforceGroups || controls.enforceGroups.includes(input.routeGroup)) ? 'enforce' : 'observe') : originalMode;
|
|
124
126
|
details = { routeGroup: input.routeGroup, lane, mode };
|
|
127
|
+
const rates = controls?.rates;
|
|
128
|
+
const minimum = (a, b) => ({ capacity: Math.min(a.capacity, b?.capacity ?? a.capacity), refillPerSecond: Math.min(a.refillPerSecond, b?.refillPerSecond ?? a.refillPerSecond) });
|
|
125
129
|
const classified = this.config.registry.classify(ip, input.userAgent);
|
|
126
130
|
evidence = this.config.trustedEvidence?.(input.request, ip, input.userAgent) ?? (classified.claimedCrawler === 'bingbot' && (0, verification_1.crawlerClaim)(input.userAgent)?.provider === 'bing'
|
|
127
131
|
? this.config.bing.classify(ip) : classified);
|
|
@@ -134,22 +138,26 @@ class CrawlerGuard {
|
|
|
134
138
|
// Known source without an explicit allowance gets the conservative policy.
|
|
135
139
|
const privileged = Boolean(provider && crawlerRate);
|
|
136
140
|
const bucket = (key, rate) => ({ key, ...rate, cost: input.cost });
|
|
137
|
-
const buckets = [bucket('global', this.policy.globalRate), bucket('ip:' + (0, admission_1.keyPart)(ip), this.policy.perIpRate)];
|
|
141
|
+
const buckets = [bucket('global', minimum(this.policy.globalRate, rates?.global)), bucket('ip:' + (0, admission_1.keyPart)(ip), minimum(this.policy.perIpRate, rates?.perIp))];
|
|
138
142
|
if (customer) {
|
|
139
143
|
buckets.splice(0, buckets.length, bucket('customer:' + lane, lane === 'checkout' ? this.policy.customers.checkoutRate : this.policy.customers.shopperRate), bucket('customer-principal:' + lane + ':' + (0, admission_1.keyPart)(customer.principal), this.policy.perIpRate));
|
|
140
144
|
}
|
|
141
|
-
buckets.push(bucket((customer ? lane + ':' : '') + 'route:' + input.routeGroup, this.policy.routes[input.routeGroup].rate));
|
|
145
|
+
buckets.push(bucket((customer ? lane + ':' : '') + 'route:' + input.routeGroup, minimum(this.policy.routes[input.routeGroup].rate, rates?.routes?.[input.routeGroup])));
|
|
142
146
|
if (!customer) {
|
|
143
147
|
if (privileged) {
|
|
144
|
-
buckets.push(bucket('provider:' + evidence.provider, provider.rate));
|
|
148
|
+
buckets.push(bucket('provider:' + evidence.provider, minimum(provider.rate, rates?.providers?.[evidence.provider])));
|
|
145
149
|
buckets.push(bucket('crawler:' + evidence.provider + ':' + evidence.crawlerClass, crawlerRate));
|
|
146
150
|
}
|
|
147
|
-
else
|
|
148
|
-
|
|
151
|
+
else {
|
|
152
|
+
let unknown = minimum(this.policy.unknownRate, rates?.unknown);
|
|
153
|
+
for (const rate of Object.values(rates?.providers ?? {}))
|
|
154
|
+
unknown = minimum(unknown, rate);
|
|
155
|
+
buckets.push(bucket('unknown', unknown));
|
|
156
|
+
}
|
|
149
157
|
}
|
|
150
158
|
const denied = !customer && (verified
|
|
151
|
-
? this.config.crawlerAccess?.(evidence, input.routeGroup) === 'deny'
|
|
152
|
-
: this.config.unverifiedAccess === 'deny');
|
|
159
|
+
? (controls ? controls.rules.find(r => r.provider === evidence.provider && r.crawlerClass === evidence.crawlerClass && r.groups.includes(input.routeGroup))?.action ?? controls.defaultAction : this.config.crawlerAccess?.(evidence, input.routeGroup)) === 'deny'
|
|
160
|
+
: (controls?.unverifiedAction ?? this.config.unverifiedAccess) === 'deny');
|
|
153
161
|
if (denied && mode === 'enforce') {
|
|
154
162
|
decision = { ...base, action: 'block', reason: 'crawler_policy_denied' };
|
|
155
163
|
this.emit(decision, evidence, { ...details, proposedAction: 'block' });
|