@jini-ai/diagnostics 0.1.1 → 0.4.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 (67) hide show
  1. package/CHANGELOG.md +79 -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 +18 -0
  16. package/dist/observability/hooks.js +24 -0
  17. package/dist/observability/index.d.ts +14 -0
  18. package/dist/observability/index.js +14 -0
  19. package/dist/observability/noop.d.ts +4 -0
  20. package/dist/observability/noop.js +6 -0
  21. package/dist/observability/otel.d.ts +14 -0
  22. package/dist/observability/otel.js +28 -0
  23. package/dist/observability/ports.d.ts +79 -0
  24. package/dist/observability/ports.js +2 -0
  25. package/dist/ports.d.ts +45 -0
  26. package/dist/ports.js +2 -0
  27. package/dist/redaction/secret-patterns.d.ts +8 -0
  28. package/dist/redaction/secret-patterns.js +18 -0
  29. package/dist/redaction/secrets-only.d.ts +44 -0
  30. package/dist/redaction/secrets-only.js +179 -0
  31. package/dist/redaction.d.ts +12 -3
  32. package/dist/redaction.js +18 -8
  33. package/dist/sources.d.ts +22 -12
  34. package/dist/sources.js +22 -42
  35. package/dist/types.d.ts +24 -0
  36. package/dist/types.js +2 -0
  37. package/dist/web-evidence/browser-port.d.ts +166 -0
  38. package/dist/web-evidence/browser-port.js +6 -0
  39. package/dist/web-evidence/collect-page-evidence.d.ts +160 -0
  40. package/dist/web-evidence/collect-page-evidence.js +215 -0
  41. package/dist/web-evidence/index.d.ts +5 -0
  42. package/dist/web-evidence/index.js +5 -0
  43. package/dist/web-evidence/page-structure-script.d.ts +53 -0
  44. package/dist/web-evidence/page-structure-script.js +338 -0
  45. package/dist/web-evidence/page-work-budget.d.ts +27 -0
  46. package/dist/web-evidence/page-work-budget.js +53 -0
  47. package/dist/web-evidence/playwright-browser.d.ts +131 -0
  48. package/dist/web-evidence/playwright-browser.js +349 -0
  49. package/dist/web-evidence/same-origin.d.ts +126 -0
  50. package/dist/web-evidence/same-origin.js +141 -0
  51. package/dist/zip.d.ts +8 -3
  52. package/dist/zip.js +23 -16
  53. package/package.json +46 -5
  54. package/dist/agent-logs.d.ts.map +0 -1
  55. package/dist/agent-logs.js.map +0 -1
  56. package/dist/contract.d.ts.map +0 -1
  57. package/dist/contract.js.map +0 -1
  58. package/dist/index.d.ts.map +0 -1
  59. package/dist/index.js.map +0 -1
  60. package/dist/manifest.d.ts.map +0 -1
  61. package/dist/manifest.js.map +0 -1
  62. package/dist/redaction.d.ts.map +0 -1
  63. package/dist/redaction.js.map +0 -1
  64. package/dist/sources.d.ts.map +0 -1
  65. package/dist/sources.js.map +0 -1
  66. package/dist/zip.d.ts.map +0 -1
  67. package/dist/zip.js.map +0 -1
@@ -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
@@ -0,0 +1,141 @@
1
+ /** Longest site-relative path this tool will accept. Well past any real page URL; exists so a
2
+ * pathological input cannot be handed to a browser at all. */
3
+ const MAX_PATH_LENGTH = 2048;
4
+ /** Raw C0 controls, DEL, and whitespace — the characters that let a crafted string mean one thing
5
+ * to a validator and another to a URL parser. Mirrors `origin/origin.ts`'s
6
+ * `normalizeOriginCandidate`, which rejects the same class for the same reason. */
7
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: matching control characters is the entire purpose — a raw CR/LF/NUL in a path is exactly the smuggling vector this refuses.
8
+ const FORBIDDEN_CHARACTERS = /[\u0000-\u0020\u007f]/;
9
+ /**
10
+ * The syntactic rejections that only need the trimmed raw string — every one of these fires before
11
+ * a fragment is ever stripped or a leading slash ever added. Split out of {@link normalizeSitePath}
12
+ * purely to keep that function's own complexity below the repo's gate; the checks, their order, and
13
+ * every message are unchanged.
14
+ *
15
+ * @returns The rejection, or `null` if `trimmed` passes every syntactic check.
16
+ * @complexity O(n) in the path's own length.
17
+ */
18
+ function rejectionForRawPath(trimmed) {
19
+ if (trimmed.length === 0)
20
+ return reject("empty", "path is empty");
21
+ if (trimmed.length > MAX_PATH_LENGTH) {
22
+ return reject("too-long", `path is ${trimmed.length} characters, over the ${MAX_PATH_LENGTH}-character cap`);
23
+ }
24
+ if (FORBIDDEN_CHARACTERS.test(trimmed)) {
25
+ return reject("forbidden-character", "path contains a control character or embedded whitespace");
26
+ }
27
+ // `\` is a path separator to some URL parsers and a literal to others; a value containing one is
28
+ // never a path this tool should try to interpret. Checked BEFORE the scheme test so `\\host` is
29
+ // reported as what it is rather than as a generic "not a path".
30
+ if (trimmed.includes("\\")) {
31
+ return reject("backslash", "path contains a backslash, which some URL parsers treat as an authority separator");
32
+ }
33
+ if (trimmed.startsWith("//")) {
34
+ return reject("protocol-relative", "path is protocol-relative ('//host/…'), which names a different origin");
35
+ }
36
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
37
+ return reject("absolute-url", "path is an absolute URL; this tool accepts site-relative paths only and never fetches another origin");
38
+ }
39
+ return null;
40
+ }
41
+ /**
42
+ * Normalizes one caller-supplied site-relative path, or explains why it is not one.
43
+ *
44
+ * Accepts a leading-slash path with an optional query string (`/pricing`, `/blog/post?draft=1`).
45
+ * A missing leading slash is added rather than rejected — `pricing` is an unambiguous typo for
46
+ * `/pricing`, and there is no authority it could be confused with once every other form below is
47
+ * already refused.
48
+ *
49
+ * A fragment is stripped: it never reaches the server, so it cannot change what is observed, and
50
+ * keeping it would make two citations of the same evidence look like different pages.
51
+ *
52
+ * @throws Nothing — every rejection is returned, matching this codebase's convention for expected
53
+ * validation outcomes (`agent-plugins/manifest.ts`, `plugin-runtime/discovery.ts`).
54
+ * @complexity O(n) in the path's own length.
55
+ */
56
+ export function normalizeSitePath({ raw }) {
57
+ const trimmed = raw.trim();
58
+ const syntaxRejection = rejectionForRawPath(trimmed);
59
+ if (syntaxRejection)
60
+ return syntaxRejection;
61
+ const withoutFragment = trimmed.split("#", 1)[0];
62
+ // Always non-empty and always leading-slash by construction (either `withoutFragment` already
63
+ // started with "/", or one was just prepended) — `rejectionForRawPath` has already refused the
64
+ // only two raw forms that could make this empty (the empty string and a `//`-prefixed one).
65
+ const absolute = withoutFragment.startsWith("/") ? withoutFragment : `/${withoutFragment}`;
66
+ // Refused rather than resolved. Resolving would be safe (the join below is `new URL`-based and
67
+ // cannot escape the origin), but a `..` in a caller-supplied path means the caller believes it is
68
+ // somewhere it is not, and silently rewriting it would produce evidence cited against a path
69
+ // nobody asked for.
70
+ if (absolute.split("/").includes("..")) {
71
+ return reject("traversal", "path contains a '..' segment; give the resolved path instead");
72
+ }
73
+ return { ok: true, path: absolute };
74
+ }
75
+ function reject(reason, message) {
76
+ return { ok: false, reason, message };
77
+ }
78
+ /**
79
+ * Renders a `VerifiedOrigin` as a base URL string (`https://example.com`, `http://localhost:3000`).
80
+ *
81
+ * Duplicated locally rather than imported: `newsletter/unsubscribe.ts`, `newsletter/confirmation.ts`,
82
+ * `redirects/phase-handler.ts` and `members/write-service.ts` each already keep their own private
83
+ * copy of this three-line join, and `origin/` deliberately exports no shared formatter. Adding a
84
+ * fifth private copy is the existing convention; promoting one into `origin/` is a cross-cutting
85
+ * change that belongs to that module's owner, not to this feature.
86
+ *
87
+ * @complexity O(1).
88
+ */
89
+ export function verifiedOriginToBaseUrl({ origin }) {
90
+ const authority = origin.port === undefined ? origin.host : `${origin.host}:${origin.port}`;
91
+ return `${origin.scheme}://${authority}${origin.basePath ?? ""}`;
92
+ }
93
+ /**
94
+ * Joins a normalized site path onto a workspace's verified origin, preserving the origin's own
95
+ * base path.
96
+ *
97
+ * **Not `new URL(path, baseUrl)`** — that was the first implementation and it was wrong, caught by
98
+ * this module's own test rather than by review: a leading-slash path is ROOT-relative, so
99
+ * `new URL("/pricing", "https://example.test/site/")` resolves to `https://example.test/pricing`
100
+ * and silently discards the `/site` base path a `VerifiedOrigin` may carry. Not a security hole
101
+ * (the result is still same-origin) but a correctness one: every citation would then name a page
102
+ * the operator does not have.
103
+ *
104
+ * So the base path is prepended explicitly, and the result is resolved against `base.origin` — a
105
+ * bare origin with no path of its own, which is what makes the "cannot escape" property hold no
106
+ * matter what `path` contains. Leading slashes on `path` are collapsed to exactly one before the
107
+ * join specifically so a `//host` value (which {@link normalizeSitePath} already refuses, but which
108
+ * a future caller could reach this function with directly) degrades to the harmless `/host` rather
109
+ * than being read as an authority.
110
+ *
111
+ * @throws {TypeError} If `baseUrl` is not a parseable URL. Unreachable for a `VerifiedOrigin`
112
+ * rendered by {@link verifiedOriginToBaseUrl}; not caught here so a malformed registry row fails
113
+ * loudly at the composition root rather than being reported as a per-page evidence gap.
114
+ * @complexity O(n) in the joined URL's length.
115
+ */
116
+ export function resolveSameOriginUrl({ baseUrl, path }) {
117
+ const base = new URL(baseUrl);
118
+ const basePath = base.pathname.replace(/\/+$/, "");
119
+ const rootRelative = `/${path.replace(/^\/+/, "")}`;
120
+ return new URL(`${basePath}${rootRelative}`, base.origin).toString();
121
+ }
122
+ /**
123
+ * Whether `candidateUrl` is on the same origin as `baseUrl` — scheme, host, and effective port all
124
+ * equal. The post-navigation check: a page is allowed to redirect within its own site, and is not
125
+ * allowed to redirect this tool onto somebody else's.
126
+ *
127
+ * Fails closed: an unparseable candidate is not same-origin.
128
+ *
129
+ * @complexity O(n) in the two URLs' lengths.
130
+ */
131
+ export function isSameOriginUrl({ baseUrl, candidateUrl }) {
132
+ try {
133
+ const base = new URL(baseUrl);
134
+ const candidate = new URL(candidateUrl);
135
+ return base.protocol === candidate.protocol && base.host === candidate.host;
136
+ }
137
+ catch {
138
+ return false;
139
+ }
140
+ }
141
+ //# sourceMappingURL=same-origin.js.map
package/dist/zip.d.ts CHANGED
@@ -1,17 +1,22 @@
1
+ import type { DiagnosticsPorts } from "./ports.js";
1
2
  import { type RedactionOptions } from "./redaction.js";
2
3
  import { type DiagnosticsContext, type DiagnosticsManifest, type MachineInfo } from "./manifest.js";
3
- import { type CrashReportLookup, type LogSource } from "./sources.js";
4
- export interface DiagnosticsExportInput {
4
+ import { type CrashReportLookup, type CrashReportOptions, type LogSource } from "./sources.js";
5
+ export interface DiagnosticsExportInput extends DiagnosticsPorts {
5
6
  context: DiagnosticsContext;
6
7
  sources: LogSource[];
8
+ }
9
+ export interface DiagnosticsExportOptions {
7
10
  redaction?: RedactionOptions;
8
11
  /** When provided, scan macOS crash reports matching these substrings. */
9
12
  crashReports?: CrashReportLookup;
13
+ crashReportOptions?: CrashReportOptions;
10
14
  }
11
15
  export interface DiagnosticsExportResult {
12
16
  zip: Buffer;
13
17
  manifest: DiagnosticsManifest;
14
18
  machineInfo: MachineInfo;
15
19
  }
16
- export declare function buildDiagnosticsZip(input: DiagnosticsExportInput): Promise<DiagnosticsExportResult>;
20
+ /** Packages redacted files and summaries into a fresh host-provided archive. */
21
+ export declare function buildDiagnosticsZip(input: DiagnosticsExportInput, options?: DiagnosticsExportOptions): Promise<DiagnosticsExportResult>;
17
22
  //# sourceMappingURL=zip.d.ts.map