@jini-ai/diagnostics 0.7.3-next.1 → 0.7.3-next.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +41 -0
  3. package/dist/browser-diagnostics.d.ts +43 -0
  4. package/dist/browser-diagnostics.js +92 -0
  5. package/dist/console-tee.d.ts +21 -6
  6. package/dist/console-tee.js +16 -4
  7. package/dist/domain-dns/index.d.ts +6 -14
  8. package/dist/domain-dns/index.js +4 -6
  9. package/dist/local-text.d.ts +4 -1
  10. package/dist/local-text.js +3 -2
  11. package/dist/observability/error-events.d.ts +32 -0
  12. package/dist/observability/error-events.js +32 -0
  13. package/dist/observability/fanout.js +23 -1
  14. package/dist/observability/hooks.js +1 -0
  15. package/dist/observability/index.d.ts +2 -1
  16. package/dist/observability/index.js +1 -0
  17. package/dist/observability/report-error.d.ts +9 -4
  18. package/dist/observability/report-error.js +7 -6
  19. package/dist/observability/telemetry-test.d.ts +1 -1
  20. package/dist/observability/tool-registrations.d.ts +21 -0
  21. package/dist/observability/tool-registrations.js +38 -0
  22. package/dist/observability/tracker-noop.d.ts +1 -1
  23. package/dist/observability/tracker-types.d.ts +2 -57
  24. package/dist/observability/tracker.d.ts +2 -1
  25. package/dist/observability/tracker.js +5 -1
  26. package/dist/redaction/repo-secret-scan.d.ts +48 -0
  27. package/dist/redaction/repo-secret-scan.js +77 -0
  28. package/dist/redaction/repo-secret-scan.node.d.ts +56 -0
  29. package/dist/redaction/repo-secret-scan.node.js +174 -0
  30. package/dist/redaction/secret-scan.d.ts +15 -0
  31. package/dist/redaction/secret-scan.js +18 -0
  32. package/dist/redaction/secrets-only.d.ts +1 -0
  33. package/dist/redaction/secrets-only.js +2 -0
  34. package/dist/redaction.d.ts +6 -0
  35. package/dist/redaction.js +9 -5
  36. package/dist/server-logs/agent-tools.d.ts +34 -0
  37. package/dist/server-logs/agent-tools.js +19 -0
  38. package/dist/server-logs/read-server-logs.d.ts +49 -0
  39. package/dist/server-logs/read-server-logs.js +90 -0
  40. package/dist/server-logs/tool-registrations.d.ts +25 -0
  41. package/dist/server-logs/tool-registrations.js +39 -0
  42. package/dist/tool-audit/repo.d.ts +107 -0
  43. package/dist/tool-audit/repo.js +117 -0
  44. package/dist/tool-audit/repo.memory.d.ts +31 -0
  45. package/dist/tool-audit/repo.memory.js +30 -0
  46. package/dist/tool-audit/repo.rows.d.ts +19 -0
  47. package/dist/tool-audit/repo.rows.js +2 -0
  48. package/dist/tool-audit/tool-gaps.repo.d.ts +22 -0
  49. package/dist/tool-audit/tool-gaps.repo.js +36 -0
  50. package/dist/web-evidence/agent-tools.d.ts +31 -0
  51. package/dist/web-evidence/agent-tools.js +61 -0
  52. package/dist/web-evidence/capture-budget.d.ts +3 -10
  53. package/dist/web-evidence/live-url.d.ts +86 -0
  54. package/dist/web-evidence/live-url.js +191 -0
  55. package/dist/web-evidence/page-performance-script.js +30 -32
  56. package/dist/web-evidence/playwright-browser.d.ts +2 -0
  57. package/dist/web-evidence/playwright-page-capture.d.ts +129 -0
  58. package/dist/web-evidence/playwright-page-capture.js +226 -0
  59. package/dist/web-evidence/public-page.d.ts +2 -1
  60. package/dist/web-evidence/published-page.d.ts +180 -0
  61. package/dist/web-evidence/published-page.js +172 -0
  62. package/dist/web-evidence/request-guard.d.ts +1 -31
  63. package/dist/web-evidence/site-path-policy.d.ts +20 -0
  64. package/dist/web-evidence/site-path-policy.js +54 -0
  65. package/dist/web-evidence/web-screenshot/agent-tools.d.ts +28 -0
  66. package/dist/web-evidence/web-screenshot/agent-tools.js +34 -0
  67. package/dist/web-evidence/web-screenshot/tool-registrations.d.ts +79 -0
  68. package/dist/web-evidence/web-screenshot/tool-registrations.js +47 -0
  69. package/package.json +115 -7
@@ -0,0 +1,226 @@
1
+ import { describeErrorForLog } from "@jini-ai/core/model-facing-tool-errors";
2
+ import { observed } from "@jini-ai/core/errors/idioms";
3
+ import { captureBudget } from "./capture-budget.js";
4
+ import { REAL_CAPTURE_CLOCK } from "./capture-clock.js";
5
+ import { renderPage, PageWorkTimeout, PUBLIC_RENDER_LAUNCH_OPTIONS, createRenderBrowserPool } from "./playwright-browser.js";
6
+ import { createRequestRouter, fetchOwnSiteResource } from "./playwright-browser.js";
7
+ export const IDLE_CLOSE_MS = 60_000;
8
+ /**
9
+ * Scrolls a full-page capture through its height (capped at `cap` px) one viewport at a time, then
10
+ * back to the top. Scroll-reveal sections and lazy images only appear once scrolled into view; a
11
+ * full-page screenshot never scrolls, so without this everything below the fold of such a page
12
+ * (luviraconsulting.com, 2026-10-08) is captured as blank sections. `behavior: "instant"` because a
13
+ * page with CSS `scroll-behavior: smooth` otherwise animates each jump and never gets far. A string,
14
+ * so no page-side function crosses the boundary; ~10 steps of 150 ms at the 8000 px cap.
15
+ */
16
+ const scrollThroughExpression = ({ cap }, _optional = {}) => `(async () => { const end = Math.min(document.documentElement.scrollHeight, ${cap}); ` +
17
+ `for (let y = 0; y < end; y += window.innerHeight) { window.scrollTo({ top: y, behavior: "instant" }); await new Promise((r) => setTimeout(r, 150)); } ` +
18
+ `window.scrollTo({ top: 0, behavior: "instant" }); await new Promise((r) => setTimeout(r, 300)); })()`;
19
+ function playwrightLauncherFrom({ importPlaywrightChromium }, _optional = {}) {
20
+ return async () => {
21
+ const chromium = await importPlaywrightChromium();
22
+ return { launch: (options) => chromium.launch({ ...options }) };
23
+ };
24
+ }
25
+ function clampHeight({ raw, fallback }, _optional = {}) {
26
+ return typeof raw === "number" && Number.isFinite(raw) && raw > 0 ? Math.ceil(raw) : fallback;
27
+ }
28
+ /**
29
+ * @param required.httpClient - Guarded client built from `WEB_SCREENSHOT_EGRESS_POLICY`.
30
+ * @complexity O(1) per capture beyond the page load and screenshot; at most one browser per adapter.
31
+ */
32
+ export function createPlaywrightPageCapture({ httpClient, limits, createCaptureError, isCaptureTimeout, importPlaywrightChromium }, { loadLauncher = playwrightLauncherFrom({ importPlaywrightChromium }), ownSiteFetch = fetchOwnSiteResource, routerOptions = {}, allowUnsandboxed = false, clock = REAL_CAPTURE_CLOCK, idleCloseMs = IDLE_CLOSE_MS, browserPool } = {}) {
33
+ const errors = { createCaptureError, isCaptureTimeout };
34
+ const browser = browserPool ?? createRenderBrowserPool({ launch: async () => {
35
+ const launched = await (await loadLauncher()).launch({ headless: true, chromiumSandbox: !allowUnsandboxed, args: [...PUBLIC_RENDER_LAUNCH_OPTIONS.args] });
36
+ return { newContext: options => launched.newContext(options), close: () => launched.close() };
37
+ } }, { idleCloseMs });
38
+ const shoot = createCaptureShooter({ browser, httpClient, ownSiteFetch, routerOptions, clock, errors });
39
+ return {
40
+ async capture(request, { signal } = {}) {
41
+ const plan = captureBudget(budgetRequestOf({ request }), limits);
42
+ const progress = { loaded: false };
43
+ const controller = new AbortController();
44
+ const onAbort = () => controller.abort();
45
+ signal?.addEventListener("abort", onAbort, { once: true });
46
+ if (signal?.aborted)
47
+ controller.abort();
48
+ let timer;
49
+ const deadline = new Promise((_, reject) => {
50
+ timer = clock.setTimeout(() => {
51
+ controller.abort();
52
+ reject(timeoutError({ plan, progress, errors, hardStop: true }));
53
+ }, plan.totalMs);
54
+ });
55
+ try {
56
+ const work = shoot({ request, plan, progress }, controller.signal);
57
+ // A capture that lost the race still settles later; its outcome is already reported.
58
+ observed({ promise: work });
59
+ return await Promise.race([work, deadline]);
60
+ }
61
+ catch (error) {
62
+ // A caller's cancel is not a capture failure: its own reason reaches the caller, never a "navigation failed".
63
+ if (signal?.aborted)
64
+ throw signal.reason;
65
+ dropBrowserAfterTimeout({ browser, error, owned: !browserPool, errors });
66
+ throw error;
67
+ }
68
+ finally {
69
+ clock.clearTimeout(timer);
70
+ signal?.removeEventListener("abort", onAbort);
71
+ }
72
+ },
73
+ close() {
74
+ return browser.close();
75
+ },
76
+ };
77
+ }
78
+ /** A page that hung the renderer can also hang its context's close: drop the whole browser (never a pool its host shares). */
79
+ function dropBrowserAfterTimeout({ browser, error, owned, errors }, _optional = {}) {
80
+ if (!owned || !errors.isCaptureTimeout({ error }))
81
+ return;
82
+ void browser.close().catch((closeError) => console.error("[screenshot] Could not close the timed-out browser", describeErrorForLog({ err: closeError })));
83
+ }
84
+ /** The capture's timeout. Before the page loaded it is the work deadline that ran out (a render that never committed
85
+ * navigation fails there); once loaded, or when the hard stop of the whole capture fires, it is the total. */
86
+ function timeoutError({ plan, progress, errors, hardStop = false }, _optional = {}) {
87
+ const limitMs = progress.loaded || hardStop ? plan.totalMs : plan.softDeadlineMs;
88
+ return errors.createCaptureError({ kind: "timeout", message: `exceeded ${limitMs}ms`, limitMs, loaded: progress.loaded });
89
+ }
90
+ /** What the request asks for, in the units `captureBudget` reads. A selector wait adds nothing: it ends when the element shows. */
91
+ function budgetRequestOf({ request }, _optional = {}) {
92
+ return { settleMs: request.settleMs, fullPage: request.fullPage, ...(typeof request.waitFor === "number" ? { waitForSeconds: request.waitFor } : {}) };
93
+ }
94
+ /**
95
+ * The work `renderPage` hands over once the page has loaded: scroll (full page), measure, shoot, read the title.
96
+ * `session.phaseTimedOut` is set when ordinary work hit its deadline on a page that had already loaded: that page
97
+ * is shot as it is, inside what is left of the total. The scroll is ordinary work too, so it gets the same treatment.
98
+ * @complexity O(1) beyond the page work.
99
+ */
100
+ async function consumeCapture({ session: { page, response, finalUrl, budget, phaseTimedOut }, request, router, plan, clock }, _optional = {}) {
101
+ const { viewport } = request;
102
+ const scrollCutShort = request.fullPage && await scrollWithinWorkTime({ page, budget, cap: request.maxPageHeightPx, plan, clock });
103
+ const pageHeight = request.fullPage ? await measuredHeight({ page, budget, fallback: viewport.height }) : viewport.height;
104
+ const { capturedHeight, clip } = frameGeometry({ request, pageHeight });
105
+ if (!page.screenshot)
106
+ throw new Error("Browser cannot take screenshots");
107
+ // NEEDS-JINI: `RenderPage.screenshot` narrows `animations` to "disabled"; the object is
108
+ // Playwright's Page, whose documented option also takes "allow" (the fallback below).
109
+ const { png, note } = await shootFrame({ page: page, budget, fullPage: request.fullPage, clip, plan, settleCutShort: phaseTimedOut !== undefined || scrollCutShort });
110
+ const title = (await budget.run({ work: () => page.title() })).slice(0, 300);
111
+ return { png, finalUrl, status: response?.status() ?? null, title, pageHeight, capturedHeight, blockedRequests: router.report().blocked, ...(note ? { note } : {}) };
112
+ }
113
+ /** What a capture keeps of the page: the height (a full page is capped) and, for a full page, the clip that spans it. */
114
+ function frameGeometry({ request, pageHeight }, _optional = {}) {
115
+ if (!request.fullPage)
116
+ return { capturedHeight: Math.min(pageHeight, request.viewport.height), clip: {} };
117
+ const capturedHeight = Math.min(pageHeight, request.maxPageHeightPx);
118
+ return { capturedHeight, clip: { clip: { x: 0, y: 0, width: request.viewport.width, height: capturedHeight } } };
119
+ }
120
+ /** The document's full height in CSS px, or `fallback` when the page reports none; within the page budget. */
121
+ async function measuredHeight({ page, budget, fallback }, _optional = {}) {
122
+ const raw = await budget.run({ work: () => page.evaluate("Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0)") });
123
+ return clampHeight({ raw, fallback });
124
+ }
125
+ /**
126
+ * Scrolls a full page, but only until the work deadline (the total minus the reserve): a page that is still
127
+ * scrolling by then is shot as it is, like one still settling, instead of failing with nothing.
128
+ * The scroll that lost the race is abandoned; the race already handled its late rejection (the budget's own timeout).
129
+ * @returns true when the work deadline cut the scroll short.
130
+ * @throws PageWorkTimeout when the total budget ends first; a scroll script that fails on its own is best-effort.
131
+ * @complexity O(1) beyond the page work.
132
+ */
133
+ async function scrollWithinWorkTime({ page, budget, cap, plan, clock }, _optional = {}) {
134
+ const workLeftMs = budget.remainingMs() - plan.reserveMs;
135
+ if (workLeftMs <= 0)
136
+ return true;
137
+ let timer;
138
+ const cutShort = new Promise(resolve => { timer = clock.setTimeout(() => resolve(true), workLeftMs); });
139
+ const scrolled = budget.run({ work: () => page.evaluate(scrollThroughExpression({ cap })) })
140
+ .then(() => false, (error) => { if (error instanceof PageWorkTimeout)
141
+ throw error; return false; });
142
+ try {
143
+ return await Promise.race([scrolled, cutShort]);
144
+ }
145
+ finally {
146
+ clock.clearTimeout(timer);
147
+ }
148
+ }
149
+ /**
150
+ * A stable frame first (`animations: "disabled"` waits for finite animations to end); if Playwright's
151
+ * own timeout fires on that, the page was still animating (WebGL heroes, endless transitions, e.g.
152
+ * a provider dashboard), so the frame on screen is captured as it is, with a note, instead of failing the call.
153
+ * Only Playwright's `TimeoutError` falls back: a closed page or a budget timeout still fails.
154
+ * The stable attempt keeps the plan's reserve for that second shot, taken from what is left before the hard stop.
155
+ * A page whose settling was already cut short (`settleCutShort`) has no time for a stable attempt: it goes straight to the current frame.
156
+ * @complexity O(1) beyond the screenshots.
157
+ */
158
+ async function shootFrame({ page, budget, fullPage, clip, plan, settleCutShort }) {
159
+ if (settleCutShort)
160
+ return { png: await currentFrame({ page, budget, fullPage, clip, plan }), note: `page loaded but did not settle within ${plan.softDeadlineMs / 1000} s; captured the current frame (content may still be loading).` };
161
+ // Playwright treats timeout 0 as "no timeout", so the stable attempt always gets at least 1 ms.
162
+ const stableTimeout = Math.max(1, budget.remainingMs() - plan.reserveMs);
163
+ try {
164
+ return { png: await budget.run({ work: () => page.screenshot({ type: "png", fullPage, timeout: stableTimeout, animations: "disabled", ...clip }) }) };
165
+ }
166
+ catch (error) {
167
+ if (error.name !== "TimeoutError")
168
+ throw error;
169
+ }
170
+ return { png: await currentFrame({ page, budget, fullPage, clip, plan }), note: `page was still animating near the ${plan.totalMs / 1000} s deadline; captured the current frame (it may show a mid-animation state).` };
171
+ }
172
+ /** The frame on screen right now, within what is left of the total; Playwright's own timeout there is the capture's timeout. */
173
+ function currentFrame({ page, budget, fullPage, clip, plan }) {
174
+ return budget.run({ work: () => page.screenshot({ type: "png", fullPage, timeout: Math.max(1, budget.remainingMs()), animations: "allow", ...clip }) })
175
+ .catch((error) => { throw error.name === "TimeoutError" ? new PageWorkTimeout({ timeoutMs: plan.totalMs }) : error; });
176
+ }
177
+ /** Chromium's `net::ERR_*` code only — never a raw message that could echo an internal address. */
178
+ function navigationErrorCode({ error }, _optional = {}) {
179
+ if (error instanceof Error && error.message === "too many redirects")
180
+ return error.message;
181
+ const code = /net::(ERR_[A-Z_]+)/.exec(error instanceof Error ? error.message : "")?.[1];
182
+ return code ?? "navigation failed";
183
+ }
184
+ function createCaptureShooter({ browser, httpClient, ownSiteFetch, routerOptions, clock, errors }) {
185
+ return async function shoot({ request, plan, progress }, signal) {
186
+ let lease;
187
+ try {
188
+ lease = await browser.acquire({}, { signal });
189
+ }
190
+ catch (error) {
191
+ throw errors.createCaptureError({ kind: "unavailable", message: error.message });
192
+ }
193
+ const { viewport } = request;
194
+ // Product HTTP signature adapter; Jini owns pinned request routing and redirect/budget rules.
195
+ // Security rationale and why Chromium never receives redirects live in Jini's request-guard.ts.
196
+ // Adapt the host signature without opening any raw public transport.
197
+ const routerClient = { send: ({ request: hop }) => httpClient.send(hop) };
198
+ const router = createRequestRouter({ httpClient: routerClient, ownSiteFetch, allowedOrigins: request.allowedOrigins, signal }, { ...routerOptions, allowDataRequests: false });
199
+ const contextOptions = {
200
+ viewport: { width: viewport.width, height: viewport.height }, deviceScaleFactor: viewport.deviceScaleFactor,
201
+ isMobile: viewport.isMobile, hasTouch: viewport.isMobile, serviceWorkers: "block", acceptDownloads: false,
202
+ ignoreHTTPSErrors: false, javaScriptEnabled: true,
203
+ };
204
+ try {
205
+ return await renderPage({
206
+ browser: { newContext: () => lease.browser.newContext({ ...contextOptions }), close: () => lease.browser.close() },
207
+ url: request.url,
208
+ consume: session => { progress.loaded = true; return consumeCapture({ session, request, router, plan, clock }); },
209
+ }, { originPolicy: "public", router, signal, timeoutMs: plan.totalMs, softDeadlineMs: plan.softDeadlineMs, onSoftDeadline: "consume-current", clock,
210
+ waitFor: request.waitFor ?? request.settleMs / 1000,
211
+ dismissCookieBanners: request.dismissCookieBanners === true, loadWaitMs: 5_000,
212
+ });
213
+ }
214
+ catch (error) {
215
+ if (error instanceof PageWorkTimeout)
216
+ throw timeoutError({ plan, progress, errors });
217
+ if (router.report().navigationRefused)
218
+ throw errors.createCaptureError({ kind: "refused", message: "refused by the egress guard" });
219
+ throw errors.createCaptureError({ kind: "failed", message: navigationErrorCode({ error }) });
220
+ }
221
+ finally {
222
+ lease.release();
223
+ }
224
+ };
225
+ }
226
+ //# sourceMappingURL=playwright-page-capture.js.map
@@ -1,5 +1,6 @@
1
1
  import type { HttpClientPort } from "@jini-ai/core/primitives";
2
- import { type FetchedResource, type AbortReason } from "./request-guard.js";
2
+ import { type FetchedResource } from "./request-guard.js";
3
+ import type { AbortReason } from "@jini-ai/core/contracts/site/web-evidence-playwright";
3
4
  import { type PlaywrightAdapterOptions } from "./playwright-runtime.js";
4
5
  import type { RenderBrowserPool } from "./lazy-browser.js";
5
6
  export interface CapturedJsonResponse {
@@ -0,0 +1,180 @@
1
+ import { type RequestListener, type Server } from "node:http";
2
+ import { type ObservabilityPort } from "@jini-ai/core/contracts/observability";
3
+ import { type CookieShape } from "./cookie-shapes.js";
4
+ import { type PageBodyOptions, type ShapedPageBody } from "./page-body.js";
5
+ /**
6
+ * @file `fetchPublishedPage()` — renders ONE route of this site's own public surface and returns
7
+ * what a visitor would actually receive: status, headers, cookie shapes and (bounded) body.
8
+ *
9
+ * Why this exists as a sibling of `site-profile.ts` rather than a bigger snapshot (2026-08-26
10
+ * swarm-consensus, "config truth vs. render truth", agreed 5/5): a configuration snapshot can
11
+ * truthfully report "cookie-consent widget: installed, enabled" while the published page renders
12
+ * nothing of the sort. This codebase has three render paths that do not agree, and configuration is
13
+ * not one of them. Anything that must know what is LIVE has to fetch the live thing.
14
+ *
15
+ * ---------------------------------------------------------------------------
16
+ * This is an SSRF-shaped surface. Here is why it structurally is not one.
17
+ * ---------------------------------------------------------------------------
18
+ *
19
+ * The tool takes a **path**, never a URL. There is no caller-supplied host, scheme, port or
20
+ * credential anywhere in this module, so there is no allowlist to get wrong and no redirect hop to
21
+ * re-validate against a denylist of private ranges.
22
+ *
23
+ * The origin is one this process CREATES for the duration of a single call: `createSiteApp()`'s own
24
+ * Express app on an ephemeral `127.0.0.1` port, exactly the way the host's static site exporter already
25
+ * renders the site for a static export. Nothing in the input can steer that origin. Even a caller
26
+ * that smuggles an absolute URL past the string checks would fail the explicit
27
+ * `url.origin === base.origin` assertion in `resolveSameOriginPath` (`@jini-ai/diagnostics/web-evidence`), which compares against
28
+ * the origin this module minted rather than against a pattern.
29
+ *
30
+ * On top of that, the path itself is validated allowlist-style before it is used
31
+ * (`resolveSitePath`, which binds that guard to this site's pathname policy): must be root-relative, no protocol-relative `//` prefix, no
32
+ * backslashes, no control characters (CR/LF request splitting), no `..` segments after a single
33
+ * percent-decode, and not under `/api/` — see that function's own doc for why each one is there.
34
+ *
35
+ * `redirect: "manual"` is deliberate: a 30x is EVIDENCE (a compliance consumer wants to know the
36
+ * privacy-policy URL redirects), and following it automatically would be the one place a
37
+ * server-controlled `Location` could walk this fetch off-origin.
38
+ *
39
+ * ---------------------------------------------------------------------------
40
+ * What is and is not returned
41
+ * ---------------------------------------------------------------------------
42
+ * - **All response headers except `set-cookie`.** An allowlist would defeat the point: "does this
43
+ * site emit an unexpected header" is exactly the kind of question this tool exists to answer.
44
+ * These are headers this site's own code emits; none of them is a stored credential.
45
+ * - **`set-cookie` is projected to name + attributes, never a value** (`toCookieShapes` in `@jini-ai/diagnostics/web-evidence`).
46
+ * For the compliance case the cookie NAME and its `Secure`/`HttpOnly`/`SameSite`/`Max-Age`
47
+ * attributes are the whole signal; the value is the only part that could carry a session token.
48
+ * - **The body, capped** at {@link DEFAULT_MAX_BODY_BYTES} with an explicit `truncated` flag. The
49
+ * read stops at the cap rather than buffering the whole response and slicing afterwards, so a
50
+ * pathologically large route cannot be turned into a memory-exhaustion lever.
51
+ */
52
+ /** Wall clock for one render+fetch, including booting the ephemeral app. */
53
+ export declare const DEFAULT_FETCH_TIMEOUT_MS = 15000;
54
+ export interface PublishedPageMetadata {
55
+ /** The canonical path actually requested, after normalization — not the raw caller string. */
56
+ path: string;
57
+ status: number;
58
+ /** `true` for 2xx only. A 30x/404 is a successful OBSERVATION, so the call does not throw. */
59
+ ok: boolean;
60
+ /** Response headers, lowercased, `set-cookie` excluded (see {@link cookies}). */
61
+ headers: Record<string, string>;
62
+ /** `Set-Cookie` headers with their values stripped — see this file's header. */
63
+ cookies: CookieShape[];
64
+ /** Bytes actually read into {@link body} (not `Content-Length`, which may disagree). */
65
+ bodyBytes: number;
66
+ /** `true` when the cap stopped the read before the response ended. */
67
+ truncated: boolean;
68
+ }
69
+ export type PublishedPageResult = Omit<PublishedPageMetadata, "bodyBytes" | "truncated"> & ShapedPageBody;
70
+ export interface FetchPublishedPageDeps {
71
+ /**
72
+ * The SAME site-app factory the static exporter renders through (`RouteDeps.createSiteApp`).
73
+ *
74
+ * Takes the optional render override (`{ themeId }`, 2026-10-08: `web_screenshot_page` seeing a
75
+ * theme copy without activating it). It used to be handed the deps bag itself, for a historical
76
+ * `(routeDeps: RouteDeps) => Express` shape; both composition roots have long been nullary-closed
77
+ * over their deps, so nothing reads that argument any more.
78
+ *
79
+ * Typed as Node's `RequestListener` rather than Express's `Express` because that is what this
80
+ * module actually consumes — the sole use is `createServer(deps.createSiteApp(...))`, and
81
+ * `http.createServer` takes a request listener. Naming `Express` here made the feature import a
82
+ * web framework to describe a two-argument callback, which is the `features/` boundary violation
83
+ * `src/features/__tests__/features-no-server-imports.boundary.test.ts` fails on. A real Express
84
+ * app still satisfies this: `@types/express-serve-static-core`'s `Application` declares an
85
+ * explicit `(req: http.IncomingMessage, res: http.ServerResponse)` call signature, which is
86
+ * exactly why `createServer(app)` type-checked before this change and still does.
87
+ */
88
+ createSiteApp(optional?: {
89
+ themeId?: string;
90
+ consentAudit?: true;
91
+ }): RequestListener;
92
+ /** Native server factory; injected fakes can exercise rendering without opening a socket. */
93
+ readonly createServer?: (listener: RequestListener) => Server;
94
+ /** HTTP transport; omitted, uses the global fetch read at call time. */
95
+ readonly fetch?: typeof globalThis.fetch;
96
+ /** Traces the loopback render as one outbound span (method, host/port, status — never the path).
97
+ * `RouteDeps.observability` in production; omitted, the render is untraced. */
98
+ readonly observability?: ObservabilityPort;
99
+ /**
100
+ * Wraps the transport so the loopback render is one outbound span. The host binds
101
+ * `trackFetch` from `@jini-ai/diagnostics/observability`; it is injected rather than imported so
102
+ * this evidence module stays out of the observability domain. Called once per request with the
103
+ * per-call `fetch` and `observability` (the no-op port when {@link observability} is omitted).
104
+ */
105
+ readonly trackFetch: PublishedPageFetchTracker;
106
+ /**
107
+ * The host's reserved first path segments (case-folded, e.g. `admin`, `api`) that
108
+ * {@link resolveSitePath} refuses. Injected so the host stays the one owner of its URL-space policy.
109
+ */
110
+ readonly reservedSegments: ReadonlySet<string>;
111
+ }
112
+ /** The shape of the observability subpath's `trackFetch`, as this module consumes it. */
113
+ export type PublishedPageFetchTracker = (required: {
114
+ fetch: typeof globalThis.fetch;
115
+ observability: ObservabilityPort;
116
+ }) => typeof globalThis.fetch;
117
+ export interface FetchPublishedPageOptions extends PageBodyOptions {
118
+ /** Body bytes to keep, clamped to `[1, MAX_MAX_BODY_BYTES]`. */
119
+ maxBytes?: number;
120
+ /** Wall clock for the whole call. */
121
+ timeoutMs?: number;
122
+ }
123
+ /** This site's own app, listening on a per-call loopback origin until `close` is awaited. */
124
+ export interface LoopbackSiteServer {
125
+ /** e.g. `http://127.0.0.1:53142` — fixed host, ephemeral port, no trailing slash. */
126
+ readonly origin: string;
127
+ close(required?: {}, optional?: {}): Promise<void>;
128
+ }
129
+ /**
130
+ * Boots the site's real app on an ephemeral `127.0.0.1` port. Shared by `fetch_published_page` and
131
+ * `web_screenshot_page`'s own-site mode, so both observe the one render path the static exporter uses.
132
+ * The caller owns the lifetime: `close()` in a `finally` (see {@link fetchPublishedPage} for why a
133
+ * per-call server rather than a long-lived one).
134
+ * @param required.deps - Supplies `createSiteApp` and an optional `createServer`.
135
+ * @param optional.themeId - Render this site through that installed theme instead of the active one
136
+ * (`createSiteApp({ themeId })`); the caller checks it exists. Never reachable from a visitor: it is
137
+ * an option of this one throwaway app, not anything a request carries.
138
+ * @param optional.consentAudit - Build the app without the cookie consent layer, so a screenshot shows
139
+ * the page rather than the banner over it. Same reach as `themeId`: this throwaway app only.
140
+ * @complexity O(1) beyond one app construction.
141
+ */
142
+ export declare function openLoopbackSiteServer({ deps }: {
143
+ deps: Pick<FetchPublishedPageDeps, "createSiteApp" | "createServer">;
144
+ }, { themeId, consentAudit }?: {
145
+ themeId?: string;
146
+ consentAudit?: true;
147
+ }): Promise<LoopbackSiteServer>;
148
+ /**
149
+ * Fetches one route of this site's own published surface and reports exactly what came back.
150
+ *
151
+ * Boots the site's real Express app on an ephemeral loopback port for the duration of ONE call,
152
+ * requests the validated path, and tears the server down in a `finally` — the same lifecycle
153
+ * the host's static site exporter uses to render a static export, so this observes the real render path
154
+ * rather than a second, agreeing-today copy of it.
155
+ *
156
+ * A per-call server rather than a memoized one is deliberate: a long-lived listening socket in the
157
+ * agent daemon would be a resource with no owner, and the cost here (route registration plus a
158
+ * loopback round trip) is nothing against the LLM turn that requested it.
159
+ *
160
+ * @param deps - Supplies `createSiteApp` (see {@link FetchPublishedPageDeps} for why the signature
161
+ * is written the way it is).
162
+ * @param input.path - A root-relative path on this site, e.g. `/` or `/blog/hello?page=2`.
163
+ * @param options.maxBytes - Body bytes to keep, clamped to `[1, MAX_MAX_BODY_BYTES]`.
164
+ * @param options.timeoutMs - Wall clock for the whole call, default {@link DEFAULT_FETCH_TIMEOUT_MS}.
165
+ * @returns A {@link PublishedPageResult}. A 404 or 30x is a RESULT, not an error — the caller
166
+ * asked what is live, and "nothing is there" is a true answer.
167
+ * @throws {SameOriginPathError} When `path` fails {@link resolveSitePath}.
168
+ * @throws {Error} Named `PublishedPageTimeoutError` when the render exceeds `timeoutMs`.
169
+ * @complexity O(min(B, maxBytes)) in the rendered response size, plus one Express app construction.
170
+ * @example
171
+ * const live = await fetchPublishedPage({ deps: routeDeps, input: { path: "/privacy" } }, { maxBytes: 50_000 });
172
+ * if (live.status === 404) console.log("no privacy policy is published");
173
+ */
174
+ export declare function fetchPublishedPage({ deps, input }: {
175
+ deps: FetchPublishedPageDeps;
176
+ input: {
177
+ path: string;
178
+ };
179
+ }, options?: FetchPublishedPageOptions): Promise<PublishedPageResult>;
180
+ //# sourceMappingURL=published-page.d.ts.map
@@ -0,0 +1,172 @@
1
+ import { createServer } from "node:http";
2
+ import { once } from "node:events";
3
+ import { createNoopObservabilityPort } from "@jini-ai/core/contracts/observability";
4
+ import { readBoundedBody } from "./bounded-body.js";
5
+ import { toCookieShapes } from "./cookie-shapes.js";
6
+ import { DEFAULT_MAX_BODY_BYTES, MAX_MAX_BODY_BYTES, shapePageBody } from "./page-body.js";
7
+ import { resolveSitePath } from "./site-path-policy.js";
8
+ /**
9
+ * @file `fetchPublishedPage()` — renders ONE route of this site's own public surface and returns
10
+ * what a visitor would actually receive: status, headers, cookie shapes and (bounded) body.
11
+ *
12
+ * Why this exists as a sibling of `site-profile.ts` rather than a bigger snapshot (2026-08-26
13
+ * swarm-consensus, "config truth vs. render truth", agreed 5/5): a configuration snapshot can
14
+ * truthfully report "cookie-consent widget: installed, enabled" while the published page renders
15
+ * nothing of the sort. This codebase has three render paths that do not agree, and configuration is
16
+ * not one of them. Anything that must know what is LIVE has to fetch the live thing.
17
+ *
18
+ * ---------------------------------------------------------------------------
19
+ * This is an SSRF-shaped surface. Here is why it structurally is not one.
20
+ * ---------------------------------------------------------------------------
21
+ *
22
+ * The tool takes a **path**, never a URL. There is no caller-supplied host, scheme, port or
23
+ * credential anywhere in this module, so there is no allowlist to get wrong and no redirect hop to
24
+ * re-validate against a denylist of private ranges.
25
+ *
26
+ * The origin is one this process CREATES for the duration of a single call: `createSiteApp()`'s own
27
+ * Express app on an ephemeral `127.0.0.1` port, exactly the way the host's static site exporter already
28
+ * renders the site for a static export. Nothing in the input can steer that origin. Even a caller
29
+ * that smuggles an absolute URL past the string checks would fail the explicit
30
+ * `url.origin === base.origin` assertion in `resolveSameOriginPath` (`@jini-ai/diagnostics/web-evidence`), which compares against
31
+ * the origin this module minted rather than against a pattern.
32
+ *
33
+ * On top of that, the path itself is validated allowlist-style before it is used
34
+ * (`resolveSitePath`, which binds that guard to this site's pathname policy): must be root-relative, no protocol-relative `//` prefix, no
35
+ * backslashes, no control characters (CR/LF request splitting), no `..` segments after a single
36
+ * percent-decode, and not under `/api/` — see that function's own doc for why each one is there.
37
+ *
38
+ * `redirect: "manual"` is deliberate: a 30x is EVIDENCE (a compliance consumer wants to know the
39
+ * privacy-policy URL redirects), and following it automatically would be the one place a
40
+ * server-controlled `Location` could walk this fetch off-origin.
41
+ *
42
+ * ---------------------------------------------------------------------------
43
+ * What is and is not returned
44
+ * ---------------------------------------------------------------------------
45
+ * - **All response headers except `set-cookie`.** An allowlist would defeat the point: "does this
46
+ * site emit an unexpected header" is exactly the kind of question this tool exists to answer.
47
+ * These are headers this site's own code emits; none of them is a stored credential.
48
+ * - **`set-cookie` is projected to name + attributes, never a value** (`toCookieShapes` in `@jini-ai/diagnostics/web-evidence`).
49
+ * For the compliance case the cookie NAME and its `Secure`/`HttpOnly`/`SameSite`/`Max-Age`
50
+ * attributes are the whole signal; the value is the only part that could carry a session token.
51
+ * - **The body, capped** at {@link DEFAULT_MAX_BODY_BYTES} with an explicit `truncated` flag. The
52
+ * read stops at the cap rather than buffering the whole response and slicing afterwards, so a
53
+ * pathologically large route cannot be turned into a memory-exhaustion lever.
54
+ */
55
+ /** Wall clock for one render+fetch, including booting the ephemeral app. */
56
+ export const DEFAULT_FETCH_TIMEOUT_MS = 15_000;
57
+ /** The origin this module mints for every call. Fixed loopback host; only the port varies. */
58
+ const LOOPBACK_HOST = "http://127.0.0.1";
59
+ const UNTRACED = createNoopObservabilityPort({});
60
+ /** Clamps `maxBytes` into `[1, MAX_MAX_BODY_BYTES]`, defaulting when absent or nonsensical. */
61
+ function resolveMaxBytes({ requested }, _optional = {}) {
62
+ if (requested === undefined || !Number.isInteger(requested) || requested < 1)
63
+ return DEFAULT_MAX_BODY_BYTES;
64
+ return Math.min(requested, MAX_MAX_BODY_BYTES);
65
+ }
66
+ /**
67
+ * Boots the site's real app on an ephemeral `127.0.0.1` port. Shared by `fetch_published_page` and
68
+ * `web_screenshot_page`'s own-site mode, so both observe the one render path the static exporter uses.
69
+ * The caller owns the lifetime: `close()` in a `finally` (see {@link fetchPublishedPage} for why a
70
+ * per-call server rather than a long-lived one).
71
+ * @param required.deps - Supplies `createSiteApp` and an optional `createServer`.
72
+ * @param optional.themeId - Render this site through that installed theme instead of the active one
73
+ * (`createSiteApp({ themeId })`); the caller checks it exists. Never reachable from a visitor: it is
74
+ * an option of this one throwaway app, not anything a request carries.
75
+ * @param optional.consentAudit - Build the app without the cookie consent layer, so a screenshot shows
76
+ * the page rather than the banner over it. Same reach as `themeId`: this throwaway app only.
77
+ * @complexity O(1) beyond one app construction.
78
+ */
79
+ export async function openLoopbackSiteServer({ deps }, { themeId, consentAudit } = {}) {
80
+ const server = (deps.createServer ?? createServer)(deps.createSiteApp({ ...(themeId === undefined ? {} : { themeId }), ...(consentAudit ? { consentAudit } : {}) }));
81
+ server.listen(0, "127.0.0.1");
82
+ await once(server, "listening");
83
+ const address = server.address();
84
+ return {
85
+ origin: `${LOOPBACK_HOST}:${address.port}`,
86
+ async close() {
87
+ server.closeAllConnections?.();
88
+ // Resolves once the server is fully closed. Mirrors `Jini packages/devops/src/static-export/node-adapters.ts`'s own teardown.
89
+ await new Promise((resolve) => server.close(() => resolve()));
90
+ },
91
+ };
92
+ }
93
+ /** Maps transport aborts to the published-page error while leaving body-read failures unchanged. */
94
+ async function requestPublishedPage({ deps, baseUrl, path, timeoutMs }, _options = {}) {
95
+ try {
96
+ // The default global `fetch` is read per call, so a test that swaps it is still honored.
97
+ const { fetch = globalThis.fetch } = deps;
98
+ const send = deps.trackFetch({ fetch, observability: deps.observability ?? UNTRACED });
99
+ return await send(`${baseUrl}${path}`, {
100
+ redirect: "manual",
101
+ signal: AbortSignal.timeout(timeoutMs),
102
+ });
103
+ }
104
+ catch (err) {
105
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
106
+ const timeout = new Error(`rendering '${path}' exceeded ${timeoutMs}ms`, { cause: err });
107
+ timeout.name = "PublishedPageTimeoutError";
108
+ throw timeout;
109
+ }
110
+ throw err;
111
+ }
112
+ }
113
+ /**
114
+ * Fetches one route of this site's own published surface and reports exactly what came back.
115
+ *
116
+ * Boots the site's real Express app on an ephemeral loopback port for the duration of ONE call,
117
+ * requests the validated path, and tears the server down in a `finally` — the same lifecycle
118
+ * the host's static site exporter uses to render a static export, so this observes the real render path
119
+ * rather than a second, agreeing-today copy of it.
120
+ *
121
+ * A per-call server rather than a memoized one is deliberate: a long-lived listening socket in the
122
+ * agent daemon would be a resource with no owner, and the cost here (route registration plus a
123
+ * loopback round trip) is nothing against the LLM turn that requested it.
124
+ *
125
+ * @param deps - Supplies `createSiteApp` (see {@link FetchPublishedPageDeps} for why the signature
126
+ * is written the way it is).
127
+ * @param input.path - A root-relative path on this site, e.g. `/` or `/blog/hello?page=2`.
128
+ * @param options.maxBytes - Body bytes to keep, clamped to `[1, MAX_MAX_BODY_BYTES]`.
129
+ * @param options.timeoutMs - Wall clock for the whole call, default {@link DEFAULT_FETCH_TIMEOUT_MS}.
130
+ * @returns A {@link PublishedPageResult}. A 404 or 30x is a RESULT, not an error — the caller
131
+ * asked what is live, and "nothing is there" is a true answer.
132
+ * @throws {SameOriginPathError} When `path` fails {@link resolveSitePath}.
133
+ * @throws {Error} Named `PublishedPageTimeoutError` when the render exceeds `timeoutMs`.
134
+ * @complexity O(min(B, maxBytes)) in the rendered response size, plus one Express app construction.
135
+ * @example
136
+ * const live = await fetchPublishedPage({ deps: routeDeps, input: { path: "/privacy" } }, { maxBytes: 50_000 });
137
+ * if (live.status === 404) console.log("no privacy policy is published");
138
+ */
139
+ export async function fetchPublishedPage({ deps, input }, options = {}) {
140
+ const maxBytes = resolveMaxBytes({ requested: options.maxBytes });
141
+ const timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
142
+ const site = await openLoopbackSiteServer({ deps });
143
+ const baseUrl = site.origin;
144
+ try {
145
+ // Validated against the origin this call just minted — see `resolveSitePath`'s doc.
146
+ const path = resolveSitePath({ raw: input.path, base: baseUrl, reservedSegments: deps.reservedSegments });
147
+ const response = await requestPublishedPage({ deps, baseUrl, path, timeoutMs });
148
+ const headers = {};
149
+ response.headers.forEach((value, key) => {
150
+ // `set-cookie` is reported separately, with values stripped — see this file's header.
151
+ if (key.toLowerCase() !== "set-cookie")
152
+ headers[key.toLowerCase()] = value;
153
+ });
154
+ const raw = await readBoundedBody({ response, maxBytes: options.textOnly || options.find !== undefined ? MAX_MAX_BODY_BYTES : maxBytes });
155
+ // Preserve exact byte accounting/decoding for legacy reads, including split UTF-8.
156
+ const legacy = !options.textOnly && options.find === undefined;
157
+ const shaped = legacy ? raw : shapePageBody({ body: raw.body }, { ...options, maxBytes });
158
+ return {
159
+ path,
160
+ status: response.status,
161
+ ok: response.status >= 200 && response.status < 300,
162
+ headers,
163
+ cookies: toCookieShapes({ headers: response.headers }),
164
+ ...shaped,
165
+ truncated: raw.truncated || shaped.truncated,
166
+ };
167
+ }
168
+ finally {
169
+ await site.close();
170
+ }
171
+ }
172
+ //# sourceMappingURL=published-page.js.map
@@ -1,4 +1,5 @@
1
1
  import type { HttpClientPort } from "@jini-ai/core/primitives";
2
+ import type { AbortReason, RequestDecision, RequestRouterReport, RoutedRequest } from "@jini-ai/core/contracts/site/web-evidence-playwright";
2
3
  /**
3
4
  * @file Every network request the screenshot browser makes, decided and carried here — Chromium
4
5
  * itself never opens a socket.
@@ -33,19 +34,6 @@ import type { HttpClientPort } from "@jini-ai/core/primitives";
33
34
  * their fresh, storage-less context. Evidence forwards only its own fresh visitor cookies to
34
35
  * the own-site origin; first- and third-party response cookies stay in its in-memory context.
35
36
  */
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
37
  /** The slice of a Playwright `Route` the router drives. */
50
38
  export interface RouteLike {
51
39
  request(): RoutedRequest;
@@ -74,18 +62,8 @@ export type OwnSiteFetch = (required: {
74
62
  maxBytes: number;
75
63
  fetch?: typeof globalThis.fetch;
76
64
  }) => Promise<FetchedResource>;
77
- export type AbortReason = "scheme" | "method" | "resource-type" | "budget" | "refused" | "failed";
78
65
  /** Redirect hops followed per request (and per page navigation), each one re-vetted. */
79
66
  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
67
  /**
90
68
  * Pure routing decision for one request. Budget is not considered here (see the router).
91
69
  * @complexity O(url length + allowedOrigins).
@@ -98,13 +76,6 @@ export declare function decideRequest({ url, method, resourceType, allowedOrigin
98
76
  }, { allowDataRequests }?: {
99
77
  allowDataRequests?: boolean;
100
78
  }): 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
79
  export interface RequestRouter {
109
80
  handle(route: RouteLike): Promise<void>;
110
81
  report(): RequestRouterReport;
@@ -162,5 +133,4 @@ export declare function createRequestRouter({ httpClient, ownSiteFetch, allowedO
162
133
  * @complexity O(min(body, maxBytes)).
163
134
  */
164
135
  export declare const fetchOwnSiteResource: OwnSiteFetch;
165
- export {};
166
136
  //# sourceMappingURL=request-guard.d.ts.map