@jini-ai/diagnostics 0.6.15-rc.2 → 0.6.15

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.
@@ -23,16 +23,11 @@ export async function buildRunEventLogSources({ runsDir, filesystem }, options =
23
23
  const tailBytes = options.tailBytes ?? DEFAULT_RUN_EVENT_TAIL_BYTES;
24
24
  const entries = await readDirectorySafe({ path: runsDir, filesystem });
25
25
  const candidates = [];
26
- for (const entry of entries) {
27
- if (!entry.isDirectory)
28
- continue;
29
- if (!SAFE_DIR_ENTRY.test(entry.name))
30
- continue;
26
+ for (const entry of entries.filter((each) => each.isDirectory && SAFE_DIR_ENTRY.test(each.name))) {
31
27
  const absolutePath = join(runsDir, entry.name, "events.jsonl");
32
28
  const info = await statSafe({ path: absolutePath, filesystem });
33
- if (!info || !info.isFile)
34
- continue;
35
- candidates.push({ runId: entry.name, absolutePath, mtimeMs: info.mtimeMs });
29
+ if (info?.isFile)
30
+ candidates.push({ runId: entry.name, absolutePath, mtimeMs: info.mtimeMs });
36
31
  }
37
32
  candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
38
33
  return candidates.slice(0, maxRuns).map(({ runId, absolutePath }) => ({
@@ -45,16 +40,11 @@ export async function buildRunEventLogSources({ runsDir, filesystem }, options =
45
40
  async function latestLogFilesIn(dir, max, filesystem) {
46
41
  const names = await readDirectorySafe({ path: dir, filesystem });
47
42
  const candidates = [];
48
- for (const { name } of names) {
49
- if (!name.endsWith(".log"))
50
- continue;
51
- if (!SAFE_DIR_ENTRY.test(name))
52
- continue;
43
+ for (const { name } of names.filter((each) => each.name.endsWith(".log") && SAFE_DIR_ENTRY.test(each.name))) {
53
44
  const absolutePath = join(dir, name);
54
45
  const info = await statSafe({ path: absolutePath, filesystem });
55
- if (!info || !info.isFile)
56
- continue;
57
- candidates.push({ name, absolutePath, mtimeMs: info.mtimeMs });
46
+ if (info?.isFile)
47
+ candidates.push({ name, absolutePath, mtimeMs: info.mtimeMs });
58
48
  }
59
49
  candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
60
50
  return candidates.slice(0, max).map(({ name, absolutePath }) => ({ name, absolutePath }));
@@ -18,6 +18,14 @@ const REUSED_CREDENTIAL_RULES = SECRET_SHAPE_PATTERNS.map((vendor) => ({
18
18
  * this file's header's Must NOT change list for why a bare prose colon (`password: must be...`)
19
19
  * is deliberately excluded from all three shapes below. */
20
20
  const LABELED_SECRET_LABELS = "password|passwd|pwd|secret|client_secret|api_key|apikey|access_token|refresh_token|id_token|auth_token|token|private_key|secret_access_key|signing_secret|webhook_secret";
21
+ // Parts of the auth-header rule below. The separator's optional quote now carries its own trailing
22
+ // space run (`\s*(?:["']\s*)?` matches exactly what `\s*["']?\s*` did) so two adjacent `\s*` runs no
23
+ // longer backtrack against each other across long whitespace.
24
+ const AUTH_HEADER_NAMES = "(?:proxy-)?authorization|x-api-key|api-key|x-goog-api-key|x-auth-token";
25
+ const AUTH_SCHEMES = "Bearer|Basic|Token|Digest|ApiKey";
26
+ const AUTH_VALUE = String.raw `(?!\[REDACTED)[^\s"'),;]+`;
27
+ const AUTH_HEADER_VALUE_RE = new RegExp(String.raw `(?<![a-z0-9-])(${AUTH_HEADER_NAMES})(\s*(?:["']\s*)?[:=]\s*["']?)` +
28
+ String.raw `(?:((?:${AUTH_SCHEMES})\s+)${AUTH_VALUE}|(?!(?:${AUTH_SCHEMES})\s)${AUTH_VALUE})`, "gi");
21
29
  /**
22
30
  * Every rule this module applies, in order. Order matters: `private_key` must run before the
23
31
  * reused header-only PEM pattern (inside {@link REUSED_CREDENTIAL_RULES}) so a full block is
@@ -48,12 +56,12 @@ const REDACTION_RULES = [
48
56
  // text. The second alternative's own `(?!(?:Bearer|...)\s)` explicitly refuses to start on a
49
57
  // scheme keyword, so when the first alternative's lookahead fails there is no fallback left to
50
58
  // backtrack into, and the whole rule correctly finds no match on a second pass.
51
- pattern: /(?<![A-Za-z0-9-])((?:proxy-)?authorization|x-api-key|api-key|x-goog-api-key|x-auth-token)(\s*["']?\s*[:=]\s*["']?)(?:((?:Bearer|Basic|Token|Digest|ApiKey)\s+)(?!\[REDACTED)[^\s"'),;]+|(?!\[REDACTED)(?!(?:Bearer|Basic|Token|Digest|ApiKey)\s)[^\s"'),;]+)/gi,
59
+ pattern: AUTH_HEADER_VALUE_RE,
52
60
  replacement: ({ match: m }) => `${m[1]}${m[2]}${m[3] ?? ""}[REDACTED:auth_header]`,
53
61
  },
54
62
  {
55
63
  kind: "auth_header",
56
- pattern: /(?<![A-Za-z0-9-])((?:set-)?cookie)(\s*[:=]\s*)(?!\[REDACTED)[^\s"'),;]+(?:;\s*[^\s"'),;]+)*/gi,
64
+ pattern: /(?<![a-z0-9-])((?:set-)?cookie)(\s*[:=]\s*)(?!\[REDACTED)[^\s"'),;]+(?:;\s*[^\s"'),;]+)*/gi,
57
65
  replacement: ({ match: m }) => `${m[1]}${m[2]}[REDACTED:auth_header]`,
58
66
  },
59
67
  {
@@ -69,18 +77,18 @@ const REDACTION_RULES = [
69
77
  ...REUSED_CREDENTIAL_RULES,
70
78
  {
71
79
  kind: "stripe_key",
72
- pattern: /(?<![A-Za-z0-9_])(?:sk|rk)_(?:live|test)_[0-9A-Za-z]{16,}/g,
80
+ pattern: /(?<!\w)(?:sk|rk)_(?:live|test)_[0-9A-Za-z]{16,}/g,
73
81
  replacement: () => "[REDACTED:stripe_key]",
74
82
  },
75
83
  {
76
84
  kind: "stripe_key",
77
- pattern: /(?<![A-Za-z0-9_])whsec_[A-Za-z0-9]{24,}/g,
85
+ pattern: /(?<!\w)whsec_[A-Za-z0-9]{24,}/g,
78
86
  replacement: () => "[REDACTED:stripe_key]",
79
87
  },
80
88
  {
81
89
  kind: "github_token",
82
90
  // Covers `ghs_`/`ghu_`/`ghr_` and lengths the exact-length SECRET_SHAPE_PATTERNS entries miss.
83
- pattern: /(?<![A-Za-z0-9_])gh[pousr]_[A-Za-z0-9]{30,}/g,
91
+ pattern: /(?<!\w)gh[pousr]_[A-Za-z0-9]{30,}/g,
84
92
  replacement: () => "[REDACTED:github_token]",
85
93
  },
86
94
  {
@@ -216,7 +224,7 @@ function hasSecretLiteralContext({ previous }, _options = {}) {
216
224
  if (!name || (name.type !== "IdentifierName" && name.type !== "StringLiteral"))
217
225
  return false;
218
226
  const label = name.type === "StringLiteral" ? decodeStaticLiteral({ content: name.value.slice(1, -1) }) : name.value;
219
- if (!/(pass(word|wd)?|secret|token|api[-_]?key|access[-_]?key|private[-_]?key|client[-_]?secret|auth(orization)?|bearer|cookie|credential)s?$/i.test(label))
227
+ if (!SECRET_LABEL_SUFFIX.test(label))
220
228
  return false;
221
229
  if (separator === ":" || separator === "=")
222
230
  return true;
@@ -248,22 +256,28 @@ function redactUnclassifiedLiteral({ content, adjacentSecret }, _options = {}) {
248
256
  return { text: "[REDACTED:high_entropy]", redactions: 1 };
249
257
  return { text: content, redactions: 0 };
250
258
  }
259
+ /** Names that label a secret value, matched at the end of a property/argument name (plural allowed). */
260
+ const SECRET_LABEL_WORDS = [
261
+ 'pass(word|wd)?', 'secret', 'token', 'api[-_]?key', 'access[-_]?key', 'private[-_]?key', 'client[-_]?secret',
262
+ 'auth(orization)?', 'bearer', 'cookie', 'credential',
263
+ ];
264
+ const SECRET_LABEL_SUFFIX = new RegExp(`(${SECRET_LABEL_WORDS.join('|')})s?$`, 'i');
251
265
  /** Decodes static JavaScript escapes for classification without evaluating source.
252
266
  * O(n) time/space in literal length; nonsecret source keeps its original spelling. */
253
267
  function decodeStaticLiteral({ content }, _options = {}) {
254
268
  const escapes = { n: "\n", r: "\r", t: "\t", b: "\b", f: "\f", v: "\v" };
255
- return content.replace(/\\(u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0-7]{1,3}|\r\n|[\s\S])/g, (_match, escape) => {
256
- if (escape.startsWith("u{")) {
257
- const point = Number.parseInt(escape.slice(2, -1), 16);
269
+ return content.replace(/\\(u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0-7]{1,3}|\r\n|[\s\S])/g, (_match, sequence) => {
270
+ if (sequence.startsWith("u{")) {
271
+ const point = Number.parseInt(sequence.slice(2, -1), 16);
258
272
  return point <= 0x10ffff ? String.fromCodePoint(point) : "";
259
273
  }
260
- if (/^[ux]/.test(escape) && escape.length > 1)
261
- return String.fromCharCode(Number.parseInt(escape.slice(1), 16));
262
- if (/^[0-7]+$/.test(escape))
263
- return String.fromCharCode(Number.parseInt(escape, 8));
264
- if (/^[\r\n]/.test(escape))
274
+ if (/^[ux]/.test(sequence) && sequence.length > 1)
275
+ return String.fromCharCode(Number.parseInt(sequence.slice(1), 16));
276
+ if (/^[0-7]+$/.test(sequence))
277
+ return String.fromCharCode(Number.parseInt(sequence, 8));
278
+ if (/^[\r\n]/.test(sequence))
265
279
  return "";
266
- return escapes[escape] ?? escape;
280
+ return escapes[sequence] ?? sequence;
267
281
  });
268
282
  }
269
283
  function redactCodeTokenContent({ content, literal, adjacentSecret, policy }, _options = {}) {
@@ -6,6 +6,11 @@ export class DomainDnsInputError extends Error {
6
6
  }
7
7
  /** Public DNS only. The composition root supplies a resolver that cannot inspect internal DNS. */
8
8
  export const DNS_TYPES = ["A", "AAAA", "CNAME", "MX", "TXT", "NS"];
9
+ function hostDnsStatus({ hasExpected, differs }) {
10
+ if (!hasExpected)
11
+ return "unknown";
12
+ return differs ? "mismatch" : "matches-host-dns";
13
+ }
9
14
  /**
10
15
  * Normalizes a public hostname before any effect.
11
16
  * @param required Hostname text and the caller's error-message prefix.
@@ -37,7 +42,8 @@ function readPublicName(value, toolId, options = {}) {
37
42
  const validLabels = labels.every(label => labelPattern.test(label));
38
43
  const validSuffix = /^[a-z][a-z0-9-]*$/.test(labels.at(-1));
39
44
  const reservedName = /\.(?:local|localhost|internal|invalid|test|onion)$/.test(domain);
40
- if (!domain || domain.length > 253 || isIP(domain) || labels.length < 2 || !validLabels || !validSuffix || reservedName)
45
+ const validShape = Boolean(domain) && domain.length <= 253 && !isIP(domain) && labels.length >= 2;
46
+ if (!validShape || !validLabels || !validSuffix || reservedName)
41
47
  throw invalid();
42
48
  return domain;
43
49
  }
@@ -50,7 +56,8 @@ function readPublicNameText({ value, invalid }, _options = {}) {
50
56
  function readTypes(value) {
51
57
  if (value === undefined)
52
58
  return [...DNS_TYPES];
53
- if (!Array.isArray(value) || value.length < 1 || value.length > 6 || new Set(value).size !== value.length || !value.every(type => DNS_TYPES.includes(type))) {
59
+ const validList = Array.isArray(value) && value.length >= 1 && value.length <= 6;
60
+ if (!validList || new Set(value).size !== value.length || !value.every(type => DNS_TYPES.includes(type))) {
54
61
  throw new DomainDnsInputError({ message: "domain_lookup_dns: types must be a non-empty list of distinct A, AAAA, CNAME, MX, TXT, or NS record types." });
55
62
  }
56
63
  return value;
@@ -90,7 +97,7 @@ async function checkHost(deps, domain, selected) {
90
97
  const missing = { A: difference(expected.A, observed.A), AAAA: difference(expected.AAAA, observed.AAAA) };
91
98
  const hasExpected = expected.A.length + expected.AAAA.length > 0;
92
99
  const differs = unexpected.A.length + unexpected.AAAA.length + missing.A.length + missing.AAAA.length > 0;
93
- return { domain, expectedHost, status: !hasExpected ? "unknown" : differs ? "mismatch" : "matches-host-dns", expectationSource: "host-dns", expected, observed, unexpected, missing, untrusted: true, limitation: "Compares current public DNS, not provider-required records. Shared/CDN addresses do not prove that traffic reaches the correct app." };
100
+ return { domain, expectedHost, status: hostDnsStatus({ hasExpected, differs }), expectationSource: "host-dns", expected, observed, unexpected, missing, untrusted: true, limitation: "Compares current public DNS, not provider-required records. Shared/CDN addresses do not prove that traffic reaches the correct app." };
94
101
  }
95
102
  /** Builds three bounded read operations without CMS/tool registration.
96
103
  * @param deps Required public-network, hosting-source and authorization ports.
@@ -1,3 +1,4 @@
1
+ import { trimCharsEnd } from '@jini-ai/core/primitives';
1
2
  /** Resolves explicit OTLP settings. Traces endpoint wins; general endpoint gets /v1/traces.
2
3
  * @param required Caller-owned service and tracer identity.
3
4
  * @param options Explicit endpoints; absence disables telemetry.
@@ -16,6 +17,6 @@ export function resolveObservabilityConfig({ serviceName, tracerName }, { endpoi
16
17
  throw new TypeError('tracerName must be non-empty');
17
18
  // A signal-specific endpoint already names its route; the general endpoint needs /v1/traces.
18
19
  // Treating the general endpoint as complete would send traces to the collector's wrong route.
19
- return { enabled: true, serviceName: serviceName.trim(), tracerName: tracerName.trim(), endpoint: traces || `${base.replace(/\/+$/, '')}/v1/traces` };
20
+ return { enabled: true, serviceName: serviceName.trim(), tracerName: tracerName.trim(), endpoint: traces || `${trimCharsEnd({ text: base, chars: '/' })}/v1/traces` };
20
21
  }
21
22
  //# sourceMappingURL=config.js.map
@@ -1,7 +1,9 @@
1
1
  const ERROR_CLASSES = new Set(["Error", "TypeError", "RangeError", "TimeoutError", "AbortError", "OTLPExporterError", "PluginProviderError"]);
2
2
  /** HTTP status is numeric and bounded; transport codes and text are deliberately not exposed. */
3
3
  function httpStatus(value) {
4
- return typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599 ? value : undefined;
4
+ if (typeof value !== "number" || !Number.isInteger(value))
5
+ return undefined;
6
+ return value >= 100 && value <= 599 ? value : undefined;
5
7
  }
6
8
  /** Reduces opaque SDK failures to fixed labels; even an Error's name can contain credentials.
7
9
  * @returns Error class and optional HTTP status, never a message, stack, URL or header.
@@ -50,8 +52,9 @@ export function createTelemetryDeliveryMonitor({ warn }, { now = () => new Date(
50
52
  return;
51
53
  failures.add(kind);
52
54
  logged.set(providerId, failures);
55
+ const httpNote = report.statusCode === undefined ? "" : `, HTTP ${report.statusCode}`;
53
56
  try {
54
- warn(`observability: ${providerId} ${report.phase} failed (${report.errorClass ?? "Error"}${report.statusCode === undefined ? "" : `, HTTP ${report.statusCode}`}, host ${report.host})`);
57
+ warn(`observability: ${providerId} ${report.phase} failed (${report.errorClass ?? "Error"}${httpNote}, host ${report.host})`);
55
58
  }
56
59
  catch { /* A broken log sink must not fail an exporter callback or shutdown. */ }
57
60
  },
@@ -3,12 +3,6 @@ export interface ReportedErrorDescription {
3
3
  message: string;
4
4
  stack?: string;
5
5
  }
6
- /** Vendor-neutral, redacted view of a reported error that any error-tracker adapter can send.
7
- * Secret shapes (tokens, keys, `password=…`) are blanked; e-mails and hostnames are NOT — callers
8
- * must not put personal data in error messages (see the plan's PII section).
9
- * @param required The raw error as handed to `ObservabilityPort.reportError`.
10
- * @returns Type label, redacted capped message, and redacted capped stack when there is one.
11
- * @complexity O(n) in message + stack length. */
12
6
  export declare function describeReportedError({ error }: {
13
7
  error: unknown;
14
8
  }, _options?: {}): ReportedErrorDescription;
@@ -15,9 +15,14 @@ function redact(text) {
15
15
  * @param required The raw error as handed to `ObservabilityPort.reportError`.
16
16
  * @returns Type label, redacted capped message, and redacted capped stack when there is one.
17
17
  * @complexity O(n) in message + stack length. */
18
+ function rawMessage({ error, type }) {
19
+ if (error instanceof Error)
20
+ return error.message;
21
+ return typeof error === 'string' ? error : type;
22
+ }
18
23
  export function describeReportedError({ error }, _options = {}) {
19
24
  const type = errorType(error);
20
- const raw = error instanceof Error ? error.message : typeof error === 'string' ? error : type;
25
+ const raw = rawMessage({ error, type });
21
26
  const stack = error instanceof Error && typeof error.stack === 'string'
22
27
  ? redact(error.stack).split('\n').slice(0, MAX_STACK_LINES).join('\n') : undefined;
23
28
  return { type, message: redact(raw).slice(0, MAX_MESSAGE), ...(stack ? { stack } : {}) };
@@ -156,8 +156,11 @@ export function combineObservabilityPorts({ ports }, { onFailure } = {}) {
156
156
  if (results.includes(true))
157
157
  return true;
158
158
  // One fulfilled admission is enough; a stalled destination must not delay another's receipt.
159
- const admissions = results.map(async (result) => { if (!await result)
160
- throw new Error('Report refused'); return true; });
159
+ const admissions = results.map(async (result) => {
160
+ if (!await result)
161
+ throw new Error('Report refused');
162
+ return true;
163
+ });
161
164
  return Promise.any(admissions).catch(() => false);
162
165
  },
163
166
  };
@@ -9,11 +9,6 @@ export interface OtelAdapterOptions {
9
9
  scope?: SpanScopePort;
10
10
  }
11
11
  type Attributes = Record<string, string | number>;
12
- /** A low-cardinality error label: a SCREAMING_CASE code (ECONNREFUSED, SQLITE_BUSY), else the class
13
- * name. Messages are never exported: they carry SQL fragments, hostnames, emails, even credentials.
14
- * Both `error.code` and `Error.name` are writable secret channels (review 2026-10-25 #2):
15
- * select the label, then redact and cap it
16
- * to {@link MAX_ERROR_TYPE} (redact first: a cut could leave a secret prefix too short to match). */
17
12
  export declare function errorType(error: unknown): string;
18
13
  /** Feature attributes are documented as ids and fixed labels, but a caller can still hand over a
19
14
  * secret-shaped value (an unknown tool id straight from a request, review #1). Every string is
@@ -23,10 +18,6 @@ export declare function errorType(error: unknown): string;
23
18
  export declare function redactOperationAttributes({ attributes }: {
24
19
  attributes: Readonly<Record<string, string | number>>;
25
20
  }): Attributes;
26
- /** Prefer a router-owned template. Otherwise drop query/fragment and replace sensitive-looking
27
- * segments; raw ids no longer cross the export boundary (correlation belongs on explicit ids).
28
- * @returns A bounded request target. @complexity O(p) path text.
29
- */
30
21
  export declare function redactRequestTarget({ path }: {
31
22
  path: string;
32
23
  }, { routePattern }?: {
@@ -4,10 +4,12 @@ import { redactSecretShapes } from '../core/secrets-only.js';
4
4
  * Both `error.code` and `Error.name` are writable secret channels (review 2026-10-25 #2):
5
5
  * select the label, then redact and cap it
6
6
  * to {@link MAX_ERROR_TYPE} (redact first: a cut could leave a secret prefix too short to match). */
7
+ function fallbackErrorLabel(error) {
8
+ return error instanceof Error ? String(error.name) : typeof error;
9
+ }
7
10
  export function errorType(error) {
8
11
  const code = error?.code;
9
- const label = typeof code === 'string' && /^[A-Z][A-Z0-9_]{1,63}$/.test(code)
10
- ? code : error instanceof Error ? String(error.name) : typeof error;
12
+ const label = typeof code === 'string' && /^[A-Z][A-Z0-9_]{1,63}$/.test(code) ? code : fallbackErrorLabel(error);
11
13
  return redactLabel(label).slice(0, MAX_ERROR_TYPE) || 'Error';
12
14
  }
13
15
  const MAX_ERROR_TYPE = 64;
@@ -24,12 +26,9 @@ function redactLabel(text) {
24
26
  * @param required The caller's attributes. @returns A fresh, redacted copy. @complexity O(total text). */
25
27
  export function redactOperationAttributes({ attributes }) {
26
28
  const safe = {};
27
- for (const name of Object.keys(attributes)) {
28
- if (Object.keys(safe).length >= MAX_ATTRIBUTES)
29
- break;
30
- // Keys are a bounded label allow-list too: never export emails, URLs or credential-shaped keys.
31
- if (!ATTRIBUTE_KEY.test(name) || redactLabel(name) !== name)
32
- continue;
29
+ // Keys are a bounded label allow-list too: never export emails, URLs or credential-shaped keys.
30
+ const names = Object.keys(attributes).filter(name => ATTRIBUTE_KEY.test(name) && redactLabel(name) === name);
31
+ for (const name of names.slice(0, MAX_ATTRIBUTES)) {
33
32
  const value = attributes[name];
34
33
  safe[name] = typeof value === 'string' ? redactLabel(value).slice(0, MAX_ATTRIBUTE_TEXT) : value;
35
34
  }
@@ -59,10 +58,15 @@ function safePathSegment({ segment }, _options = {}) {
59
58
  * segments; raw ids no longer cross the export boundary (correlation belongs on explicit ids).
60
59
  * @returns A bounded request target. @complexity O(p) path text.
61
60
  */
61
+ /** Cuts at the first `?` or `#`, as /[?#][\s\S]*$/ did, without its backtracking. */
62
+ function withoutQueryOrFragment(target) {
63
+ const cut = target.search(/[?#]/);
64
+ return cut === -1 ? target : target.slice(0, cut);
65
+ }
62
66
  export function redactRequestTarget({ path }, { routePattern } = {}) {
63
67
  if (routePattern && routePattern !== 'unmatched')
64
- return routePattern.replace(/[?#][\s\S]*$/, '').slice(0, 1024);
65
- return path.replace(/[?#][\s\S]*$/, '').split('/').map(segment => safePathSegment({ segment })).join('/').slice(0, 1024);
68
+ return withoutQueryOrFragment(routePattern).slice(0, 1024);
69
+ return withoutQueryOrFragment(path).split('/').map(segment => safePathSegment({ segment })).join('/').slice(0, 1024);
66
70
  }
67
71
  /** Scheme, host and explicit port only. Paths carry bot tokens and signed-URL keys; userinfo carries passwords. */
68
72
  export function outboundTargetAttributes(url) {
@@ -83,8 +87,12 @@ const FAILED_RUN_STATUSES = new Set(['failed', 'interrupted']);
83
87
  /** Wraps an end handler so a second end() is ignored. */
84
88
  function once(handler) {
85
89
  let ended = false;
86
- return (outcome) => { if (ended)
87
- return; ended = true; handler(outcome); };
90
+ return (outcome) => {
91
+ if (ended)
92
+ return;
93
+ ended = true;
94
+ handler(outcome);
95
+ };
88
96
  }
89
97
  /** Builds request, DB, outbound, agent-run and operation spans, and exception events for reported errors, through injected provider/exporter factories.
90
98
  * @param required Explicit config and structural factories. Hosts wrap their SDK here.
@@ -153,8 +161,10 @@ export function createOtelObservabilityPort({ config, exporterFactory, tracerPro
153
161
  const span = start({ name: `${method} ${target['server.address']}`, kind: 'client', attributes: { 'http.request.method': method, ...target } });
154
162
  return { run: runIn(span), end: once(({ statusCode, error }) => {
155
163
  const attributes = statusCode !== undefined ? { 'http.response.status_code': statusCode } : {};
156
- if (error !== undefined)
157
- return finish({ span, attributes }, { failure: errorType(error), error });
164
+ if (error !== undefined) {
165
+ finish({ span, attributes }, { failure: errorType(error), error });
166
+ return;
167
+ }
158
168
  // Client-span semantics: a 4xx is this caller's failure, unlike a server span's 4xx.
159
169
  finish({ span, attributes }, statusCode !== undefined && statusCode >= 400 ? { failure: String(statusCode) } : {});
160
170
  }) };
@@ -179,6 +189,7 @@ export function createOtelObservabilityPort({ config, exporterFactory, tracerPro
179
189
  reportedSpans.add(span);
180
190
  if (!active)
181
191
  span.end({});
192
+ return true;
182
193
  }
183
194
  catch {
184
195
  // Reporting is best-effort: a broken exporter must not turn an already-handled failure into a crash.
@@ -193,8 +204,10 @@ export function createOtelObservabilityPort({ config, exporterFactory, tracerPro
193
204
  } }, { root: true });
194
205
  return { run: runIn(span), end: once(({ status, error }) => {
195
206
  const attributes = { 'agent.run.status': status };
196
- if (error !== undefined)
197
- return finish({ span, attributes }, { failure: errorType(error), error });
207
+ if (error !== undefined) {
208
+ finish({ span, attributes }, { failure: errorType(error), error });
209
+ return;
210
+ }
198
211
  finish({ span, attributes }, FAILED_RUN_STATUSES.has(status) ? { failure: status } : {});
199
212
  }) };
200
213
  },
@@ -1,11 +1,13 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
+ /** The fixed name the telemetry self-test uses for its error operation, span and metric. */
3
+ const TELEMETRY_TEST_NAME = "telemetry.test";
2
4
  /** Recognize only the fixed diagnostic signals; incidental work in the same scope is ignored. */
3
5
  function testSignal({ method, input }) {
4
- if (method === "reportError" && input.context?.operation === "telemetry.test")
6
+ if (method === "reportError" && input.context?.operation === TELEMETRY_TEST_NAME)
5
7
  return "error";
6
- if (method === "trackOperation" && input.name === "telemetry.test")
8
+ if (method === "trackOperation" && input.name === TELEMETRY_TEST_NAME)
7
9
  return "span";
8
- if (method === "metric" && input.name === "telemetry.test")
10
+ if (method === "metric" && input.name === TELEMETRY_TEST_NAME)
9
11
  return "metric";
10
12
  if (method === "capture" && input.name === "telemetry_test")
11
13
  return "analytics";
@@ -33,9 +35,9 @@ export function createTelemetryTestProbe(_required, _options = {}) {
33
35
  },
34
36
  async send({ tracker, error, userId }, _optional = {}) {
35
37
  return active.run(new Map(), async () => {
36
- await tracker.trace({ name: "telemetry.test", run: async () => {
37
- tracker.metric({ name: "telemetry.test", value: 1 }, { kind: "counter" });
38
- tracker.error({ error }, { context: { operation: "telemetry.test" } });
38
+ await tracker.trace({ name: TELEMETRY_TEST_NAME, run: async () => {
39
+ tracker.metric({ name: TELEMETRY_TEST_NAME, value: 1 }, { kind: "counter" });
40
+ tracker.error({ error }, { context: { operation: TELEMETRY_TEST_NAME } });
39
41
  await tracker.capture({ name: "telemetry_test", userId });
40
42
  } });
41
43
  return { providers: [...active.getStore()].map(([providerId, signals]) => ({ providerId, signals: [...signals] })) };
@@ -1,5 +1,18 @@
1
- import type { ProductAnalyticsPort, ProductEvent } from "@jini-ai/analytics/product";
2
1
  import type { AgentRunTrackingInput, AgentRunTrackingOptions, AgentRunTrackingOutcome, ObservabilityPort, OperationAttributes, OperationTrackingOutcome, RequestTrackingInput, RequestTrackingOptions, RequestTrackingOutcome, MetricInput, MetricOptions } from "./ports.js";
2
+ /** Capture-only consumer port; higher-layer analytics adapters satisfy it structurally. */
3
+ interface CaptureEvent {
4
+ name: string;
5
+ userId: string;
6
+ properties?: Readonly<Record<string, string | number | boolean>>;
7
+ }
8
+ interface CapturePort {
9
+ capture(event: CaptureEvent): void | Promise<void>;
10
+ /** Retained for existing provider literals; the tracker never identifies users. */
11
+ identify?(identity: {
12
+ userId: string;
13
+ traits?: CaptureEvent['properties'];
14
+ }): void;
15
+ }
3
16
  /** Signals share one dependency; each method retains its own typed payload. */
4
17
  export interface TrackerErrorContext {
5
18
  level?: 'warning' | 'error';
@@ -29,7 +42,7 @@ export interface Tracker {
29
42
  /** Current tracing IDs, absent without an active span; optional for older host facades. */
30
43
  activeTraceIds?(required?: Record<string, never>, optional?: Record<string, never>): import('./ports.js').TraceIds | undefined;
31
44
  /** Awaitable local admission; does not wait for remote delivery. */
32
- capture(input: Pick<ProductEvent, "name" | "userId">, options?: Pick<ProductEvent, "properties">): void | Promise<void>;
45
+ capture(input: Pick<CaptureEvent, "name" | "userId">, options?: Pick<CaptureEvent, "properties">): void | Promise<void>;
33
46
  error(input: {
34
47
  error: Error;
35
48
  }, options?: {
@@ -52,10 +65,11 @@ export interface Tracker {
52
65
  }
53
66
  export interface TrackerProviders {
54
67
  /** Already guarded by the host's existing consent policy; never guard a second time. */
55
- productAnalytics?: ProductAnalyticsPort | undefined;
68
+ productAnalytics?: CapturePort | undefined;
56
69
  observability?: ObservabilityPort | undefined;
57
70
  }
58
71
  export interface TrackerOptions {
59
72
  warn?: ((message: string) => void) | undefined;
60
73
  }
74
+ export {};
61
75
  //# sourceMappingURL=tracker-types.d.ts.map
@@ -1,4 +1,3 @@
1
- import { isNoopProductAnalytics } from "@jini-ai/analytics/product";
2
1
  import { createNoopTracker } from "./tracker-noop.js";
3
2
  import { isNoopObservabilityPort } from "./noop.js";
4
3
  import { combineObservabilityPorts } from "./fanout.js";
@@ -58,7 +57,8 @@ function thrownOutcome({ options, outcome, error }, _options = {}) {
58
57
  * @complexity O(1) facade state; delivery/redaction costs remain with the existing ports.
59
58
  */
60
59
  export function createTracker(required, optional = {}) {
61
- if ((!required.observability || isNoopObservabilityPort(required.observability)) && (!required.productAnalytics || isNoopProductAnalytics(required.productAnalytics)))
60
+ // Supplied analytics ports own their no-op behavior; their optional package must never load here.
61
+ if (!required.productAnalytics && (!required.observability || isNoopObservabilityPort(required.observability)))
62
62
  return createNoopTracker({});
63
63
  const failed = createTrackerWarning({}, optional);
64
64
  const observability = combineObservabilityPorts({ ports: required.observability ? [required.observability] : [] }, { onFailure: failed });
@@ -100,12 +100,15 @@ export function createTracker(required, optional = {}) {
100
100
  }
101
101
  return {
102
102
  activeTraceIds: (_required = {}, _optional = {}) => observability.activeTraceIds?.(),
103
- capture(input, options = {}) { try {
104
- return Promise.resolve(required.productAnalytics?.capture({ ...input, ...options })).catch(failed);
105
- }
106
- catch {
107
- failed();
108
- } },
103
+ capture(input, options = {}) {
104
+ try {
105
+ return Promise.resolve(required.productAnalytics?.capture({ ...input, ...options })).catch(failed);
106
+ }
107
+ catch {
108
+ failed();
109
+ return undefined;
110
+ }
111
+ },
109
112
  metric(input, options = {}) { observability.metric(input, options); },
110
113
  error,
111
114
  trace: trace,
package/dist/redaction.js CHANGED
@@ -17,7 +17,8 @@ const BARE_SECRET_RE = /(^|[\s,;])(access_token|refresh_token|id_token|api[_-]?k
17
17
  // Character class covers RFC 6750 token68 (ALPHA / DIGIT / "-" / "." / "_"
18
18
  // / "~" / "+" / "/" / "=") plus ":" for Basic credentials. Missing "~"
19
19
  // previously left tokens like `Bearer abcd~efgh` partially exposed.
20
- const HTTP_AUTH_SCHEME_RE = /\b(Bearer|Token|Basic)\s+([A-Za-z0-9._~\-+/=:]{4,})/gi;
20
+ // Case-insensitive, so the class needs only one letter case.
21
+ const HTTP_AUTH_SCHEME_RE = /\b(Bearer|Token|Basic)\s+([a-z0-9._~\-+/=:]{4,})/gi;
21
22
  const REDACTED = "[REDACTED]";
22
23
  function redactJsonObject({ value }, opts = {}) {
23
24
  const out = {};
@@ -81,8 +82,13 @@ export function redactJsonText({ text }, opts = {}) {
81
82
  // Each alternative consumes one path in a forward scan; no nested repetitions or wildcard retries.
82
83
  // `<`/`>` stay inside a plain path: an upstream username redaction yields `/Users/<USER>/…`, whose
83
84
  // tail would otherwise escape after a masked `/Users/` prefix.
84
- const LOCAL_PATH_RE = /(["'(])((?:file:\/\/|[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)[^"'()\r\n]*)(["')])|(^|[\s="'(<[\]{},;`])((?:file:\/\/|[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)[^\s"'`()[\]{},;]*)/g;
85
- const QUOTED_LOCAL_PATH_RE = /(["'])((?:file:\/\/|[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)[^"'\r\n]*)\1/g;
85
+ // How a local path starts: a file URL, a drive letter, a UNC prefix, a home `~`, or a root `/`.
86
+ const BACKTICK = "`";
87
+ const LOCAL_PATH_START = String.raw `(?:file:\/\/|[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)`;
88
+ const DELIMITED_LOCAL_PATH = String.raw `(["'(])(${LOCAL_PATH_START}[^"'()\r\n]*)(["')])`;
89
+ const BARE_LOCAL_PATH = String.raw `(^|[\s="'(<[\]{},;${BACKTICK}])(${LOCAL_PATH_START}[^\s"'${BACKTICK}()[\]{},;]*)`;
90
+ const LOCAL_PATH_RE = new RegExp(`${DELIMITED_LOCAL_PATH}|${BARE_LOCAL_PATH}`, "g");
91
+ const QUOTED_LOCAL_PATH_RE = new RegExp(String.raw `(["'])(${LOCAL_PATH_START}[^"'\r\n]*)\1`, "g");
86
92
  /** Decode local file URLs independently of the host OS; invalid URLs are always masked. O(n). */
87
93
  function decodedLocalPath({ value }, _options = {}) {
88
94
  // Treat ~ as a lexical root, never expand it using the current user's home directory.
package/dist/sources.js CHANGED
@@ -30,15 +30,11 @@ const DEFAULT_CRASH_DIRS_DARWIN = [
30
30
  async function crashReportsInDirectory({ dir, matches, cutoff, filesystem }, _options = {}) {
31
31
  const entries = await readDirectorySafe({ path: dir, filesystem });
32
32
  const found = [];
33
- for (const { name: entry } of entries) {
34
- const lower = entry.toLowerCase();
35
- if (!matches.some((needle) => lower.includes(needle)))
36
- continue;
33
+ const matching = entries.filter(({ name }) => matches.some((needle) => name.toLowerCase().includes(needle)));
34
+ for (const { name: entry } of matching) {
37
35
  const absolutePath = join(dir, entry);
38
36
  const info = await statSafe({ path: absolutePath, filesystem });
39
- if (!info || !info.isFile)
40
- continue;
41
- if (info.mtimeMs < cutoff)
37
+ if (!info?.isFile || info.mtimeMs < cutoff)
42
38
  continue;
43
39
  found.push({ absolutePath, mtimeMs: info.mtimeMs, name: entry });
44
40
  }
@@ -178,13 +178,13 @@ function partitionRequestedPaths(paths) {
178
178
  const normalized = normalizeSitePath({ raw });
179
179
  if (!normalized.ok) {
180
180
  skipped.push(skip(raw, "invalid-path", `${normalized.message} (${normalized.reason})`));
181
- continue;
182
181
  }
183
- if (accepted.length >= SITE_EVIDENCE_LIMITS.maxPagesPerCall) {
182
+ else if (accepted.length >= SITE_EVIDENCE_LIMITS.maxPagesPerCall) {
184
183
  skipped.push(skip(normalized.path, "page-cap", `this call already accepted the maximum of ${SITE_EVIDENCE_LIMITS.maxPagesPerCall} pages — request the remaining paths in a follow-up call`));
185
- continue;
186
184
  }
187
- accepted.push(normalized.path);
185
+ else {
186
+ accepted.push(normalized.path);
187
+ }
188
188
  }
189
189
  return { accepted, skipped };
190
190
  }
@@ -20,9 +20,11 @@ export async function collectPagePerformance(_required, _options = {}) {
20
20
  counts.hiddenPreElements++;
21
21
  }
22
22
  function countNode(node) {
23
- if (node.nodeType === Node.ELEMENT_NODE)
23
+ if (node.nodeType === Node.ELEMENT_NODE) {
24
24
  countElement(node);
25
- else if (node.nodeType === Node.TEXT_NODE && node.parentElement?.closest('pre')?.getClientRects().length === 0) {
25
+ return;
26
+ }
27
+ if (node.nodeType === Node.TEXT_NODE && node.parentElement?.closest('pre')?.getClientRects().length === 0) {
26
28
  // Count text once, without copying hidden output into model context.
27
29
  counts.hiddenPreTextChars += node.textContent?.length ?? 0;
28
30
  }
@@ -37,13 +37,10 @@ export function collectPageStructure(limits) {
37
37
  let depth = 0;
38
38
  while (current && current.nodeType === 1 && depth < 5) {
39
39
  const terminal = terminalSegment(current);
40
- if (terminal !== null) {
41
- parts.unshift(terminal);
42
- break;
43
- }
44
40
  const parent = current.parentElement;
45
- if (!parent) {
46
- parts.unshift(current.tagName.toLowerCase());
41
+ // A uniquely addressable ancestor, or the root element, ends the selector.
42
+ if (terminal !== null || !parent) {
43
+ parts.unshift(terminal ?? current.tagName.toLowerCase());
47
44
  break;
48
45
  }
49
46
  parts.unshift(siblingSegment(current, parent));
@@ -146,7 +143,8 @@ export function collectPageStructure(limits) {
146
143
  for (const element of Array.from(document.querySelectorAll("h1,h2,h3,h4,h5,h6,[role='heading']"))) {
147
144
  const tagLevel = /^H([1-6])$/.exec(element.tagName);
148
145
  const ariaLevel = element.getAttribute("aria-level");
149
- const level = tagLevel ? Number(tagLevel[1]) : ariaLevel ? Number(ariaLevel) : 0;
146
+ // Number(null) and Number("") are both 0, the "no level" value.
147
+ const level = tagLevel ? Number(tagLevel[1]) : Number(ariaLevel);
150
148
  if (!Number.isFinite(level) || level === 0)
151
149
  continue;
152
150
  out.push({ level, selector: selectorFor(element), text: textOf(element, 160) });
@@ -298,17 +296,18 @@ export function collectPageStructure(limits) {
298
296
  function collectContrastSamples() {
299
297
  const out = [];
300
298
  const candidates = Array.from(document.querySelectorAll(CONTRAST_CANDIDATE_SELECTOR));
299
+ const sampleOf = (element) => {
300
+ if (!hasOwnSampleableText(element))
301
+ return null;
302
+ const style = getComputedStyle(element);
303
+ return isRenderedVisible(element, style) ? contrastSampleFor(element, style) : null;
304
+ };
301
305
  for (const element of candidates) {
302
306
  if (out.length >= limits.maxContrastSamples) {
303
307
  truncated.push("contrastSamples");
304
308
  break;
305
309
  }
306
- if (!hasOwnSampleableText(element))
307
- continue;
308
- const style = getComputedStyle(element);
309
- if (!isRenderedVisible(element, style))
310
- continue;
311
- const sample = contrastSampleFor(element, style);
310
+ const sample = sampleOf(element);
312
311
  if (sample)
313
312
  out.push(sample);
314
313
  }
@@ -97,10 +97,14 @@ async function guardRequests({ context, budget, originPolicy, originBaseUrl }, {
97
97
  // (Public mode always has a router: renderPage refuses public rendering without one.)
98
98
  const blocked = offOrigin || (originPolicy !== "public" && !["GET", "HEAD"].includes(pending.method().toUpperCase()));
99
99
  const markBlocked = onRequest?.({ route, blocked });
100
- if (blocked)
101
- return route.abort("blockedbyclient").catch(() => { });
102
- if (router)
103
- return routeThroughRouter({ router, route }, { markBlocked });
100
+ if (blocked) {
101
+ await route.abort("blockedbyclient").catch(() => { });
102
+ return;
103
+ }
104
+ if (router) {
105
+ await routeThroughRouter({ router, route }, { markBlocked });
106
+ return;
107
+ }
104
108
  // Trusted own-origin evidence retains browser cookies, but never posts preferences or forms.
105
109
  if (!route.continue)
106
110
  throw new Error("Own-origin browser route cannot continue: the route port has no continue()");
@@ -146,18 +150,22 @@ function nextHopAfterFailedGoto({ error, hop, target, refusedOrigin }, { router
146
150
  }
147
151
  throw error;
148
152
  }
153
+ /** A selector waits until visible; a number is a settle delay in seconds (zero or less waits for nothing). */
154
+ async function waitForSelectorOrDelay({ page, budget, waitFor }) {
155
+ if (typeof waitFor === "number") {
156
+ if (waitFor > 0)
157
+ await budget.run({ work: () => page.waitForTimeout(waitFor * 1000) });
158
+ return;
159
+ }
160
+ if (!page.waitForSelector)
161
+ throw new Error(`Rendering cannot wait for selector "${waitFor}": this browser port has no waitForSelector`);
162
+ await budget.run({ work: () => page.waitForSelector(waitFor, { state: "visible", timeout: budget.remainingMs() }) });
163
+ }
149
164
  /** Cookie dismissal, the selector/settle strategy and the best-effort load wait, all within the page budget. */
150
165
  async function settlePage({ page, budget, signal }, options) {
151
166
  const { waitFor = 1.2, dismissCookieBanners: dismiss = false } = options;
152
167
  const dismissed = dismiss && await dismissCookieBanners({ page, budget });
153
- if (typeof waitFor === "string") {
154
- if (!page.waitForSelector)
155
- throw new Error(`Rendering cannot wait for selector "${waitFor}": this browser port has no waitForSelector`);
156
- await budget.run({ work: () => page.waitForSelector(waitFor, { state: "visible", timeout: budget.remainingMs() }) });
157
- }
158
- else if (waitFor > 0) {
159
- await budget.run({ work: () => page.waitForTimeout(waitFor * 1000) });
160
- }
168
+ await waitForSelectorOrDelay({ page, budget, waitFor });
161
169
  await waitForLoad({ page, budget, signal }, options);
162
170
  // Hydrated consent widgets can arrive during the settle/selector wait.
163
171
  if (dismiss && !dismissed && await dismissCookieBanners({ page, budget })) {
@@ -78,7 +78,9 @@ function redirectTarget(resource, base) {
78
78
  function redirectedRequest({ status, method, body, headers }) {
79
79
  if (status !== 303 && !([301, 302].includes(status) && method.toUpperCase() === "POST"))
80
80
  return { method, body, headers };
81
- const { "content-type": _dropped, ...kept } = headers;
81
+ // The body is dropped, so its content type goes with it.
82
+ const kept = { ...headers };
83
+ delete kept["content-type"];
82
84
  return { method: "GET", body: undefined, headers: kept };
83
85
  }
84
86
  /** A counting semaphore: at most `limit` holders, FIFO waiters. */
@@ -206,6 +208,20 @@ export function createRequestRouter({ httpClient, ownSiteFetch, allowedOrigins,
206
208
  },
207
209
  };
208
210
  }
211
+ /** Reads chunks until the stream ends or the next one would pass `maxBytes` (then `truncated`). */
212
+ async function readCapped(reader, maxBytes) {
213
+ const chunks = [];
214
+ let size = 0;
215
+ let next = await reader.read();
216
+ while (!next.done) {
217
+ size += next.value.byteLength;
218
+ if (size > maxBytes)
219
+ return { chunks, truncated: true };
220
+ chunks.push(Buffer.from(next.value));
221
+ next = await reader.read();
222
+ }
223
+ return { chunks, truncated: false };
224
+ }
209
225
  /**
210
226
  * The default {@link OwnSiteFetch}: the global `fetch`, redirects returned rather than followed (so
211
227
  * the router re-decides the next hop), body read up to `maxBytes`. Overflow cancels the stream;
@@ -219,23 +235,11 @@ export const fetchOwnSiteResource = async ({ url, method, headers }, { signal, m
219
235
  const cookies = response.headers.getSetCookie();
220
236
  if (cookies.length)
221
237
  responseHeaders["set-cookie"] = cookies.join("\n");
222
- const chunks = [];
223
- let size = 0;
224
- let truncated = false;
238
+ let read = { chunks: [], truncated: false };
225
239
  if (response.body) {
226
240
  const reader = response.body.getReader();
227
241
  try {
228
- for (;;) {
229
- const { done, value } = await reader.read();
230
- if (done)
231
- break;
232
- size += value.byteLength;
233
- if (size > maxBytes) {
234
- truncated = true;
235
- break;
236
- }
237
- chunks.push(Buffer.from(value));
238
- }
242
+ read = await readCapped(reader, maxBytes);
239
243
  }
240
244
  finally {
241
245
  // Cleanup must not replace the original read error when the stream is already errored.
@@ -243,6 +247,6 @@ export const fetchOwnSiteResource = async ({ url, method, headers }, { signal, m
243
247
  reader.releaseLock();
244
248
  }
245
249
  }
246
- return { status: response.status, headers: responseHeaders, body: Buffer.concat(chunks), truncated };
250
+ return { status: response.status, headers: responseHeaders, body: Buffer.concat(read.chunks), truncated: read.truncated };
247
251
  };
248
252
  //# sourceMappingURL=request-guard.js.map
@@ -1,33 +1,3 @@
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
1
  /** Caller-owned origin verification data; no origin is derived from request input. */
32
2
  export interface VerifiedOrigin {
33
3
  readonly scheme: "http" | "https";
@@ -1,3 +1,34 @@
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
+ import { trimCharsEnd, trimCharsStart } from "@jini-ai/core/primitives";
1
32
  /** Longest site-relative path this tool will accept. Well past any real page URL; exists so a
2
33
  * pathological input cannot be handed to a browser at all. */
3
34
  const MAX_PATH_LENGTH = 2048;
@@ -115,8 +146,8 @@ export function verifiedOriginToBaseUrl({ origin }) {
115
146
  */
116
147
  export function resolveSameOriginUrl({ baseUrl, path }) {
117
148
  const base = new URL(baseUrl);
118
- const basePath = base.pathname.replace(/\/+$/, "");
119
- const rootRelative = `/${path.replace(/^\/+/, "")}`;
149
+ const basePath = trimCharsEnd({ text: base.pathname, chars: "/" });
150
+ const rootRelative = `/${trimCharsStart({ text: path, chars: "/" })}`;
120
151
  return new URL(`${basePath}${rootRelative}`, base.origin).toString();
121
152
  }
122
153
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/diagnostics",
3
- "version": "0.6.15-rc.2",
3
+ "version": "0.6.15",
4
4
  "description": "Diagnostics-bundle tooling: JSON/text secret redaction, log-source collection, manifest building, and zip packaging for support exports.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -82,21 +82,17 @@
82
82
  "devDependencies": {
83
83
  "@vitest/coverage-v8": "^2.1.9",
84
84
  "jszip": "^3.10.1",
85
- "@jini-ai/core": "^0.6.15-rc.2",
86
- "@jini-ai/analytics": "^0.6.15-rc.2"
85
+ "@jini-ai/analytics": "^0.6.15",
86
+ "@jini-ai/core": "^0.6.15"
87
87
  },
88
88
  "dependencies": {
89
89
  "js-tokens": "^9.0.1",
90
- "@jini-ai/core": "^0.6.15-rc.2"
90
+ "@jini-ai/core": "^0.6.15"
91
91
  },
92
92
  "peerDependencies": {
93
- "@jini-ai/analytics": "^0.6.15-rc.2",
94
93
  "jszip": "^3.10.1"
95
94
  },
96
95
  "peerDependenciesMeta": {
97
- "@jini-ai/analytics": {
98
- "optional": true
99
- },
100
96
  "jszip": {
101
97
  "optional": true
102
98
  }