@jini-ai/diagnostics 0.1.2 → 0.5.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +114 -0
  3. package/dist/agent-logs.d.ts +9 -4
  4. package/dist/agent-logs.js +14 -15
  5. package/dist/domain-dns/index.d.ts +136 -0
  6. package/dist/domain-dns/index.js +117 -0
  7. package/dist/index.d.ts +41 -3
  8. package/dist/index.js +38 -1
  9. package/dist/manifest.d.ts +22 -16
  10. package/dist/manifest.js +9 -19
  11. package/dist/node-ports.d.ts +6 -0
  12. package/dist/node-ports.js +57 -0
  13. package/dist/observability/config.d.ts +24 -0
  14. package/dist/observability/config.js +21 -0
  15. package/dist/observability/hooks.d.ts +19 -0
  16. package/dist/observability/hooks.js +32 -0
  17. package/dist/observability/index.d.ts +17 -0
  18. package/dist/observability/index.js +16 -0
  19. package/dist/observability/instrumentation.d.ts +61 -0
  20. package/dist/observability/instrumentation.js +139 -0
  21. package/dist/observability/node.d.ts +12 -0
  22. package/dist/observability/node.js +15 -0
  23. package/dist/observability/noop.d.ts +7 -0
  24. package/dist/observability/noop.js +22 -0
  25. package/dist/observability/otel.d.ts +28 -0
  26. package/dist/observability/otel.js +120 -0
  27. package/dist/observability/ports.d.ts +150 -0
  28. package/dist/observability/ports.js +2 -0
  29. package/dist/ports.d.ts +45 -0
  30. package/dist/ports.js +2 -0
  31. package/dist/redaction/secrets-only.d.ts +44 -0
  32. package/dist/redaction/secrets-only.js +179 -0
  33. package/dist/redaction.d.ts +12 -3
  34. package/dist/redaction.js +18 -8
  35. package/dist/sources.d.ts +22 -12
  36. package/dist/sources.js +22 -42
  37. package/dist/types.d.ts +24 -0
  38. package/dist/types.js +2 -0
  39. package/dist/web-evidence/browser-port.d.ts +166 -0
  40. package/dist/web-evidence/browser-port.js +6 -0
  41. package/dist/web-evidence/collect-page-evidence.d.ts +160 -0
  42. package/dist/web-evidence/collect-page-evidence.js +215 -0
  43. package/dist/web-evidence/index.d.ts +5 -0
  44. package/dist/web-evidence/index.js +5 -0
  45. package/dist/web-evidence/page-structure-script.d.ts +53 -0
  46. package/dist/web-evidence/page-structure-script.js +338 -0
  47. package/dist/web-evidence/page-work-budget.d.ts +27 -0
  48. package/dist/web-evidence/page-work-budget.js +53 -0
  49. package/dist/web-evidence/playwright-browser.d.ts +131 -0
  50. package/dist/web-evidence/playwright-browser.js +349 -0
  51. package/dist/web-evidence/same-origin.d.ts +126 -0
  52. package/dist/web-evidence/same-origin.js +141 -0
  53. package/dist/zip.d.ts +8 -3
  54. package/dist/zip.js +23 -16
  55. package/package.json +50 -5
  56. package/dist/agent-logs.d.ts.map +0 -1
  57. package/dist/agent-logs.js.map +0 -1
  58. package/dist/contract.d.ts.map +0 -1
  59. package/dist/contract.js.map +0 -1
  60. package/dist/index.d.ts.map +0 -1
  61. package/dist/index.js.map +0 -1
  62. package/dist/manifest.d.ts.map +0 -1
  63. package/dist/manifest.js.map +0 -1
  64. package/dist/redaction.d.ts.map +0 -1
  65. package/dist/redaction.js.map +0 -1
  66. package/dist/sources.d.ts.map +0 -1
  67. package/dist/sources.js.map +0 -1
  68. package/dist/zip.d.ts.map +0 -1
  69. package/dist/zip.js.map +0 -1
@@ -0,0 +1,53 @@
1
+ /** Internal deadline shared by every asynchronous step of one page observation. */
2
+ export class PageWorkTimeout extends Error {
3
+ constructor({ timeoutMs }) {
4
+ super(`page work timed out after ${timeoutMs}ms`);
5
+ }
6
+ }
7
+ /** A timeout is a budget for the whole page, not a fresh allowance for each browser operation. */
8
+ export class PageWorkBudget {
9
+ expiresAt;
10
+ timeoutMs;
11
+ constructor({ timeoutMs }) {
12
+ this.timeoutMs = timeoutMs;
13
+ this.expiresAt = Date.now() + timeoutMs;
14
+ }
15
+ remainingMs() { return Math.max(0, this.expiresAt - Date.now()); }
16
+ /** Races even APIs without native timeouts (evaluation/cookies) and never starts expired work.
17
+ * @complexity O(1) time and space apart from the injected operation. */
18
+ async run({ work }) {
19
+ const remaining = this.remainingMs();
20
+ if (remaining <= 0)
21
+ throw new PageWorkTimeout({ timeoutMs: this.timeoutMs });
22
+ let timer;
23
+ try {
24
+ return await Promise.race([
25
+ work(),
26
+ new Promise((_resolve, reject) => {
27
+ timer = setTimeout(() => reject(new PageWorkTimeout({ timeoutMs: this.timeoutMs })), remaining);
28
+ }),
29
+ ]);
30
+ }
31
+ finally {
32
+ clearTimeout(timer);
33
+ }
34
+ }
35
+ /** Always initiate resource release, but a stalled close must not extend an exhausted budget.
36
+ * Pending Playwright operations are interrupted by context/browser close; late rejections are handled.
37
+ * @complexity O(1) aside from resource release. */
38
+ async release({ close }) {
39
+ const closing = close();
40
+ if (this.remainingMs() <= 0) {
41
+ void closing.catch(() => { });
42
+ return;
43
+ }
44
+ try {
45
+ await this.run({ work: () => closing });
46
+ }
47
+ catch (error) {
48
+ if (!(error instanceof PageWorkTimeout))
49
+ throw error;
50
+ }
51
+ }
52
+ }
53
+ //# sourceMappingURL=page-work-budget.js.map
@@ -0,0 +1,131 @@
1
+ /**
2
+ * @file The one and only module in this repository that touches a real headless browser.
3
+ * Implements `SiteEvidenceBrowserPort` (`browser-port.ts`) on Playwright's Chromium.
4
+ *
5
+ * ---------------------------------------------------------------------------
6
+ * Why the import is dynamic, and why the module's types are declared here
7
+ * ---------------------------------------------------------------------------
8
+ * The host may optionally install `playwright`; this package adds no browser dependency. The BROWSER
9
+ * BINARY it drives needs a separate `playwright install chromium` step in the host deployment.
10
+ * Installing the module alone does not supply that binary. So both halves can
11
+ * legitimately be missing at runtime, independently:
12
+ *
13
+ * - the module itself, on a deployment that pruned it;
14
+ * - the Chromium binary, on a deployment that installed the module but not the browser.
15
+ *
16
+ * Both are caught here and converted into `{ available: false, reason }`, never a thrown error and
17
+ * never a boot failure. The tool then reports "no browser in this deployment" and the compliance
18
+ * skill is required by its own output contract to downgrade every rendered-truth finding to
19
+ * `cannot-determine`. That is the entire reason this adapter must not be a static import: a static
20
+ * one would make an optional capability a hard boot dependency for every host install.
21
+ *
22
+ * {@link PlaywrightLike} declares, structurally, exactly the eight or so members this adapter uses.
23
+ * That is deliberate rather than importing Playwright's own (very large) `.d.ts`: typechecking this
24
+ * repository must not depend on a browser automation library's type surface being resolvable, and
25
+ * naming the members used makes the actual coupling one short, reviewable block instead of an
26
+ * open-ended import.
27
+ *
28
+ * ---------------------------------------------------------------------------
29
+ * Privacy properties, enforced here rather than promised
30
+ * ---------------------------------------------------------------------------
31
+ * - **Ephemeral context.** `browser.newContext()` with no `storageState` and no user-data
32
+ * directory. Cookies, storage, and cache exist only in memory and die with `close()`. Nothing is
33
+ * written to disk by this module.
34
+ * - **One context per page.** Each `observe()` call gets a fresh context, so a cookie set by page A
35
+ * can never be reported as though page B set it — which would be an outright false citation in a
36
+ * pre-consent cookie finding.
37
+ * - **No non-GET request ever leaves the process.** Every request is intercepted; anything that is
38
+ * not GET or HEAD is aborted and recorded as blocked. This is what makes "never submits forms" a
39
+ * structural property instead of a policy: even if a page auto-submits, or a consent widget POSTs
40
+ * preferences, the attempt is observed and the bytes do not go out.
41
+ * - **Values are never read.** Cookie values, request bodies, and form-field values are not
42
+ * extracted anywhere below, because `browser-port.ts`'s shapes have nowhere to put them.
43
+ */
44
+ import type { SiteEvidenceBrowserAvailability } from "./browser-port.js";
45
+ interface PwRoute {
46
+ request(): PwRequest;
47
+ abort(errorCode?: string): Promise<void>;
48
+ continue(): Promise<void>;
49
+ }
50
+ interface PwRequest {
51
+ url(): string;
52
+ method(): string;
53
+ resourceType(): string;
54
+ }
55
+ interface PwResponse {
56
+ status(): number;
57
+ url(): string;
58
+ headers(): Record<string, string>;
59
+ }
60
+ interface PwCookie {
61
+ name: string;
62
+ value: string;
63
+ domain: string;
64
+ path: string;
65
+ expires: number;
66
+ httpOnly: boolean;
67
+ secure: boolean;
68
+ sameSite: string;
69
+ }
70
+ interface PwLocator {
71
+ first(): PwLocator;
72
+ count(): Promise<number>;
73
+ click(options?: {
74
+ timeout?: number;
75
+ }): Promise<void>;
76
+ }
77
+ interface PwPage {
78
+ goto(url: string, options?: {
79
+ waitUntil?: string;
80
+ timeout?: number;
81
+ }): Promise<PwResponse | null>;
82
+ /** Only the STRING form is used — see {@link buildPageStructureExpression} for why passing the
83
+ * function reference directly is not safe here. */
84
+ evaluate<T>(expression: string): Promise<T>;
85
+ locator(selector: string): PwLocator;
86
+ waitForTimeout(ms: number): Promise<void>;
87
+ title(): Promise<string>;
88
+ }
89
+ interface PwContext {
90
+ newPage(): Promise<PwPage>;
91
+ route(pattern: string, handler: (route: PwRoute) => void | Promise<void>): Promise<void>;
92
+ cookies(): Promise<PwCookie[]>;
93
+ close(): Promise<void>;
94
+ }
95
+ interface PwBrowser {
96
+ newContext(options?: Record<string, unknown>): Promise<PwContext>;
97
+ close(): Promise<void>;
98
+ }
99
+ export interface PlaywrightLike {
100
+ chromium: {
101
+ launch(options?: {
102
+ headless?: boolean;
103
+ args?: readonly string[];
104
+ }): Promise<PwBrowser>;
105
+ };
106
+ }
107
+ /**
108
+ * Opens a real Chromium and returns a `SiteEvidenceBrowserPort` over it, or explains why this
109
+ * deployment cannot.
110
+ *
111
+ * @returns `{ available: true, browser }` on success; `{ available: false, reason }` when the
112
+ * `playwright` module or its Chromium binary is not present. Never throws for either case — see
113
+ * this file's header for why an absent browser must be a reportable state rather than an error.
114
+ * @complexity One process launch. The caller is responsible for calling `close()`, which
115
+ * `collectPageEvidence` does in a `finally`.
116
+ */
117
+ export interface PlaywrightAdapterOptions {
118
+ readonly moduleLoader?: {
119
+ load(required: {
120
+ moduleName: string;
121
+ }): Promise<PlaywrightLike>;
122
+ };
123
+ readonly launchOptions?: {
124
+ headless?: boolean;
125
+ args?: string[];
126
+ };
127
+ }
128
+ /** Opens the optional browser capability; import and launch failures become availability results. */
129
+ export declare function openPlaywrightSiteEvidenceBrowser(_required: Record<string, never>, options?: PlaywrightAdapterOptions): Promise<SiteEvidenceBrowserAvailability>;
130
+ export {};
131
+ //# sourceMappingURL=playwright-browser.d.ts.map
@@ -0,0 +1,349 @@
1
+ import { collectPageStructure } from "./page-structure-script.js";
2
+ import { PageWorkBudget, PageWorkTimeout } from "./page-work-budget.js";
3
+ /** Methods allowed out of the browser. Everything else is aborted — see this file's header. */
4
+ const SAFE_METHODS = new Set(["GET", "HEAD"]);
5
+ /** How long to wait for the page to settle after the consent click before re-reading state. Short
6
+ * on purpose: this is a debounce for the widget's own DOM/network reaction, not a crawl budget,
7
+ * and it is charged against the same per-page timeout as everything else. */
8
+ const CONSENT_SETTLE_MS = 1_500;
9
+ /** Opens the optional browser capability; import and launch failures become availability results. */
10
+ // A successful launch transfers process ownership to the caller; close the browser in a finally
11
+ // block so an unreachable or unstable page cannot leak the browser process.
12
+ export async function openPlaywrightSiteEvidenceBrowser(_required, options = {}) {
13
+ let playwright;
14
+ try {
15
+ const moduleName = "playwright";
16
+ playwright = options.moduleLoader
17
+ ? await options.moduleLoader.load({ moduleName })
18
+ : (await import(moduleName));
19
+ }
20
+ catch (error) {
21
+ return {
22
+ available: false,
23
+ reason: "the 'playwright' package is not installed in this deployment, so rendered-page behaviour " +
24
+ `cannot be observed here (${messageOf(error)})`,
25
+ };
26
+ }
27
+ let browser;
28
+ try {
29
+ browser = await playwright.chromium.launch({ headless: true, ...options.launchOptions });
30
+ }
31
+ catch (error) {
32
+ return {
33
+ available: false,
34
+ reason: "Chromium could not be launched in this deployment — the 'playwright' package is present but its " +
35
+ `browser binary is not installed (run 'npx playwright install --with-deps chromium'). Underlying error: ${messageOf(error)}`,
36
+ };
37
+ }
38
+ return { available: true, browser: new PlaywrightSiteEvidenceBrowser({ browser }) };
39
+ }
40
+ class PlaywrightSiteEvidenceBrowser {
41
+ browser;
42
+ constructor({ browser }) { this.browser = browser; }
43
+ /**
44
+ * Loads one page in a fresh ephemeral context and returns what was observed.
45
+ *
46
+ * @returns `{ ok: false, reason }` for any navigation failure or timeout — one unreachable page
47
+ * must not end the whole run, and "this page could not be loaded" is itself evidence the report
48
+ * is required to state.
49
+ * @complexity One page load bounded by `request.timeoutMs`, plus one in-page DOM walk bounded by
50
+ * the per-category caps in `request`.
51
+ */
52
+ async observe(required, options = {}) {
53
+ const request = { ...required, ...options };
54
+ const budget = new PageWorkBudget({ timeoutMs: request.timeoutMs });
55
+ // No `storageState`, no `recordVideo`, no `recordHar`, no user-data dir: nothing this context
56
+ // observes can outlive `close()` below or reach the filesystem. See this file's header.
57
+ let context;
58
+ try {
59
+ context = await budget.run({ work: async () => {
60
+ const created = await this.browser.newContext({ ignoreHTTPSErrors: false });
61
+ // A context can finish opening after our race timed out. It still belongs to this call.
62
+ if (budget.remainingMs() <= 0) {
63
+ void created.close().catch(() => { });
64
+ throw new PageWorkTimeout({ timeoutMs: request.timeoutMs });
65
+ }
66
+ return created;
67
+ } });
68
+ }
69
+ catch (error) {
70
+ return { ok: false, reason: `page capture failed before load: ${messageOf(error)}` };
71
+ }
72
+ const requests = [];
73
+ const notes = [];
74
+ let phase = "before";
75
+ try {
76
+ await budget.run({ work: () => context.route("**/*", async (route) => {
77
+ const pending = route.request();
78
+ const method = pending.method().toUpperCase();
79
+ const blocked = !SAFE_METHODS.has(method);
80
+ recordRequest(requests, request, {
81
+ method,
82
+ url: pending.url(),
83
+ resourceType: pending.resourceType(),
84
+ phase,
85
+ ...(blocked
86
+ ? {
87
+ blockedReason: "aborted: this tool never sends a non-GET request, so no form, consent preference, or " +
88
+ "analytics beacon it observes is ever actually submitted. The attempt itself is the evidence.",
89
+ }
90
+ : {}),
91
+ });
92
+ if (blocked) {
93
+ await route.abort("blockedbyclient");
94
+ return;
95
+ }
96
+ await route.continue();
97
+ }) });
98
+ const page = await budget.run({ work: () => context.newPage() });
99
+ let response;
100
+ try {
101
+ response = await budget.run({ work: () => page.goto(request.url, { waitUntil: "load", timeout: budget.remainingMs() }) });
102
+ }
103
+ catch (error) {
104
+ return { ok: false, reason: `navigation failed or timed out after ${request.timeoutMs}ms: ${messageOf(error)}` };
105
+ }
106
+ if (response === null) {
107
+ return { ok: false, reason: "the browser produced no response for this navigation (no HTTP exchange to observe)" };
108
+ }
109
+ const finalUrl = response.url();
110
+ const structureLimits = {
111
+ maxTextExcerptChars: request.maxTextExcerptChars,
112
+ maxNodesPerCategory: request.maxAccessibilityNodesPerCategory,
113
+ maxContrastSamples: request.maxContrastSamples,
114
+ collectAccessibility: request.collectAccessibility,
115
+ };
116
+ let structure;
117
+ let cookies;
118
+ try {
119
+ structure = await budget.run({ work: () => page.evaluate(buildPageStructureExpression(structureLimits)) });
120
+ if (request.consentAcceptSelector !== undefined) {
121
+ await this.performConsentClick(page, request, notes, () => {
122
+ phase = "after";
123
+ }, budget);
124
+ }
125
+ cookies = await budget.run({ work: () => context.cookies() });
126
+ }
127
+ catch (error) {
128
+ // The page can navigate away, close, or crash between `goto` resolving above and either of
129
+ // these reads — most commonly surfacing as Playwright's own "Execution context was
130
+ // destroyed". That is exactly the class of failure this port's contract exists to report as
131
+ // `{ ok: false, reason }` rather than let escape as a thrown error: one unreachable/unstable
132
+ // page must not end the whole `site_collect_page_evidence` run (`collect-page-evidence.ts`'s
133
+ // own per-page catch is the second, defense-in-depth layer for a port that does not honor
134
+ // this).
135
+ return { ok: false, reason: `page capture failed after load: ${messageOf(error)}` };
136
+ }
137
+ return {
138
+ ok: true,
139
+ observation: buildObservation({
140
+ request,
141
+ finalUrl,
142
+ httpStatus: response.status(),
143
+ headers: response.headers(),
144
+ title: structure.title,
145
+ structure,
146
+ cookies,
147
+ requests,
148
+ notes,
149
+ consentPhase: phase,
150
+ }),
151
+ };
152
+ }
153
+ catch (error) {
154
+ return { ok: false, reason: `page capture failed: ${messageOf(error)}` };
155
+ }
156
+ finally {
157
+ await budget.release({ close: () => context.close() });
158
+ }
159
+ }
160
+ async close(_required) {
161
+ await this.browser.close();
162
+ }
163
+ /**
164
+ * Clicks the operator-named consent control exactly once, flipping the observation phase.
165
+ *
166
+ * A selector that matches nothing is a NOTE, not a failure: "the consent selector you gave me
167
+ * matched no element on this page" is precisely the kind of thing the report must say out loud,
168
+ * and turning it into a thrown error would lose the rest of the page's evidence with it.
169
+ */
170
+ async performConsentClick(page, request, notes, markAfterPhase, budget) {
171
+ const selector = request.consentAcceptSelector;
172
+ let matches;
173
+ try {
174
+ matches = await budget.run({ work: () => page.locator(selector).count() });
175
+ }
176
+ catch (error) {
177
+ if (error instanceof PageWorkTimeout)
178
+ throw error;
179
+ notes.push(`consent selector '${selector}' is not a usable selector on this page: ${messageOf(error)}`);
180
+ return;
181
+ }
182
+ if (matches === 0) {
183
+ notes.push(`consent selector '${selector}' matched no element on this page — no consent interaction was performed, ` +
184
+ "so nothing below distinguishes pre-consent from post-consent behaviour");
185
+ return;
186
+ }
187
+ markAfterPhase();
188
+ try {
189
+ await budget.run({ work: () => page.locator(selector).first().click({ timeout: Math.min(budget.remainingMs(), 5_000) }) });
190
+ await budget.run({ work: () => page.waitForTimeout(CONSENT_SETTLE_MS) });
191
+ notes.push(`consent selector '${selector}' matched ${matches} element(s); the first was clicked. Cookies and requests ` +
192
+ "observed after that point are marked phase 'after'.");
193
+ }
194
+ catch (error) {
195
+ if (error instanceof PageWorkTimeout)
196
+ throw error;
197
+ notes.push(`consent selector '${selector}' matched ${matches} element(s) but the click did not complete: ${messageOf(error)}. ` +
198
+ "Post-consent evidence below is incomplete and must not be read as showing what a real visitor would see.");
199
+ }
200
+ }
201
+ }
202
+ /**
203
+ * Builds the self-contained JavaScript expression that runs `collectPageStructure` inside the page.
204
+ *
205
+ * **Why not just `page.evaluate(collectPageStructure, limits)`.** That was the obvious first
206
+ * implementation and it fails at runtime, in the browser, with `ReferenceError: __name is not
207
+ * defined` — found by this feature's real-browser integration test, and invisible to every
208
+ * fake-browser test and to `tsc`. The cause: esbuild (which `tsx` uses, and which any bundler with
209
+ * `keepNames` enabled uses) rewrites nested function declarations as
210
+ * `var f = __name(function f() {...}, "f")` and emits `__name` as a MODULE-scope helper. Playwright
211
+ * serialises only the function's own source text, so the helper it now depends on is left behind on
212
+ * the Node side and the page hits an undefined identifier.
213
+ *
214
+ * The fix is to ship a one-line `__name` shim into the page alongside the function source, inside an
215
+ * IIFE so both stay out of the page's own global scope. That makes the evaluated code genuinely
216
+ * self-contained — which is what `page-structure-script.ts`'s header already claims, and now
217
+ * actually is under every transpiler this repo runs through.
218
+ *
219
+ * `limits` is embedded as a JSON literal rather than passed as an argument for the same reason:
220
+ * one string, no second serialization path that could behave differently.
221
+ *
222
+ * @complexity O(n) in the function's own source length.
223
+ */
224
+ function buildPageStructureExpression(limits) {
225
+ return ("(() => {" +
226
+ // The shim. Identity, because name preservation has no meaning in the page.
227
+ "var __name = function (fn) { return fn; };" +
228
+ `var __collect = ${collectPageStructure.toString()};` +
229
+ `return __collect(${JSON.stringify(limits)});` +
230
+ "})()");
231
+ }
232
+ /**
233
+ * Appends one request observation, applying the cap.
234
+ *
235
+ * At the cap the request is dropped rather than replacing an earlier one: the earliest requests are
236
+ * the ones a pre-consent finding turns on, so keeping the head of the list and reporting truncation
237
+ * is the ordering that preserves the evidence that matters. Truncation is surfaced to the caller by
238
+ * the list length equalling `maxRequests`, which the result's own `limits` block makes checkable.
239
+ *
240
+ * @complexity O(1) per request.
241
+ */
242
+ function recordRequest(sink, request, input) {
243
+ if (sink.length >= request.maxRequests)
244
+ return;
245
+ let host;
246
+ let hostname;
247
+ let pathname;
248
+ try {
249
+ const parsed = new URL(input.url);
250
+ // `host` (with port) is what gets CITED — a reader needs to see the exact authority the browser
251
+ // talked to. `hostname` (without) is what the first-party comparison uses; see `sameHost`.
252
+ host = parsed.host;
253
+ hostname = parsed.hostname;
254
+ pathname = parsed.pathname;
255
+ }
256
+ catch {
257
+ host = "(unparseable)";
258
+ hostname = "(unparseable)";
259
+ pathname = "(unparseable)";
260
+ }
261
+ sink.push({
262
+ method: input.method,
263
+ host,
264
+ pathname,
265
+ resourceType: input.resourceType,
266
+ firstParty: sameHost(request.originBaseUrl, hostname),
267
+ phase: input.phase,
268
+ ...(input.blockedReason !== undefined ? { blockedReason: input.blockedReason } : {}),
269
+ });
270
+ }
271
+ /** Assembles the port-shaped observation. Pure — every input has already been gathered, so this is
272
+ * the seam a unit test can exercise without a browser. */
273
+ function buildObservation(input) {
274
+ const { request, structure } = input;
275
+ return {
276
+ document: {
277
+ httpStatus: input.httpStatus,
278
+ finalUrl: input.finalUrl,
279
+ redirected: normalizeUrlForComparison(input.finalUrl) !== normalizeUrlForComparison(request.url),
280
+ title: input.title,
281
+ lang: structure.lang,
282
+ headers: Object.entries(input.headers).map(([name, value]) => ({ name, value })),
283
+ textExcerpt: structure.textExcerpt,
284
+ textTruncated: structure.textTruncated,
285
+ },
286
+ cookies: input.cookies.slice(0, request.maxCookies).map((cookie) => toCookieEvidence(cookie, request, input.consentPhase)),
287
+ requests: input.requests,
288
+ ...(request.collectAccessibility ? { accessibility: structure.accessibility } : {}),
289
+ notes: [
290
+ ...input.notes,
291
+ ...(input.cookies.length > request.maxCookies
292
+ ? [`cookie list truncated at the ${request.maxCookies}-cookie cap (${input.cookies.length} were present)`]
293
+ : []),
294
+ ],
295
+ };
296
+ }
297
+ /**
298
+ * Converts one Playwright cookie into evidence — **dropping its value on the floor**, which is the
299
+ * point (`browser-port.ts`'s header). A session cookie's value is very often a user identifier;
300
+ * copying it into a report would put a real visitor's session token into an LLM's context.
301
+ *
302
+ * The phase is the phase the CONTEXT was in when cookies were read. Playwright's cookie jar has no
303
+ * per-cookie set time, so a cookie observed after a consent click cannot be attributed to before or
304
+ * after it from the jar alone. The honest reading, stated in the compliance skill's procedure, is
305
+ * to compare a `consentAction: none` run's cookies against an accepted run's — which is why the
306
+ * phase is recorded rather than guessed at per cookie.
307
+ */
308
+ function toCookieEvidence(cookie, request, phase) {
309
+ return {
310
+ name: cookie.name,
311
+ domain: cookie.domain,
312
+ path: cookie.path,
313
+ secure: cookie.secure,
314
+ httpOnly: cookie.httpOnly,
315
+ sameSite: cookie.sameSite,
316
+ expiresAt: cookie.expires > 0 ? new Date(cookie.expires * 1000).toISOString() : null,
317
+ firstParty: sameHost(request.originBaseUrl, cookie.domain.replace(/^\./, "")),
318
+ phase,
319
+ };
320
+ }
321
+ /**
322
+ * Hostname equality against the site's own origin — the `firstParty` flag.
323
+ *
324
+ * **`hostname`, not `host`, and that distinction was a real bug.** `URL.host` includes the port; a
325
+ * cookie's `domain` never does. Comparing `host` therefore classified every first-party cookie on a
326
+ * non-default port as THIRD-PARTY — caught by the real-browser integration test against a fixture
327
+ * server on an ephemeral port, and it would have been a silently wrong citation in a privacy
328
+ * finding, which is the worst failure this tool has available.
329
+ *
330
+ * Fails closed (`false`, i.e. treated as third-party) on an unparseable base URL: over-reporting
331
+ * third-party makes a screening noisier, under-reporting it makes a screening wrong.
332
+ */
333
+ function sameHost(originBaseUrl, hostname) {
334
+ try {
335
+ return new URL(originBaseUrl).hostname.toLowerCase() === hostname.toLowerCase();
336
+ }
337
+ catch {
338
+ return false;
339
+ }
340
+ }
341
+ /** Strips a single trailing slash so `https://x/pricing` and `https://x/pricing/` do not read as a
342
+ * redirect. Anything else that differs genuinely is one. */
343
+ function normalizeUrlForComparison(url) {
344
+ return url.endsWith("/") ? url.slice(0, -1) : url;
345
+ }
346
+ function messageOf(error) {
347
+ return error instanceof Error ? error.message : String(error);
348
+ }
349
+ //# sourceMappingURL=playwright-browser.js.map
@@ -0,0 +1,126 @@
1
+ /**
2
+ * @file The same-origin boundary for `site_collect_page_evidence` — the one place that decides
3
+ * which URL a headless browser is allowed to open on this workspace's behalf.
4
+ *
5
+ * ---------------------------------------------------------------------------
6
+ * Unrepresentability first, validation second
7
+ * ---------------------------------------------------------------------------
8
+ * The tool's input accepts **site-relative paths**, never URLs. That is deliberate and it is the
9
+ * primary guarantee: a caller (including a model that has been talked into fetching
10
+ * `http://169.254.169.254/latest/meta-data/`) has no input field in which an absolute URL, a host,
11
+ * or a scheme can be expressed at all. {@link normalizeSitePath} then refuses every syntactic form
12
+ * that could smuggle an authority through a field that is supposed to hold a path —
13
+ * `//evil.example`, `https://evil.example`, `\\evil.example`, and anything carrying a raw control
14
+ * character or a `..` segment.
15
+ *
16
+ * The origin the path is joined to comes from `OriginRegistryPort.canonicalOrigin` ( F2),
17
+ * which is the workspace's own verified origin and is never derived from a request `Host` header
18
+ * or from tool input. So "same-origin" here is not a comparison the caller can influence: the
19
+ * origin is fixed by the workspace, and only the path varies.
20
+ *
21
+ * {@link isSameOriginUrl} is the SECOND layer, for the one thing the first cannot cover: a page
22
+ * that responds with a redirect to somewhere else. The browser follows redirects, so the URL that
23
+ * actually got loaded has to be re-checked after the fact against the same canonical origin, and a
24
+ * page that left the origin is recorded as evidence and dropped rather than inspected.
25
+ *
26
+ * Architectural role:
27
+ * Pure string/URL logic. No I/O, no browser, no repo — `collect-page-evidence.ts` composes this
28
+ * with the real origin lookup and the real browser port.
29
+ * See docs/decisions/DR-001-trusted-evidence-addresses.md.
30
+ */
31
+ /** Caller-owned origin verification data; no origin is derived from request input. */
32
+ export interface VerifiedOrigin {
33
+ readonly scheme: "http" | "https";
34
+ readonly host: string;
35
+ readonly port?: number;
36
+ readonly basePath?: string;
37
+ readonly verifiedAt: string;
38
+ readonly source: string;
39
+ }
40
+ export interface VerifiedOriginPort {
41
+ canonicalOrigin(required: {
42
+ workspaceId: string;
43
+ }): Promise<VerifiedOrigin>;
44
+ }
45
+ export type SitePathRejectionReason = "empty" | "too-long" | "absolute-url" | "protocol-relative" | "backslash" | "not-absolute-path" | "forbidden-character" | "traversal";
46
+ export type NormalizeSitePathResult = {
47
+ readonly ok: true;
48
+ readonly path: string;
49
+ } | {
50
+ readonly ok: false;
51
+ readonly reason: SitePathRejectionReason;
52
+ readonly message: string;
53
+ };
54
+ /**
55
+ * Normalizes one caller-supplied site-relative path, or explains why it is not one.
56
+ *
57
+ * Accepts a leading-slash path with an optional query string (`/pricing`, `/blog/post?draft=1`).
58
+ * A missing leading slash is added rather than rejected — `pricing` is an unambiguous typo for
59
+ * `/pricing`, and there is no authority it could be confused with once every other form below is
60
+ * already refused.
61
+ *
62
+ * A fragment is stripped: it never reaches the server, so it cannot change what is observed, and
63
+ * keeping it would make two citations of the same evidence look like different pages.
64
+ *
65
+ * @throws Nothing — every rejection is returned, matching this codebase's convention for expected
66
+ * validation outcomes (`agent-plugins/manifest.ts`, `plugin-runtime/discovery.ts`).
67
+ * @complexity O(n) in the path's own length.
68
+ */
69
+ export declare function normalizeSitePath({ raw }: {
70
+ raw: string;
71
+ }): NormalizeSitePathResult;
72
+ /**
73
+ * Renders a `VerifiedOrigin` as a base URL string (`https://example.com`, `http://localhost:3000`).
74
+ *
75
+ * Duplicated locally rather than imported: `newsletter/unsubscribe.ts`, `newsletter/confirmation.ts`,
76
+ * `redirects/phase-handler.ts` and `members/write-service.ts` each already keep their own private
77
+ * copy of this three-line join, and `origin/` deliberately exports no shared formatter. Adding a
78
+ * fifth private copy is the existing convention; promoting one into `origin/` is a cross-cutting
79
+ * change that belongs to that module's owner, not to this feature.
80
+ *
81
+ * @complexity O(1).
82
+ */
83
+ export declare function verifiedOriginToBaseUrl({ origin }: {
84
+ origin: VerifiedOrigin;
85
+ }): string;
86
+ /**
87
+ * Joins a normalized site path onto a workspace's verified origin, preserving the origin's own
88
+ * base path.
89
+ *
90
+ * **Not `new URL(path, baseUrl)`** — that was the first implementation and it was wrong, caught by
91
+ * this module's own test rather than by review: a leading-slash path is ROOT-relative, so
92
+ * `new URL("/pricing", "https://example.test/site/")` resolves to `https://example.test/pricing`
93
+ * and silently discards the `/site` base path a `VerifiedOrigin` may carry. Not a security hole
94
+ * (the result is still same-origin) but a correctness one: every citation would then name a page
95
+ * the operator does not have.
96
+ *
97
+ * So the base path is prepended explicitly, and the result is resolved against `base.origin` — a
98
+ * bare origin with no path of its own, which is what makes the "cannot escape" property hold no
99
+ * matter what `path` contains. Leading slashes on `path` are collapsed to exactly one before the
100
+ * join specifically so a `//host` value (which {@link normalizeSitePath} already refuses, but which
101
+ * a future caller could reach this function with directly) degrades to the harmless `/host` rather
102
+ * than being read as an authority.
103
+ *
104
+ * @throws {TypeError} If `baseUrl` is not a parseable URL. Unreachable for a `VerifiedOrigin`
105
+ * rendered by {@link verifiedOriginToBaseUrl}; not caught here so a malformed registry row fails
106
+ * loudly at the composition root rather than being reported as a per-page evidence gap.
107
+ * @complexity O(n) in the joined URL's length.
108
+ */
109
+ export declare function resolveSameOriginUrl({ baseUrl, path }: {
110
+ baseUrl: string;
111
+ path: string;
112
+ }): string;
113
+ /**
114
+ * Whether `candidateUrl` is on the same origin as `baseUrl` — scheme, host, and effective port all
115
+ * equal. The post-navigation check: a page is allowed to redirect within its own site, and is not
116
+ * allowed to redirect this tool onto somebody else's.
117
+ *
118
+ * Fails closed: an unparseable candidate is not same-origin.
119
+ *
120
+ * @complexity O(n) in the two URLs' lengths.
121
+ */
122
+ export declare function isSameOriginUrl({ baseUrl, candidateUrl }: {
123
+ baseUrl: string;
124
+ candidateUrl: string;
125
+ }): boolean;
126
+ //# sourceMappingURL=same-origin.d.ts.map