@valiron/crawler-protection 0.3.0 → 0.4.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 +100 -3
- package/dist/activation.js +1 -1
- package/dist/admission.d.ts +1 -1
- package/dist/admission.js +16 -2
- package/dist/device-identity/collector-script.d.ts +6 -0
- package/dist/device-identity/collector-script.js +9 -0
- package/dist/device-identity/cookie.d.ts +28 -0
- package/dist/device-identity/cookie.js +76 -0
- package/dist/device-identity/identity.d.ts +98 -0
- package/dist/device-identity/identity.js +198 -0
- package/dist/device-identity/index.d.ts +25 -0
- package/dist/device-identity/index.js +41 -0
- package/dist/device-identity/middleware.d.ts +26 -0
- package/dist/device-identity/middleware.js +110 -0
- package/dist/device-identity/redis.d.ts +33 -0
- package/dist/device-identity/redis.js +70 -0
- package/dist/device-identity/signals.d.ts +50 -0
- package/dist/device-identity/signals.js +120 -0
- package/dist/device-identity/store.d.ts +40 -0
- package/dist/device-identity/store.js +66 -0
- package/dist/directory.js +6 -4
- package/dist/guard.d.ts +5 -0
- package/dist/guard.js +4 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.js +13 -1
- package/dist/operations.js +2 -1
- package/dist/verification.d.ts +3 -1
- package/dist/webbotauth.d.ts +70 -0
- package/dist/webbotauth.js +323 -0
- package/gateway/README.md +1 -1
- package/package.json +4 -1
- package/public/collector.js +90 -0
package/dist/index.d.ts
CHANGED
|
@@ -14,4 +14,7 @@ export * from './onboarding';
|
|
|
14
14
|
export * from './gateway';
|
|
15
15
|
export * from './telemetry';
|
|
16
16
|
export * from './directory';
|
|
17
|
+
export * from './webbotauth';
|
|
17
18
|
export { createCrawlerActivation, activateCrawlerProtection, CRAWLER_ACTIVATION_ENDPOINT, type CrawlerActivation } from './activation';
|
|
19
|
+
export { DeviceIdentity, MemoryIdentityStore, RedisIdentityStore, createNodeDeviceIdentityMiddleware, deviceIdentityCollectorScript, serializeCookieClear, DEVICE_IDENTITY_DEFAULT_BASE_PATH, } from './device-identity';
|
|
20
|
+
export type { DeviceIdentityOptions, DeviceIdentityMiddlewareConfig, Recognition, RecognitionState, RecognizeResult, IdentityStore, StoredProfile, RawSignals, ScreenSignals, CookieOptions, VerifiedCookie, } from './device-identity';
|
package/dist/index.js
CHANGED
|
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.CRAWLER_ACTIVATION_ENDPOINT = exports.activateCrawlerProtection = exports.createCrawlerActivation = void 0;
|
|
17
|
+
exports.DEVICE_IDENTITY_DEFAULT_BASE_PATH = exports.serializeCookieClear = exports.deviceIdentityCollectorScript = exports.createNodeDeviceIdentityMiddleware = exports.RedisIdentityStore = exports.MemoryIdentityStore = exports.DeviceIdentity = exports.CRAWLER_ACTIVATION_ENDPOINT = exports.activateCrawlerProtection = exports.createCrawlerActivation = void 0;
|
|
18
18
|
__exportStar(require("./ip"), exports);
|
|
19
19
|
__exportStar(require("./verification"), exports);
|
|
20
20
|
__exportStar(require("./admission"), exports);
|
|
@@ -31,7 +31,19 @@ __exportStar(require("./onboarding"), exports);
|
|
|
31
31
|
__exportStar(require("./gateway"), exports);
|
|
32
32
|
__exportStar(require("./telemetry"), exports);
|
|
33
33
|
__exportStar(require("./directory"), exports);
|
|
34
|
+
__exportStar(require("./webbotauth"), exports);
|
|
34
35
|
var activation_1 = require("./activation");
|
|
35
36
|
Object.defineProperty(exports, "createCrawlerActivation", { enumerable: true, get: function () { return activation_1.createCrawlerActivation; } });
|
|
36
37
|
Object.defineProperty(exports, "activateCrawlerProtection", { enumerable: true, get: function () { return activation_1.activateCrawlerProtection; } });
|
|
37
38
|
Object.defineProperty(exports, "CRAWLER_ACTIVATION_ENDPOINT", { enumerable: true, get: function () { return activation_1.CRAWLER_ACTIVATION_ENDPOINT; } });
|
|
39
|
+
// Returning-browser recognition, folded into Crawler Protection so existing
|
|
40
|
+
// installs gain it without a second SDK. Evidence only: no fraud verdicts,
|
|
41
|
+
// no enforcement; collection activates only when the middleware is mounted.
|
|
42
|
+
var device_identity_1 = require("./device-identity");
|
|
43
|
+
Object.defineProperty(exports, "DeviceIdentity", { enumerable: true, get: function () { return device_identity_1.DeviceIdentity; } });
|
|
44
|
+
Object.defineProperty(exports, "MemoryIdentityStore", { enumerable: true, get: function () { return device_identity_1.MemoryIdentityStore; } });
|
|
45
|
+
Object.defineProperty(exports, "RedisIdentityStore", { enumerable: true, get: function () { return device_identity_1.RedisIdentityStore; } });
|
|
46
|
+
Object.defineProperty(exports, "createNodeDeviceIdentityMiddleware", { enumerable: true, get: function () { return device_identity_1.createNodeDeviceIdentityMiddleware; } });
|
|
47
|
+
Object.defineProperty(exports, "deviceIdentityCollectorScript", { enumerable: true, get: function () { return device_identity_1.deviceIdentityCollectorScript; } });
|
|
48
|
+
Object.defineProperty(exports, "serializeCookieClear", { enumerable: true, get: function () { return device_identity_1.serializeCookieClear; } });
|
|
49
|
+
Object.defineProperty(exports, "DEVICE_IDENTITY_DEFAULT_BASE_PATH", { enumerable: true, get: function () { return device_identity_1.DEVICE_IDENTITY_DEFAULT_BASE_PATH; } });
|
package/dist/operations.js
CHANGED
|
@@ -31,7 +31,8 @@ if lane == 'catalog' or lane == 'cache' or lane == 'gateway' then
|
|
|
31
31
|
if state == 'open' then return 0 end
|
|
32
32
|
if state == 'probe' then
|
|
33
33
|
if lane == 'cache' then return 0 end
|
|
34
|
-
|
|
34
|
+
-- KEYS[1] is the pending-acquire cancellation key; KEYS[2] is inventory.
|
|
35
|
+
for _,raw in ipairs(redis.call('HVALS',KEYS[2])) do
|
|
35
36
|
local held=cjson.decode(raw)
|
|
36
37
|
if held.lane == lane then return 0 end
|
|
37
38
|
end
|
package/dist/verification.d.ts
CHANGED
|
@@ -3,9 +3,11 @@ export type CrawlerEvidence = Readonly<{
|
|
|
3
3
|
claimedCrawler?: string;
|
|
4
4
|
provider?: string;
|
|
5
5
|
crawlerClass?: string;
|
|
6
|
-
method?: 'published_cidr' | 'forward_confirmed_reverse_dns' | 'trusted_waf' | 'directory_cidr';
|
|
6
|
+
method?: 'published_cidr' | 'forward_confirmed_reverse_dns' | 'trusted_waf' | 'directory_cidr' | 'web_bot_auth';
|
|
7
7
|
evidenceVersion?: string;
|
|
8
8
|
expiresAt?: number;
|
|
9
|
+
/** Set only after a Web Bot Auth signature cryptographically verifies; a claimed URL is never reported. */
|
|
10
|
+
signerUrl?: string;
|
|
9
11
|
}>;
|
|
10
12
|
type Claim = {
|
|
11
13
|
provider: string;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { CrawlerEvidence } from './verification';
|
|
2
|
+
/**
|
|
3
|
+
* Web Bot Auth (draft-ietf-webbotauth-httpsig-protocol) verification for
|
|
4
|
+
* crawlers and agents that cannot publish IP ranges.
|
|
5
|
+
*
|
|
6
|
+
* Scope and trust model:
|
|
7
|
+
* - A valid signature proves control of a pinned key for a Signature-Agent URL.
|
|
8
|
+
* It is not proof of good intent, of a recognized provider, or of admission.
|
|
9
|
+
* Budgets and policy still apply exactly as with IP/DNS verification.
|
|
10
|
+
* - Pin-only: keys come from operator-reviewed configuration. This module
|
|
11
|
+
* performs no network fetch, so a request can never steer this process into
|
|
12
|
+
* contacting an attacker-chosen directory URL. Dynamic resolution is
|
|
13
|
+
* deliberately omitted until it can ship with connect-time destination
|
|
14
|
+
* validation and bounded egress.
|
|
15
|
+
* - Freshness is not replay protection. The draft minimum coverage binds only
|
|
16
|
+
* @authority, so a captured signature can be replayed against this origin
|
|
17
|
+
* until `expires`. Verified signers remain subject to every budget, which
|
|
18
|
+
* bounds replay damage, and promotion to verified evidence is opt-in per
|
|
19
|
+
* signer. The optional 'strict' profile additionally requires @method and
|
|
20
|
+
* @path coverage; it is a Valiron profile stronger than the draft minimum,
|
|
21
|
+
* not a standard compliance claim.
|
|
22
|
+
*/
|
|
23
|
+
export type WebBotAuthAgent = Readonly<{
|
|
24
|
+
provider: string;
|
|
25
|
+
crawlerClass: string;
|
|
26
|
+
/** Pinned Ed25519 JWKs (kty OKP, crv Ed25519) served by the signer URL. */
|
|
27
|
+
keys: readonly unknown[];
|
|
28
|
+
/** Opt-in: allow a valid signature to produce verified evidence. Default false:
|
|
29
|
+
* the authenticated signer is reported but admission stays on unverified budgets. */
|
|
30
|
+
promote?: boolean;
|
|
31
|
+
/** 'strict' additionally requires "@method" and "@path" coverage. Default draft minimum. */
|
|
32
|
+
profile?: 'standard' | 'strict';
|
|
33
|
+
}>;
|
|
34
|
+
type HeaderView = Readonly<{
|
|
35
|
+
method?: string;
|
|
36
|
+
url?: string;
|
|
37
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
38
|
+
}>;
|
|
39
|
+
/** base64url JWK SHA-256 thumbprint for an Ed25519 OKP key (RFC 8037 Appendix A.3). */
|
|
40
|
+
export declare function ed25519Thumbprint(jwk: {
|
|
41
|
+
kty: string;
|
|
42
|
+
crv: string;
|
|
43
|
+
x: string;
|
|
44
|
+
}): string;
|
|
45
|
+
export declare class WebBotAuthVerifier {
|
|
46
|
+
private readonly agents;
|
|
47
|
+
private readonly now;
|
|
48
|
+
private readonly maxWindowMs;
|
|
49
|
+
private readonly skewMs;
|
|
50
|
+
constructor(options: {
|
|
51
|
+
agents: Readonly<Record<string, WebBotAuthAgent>>;
|
|
52
|
+
now?: () => number;
|
|
53
|
+
maxSignatureWindowMs?: number;
|
|
54
|
+
clockSkewMs?: number;
|
|
55
|
+
});
|
|
56
|
+
/**
|
|
57
|
+
* Compatible with CrawlerGuard's fallbackEvidence hook: pass the inbound request.
|
|
58
|
+
* Wired as fallbackEvidence, Web Bot Auth is consulted only when trusted/IP/DNS
|
|
59
|
+
* evidence did not verify, so an existing verified identity always stands.
|
|
60
|
+
* Returns undefined when the request carries no Web Bot Auth material, so the
|
|
61
|
+
* original evidence proceeds unchanged.
|
|
62
|
+
*/
|
|
63
|
+
fallbackEvidence(request: unknown): CrawlerEvidence | undefined;
|
|
64
|
+
classify(request: HeaderView): CrawlerEvidence | undefined;
|
|
65
|
+
private verifyCandidate;
|
|
66
|
+
/** RFC 9421 signature base, rebuilt from the exact raw parameters the signer sent. */
|
|
67
|
+
private signatureBase;
|
|
68
|
+
private componentValue;
|
|
69
|
+
}
|
|
70
|
+
export {};
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.WebBotAuthVerifier = void 0;
|
|
4
|
+
exports.ed25519Thumbprint = ed25519Thumbprint;
|
|
5
|
+
const node_crypto_1 = require("node:crypto");
|
|
6
|
+
const MAX_HEADER = 8192;
|
|
7
|
+
const MAX_SIGNATURES = 4;
|
|
8
|
+
const MAX_AGENTS = 2000;
|
|
9
|
+
const MAX_KEYS = 16;
|
|
10
|
+
const DEFAULT_MAX_WINDOW_MS = 24 * 3600 * 1000; // draft recommends expires <= created + 24h
|
|
11
|
+
const DEFAULT_SKEW_MS = 60000;
|
|
12
|
+
const identityLabel = /^[a-z0-9_-]{1,64}$/;
|
|
13
|
+
function headerValue(headers, name) {
|
|
14
|
+
const value = headers?.[name];
|
|
15
|
+
const single = Array.isArray(value) ? (value.length === 1 ? value[0] : undefined) : value;
|
|
16
|
+
if (typeof single !== 'string' || single.length > MAX_HEADER)
|
|
17
|
+
return undefined;
|
|
18
|
+
return single;
|
|
19
|
+
}
|
|
20
|
+
/** Split on top-level separators, ignoring those inside strings or inner lists. */
|
|
21
|
+
function splitTopLevel(value, separator) {
|
|
22
|
+
const out = [];
|
|
23
|
+
let depth = 0, quoted = false, start = 0;
|
|
24
|
+
for (let i = 0; i < value.length; i++) {
|
|
25
|
+
const c = value[i];
|
|
26
|
+
if (quoted) {
|
|
27
|
+
if (c === '\\')
|
|
28
|
+
i++;
|
|
29
|
+
else if (c === '"')
|
|
30
|
+
quoted = false;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (c === '"')
|
|
34
|
+
quoted = true;
|
|
35
|
+
else if (c === '(')
|
|
36
|
+
depth++;
|
|
37
|
+
else if (c === ')')
|
|
38
|
+
depth = Math.max(0, depth - 1);
|
|
39
|
+
else if (c === separator && depth === 0) {
|
|
40
|
+
out.push(value.slice(start, i));
|
|
41
|
+
start = i + 1;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
out.push(value.slice(start));
|
|
45
|
+
return out.map(part => part.trim()).filter(Boolean);
|
|
46
|
+
}
|
|
47
|
+
function parseStringItem(value) {
|
|
48
|
+
if (value.length < 2 || value[0] !== '"' || value[value.length - 1] !== '"')
|
|
49
|
+
return undefined;
|
|
50
|
+
const inner = value.slice(1, -1);
|
|
51
|
+
if (!/^[ -~]*$/.test(inner))
|
|
52
|
+
return undefined;
|
|
53
|
+
return inner.replace(/\\(["\\])/g, '$1');
|
|
54
|
+
}
|
|
55
|
+
/** Parse one Signature-Input member: ("comp" "comp";key="label");created=...;expires=...;keyid="...";tag="..." */
|
|
56
|
+
function parseSignatureInputMember(label, raw) {
|
|
57
|
+
const close = raw.indexOf(')');
|
|
58
|
+
if (!raw.startsWith('(') || close < 0)
|
|
59
|
+
return undefined;
|
|
60
|
+
const inner = raw.slice(1, close);
|
|
61
|
+
const params = raw.slice(close + 1);
|
|
62
|
+
const components = [];
|
|
63
|
+
for (const item of splitTopLevel(inner, ' ')) {
|
|
64
|
+
const paramAt = item.indexOf(';');
|
|
65
|
+
const name = parseStringItem(paramAt === -1 ? item : item.slice(0, paramAt));
|
|
66
|
+
if (!name || name.length > 64)
|
|
67
|
+
return undefined;
|
|
68
|
+
let key;
|
|
69
|
+
if (paramAt !== -1) {
|
|
70
|
+
const match = /^;key=("(?:[^"\\]|\\.){1,64}")$/.exec(item.slice(paramAt));
|
|
71
|
+
if (!match)
|
|
72
|
+
return undefined; // only the key parameter is consumed here
|
|
73
|
+
key = parseStringItem(match[1]);
|
|
74
|
+
if (!key)
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
components.push({ id: name.toLowerCase(), key });
|
|
78
|
+
}
|
|
79
|
+
if (!components.length || components.length > 16)
|
|
80
|
+
return undefined;
|
|
81
|
+
const parsed = {};
|
|
82
|
+
for (const param of splitTopLevel(params.replace(/;/g, ','), ',')) {
|
|
83
|
+
if (!param)
|
|
84
|
+
continue;
|
|
85
|
+
const eq = param.indexOf('=');
|
|
86
|
+
if (eq < 1)
|
|
87
|
+
return undefined;
|
|
88
|
+
parsed[param.slice(0, eq).trim().toLowerCase()] = param.slice(eq + 1).trim();
|
|
89
|
+
}
|
|
90
|
+
const created = Number(parsed.created), expires = Number(parsed.expires);
|
|
91
|
+
const keyid = parsed.keyid ? parseStringItem(parsed.keyid) : undefined;
|
|
92
|
+
const tag = parsed.tag ? parseStringItem(parsed.tag) : undefined;
|
|
93
|
+
if (!Number.isSafeInteger(created) || !Number.isSafeInteger(expires) || !keyid || keyid.length > 64 || tag !== 'web-bot-auth')
|
|
94
|
+
return undefined;
|
|
95
|
+
return { label, raw: raw.trim(), components, created, expires, keyid, tag };
|
|
96
|
+
}
|
|
97
|
+
/** Signature-Agent members keyed by signature label, plus the legacy bare-string form. */
|
|
98
|
+
function parseSignatureAgent(header) {
|
|
99
|
+
const members = new Map();
|
|
100
|
+
if (header.startsWith('"')) {
|
|
101
|
+
const value = parseStringItem(header.trim());
|
|
102
|
+
return value ? new Map([['', value]]) : undefined; // legacy form; caller maps the covering label
|
|
103
|
+
}
|
|
104
|
+
for (const entry of splitTopLevel(header, ',')) {
|
|
105
|
+
const eq = entry.indexOf('=');
|
|
106
|
+
if (eq < 1)
|
|
107
|
+
return undefined;
|
|
108
|
+
const label = entry.slice(0, eq).trim();
|
|
109
|
+
let value = entry.slice(eq + 1).trim();
|
|
110
|
+
const semi = value.indexOf(';');
|
|
111
|
+
if (semi !== -1) {
|
|
112
|
+
value = value.slice(0, semi).trim();
|
|
113
|
+
continue;
|
|
114
|
+
} // members with parameters MUST be ignored
|
|
115
|
+
const url = parseStringItem(value);
|
|
116
|
+
if (!url)
|
|
117
|
+
return undefined;
|
|
118
|
+
members.set(label, url);
|
|
119
|
+
}
|
|
120
|
+
return members.size ? members : undefined;
|
|
121
|
+
}
|
|
122
|
+
function httpsAgentUrl(value) {
|
|
123
|
+
if (value.length > 2048)
|
|
124
|
+
return undefined;
|
|
125
|
+
try {
|
|
126
|
+
const url = new URL(value);
|
|
127
|
+
if (url.protocol !== 'https:' || url.username || url.password)
|
|
128
|
+
return undefined;
|
|
129
|
+
return url.href;
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/** base64url JWK SHA-256 thumbprint for an Ed25519 OKP key (RFC 8037 Appendix A.3). */
|
|
136
|
+
function ed25519Thumbprint(jwk) {
|
|
137
|
+
const canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x });
|
|
138
|
+
return (0, node_crypto_1.createHash)('sha256').update(canonical, 'utf8').digest('base64url');
|
|
139
|
+
}
|
|
140
|
+
function pinKeys(keys) {
|
|
141
|
+
if (!Array.isArray(keys) || !keys.length || keys.length > MAX_KEYS)
|
|
142
|
+
throw new Error('Invalid pinned key set');
|
|
143
|
+
return keys.map(candidate => {
|
|
144
|
+
const jwk = candidate;
|
|
145
|
+
if (!jwk || jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.x !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(jwk.x)) {
|
|
146
|
+
throw new Error('Only Ed25519 OKP JWKs are supported');
|
|
147
|
+
}
|
|
148
|
+
const key = (0, node_crypto_1.createPublicKey)({ key: { kty: 'OKP', crv: 'Ed25519', x: jwk.x }, format: 'jwk' });
|
|
149
|
+
return { thumbprint: ed25519Thumbprint({ kty: 'OKP', crv: 'Ed25519', x: jwk.x }), key };
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
class WebBotAuthVerifier {
|
|
153
|
+
agents = new Map();
|
|
154
|
+
now;
|
|
155
|
+
maxWindowMs;
|
|
156
|
+
skewMs;
|
|
157
|
+
constructor(options) {
|
|
158
|
+
if (!options.agents || typeof options.agents !== 'object' || Array.isArray(options.agents) ||
|
|
159
|
+
Object.keys(options.agents).length > MAX_AGENTS)
|
|
160
|
+
throw new Error('Invalid Web Bot Auth agents');
|
|
161
|
+
this.now = options.now ?? Date.now;
|
|
162
|
+
this.maxWindowMs = options.maxSignatureWindowMs ?? DEFAULT_MAX_WINDOW_MS;
|
|
163
|
+
this.skewMs = options.clockSkewMs ?? DEFAULT_SKEW_MS;
|
|
164
|
+
if (!Number.isSafeInteger(this.maxWindowMs) || this.maxWindowMs < 1000 || this.maxWindowMs > DEFAULT_MAX_WINDOW_MS ||
|
|
165
|
+
!Number.isSafeInteger(this.skewMs) || this.skewMs < 0 || this.skewMs > 300000)
|
|
166
|
+
throw new Error('Invalid freshness bounds');
|
|
167
|
+
for (const [rawUrl, config] of Object.entries(options.agents)) {
|
|
168
|
+
const url = httpsAgentUrl(rawUrl);
|
|
169
|
+
if (!url || !config || !identityLabel.test(config.provider) || !identityLabel.test(config.crawlerClass) ||
|
|
170
|
+
(config.profile !== undefined && !['standard', 'strict'].includes(config.profile))) {
|
|
171
|
+
throw new Error('Invalid Web Bot Auth agent');
|
|
172
|
+
}
|
|
173
|
+
this.agents.set(url, { config: Object.freeze({ ...config }), keys: pinKeys(config.keys) });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Compatible with CrawlerGuard's fallbackEvidence hook: pass the inbound request.
|
|
178
|
+
* Wired as fallbackEvidence, Web Bot Auth is consulted only when trusted/IP/DNS
|
|
179
|
+
* evidence did not verify, so an existing verified identity always stands.
|
|
180
|
+
* Returns undefined when the request carries no Web Bot Auth material, so the
|
|
181
|
+
* original evidence proceeds unchanged.
|
|
182
|
+
*/
|
|
183
|
+
fallbackEvidence(request) {
|
|
184
|
+
return this.classify(request);
|
|
185
|
+
}
|
|
186
|
+
classify(request) {
|
|
187
|
+
const signatureInput = headerValue(request?.headers, 'signature-input');
|
|
188
|
+
const signature = headerValue(request?.headers, 'signature');
|
|
189
|
+
const signatureAgent = headerValue(request?.headers, 'signature-agent');
|
|
190
|
+
if (signatureInput === undefined && signature === undefined && signatureAgent === undefined)
|
|
191
|
+
return undefined;
|
|
192
|
+
if (!signatureInput || !signature || !signatureAgent)
|
|
193
|
+
return { state: 'unverified' };
|
|
194
|
+
const agentUrls = parseSignatureAgent(signatureAgent);
|
|
195
|
+
if (!agentUrls)
|
|
196
|
+
return { state: 'unverified' };
|
|
197
|
+
const inputs = splitTopLevel(signatureInput, ',').slice(0, MAX_SIGNATURES + 1);
|
|
198
|
+
const signatures = splitTopLevel(signature, ',').slice(0, MAX_SIGNATURES + 1);
|
|
199
|
+
if (inputs.length > MAX_SIGNATURES || signatures.length > MAX_SIGNATURES)
|
|
200
|
+
return { state: 'unverified' };
|
|
201
|
+
const signatureValues = new Map();
|
|
202
|
+
for (const entry of signatures) {
|
|
203
|
+
const match = /^([a-z0-9.*-]{1,64})=:([A-Za-z0-9+/=_-]{1,4096}):$/.exec(entry);
|
|
204
|
+
if (!match)
|
|
205
|
+
return { state: 'unverified' };
|
|
206
|
+
signatureValues.set(match[1], match[2]);
|
|
207
|
+
}
|
|
208
|
+
for (const member of inputs) {
|
|
209
|
+
const eq = member.indexOf('=');
|
|
210
|
+
if (eq < 1)
|
|
211
|
+
continue;
|
|
212
|
+
const label = member.slice(0, eq).trim();
|
|
213
|
+
const params = parseSignatureInputMember(label, member.slice(eq + 1));
|
|
214
|
+
if (!params)
|
|
215
|
+
continue; // not a Web Bot Auth signature; another label may be
|
|
216
|
+
const outcome = this.verifyCandidate(request, params, agentUrls, signatureValues);
|
|
217
|
+
if (outcome)
|
|
218
|
+
return outcome;
|
|
219
|
+
}
|
|
220
|
+
return { state: 'unverified' };
|
|
221
|
+
}
|
|
222
|
+
verifyCandidate(request, params, agentUrls, signatureValues) {
|
|
223
|
+
// Required draft coverage: @authority plus the signature-agent member for this label.
|
|
224
|
+
const hasAuthority = params.components.some(c => c.id === '@authority' && !c.key);
|
|
225
|
+
const agentComponent = params.components.find(c => c.id === 'signature-agent' && c.key === params.label);
|
|
226
|
+
if (!hasAuthority || !agentComponent)
|
|
227
|
+
return undefined;
|
|
228
|
+
const rawUrl = agentUrls.get(params.label) ?? agentUrls.get(''); // legacy bare string
|
|
229
|
+
const url = rawUrl !== undefined ? httpsAgentUrl(rawUrl) : undefined;
|
|
230
|
+
if (!url)
|
|
231
|
+
return { state: 'unverified' };
|
|
232
|
+
const agent = this.agents.get(url);
|
|
233
|
+
if (!agent)
|
|
234
|
+
return { state: 'unverified' }; // unpinned signer: claim only, never privileged
|
|
235
|
+
const claimedCrawler = agent.config.crawlerClass;
|
|
236
|
+
const now = this.now();
|
|
237
|
+
// Freshness bounds the replay window; it is not replay protection.
|
|
238
|
+
if (params.expires * 1000 <= now - this.skewMs || params.created * 1000 > now + this.skewMs ||
|
|
239
|
+
(params.expires - params.created) * 1000 > this.maxWindowMs)
|
|
240
|
+
return { state: 'unverified', claimedCrawler };
|
|
241
|
+
if (agent.config.profile === 'strict' &&
|
|
242
|
+
!['@method', '@path'].every(id => params.components.some(c => c.id === id && !c.key))) {
|
|
243
|
+
return { state: 'claim_mismatch', claimedCrawler };
|
|
244
|
+
}
|
|
245
|
+
const key = agent.keys.find(candidate => candidate.thumbprint === params.keyid);
|
|
246
|
+
if (!key)
|
|
247
|
+
return { state: 'claim_mismatch', claimedCrawler }; // pinned set is evidence; a missing key fails
|
|
248
|
+
const signatureBase = this.signatureBase(request, params, url);
|
|
249
|
+
if (!signatureBase)
|
|
250
|
+
return { state: 'claim_mismatch', claimedCrawler };
|
|
251
|
+
const signatureBytes = Buffer.from(signatureValues.get(params.label) ?? '', 'base64');
|
|
252
|
+
if (!signatureBytes.length)
|
|
253
|
+
return { state: 'claim_mismatch', claimedCrawler };
|
|
254
|
+
let valid = false;
|
|
255
|
+
try {
|
|
256
|
+
valid = (0, node_crypto_1.verify)(null, Buffer.from(signatureBase, 'utf8'), key.key, signatureBytes);
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
valid = false;
|
|
260
|
+
}
|
|
261
|
+
if (!valid)
|
|
262
|
+
return { state: 'claim_mismatch', claimedCrawler };
|
|
263
|
+
if (agent.config.promote !== true) {
|
|
264
|
+
// Authenticated but not promoted: report the signer, keep unverified budgets.
|
|
265
|
+
return { state: 'unverified', claimedCrawler, signerUrl: url };
|
|
266
|
+
}
|
|
267
|
+
return {
|
|
268
|
+
state: 'verified', claimedCrawler, provider: agent.config.provider, crawlerClass: agent.config.crawlerClass,
|
|
269
|
+
method: 'web_bot_auth', evidenceVersion: 'webbotauth-pinned-v1', signerUrl: url,
|
|
270
|
+
expiresAt: params.expires * 1000,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
/** RFC 9421 signature base, rebuilt from the exact raw parameters the signer sent. */
|
|
274
|
+
signatureBase(request, params, agentUrl) {
|
|
275
|
+
const lines = [];
|
|
276
|
+
for (const component of params.components) {
|
|
277
|
+
const serialized = this.componentValue(request, component, agentUrl);
|
|
278
|
+
if (serialized === undefined)
|
|
279
|
+
return undefined;
|
|
280
|
+
const identifier = component.key !== undefined ? `"${component.id}";key="${component.key}"` : `"${component.id}"`;
|
|
281
|
+
lines.push(`${identifier}: ${serialized}`);
|
|
282
|
+
}
|
|
283
|
+
lines.push(`"@signature-params": ${params.raw}`);
|
|
284
|
+
return lines.join('\n');
|
|
285
|
+
}
|
|
286
|
+
componentValue(request, component, agentUrl) {
|
|
287
|
+
if (component.id === 'signature-agent')
|
|
288
|
+
return component.key !== undefined ? `"${agentUrl}"` : undefined;
|
|
289
|
+
if (component.key !== undefined)
|
|
290
|
+
return undefined; // only signature-agent;key is supported
|
|
291
|
+
switch (component.id) {
|
|
292
|
+
case '@authority': {
|
|
293
|
+
const host = headerValue(request.headers, 'host')?.toLowerCase();
|
|
294
|
+
if (!host || host.length > 255 || /[\r\n]/.test(host))
|
|
295
|
+
return undefined;
|
|
296
|
+
return host;
|
|
297
|
+
}
|
|
298
|
+
case '@method': {
|
|
299
|
+
const method = request.method?.toLowerCase();
|
|
300
|
+
return method && /^[a-z]{1,16}$/.test(method) ? method : undefined;
|
|
301
|
+
}
|
|
302
|
+
case '@path': {
|
|
303
|
+
const path = request.url ?? '';
|
|
304
|
+
const queryAt = path.indexOf('?');
|
|
305
|
+
const value = queryAt === -1 ? path : path.slice(0, queryAt);
|
|
306
|
+
return value.startsWith('/') && value.length <= 4096 ? value : undefined;
|
|
307
|
+
}
|
|
308
|
+
case '@target-uri':
|
|
309
|
+
case '@scheme':
|
|
310
|
+
case '@request-target':
|
|
311
|
+
case '@query':
|
|
312
|
+
case '@status':
|
|
313
|
+
return undefined; // not reconstructible from the inbound view; treated as unverifiable
|
|
314
|
+
default: {
|
|
315
|
+
if (component.id.startsWith('@'))
|
|
316
|
+
return undefined;
|
|
317
|
+
const value = headerValue(request.headers, component.id);
|
|
318
|
+
return value !== undefined && !/[\r\n]/.test(value) ? value : undefined;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
exports.WebBotAuthVerifier = WebBotAuthVerifier;
|
package/gateway/README.md
CHANGED
|
@@ -40,7 +40,7 @@ node packages/valiron-crawler-protection/gateway/service.cjs
|
|
|
40
40
|
|
|
41
41
|
Provision authoritative `noeviction` Redis, configure a schema-v1 exported site policy and supply server-only environment settings. `--check` validates configuration and API-key syntax without listening, connecting to Redis, checking the subscription online, activating policy or printing secrets. Normal startup checks the current Free/Pro/Enterprise account before listening. Build the supplied Dockerfile from the repository root to run the same service as a container. The Compose template keeps Redis and the work API off public host ports; attach the application to its separate private work network if it needs operation admission.
|
|
42
42
|
|
|
43
|
-
Required settings (SDK 0.
|
|
43
|
+
Required settings (SDK 0.3.0+):
|
|
44
44
|
|
|
45
45
|
| Setting | Purpose |
|
|
46
46
|
| --- | --- |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@valiron/crawler-protection",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Valiron Crawler Protection: HTTP gateway and shared workload admission for any website backend",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
"files": [
|
|
14
14
|
"dist",
|
|
15
15
|
"README.md",
|
|
16
|
+
"public/collector.js",
|
|
16
17
|
"gateway/service.cjs",
|
|
17
18
|
"gateway/admin.cjs",
|
|
18
19
|
"gateway/directory.cjs",
|
|
@@ -57,3 +58,5 @@
|
|
|
57
58
|
"registry": "https://registry.npmjs.org/"
|
|
58
59
|
}
|
|
59
60
|
}
|
|
61
|
+
|
|
62
|
+
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Valiron Device Identity collector (browser), shipped inside
|
|
3
|
+
* Valiron Crawler Protection and served by createNodeDeviceIdentityMiddleware().
|
|
4
|
+
*
|
|
5
|
+
* Collects coarsened device signals and POSTs them to the deployment's
|
|
6
|
+
* identify endpoint. The deterministic visitor id lives in a first-party,
|
|
7
|
+
* HttpOnly cookie set by the server; this script never reads or writes it,
|
|
8
|
+
* and it never touches localStorage. No third-party requests are made.
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* <script src="/api/valiron/device-identity/collector.js"></script>
|
|
12
|
+
* <script>
|
|
13
|
+
* ValironDevice.identify({ endpoint: '/api/valiron/device-identity/identify' })
|
|
14
|
+
* .then(function (result) { console.log(result.state); });
|
|
15
|
+
* </script>
|
|
16
|
+
*
|
|
17
|
+
* Set respectPrivacySignals: true to skip collection entirely when the
|
|
18
|
+
* browser sends Do Not Track or Global Privacy Control.
|
|
19
|
+
*/
|
|
20
|
+
(function () {
|
|
21
|
+
'use strict';
|
|
22
|
+
|
|
23
|
+
function safe(fn, fallback) {
|
|
24
|
+
try {
|
|
25
|
+
var value = fn();
|
|
26
|
+
return value === undefined ? fallback : value;
|
|
27
|
+
} catch (_) {
|
|
28
|
+
return fallback;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function privacyRequested() {
|
|
33
|
+
return safe(function () { return navigator.globalPrivacyControl === true; }, false)
|
|
34
|
+
|| safe(function () { return navigator.doNotTrack === '1' || window.doNotTrack === '1'; }, false);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function collect() {
|
|
38
|
+
var screen_ = safe(function () {
|
|
39
|
+
return {
|
|
40
|
+
width: window.screen.width,
|
|
41
|
+
height: window.screen.height,
|
|
42
|
+
colorDepth: window.screen.colorDepth,
|
|
43
|
+
pixelRatio: window.devicePixelRatio,
|
|
44
|
+
};
|
|
45
|
+
}, undefined);
|
|
46
|
+
return {
|
|
47
|
+
userAgent: safe(function () { return navigator.userAgent; }, undefined),
|
|
48
|
+
languages: safe(function () {
|
|
49
|
+
return navigator.languages && navigator.languages.length ? Array.from(navigator.languages) : [navigator.language];
|
|
50
|
+
}, undefined),
|
|
51
|
+
timezone: safe(function () { return Intl.DateTimeFormat().resolvedOptions().timeZone; }, undefined),
|
|
52
|
+
platform: safe(function () { return navigator.platform; }, undefined),
|
|
53
|
+
hardwareConcurrency: safe(function () { return navigator.hardwareConcurrency; }, undefined),
|
|
54
|
+
deviceMemory: safe(function () { return navigator.deviceMemory; }, undefined),
|
|
55
|
+
maxTouchPoints: safe(function () { return navigator.maxTouchPoints; }, undefined),
|
|
56
|
+
screen: screen_,
|
|
57
|
+
cookiesEnabled: safe(function () { return navigator.cookieEnabled; }, undefined),
|
|
58
|
+
doNotTrack: privacyRequested(),
|
|
59
|
+
webdriver: safe(function () { return navigator.webdriver === true; }, undefined),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function identify(options) {
|
|
64
|
+
if (!options || typeof options.endpoint !== 'string' || options.endpoint.length > 2048) {
|
|
65
|
+
return Promise.reject(new Error('ValironDevice: endpoint is required'));
|
|
66
|
+
}
|
|
67
|
+
if (options.respectPrivacySignals === true && privacyRequested()) {
|
|
68
|
+
return Promise.resolve({ state: 'skipped', reason: 'privacy_signal' });
|
|
69
|
+
}
|
|
70
|
+
var timeoutMs = typeof options.timeoutMs === 'number' && options.timeoutMs >= 500 && options.timeoutMs <= 10000
|
|
71
|
+
? options.timeoutMs : 4000;
|
|
72
|
+
var controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
|
|
73
|
+
var timer = controller ? setTimeout(function () { controller.abort(); }, timeoutMs) : undefined;
|
|
74
|
+
return fetch(options.endpoint, {
|
|
75
|
+
method: 'POST',
|
|
76
|
+
headers: { 'content-type': 'application/json' },
|
|
77
|
+
credentials: options.credentials || 'same-origin',
|
|
78
|
+
body: JSON.stringify({ signals: collect() }),
|
|
79
|
+
signal: controller ? controller.signal : undefined,
|
|
80
|
+
}).then(function (response) {
|
|
81
|
+
if (!response.ok) throw new Error('ValironDevice: identify failed with ' + response.status);
|
|
82
|
+
return response.json();
|
|
83
|
+
}).finally(function () {
|
|
84
|
+
if (timer) clearTimeout(timer);
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
window.ValironDevice = Object.freeze({ identify: identify, collect: collect });
|
|
89
|
+
})();
|
|
90
|
+
|