@rebilder/agent-readability 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.
@@ -0,0 +1,385 @@
1
+ import { C as ArsVantage, e as ArsEvidence, c as ArsRuleset } from '../types-B2FhQ1YC.js';
2
+
3
+ /**
4
+ * probe/ssrf.ts — the network-side host policy for `@rebilder/agent-readability`.
5
+ *
6
+ * WHAT CHANGED, AND WHY IT HAD TO. The ancestor of this file
7
+ * (`apps/rebilder-web/lib/preview/ssrf.ts`) described itself as *"Pure parse +
8
+ * reject (no DNS resolution in v1)"*. That sentence is deliberately not repeated
9
+ * here, because it is a description of a hole. A parse-only guard rejects IP
10
+ * literals; it does not reject `https://attacker.example/` whose A record is
11
+ * `169.254.169.254`, `10.0.0.5` or `127.0.0.1`, and DNS rebinding beats it by
12
+ * construction — resolve public, pass the guard, resolve private, connect.
13
+ * Behind a Console login that was defensible. On a public endpoint it is not,
14
+ * and this module is the one the public scanner, the CLI and the MCP server all
15
+ * go through. So (design §5.2):
16
+ *
17
+ * 1. WE RESOLVE THE HOSTNAME OURSELVES and reject if **any** returned A/AAAA
18
+ * is private or reserved. Not "the first one" — a hostname with one public
19
+ * and one private answer is an attack, not a multi-homed service.
20
+ * 2. WE CONNECT PINNED TO THE VALIDATED IP, with `Host` and SNI still carrying
21
+ * the hostname. This closes the rebinding window: the address the guard
22
+ * approved is the address the socket uses, because the resolver the socket
23
+ * would have called is replaced by a function that returns the approved set
24
+ * and nothing else.
25
+ * 3. EVERY REDIRECT HOP RE-RESOLVES AND RE-PINS. Re-parsing the `Location`
26
+ * URL is not enough; hop 2 is a fresh connection to a fresh name.
27
+ * 4. THE RESERVED SET IS THE FULL ONE — CGNAT (`100.64/10`, which is also
28
+ * where Alibaba keeps its metadata service at `100.100.100.200`), IETF
29
+ * protocol assignments, benchmarking, multicast, the whole of `240/4`,
30
+ * the broadcast address, and the IPv6 equivalents including IPv4-mapped
31
+ * and NAT64/6to4 forms, where a reserved v4 address hides inside a v6 one.
32
+ *
33
+ * WHAT THIS MODULE STILL CANNOT DO. It cannot stop a target whose *public* IP
34
+ * fronts an internal service (a cloud load balancer with a private backend), and
35
+ * it cannot stop a captive network from answering for someone else. Design §5.2
36
+ * requires the belt to the braces: scanner egress runs on a network with no route
37
+ * to cloud metadata or any internal subnet. This file assumes that and does not
38
+ * replace it.
39
+ *
40
+ * NOT AN ENTRY POINT. `package.json#exports` publishes `.`, `./probe` and
41
+ * `./probe/local` only, so `ALLOW_PRIVATE_HOSTS` below is unreachable from
42
+ * outside the package at runtime, and `tooling/check-package-graph.ts` fails any
43
+ * deep import that tries. That is what makes the symbol an unforgeable capability
44
+ * rather than a naming convention.
45
+ */
46
+ /**
47
+ * The capability that unlocks private/loopback targets. Held by `./probe/local`
48
+ * and by nothing else.
49
+ *
50
+ * WHY A SYMBOL AND NOT A BOOLEAN. `ProbePolicy` (see `./index`) has no
51
+ * `allowPrivateHosts` field on purpose. A boolean on a shared config object will
52
+ * eventually be passed as `true` by a hosted endpoint — not maliciously, just by
53
+ * someone wiring a new route who copies a working config. The concrete failure:
54
+ * an MCP server on a developer's machine, driven by a model whose context
55
+ * contains untrusted web text, asked to "check http://169.254.169.254/". A symbol
56
+ * that only a separate, import-time-gated entry point can obtain cannot be turned
57
+ * on by a config file, an env var, or a copied object literal.
58
+ */
59
+ declare const ALLOW_PRIVATE_HOSTS: unique symbol;
60
+ /** `'public-only'` everywhere except the `./probe/local` entry point. */
61
+ type HostPolicy = 'public-only' | typeof ALLOW_PRIVATE_HOSTS;
62
+ interface IpClassification {
63
+ /** `null` when the text is not an IP literal at all (i.e. it is a hostname). */
64
+ readonly family: 4 | 6 | null;
65
+ /** True for anything that is not a globally routable unicast address. */
66
+ readonly reserved: boolean;
67
+ /** Human-readable reason, printed in guard messages and probe details. */
68
+ readonly label: string;
69
+ }
70
+ /** Strict dotted-quad. Leading zeros are rejected: `010.0.0.1` is ambiguous octal. */
71
+ declare function parseIpv4(text: string): [number, number, number, number] | null;
72
+ /**
73
+ * IPv6 to eight 16-bit groups. Handles `::` compression, a zone id, and the
74
+ * trailing-IPv4 forms (`::ffff:169.254.169.254`, `64:ff9b::10.0.0.5`) that are
75
+ * the whole reason IPv6 belongs in an SSRF guard at all.
76
+ */
77
+ declare function parseIpv6(input: string): number[] | null;
78
+ /**
79
+ * Classifies an IP literal. `family: null` means the text is not an IP at all.
80
+ * Fails closed: anything that looks like an IP but does not parse is reserved.
81
+ */
82
+ declare function classifyIp(text: string): IpClassification;
83
+ type UrlGuardResult = {
84
+ ok: true;
85
+ url: URL;
86
+ } | {
87
+ ok: false;
88
+ reason: string;
89
+ };
90
+ interface UrlGuardPolicy {
91
+ /** `false` in every hosted path. `true` only under `./probe/local`. */
92
+ readonly allowHttp: boolean;
93
+ readonly hostPolicy: HostPolicy;
94
+ }
95
+ /**
96
+ * Parse + reject, with no I/O. This is the FIRST of two gates, not the only one:
97
+ * `resolveAndValidate` is the second and is the one that closes the DNS hole.
98
+ * Splitting them keeps the syntactic policy testable without a resolver and keeps
99
+ * the resolver from being the place a reviewer has to look for "is http allowed".
100
+ */
101
+ declare function guardUrl(input: string, policy: UrlGuardPolicy): UrlGuardResult;
102
+ /**
103
+ * The strict public policy, and the name the Console preview has always used.
104
+ * Kept as a named export because `apps/rebilder-web/lib/preview/ssrf.ts` and its
105
+ * shipped tests are written against it.
106
+ */
107
+ declare function guardPreviewUrl(input: string): UrlGuardResult;
108
+ interface PinnedAddress {
109
+ readonly address: string;
110
+ readonly family: 4 | 6;
111
+ }
112
+ interface HostResolver {
113
+ resolve(hostname: string): Promise<readonly PinnedAddress[]>;
114
+ }
115
+ type ResolveOutcome = {
116
+ ok: true;
117
+ addresses: readonly PinnedAddress[];
118
+ } | {
119
+ ok: false;
120
+ kind: 'unreachable' | 'policy-rejected';
121
+ reason: string;
122
+ };
123
+ /** Real DNS. The only resolver a hosted path ever uses. */
124
+ declare function createDnsResolver(): HostResolver;
125
+ /**
126
+ * Resolves and validates. Rejects if ANY answer is reserved — not "if the first
127
+ * one is". A name that answers with one public and one private address is the
128
+ * shape of the attack, and picking the public one and connecting anyway is how
129
+ * a guard that looks correct fails.
130
+ */
131
+ declare function resolveAndValidate(hostname: string, resolver: HostResolver, hostPolicy: HostPolicy): Promise<ResolveOutcome>;
132
+ interface ProbeRequestInit {
133
+ readonly headers: Readonly<Record<string, string>>;
134
+ /** Always `'manual'`: hops are our decision, because each one must re-resolve. */
135
+ readonly redirect: 'manual';
136
+ readonly signal: AbortSignal;
137
+ /**
138
+ * The addresses `resolveAndValidate` approved for this exact URL's hostname.
139
+ * The transport MUST connect to one of these and MUST NOT consult a resolver
140
+ * of its own; that is the whole anti-rebinding mechanism.
141
+ */
142
+ readonly pinnedAddresses: readonly PinnedAddress[];
143
+ }
144
+ /**
145
+ * A response, reduced to the three things ARS evidence needs.
146
+ *
147
+ * `headers` is `name → all values`, not `name → value`. `Link` is routinely sent
148
+ * more than once and is scored twice over (D2.2 declared alternates, D6.5
149
+ * machine endpoints); a transport that joins them is losing scored evidence.
150
+ */
151
+ interface ProbeHttpResponse {
152
+ readonly status: number;
153
+ readonly headers: Record<string, string[]>;
154
+ readonly body: ReadableStream<Uint8Array> | null;
155
+ }
156
+ type ProbeTransport = (url: string, init: ProbeRequestInit) => Promise<ProbeHttpResponse>;
157
+ /** Adapts a WHATWG `Response` — the shape tests and fixtures find easiest to build. */
158
+ declare function fromWebResponse(response: Response): ProbeHttpResponse;
159
+ /**
160
+ * The production transport: `node:https`/`node:http` with a `lookup` that can
161
+ * only return the validated addresses.
162
+ *
163
+ * WHY NOT `fetch` + an undici `Agent`. Design §5.2 names undici's `Agent` with a
164
+ * custom `lookup`, which is the same mechanism; `undici` is not reachable as a
165
+ * built-in module and this package's contract is zero runtime dependencies, so
166
+ * the identical property is obtained from `node:https`, whose options flow
167
+ * through to `net.connect`. `servername` keeps SNI on the hostname and Node's
168
+ * default `setHost` keeps the `Host` header on the hostname, so the origin sees
169
+ * a normal request and only the socket's destination is fixed.
170
+ *
171
+ * No `Accept-Encoding` is sent, so nothing arrives compressed and the decoded
172
+ * byte count is the transferred byte count. §3.3 drops `transferBytes` for
173
+ * exactly this reason: a hashed field that is platform-dependent is worse than
174
+ * no field.
175
+ */
176
+ declare function createPinnedTransport(): ProbeTransport;
177
+
178
+ /**
179
+ * probe/limiter.ts — politeness, as a thing you have to hold rather than a thing
180
+ * you have to remember.
181
+ *
182
+ * WHY IT LIVES IN THE PACKAGE. Every consumer of `./probe` — the hosted scanner,
183
+ * the CLI, the MCP server on a stranger's laptop — puts OUR user agent on OUR
184
+ * domain in front of somebody else's origin. A limiter that each consumer is
185
+ * asked to remember to install is a limiter that one of them ships without.
186
+ * `ProbePolicy.limiter` is therefore required, not optional: there is no code
187
+ * path through `probeStrict` that does not take a lease first.
188
+ *
189
+ * WHY IT IS INJECTED AND NEVER MODULE-GLOBAL. Module state is exactly right in a
190
+ * CLI process — one run, one budget, exit — and exactly wrong in a warm
191
+ * serverless instance, where a module-level counter is shared by every request
192
+ * the container ever serves. A 20-probe soft cap implemented as a module global
193
+ * would work perfectly in testing and then, on the twenty-first scan of an
194
+ * instance's life, start refusing unrelated users with no signal that anything
195
+ * had changed. So the limiter is constructed by the caller, scoped to whatever
196
+ * the caller means by "a run", and passed in.
197
+ *
198
+ * DEFAULTS (design §5.2): 1 concurrent probe per host, 2 globally, ≥1s between
199
+ * probes to the same host, ~20 probes per run and then an explicit override.
200
+ * "Probe" here means one HTTP request, which is the unit an origin experiences.
201
+ * A cold single-URL scan is 5 requests (§3.3: robots, agent, browser, llms.txt,
202
+ * .well-known/ucp), so the default budget is about four cold URLs — a deliberate
203
+ * floor that a multi-URL CLI run raises on purpose by passing `maxProbesPerRun`.
204
+ *
205
+ * NOTHING HERE IS PURE, and it does not have to be: the ESLint purity rule
206
+ * exempts `src/probe/**`. `now` and `sleep` are injectable so the tests do not
207
+ * spend real seconds proving that a one-second gap is a one-second gap.
208
+ */
209
+ interface LimiterLease {
210
+ /** Idempotent. Releases the host and global slots and starts the host's cooldown. */
211
+ release(): void;
212
+ }
213
+ interface Limiter {
214
+ /** Resolves when it is polite to send. Rejects with `ProbeBudgetExceededError`. */
215
+ acquire(host: string): Promise<LimiterLease>;
216
+ /** Requests started in this run, including ones still in flight. */
217
+ readonly used: number;
218
+ /** The soft cap this limiter was constructed with. */
219
+ readonly budget: number;
220
+ }
221
+ /**
222
+ * Thrown by `acquire` when the run budget is spent. A distinct type because the
223
+ * caller has to be able to tell "we chose not to send this" from "the origin
224
+ * did not answer" — the CLI maps them to different exit codes (4 vs 3) and
225
+ * confusing the two deletes a CI check within a week (design §5.6).
226
+ */
227
+ declare class ProbeBudgetExceededError extends Error {
228
+ readonly budget: number;
229
+ constructor(budget: number);
230
+ }
231
+ interface LimiterOptions {
232
+ /** Default 1. Two concurrent requests to one origin is not a probe, it is a load test. */
233
+ maxConcurrentPerHost?: number;
234
+ /** Default 2. */
235
+ maxConcurrentGlobal?: number;
236
+ /** Default 1000ms, measured from the release of the previous lease for that host. */
237
+ minIntervalPerHostMs?: number;
238
+ /** Default 20 requests. The explicit override is passing a different number here. */
239
+ maxProbesPerRun?: number;
240
+ now?: () => number;
241
+ sleep?: (ms: number) => Promise<void>;
242
+ }
243
+ /**
244
+ * Builds a limiter scoped to one "run" — one CLI invocation, one MCP session,
245
+ * one scan job. Acquisition order is global-then-host in every path, so two
246
+ * hosts can never deadlock each other.
247
+ */
248
+ declare function createLimiter(options?: LimiterOptions): Limiter;
249
+
250
+ /**
251
+ * probe/index.ts — `"./probe"`. The server-only, deliberately impure half.
252
+ *
253
+ * The pure half (`.`) consumes exactly one thing: an `ArsEvidence` bundle. This
254
+ * file is the only sanctioned way to produce one from a live origin. Everything
255
+ * non-deterministic in ARS is here — sockets, DNS, the clock, sleeping — and
256
+ * nothing here influences a score except through the bundle it returns. The
257
+ * ESLint purity rule in `eslint.config.mjs` exempts `src/probe/**`, and only
258
+ * `src/probe/**`; nothing that needs a clock or a socket may move up a directory.
259
+ *
260
+ * THE REQUEST SET IS CLOSED (§3.3). Per URL: an **agent probe** and a **browser
261
+ * control** that differ in the `Accept` header AND IN NOTHING ELSE — same User
262
+ * Agent, same everything. That is what makes the D2.4 parity check meaningful and
263
+ * what stops a correctly installed gateway, which negotiates on `Accept` and not
264
+ * on UA, from being scored as a cloaker. Per origin: `/robots.txt` (first),
265
+ * `/llms.txt`, `/.well-known/ucp`. Nothing else. No guessing `/sitemap.xml`,
266
+ * `/mcp`, `/acp` — credit for an endpoint comes from *declaring* it, because an
267
+ * endpoint an agent cannot find is an endpoint that does not exist. The three
268
+ * probed paths are the disclosed exception: published conventions at published
269
+ * locations.
270
+ *
271
+ * WE IMITATE AGENT INTENT, NEVER AGENT IDENTITY. `assertIdentities` refuses a
272
+ * User-Agent that names somebody else's crawler and refuses an agent/browser
273
+ * pair whose UAs differ. The printed consequence, which belongs next to the
274
+ * parity check and not in a footnote: ARS cannot detect UA-targeted cloaking,
275
+ * including cloaking aimed at `rebilder-ars` itself.
276
+ *
277
+ * THE TWO DEFECTS THIS FILE EXISTS TO CLOSE (design §5.2):
278
+ * - **DNS.** The ancestor guard rejected IP literals and resolved nothing. See
279
+ * `./ssrf`: we resolve, we reject if any answer is reserved, we connect
280
+ * pinned to the validated address, and we re-resolve and re-pin on every hop.
281
+ * - **Byte cap.** The ancestor called `await response.text()` with no limit.
282
+ * Bodies are streamed through `getReader()`, decoded bytes are counted, the
283
+ * read is aborted at the ruleset's 2 MiB and `truncated: true` is recorded.
284
+ * Silently scoring a truncated body would make the heaviest pages score best
285
+ * on D3.2 — the one number the product is built on.
286
+ *
287
+ * WHAT THIS FILE DOES NOT DO. It does not take the §3.8 parity-confirm probe
288
+ * (`probes.parityConfirm` is always `null` here): that one is taken ≥30s after a
289
+ * divergence is detected, which is a scan-orchestration decision, not something
290
+ * to hide inside a call with a 5s budget. It does not cache; caching is the
291
+ * caller's, because the cache key is the caller's. And it does not decide what a
292
+ * result means — `score()` does, from the bundle alone.
293
+ */
294
+
295
+ type ProbeRole = 'agent' | 'browser' | 'asset';
296
+ interface ProbeIdentity {
297
+ readonly role: ProbeRole;
298
+ readonly userAgent: string;
299
+ readonly accept: string;
300
+ }
301
+ /** Honest, contactable, and never anybody else's. */
302
+ declare const ARS_USER_AGENT = "rebilder-ars/0.1 (+https://rebilder.com/bots)";
303
+ /** The robots.txt token this probe answers to. Matched case-insensitively. */
304
+ declare const ARS_ROBOTS_TOKEN = "rebilder-ars";
305
+ declare const AGENT_ACCEPT = "text/markdown;q=1.0, text/html;q=0.8, text/plain;q=0.5, */*;q=0.1";
306
+ declare const BROWSER_ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
307
+ declare const ASSET_ACCEPT = "text/plain,*/*;q=0.5";
308
+ declare const DEFAULT_IDENTITIES: readonly ProbeIdentity[];
309
+ /**
310
+ * Policy as a type rather than a pile of booleans — and note what is NOT here:
311
+ * there is no `allowPrivateHosts`. Private/loopback targets are unlocked by
312
+ * importing a different entry point (`./probe/local`), which throws at import
313
+ * time without a per-invocation opt-in, not by flipping a field on a config
314
+ * object that somebody will one day copy into a hosted route.
315
+ */
316
+ interface ProbePolicy {
317
+ /** Default false. True only under `./probe/local`. */
318
+ allowHttp: boolean;
319
+ /** 2 MiB, from the ruleset. Normative: two caps produce two different scores. */
320
+ maxBodyBytes: number;
321
+ /** 3, from the ruleset. */
322
+ maxRedirects: number;
323
+ /** 5 000ms, from the ruleset. */
324
+ timeoutMs: number;
325
+ /** Injected, never module-global. See `./limiter` for why that matters. */
326
+ limiter: Limiter;
327
+ identities: readonly ProbeIdentity[];
328
+ }
329
+ /**
330
+ * The hosted policy: https only, ruleset caps, default identities. The limiter
331
+ * is a required argument because "who owns this run's budget" is a question the
332
+ * caller has to answer, and a default would answer it wrongly in a warm
333
+ * serverless instance.
334
+ */
335
+ declare function strictPolicy(limiter: Limiter, ruleset?: ArsRuleset): ProbePolicy;
336
+ interface ProbeOptions {
337
+ /** Default `'public'`. Only `'public'` is gated on the `rebilder-ars` token. */
338
+ vantage?: ArsVantage;
339
+ /** Default: DNS-pinned `node:https`. Injected in tests; never bypasses the guard. */
340
+ transport?: ProbeTransport;
341
+ /** Default: real DNS. Validation runs whatever transport is in use. */
342
+ resolver?: HostResolver;
343
+ /** Default: wall clock. Feeds `ArsEvidence.capturedAt`, which is excluded from the hash. */
344
+ now?: () => Date;
345
+ sleep?: (ms: number) => Promise<void>;
346
+ /** §3.3: one retry after 5s before a 5xx robots.txt becomes `robots-unavailable`. */
347
+ robotsRetryDelayMs?: number;
348
+ }
349
+ /**
350
+ * Why `rejection` is not an `ArsUnscoredReason`: these are the cases where no
351
+ * evidence bundle exists at all, so there is nothing for `score()` to judge.
352
+ * Everything the origin actually said — a 404, a 500, a timeout, a redirect loop
353
+ * — comes back as `{ ok: true }` with the failure recorded inside the bundle,
354
+ * because that IS the observation.
355
+ */
356
+ type ProbeRejection = 'invalid-url' | 'policy-rejected' | 'budget-exceeded';
357
+ type ProbeOutcome = {
358
+ ok: true;
359
+ evidence: ArsEvidence;
360
+ } | {
361
+ ok: false;
362
+ rejection: ProbeRejection;
363
+ detail: string;
364
+ };
365
+ /**
366
+ * `hostPolicy` is a capability, not a flag: the only value other than
367
+ * `'public-only'` is a symbol exported from a non-entry-point module, so a
368
+ * consumer of `"./probe"` cannot construct one. Exported because
369
+ * `"./probe/local"` has to call it; harmless because calling it without the
370
+ * symbol is exactly `probeStrict`.
371
+ */
372
+ declare function probeWithHostPolicy(target: string, policy: ProbePolicy, hostPolicy: HostPolicy, options?: ProbeOptions): Promise<ProbeOutcome>;
373
+ /**
374
+ * The hosted probe. https only, public hosts only, DNS-validated and pinned,
375
+ * 2 MiB streamed cap, robots-gated, limiter-gated.
376
+ *
377
+ * There is deliberately no argument that relaxes any of that. `probeLocal` lives
378
+ * at `"./probe/local"`, throws at import time without a per-invocation opt-in,
379
+ * and is imported by the CLI and by nothing that can be reached over HTTP.
380
+ */
381
+ declare function probeStrict(target: string, policy: ProbePolicy, options?: ProbeOptions): Promise<ProbeOutcome>;
382
+ /** Convenience for one-off callers: a fresh run-scoped limiter and the strict policy. */
383
+ declare function strictPolicyForRun(overrides?: Partial<ProbePolicy>): ProbePolicy;
384
+
385
+ export { AGENT_ACCEPT, ARS_ROBOTS_TOKEN, ARS_USER_AGENT, ASSET_ACCEPT, BROWSER_ACCEPT, DEFAULT_IDENTITIES, type HostPolicy, type HostResolver, type IpClassification, type Limiter, type LimiterLease, type LimiterOptions, type PinnedAddress, ProbeBudgetExceededError, type ProbeHttpResponse, type ProbeIdentity, type ProbeOptions, type ProbeOutcome, type ProbePolicy, type ProbeRejection, type ProbeRequestInit, type ProbeRole, type ProbeTransport, type ResolveOutcome, type UrlGuardPolicy, type UrlGuardResult, classifyIp, createDnsResolver, createLimiter, createPinnedTransport, fromWebResponse, guardPreviewUrl, guardUrl, parseIpv4, parseIpv6, probeStrict, probeWithHostPolicy, resolveAndValidate, strictPolicy, strictPolicyForRun };