@valiron/crawler-protection 0.0.0-stage → 0.2.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 +223 -2
- package/dist/activation.d.ts +25 -0
- package/dist/activation.js +121 -0
- package/dist/adapters.d.ts +29 -0
- package/dist/adapters.js +69 -0
- package/dist/admission.d.ts +62 -0
- package/dist/admission.js +188 -0
- package/dist/cache.d.ts +42 -0
- package/dist/cache.js +130 -0
- package/dist/configuration.d.ts +54 -0
- package/dist/configuration.js +223 -0
- package/dist/directory.d.ts +36 -0
- package/dist/directory.js +155 -0
- package/dist/gateway.d.ts +31 -0
- package/dist/gateway.js +352 -0
- package/dist/guard.d.ts +110 -0
- package/dist/guard.js +294 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +37 -0
- package/dist/internal.d.ts +29 -0
- package/dist/internal.js +50 -0
- package/dist/ip.d.ts +18 -0
- package/dist/ip.js +81 -0
- package/dist/meta.d.ts +13 -0
- package/dist/meta.js +34 -0
- package/dist/onboarding.d.ts +56 -0
- package/dist/onboarding.js +60 -0
- package/dist/operations.d.ts +60 -0
- package/dist/operations.js +149 -0
- package/dist/reporting.d.ts +44 -0
- package/dist/reporting.js +72 -0
- package/dist/runtime.d.ts +56 -0
- package/dist/runtime.js +69 -0
- package/dist/telemetry.d.ts +16 -0
- package/dist/telemetry.js +61 -0
- package/dist/verification.d.ts +113 -0
- package/dist/verification.js +238 -0
- package/gateway/Dockerfile +21 -0
- package/gateway/README.md +110 -0
- package/gateway/admin.cjs +34 -0
- package/gateway/compose.yaml +40 -0
- package/gateway/directory.cjs +10 -0
- package/gateway/service.cjs +97 -0
- package/gateway/work-api.openapi.json +186 -0
- package/integrations/python/valiron_crawler_protection.py +90 -0
- package/package.json +57 -4
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createEcommercePilotConfiguration = void 0;
|
|
4
|
+
exports.planCrawlerRollout = planCrawlerRollout;
|
|
5
|
+
exports.createEcommerceConfiguration = createEcommerceConfiguration;
|
|
6
|
+
const configuration_1 = require("./configuration");
|
|
7
|
+
/** Read-only onboarding report. Missing measurements never become invented production limits. */
|
|
8
|
+
function planCrawlerRollout(configuration, baseline, now = Date.now()) {
|
|
9
|
+
const c = (0, configuration_1.compileCrawlerConfiguration)(configuration, now);
|
|
10
|
+
const blockers = [];
|
|
11
|
+
let poolConnections;
|
|
12
|
+
if (!baseline)
|
|
13
|
+
blockers.push('Supply measured database headroom, all process pools and a representative traffic/checkout baseline.');
|
|
14
|
+
else {
|
|
15
|
+
const fields = ['safeDbConnections', 'nonGuardConnections', 'windowSeconds', 'sampledRequests', 'checkoutP95Ms', 'checkoutTargetMs'];
|
|
16
|
+
if (typeof baseline !== 'object' || Array.isArray(baseline) || Object.keys(baseline).some(key => ![...fields, 'pools'].includes(key)) ||
|
|
17
|
+
fields.some(key => !Number.isFinite(baseline[key]) || baseline[key] < 0 || baseline[key] > 1e12))
|
|
18
|
+
throw new Error('Invalid capacity baseline');
|
|
19
|
+
if (!Number.isSafeInteger(baseline.safeDbConnections) || baseline.safeDbConnections < 1 || !Number.isSafeInteger(baseline.nonGuardConnections) ||
|
|
20
|
+
!Array.isArray(baseline.pools) || baseline.pools.length < 1 || baseline.pools.length > 128 || new Set(baseline.pools.map(p => p.name)).size !== baseline.pools.length ||
|
|
21
|
+
baseline.pools.some(p => typeof p.name !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(p.name) || ![p.maxConnections, p.processes].every(n => Number.isSafeInteger(n) && n >= 1 && n <= 100000)))
|
|
22
|
+
throw new Error('Invalid database capacity envelope');
|
|
23
|
+
const total = baseline.pools.reduce((sum, pool) => sum + pool.maxConnections * pool.processes, 0);
|
|
24
|
+
poolConnections = total;
|
|
25
|
+
if (total + baseline.nonGuardConnections > baseline.safeDbConnections)
|
|
26
|
+
blockers.push('Combined process pools exceed measured safe DB headroom.');
|
|
27
|
+
if (c.policy.globalWorkLimit > baseline.safeDbConnections - baseline.nonGuardConnections || c.policy.globalWorkLimit > total)
|
|
28
|
+
blockers.push('Global work ceiling exceeds the measured DB/pool envelope.');
|
|
29
|
+
if (baseline.windowSeconds <= 0 || baseline.sampledRequests < 1)
|
|
30
|
+
blockers.push('Collect a representative nonempty traffic baseline, including peak periods.');
|
|
31
|
+
if (baseline.checkoutTargetMs <= 0 || baseline.checkoutP95Ms <= 0 || baseline.checkoutP95Ms > baseline.checkoutTargetMs)
|
|
32
|
+
blockers.push('Establish a passing checkout latency baseline before increasing crawler access.');
|
|
33
|
+
}
|
|
34
|
+
return { configurationId: c.fingerprint, mode: c.configuration.rollout.mode, enforceGroups: c.configuration.rollout.enforceGroups,
|
|
35
|
+
inventory: c.configuration.inventory.map(r => ({ id: r.id, kind: r.kind, methods: r.methods, path: r.path })),
|
|
36
|
+
poolConnections, readyForControlledTrial: blockers.length === 0, blockers,
|
|
37
|
+
next: ['Run observation behind existing CDN/WAF restrictions and enforced work/safety caps.',
|
|
38
|
+
'Test cache, customer grants, every DB path, overload, disconnects and Redis recovery on owned fixtures.',
|
|
39
|
+
'Pause and drain, activate a new configuration, then enforce selected route groups.',
|
|
40
|
+
'Enable one verified crawler class at a time; verify actual useful fetches and shopper/error targets.',
|
|
41
|
+
'Rollback crawler permissions at the edge before removing integration; retain workload caps.'],
|
|
42
|
+
boundaries: ['This report does not certify production readiness or prove crawler acceptance.', 'Origin counters exclude CDN hits; anonymous callers are not inferred humans.', 'No production budgets are inferred from daily request totals.'] };
|
|
43
|
+
}
|
|
44
|
+
/** The customer supplies every budget and actual route. No company-specific branch in the engine. */
|
|
45
|
+
function createEcommerceConfiguration(input, now = Date.now()) {
|
|
46
|
+
const c = { schemaVersion: 1, tenant: input.tenant, policy: input.policy, rollout: input.rollout,
|
|
47
|
+
inventory: [
|
|
48
|
+
{ id: 'catalog-listing', kind: 'protected', path: input.paths.listing, methods: ['GET', 'HEAD'], group: input.groups.listing },
|
|
49
|
+
{ id: 'catalog-detail', kind: 'protected', path: input.paths.detail, methods: ['GET', 'HEAD'], group: input.groups.detail },
|
|
50
|
+
{ id: 'checkout', kind: 'protected', path: input.paths.checkout, methods: ['GET', 'HEAD', 'POST'], group: input.groups.checkout },
|
|
51
|
+
...(input.paths.bypass ?? []).map(r => ({ ...r, kind: 'bypass' })),
|
|
52
|
+
], ...(input.cache ? { cache: input.cache } : {}), ...(input.crawlerAccess ? { crawlerAccess: input.crawlerAccess } : {}) };
|
|
53
|
+
if (input.policy.routes[input.groups.checkout]?.customerLane !== 'checkout')
|
|
54
|
+
throw new Error('Checkout group needs explicit customerLane');
|
|
55
|
+
if (input.groups.listing === input.groups.checkout || input.groups.detail === input.groups.checkout)
|
|
56
|
+
throw new Error('Checkout must have its own route group');
|
|
57
|
+
return (0, configuration_1.compileCrawlerConfiguration)(c, now).configuration;
|
|
58
|
+
}
|
|
59
|
+
/** @deprecated Use createEcommerceConfiguration. Retained for existing integrations. */
|
|
60
|
+
exports.createEcommercePilotConfiguration = createEcommerceConfiguration;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { RedisAdmission, type RedisEval } from './admission';
|
|
2
|
+
/** Stable policy identity: changing limits without changing version still rejects stale workers. */
|
|
3
|
+
export declare function policyFingerprint(policy: unknown): string;
|
|
4
|
+
export type Hold = {
|
|
5
|
+
id: string;
|
|
6
|
+
acquiredAt: number;
|
|
7
|
+
owner: string;
|
|
8
|
+
requestId?: string;
|
|
9
|
+
lane?: string;
|
|
10
|
+
keys: string[];
|
|
11
|
+
slots?: string[];
|
|
12
|
+
};
|
|
13
|
+
/** Managed mode never bootstraps itself. Missing control state fails closed. */
|
|
14
|
+
export declare class ManagedRedisAdmission extends RedisAdmission {
|
|
15
|
+
private readonly identity;
|
|
16
|
+
constructor(redis: RedisEval, tenant: string, policy: unknown, timeoutMs?: number);
|
|
17
|
+
protected run(script: string, keys: string[], args: (string | number)[]): Promise<unknown>;
|
|
18
|
+
/** New namespace only, after proving all old workers and queries are stopped. Creates paused. */
|
|
19
|
+
initialize(input: {
|
|
20
|
+
confirmedDrained: true;
|
|
21
|
+
evidence: string;
|
|
22
|
+
}): Promise<void>;
|
|
23
|
+
pause(): Promise<void>;
|
|
24
|
+
inspect(): Promise<{
|
|
25
|
+
paused: boolean;
|
|
26
|
+
identity: string | null;
|
|
27
|
+
holds: Hold[];
|
|
28
|
+
catalog: string;
|
|
29
|
+
}>;
|
|
30
|
+
/** Drain before activating a new policy; CAS prevents competing operators from overwriting it. */
|
|
31
|
+
activate(previousIdentity: string): Promise<void>;
|
|
32
|
+
resume(): Promise<void>;
|
|
33
|
+
private proof;
|
|
34
|
+
/** No age-based deletion. Stop queries/connections first, then name exact orphan IDs. */
|
|
35
|
+
reconcile(ids: string[], input: {
|
|
36
|
+
confirmedDrained: true;
|
|
37
|
+
evidence: string;
|
|
38
|
+
}): Promise<void>;
|
|
39
|
+
/** Open on observed DB distress; explicit probe mode admits one catalog query at a time.
|
|
40
|
+
* Checkout keeps its reservations. Bypass cache regeneration while probing.
|
|
41
|
+
* Returning to healthy requires fresh successful bounded probes, never an elapsed timer alone.
|
|
42
|
+
*/
|
|
43
|
+
catalogCircuit(state: 'open' | 'probe' | 'healthy', evidence: string): Promise<void>;
|
|
44
|
+
/** Feed actual pool/query outcomes. A bounded server-time window opens catalog admission.
|
|
45
|
+
* Never closes automatically: use explicit probes and inspect fresh results before recovery.
|
|
46
|
+
*/
|
|
47
|
+
observeDatabase(sample: {
|
|
48
|
+
poolWaitMs: number;
|
|
49
|
+
queryMs: number;
|
|
50
|
+
error: boolean;
|
|
51
|
+
}, limits: {
|
|
52
|
+
windowMs: number;
|
|
53
|
+
minSamples: number;
|
|
54
|
+
badSamples: number;
|
|
55
|
+
maxPoolWaitMs: number;
|
|
56
|
+
maxQueryMs: number;
|
|
57
|
+
}): Promise<boolean>;
|
|
58
|
+
/** Atomic one-use child authorization and parent fanout, retained until parent expiry. */
|
|
59
|
+
claimChild(parent: string, child: string, max: number, expiresAt: number): Promise<boolean>;
|
|
60
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ManagedRedisAdmission = void 0;
|
|
4
|
+
exports.policyFingerprint = policyFingerprint;
|
|
5
|
+
const admission_1 = require("./admission");
|
|
6
|
+
/** Stable policy identity: changing limits without changing version still rejects stale workers. */
|
|
7
|
+
function policyFingerprint(policy) {
|
|
8
|
+
const canonical = (v) => Array.isArray(v) ? v.map(canonical) : v && typeof v === 'object'
|
|
9
|
+
? Object.fromEntries(Object.keys(v).sort().map(k => [k, canonical(v[k])])) : v;
|
|
10
|
+
return (0, admission_1.keyPart)(JSON.stringify(canonical(policy)));
|
|
11
|
+
}
|
|
12
|
+
const GATE = `
|
|
13
|
+
local control = table.remove(KEYS,1)
|
|
14
|
+
local expected = table.remove(ARGV,1)
|
|
15
|
+
if redis.call('HGET',control,'identity') ~= expected or redis.call('HGET',control,'paused') ~= '0' then
|
|
16
|
+
return redis.error_reply('Admission paused or policy inactive')
|
|
17
|
+
end
|
|
18
|
+
`;
|
|
19
|
+
/** Managed mode never bootstraps itself. Missing control state fails closed. */
|
|
20
|
+
class ManagedRedisAdmission extends admission_1.RedisAdmission {
|
|
21
|
+
identity;
|
|
22
|
+
constructor(redis, tenant, policy, timeoutMs = 250) {
|
|
23
|
+
super(redis, tenant, timeoutMs);
|
|
24
|
+
this.identity = policyFingerprint(policy);
|
|
25
|
+
}
|
|
26
|
+
run(script, keys, args) {
|
|
27
|
+
const circuit = script.includes('-- WORK_ACQUIRE') ? `
|
|
28
|
+
local lane=cjson.decode(ARGV[1]).lane or 'catalog'
|
|
29
|
+
local state=redis.call('HGET',control,'catalog') or 'healthy'
|
|
30
|
+
if lane == 'catalog' or lane == 'cache' or lane == 'gateway' then
|
|
31
|
+
if state == 'open' then return 0 end
|
|
32
|
+
if state == 'probe' then
|
|
33
|
+
if lane == 'cache' then return 0 end
|
|
34
|
+
for _,raw in ipairs(redis.call('HVALS',KEYS[1])) do
|
|
35
|
+
local held=cjson.decode(raw)
|
|
36
|
+
if held.lane == lane then return 0 end
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
` : '';
|
|
41
|
+
if (script.includes('-- ADMISSION'))
|
|
42
|
+
return super.run(GATE + circuit + script, [this.prefix + 'control', ...keys], [this.identity, ...args]);
|
|
43
|
+
return super.run(script, keys, args);
|
|
44
|
+
}
|
|
45
|
+
/** New namespace only, after proving all old workers and queries are stopped. Creates paused. */
|
|
46
|
+
async initialize(input) {
|
|
47
|
+
this.proof(input);
|
|
48
|
+
await this.run(`
|
|
49
|
+
if redis.call('EXISTS',KEYS[1]) == 1 or redis.call('HLEN',KEYS[2]) > 0 then return redis.error_reply('Already initialized or holds exist') end
|
|
50
|
+
redis.call('HSET',KEYS[1],'identity',ARGV[1],'paused',1,'evidence',ARGV[2])
|
|
51
|
+
return 1`, [this.prefix + 'control', this.prefix + 'holds'], [this.identity, input.evidence]);
|
|
52
|
+
}
|
|
53
|
+
async pause() {
|
|
54
|
+
await this.run(`if redis.call('EXISTS',KEYS[1]) == 0 then return redis.error_reply('Missing control') end
|
|
55
|
+
redis.call('HSET',KEYS[1],'paused',1) return 1`, [this.prefix + 'control'], []);
|
|
56
|
+
}
|
|
57
|
+
async inspect() {
|
|
58
|
+
const raw = await this.run(`return {redis.call('HGET',KEYS[1],'paused') or '1',redis.call('HGET',KEYS[1],'identity') or '',redis.call('HGETALL',KEYS[2]),redis.call('HGET',KEYS[1],'catalog') or 'healthy'}`, [this.prefix + 'control', this.prefix + 'holds'], []);
|
|
59
|
+
const holds = [];
|
|
60
|
+
for (let i = 0; i < raw[2].length; i += 2)
|
|
61
|
+
holds.push({ ...JSON.parse(raw[2][i + 1]), id: raw[2][i] });
|
|
62
|
+
return { catalog: raw[3], paused: raw[0] !== '0', identity: raw[1] || null, holds: holds.sort((a, b) => a.acquiredAt - b.acquiredAt) };
|
|
63
|
+
}
|
|
64
|
+
/** Drain before activating a new policy; CAS prevents competing operators from overwriting it. */
|
|
65
|
+
async activate(previousIdentity) {
|
|
66
|
+
await this.run(`
|
|
67
|
+
if redis.call('HGET',KEYS[1],'paused') ~= '1' or redis.call('HLEN',KEYS[2]) > 0 or redis.call('HGET',KEYS[1],'identity') ~= ARGV[1] then return redis.error_reply('Pause, drain and compare policy first') end
|
|
68
|
+
redis.call('HSET',KEYS[1],'identity',ARGV[2]) return 1`, [this.prefix + 'control', this.prefix + 'holds'], [previousIdentity, this.identity]);
|
|
69
|
+
}
|
|
70
|
+
async resume() {
|
|
71
|
+
await this.run(`
|
|
72
|
+
if redis.call('HGET',KEYS[1],'identity') ~= ARGV[1] or redis.call('HLEN',KEYS[2]) > 0 then return redis.error_reply('Drain and activate policy before resume') end
|
|
73
|
+
redis.call('HSET',KEYS[1],'paused',0) return 1`, [this.prefix + 'control', this.prefix + 'holds'], [this.identity]);
|
|
74
|
+
}
|
|
75
|
+
proof(input) {
|
|
76
|
+
if (input.confirmedDrained !== true || typeof input.evidence !== 'string' || input.evidence.length < 10 || input.evidence.length > 1024)
|
|
77
|
+
throw new Error('Explicit drain confirmation and evidence required');
|
|
78
|
+
}
|
|
79
|
+
/** No age-based deletion. Stop queries/connections first, then name exact orphan IDs. */
|
|
80
|
+
async reconcile(ids, input) {
|
|
81
|
+
this.proof(input);
|
|
82
|
+
if (!ids.length || ids.length > 100 || new Set(ids).size !== ids.length || ids.some(id => !/^[a-f0-9-]{36}$/.test(id)))
|
|
83
|
+
throw new Error('Invalid hold IDs');
|
|
84
|
+
await this.run(`
|
|
85
|
+
if redis.call('HGET',KEYS[1],'paused') ~= '1' then return redis.error_reply('Pause before reconcile') end
|
|
86
|
+
local records = {}
|
|
87
|
+
for i=3,#ARGV do
|
|
88
|
+
local raw = redis.call('HGET',KEYS[2],ARGV[i])
|
|
89
|
+
if not raw then return redis.error_reply('Hold missing; inspect again') end
|
|
90
|
+
local record = cjson.decode(raw)
|
|
91
|
+
for _,key in ipairs(record.keys) do
|
|
92
|
+
if string.sub(key,1,string.len(ARGV[1])) ~= ARGV[1] then return redis.error_reply('Invalid hold key') end
|
|
93
|
+
end
|
|
94
|
+
records[i] = record
|
|
95
|
+
end
|
|
96
|
+
for i=3,#ARGV do
|
|
97
|
+
for _,key in ipairs(records[i].keys) do redis.call('HDEL',key,ARGV[i]) end
|
|
98
|
+
redis.call('HDEL',KEYS[2],ARGV[i])
|
|
99
|
+
redis.call('LPUSH',KEYS[3],cjson.encode({id=ARGV[i],evidence=ARGV[2]}))
|
|
100
|
+
end
|
|
101
|
+
redis.call('LTRIM',KEYS[3],0,99)
|
|
102
|
+
return 1`, [this.prefix + 'control', this.prefix + 'holds', this.prefix + 'recovery-audit'], [this.prefix + 'work:', input.evidence, ...ids]);
|
|
103
|
+
}
|
|
104
|
+
/** Open on observed DB distress; explicit probe mode admits one catalog query at a time.
|
|
105
|
+
* Checkout keeps its reservations. Bypass cache regeneration while probing.
|
|
106
|
+
* Returning to healthy requires fresh successful bounded probes, never an elapsed timer alone.
|
|
107
|
+
*/
|
|
108
|
+
async catalogCircuit(state, evidence) {
|
|
109
|
+
if (!['open', 'probe', 'healthy'].includes(state) || typeof evidence !== 'string' || evidence.length < 10 || evidence.length > 1024)
|
|
110
|
+
throw new Error('Circuit evidence required');
|
|
111
|
+
await this.run(`if redis.call('HGET',KEYS[1],'identity') ~= ARGV[1] then return redis.error_reply('Inactive policy') end
|
|
112
|
+
redis.call('HSET',KEYS[1],'catalog',ARGV[2],'circuitEvidence',ARGV[3])
|
|
113
|
+
redis.call('DEL',KEYS[2]) return 1`, [this.prefix + 'control', this.prefix + 'db-health'], [this.identity, state, evidence]);
|
|
114
|
+
}
|
|
115
|
+
/** Feed actual pool/query outcomes. A bounded server-time window opens catalog admission.
|
|
116
|
+
* Never closes automatically: use explicit probes and inspect fresh results before recovery.
|
|
117
|
+
*/
|
|
118
|
+
async observeDatabase(sample, limits) {
|
|
119
|
+
if (![sample.poolWaitMs, sample.queryMs].every(n => Number.isFinite(n) && n >= 0 && n <= 86400000) ||
|
|
120
|
+
!Object.values(limits).every(n => Number.isSafeInteger(n) && n >= 1 && n <= 60000) ||
|
|
121
|
+
limits.badSamples > limits.minSamples || limits.windowMs > 60000)
|
|
122
|
+
throw new Error('Invalid database health sample');
|
|
123
|
+
const bad = sample.error || sample.poolWaitMs >= limits.maxPoolWaitMs || sample.queryMs >= limits.maxQueryMs;
|
|
124
|
+
const result = await this.run(`
|
|
125
|
+
if redis.call('HGET',KEYS[1],'identity') ~= ARGV[1] then return redis.error_reply('Inactive policy') end
|
|
126
|
+
local clock=redis.call('TIME') local now=tonumber(clock[1])*1000+tonumber(clock[2])/1000
|
|
127
|
+
local started=tonumber(redis.call('HGET',KEYS[2],'at') or '0')
|
|
128
|
+
if now-started >= tonumber(ARGV[2]) then redis.call('DEL',KEYS[2]) redis.call('HSET',KEYS[2],'at',now) end
|
|
129
|
+
local samples=redis.call('HINCRBY',KEYS[2],'samples',1)
|
|
130
|
+
local bad=redis.call('HINCRBY',KEYS[2],'bad',tonumber(ARGV[5]))
|
|
131
|
+
redis.call('PEXPIRE',KEYS[2],ARGV[2])
|
|
132
|
+
if samples >= tonumber(ARGV[3]) and bad >= tonumber(ARGV[4]) then
|
|
133
|
+
redis.call('HSET',KEYS[1],'catalog','open','circuitEvidence','measured database distress','observedAt',now) return 1
|
|
134
|
+
end return 0`, [this.prefix + 'control', this.prefix + 'db-health'], [this.identity, limits.windowMs, limits.minSamples, limits.badSamples, bad ? 1 : 0]);
|
|
135
|
+
return Number(result) === 1;
|
|
136
|
+
}
|
|
137
|
+
/** Atomic one-use child authorization and parent fanout, retained until parent expiry. */
|
|
138
|
+
async claimChild(parent, child, max, expiresAt) {
|
|
139
|
+
if (!/^[a-f0-9-]{36}$/.test(parent) || !/^[a-f0-9-]{36}$/.test(child) || !Number.isSafeInteger(max) || max < 1 || max > 100000 || !Number.isSafeInteger(expiresAt))
|
|
140
|
+
throw new Error('Invalid child authorization');
|
|
141
|
+
const script = `-- ADMISSION
|
|
142
|
+
local clock=redis.call('TIME') local now=tonumber(clock[1])*1000+tonumber(clock[2])/1000
|
|
143
|
+
if tonumber(ARGV[3]) <= now or tonumber(ARGV[3])-now > 60000 then return 0 end
|
|
144
|
+
if redis.call('HEXISTS',KEYS[1],ARGV[1]) == 1 or redis.call('HLEN',KEYS[1]) >= tonumber(ARGV[2]) then return 0 end
|
|
145
|
+
redis.call('HSET',KEYS[1],ARGV[1],1) redis.call('PEXPIREAT',KEYS[1],ARGV[3]) return 1`;
|
|
146
|
+
return Number(await this.run(script, [this.prefix + 'children:' + (0, admission_1.keyPart)(parent)], [child, max, expiresAt])) === 1;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
exports.ManagedRedisAdmission = ManagedRedisAdmission;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Decision } from './admission';
|
|
2
|
+
import type { GuardPolicy } from './guard';
|
|
3
|
+
import type { DecisionDetails, RequestContext } from './guard';
|
|
4
|
+
import type { CacheEvent } from './cache';
|
|
5
|
+
import type { CrawlerEvidence } from './verification';
|
|
6
|
+
export type WorkEvent = {
|
|
7
|
+
phase: 'database' | 'render';
|
|
8
|
+
outcome: 'settled' | 'rejected' | 'error';
|
|
9
|
+
routeGroup: string;
|
|
10
|
+
durationMs: number;
|
|
11
|
+
};
|
|
12
|
+
/** Bounded process-local aggregates. No IPs, URLs, UA, sessions, tokens or request IDs. */
|
|
13
|
+
export declare class CrawlerReport {
|
|
14
|
+
private readonly maxSeries;
|
|
15
|
+
private readonly series;
|
|
16
|
+
private readonly groups;
|
|
17
|
+
private readonly policy;
|
|
18
|
+
private readonly providers;
|
|
19
|
+
private readonly classes;
|
|
20
|
+
private overflow;
|
|
21
|
+
constructor(policy: GuardPolicy, maxSeries?: number, sources?: readonly {
|
|
22
|
+
provider: string;
|
|
23
|
+
crawlerClass: string;
|
|
24
|
+
}[]);
|
|
25
|
+
private record;
|
|
26
|
+
decision(decision: Decision, evidence?: CrawlerEvidence, details?: DecisionDetails): void;
|
|
27
|
+
work(context: RequestContext, event: Omit<WorkEvent, 'routeGroup'>): void;
|
|
28
|
+
gateway(group: string, outcome: 'admitted' | 'rejected' | 'completed' | 'orphan'): void;
|
|
29
|
+
databasePermit(group: string, outcome: 'admitted' | 'rejected'): void;
|
|
30
|
+
cache(group: string, outcome: CacheEvent): void;
|
|
31
|
+
snapshot(): {
|
|
32
|
+
scope: "process-origin-only";
|
|
33
|
+
policyVersion: string;
|
|
34
|
+
configurationId: string | undefined;
|
|
35
|
+
overflow: number;
|
|
36
|
+
durationBucketUpperBoundsMs: (number | null)[];
|
|
37
|
+
series: {
|
|
38
|
+
count: number;
|
|
39
|
+
durationMs: number;
|
|
40
|
+
durationBuckets: number[];
|
|
41
|
+
tags: any;
|
|
42
|
+
}[];
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CrawlerReport = void 0;
|
|
4
|
+
/** Bounded process-local aggregates. No IPs, URLs, UA, sessions, tokens or request IDs. */
|
|
5
|
+
class CrawlerReport {
|
|
6
|
+
maxSeries;
|
|
7
|
+
series = new Map();
|
|
8
|
+
groups;
|
|
9
|
+
policy;
|
|
10
|
+
providers = new Set();
|
|
11
|
+
classes = new Set();
|
|
12
|
+
overflow = 0;
|
|
13
|
+
constructor(policy, maxSeries = 1024, sources = []) {
|
|
14
|
+
this.maxSeries = maxSeries;
|
|
15
|
+
if (!Number.isSafeInteger(maxSeries) || maxSeries < 1 || maxSeries > 10000)
|
|
16
|
+
throw new Error('Invalid reporting bound');
|
|
17
|
+
this.policy = structuredClone(policy);
|
|
18
|
+
this.groups = new Set(Object.keys(policy.routes));
|
|
19
|
+
for (const source of [...sources, ...Object.entries(policy.providers).flatMap(([provider, p]) => Object.keys(p.classes).map(crawlerClass => ({ provider, crawlerClass })))]) {
|
|
20
|
+
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(source.provider) || !/^[a-zA-Z0-9_-]{1,64}$/.test(source.crawlerClass))
|
|
21
|
+
throw new Error('Invalid reporting source');
|
|
22
|
+
this.providers.add(source.provider);
|
|
23
|
+
this.classes.add(source.provider + ':' + source.crawlerClass);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
record(tags, durationMs = 0) {
|
|
27
|
+
const key = JSON.stringify(tags);
|
|
28
|
+
let value = this.series.get(key);
|
|
29
|
+
if (!value) {
|
|
30
|
+
if (this.series.size >= this.maxSeries) {
|
|
31
|
+
this.overflow++;
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
value = { count: 0, durationMs: 0, durationBuckets: [0, 0, 0, 0, 0, 0] };
|
|
35
|
+
this.series.set(key, value);
|
|
36
|
+
}
|
|
37
|
+
value.count++;
|
|
38
|
+
if (['database', 'render'].includes(tags.phase) && Number.isFinite(durationMs) && durationMs >= 0) {
|
|
39
|
+
value.durationMs += Math.min(durationMs, 86400000);
|
|
40
|
+
const i = [10, 50, 100, 500, 1000].findIndex(n => durationMs <= n);
|
|
41
|
+
value.durationBuckets[i === -1 ? 5 : i]++;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
decision(decision, evidence, details) {
|
|
45
|
+
if (!details?.routeGroup || !this.groups.has(details.routeGroup))
|
|
46
|
+
return;
|
|
47
|
+
const provider = evidence?.state === 'verified' && evidence.provider && this.providers.has(evidence.provider) ? evidence.provider : 'other';
|
|
48
|
+
const crawlerClass = provider !== 'other' && evidence?.crawlerClass && this.classes.has(provider + ':' + evidence.crawlerClass) ? evidence.crawlerClass : 'other';
|
|
49
|
+
this.record({ phase: 'request', group: details.routeGroup, lane: ['catalog', 'shopper', 'checkout'].includes(details.lane ?? '') ? details.lane : 'unknown',
|
|
50
|
+
mode: details.mode === 'observe' ? 'observe' : 'enforce', action: decision.action,
|
|
51
|
+
proposedAction: details.proposedAction ?? 'unknown', provider, crawlerClass,
|
|
52
|
+
reason: ['within_budget', 'observation_within_safety', 'crawler_policy_denied', 'safety_budget_exhausted', 'rate_budget_exhausted', 'admission_unavailable'].includes(decision.reason) ? decision.reason : 'other',
|
|
53
|
+
verification: evidence?.state ?? 'verification_unavailable' });
|
|
54
|
+
}
|
|
55
|
+
work(context, event) {
|
|
56
|
+
this.record({ phase: event.phase, lane: ['catalog', 'shopper', 'checkout'].includes(context?.lane ?? '') ? context.lane : 'unknown', group: this.groups.has(context?.routeGroup) ? context.routeGroup : 'unknown', outcome: event.outcome }, event.durationMs);
|
|
57
|
+
}
|
|
58
|
+
gateway(group, outcome) {
|
|
59
|
+
this.record({ phase: 'gateway', group: this.groups.has(group) ? group : 'unknown', outcome });
|
|
60
|
+
}
|
|
61
|
+
databasePermit(group, outcome) {
|
|
62
|
+
this.record({ phase: 'database-permit', group: this.groups.has(group) ? group : 'unknown', outcome });
|
|
63
|
+
}
|
|
64
|
+
cache(group, outcome) { this.record({ phase: 'cache', group: this.groups.has(group) ? group : 'unknown', outcome }); }
|
|
65
|
+
snapshot() {
|
|
66
|
+
return { scope: 'process-origin-only', policyVersion: this.policy.version,
|
|
67
|
+
configurationId: this.policy.configurationId, overflow: this.overflow,
|
|
68
|
+
durationBucketUpperBoundsMs: [10, 50, 100, 500, 1000, null],
|
|
69
|
+
series: [...this.series].map(([key, value]) => ({ tags: JSON.parse(key), ...structuredClone(value) })) };
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
exports.CrawlerReport = CrawlerReport;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { IncomingMessage } from 'node:http';
|
|
2
|
+
import { CrawlerGuard, type RequestContext } from './guard';
|
|
3
|
+
import { ManagedRedisAdmission } from './operations';
|
|
4
|
+
import { type RedisEval } from './admission';
|
|
5
|
+
import { CrawlerRegistry, BingVerifier } from './verification';
|
|
6
|
+
import { type PublicResponse } from './cache';
|
|
7
|
+
import { CrawlerReport } from './reporting';
|
|
8
|
+
import { type CrawlerActivation } from './activation';
|
|
9
|
+
type GuardDependencies = ConstructorParameters<typeof CrawlerGuard>[0];
|
|
10
|
+
/** Assemble framework-independent enforcement from one validated deployment configuration. */
|
|
11
|
+
export declare function createCrawlerRuntime(input: {
|
|
12
|
+
configuration: unknown;
|
|
13
|
+
redis: RedisEval;
|
|
14
|
+
activation: CrawlerActivation;
|
|
15
|
+
clientIp: (request: IncomingMessage) => string;
|
|
16
|
+
registry?: CrawlerRegistry;
|
|
17
|
+
bing?: BingVerifier;
|
|
18
|
+
customer?: GuardDependencies['customer'];
|
|
19
|
+
trustedEvidence?: GuardDependencies['trustedEvidence'];
|
|
20
|
+
onDecision?: GuardDependencies['onDecision'];
|
|
21
|
+
now?: () => number;
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
}): Readonly<{
|
|
24
|
+
compiled: Readonly<{
|
|
25
|
+
configuration: import("./configuration").CrawlerConfiguration;
|
|
26
|
+
policy: import("./guard").GuardPolicy;
|
|
27
|
+
fingerprint: string;
|
|
28
|
+
resolve: (request: Pick<IncomingMessage, "method" | "url">) => import("./configuration").ResolvedRoute;
|
|
29
|
+
}>;
|
|
30
|
+
store: ManagedRedisAdmission;
|
|
31
|
+
guard: CrawlerGuard;
|
|
32
|
+
report: CrawlerReport;
|
|
33
|
+
activation: Readonly<{
|
|
34
|
+
tenant: string;
|
|
35
|
+
start(): Promise<void>;
|
|
36
|
+
refresh(): Promise<void>;
|
|
37
|
+
stop(): void;
|
|
38
|
+
status(): Readonly<{
|
|
39
|
+
active: boolean;
|
|
40
|
+
expiresAt?: number;
|
|
41
|
+
}>;
|
|
42
|
+
}>;
|
|
43
|
+
nodeMiddleware: (request: import("./adapters").GuardedRequest, response: import("http").ServerResponse, next: (error?: unknown) => void) => void;
|
|
44
|
+
nuxtMiddleware: (event: {
|
|
45
|
+
node: {
|
|
46
|
+
req: IncomingMessage;
|
|
47
|
+
res: import("http").ServerResponse;
|
|
48
|
+
};
|
|
49
|
+
context: Record<string, unknown>;
|
|
50
|
+
}) => Promise<void>;
|
|
51
|
+
withDatabaseAdmission: <T>(context: RequestContext, operation: () => Promise<T>) => Promise<T>;
|
|
52
|
+
withRenderingAdmission: <T>(context: RequestContext, operation: () => Promise<T>) => Promise<T>;
|
|
53
|
+
/** Loader must perform page admission and wrap render/DB work. This wrapper authenticates every request, including hits. */
|
|
54
|
+
publicResponse(request: IncomingMessage, admittedLoader: () => Promise<PublicResponse>, background?: (work: Promise<void>) => void): Promise<PublicResponse>;
|
|
55
|
+
}>;
|
|
56
|
+
export {};
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createCrawlerRuntime = createCrawlerRuntime;
|
|
4
|
+
const guard_1 = require("./guard");
|
|
5
|
+
const operations_1 = require("./operations");
|
|
6
|
+
const admission_1 = require("./admission");
|
|
7
|
+
const verification_1 = require("./verification");
|
|
8
|
+
const configuration_1 = require("./configuration");
|
|
9
|
+
const cache_1 = require("./cache");
|
|
10
|
+
const reporting_1 = require("./reporting");
|
|
11
|
+
const adapters_1 = require("./adapters");
|
|
12
|
+
const activation_1 = require("./activation");
|
|
13
|
+
/** Assemble framework-independent enforcement from one validated deployment configuration. */
|
|
14
|
+
function createCrawlerRuntime(input) {
|
|
15
|
+
const compiled = (0, configuration_1.compileCrawlerConfiguration)(input.configuration, (input.now ?? Date.now)());
|
|
16
|
+
(0, activation_1.validateActivation)(input.activation, compiled.configuration.tenant);
|
|
17
|
+
const store = new operations_1.ManagedRedisAdmission(input.redis, compiled.configuration.tenant, compiled.policy, input.timeoutMs);
|
|
18
|
+
const report = new reporting_1.CrawlerReport(compiled.policy, 1024, compiled.configuration.crawlerAccess);
|
|
19
|
+
const access = compiled.configuration.crawlerAccess ?? [];
|
|
20
|
+
const guard = new guard_1.CrawlerGuard({ activation: input.activation, policy: compiled.policy, store, registry: input.registry ?? new verification_1.CrawlerRegistry(), bing: input.bing ?? new verification_1.BingVerifier(),
|
|
21
|
+
customer: input.customer, trustedEvidence: input.trustedEvidence, now: input.now,
|
|
22
|
+
crawlerAccess: (e, group) => access.find(rule => rule.provider === e.provider && rule.crawlerClass === e.crawlerClass && rule.groups.includes(group))?.action ?? 'budget',
|
|
23
|
+
onDecision: (decision, evidence, details) => {
|
|
24
|
+
report.decision(decision, evidence, details);
|
|
25
|
+
return input.onDecision?.(decision, evidence, details);
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
const adapter = { guard, clientIp: input.clientIp, route: (request) => {
|
|
29
|
+
const match = compiled.resolve(request);
|
|
30
|
+
return match.kind === 'bypass' ? undefined : { group: match.group, cost: match.cost };
|
|
31
|
+
} };
|
|
32
|
+
const settings = compiled.configuration.cache;
|
|
33
|
+
const caches = new Map((settings?.groups ?? []).map(group => [group, new cache_1.CatalogCache({ ...settings, redis: input.redis, admission: store,
|
|
34
|
+
namespace: compiled.fingerprint, onEvent: event => report.cache(group, event) })]));
|
|
35
|
+
async function work(phase, context, operation) {
|
|
36
|
+
const start = performance.now();
|
|
37
|
+
let entered = false;
|
|
38
|
+
const wrapped = async () => { entered = true; return operation(); };
|
|
39
|
+
try {
|
|
40
|
+
const value = await (phase === 'database' ? guard.withDatabaseAdmission(context, wrapped) : guard.withRenderingAdmission(context, wrapped));
|
|
41
|
+
report.work(context, { phase, outcome: 'settled', durationMs: performance.now() - start });
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
// A rejected callback is prevented work, not an estimate of queries/CPU saved.
|
|
46
|
+
report.work(context, { phase, outcome: !entered && error instanceof admission_1.AdmissionError ? 'rejected' : 'error', durationMs: performance.now() - start });
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return Object.freeze({ compiled, store, guard, report, activation: input.activation,
|
|
51
|
+
nodeMiddleware: (0, adapters_1.createNodeCrawlerMiddleware)(adapter), nuxtMiddleware: (0, adapters_1.createNuxtCrawlerMiddleware)(adapter),
|
|
52
|
+
withDatabaseAdmission: (context, operation) => work('database', context, operation),
|
|
53
|
+
withRenderingAdmission: (context, operation) => work('render', context, operation),
|
|
54
|
+
/** Loader must perform page admission and wrap render/DB work. This wrapper authenticates every request, including hits. */
|
|
55
|
+
async publicResponse(request, admittedLoader, background) {
|
|
56
|
+
input.clientIp(request);
|
|
57
|
+
(0, activation_1.assertActivation)(input.activation);
|
|
58
|
+
const route = compiled.resolve(request);
|
|
59
|
+
if (route.kind !== 'protected')
|
|
60
|
+
throw new Error('Public cache requires a protected inventoried route');
|
|
61
|
+
const cache = caches.get(route.group);
|
|
62
|
+
if (!cache) {
|
|
63
|
+
report.cache(route.group, 'bypass');
|
|
64
|
+
return admittedLoader();
|
|
65
|
+
}
|
|
66
|
+
return cache.get({ method: request.method ?? '', url: request.url ?? '', headers: request.headers }, admittedLoader, background);
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { createCrawlerRuntime } from './runtime';
|
|
2
|
+
type Runtime = ReturnType<typeof createCrawlerRuntime>;
|
|
3
|
+
/** Optional asynchronous reporting. No network I/O on admission or DB execution paths. */
|
|
4
|
+
export declare function createCrawlerTelemetry(input: {
|
|
5
|
+
runtime: Runtime;
|
|
6
|
+
endpoint: string;
|
|
7
|
+
apiKey: string;
|
|
8
|
+
site: string;
|
|
9
|
+
intervalMs?: number;
|
|
10
|
+
fetch?: typeof fetch;
|
|
11
|
+
onError?: () => void;
|
|
12
|
+
}): {
|
|
13
|
+
flush: () => Promise<void>;
|
|
14
|
+
stop(): void;
|
|
15
|
+
};
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createCrawlerTelemetry = createCrawlerTelemetry;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const operations_1 = require("./operations");
|
|
6
|
+
/** Optional asynchronous reporting. No network I/O on admission or DB execution paths. */
|
|
7
|
+
function createCrawlerTelemetry(input) {
|
|
8
|
+
const url = new URL(input.endpoint);
|
|
9
|
+
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
10
|
+
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) || url.username || url.password || url.search || url.hash || url.pathname !== '/operator/crawlers/telemetry')
|
|
11
|
+
throw Error('Invalid telemetry endpoint');
|
|
12
|
+
if (!/^val_op_[a-zA-Z0-9_-]{1,200}$/.test(input.apiKey) || !/^[a-zA-Z0-9_-]{1,100}$/.test(input.site))
|
|
13
|
+
throw Error('Invalid telemetry credentials or site');
|
|
14
|
+
const intervalMs = input.intervalMs ?? 30000;
|
|
15
|
+
if (!Number.isSafeInteger(intervalMs) || intervalMs < 10000 || intervalMs > 60000)
|
|
16
|
+
throw Error('Invalid telemetry interval');
|
|
17
|
+
const instance = (0, node_crypto_1.randomUUID)();
|
|
18
|
+
let sequence = 0, busy = false, stopped = false;
|
|
19
|
+
const { runtime } = input;
|
|
20
|
+
async function flush() {
|
|
21
|
+
if (busy || stopped)
|
|
22
|
+
return;
|
|
23
|
+
busy = true;
|
|
24
|
+
try {
|
|
25
|
+
let capacity = { available: false };
|
|
26
|
+
try {
|
|
27
|
+
const state = await runtime.store.inspect();
|
|
28
|
+
const slots = (slot) => state.holds.filter(h => h.slots?.includes(slot)).length;
|
|
29
|
+
capacity = { available: true, paused: state.paused, activePolicy: state.identity === (0, operations_1.policyFingerprint)(runtime.compiled.policy), catalog: state.catalog,
|
|
30
|
+
holds: state.holds.length, limit: runtime.compiled.policy.globalWorkLimit,
|
|
31
|
+
database: slots('global'), render: slots('ssr:global'), gateway: slots('gateway:global'),
|
|
32
|
+
oldestHoldMs: state.holds.length ? Math.max(0, Date.now() - state.holds[0].acquiredAt) : 0 };
|
|
33
|
+
}
|
|
34
|
+
catch { /* Report unavailable capacity without changing admission. */ }
|
|
35
|
+
const snapshot = runtime.report.snapshot();
|
|
36
|
+
const body = JSON.stringify({ site: input.site, instance, sequence: ++sequence, tenant: runtime.compiled.configuration.tenant,
|
|
37
|
+
configurationId: runtime.compiled.fingerprint, mode: runtime.compiled.configuration.rollout.mode,
|
|
38
|
+
overflow: snapshot.overflow + snapshot.series.slice(256).reduce((n, s) => n + s.count, 0),
|
|
39
|
+
series: snapshot.series.slice(0, 256).map(({ tags, count, durationMs }) => ({ tags, count, durationMs })), capacity });
|
|
40
|
+
if (Buffer.byteLength(body) > 262144)
|
|
41
|
+
throw Error('Telemetry too large');
|
|
42
|
+
const response = await (input.fetch ?? fetch)(url, { method: 'POST', headers: { Authorization: 'Bearer ' + input.apiKey, 'Content-Type': 'application/json' }, body,
|
|
43
|
+
redirect: 'error', signal: AbortSignal.timeout(5000) });
|
|
44
|
+
await response.body?.cancel();
|
|
45
|
+
if (!response.ok)
|
|
46
|
+
throw Error('Telemetry unavailable');
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
try {
|
|
50
|
+
input.onError?.();
|
|
51
|
+
}
|
|
52
|
+
catch { }
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
busy = false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const timer = setInterval(() => void flush(), intervalMs);
|
|
59
|
+
timer.unref();
|
|
60
|
+
return { flush, stop() { stopped = true; clearInterval(timer); } };
|
|
61
|
+
}
|