@jini-ai/diagnostics 0.5.1 → 0.5.3

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,192 @@
1
+ import { PageWorkBudget, PageWorkTimeout } from "./page-work-budget.js";
2
+ import { isSameOriginUrl } from "./same-origin.js";
3
+ import { MAX_REDIRECT_HOPS, isMainFrameNavigation } from "./request-guard.js";
4
+ /** Stable safe code for a renderer behind a port; no resolved peer or target path is exposed. */
5
+ export class RenderRequestRefused extends Error {
6
+ code = "WEB_RENDER_REFUSED";
7
+ constructor(_required, _options = {}) { super("Navigation refused by the egress guard"); }
8
+ }
9
+ /** Origin-only refusal metadata lets collectors retain their existing off-origin skip result. */
10
+ export class OffOriginNavigationError extends Error {
11
+ origin;
12
+ constructor({ url }) {
13
+ super("Off-origin navigation refused");
14
+ this.origin = new URL(url).origin;
15
+ }
16
+ }
17
+ /** Narrow known consent controls: never click a generic page-wide 'close' or 'accept' button. */
18
+ export const COOKIE_DISMISS_SELECTORS = [
19
+ "#onetrust-accept-btn-handler", "#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll",
20
+ "button#cookie-accept", "button[aria-label='Accept cookies']", "button[aria-label='Accept all cookies']",
21
+ "[role='dialog']:has-text('cookie') button:has-text('Accept all')",
22
+ "[role='dialog']:has-text('cookie') button[aria-label='Close']",
23
+ "[id*='cookie'] button:has-text('Accept')", "[class*='cookie'] button:has-text('Accept all')",
24
+ "#onetrust-close-btn-container button", "[id*='cookie'] button[aria-label='Close']", "[class*='cookie'] button[aria-label='Close']",
25
+ ];
26
+ /** Click the first visible known cookie control; absence or a disappearing banner is harmless.
27
+ * @complexity O(k), k is the fixed selector list; clicks use the same total page budget. */
28
+ export async function dismissCookieBanners({ page, budget }, _options = {}) {
29
+ if (!page.locator)
30
+ return false;
31
+ for (const selector of COOKIE_DISMISS_SELECTORS) {
32
+ try {
33
+ const locator = page.locator(selector).first();
34
+ if (await budget.run({ work: () => locator.count() }) === 0)
35
+ continue;
36
+ if (locator.isVisible && !await budget.run({ work: () => locator.isVisible() }))
37
+ continue;
38
+ await budget.run({ work: () => locator.click({ timeout: Math.min(500, budget.remainingMs()) }) });
39
+ return true;
40
+ }
41
+ catch (error) {
42
+ if (error instanceof PageWorkTimeout)
43
+ throw error;
44
+ }
45
+ }
46
+ return false;
47
+ }
48
+ /** Syntax boundary; address/DNS decisions belong exclusively to the pinned request router. */
49
+ function assertHttpUrl({ url }, _options = {}) {
50
+ const parsed = new URL(url);
51
+ if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password) {
52
+ throw new Error("Rendering requires an anonymous http(s) URL");
53
+ }
54
+ }
55
+ /** Open, guard, wait and consume ONE ephemeral page, always releasing the context.
56
+ * No network-idle wait: SPAs and polling sites can stay busy forever. DNS decisions are not followed
57
+ * by Chromium `continue()` in public mode: the router fetches on pinned vetted peers and fulfills
58
+ * responses; a dead proxy at launch prevents unrouted protocols from escaping.
59
+ * A fulfilled 3xx is never handed to Chromium: Playwright does not route its next hop. The router
60
+ * aborts a main-frame redirect and records its target, so each explicit goto is vetted again.
61
+ * @throws Browser errors, cancellation, PageWorkTimeout, or a refused origin/transport boundary.
62
+ * @complexity Bounded page I/O plus the consumer; at most six explicit navigation hops. */
63
+ export async function renderPage({ browser, url, consume }, options = {}) {
64
+ const { timeoutMs = 30_000, signal: callerSignal, waitFor = 1.2, originPolicy = "same-origin", originBaseUrl = url, router } = options;
65
+ assertHttpUrl({ url });
66
+ if (originPolicy === "public" && !router)
67
+ throw new Error("Public rendering requires a guarded request router");
68
+ // A native total timer remains firm even if the wall clock moves between budgeted steps.
69
+ const deadline = AbortSignal.timeout(timeoutMs);
70
+ const signal = callerSignal ? AbortSignal.any([callerSignal, deadline]) : deadline;
71
+ const budget = new PageWorkBudget({ timeoutMs }, { signal });
72
+ let context;
73
+ const onAbort = () => { void context?.close().catch(() => { }); };
74
+ signal?.throwIfAborted();
75
+ signal?.addEventListener("abort", onAbort, { once: true });
76
+ try {
77
+ context = await budget.run({ work: async () => {
78
+ const supplied = options.contextOptions ?? {};
79
+ const contextOptions = Object.fromEntries(["viewport", "deviceScaleFactor", "isMobile", "hasTouch", "javaScriptEnabled"].filter(key => supplied[key] !== undefined).map(key => [key, supplied[key]]));
80
+ // No storageState, recordVideo, recordHar or user-data dir: observed state never reaches disk.
81
+ const opened = await browser.newContext({ ...contextOptions, ignoreHTTPSErrors: false, serviceWorkers: "block", acceptDownloads: false });
82
+ // A context that opens after cancellation/deadline still belongs to this call.
83
+ if (budget.remainingMs() <= 0 || signal?.aborted) {
84
+ void opened.close().catch(() => { });
85
+ signal?.throwIfAborted();
86
+ throw new PageWorkTimeout({ timeoutMs });
87
+ }
88
+ return opened;
89
+ } });
90
+ const active = context;
91
+ await budget.run({ work: async () => { await active.routeWebSocket?.(/.*/, socket => socket.close().catch(() => { })); } });
92
+ let refusedOrigin;
93
+ await budget.run({ work: async () => {
94
+ await active.route("**/*", async (route) => {
95
+ const pending = route.request();
96
+ const navigation = isMainFrameNavigation({ request: pending });
97
+ const offOrigin = originPolicy === "same-origin" && navigation && !isSameOriginUrl({ baseUrl: originBaseUrl, candidateUrl: pending.url() });
98
+ if (offOrigin && navigation)
99
+ refusedOrigin = new URL(pending.url()).origin;
100
+ // Public data methods belong to the router; evidence always refuses writes first.
101
+ const blocked = offOrigin || ((originPolicy !== "public" || !router) && !["GET", "HEAD"].includes(pending.method().toUpperCase()));
102
+ const markBlocked = options.onRequest?.({ route, blocked });
103
+ if (blocked) {
104
+ await route.abort("blockedbyclient").catch(() => { });
105
+ return;
106
+ }
107
+ if (router) {
108
+ await router.handle({
109
+ request: () => pending, fulfill: options => route.fulfill(options),
110
+ abort: async (code) => {
111
+ // Redirect aborts are navigation control, not a refused network observation.
112
+ if (code !== "aborted" && typeof markBlocked === "function")
113
+ markBlocked({ reason: "aborted by the guarded browser request router (unsafe target, unsupported request or resource cap)" });
114
+ await route.abort(code);
115
+ },
116
+ });
117
+ return;
118
+ }
119
+ // Trusted own-origin evidence retains browser cookies, but never posts preferences or forms.
120
+ if (!route.continue)
121
+ throw new Error("Own-origin browser route cannot continue");
122
+ await route.continue();
123
+ });
124
+ } });
125
+ const page = await budget.run({ work: () => active.newPage() });
126
+ let target = url;
127
+ let response = null;
128
+ for (let hop = 0;; hop += 1) {
129
+ assertHttpUrl({ url: target });
130
+ if (originPolicy === "same-origin" && !isSameOriginUrl({ baseUrl: originBaseUrl, candidateUrl: target }))
131
+ throw new OffOriginNavigationError({ url: target });
132
+ try {
133
+ response = await budget.run({ work: () => page.goto(target, { waitUntil: "domcontentloaded", timeout: budget.remainingMs() }) });
134
+ break;
135
+ }
136
+ catch (error) {
137
+ if (refusedOrigin)
138
+ throw new OffOriginNavigationError({ url: refusedOrigin });
139
+ const next = router?.takeNavigationRedirect();
140
+ if (next !== undefined && hop < MAX_REDIRECT_HOPS) {
141
+ target = next;
142
+ continue;
143
+ }
144
+ if (router?.report().navigationRefused)
145
+ throw new RenderRequestRefused({});
146
+ if (next !== undefined)
147
+ throw new Error("too many redirects");
148
+ throw error;
149
+ }
150
+ }
151
+ const dismissed = options.dismissCookieBanners ? await dismissCookieBanners({ page, budget }) : false;
152
+ if (typeof waitFor === "string") {
153
+ if (!page.waitForSelector)
154
+ throw new Error("Browser does not support selector waits");
155
+ await budget.run({ work: () => page.waitForSelector(waitFor, { state: "visible", timeout: budget.remainingMs() }) });
156
+ }
157
+ else if (waitFor > 0) {
158
+ await budget.run({ work: () => page.waitForTimeout(waitFor * 1000) });
159
+ }
160
+ if (options.loadWaitMs && page.waitForLoadState) {
161
+ try {
162
+ await budget.run({ work: () => page.waitForLoadState("load", { timeout: Math.min(options.loadWaitMs, budget.remainingMs()) }) });
163
+ }
164
+ catch (error) {
165
+ if (error instanceof PageWorkTimeout || signal.aborted)
166
+ throw error;
167
+ // A polling or slow resource must not prevent bounded best-effort evidence/capture.
168
+ }
169
+ }
170
+ // Hydrated consent widgets can arrive during the settle/selector wait.
171
+ if (options.dismissCookieBanners && !dismissed && await dismissCookieBanners({ page, budget })) {
172
+ await budget.run({ work: () => page.waitForTimeout(200) });
173
+ }
174
+ signal?.throwIfAborted();
175
+ const finalUrl = page.url?.() ?? response?.url?.() ?? target;
176
+ assertHttpUrl({ url: finalUrl });
177
+ if (originPolicy === "same-origin" && !isSameOriginUrl({ baseUrl: originBaseUrl, candidateUrl: finalUrl }))
178
+ throw new OffOriginNavigationError({ url: finalUrl });
179
+ return await budget.run({ work: () => consume({ page, context: active, response, finalUrl, budget }) });
180
+ }
181
+ catch (error) {
182
+ if (deadline.aborted && !callerSignal?.aborted)
183
+ throw new PageWorkTimeout({ timeoutMs });
184
+ throw error;
185
+ }
186
+ finally {
187
+ signal?.removeEventListener("abort", onAbort);
188
+ if (context)
189
+ await budget.release({ close: () => context.close().catch(() => { }) });
190
+ }
191
+ }
192
+ //# sourceMappingURL=render-page.js.map
@@ -0,0 +1,166 @@
1
+ import type { HttpClientPort } from "@jini-ai/core/primitives";
2
+ /**
3
+ * @file Every network request the screenshot browser makes, decided and carried here — Chromium
4
+ * itself never opens a socket.
5
+ *
6
+ * The browser context routes `**\/*` to {@link createRequestRouter}. Each request is either aborted
7
+ * or FETCHED BY THIS PROCESS and fulfilled back into the page:
8
+ *
9
+ * - **Public origins** go through the injected guarded client — the same `@jini-ai/platform` guard
10
+ * `web_fetch_page` and `media_import_from_url` use. It resolves DNS, refuses loopback, RFC1918,
11
+ * link-local/cloud-metadata and IPv6 ULA/mapped addresses, and PINS the vetted address for the
12
+ * connection, so a DNS-rebinding answer between "check" and "connect" cannot reach a private host.
13
+ * That pinning is why requests are fetched here rather than vetted and then `continue()`d: a
14
+ * continued request is resolved again by Chromium, after the check.
15
+ * - **A redirect is never handed to Chromium.** The guard itself does not follow one
16
+ * (`maxRedirects: 0`), and a 3xx is not fulfilled either: Playwright does NOT route the next hop of
17
+ * a fulfilled redirect — Chromium sends it straight to the network (verified against real Chromium,
18
+ * 2026-10-08), where only the launch's dead proxy stops it. So the router follows every redirect
19
+ * itself, one hop at a time, and each hop is decided and fetched exactly like a new request: a
20
+ * redirect to a private address is refused at the hop that introduces it. A subresource's hops are
21
+ * followed here and the final answer fulfilled; the page's own (main-frame) navigation is aborted
22
+ * with its target recorded ({@link RequestRouter.takeNavigationRedirect}), and the capture navigates
23
+ * to that target, so the document lives at its real URL and relative links resolve against it.
24
+ * - **The allowlisted origins** (only ever this site's own per-call loopback render, injected by the
25
+ * host for own-site screenshots) go through `ownSiteFetch`, a plain loopback fetch that is never
26
+ * handed any other origin.
27
+ * - Public readers may opt into bounded XHR/fetch POST/PUT/PATCH via the guard. Evidence and
28
+ * screenshots remain GET/HEAD only. Everything else is aborted: non-http(s) schemes (a screenshot needs no
29
+ * writes, beacons or form posts), streaming/media types that only cost bandwidth in a still
30
+ * picture, and anything past the per-capture request/byte budget.
31
+ *
32
+ * Public captures drop request `Cookie`/`Authorization` and response `Set-Cookie`, on top of
33
+ * their fresh, storage-less context. Evidence forwards only its own fresh visitor cookies to
34
+ * the own-site origin; first- and third-party response cookies stay in its in-memory context.
35
+ */
36
+ /** The slice of a Playwright `Request` the router reads — structural, so tests pass plain objects. */
37
+ export interface RoutedRequest {
38
+ url(): string;
39
+ method(): string;
40
+ headers(): Record<string, string>;
41
+ /** Transport only: request bodies are never retained as evidence. */
42
+ postData?(): string | null;
43
+ resourceType(): string;
44
+ isNavigationRequest(): boolean;
45
+ frame(): {
46
+ parentFrame(): unknown;
47
+ };
48
+ }
49
+ /** The slice of a Playwright `Route` the router drives. */
50
+ export interface RouteLike {
51
+ request(): RoutedRequest;
52
+ fulfill(options: {
53
+ status: number;
54
+ headers: Record<string, string>;
55
+ body: Buffer;
56
+ }): Promise<void>;
57
+ abort(errorCode?: string): Promise<void>;
58
+ }
59
+ /** One fetched resource, already bounded. */
60
+ export interface FetchedResource {
61
+ status: number;
62
+ headers: Readonly<Record<string, string>>;
63
+ body: Buffer;
64
+ /** A clipped body is corrupt (a half image), so it is aborted rather than fulfilled. */
65
+ truncated: boolean;
66
+ }
67
+ /** Fetches one allowlisted own-site URL without following redirects. Never given another origin. */
68
+ export type OwnSiteFetch = (required: {
69
+ url: string;
70
+ method: "GET" | "HEAD";
71
+ headers: Record<string, string>;
72
+ }, optional: {
73
+ signal: AbortSignal;
74
+ maxBytes: number;
75
+ fetch?: typeof globalThis.fetch;
76
+ }) => Promise<FetchedResource>;
77
+ export type AbortReason = "scheme" | "method" | "resource-type" | "budget" | "refused" | "failed";
78
+ /** Redirect hops followed per request (and per page navigation), each one re-vetted. */
79
+ export declare const MAX_REDIRECT_HOPS = 5;
80
+ type RoutedMethod = "GET" | "HEAD" | "POST" | "PUT" | "PATCH";
81
+ export type RequestDecision = {
82
+ action: "fetch";
83
+ via: "guarded" | "own-site";
84
+ method: RoutedMethod;
85
+ } | {
86
+ action: "abort";
87
+ reason: AbortReason;
88
+ };
89
+ /**
90
+ * Pure routing decision for one request. Budget is not considered here (see the router).
91
+ * @complexity O(url length + allowedOrigins).
92
+ */
93
+ export declare function decideRequest({ url, method, resourceType, allowedOrigins }: {
94
+ url: string;
95
+ method: string;
96
+ resourceType: string;
97
+ allowedOrigins: readonly string[];
98
+ }, { allowDataRequests }?: {
99
+ allowDataRequests?: boolean;
100
+ }): RequestDecision;
101
+ export interface RequestRouterReport {
102
+ fulfilled: number;
103
+ blocked: number;
104
+ /** The page's own (main-frame) navigation, or a redirect hop of it, was refused by the egress guard. */
105
+ navigationRefused: boolean;
106
+ bytes: number;
107
+ }
108
+ export interface RequestRouter {
109
+ handle(route: RouteLike): Promise<void>;
110
+ report(): RequestRouterReport;
111
+ /** The absolute target of the last main-frame navigation answered with a redirect, then cleared. */
112
+ takeNavigationRedirect(): string | undefined;
113
+ }
114
+ export interface RequestRouterOptions {
115
+ /** Evidence observes first/third-party response cookies in memory; only own-site request cookies travel. */
116
+ preserveOwnSiteCookies?: boolean;
117
+ /** Public render only: permit bounded XHR/fetch POST/PUT/PATCH through the public guard. */
118
+ allowDataRequests?: boolean;
119
+ maxRequestBodyBytes?: number;
120
+ maxRequests?: number;
121
+ maxTotalBytes?: number;
122
+ maxResourceBytes?: number;
123
+ /** Concurrent fetches in flight; the guard's policy asks untrusted fan-out for a host limiter. */
124
+ maxConcurrent?: number;
125
+ perRequestTimeoutMs?: number;
126
+ /** Host classification port: diagnostics does not depend on the platform transport. */
127
+ isEgressRefused?: (error: unknown) => boolean;
128
+ /** Receives only bounded, credential-free responses from this page's own requests. */
129
+ onBlocked?: (required: {
130
+ url: string;
131
+ resourceType: string;
132
+ reason: AbortReason;
133
+ }) => void;
134
+ onResponse?: (required: {
135
+ url: string;
136
+ resourceType: string;
137
+ resource: FetchedResource;
138
+ }) => void;
139
+ }
140
+ /** Main-frame origin/refusal policy must not classify iframe or worker requests as page redirects. */
141
+ export declare function isMainFrameNavigation({ request }: {
142
+ request: RoutedRequest;
143
+ }, _options?: {}): boolean;
144
+ /**
145
+ * Builds the router for ONE capture (budgets and counters are per capture).
146
+ * @param required.httpClient - Guarded client built from `platform/http`'s `WEB_SCREENSHOT_EGRESS_POLICY`; never a raw transport.
147
+ * @param required.ownSiteFetch - Loopback fetch for `allowedOrigins` only.
148
+ * @param required.allowedOrigins - Exact origins (scheme://host:port) that bypass the public guard; empty for public pages.
149
+ * @param required.signal - Aborts every in-flight fetch when the capture ends or times out.
150
+ * @complexity O(1) bookkeeping per hop, at most {@link MAX_REDIRECT_HOPS} + 1 hops per request; fetches are bounded by `maxConcurrent` and the budgets.
151
+ */
152
+ export declare function createRequestRouter({ httpClient, ownSiteFetch, allowedOrigins, signal }: {
153
+ httpClient: HttpClientPort;
154
+ ownSiteFetch: OwnSiteFetch;
155
+ allowedOrigins: readonly string[];
156
+ signal: AbortSignal;
157
+ }, { maxRequests, maxTotalBytes, maxResourceBytes, maxConcurrent, perRequestTimeoutMs, preserveOwnSiteCookies, allowDataRequests, maxRequestBodyBytes, isEgressRefused, onResponse, onBlocked }?: RequestRouterOptions): RequestRouter;
158
+ /**
159
+ * The default {@link OwnSiteFetch}: the global `fetch`, redirects returned rather than followed (so
160
+ * the router re-decides the next hop), body read up to `maxBytes`. Overflow cancels the stream;
161
+ * fetch/read failures propagate, and the reader lock is always released.
162
+ * @complexity O(min(body, maxBytes)).
163
+ */
164
+ export declare const fetchOwnSiteResource: OwnSiteFetch;
165
+ export {};
166
+ //# sourceMappingURL=request-guard.d.ts.map
@@ -0,0 +1,239 @@
1
+ /** Redirect hops followed per request (and per page navigation), each one re-vetted. */
2
+ export const MAX_REDIRECT_HOPS = 5;
3
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
4
+ /** Streaming and media types that add nothing to a still picture and could hold a fetch open. */
5
+ const SKIPPED_RESOURCE_TYPES = new Set(["media", "eventsource", "websocket", "texttrack"]);
6
+ /**
7
+ * Pure routing decision for one request. Budget is not considered here (see the router).
8
+ * @complexity O(url length + allowedOrigins).
9
+ */
10
+ export function decideRequest({ url, method, resourceType, allowedOrigins }, { allowDataRequests = false } = {}) {
11
+ let parsed;
12
+ try {
13
+ parsed = new URL(url);
14
+ }
15
+ catch {
16
+ return { action: "abort", reason: "scheme" };
17
+ }
18
+ if (parsed.username || parsed.password)
19
+ return { action: "abort", reason: "scheme" };
20
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
21
+ return { action: "abort", reason: "scheme" };
22
+ const upper = method.toUpperCase();
23
+ const dataWrite = allowDataRequests && ["xhr", "fetch"].includes(resourceType) && ["POST", "PUT", "PATCH"].includes(upper);
24
+ if (upper !== "GET" && upper !== "HEAD" && !dataWrite)
25
+ return { action: "abort", reason: "method" };
26
+ if (SKIPPED_RESOURCE_TYPES.has(resourceType))
27
+ return { action: "abort", reason: "resource-type" };
28
+ return { action: "fetch", via: !dataWrite && allowedOrigins.includes(parsed.origin) ? "own-site" : "guarded", method: upper };
29
+ }
30
+ /** Request headers that must never leave this process, plus hop-by-hop ones the transport owns. */
31
+ const DROPPED_REQUEST_HEADERS = new Set(["cookie", "authorization", "proxy-authorization", "host", "connection", "content-length", "transfer-encoding", "upgrade"]);
32
+ /** Response headers that would lie about the (already decoded) body or try to persist state. */
33
+ const DROPPED_RESPONSE_HEADERS = new Set(["set-cookie", "set-cookie2", "content-encoding", "content-length", "transfer-encoding", "connection", "keep-alive", "alt-svc"]);
34
+ const OWN_SITE_RESPONSE_HEADERS = new Set([...DROPPED_RESPONSE_HEADERS].filter(name => name !== "set-cookie" && name !== "set-cookie2"));
35
+ function filterHeaders(headers, dropped) {
36
+ const kept = {};
37
+ for (const [name, value] of Object.entries(headers)) {
38
+ const lower = name.toLowerCase();
39
+ if (!lower.startsWith(":") && !dropped.has(lower))
40
+ kept[lower] = value;
41
+ }
42
+ return kept;
43
+ }
44
+ /** Main-frame origin/refusal policy must not classify iframe or worker requests as page redirects. */
45
+ export function isMainFrameNavigation({ request }, _options = {}) {
46
+ try {
47
+ return request.isNavigationRequest() && request.frame().parentFrame() === null;
48
+ }
49
+ catch {
50
+ // Requests without a frame (workers) are never the page's own navigation.
51
+ return false;
52
+ }
53
+ }
54
+ /**
55
+ * The absolute URL a redirect response points at, or `undefined` when it is not a redirect. An
56
+ * unparsable `Location` comes back raw, so the next hop's {@link decideRequest} aborts it.
57
+ */
58
+ function redirectTarget(resource, base) {
59
+ if (!REDIRECT_STATUSES.has(resource.status))
60
+ return undefined;
61
+ const location = Object.entries(resource.headers).find(([name]) => name.toLowerCase() === "location")?.[1];
62
+ if (!location)
63
+ return undefined;
64
+ try {
65
+ return new URL(location, base).href;
66
+ }
67
+ catch {
68
+ return location;
69
+ }
70
+ }
71
+ /** A counting semaphore: at most `limit` holders, FIFO waiters. */
72
+ function createSemaphore(limit) {
73
+ let active = 0;
74
+ const waiters = [];
75
+ const release = () => {
76
+ active -= 1;
77
+ waiters.shift()?.();
78
+ };
79
+ return {
80
+ async acquire() {
81
+ if (active >= limit)
82
+ await new Promise((resolve) => waiters.push(resolve));
83
+ active += 1;
84
+ return release;
85
+ },
86
+ };
87
+ }
88
+ /**
89
+ * Builds the router for ONE capture (budgets and counters are per capture).
90
+ * @param required.httpClient - Guarded client built from `platform/http`'s `WEB_SCREENSHOT_EGRESS_POLICY`; never a raw transport.
91
+ * @param required.ownSiteFetch - Loopback fetch for `allowedOrigins` only.
92
+ * @param required.allowedOrigins - Exact origins (scheme://host:port) that bypass the public guard; empty for public pages.
93
+ * @param required.signal - Aborts every in-flight fetch when the capture ends or times out.
94
+ * @complexity O(1) bookkeeping per hop, at most {@link MAX_REDIRECT_HOPS} + 1 hops per request; fetches are bounded by `maxConcurrent` and the budgets.
95
+ */
96
+ export function createRequestRouter({ httpClient, ownSiteFetch, allowedOrigins, signal }, { maxRequests = 300, maxTotalBytes = 60 * 1024 * 1024, maxResourceBytes = 15 * 1024 * 1024, maxConcurrent = 6, perRequestTimeoutMs = 15_000, preserveOwnSiteCookies = false, allowDataRequests = false, maxRequestBodyBytes = 64 * 1024, isEgressRefused = error => error instanceof Error && error.name === "EgressRefusedError", onResponse, onBlocked } = {}) {
97
+ const report = { fulfilled: 0, blocked: 0, navigationRefused: false, bytes: 0 };
98
+ const slots = createSemaphore(maxConcurrent);
99
+ let started = 0;
100
+ let navigationRedirect;
101
+ async function abort(route, reason, isNavigation) {
102
+ report.blocked += 1;
103
+ onBlocked?.({ url: route.request().url(), resourceType: route.request().resourceType(), reason });
104
+ if (reason === "refused" && isNavigation)
105
+ report.navigationRefused = true;
106
+ // The context may already be closing; a route that is gone has nothing left to abort.
107
+ await route.abort(reason === "failed" ? "failed" : "blockedbyclient").catch(() => { });
108
+ }
109
+ async function fetchResource(decision, url, headers, requestBody) {
110
+ if (decision.via === "own-site") {
111
+ return ownSiteFetch({ url, method: decision.method, headers }, { signal, maxBytes: maxResourceBytes });
112
+ }
113
+ const response = await httpClient.send({ request: { method: decision.method, url, headers, ...(requestBody === undefined ? {} : { body: requestBody }), signal, timeoutMs: perRequestTimeoutMs, maxResponseBytes: maxResourceBytes } });
114
+ const body = response.bodyBytes ? Buffer.from(response.bodyBytes) : Buffer.from(response.bodyText, "utf8");
115
+ return { status: response.status, headers: { ...response.headers, ...(response.setCookies?.length ? { "set-cookie": response.setCookies.join("\n") } : {}) }, body, truncated: response.bodyBytes ? response.bodyBytesTruncated === true : response.bodyTruncated === true };
116
+ }
117
+ /** One hop: budget, a concurrency slot, the fetch, and the byte accounting — or why it was refused. */
118
+ async function fetchHop(decision, url, headers, body) {
119
+ if (started >= maxRequests || report.bytes >= maxTotalBytes || signal.aborted)
120
+ return "budget";
121
+ started += 1;
122
+ const release = await slots.acquire();
123
+ if (signal.aborted) {
124
+ release();
125
+ return "budget";
126
+ }
127
+ let resource;
128
+ try {
129
+ resource = await fetchResource(decision, url, headers, body);
130
+ }
131
+ catch (error) {
132
+ return isEgressRefused(error) ? "refused" : "failed";
133
+ }
134
+ finally {
135
+ release();
136
+ }
137
+ if (resource.truncated)
138
+ return "budget";
139
+ report.bytes += resource.body.length;
140
+ return report.bytes > maxTotalBytes ? "budget" : resource;
141
+ }
142
+ return {
143
+ async handle(route) {
144
+ const request = route.request();
145
+ const isNavigation = isMainFrameNavigation({ request });
146
+ const headers = filterHeaders(request.headers(), DROPPED_REQUEST_HEADERS);
147
+ let url = request.url();
148
+ let method = request.method();
149
+ let body;
150
+ // Reject oversized writes whole; a clipped GraphQL payload would be a different request.
151
+ if (allowDataRequests && ["xhr", "fetch"].includes(request.resourceType()) && ["POST", "PUT", "PATCH"].includes(method.toUpperCase())) {
152
+ body = request.postData?.() ?? undefined;
153
+ if (body !== undefined && Buffer.byteLength(body, "utf8") > maxRequestBodyBytes)
154
+ return abort(route, "budget", isNavigation);
155
+ }
156
+ for (let hop = 0;; hop += 1) {
157
+ const decision = decideRequest({ url, method, resourceType: request.resourceType(), allowedOrigins }, { allowDataRequests });
158
+ if (decision.action === "abort")
159
+ return abort(route, decision.reason, isNavigation);
160
+ const ownCookie = preserveOwnSiteCookies && decision.via === "own-site" ? request.headers().cookie : undefined;
161
+ const resource = await fetchHop(decision, url, ownCookie ? { ...headers, cookie: ownCookie } : headers, body);
162
+ if (typeof resource === "string")
163
+ return abort(route, resource, isNavigation);
164
+ const next = redirectTarget(resource, url);
165
+ if (next === undefined) {
166
+ report.fulfilled += 1;
167
+ onResponse?.({ url, resourceType: request.resourceType(), resource });
168
+ await route.fulfill({ status: resource.status, headers: filterHeaders(resource.headers, preserveOwnSiteCookies
169
+ ? OWN_SITE_RESPONSE_HEADERS
170
+ : DROPPED_RESPONSE_HEADERS), body: resource.body }).catch(() => { });
171
+ return;
172
+ }
173
+ if (isNavigation) {
174
+ // Not a block: the capture navigates to `next` itself, so that hop is routed like this one.
175
+ // `aborted` (net::ERR_ABORTED) commits no error page; `blockedbyclient` would commit
176
+ // chrome-error://, which interrupts that next navigation (real Chromium, 2026-10-08).
177
+ navigationRedirect = next;
178
+ await route.abort("aborted").catch(() => { });
179
+ return;
180
+ }
181
+ if (hop >= MAX_REDIRECT_HOPS)
182
+ return abort(route, "failed", isNavigation);
183
+ // Match fetch redirect semantics without letting Chromium follow an unvetted hop.
184
+ if (resource.status === 303 || ([301, 302].includes(resource.status) && method.toUpperCase() === "POST")) {
185
+ method = "GET";
186
+ body = undefined;
187
+ delete headers["content-type"];
188
+ }
189
+ url = next;
190
+ }
191
+ },
192
+ report: () => ({ ...report }),
193
+ takeNavigationRedirect() {
194
+ const target = navigationRedirect;
195
+ navigationRedirect = undefined;
196
+ return target;
197
+ },
198
+ };
199
+ }
200
+ /**
201
+ * The default {@link OwnSiteFetch}: the global `fetch`, redirects returned rather than followed (so
202
+ * the router re-decides the next hop), body read up to `maxBytes`. Overflow cancels the stream;
203
+ * fetch/read failures propagate, and the reader lock is always released.
204
+ * @complexity O(min(body, maxBytes)).
205
+ */
206
+ export const fetchOwnSiteResource = async ({ url, method, headers }, { signal, maxBytes, fetch: fetchResource = globalThis.fetch }) => {
207
+ const response = await fetchResource(url, { method, headers, redirect: "manual", signal });
208
+ const responseHeaders = {};
209
+ response.headers.forEach((value, name) => { responseHeaders[name] = value; });
210
+ const cookies = response.headers.getSetCookie();
211
+ if (cookies.length)
212
+ responseHeaders["set-cookie"] = cookies.join("\n");
213
+ const chunks = [];
214
+ let size = 0;
215
+ let truncated = false;
216
+ if (response.body) {
217
+ const reader = response.body.getReader();
218
+ try {
219
+ for (;;) {
220
+ const { done, value } = await reader.read();
221
+ if (done)
222
+ break;
223
+ size += value.byteLength;
224
+ if (size > maxBytes) {
225
+ truncated = true;
226
+ break;
227
+ }
228
+ chunks.push(Buffer.from(value));
229
+ }
230
+ }
231
+ finally {
232
+ // Cleanup must not replace the original read error when the stream is already errored.
233
+ await reader.cancel().catch(() => { });
234
+ reader.releaseLock();
235
+ }
236
+ }
237
+ return { status: response.status, headers: responseHeaders, body: Buffer.concat(chunks), truncated };
238
+ };
239
+ //# sourceMappingURL=request-guard.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/diagnostics",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "Diagnostics-bundle tooling: JSON/text secret redaction, log-source collection, manifest building, and zip packaging for support exports.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -82,10 +82,10 @@
82
82
  "devDependencies": {
83
83
  "@vitest/coverage-v8": "^2.1.9",
84
84
  "jszip": "^3.10.1",
85
- "@jini-ai/core": "^0.4.2"
85
+ "@jini-ai/core": "^0.4.6"
86
86
  },
87
87
  "dependencies": {
88
- "@jini-ai/core": "^0.4.2"
88
+ "@jini-ai/core": "^0.4.6"
89
89
  },
90
90
  "peerDependencies": {
91
91
  "jszip": "^3.10.1"