@valiron/crawler-protection 0.0.0-stage → 0.1.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 +217 -2
- 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 +341 -0
- package/dist/guard.d.ts +108 -0
- package/dist/guard.js +278 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +32 -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 +44 -0
- package/dist/runtime.js +66 -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 +107 -0
- package/gateway/admin.cjs +34 -0
- package/gateway/compose.yaml +40 -0
- package/gateway/directory.cjs +10 -0
- package/gateway/service.cjs +91 -0
- package/gateway/work-api.openapi.json +186 -0
- package/integrations/python/valiron_crawler_protection.py +90 -0
- package/package.json +57 -4
package/README.md
CHANGED
|
@@ -1,3 +1,218 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Valiron Crawler Protection
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Install the integration package from npm: `npm install @valiron/crawler-protection` (Node.js 22+).
|
|
4
|
+
|
|
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
|
+
|
|
7
|
+
Integration for [Valiron Crawler Protection](https://www.valiron.co/docs/crawler-protection). Protects origin work in customer infrastructure. No blockchain, hosted Valiron round trip or crawler signup is required.
|
|
8
|
+
|
|
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
|
+
|
|
11
|
+
Implemented:
|
|
12
|
+
|
|
13
|
+
- Strict client IP parsing and an authenticated CloudFront origin-header adapter; never trusts the leftmost forwarded value.
|
|
14
|
+
- Broader directory discovery with reviewed metadata approvals, distinct third-party CIDR evidence, and conservative fallback; see [directory setup](https://valiron.co/docs/agents/CRAWLER-PROTECTION.md#broader-crawler-directory).
|
|
15
|
+
- Official CIDR verification for OpenAI, Googlebot/AdsBot, Applebot, DuckDuckBot and Perplexity search/user-fetch classes, with bounded background refresh from an immutable nine-feed catalog.
|
|
16
|
+
- Bing forward-confirmed reverse DNS with deduplicated, concurrency-limited cold lookups and a bounded cache.
|
|
17
|
+
- Atomic Redis token buckets across global, route, IP, provider and crawler-class budgets.
|
|
18
|
+
- Shared DB work slots, local concurrency limits, short-lived guard-owned request contexts and per-request operation bounds.
|
|
19
|
+
- Node middleware and a structural Nuxt/Nitro server middleware adapter. Unknown callers retain baseline limits.
|
|
20
|
+
- Noncacheable 429/503 responses, policy/evidence expiry and conservative dependency-failure handling.
|
|
21
|
+
|
|
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
|
+
|
|
24
|
+
## Install and validate inside this workspace
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
pnpm --filter @valiron/crawler-protection build
|
|
28
|
+
pnpm test:crawlers
|
|
29
|
+
pnpm test:crawlers:redis
|
|
30
|
+
pnpm --filter @valiron/crawler-protection test:python
|
|
31
|
+
pnpm test:crawlers:service
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
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`.
|
|
35
|
+
|
|
36
|
+
Website availability: **Pro** (also Enterprise). Dashboard → Valiron 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.
|
|
37
|
+
|
|
38
|
+
## Release CI coverage
|
|
39
|
+
|
|
40
|
+
| Command/job | What it checks |
|
|
41
|
+
| --- | --- |
|
|
42
|
+
| `pnpm test:crawlers` | Source verification, signed context, policy/configuration, cache and work-control unit tests. |
|
|
43
|
+
| `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. |
|
|
44
|
+
| `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. |
|
|
45
|
+
| `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. |
|
|
46
|
+
| Gateway CI on Node 22 and 24 | Runs Python, Redis/HTTP and service suites with isolated fixtures and captures failure logs. |
|
|
47
|
+
| Gateway release-container CI | Builds the shipped image and repeats service lifecycle acceptance in the nonroot Linux container (`CRAWLER_TEST_IMAGE` selects that mode). |
|
|
48
|
+
| Nuxt/Node/MariaDB CI | Real framework/database workload, cancellation, cache and recovery scenarios from the isolated full-stack fixture. |
|
|
49
|
+
| Website CI | Pro/Free account gating, configuration validation/export, pricing/checkout selection and desktop/mobile setup journeys. |
|
|
50
|
+
|
|
51
|
+
Both gateway matrix results and the Nuxt/MariaDB job feed the aggregate `CI required` result. Package-content checks include the gateway commands, private protocol, container files and Python client, and reject fixture/env/source leakage. Container-mode lifecycle tests require Linux Docker host networking and a locally built image; leave `CRAWLER_TEST_IMAGE` unset for local process tests. Full-stack fixtures are maintained in the source repository and are not part of the npm package. Passing fixtures does not establish customer capacity, real crawler/Meta acceptance or production deployment.
|
|
52
|
+
|
|
53
|
+
## Generic runtime and deployment configuration
|
|
54
|
+
|
|
55
|
+
The recommended managed integration is `compileCrawlerConfiguration()` / `createCrawlerRuntime()`. Schema version 1 validates immutable site policy, explicit route/method inventory, staged rollout, verified crawler rules and public cache settings. Unknown or overlapping paths reject; GET includes HEAD. No customer-specific route logic is built into the engine.
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
const runtime = createCrawlerRuntime({
|
|
59
|
+
configuration: siteConfiguration, redis, clientIp: trustedClientIp,
|
|
60
|
+
customer: validateShoppingGrant,
|
|
61
|
+
});
|
|
62
|
+
app.use(runtime.nodeMiddleware);
|
|
63
|
+
// Nuxt: defineEventHandler(runtime.nuxtMiddleware)
|
|
64
|
+
// Handlers: runtime.withRenderingAdmission(context, renderAndFetch)
|
|
65
|
+
// Queries: runtime.withDatabaseAdmission(context, actualQueryPromise)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
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.
|
|
69
|
+
|
|
70
|
+
`runtime.publicResponse()` authenticates ingress even on cache hits, resolves inventory, and caches only configured public groups through an admitted loader. Cache hits remain public content, outside origin crawler access policy; deny cached access separately at the edge where required. `runtime.report.snapshot()` provides bounded process-local request/work/cache aggregates without raw caller data. These are origin observations, not CDN totals, inferred humans or measured SQL cost savings.
|
|
71
|
+
|
|
72
|
+
Observation shadows candidate rate/access decisions while hard safety/customer rates, SSR/DB caps, fanout, policy/ingress checks and outages remain enforced. Selective enforcement uses explicit groups. Changing routing, cache, rollout or access rules changes the managed policy identity and requires pause/drain/activation; stale configurations reject.
|
|
73
|
+
|
|
74
|
+
Read-only onboarding uses `compileCrawlerConfiguration()` for the effective policy/fingerprint and `planCrawlerRollout()` for measured rollout blockers. `createEcommerceConfiguration()` prepares reusable ecommerce route inventory from operator-supplied paths and budgets. Validation does not activate a deployment. See the [integration guide](https://www.valiron.co/docs/crawler-protection/integration). The source checkout also includes development fixtures and CLI examples; they are not included in the integration archive.
|
|
75
|
+
|
|
76
|
+
## Construct one guard per process
|
|
77
|
+
|
|
78
|
+
The following uses illustrative low fixture values. Production limits, context lifetime and evidence TTL must come from the actual application inventory and load measurements.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
import Redis from 'ioredis';
|
|
82
|
+
import {
|
|
83
|
+
BingVerifier, CrawlerGuard, CrawlerRegistry, RedisAdmission,
|
|
84
|
+
refreshCrawlerFeeds, createCloudFrontClientIpResolver,
|
|
85
|
+
} from '@valiron/crawler-protection';
|
|
86
|
+
|
|
87
|
+
const redis = new Redis(process.env.CRAWLER_REDIS_URL!, {
|
|
88
|
+
enableOfflineQueue: false,
|
|
89
|
+
maxRetriesPerRequest: 0,
|
|
90
|
+
retryStrategy: null,
|
|
91
|
+
commandTimeout: 200,
|
|
92
|
+
connectTimeout: 1000,
|
|
93
|
+
});
|
|
94
|
+
// Await readiness before accepting requests. Reconnection/recovery is an
|
|
95
|
+
// operator action: do not automatically resume against an empty failover store.
|
|
96
|
+
redis.on('error', reportDependencyError);
|
|
97
|
+
|
|
98
|
+
const registry = new CrawlerRegistry();
|
|
99
|
+
const rate = { capacity: 10, refillPerSecond: 1 };
|
|
100
|
+
const guard = new CrawlerGuard({
|
|
101
|
+
registry,
|
|
102
|
+
bing: new BingVerifier(),
|
|
103
|
+
store: new RedisAdmission(redis, 'customer-tenant-id', 250),
|
|
104
|
+
policy: {
|
|
105
|
+
version: 'production-1', expiresAt: Date.now() + 60 * 60 * 1000,
|
|
106
|
+
globalRate: rate, perIpRate: rate,
|
|
107
|
+
unknownRate: { capacity: 3, refillPerSecond: 0.2 },
|
|
108
|
+
providers: {
|
|
109
|
+
openai: { rate, classes: { 'oai-searchbot': rate } },
|
|
110
|
+
bing: { rate, classes: { bingbot: rate } },
|
|
111
|
+
},
|
|
112
|
+
routes: {
|
|
113
|
+
product: { cost: 1, rate },
|
|
114
|
+
listing: { cost: 3, rate },
|
|
115
|
+
},
|
|
116
|
+
globalWorkLimit: 4, unknownWorkLimit: 1,
|
|
117
|
+
providerWorkLimit: 2, localWorkLimit: 4,
|
|
118
|
+
maxOperationsPerRequest: 4, maxContextAgeMs: 10000,
|
|
119
|
+
},
|
|
120
|
+
onDecision: decision => boundedTelemetryQueue.tryPush(decision),
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
// Background startup/scheduled refresh; never fetch a feed in a page handler.
|
|
124
|
+
// Run at an interval shorter than its TTL, report refresh failure and retain
|
|
125
|
+
// last-known-good data only until expiry. Each process refreshes independently
|
|
126
|
+
// centrally distributed snapshots are not implemented yet.
|
|
127
|
+
const feedStatus = await refreshCrawlerFeeds(registry, { ttlMs: 60 * 60 * 1000, concurrency: 3 });
|
|
128
|
+
// Monitor 'unavailable' entries; expired evidence stays conservative.
|
|
129
|
+
// refreshOpenAiFeed remains available for existing OpenAI-only integrations.
|
|
130
|
+
|
|
131
|
+
const clientIp = createCloudFrontClientIpResolver({
|
|
132
|
+
originSecret: process.env.CRAWLER_ORIGIN_SECRET!,
|
|
133
|
+
trustedProxyCidrs: configuredCloudFrontOriginCidrs,
|
|
134
|
+
additionalProxyHops: 0,
|
|
135
|
+
});
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
`reportDependencyError`, `boundedTelemetryQueue` and `configuredCloudFrontOriginCidrs` are application-supplied dependencies, not package exports. Keep secrets out of logs. Configure CloudFront to overwrite `X-Valiron-Origin-Auth` with the shared high-entropy secret, restrict origin ingress and forward user-agent without including arbitrary user-agent strings in the public cache key. Validate every proxy hop for the actual topology.
|
|
139
|
+
|
|
140
|
+
Use only explicit inventoried routes. Normalize route/query semantics in application code; do not remove filters, currency, locale or pagination that change the representation. Every route's configured cost must match the middleware mapping. Both GET and HEAD need protection when they execute the same expensive code. Do not accidentally exempt writes, alternate API paths or background refreshes: apply existing authorization and workload caps to those independently.
|
|
141
|
+
|
|
142
|
+
## Nuxt 4 middleware
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
// server/middleware/crawler.ts
|
|
146
|
+
import { createNuxtCrawlerMiddleware } from '@valiron/crawler-protection';
|
|
147
|
+
import { guard, clientIp } from '../utils/crawlerGuard';
|
|
148
|
+
|
|
149
|
+
const middleware = createNuxtCrawlerMiddleware({
|
|
150
|
+
guard, clientIp,
|
|
151
|
+
route: request => {
|
|
152
|
+
const path = new URL(request.url!, 'https://internal.invalid').pathname;
|
|
153
|
+
// Replace with your website's actual route inventory.
|
|
154
|
+
if (path.startsWith('/products/')) return { group: 'product', cost: 1 };
|
|
155
|
+
if (path === '/rings') return { group: 'listing', cost: 3 };
|
|
156
|
+
return undefined;
|
|
157
|
+
},
|
|
158
|
+
});
|
|
159
|
+
export default defineEventHandler(middleware);
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
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.
|
|
163
|
+
|
|
164
|
+
## Node API and actual database work
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
app.use(createNodeCrawlerMiddleware({ guard, clientIp, route: mapProtectedApi }));
|
|
168
|
+
|
|
169
|
+
app.get('/api/products/:id', async (req, res, next) => {
|
|
170
|
+
try {
|
|
171
|
+
const product = await guard.withDatabaseAdmission(req.valironCrawler!, async () => {
|
|
172
|
+
// The promise must settle only after the query stops and its connection
|
|
173
|
+
// is released. A timeout response alone does not terminate DB work.
|
|
174
|
+
return queryProductWithBoundedPoolAndServerTimeout(req.params.id);
|
|
175
|
+
});
|
|
176
|
+
res.json(product);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
if (error instanceof AdmissionError) return sendDenial(res, error.decision);
|
|
179
|
+
next(error);
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Import the middleware, error and denial helper from this package. Protect each expensive operation, including parallel fanout. Missing or fabricated contexts cannot acquire work through `CrawlerGuard`; contexts expire and can start only the configured number of operations. Keep database pools bounded across **all** workers, jobs and Nuxt processes; this package cannot protect unwrapped database calls.
|
|
185
|
+
|
|
186
|
+
Managed mode supports signed Nuxt-to-Node propagation. Create `InternalAdmission` with a server-held keyring (minimum 32-byte secrets), issuer and audience. Nuxt calls `guard.forward(context, channel, { method, path, body })`; Node calls `guard.acceptInternal(token, channel, target)` on a dedicated authenticated internal route, then `withDatabaseAdmission`. Bind the exact method, path/query and raw request bytes; use TLS or a protected private network. Do not run the public adapter over this internal route: it intentionally strips internal headers. Missing/invalid internal tokens must reject before the handler. Public direct API calls still perform normal admission. Tokens never enter browser responses or cache entries.
|
|
187
|
+
|
|
188
|
+
The page budget is consumed once; each local or downstream DB operation atomically consumes the shared parent fanout budget. A child token authorizes one DB operation, not an entire unrestricted handler. Replayed child tokens cannot execute another operation. Context policy fingerprints, issuer/audience, signature and expiry must match. Managed mode is required for cross-service replay protection.
|
|
189
|
+
|
|
190
|
+
Call `guard.withRenderingAdmission(context, renderAndFetch)` around actual SSR. Its independent shared render slots use the same configured ceilings and customer reservations; it does not consume a DB fanout unit. Wait for all fetches/render work to settle before release.
|
|
191
|
+
|
|
192
|
+
## Slot recovery and outages
|
|
193
|
+
|
|
194
|
+
Work-slot hashes deliberately have **no automatic expiry**. A disconnected browser, a crashed Node process or a response timeout does not prove a database query stopped. Release follows actual operation settlement. A release error preserves the query result, emits `work_release_failed`, and leaves a conservative slot held.
|
|
195
|
+
|
|
196
|
+
Use `ManagedRedisAdmission` for deployment, with the exact immutable policy on every process. New namespaces require explicit drained initialization and resume; workers never initialize themselves. Every rate/work/child mutation atomically checks the active policy fingerprint and pause flag. `inspect()` lists held request IDs, owner host/process, age timestamp and keys. `pause()`, confirmed-drain `reconcile(exactIds, evidence)`, drained CAS `activate(previousFingerprint)`, and `resume()` provide recovery. No public admin endpoint is added. See [deployment and recovery instructions](gateway/README.md). Legacy `RedisAdmission` remains for compatibility and has no managed pause/policy gate.
|
|
197
|
+
|
|
198
|
+
`observeDatabase(actualSample, thresholds)` opens the shared catalog circuit on measured pool waits, query latency or failures in a bounded server-time window. It does not infer health from HTTP status. `catalogCircuit('probe', evidence)` permits one catalog DB operation at a time; bypass regeneration caches while probing. An operator returns to healthy after observing fresh successful probes. Checkout keeps its reserved capacity during catalog distress. A global pause still denies every expensive lane.
|
|
199
|
+
|
|
200
|
+
Redis command timeout/offline errors cause 503 before expensive callbacks. Use no offline queue or automatic command retries. If Redis loses recent state or fails over to an empty store, keep admission stopped until all prior work is drained/reconciled. The package cannot itself establish that a newly reachable Redis contains the authoritative pre-failure state. Retain independent process/pool caps.
|
|
201
|
+
|
|
202
|
+
The guard sees origin requests only. CloudFront cache hits are neither classified nor charged here; serving a cached public page remains an edge decision. Configure CloudFront error handling to avoid caching denials. Keep personalized responses out of public caches and retain WAF controls.
|
|
203
|
+
|
|
204
|
+
## Customer lanes and cache
|
|
205
|
+
|
|
206
|
+
`GuardPolicy.customers` configures `shopperReserve`, `checkoutReserve`, `shopperRate` and `checkoutRate`. Together reservations must be smaller than `globalWorkLimit`, and `localWorkLimit` must cover the shared total. A trusted `customer(request, routeGroup)` callback must validate a bounded, server-stored shopping/cart/session grant and return `{ lane, principal }`. Caller flags, UA or arbitrary cookies never grant priority. Checkout priority additionally requires `routes[group].customerLane = 'checkout'`; other uses downgrade to shopper. Authentication alone does not establish a genuine shopper. Unknown anonymous traffic remains conservative; monitor false throttles rather than calling it human.
|
|
207
|
+
|
|
208
|
+
Use physically separate bounded catalog/checkout DB pools. Catalog work cannot occupy the reserved slots; the sum of every process pool and job pool still must fit the DB safe budget. Reservations are ceilings and reserved headroom, not a latency guarantee.
|
|
209
|
+
|
|
210
|
+
`CatalogCache` canonicalizes explicit public GET/HEAD URL/query keys, preserves meaningful variants, bypasses cookies/auth/unknown query parameters and refuses denials, Set-Cookie, Vary or private/no-store responses. The application must ensure the representation depends only on those keys; separate namespaces for hosts/tenants/locale variants as appropriate. A shared non-expiring regeneration hold deduplicates a key, and a global regeneration limit bounds distinct cold misses. Fresh HTML bypasses origin work; stale HTML can refresh only through the supplied admitted loader and explicit background-lifetime hook. A busy cold miss returns uncached 503. No generic route cache is installed automatically.
|
|
211
|
+
|
|
212
|
+
## Validation and remaining boundaries
|
|
213
|
+
|
|
214
|
+
Run unit/Redis tests, then the [isolated stack fixture](fixtures/README.md). It runs Nuxt 4.1.3/Nitro Vue SSR, a separate Node service, MariaDB 10.11.8 and Redis. It tests HTML metadata/image/redirect mechanics, signed child replay/fanout, work rejection, checkout isolation, real SQL timeouts/disconnects/process death, cache misses and managed recovery. Fixture latency is local evidence, not a customer capacity promise.
|
|
215
|
+
|
|
216
|
+
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.
|
|
217
|
+
|
|
218
|
+
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.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { CrawlerGuard, type RequestContext } from './guard';
|
|
3
|
+
import { AdmissionError, type Decision } from './admission';
|
|
4
|
+
export type ProtectedRoute = {
|
|
5
|
+
group: string;
|
|
6
|
+
cost: number;
|
|
7
|
+
};
|
|
8
|
+
export type AdapterConfig = {
|
|
9
|
+
guard: CrawlerGuard;
|
|
10
|
+
/** Must authenticate the proxy path and select a trusted client address. */
|
|
11
|
+
clientIp: (request: IncomingMessage) => string;
|
|
12
|
+
/** Match an explicit route inventory. Return undefined for unprotected paths. */
|
|
13
|
+
route: (request: IncomingMessage) => ProtectedRoute | undefined;
|
|
14
|
+
};
|
|
15
|
+
export declare function sendDenial(response: ServerResponse, decision: Decision): void;
|
|
16
|
+
export type GuardedRequest = IncomingMessage & {
|
|
17
|
+
valironCrawler?: RequestContext;
|
|
18
|
+
};
|
|
19
|
+
/** Express-compatible middleware, also usable with a plain Node handler chain. */
|
|
20
|
+
export declare function createNodeCrawlerMiddleware(config: AdapterConfig): (request: GuardedRequest, response: ServerResponse, next: (error?: unknown) => void) => void;
|
|
21
|
+
/** Structural Nitro/H3 event adapter: wrap with Nuxt's defineEventHandler. */
|
|
22
|
+
export declare function createNuxtCrawlerMiddleware(config: AdapterConfig): (event: {
|
|
23
|
+
node: {
|
|
24
|
+
req: IncomingMessage;
|
|
25
|
+
res: ServerResponse;
|
|
26
|
+
};
|
|
27
|
+
context: Record<string, unknown>;
|
|
28
|
+
}) => Promise<void>;
|
|
29
|
+
export { AdmissionError };
|
package/dist/adapters.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AdmissionError = void 0;
|
|
4
|
+
exports.sendDenial = sendDenial;
|
|
5
|
+
exports.createNodeCrawlerMiddleware = createNodeCrawlerMiddleware;
|
|
6
|
+
exports.createNuxtCrawlerMiddleware = createNuxtCrawlerMiddleware;
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const admission_1 = require("./admission");
|
|
9
|
+
Object.defineProperty(exports, "AdmissionError", { enumerable: true, get: function () { return admission_1.AdmissionError; } });
|
|
10
|
+
function sendDenial(response, decision) {
|
|
11
|
+
response.statusCode = decision.action === 'block' ? 403 : decision.action === 'limit' ? 429 : 503;
|
|
12
|
+
response.setHeader('Cache-Control', 'no-store');
|
|
13
|
+
response.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
14
|
+
if (decision.retryAfterSeconds)
|
|
15
|
+
response.setHeader('Retry-After', String(decision.retryAfterSeconds));
|
|
16
|
+
response.end(JSON.stringify({ code: 'CRAWLER_' + decision.action.toUpperCase(), requestId: decision.requestId }));
|
|
17
|
+
}
|
|
18
|
+
async function admit(config, request, response) {
|
|
19
|
+
// Internal classification is never accepted from a viewer-supplied header.
|
|
20
|
+
for (const header of Object.keys(request.headers))
|
|
21
|
+
if (header.startsWith('x-valiron-internal-'))
|
|
22
|
+
delete request.headers[header];
|
|
23
|
+
let route;
|
|
24
|
+
try {
|
|
25
|
+
route = config.route(request);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
sendDenial(response, { action: 'block', reason: 'route_not_in_inventory', requestId: (0, node_crypto_1.randomUUID)(), policyVersion: 'unknown' });
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
if (!route)
|
|
32
|
+
return undefined;
|
|
33
|
+
let ip;
|
|
34
|
+
try {
|
|
35
|
+
ip = config.clientIp(request);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
sendDenial(response, { action: 'unavailable', reason: 'untrusted_origin', requestId: (0, node_crypto_1.randomUUID)(), policyVersion: 'unknown', retryAfterSeconds: 1 });
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
const result = await config.guard.admit({ ip, userAgent: request.headers['user-agent'] ?? '', routeGroup: route.group, cost: route.cost, request });
|
|
42
|
+
if (result.decision.action !== 'allow') {
|
|
43
|
+
sendDenial(response, result.decision);
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
return result.context;
|
|
47
|
+
}
|
|
48
|
+
/** Express-compatible middleware, also usable with a plain Node handler chain. */
|
|
49
|
+
function createNodeCrawlerMiddleware(config) {
|
|
50
|
+
return (request, response, next) => {
|
|
51
|
+
delete request.valironCrawler;
|
|
52
|
+
void admit(config, request, response).then(context => {
|
|
53
|
+
if (context === false)
|
|
54
|
+
return;
|
|
55
|
+
if (context)
|
|
56
|
+
request.valironCrawler = context;
|
|
57
|
+
next();
|
|
58
|
+
}).catch(next);
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** Structural Nitro/H3 event adapter: wrap with Nuxt's defineEventHandler. */
|
|
62
|
+
function createNuxtCrawlerMiddleware(config) {
|
|
63
|
+
return async (event) => {
|
|
64
|
+
delete event.context.valironCrawler;
|
|
65
|
+
const context = await admit(config, event.node.req, event.node.res);
|
|
66
|
+
if (context)
|
|
67
|
+
event.context.valironCrawler = context;
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/** Compatible with ioredis. Configure bounded timeouts, no offline queue/retry. */
|
|
2
|
+
export interface RedisEval {
|
|
3
|
+
eval(script: string, keyCount: number, ...args: (string | number)[]): Promise<unknown>;
|
|
4
|
+
}
|
|
5
|
+
export type Bucket = {
|
|
6
|
+
key: string;
|
|
7
|
+
capacity: number;
|
|
8
|
+
refillPerSecond: number;
|
|
9
|
+
cost: number;
|
|
10
|
+
};
|
|
11
|
+
export type Slot = {
|
|
12
|
+
key: string;
|
|
13
|
+
limit: number;
|
|
14
|
+
};
|
|
15
|
+
export type Decision = {
|
|
16
|
+
action: 'allow' | 'limit' | 'unavailable' | 'block';
|
|
17
|
+
reason: string;
|
|
18
|
+
requestId: string;
|
|
19
|
+
policyVersion: string;
|
|
20
|
+
retryAfterSeconds?: number;
|
|
21
|
+
};
|
|
22
|
+
export type WorkPermit = Readonly<{
|
|
23
|
+
id: string;
|
|
24
|
+
secret: string;
|
|
25
|
+
}>;
|
|
26
|
+
export declare function keyPart(input: string): string;
|
|
27
|
+
export declare class RedisAdmission {
|
|
28
|
+
protected readonly redis: RedisEval;
|
|
29
|
+
private readonly timeoutMs;
|
|
30
|
+
protected readonly prefix: string;
|
|
31
|
+
constructor(redis: RedisEval, tenant: string, timeoutMs?: number);
|
|
32
|
+
protected keys(stage: string, names: string[]): string[];
|
|
33
|
+
protected run(script: string, keys: string[], args: (string | number)[]): Promise<unknown>;
|
|
34
|
+
consume(buckets: readonly Bucket[]): Promise<{
|
|
35
|
+
allow: boolean;
|
|
36
|
+
retryAfterSeconds: number;
|
|
37
|
+
}>;
|
|
38
|
+
/** A transferable release capability; no TTL or automatic disconnect recovery. */
|
|
39
|
+
acquirePermit(slots: readonly Slot[], metadata?: {
|
|
40
|
+
requestId?: string;
|
|
41
|
+
lane?: string;
|
|
42
|
+
}): Promise<WorkPermit | undefined>;
|
|
43
|
+
/** May run on another worker. Only the capability holder may release after confirmed settlement. */
|
|
44
|
+
releasePermit(permit: WorkPermit): Promise<void>;
|
|
45
|
+
acquire(slots: readonly Slot[], metadata?: {
|
|
46
|
+
requestId?: string;
|
|
47
|
+
lane?: string;
|
|
48
|
+
}): Promise<(() => Promise<void>) | undefined>;
|
|
49
|
+
}
|
|
50
|
+
export declare class AdmissionError extends Error {
|
|
51
|
+
readonly decision: Decision;
|
|
52
|
+
constructor(decision: Decision);
|
|
53
|
+
}
|
|
54
|
+
/** Release after actual operation settlement, never after HTTP disconnect/timeout. */
|
|
55
|
+
export declare function withWorkSlot<T>(input: {
|
|
56
|
+
store: RedisAdmission;
|
|
57
|
+
lane?: string;
|
|
58
|
+
slots: readonly Slot[];
|
|
59
|
+
policyVersion: string;
|
|
60
|
+
requestId?: string;
|
|
61
|
+
onReleaseFailure?: () => void;
|
|
62
|
+
}, operation: () => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AdmissionError = exports.RedisAdmission = void 0;
|
|
4
|
+
exports.keyPart = keyPart;
|
|
5
|
+
exports.withWorkSlot = withWorkSlot;
|
|
6
|
+
const node_os_1 = require("node:os");
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
// All buckets use one server timestamp and commit only if every bucket admits.
|
|
9
|
+
const RATE = `
|
|
10
|
+
-- ADMISSION
|
|
11
|
+
local clock = redis.call('TIME')
|
|
12
|
+
local now = tonumber(clock[1]) * 1000 + tonumber(clock[2]) / 1000
|
|
13
|
+
local values = {}
|
|
14
|
+
local retry = 0
|
|
15
|
+
for i,key in ipairs(KEYS) do
|
|
16
|
+
local offset = (i-1)*3
|
|
17
|
+
local cap = tonumber(ARGV[offset+1])
|
|
18
|
+
local refill = tonumber(ARGV[offset+2])
|
|
19
|
+
local cost = tonumber(ARGV[offset+3])
|
|
20
|
+
local old = redis.call('HMGET', key, 'tokens', 'at')
|
|
21
|
+
local available = cap
|
|
22
|
+
if old[1] then available = math.min(cap, tonumber(old[1]) + math.max(0,now-tonumber(old[2]))*refill/1000) end
|
|
23
|
+
values[i] = available-cost
|
|
24
|
+
if available < cost then retry = math.max(retry, math.ceil((cost-available)/refill)) end
|
|
25
|
+
end
|
|
26
|
+
if retry > 0 then return {0, retry} end
|
|
27
|
+
for i,key in ipairs(KEYS) do
|
|
28
|
+
local offset = (i-1)*3
|
|
29
|
+
redis.call('HSET', key, 'tokens', values[i], 'at', now)
|
|
30
|
+
redis.call('PEXPIRE', key, math.ceil(tonumber(ARGV[offset+1])/tonumber(ARGV[offset+2])*1000)+1000)
|
|
31
|
+
end
|
|
32
|
+
return {1,0}
|
|
33
|
+
`;
|
|
34
|
+
// Slots intentionally have no TTL: a crashed process cannot silently free slots
|
|
35
|
+
// while its DB query may still be alive. Reconcile orphaned holds after draining.
|
|
36
|
+
const ACQUIRE = `
|
|
37
|
+
-- ADMISSION
|
|
38
|
+
-- WORK_ACQUIRE
|
|
39
|
+
local inventory = table.remove(KEYS,1)
|
|
40
|
+
local metadata = cjson.decode(table.remove(ARGV,1))
|
|
41
|
+
if redis.call('HLEN',inventory) >= 10000 then return 0 end
|
|
42
|
+
for i,key in ipairs(KEYS) do
|
|
43
|
+
if redis.call('HLEN',key) >= tonumber(ARGV[i+1]) then return 0 end
|
|
44
|
+
end
|
|
45
|
+
local clock = redis.call('TIME')
|
|
46
|
+
metadata.acquiredAt = tonumber(clock[1])*1000+math.floor(tonumber(clock[2])/1000)
|
|
47
|
+
metadata.keys = KEYS
|
|
48
|
+
for i,key in ipairs(KEYS) do redis.call('HSET',key,ARGV[1],1) end
|
|
49
|
+
redis.call('HSET',inventory,ARGV[1],cjson.encode(metadata))
|
|
50
|
+
return 1
|
|
51
|
+
`;
|
|
52
|
+
const RELEASE_PERMIT = `
|
|
53
|
+
local raw=redis.call('HGET',KEYS[1],ARGV[1])
|
|
54
|
+
if not raw then return 1 end
|
|
55
|
+
local record=cjson.decode(raw)
|
|
56
|
+
if record.releaseHash ~= ARGV[2] then return redis.error_reply('Invalid release capability') end
|
|
57
|
+
for _,key in ipairs(record.keys) do
|
|
58
|
+
if string.sub(key,1,string.len(ARGV[3])) ~= ARGV[3] then return redis.error_reply('Invalid hold key') end
|
|
59
|
+
end
|
|
60
|
+
for _,key in ipairs(record.keys) do redis.call('HDEL',key,ARGV[1]) end
|
|
61
|
+
redis.call('HDEL',KEYS[1],ARGV[1])
|
|
62
|
+
return 1
|
|
63
|
+
`;
|
|
64
|
+
function positive(value, integer = false) {
|
|
65
|
+
if (!Number.isFinite(value) || value <= 0 || value > 1e9 || (integer && !Number.isSafeInteger(value))) {
|
|
66
|
+
throw new Error('Invalid admission limit');
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function keyPart(input) {
|
|
70
|
+
return (0, node_crypto_1.createHash)('sha256').update(input).digest('hex');
|
|
71
|
+
}
|
|
72
|
+
class RedisAdmission {
|
|
73
|
+
redis;
|
|
74
|
+
timeoutMs;
|
|
75
|
+
prefix;
|
|
76
|
+
constructor(redis, tenant, timeoutMs = 250) {
|
|
77
|
+
this.redis = redis;
|
|
78
|
+
this.timeoutMs = timeoutMs;
|
|
79
|
+
if (!tenant || tenant.length > 128)
|
|
80
|
+
throw new Error('Invalid tenant');
|
|
81
|
+
positive(timeoutMs, true);
|
|
82
|
+
this.prefix = `valiron:crawler:{${keyPart(tenant)}}:`;
|
|
83
|
+
}
|
|
84
|
+
keys(stage, names) {
|
|
85
|
+
if (!names.length || names.length > 16 || new Set(names).size !== names.length || names.some(k => !k || k.length > 512)) {
|
|
86
|
+
throw new Error('Invalid admission keys');
|
|
87
|
+
}
|
|
88
|
+
return names.map(name => this.prefix + stage + ':' + keyPart(name));
|
|
89
|
+
}
|
|
90
|
+
async run(script, keys, args) {
|
|
91
|
+
let timer;
|
|
92
|
+
try {
|
|
93
|
+
return await Promise.race([
|
|
94
|
+
this.redis.eval(script, keys.length, ...keys, ...args),
|
|
95
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Admission dependency timeout')), this.timeoutMs); }),
|
|
96
|
+
]);
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
if (timer)
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
async consume(buckets) {
|
|
104
|
+
for (const b of buckets) {
|
|
105
|
+
positive(b.capacity);
|
|
106
|
+
positive(b.refillPerSecond);
|
|
107
|
+
positive(b.cost);
|
|
108
|
+
if (b.cost > b.capacity || b.capacity / b.refillPerSecond > 86400)
|
|
109
|
+
throw new Error('Unserviceable bucket');
|
|
110
|
+
}
|
|
111
|
+
const keys = this.keys('rate', buckets.map(b => b.key));
|
|
112
|
+
const result = await this.run(RATE, keys, buckets.flatMap(b => [b.capacity, b.refillPerSecond, b.cost]));
|
|
113
|
+
if (!Array.isArray(result) || result.length !== 2 || ![0, 1].includes(Number(result[0])) ||
|
|
114
|
+
!Number.isFinite(Number(result[1])))
|
|
115
|
+
throw new Error('Invalid admission response');
|
|
116
|
+
return { allow: Number(result[0]) === 1, retryAfterSeconds: Math.min(86400, Math.max(1, Number(result[1]))) };
|
|
117
|
+
}
|
|
118
|
+
/** A transferable release capability; no TTL or automatic disconnect recovery. */
|
|
119
|
+
async acquirePermit(slots, metadata = {}) {
|
|
120
|
+
slots.forEach(s => positive(s.limit, true));
|
|
121
|
+
const fields = Object.fromEntries(Object.entries(metadata).filter(([, value]) => value !== undefined));
|
|
122
|
+
if (Object.keys(fields).some(key => !['requestId', 'lane'].includes(key)) ||
|
|
123
|
+
Object.values(fields).some(v => typeof v !== 'string' || v.length > 128))
|
|
124
|
+
throw new Error('Invalid hold metadata');
|
|
125
|
+
const keys = this.keys('work', slots.map(s => s.key));
|
|
126
|
+
const id = (0, node_crypto_1.randomUUID)();
|
|
127
|
+
const secret = (0, node_crypto_1.randomBytes)(32).toString('base64url');
|
|
128
|
+
const result = Number(await this.run(ACQUIRE, [this.prefix + 'holds', ...keys], [JSON.stringify({ ...fields,
|
|
129
|
+
slots: slots.map(s => s.key), owner: (0, node_os_1.hostname)() + ':' + process.pid + ':' + id, releaseHash: keyPart(secret) }), id, ...slots.map(s => s.limit)]));
|
|
130
|
+
if (result === 0)
|
|
131
|
+
return undefined;
|
|
132
|
+
if (result !== 1)
|
|
133
|
+
throw new Error('Invalid lease response');
|
|
134
|
+
return Object.freeze({ id, secret });
|
|
135
|
+
}
|
|
136
|
+
/** May run on another worker. Only the capability holder may release after confirmed settlement. */
|
|
137
|
+
async releasePermit(permit) {
|
|
138
|
+
if (!permit || !/^[a-f0-9-]{36}$/.test(permit.id) || !/^[A-Za-z0-9_-]{43}$/.test(permit.secret))
|
|
139
|
+
throw new Error('Invalid work permit');
|
|
140
|
+
await this.run(RELEASE_PERMIT, [this.prefix + 'holds'], [permit.id, keyPart(permit.secret), this.prefix + 'work:']);
|
|
141
|
+
}
|
|
142
|
+
async acquire(slots, metadata = {}) {
|
|
143
|
+
const permit = await this.acquirePermit(slots, metadata);
|
|
144
|
+
if (!permit)
|
|
145
|
+
return undefined;
|
|
146
|
+
let released = false;
|
|
147
|
+
return async () => {
|
|
148
|
+
if (released)
|
|
149
|
+
return;
|
|
150
|
+
await this.releasePermit(permit);
|
|
151
|
+
released = true;
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
exports.RedisAdmission = RedisAdmission;
|
|
156
|
+
class AdmissionError extends Error {
|
|
157
|
+
decision;
|
|
158
|
+
constructor(decision) {
|
|
159
|
+
super(decision.reason);
|
|
160
|
+
this.decision = decision;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
exports.AdmissionError = AdmissionError;
|
|
164
|
+
/** Release after actual operation settlement, never after HTTP disconnect/timeout. */
|
|
165
|
+
async function withWorkSlot(input, operation) {
|
|
166
|
+
const requestId = input.requestId ?? (0, node_crypto_1.randomUUID)();
|
|
167
|
+
let release;
|
|
168
|
+
try {
|
|
169
|
+
release = await input.store.acquire(input.slots, { requestId, lane: input.lane });
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
throw new AdmissionError({ action: 'unavailable', reason: 'work_store_unavailable', requestId,
|
|
173
|
+
policyVersion: input.policyVersion, retryAfterSeconds: 1 });
|
|
174
|
+
}
|
|
175
|
+
if (!release)
|
|
176
|
+
throw new AdmissionError({ action: 'unavailable', reason: 'work_capacity_exhausted', requestId,
|
|
177
|
+
policyVersion: input.policyVersion, retryAfterSeconds: 1 });
|
|
178
|
+
try {
|
|
179
|
+
return await operation();
|
|
180
|
+
}
|
|
181
|
+
finally {
|
|
182
|
+
// Preserve the operation outcome. A failed release leaves a conservative hold.
|
|
183
|
+
await release().catch(() => { try {
|
|
184
|
+
input.onReleaseFailure?.();
|
|
185
|
+
}
|
|
186
|
+
catch { /* preserve operation outcome */ } });
|
|
187
|
+
}
|
|
188
|
+
}
|
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type RedisEval } from './admission';
|
|
2
|
+
import { ManagedRedisAdmission } from './operations';
|
|
3
|
+
export type CacheEvent = 'bypass' | 'fresh_hit' | 'stale_hit' | 'miss' | 'regeneration_busy' | 'stored' | 'storage_skipped' | 'uncacheable' | 'error';
|
|
4
|
+
export type PublicResponse = {
|
|
5
|
+
status: number;
|
|
6
|
+
headers: Record<string, string>;
|
|
7
|
+
body: string;
|
|
8
|
+
};
|
|
9
|
+
/** Public catalog HTML only. Personalized requests bypass before reading shared state. */
|
|
10
|
+
export declare class CatalogCache {
|
|
11
|
+
private readonly config;
|
|
12
|
+
constructor(config: {
|
|
13
|
+
onEvent?: (event: CacheEvent) => void;
|
|
14
|
+
redis: RedisEval;
|
|
15
|
+
admission: ManagedRedisAdmission;
|
|
16
|
+
namespace: string;
|
|
17
|
+
queryKeys: readonly string[];
|
|
18
|
+
trackingKeys?: readonly string[];
|
|
19
|
+
freshMs: number;
|
|
20
|
+
staleMs: number;
|
|
21
|
+
maxBytes: number;
|
|
22
|
+
maxEntries: number;
|
|
23
|
+
maxRegenerations: number;
|
|
24
|
+
});
|
|
25
|
+
private emit;
|
|
26
|
+
private prefix;
|
|
27
|
+
key(input: {
|
|
28
|
+
method: string;
|
|
29
|
+
url: string;
|
|
30
|
+
headers: Record<string, string | undefined>;
|
|
31
|
+
}): string | undefined;
|
|
32
|
+
private cacheable;
|
|
33
|
+
get(input: {
|
|
34
|
+
method: string;
|
|
35
|
+
url: string;
|
|
36
|
+
headers: Record<string, string | undefined>;
|
|
37
|
+
},
|
|
38
|
+
/** Must admit the request BEFORE SSR, and admit every DB operation. */
|
|
39
|
+
admittedLoader: () => Promise<PublicResponse>,
|
|
40
|
+
/** Required for background stale refresh; otherwise stale is served without refresh. */
|
|
41
|
+
background?: (work: Promise<void>) => void): Promise<PublicResponse>;
|
|
42
|
+
}
|