@valiron/crawler-protection 0.2.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 +107 -6
- package/dist/activation.d.ts +5 -1
- package/dist/activation.js +27 -7
- 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 +8 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.js +13 -1
- package/dist/operations.js +2 -1
- package/dist/runtime.d.ts +1 -0
- package/dist/verification.d.ts +3 -1
- package/dist/webbotauth.d.ts +70 -0
- package/dist/webbotauth.js +323 -0
- package/gateway/README.md +4 -4
- package/package.json +4 -1
- package/public/collector.js +90 -0
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Install the integration package from npm: `npm install @valiron/crawler-protecti
|
|
|
4
4
|
|
|
5
5
|
**Any HTTP backend:** deploy the [standalone HTTP gateway](gateway/README.md) before your origin, with shared route/rate/origin-concurrency admission. PHP, Python, Ruby, Java, Go and other HTTP backends do not need to install a Node SDK. Use the private work-admission protocol around individual database operations; a standard-library Python client is included. Node/Nuxt in-process adapters remain available. SQLite and MariaDB are tested; other SQL/NoSQL drivers require integration and confirmed-settlement validation. The gateway alone does not automatically instrument queries or connection pools. Gateway deployment requires control of routing and origin access; hosted platforms that prevent those controls need a platform integration.
|
|
6
6
|
|
|
7
|
-
Integration for [Valiron Crawler Protection](https://www.valiron.co/docs/crawler-protection). Protects origin work in customer infrastructure. No blockchain
|
|
7
|
+
Integration for [Valiron Crawler Protection](https://www.valiron.co/docs/crawler-protection). Protects origin work in customer infrastructure. No blockchain or crawler signup is required. SDK 0.3.0+ requires a Free/Pro/Enterprise operator API key at startup and refreshes a short-lived account lease in the background.
|
|
8
8
|
|
|
9
9
|
Customer-facing behavior and integration contracts are documented in the [controlled crawler access guide](https://www.valiron.co/docs/agents/CRAWLER-PROTECTION.md). Install it with `npm install @valiron/crawler-protection`; it is separate from `@valiron/sdk`.
|
|
10
10
|
|
|
@@ -21,9 +21,53 @@ Implemented:
|
|
|
21
21
|
|
|
22
22
|
This is an origin admission library, not a complete bot detector. A matching user-agent and source network establish provenance, not human identity or proven crawler intent. Meta classes can use verified AWS WAF evidence over a protected ingress path; no Meta CIDR/ASN verifier is assumed. Header spoofing without a network match does not receive verified allowances.
|
|
23
23
|
|
|
24
|
-
##
|
|
24
|
+
## Returning-browser recognition (optional, observe-only)
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
The package also includes returning-browser recognition, folded in from the former standalone `@valiron/device-identity` package so an existing Crawler Protection install gains it without a second SDK. Two signal classes stay strictly separate:
|
|
27
|
+
|
|
28
|
+
1. **Deterministic** - a first-party, server-signed visitor cookie (`HttpOnly; Secure; SameSite=Lax`). A valid cookie is the only `exact` match.
|
|
29
|
+
2. **Probabilistic** - coarsened device signals (browser family/major, languages, timezone, platform, screen, hardware hints), compared per component with weighted scoring. A strong match produces a `similar` link, never an `exact` one.
|
|
30
|
+
|
|
31
|
+
Recognition is **evidence, not a verdict**: no risk score, no block decision, no enforcement hook. `similar` means "this browser resembles one we have seen" - shared devices, corporate fleets and fresh installs all produce false links, so a `similar` link is never sufficient grounds to deny or limit service.
|
|
32
|
+
|
|
33
|
+
Mount the middleware to expose the endpoints, then call the browser collector to begin recognition:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { DeviceIdentity, RedisIdentityStore, createNodeDeviceIdentityMiddleware } from '@valiron/crawler-protection';
|
|
37
|
+
|
|
38
|
+
const identity = new DeviceIdentity({
|
|
39
|
+
salt: process.env.DEVICE_IDENTITY_SALT!, // per-deployment, 16+ chars, from a secret manager
|
|
40
|
+
cookie: {
|
|
41
|
+
name: '__Host-vid',
|
|
42
|
+
secret: process.env.DEVICE_IDENTITY_COOKIE_SECRET!,
|
|
43
|
+
maxAgeMs: 180 * 24 * 3600 * 1000,
|
|
44
|
+
},
|
|
45
|
+
store: new RedisIdentityStore(redis), // or omit for the in-memory store
|
|
46
|
+
retentionMs: 30 * 24 * 3600 * 1000, // enforced bounds: 1h..90d
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
app.use(createNodeDeviceIdentityMiddleware({
|
|
50
|
+
identity,
|
|
51
|
+
onRecognition: (recognition) => analytics.record(recognition), // server-side only
|
|
52
|
+
}));
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Load the collector script and call `ValironDevice.identify({ endpoint: "/api/valiron/device-identity/identify", respectPrivacySignals: true })` only when your deployment permits collection. Mounting the middleware alone does not run the browser collector. Recognition is not automatically sent to the hosted crawler dashboard.
|
|
56
|
+
|
|
57
|
+
The middleware serves the browser collector at `GET /api/valiron/device-identity/collector.js` and recognition at `POST /api/valiron/device-identity/identify` (override with `basePath`). The browser only ever receives `{ state }` - visitor ids, matched ids and evidence stay server-side, because echoing them would let a caller mimicking another browser's signals harvest that browser's identity. The collector never reads the cookie and never uses localStorage; pass `respectPrivacySignals: true` to skip collection when the browser sends DNT/GPC.
|
|
58
|
+
|
|
59
|
+
Privacy properties enforced in code:
|
|
60
|
+
|
|
61
|
+
- Raw signal values, raw user agents and IP addresses are never stored. Profiles hold per-component salted SHA-256 hashes only. These hashes are **pseudonymous, not anonymous**: anyone holding the deployment salt can test candidate values. Protect the salt like a signing key, rotate `saltVersion` on schedule, and treat stored profiles as personal data for retention and deletion purposes.
|
|
62
|
+
- Every stored profile carries a TTL; retention is bounded to 1 hour - 90 days (default 30).
|
|
63
|
+
- The cookie carries only a random id and an HMAC - no device data.
|
|
64
|
+
- `identity.forget(visitorId)` deletes a profile and its index entries (data-subject deletion hook).
|
|
65
|
+
|
|
66
|
+
Every default here - 30-day retention, the 8/11.5 similarity threshold, the 180-day example cookie lifetime, optional privacy-signal handling - is a placeholder so the module runs, **not an approved production policy**. Before production rollout, the deployment must explicitly decide: consent flow per jurisdiction (a first-party identification cookie is not strictly necessary for most sites), DNT/GPC behavior, retention, similarity-threshold tuning against real traffic, what may consume `similar` links (recommend observe-only analytics first; the link graph is attacker-influenceable, though links and matched ids never leave the server), and cookie lifetime/rotation. Account metering/gating for this module is likewise a follow-up decision; activation is not currently required to use it.
|
|
67
|
+
|
|
68
|
+
## Account activation and monthly usage
|
|
69
|
+
|
|
70
|
+
Sign up at Valiron and create an operator API key in Dashboard → API Keys. Keep it server-side as `VALIRON_API_KEY`. Use your dashboard-exported `operator_<account ID>` tenant. `activateCrawlerProtection()` obtains a five-minute lease and refreshes every minute; pass its handle to the runtime/guard. Missing, invalid or revoked credentials cannot activate the supported SDK. Startup/background refresh use HTTPS. Each protected HTTP request obtains quota admission through the hosted usage endpoint; a database operation within that request is not counted again. Outages never extend a lease. After revocation/expiry, new protected work stops, while confirmed releases and recovery remain available. Call `activation.stop()` on shutdown. The public SDK is modifiable; these checks are not tamper-proof and do not retroactively restrict version 0.1.0. Deploy the account activation endpoint before upgrading clients.
|
|
27
71
|
|
|
28
72
|
## Install and validate inside this workspace
|
|
29
73
|
|
|
@@ -37,7 +81,7 @@ pnpm test:crawlers:service
|
|
|
37
81
|
|
|
38
82
|
The Redis and service tests start temporary Redis processes and loopback Python/SQLite origins with generated fixture credentials. `redis-server` and Python 3 must be installed. External verification-feed egress is disabled in service lifecycle fixtures; no customer URLs or production databases are used. The Python unit suite uses local HTTP fixtures only for deliberate authentication/error/redirect cases. The package is distributed through npm as `@valiron/crawler-protection`.
|
|
39
83
|
|
|
40
|
-
Website availability: **Pro
|
|
84
|
+
Website availability: **Free, Pro and Enterprise**, within each plan’s usage allowance. Dashboard → Crawler Protection offers authenticated configuration validation/export and integration guidance. Optional `createCrawlerTelemetry` reporting adds hosted rolling origin analytics, shared capacity, instance status and dashboard monitoring alerts. It does not deploy customer policies. See the public integration guide for telemetry setup, retention and measurement limits.
|
|
41
85
|
|
|
42
86
|
## Release CI coverage
|
|
43
87
|
|
|
@@ -47,7 +91,7 @@ Website availability: **Pro** (also Enterprise). Dashboard → Valiron Crawler P
|
|
|
47
91
|
| `pnpm test:crawlers:redis` | Real shared Redis/HTTP behavior, Python/SQLite work, forged/expired/foreign-tenant capabilities, malformed/oversized private API input, Redis outage, fixed-origin proxy boundaries and concurrency/recovery. |
|
|
48
92
|
| `pnpm --filter @valiron/crawler-protection test:python` | Client authentication denial, blocked work, synchronous settlement, failed-response closure, release failure, redirect denial and environment-proxy isolation. |
|
|
49
93
|
| `pnpm test:crawlers:service` | The actual service/admin commands: inactive startup, explicit initialize/resume, hard crash/restart hold retention, cross-worker release and SIGTERM draining actual SQLite work. |
|
|
50
|
-
| Gateway CI on Node 22 and 24 | Runs Python, Redis/HTTP and service suites with isolated fixtures and captures failure logs. |
|
|
94
|
+
| Gateway CI on Node 22 and 24 | Runs the complete SDK unit suite (activation, source verification, directory, policies, admission, adapters and telemetry), plus Python, Redis/HTTP and service suites with isolated fixtures and captures failure logs. |
|
|
51
95
|
| Gateway release-container CI | Builds the shipped image and repeats service lifecycle acceptance in the nonroot Linux container (`CRAWLER_TEST_IMAGE` selects that mode). |
|
|
52
96
|
| Nuxt/Node/MariaDB CI | Real framework/database workload, cancellation, cache and recovery scenarios from the isolated full-stack fixture. |
|
|
53
97
|
| Website CI | Pro/Free account gating, configuration validation/export, pricing/checkout selection and desktop/mobile setup journeys. |
|
|
@@ -67,7 +111,7 @@ const runtime = createCrawlerRuntime({ activation,
|
|
|
67
111
|
app.use(runtime.nodeMiddleware);
|
|
68
112
|
// Nuxt: defineEventHandler(runtime.nuxtMiddleware)
|
|
69
113
|
// Handlers: runtime.withRenderingAdmission(context, renderAndFetch)
|
|
70
|
-
// Queries: runtime.withDatabaseAdmission(context,
|
|
114
|
+
// Queries: runtime.withDatabaseAdmission(context, () => queryProduct(productId))
|
|
71
115
|
```
|
|
72
116
|
|
|
73
117
|
These imports are package exports; the configuration/Redis/ingress/customer dependencies are application supplied. Use `runtime.guard` for page admission and signed internal forwarding. The runtime's `store` uses an effective policy that binds the whole configuration fingerprint, not just rate numbers. Use `runtime.compiled.policy` with private management tools. Never initialize admission from worker startup.
|
|
@@ -167,6 +211,27 @@ export default defineEventHandler(middleware);
|
|
|
167
211
|
|
|
168
212
|
The Nuxt adapter ends denied Node responses before returning. It stores an admitted context on `event.context.valironCrawler`. The structural adapter and a separate Nuxt/Nitro Vue SSR route fixture are tested locally; application-specific response-cache ordering still requires validation. It is server middleware, not Vue navigation middleware.
|
|
169
213
|
|
|
214
|
+
## Next.js (App Router, bundled consumers)
|
|
215
|
+
|
|
216
|
+
The package is safe to import from code that a bundler processes. The device-identity browser collector is embedded in the built package as a string at publish time - `deviceIdentityCollectorScript()` performs no filesystem reads - so it works unchanged in Next.js dev (Turbopack) and production builds, with no `serverExternalPackages` entry, asset copying, or `__dirname` assumptions. A regression test asserts the embedded script is byte-identical to `public/collector.js` in this repository, so the shipped asset and the embedded copy cannot drift apart.
|
|
217
|
+
|
|
218
|
+
Mount the device-identity endpoints from Node-runtime route handlers (the middleware uses Node APIs; do not use the Edge runtime):
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
// app/api/valiron/device-identity/collector.js/route.ts
|
|
222
|
+
import { deviceIdentityCollectorScript } from '@valiron/crawler-protection';
|
|
223
|
+
|
|
224
|
+
export const runtime = 'nodejs';
|
|
225
|
+
|
|
226
|
+
export function GET() {
|
|
227
|
+
return new Response(deviceIdentityCollectorScript(), {
|
|
228
|
+
headers: { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'no-store' },
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
The crawler guard itself runs wherever a Node runtime is available; the same bundling note applies - no special configuration is required.
|
|
234
|
+
|
|
170
235
|
## Node API and actual database work
|
|
171
236
|
|
|
172
237
|
```ts
|
|
@@ -222,3 +287,39 @@ Run unit/Redis tests, then the [isolated stack fixture](fixtures/README.md). It
|
|
|
222
287
|
Real Meta fetch/ad diagnostics, customer-specific AWS label configuration, production policy/telemetry delivery and customer budgets remain external rollout work. The temporary website lab is still the earlier public-document experiment; this stack milestone is not automatically enabled on valiron.co or another site.
|
|
223
288
|
|
|
224
289
|
Directory data attribution: Verified Bots Directory by Mayank Gupta (https://verifiedbots.dev), CC-BY-4.0. Directory membership does not grant access. Run `node gateway/directory.cjs` to review candidates; mount selected approval hashes using `CRAWLER_DIRECTORY_APPROVALS_FILE`, then configure explicit site budgets.
|
|
290
|
+
|
|
291
|
+
Monthly bot quotas require Crawler SDK 0.3.0 or later. Upgrade existing 0.2.x deployments to use Free accounts and hosted per-request quota admission. Earlier public SDK versions are not retroactively metered.
|
|
292
|
+
|
|
293
|
+
Free includes 10,000 protected HTTP requests per UTC calendar month; Pro ($149/month) includes 100,000. The bot allowance is independent from agent access and shared across an account's API keys, sites and replicas. Local access/rate denials run before hosted quota admission and do not consume the allowance. Once hosted admission succeeds, the request is counted even if a later work-capacity check fails. Quota exhaustion returns HTTP 429; an unavailable usage check fails closed with 503. This adds a hosted round trip before protected origin work. Enterprise: email founders@valiron.co.
|
|
294
|
+
|
|
295
|
+
## Security compatibility and admission recovery
|
|
296
|
+
|
|
297
|
+
Directory approval hashes include the resolved CIDR set. Review and approve again when that evidence changes; a generic browser user-agent token cannot override an official crawler claim that fails source verification. Local access/rate denials run before hosted monthly quota admission, so rejected requests do not consume the account allowance.
|
|
298
|
+
|
|
299
|
+
Uncertain or timed-out permit acquisitions carry a deadline and cancellation tombstone so late execution cannot leave an unstarted reservation. This does not cancel work that already started: retain its hold until settlement is confirmed, or pause admission and reconcile the exact hold with confirmed-drain evidence. An HTTP timeout alone never proves database work has stopped.
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
## Web Bot Auth verification (draft protocol, opt-in)
|
|
303
|
+
|
|
304
|
+
`WebBotAuthVerifier` verifies Web Bot Auth signatures (draft-ietf-webbotauth-httpsig-protocol, an active IETF draft) as a third evidence path for crawlers and agents that cannot publish IP ranges. A signer proves control of an Ed25519 key pinned for its `Signature-Agent` HTTPS URL; a valid signature produces evidence with `method: 'web_bot_auth'` and the operator-configured provider/class, and the usual provider budgets still apply. Wire it through the guard's `fallbackEvidence` hook, which is consulted only when trusted/IP/DNS evidence did not verify - an existing verified identity always stands:
|
|
305
|
+
|
|
306
|
+
```js
|
|
307
|
+
const wba = new WebBotAuthVerifier({ agents: {
|
|
308
|
+
'https://signer.example.com/.well-known/http-message-signatures-directory': {
|
|
309
|
+
provider: 'example-ai', crawlerClass: 'examplebot',
|
|
310
|
+
keys: [/* pinned Ed25519 JWKs from the signer's directory */],
|
|
311
|
+
promote: true, // opt-in per signer; default only reports the authenticated signer
|
|
312
|
+
},
|
|
313
|
+
} });
|
|
314
|
+
new CrawlerGuard({ /* ... */ fallbackEvidence: (request) => wba.fallbackEvidence(request) });
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
The standalone gateway and `createCrawlerRuntime()` do not automatically enable this verifier; wire it explicitly when constructing `CrawlerGuard`.
|
|
318
|
+
|
|
319
|
+
Trust boundaries, deliberately stricter than the draft minimum:
|
|
320
|
+
|
|
321
|
+
- Pin-only key sources. The verifier performs no network fetch, so a request cannot steer this process into contacting an attacker-chosen directory URL. Dynamic directory resolution is omitted until it can ship with connect-time destination validation and bounded egress.
|
|
322
|
+
- A valid signature is proof of key control, not good intent or authorization. Unpinned signer URLs stay unverified, and pinned-but-not-promoted signers keep unverified budgets while telemetry records the authenticated `signerUrl`. Promotion is an explicit per-signer opt-in.
|
|
323
|
+
- Freshness is not replay protection. The draft's minimum coverage binds only `@authority`, so a captured signature can be replayed against this origin until `expires` (bounded to the draft's recommended 24-hour maximum, configurable down). Verified signers remain subject to every budget, which bounds replay damage; `profile: 'strict'` additionally requires `@method` and `@path` coverage. The strict profile is a Valiron-specific strengthening, not a standard compliance claim.
|
|
324
|
+
- The protocol is a draft. Verification is signature-only and tolerates non-Web-Bot-Auth signatures on the same request; expect wire-format changes before RFC publication.
|
|
325
|
+
|
package/dist/activation.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Account activation and authoritative per-request monthly admission. */
|
|
2
2
|
export declare const CRAWLER_ACTIVATION_ENDPOINT = "https://valiron-edge-proxy.onrender.com/operator/crawlers/activation";
|
|
3
3
|
export type CrawlerActivation = Readonly<{
|
|
4
4
|
tenant: string;
|
|
5
5
|
start(): Promise<void>;
|
|
6
|
+
consume(): Promise<void>;
|
|
6
7
|
refresh(): Promise<void>;
|
|
7
8
|
stop(): void;
|
|
8
9
|
status(): Readonly<{
|
|
@@ -10,6 +11,9 @@ export type CrawlerActivation = Readonly<{
|
|
|
10
11
|
expiresAt?: number;
|
|
11
12
|
}>;
|
|
12
13
|
}>;
|
|
14
|
+
export declare class CrawlerMonthlyLimitError extends Error {
|
|
15
|
+
constructor();
|
|
16
|
+
}
|
|
13
17
|
export declare function validateActivation(value: CrawlerActivation, tenant?: string): void;
|
|
14
18
|
export declare function assertActivation(value: CrawlerActivation): void;
|
|
15
19
|
export declare function createCrawlerActivation(input: {
|
package/dist/activation.js
CHANGED
|
@@ -1,21 +1,25 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.CRAWLER_ACTIVATION_ENDPOINT = void 0;
|
|
3
|
+
exports.CrawlerMonthlyLimitError = exports.CRAWLER_ACTIVATION_ENDPOINT = void 0;
|
|
4
4
|
exports.validateActivation = validateActivation;
|
|
5
5
|
exports.assertActivation = assertActivation;
|
|
6
6
|
exports.createCrawlerActivation = createCrawlerActivation;
|
|
7
7
|
exports.activateCrawlerProtection = activateCrawlerProtection;
|
|
8
|
-
/**
|
|
8
|
+
/** Account activation and authoritative per-request monthly admission. */
|
|
9
9
|
exports.CRAWLER_ACTIVATION_ENDPOINT = 'https://valiron-edge-proxy.onrender.com/operator/crawlers/activation';
|
|
10
|
+
class CrawlerMonthlyLimitError extends Error {
|
|
11
|
+
constructor() { super('Monthly bot protection request limit exhausted'); }
|
|
12
|
+
}
|
|
13
|
+
exports.CrawlerMonthlyLimitError = CrawlerMonthlyLimitError;
|
|
10
14
|
const activations = new WeakMap();
|
|
11
15
|
function validateActivation(value, tenant) {
|
|
12
16
|
if (!value || !activations.has(value) || (tenant !== undefined && value.tenant !== tenant))
|
|
13
|
-
throw Error('Crawler Protection requires account-bound
|
|
17
|
+
throw Error('Crawler Protection requires account-bound activation');
|
|
14
18
|
}
|
|
15
19
|
function assertActivation(value) {
|
|
16
20
|
validateActivation(value);
|
|
17
21
|
if (!activations.get(value).active())
|
|
18
|
-
throw Error('Crawler Protection
|
|
22
|
+
throw Error('Crawler Protection activation unavailable');
|
|
19
23
|
}
|
|
20
24
|
function createCrawlerActivation(input) {
|
|
21
25
|
input = { ...input };
|
|
@@ -24,7 +28,7 @@ function createCrawlerActivation(input) {
|
|
|
24
28
|
throw Error('A Valiron operator API key and tenant are required');
|
|
25
29
|
const url = new URL(input.endpoint ?? exports.CRAWLER_ACTIVATION_ENDPOINT);
|
|
26
30
|
const fixture = url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
27
|
-
if (url.
|
|
31
|
+
if ((!fixture && url.protocol !== 'https:') || url.pathname !== '/operator/crawlers/activation' || url.username || url.password || url.search || url.hash)
|
|
28
32
|
throw Error('Invalid Crawler Protection activation endpoint');
|
|
29
33
|
const now = input.now ?? Date.now, monotonic = input.monotonicNow ?? (() => performance.now());
|
|
30
34
|
let expiresAt = 0, deadline = 0, stopped = false, pending;
|
|
@@ -71,7 +75,7 @@ function createCrawlerActivation(input) {
|
|
|
71
75
|
}
|
|
72
76
|
value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
73
77
|
if (!value || Object.keys(value).some(k => !['feature', 'tenant', 'plan', 'issuedAt', 'expiresAt'].includes(k)) ||
|
|
74
|
-
value.feature !== 'crawler_protection' || value.tenant !== input.tenant || !['pro', 'enterprise'].includes(value.plan) ||
|
|
78
|
+
value.feature !== 'crawler_protection' || value.tenant !== input.tenant || !['free', 'pro', 'enterprise'].includes(value.plan) ||
|
|
75
79
|
!Number.isSafeInteger(value.issuedAt) || !Number.isSafeInteger(value.expiresAt) ||
|
|
76
80
|
value.issuedAt > now() + 30000 || value.issuedAt < now() - 30000 || value.expiresAt <= now() ||
|
|
77
81
|
value.expiresAt <= value.issuedAt || value.expiresAt - value.issuedAt > 300000)
|
|
@@ -92,7 +96,7 @@ function createCrawlerActivation(input) {
|
|
|
92
96
|
input.onError?.();
|
|
93
97
|
}
|
|
94
98
|
catch { /* Logging cannot extend access. */ }
|
|
95
|
-
throw Error('Crawler Protection
|
|
99
|
+
throw Error('Crawler Protection activation unavailable');
|
|
96
100
|
}
|
|
97
101
|
}
|
|
98
102
|
const refresh = () => {
|
|
@@ -100,7 +104,23 @@ function createCrawlerActivation(input) {
|
|
|
100
104
|
pending = exchange().finally(() => { pending = undefined; });
|
|
101
105
|
return pending;
|
|
102
106
|
};
|
|
107
|
+
const usageUrl = new URL(url);
|
|
108
|
+
usageUrl.pathname = '/operator/crawlers/usage';
|
|
103
109
|
const activation = Object.freeze({ tenant: input.tenant, refresh,
|
|
110
|
+
async consume() {
|
|
111
|
+
if (!active())
|
|
112
|
+
throw Error('Crawler activation unavailable');
|
|
113
|
+
const response = await (input.fetch ?? fetch)(usageUrl, { method: 'POST', redirect: 'error',
|
|
114
|
+
headers: { Authorization: 'Bearer ' + input.apiKey, 'Content-Type': 'application/json' },
|
|
115
|
+
body: JSON.stringify({ tenant: input.tenant }), signal: AbortSignal.timeout(5000) });
|
|
116
|
+
await response.body?.cancel();
|
|
117
|
+
if ([401, 403].includes(response.status))
|
|
118
|
+
invalidate();
|
|
119
|
+
if (response.status === 429)
|
|
120
|
+
throw new CrawlerMonthlyLimitError();
|
|
121
|
+
if (response.status !== 200 || !active())
|
|
122
|
+
throw Error('Crawler request admission unavailable');
|
|
123
|
+
},
|
|
104
124
|
async start() {
|
|
105
125
|
await refresh();
|
|
106
126
|
if (!timer && !stopped) {
|
package/dist/admission.d.ts
CHANGED
|
@@ -26,7 +26,7 @@ export type WorkPermit = Readonly<{
|
|
|
26
26
|
export declare function keyPart(input: string): string;
|
|
27
27
|
export declare class RedisAdmission {
|
|
28
28
|
protected readonly redis: RedisEval;
|
|
29
|
-
|
|
29
|
+
protected readonly timeoutMs: number;
|
|
30
30
|
protected readonly prefix: string;
|
|
31
31
|
constructor(redis: RedisEval, tenant: string, timeoutMs?: number);
|
|
32
32
|
protected keys(stage: string, names: string[]): string[];
|
package/dist/admission.js
CHANGED
|
@@ -36,6 +36,8 @@ return {1,0}
|
|
|
36
36
|
const ACQUIRE = `
|
|
37
37
|
-- ADMISSION
|
|
38
38
|
-- WORK_ACQUIRE
|
|
39
|
+
local cancelled = table.remove(KEYS,1)
|
|
40
|
+
if redis.call('EXISTS',cancelled)==1 then return 0 end
|
|
39
41
|
local inventory = table.remove(KEYS,1)
|
|
40
42
|
local metadata = cjson.decode(table.remove(ARGV,1))
|
|
41
43
|
if redis.call('HLEN',inventory) >= 10000 then return 0 end
|
|
@@ -44,6 +46,8 @@ for i,key in ipairs(KEYS) do
|
|
|
44
46
|
end
|
|
45
47
|
local clock = redis.call('TIME')
|
|
46
48
|
metadata.acquiredAt = tonumber(clock[1])*1000+math.floor(tonumber(clock[2])/1000)
|
|
49
|
+
if metadata.acquiredAt > metadata.deadlineAt then return 0 end
|
|
50
|
+
metadata.deadlineAt = nil
|
|
47
51
|
metadata.keys = KEYS
|
|
48
52
|
for i,key in ipairs(KEYS) do redis.call('HSET',key,ARGV[1],1) end
|
|
49
53
|
redis.call('HSET',inventory,ARGV[1],cjson.encode(metadata))
|
|
@@ -125,8 +129,18 @@ class RedisAdmission {
|
|
|
125
129
|
const keys = this.keys('work', slots.map(s => s.key));
|
|
126
130
|
const id = (0, node_crypto_1.randomUUID)();
|
|
127
131
|
const secret = (0, node_crypto_1.randomBytes)(32).toString('base64url');
|
|
128
|
-
const
|
|
129
|
-
|
|
132
|
+
const cancelKey = this.prefix + 'cancel:' + id;
|
|
133
|
+
const arguments_ = [JSON.stringify({ ...fields, deadlineAt: Date.now() + this.timeoutMs,
|
|
134
|
+
slots: slots.map(s => s.key), owner: (0, node_os_1.hostname)() + ':' + process.pid + ':' + id, releaseHash: keyPart(secret) }), id, ...slots.map(s => s.limit)];
|
|
135
|
+
let result;
|
|
136
|
+
try {
|
|
137
|
+
result = Number(await this.run(ACQUIRE, [cancelKey, this.prefix + 'holds', ...keys], arguments_));
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
// Cancel before releasing; queued ACQUIRE cannot create a hold after cleanup.
|
|
141
|
+
void this.redis.eval(`redis.call('SET',KEYS[1],'1','EX',60); local raw=redis.call('HGET',KEYS[2],ARGV[1]); if raw then local r=cjson.decode(raw); for _,key in ipairs(r.keys) do redis.call('HDEL',key,ARGV[1]) end; redis.call('HDEL',KEYS[2],ARGV[1]); end; return 1`, 2, cancelKey, this.prefix + 'holds', id).catch(() => { });
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
130
144
|
if (result === 0)
|
|
131
145
|
return undefined;
|
|
132
146
|
if (result !== 1)
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser collector, embedded at build time so bundlers (Next.js, Turbopack,
|
|
3
|
+
* webpack server builds) never need a filesystem read of public/collector.js.
|
|
4
|
+
* test/device-identity-collector.test.cjs asserts this matches public/collector.js.
|
|
5
|
+
*/
|
|
6
|
+
export declare const COLLECTOR_SCRIPT: string;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.COLLECTOR_SCRIPT = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* The browser collector, embedded at build time so bundlers (Next.js, Turbopack,
|
|
6
|
+
* webpack server builds) never need a filesystem read of public/collector.js.
|
|
7
|
+
* test/device-identity-collector.test.cjs asserts this matches public/collector.js.
|
|
8
|
+
*/
|
|
9
|
+
exports.COLLECTOR_SCRIPT = "/*!\r\n * Valiron Device Identity collector (browser), shipped inside\r\n * Valiron Crawler Protection and served by createNodeDeviceIdentityMiddleware().\r\n *\r\n * Collects coarsened device signals and POSTs them to the deployment's\r\n * identify endpoint. The deterministic visitor id lives in a first-party,\r\n * HttpOnly cookie set by the server; this script never reads or writes it,\r\n * and it never touches localStorage. No third-party requests are made.\r\n *\r\n * Usage:\r\n * <script src=\"/api/valiron/device-identity/collector.js\"></script>\r\n * <script>\r\n * ValironDevice.identify({ endpoint: '/api/valiron/device-identity/identify' })\r\n * .then(function (result) { console.log(result.state); });\r\n * </script>\r\n *\r\n * Set respectPrivacySignals: true to skip collection entirely when the\r\n * browser sends Do Not Track or Global Privacy Control.\r\n */\r\n(function () {\r\n 'use strict';\r\n\r\n function safe(fn, fallback) {\r\n try {\r\n var value = fn();\r\n return value === undefined ? fallback : value;\r\n } catch (_) {\r\n return fallback;\r\n }\r\n }\r\n\r\n function privacyRequested() {\r\n return safe(function () { return navigator.globalPrivacyControl === true; }, false)\r\n || safe(function () { return navigator.doNotTrack === '1' || window.doNotTrack === '1'; }, false);\r\n }\r\n\r\n function collect() {\r\n var screen_ = safe(function () {\r\n return {\r\n width: window.screen.width,\r\n height: window.screen.height,\r\n colorDepth: window.screen.colorDepth,\r\n pixelRatio: window.devicePixelRatio,\r\n };\r\n }, undefined);\r\n return {\r\n userAgent: safe(function () { return navigator.userAgent; }, undefined),\r\n languages: safe(function () {\r\n return navigator.languages && navigator.languages.length ? Array.from(navigator.languages) : [navigator.language];\r\n }, undefined),\r\n timezone: safe(function () { return Intl.DateTimeFormat().resolvedOptions().timeZone; }, undefined),\r\n platform: safe(function () { return navigator.platform; }, undefined),\r\n hardwareConcurrency: safe(function () { return navigator.hardwareConcurrency; }, undefined),\r\n deviceMemory: safe(function () { return navigator.deviceMemory; }, undefined),\r\n maxTouchPoints: safe(function () { return navigator.maxTouchPoints; }, undefined),\r\n screen: screen_,\r\n cookiesEnabled: safe(function () { return navigator.cookieEnabled; }, undefined),\r\n doNotTrack: privacyRequested(),\r\n webdriver: safe(function () { return navigator.webdriver === true; }, undefined),\r\n };\r\n }\r\n\r\n function identify(options) {\r\n if (!options || typeof options.endpoint !== 'string' || options.endpoint.length > 2048) {\r\n return Promise.reject(new Error('ValironDevice: endpoint is required'));\r\n }\r\n if (options.respectPrivacySignals === true && privacyRequested()) {\r\n return Promise.resolve({ state: 'skipped', reason: 'privacy_signal' });\r\n }\r\n var timeoutMs = typeof options.timeoutMs === 'number' && options.timeoutMs >= 500 && options.timeoutMs <= 10000\r\n ? options.timeoutMs : 4000;\r\n var controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;\r\n var timer = controller ? setTimeout(function () { controller.abort(); }, timeoutMs) : undefined;\r\n return fetch(options.endpoint, {\r\n method: 'POST',\r\n headers: { 'content-type': 'application/json' },\r\n credentials: options.credentials || 'same-origin',\r\n body: JSON.stringify({ signals: collect() }),\r\n signal: controller ? controller.signal : undefined,\r\n }).then(function (response) {\r\n if (!response.ok) throw new Error('ValironDevice: identify failed with ' + response.status);\r\n return response.json();\r\n }).finally(function () {\r\n if (timer) clearTimeout(timer);\r\n });\r\n }\r\n\r\n window.ValironDevice = Object.freeze({ identify: identify, collect: collect });\r\n})();\r\n\r\n";
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic identity: a first-party, server-signed visitor cookie.
|
|
3
|
+
*
|
|
4
|
+
* The cookie is the only exact-match signal in this package. It carries a
|
|
5
|
+
* random visitor id and an HMAC, never any device data. Signature failure
|
|
6
|
+
* or expiry is evidence ('invalid'), not an accusation.
|
|
7
|
+
*/
|
|
8
|
+
export type CookieOptions = Readonly<{
|
|
9
|
+
name: string;
|
|
10
|
+
secret: string;
|
|
11
|
+
maxAgeMs: number;
|
|
12
|
+
}>;
|
|
13
|
+
export declare function validateCookieOptions(options: CookieOptions): void;
|
|
14
|
+
export declare function newVisitorId(): string;
|
|
15
|
+
export declare function signVisitorCookie(options: CookieOptions, visitorId: string, issuedAt: number): string;
|
|
16
|
+
export type VerifiedCookie = Readonly<{
|
|
17
|
+
state: 'valid';
|
|
18
|
+
visitorId: string;
|
|
19
|
+
issuedAt: number;
|
|
20
|
+
}> | Readonly<{
|
|
21
|
+
state: 'missing' | 'invalid';
|
|
22
|
+
}>;
|
|
23
|
+
/** Extract and verify this cookie from a Cookie header. Bounded scan; first match wins. */
|
|
24
|
+
export declare function verifyVisitorCookie(options: CookieOptions, cookieHeader: string | undefined, now: number): VerifiedCookie;
|
|
25
|
+
/** Serialize the Set-Cookie response header. HttpOnly, Secure, SameSite=Lax are not optional. */
|
|
26
|
+
export declare function serializeVisitorCookie(options: CookieOptions, value: string): string;
|
|
27
|
+
/** Expire the cookie immediately (used when a deployment disables collection). */
|
|
28
|
+
export declare function serializeCookieClear(options: CookieOptions): string;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Deterministic identity: a first-party, server-signed visitor cookie.
|
|
4
|
+
*
|
|
5
|
+
* The cookie is the only exact-match signal in this package. It carries a
|
|
6
|
+
* random visitor id and an HMAC, never any device data. Signature failure
|
|
7
|
+
* or expiry is evidence ('invalid'), not an accusation.
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.validateCookieOptions = validateCookieOptions;
|
|
11
|
+
exports.newVisitorId = newVisitorId;
|
|
12
|
+
exports.signVisitorCookie = signVisitorCookie;
|
|
13
|
+
exports.verifyVisitorCookie = verifyVisitorCookie;
|
|
14
|
+
exports.serializeVisitorCookie = serializeVisitorCookie;
|
|
15
|
+
exports.serializeCookieClear = serializeCookieClear;
|
|
16
|
+
const node_crypto_1 = require("node:crypto");
|
|
17
|
+
const VALUE_PATTERN = /^v1\.(\d{1,16})\.([A-Za-z0-9_-]{16,48})\.([A-Za-z0-9_-]{43})$/;
|
|
18
|
+
const NAME_PATTERN = /^(?:__Host-)?[A-Za-z][A-Za-z0-9_-]{0,63}$/;
|
|
19
|
+
function validateCookieOptions(options) {
|
|
20
|
+
if (!NAME_PATTERN.test(options.name))
|
|
21
|
+
throw new Error('Invalid visitor cookie name');
|
|
22
|
+
if (typeof options.secret !== 'string' || options.secret.length < 16 || options.secret.length > 256) {
|
|
23
|
+
throw new Error('Invalid visitor cookie secret');
|
|
24
|
+
}
|
|
25
|
+
if (!Number.isSafeInteger(options.maxAgeMs) || options.maxAgeMs < 3600000 || options.maxAgeMs > 400 * 86400000) {
|
|
26
|
+
throw new Error('Invalid visitor cookie max age');
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function newVisitorId() {
|
|
30
|
+
return (0, node_crypto_1.randomBytes)(16).toString('base64url');
|
|
31
|
+
}
|
|
32
|
+
function mac(secret, payload) {
|
|
33
|
+
return (0, node_crypto_1.createHmac)('sha256', secret).update(payload).digest('base64url');
|
|
34
|
+
}
|
|
35
|
+
function signVisitorCookie(options, visitorId, issuedAt) {
|
|
36
|
+
const payload = `v1.${issuedAt}.${visitorId}`;
|
|
37
|
+
return `${payload}.${mac(options.secret, payload)}`;
|
|
38
|
+
}
|
|
39
|
+
/** Extract and verify this cookie from a Cookie header. Bounded scan; first match wins. */
|
|
40
|
+
function verifyVisitorCookie(options, cookieHeader, now) {
|
|
41
|
+
if (!cookieHeader || cookieHeader.length > 8192)
|
|
42
|
+
return { state: 'missing' };
|
|
43
|
+
let raw;
|
|
44
|
+
for (const part of cookieHeader.split(';')) {
|
|
45
|
+
const eq = part.indexOf('=');
|
|
46
|
+
if (eq === -1)
|
|
47
|
+
continue;
|
|
48
|
+
if (part.slice(0, eq).trim() === options.name) {
|
|
49
|
+
raw = part.slice(eq + 1).trim();
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (!raw || raw.length > 256)
|
|
54
|
+
return { state: raw === undefined ? 'missing' : 'invalid' };
|
|
55
|
+
const match = raw.match(VALUE_PATTERN);
|
|
56
|
+
if (!match)
|
|
57
|
+
return { state: 'invalid' };
|
|
58
|
+
const [, issuedText, visitorId, tag] = match;
|
|
59
|
+
const issuedAt = Number(issuedText);
|
|
60
|
+
if (!Number.isSafeInteger(issuedAt) || issuedAt > now || now - issuedAt > options.maxAgeMs)
|
|
61
|
+
return { state: 'invalid' };
|
|
62
|
+
const expected = Buffer.from(mac(options.secret, `v1.${issuedText}.${visitorId}`));
|
|
63
|
+
const actual = Buffer.from(tag);
|
|
64
|
+
if (expected.length !== actual.length || !(0, node_crypto_1.timingSafeEqual)(expected, actual))
|
|
65
|
+
return { state: 'invalid' };
|
|
66
|
+
return { state: 'valid', visitorId, issuedAt };
|
|
67
|
+
}
|
|
68
|
+
/** Serialize the Set-Cookie response header. HttpOnly, Secure, SameSite=Lax are not optional. */
|
|
69
|
+
function serializeVisitorCookie(options, value) {
|
|
70
|
+
const seconds = Math.floor(options.maxAgeMs / 1000);
|
|
71
|
+
return `${options.name}=${value}; Path=/; Max-Age=${seconds}; HttpOnly; Secure; SameSite=Lax`;
|
|
72
|
+
}
|
|
73
|
+
/** Expire the cookie immediately (used when a deployment disables collection). */
|
|
74
|
+
function serializeCookieClear(options) {
|
|
75
|
+
return `${options.name}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax`;
|
|
76
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Valiron Device Identity.
|
|
3
|
+
*
|
|
4
|
+
* Recognizes a returning browser from two independent signal classes:
|
|
5
|
+
* 1. deterministic - the server-signed first-party visitor cookie
|
|
6
|
+
* 2. probabilistic - coarsened device signals, compared per component
|
|
7
|
+
*
|
|
8
|
+
* The output is identification evidence, nothing more. This package has no
|
|
9
|
+
* notion of fraud, risk, or enforcement. A 'similar' result means "this
|
|
10
|
+
* browser resembles a browser we have seen"; it does not establish the
|
|
11
|
+
* same person (shared devices, managed fleets, fresh installs all break
|
|
12
|
+
* that inference), and it is never sufficient grounds to deny service.
|
|
13
|
+
* Abuse decisions belong to the policy layer (crawler protection, the
|
|
14
|
+
* identity gate), which may consume this evidence alongside its own.
|
|
15
|
+
*/
|
|
16
|
+
import { type CookieOptions } from './cookie';
|
|
17
|
+
import { type RawSignals } from './signals';
|
|
18
|
+
import { type IdentityStore } from './store';
|
|
19
|
+
export declare const COMPONENT_WEIGHTS: Readonly<Record<string, number>>;
|
|
20
|
+
export type RecognitionState = 'exact' | 'similar' | 'new';
|
|
21
|
+
export type Recognition = Readonly<{
|
|
22
|
+
state: RecognitionState;
|
|
23
|
+
/** The visitor id the deployment should treat as this browser going forward (from the newly set cookie). */
|
|
24
|
+
visitorId: string;
|
|
25
|
+
/** When 'similar': the prior visitor id this browser was linked from. */
|
|
26
|
+
matchedVisitorId?: string;
|
|
27
|
+
similarity?: Readonly<{
|
|
28
|
+
score: number;
|
|
29
|
+
threshold: number;
|
|
30
|
+
matched: readonly string[];
|
|
31
|
+
mismatched: readonly string[];
|
|
32
|
+
}>;
|
|
33
|
+
/** Observations a policy layer may use. Presence of a flag is evidence, not a verdict. */
|
|
34
|
+
evidence: Readonly<{
|
|
35
|
+
cookie: 'valid' | 'missing' | 'invalid';
|
|
36
|
+
webdriver: boolean;
|
|
37
|
+
doNotTrack: boolean;
|
|
38
|
+
signalVersion: number;
|
|
39
|
+
}>;
|
|
40
|
+
}>;
|
|
41
|
+
export type RecognizeResult = Readonly<{
|
|
42
|
+
recognition: Recognition;
|
|
43
|
+
/** Set-Cookie header value the server must send with its response. */
|
|
44
|
+
setCookie: string;
|
|
45
|
+
}>;
|
|
46
|
+
export type DeviceIdentityOptions = Readonly<{
|
|
47
|
+
/** Per-deployment salt for component hashes. Required; never shared across deployments. */
|
|
48
|
+
salt: string;
|
|
49
|
+
/** Bump when rotating the salt. Old profiles stop matching similarity lookups after rotation. */
|
|
50
|
+
saltVersion?: number;
|
|
51
|
+
store?: IdentityStore;
|
|
52
|
+
cookie: CookieOptions;
|
|
53
|
+
/** Profile retention. Enforced bounds: 1 hour .. 90 days. Default 30 days. */
|
|
54
|
+
retentionMs?: number;
|
|
55
|
+
/** Similarity score needed for a 'similar' link. Default 8 of 11.5. */
|
|
56
|
+
similarityThreshold?: number;
|
|
57
|
+
/**
|
|
58
|
+
* Component pair whose simultaneous mismatch vetoes a similarity link,
|
|
59
|
+
* or false to rely on the weighted score alone. Default ['tz', 'lang']:
|
|
60
|
+
* a traveler usually keeps their language, so a changed timezone alone
|
|
61
|
+
* never vetoes; both changing at once is the shared-device case this
|
|
62
|
+
* guard exists for. Set false only after measuring false-link rates.
|
|
63
|
+
*/
|
|
64
|
+
hardMismatch?: readonly [string, string] | false;
|
|
65
|
+
now?: () => number;
|
|
66
|
+
}>;
|
|
67
|
+
export declare class DeviceIdentity {
|
|
68
|
+
private readonly options;
|
|
69
|
+
private readonly store;
|
|
70
|
+
private readonly retentionMs;
|
|
71
|
+
private readonly threshold;
|
|
72
|
+
private readonly now;
|
|
73
|
+
private readonly saltVersion;
|
|
74
|
+
private readonly hardMismatch;
|
|
75
|
+
constructor(options: DeviceIdentityOptions);
|
|
76
|
+
private hash;
|
|
77
|
+
private hashedComponents;
|
|
78
|
+
/**
|
|
79
|
+
* Recall filter for similarity candidates: language + platform only.
|
|
80
|
+
* Timezone is deliberately NOT part of the index - a traveler keeps
|
|
81
|
+
* their language and platform, so they remain a candidate and the
|
|
82
|
+
* weighted score absorbs the tz change. The index only bounds recall;
|
|
83
|
+
* scoring decides. Cardinality is capped by the store.
|
|
84
|
+
*/
|
|
85
|
+
private indexKey;
|
|
86
|
+
private score;
|
|
87
|
+
/**
|
|
88
|
+
* Recognize one request. Always issues a fresh signed cookie; a 'similar'
|
|
89
|
+
* browser receives a NEW visitor id linked to the prior one - cookie
|
|
90
|
+
* continuity belongs only to the browser that actually holds the cookie.
|
|
91
|
+
*/
|
|
92
|
+
recognize(input: {
|
|
93
|
+
cookieHeader?: string;
|
|
94
|
+
signals: RawSignals;
|
|
95
|
+
}): Promise<RecognizeResult>;
|
|
96
|
+
/** Data-subject deletion: remove one visitor profile and its similarity index entries. */
|
|
97
|
+
forget(visitorId: string): Promise<void>;
|
|
98
|
+
}
|