@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,120 @@
1
+ import { redactSecretShapes } from '../redaction/secrets-only.js';
2
+ /** A low-cardinality error label: a SCREAMING_CASE code (ECONNREFUSED, SQLITE_BUSY), else the class
3
+ * name. Messages are never exported: they carry SQL fragments, hostnames, emails, even credentials. */
4
+ export function errorType(error) {
5
+ const code = error?.code;
6
+ if (typeof code === 'string' && /^[A-Z][A-Z0-9_]{1,63}$/.test(code))
7
+ return code;
8
+ if (error instanceof Error)
9
+ return error.name;
10
+ return typeof error;
11
+ }
12
+ /** Query and fragment are dropped (tokens ride there most often); secret-shaped path values are
13
+ * blanked. Ids stay: an operator searches by them, and a route pattern alone cannot name a record. */
14
+ export function redactRequestTarget(path) {
15
+ return redactSecretShapes({ text: path.replace(/[?#][\s\S]*$/, ''), policy: {} }).text;
16
+ }
17
+ /** Scheme, host and explicit port only. Paths carry bot tokens and signed-URL keys; userinfo carries passwords. */
18
+ export function outboundTargetAttributes(url) {
19
+ let parsed;
20
+ try {
21
+ parsed = new URL(url);
22
+ }
23
+ catch {
24
+ return { 'server.address': 'invalid-url' };
25
+ }
26
+ return {
27
+ 'url.scheme': parsed.protocol.replace(/:$/, ''), 'server.address': parsed.hostname,
28
+ ...(parsed.port ? { 'server.port': Number(parsed.port) } : {}),
29
+ };
30
+ }
31
+ // Interrupted means the run died with its process; canceled and abandoned are not proven failures.
32
+ const FAILED_RUN_STATUSES = new Set(['failed', 'interrupted']);
33
+ /** Wraps an end handler so a second end() is ignored. */
34
+ function once(handler) {
35
+ let ended = false;
36
+ return (outcome) => { if (ended)
37
+ return; ended = true; handler(outcome); };
38
+ }
39
+ /** Sets attributes, then the error label, status and exception event (type only), then ends. */
40
+ function finish({ span, attributes }, { failure, error } = {}) {
41
+ for (const [name, value] of Object.entries(attributes))
42
+ span.setAttribute({ name, value });
43
+ if (failure !== undefined) {
44
+ span.setAttribute({ name: 'error.type', value: failure });
45
+ span.setStatus({ code: 'error', description: failure });
46
+ if (error !== undefined)
47
+ span.addEvent({ name: 'exception', attributes: { 'exception.type': failure } });
48
+ }
49
+ span.end({});
50
+ }
51
+ /** Builds request, DB, outbound and agent-run spans through injected provider/exporter factories.
52
+ * @param required Explicit config and structural factories. Hosts wrap their SDK here.
53
+ * @param options Optional host scope storage; with it, spans started inside a tracker's run() are its children.
54
+ * @returns One adapter whose spans end once, with final names, redacted attributes and error status.
55
+ * @throws Provider/exporter errors propagate during setup. No globals or SDK imports are used.
56
+ */
57
+ export function createOtelObservabilityPort({ config, exporterFactory, tracerProviderFactory }, { scope } = {}) {
58
+ const exporter = exporterFactory.create({ endpoint: config.endpoint });
59
+ const provider = tracerProviderFactory.create({ serviceName: config.serviceName, exporter });
60
+ const tracer = provider.getTracer({ name: config.tracerName });
61
+ function start({ name, kind, attributes }, { root = false } = {}) {
62
+ const parent = root ? undefined : scope?.active();
63
+ return tracer.startSpan({ name, kind, attributes }, parent ? { parent } : {});
64
+ }
65
+ function runIn(span) {
66
+ return (fn) => (scope ? scope.run({ span, fn }) : fn());
67
+ }
68
+ return {
69
+ trackRequest(input, { requestId } = {}) {
70
+ // The id the response echoes is recorded on the span, so a reported id finds its trace.
71
+ const span = start({ name: input.method, kind: 'server', attributes: {
72
+ 'http.method': input.method, 'http.target': redactRequestTarget(input.path), ...(requestId ? { 'http.request.id': requestId } : {}),
73
+ } });
74
+ return { ...(requestId ? { requestId } : {}), run: runIn(span), end: once((outcome) => {
75
+ // Routing finishes after startSpan, so open with a provisional name and assign the final
76
+ // pattern at end. The consumer port needs no separate rename operation to express that timing.
77
+ span.updateName({ name: `${input.method} ${outcome.routePattern}` });
78
+ span.setAttribute({ name: 'http.route', value: outcome.routePattern });
79
+ span.setAttribute({ name: 'http.status_code', value: outcome.statusCode });
80
+ if (outcome.statusCode >= 500)
81
+ span.setStatus({ code: 'error' });
82
+ span.end({});
83
+ }) };
84
+ },
85
+ trackDbQuery({ system }) {
86
+ const span = start({ name: 'db', kind: 'client', attributes: { 'db.system.name': system } });
87
+ return { run: runIn(span), end: once(({ operation, table, error }) => {
88
+ // Same provisional-name timing as requests: the query is built inside the tracked body.
89
+ const op = operation.toUpperCase();
90
+ span.updateName({ name: table ? `${op} ${table}` : op });
91
+ finish({ span, attributes: { 'db.operation.name': op, ...(table ? { 'db.collection.name': table } : {}) } }, error !== undefined ? { failure: errorType(error), error } : {});
92
+ }) };
93
+ },
94
+ trackOutboundCall({ method, url }) {
95
+ const target = outboundTargetAttributes(url);
96
+ const span = start({ name: `${method} ${target['server.address']}`, kind: 'client', attributes: { 'http.request.method': method, ...target } });
97
+ return { run: runIn(span), end: once(({ statusCode, error }) => {
98
+ const attributes = statusCode !== undefined ? { 'http.response.status_code': statusCode } : {};
99
+ if (error !== undefined)
100
+ return finish({ span, attributes }, { failure: errorType(error), error });
101
+ // Client-span semantics: a 4xx is this caller's failure, unlike a server span's 4xx.
102
+ finish({ span, attributes }, statusCode !== undefined && statusCode >= 400 ? { failure: String(statusCode) } : {});
103
+ }) };
104
+ },
105
+ trackAgentRun({ runId }, { conversationId, agentName } = {}) {
106
+ // A run outlives the request that started it, so it is its own trace rather than a long child.
107
+ const span = start({ name: agentName ? `invoke_agent ${agentName}` : 'invoke_agent', kind: 'internal', attributes: {
108
+ 'gen_ai.operation.name': 'invoke_agent', ...(agentName ? { 'gen_ai.agent.name': agentName } : {}),
109
+ ...(conversationId ? { 'gen_ai.conversation.id': conversationId } : {}), 'agent.run.id': runId,
110
+ } }, { root: true });
111
+ return { run: runIn(span), end: once(({ status, error }) => {
112
+ const attributes = { 'agent.run.status': status };
113
+ if (error !== undefined)
114
+ return finish({ span, attributes }, { failure: errorType(error), error });
115
+ finish({ span, attributes }, FAILED_RUN_STATUSES.has(status) ? { failure: status } : {});
116
+ }) };
117
+ },
118
+ };
119
+ }
120
+ //# sourceMappingURL=otel.js.map
@@ -0,0 +1,150 @@
1
+ /** Vendor-neutral inbound request lifecycle. Route patterns, rather than raw paths, label metrics. */
2
+ /**
3
+ * Consumers speak in request lifecycle terms rather than Span/Tracer SDK types. That permits
4
+ * replacing the instrumentation system itself, not merely its exporter backend. Add signals
5
+ * only against real instrumentation call sites; guessed DB/outbound/agent shapes would couple
6
+ * consumers to contracts whose lifecycle has not yet been established.
7
+ * The DB/outbound/agent signals below were each shaped after their first real call site: the
8
+ * storage kernel's run/transaction body, the guarded HTTP client's send, and a host's agent-run
9
+ * watcher. Inputs carry ids and fixed labels only; adapters own redaction of anything raw.
10
+ */
11
+ export interface RequestTrackingInput {
12
+ method: string;
13
+ path: string;
14
+ }
15
+ export interface RequestTrackingOptions {
16
+ requestId?: string;
17
+ }
18
+ /** The mount-aware pattern is available only after routing; raw paths are known at request start.
19
+ * Use a fixed 'unmatched' label for misses: attacker-controlled paths would make grouping unbounded. */
20
+ export interface RequestTrackingOutcome {
21
+ statusCode: number;
22
+ routePattern: string;
23
+ }
24
+ /** Runs work inside a tracker's scope, so signals that work starts are attributed to it. */
25
+ export interface TrackerScope {
26
+ run<T>(fn: () => T): T;
27
+ }
28
+ export interface RequestTracker {
29
+ readonly requestId?: string;
30
+ end(outcome: RequestTrackingOutcome): void;
31
+ /** Optional so adapters written before scoping still satisfy the port; callers fall back to fn(). */
32
+ run?<T>(fn: () => T): T;
33
+ }
34
+ /** `system` is the engine family (`sqlite`, `postgresql`); statement text never crosses the port. */
35
+ export interface DbQueryTrackingInput {
36
+ system: string;
37
+ }
38
+ /** Like a route pattern, the operation and table are known only once the query has been built. */
39
+ export interface DbQueryTrackingOutcome {
40
+ operation: string;
41
+ table?: string;
42
+ error?: unknown;
43
+ }
44
+ export interface DbQueryTracker extends TrackerScope {
45
+ end(outcome: DbQueryTrackingOutcome): void;
46
+ }
47
+ /** The raw URL is handed over whole; adapters keep scheme/host/port and drop path, query and userinfo. */
48
+ export interface OutboundCallTrackingInput {
49
+ method: string;
50
+ url: string;
51
+ }
52
+ /** `statusCode` when a response arrived, `error` when the call failed before one did. */
53
+ export interface OutboundCallTrackingOutcome {
54
+ statusCode?: number;
55
+ error?: unknown;
56
+ }
57
+ export interface OutboundCallTracker extends TrackerScope {
58
+ end(outcome: OutboundCallTrackingOutcome): void;
59
+ }
60
+ export interface AgentRunTrackingInput {
61
+ runId: string;
62
+ }
63
+ export interface AgentRunTrackingOptions {
64
+ conversationId?: string;
65
+ agentName?: string;
66
+ }
67
+ /** `interrupted`: the run vanished (its process restarted). `abandoned`: the watcher gave up unproven. */
68
+ export type AgentRunStatus = 'succeeded' | 'failed' | 'canceled' | 'interrupted' | 'abandoned';
69
+ export interface AgentRunTrackingOutcome {
70
+ status: AgentRunStatus;
71
+ error?: unknown;
72
+ }
73
+ export interface AgentRunTracker extends TrackerScope {
74
+ end(outcome: AgentRunTrackingOutcome): void;
75
+ }
76
+ export interface ObservabilityPort {
77
+ trackRequest(input: RequestTrackingInput, options?: RequestTrackingOptions): RequestTracker;
78
+ trackDbQuery(input: DbQueryTrackingInput): DbQueryTracker;
79
+ trackOutboundCall(input: OutboundCallTrackingInput): OutboundCallTracker;
80
+ trackAgentRun(input: AgentRunTrackingInput, options?: AgentRunTrackingOptions): AgentRunTracker;
81
+ }
82
+ export interface RequestObservation extends RequestTrackingOutcome {
83
+ requestId: string;
84
+ method: string;
85
+ durationMs: number;
86
+ }
87
+ export interface RequestLogPort {
88
+ log(event: RequestObservation): void;
89
+ }
90
+ export interface RequestMetricsPort {
91
+ recordRequest(event: RequestObservation): void;
92
+ }
93
+ export interface RequestIdGenerator {
94
+ generate(required: Record<string, never>): string;
95
+ }
96
+ /** Structural SDK adapters are host-owned; no provider registration or ambient config is used. */
97
+ export interface TraceSpanPort {
98
+ updateName(required: {
99
+ name: string;
100
+ }): void;
101
+ setAttribute(required: {
102
+ name: string;
103
+ value: string | number;
104
+ }): void;
105
+ setStatus(required: {
106
+ code: 'error';
107
+ description?: string;
108
+ }): void;
109
+ addEvent(required: {
110
+ name: string;
111
+ attributes: Record<string, string | number>;
112
+ }): void;
113
+ end(required: Record<string, never>): void;
114
+ }
115
+ export type TraceSpanKind = 'server' | 'client' | 'internal';
116
+ export interface TracerPort {
117
+ /** `parent` is a span this tracer returned earlier; absent means a root span. */
118
+ startSpan(required: {
119
+ name: string;
120
+ kind: TraceSpanKind;
121
+ attributes: Record<string, string | number>;
122
+ }, optional?: {
123
+ parent?: TraceSpanPort;
124
+ }): TraceSpanPort;
125
+ }
126
+ /** Host-owned active-span storage (Node: AsyncLocalStorage). Without one, every span is a root. */
127
+ export interface SpanScopePort {
128
+ active(): TraceSpanPort | undefined;
129
+ run<T>(required: {
130
+ span: TraceSpanPort;
131
+ fn: () => T;
132
+ }): T;
133
+ }
134
+ export interface TracerProviderPort {
135
+ getTracer(required: {
136
+ name: string;
137
+ }): TracerPort;
138
+ }
139
+ export interface ExporterFactory {
140
+ create(required: {
141
+ endpoint: string;
142
+ }): unknown;
143
+ }
144
+ export interface TracerProviderFactory {
145
+ create(required: {
146
+ serviceName: string;
147
+ exporter: unknown;
148
+ }): TracerProviderPort;
149
+ }
150
+ //# sourceMappingURL=ports.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1,45 @@
1
+ import type { Clock } from "@jini-ai/core/primitives";
2
+ import type { MachineInfo } from "./types.js";
3
+ /** Host effects used by bundle collection. Core functions never read ambient host state. */
4
+ export interface DiagnosticsFilesystemPort {
5
+ /** Read the full file or a bounded trailing window without loading the full large file. */
6
+ readFile(required: {
7
+ absolutePath: string;
8
+ }, optional?: {
9
+ tailBytes?: number | undefined;
10
+ }): Promise<Buffer>;
11
+ readDirectory(required: {
12
+ absolutePath: string;
13
+ }): Promise<Array<{
14
+ name: string;
15
+ isDirectory: boolean;
16
+ }>>;
17
+ stat(required: {
18
+ absolutePath: string;
19
+ }): Promise<{
20
+ isFile: boolean;
21
+ mtimeMs: number;
22
+ }>;
23
+ }
24
+ export interface DiagnosticsSystemPort {
25
+ platform(required: Record<string, never>): string;
26
+ machineInfo(required: Record<string, never>): Omit<MachineInfo, "username">;
27
+ }
28
+ export interface DiagnosticsArchivePort {
29
+ file(required: {
30
+ name: string;
31
+ content: string;
32
+ }): void;
33
+ generate(required: Record<string, never>): Promise<Buffer>;
34
+ }
35
+ export interface DiagnosticsArchiveFactoryPort {
36
+ /** Every invocation returns a fresh archive so successive exports cannot share files. */
37
+ create(required: Record<string, never>): DiagnosticsArchivePort;
38
+ }
39
+ export interface DiagnosticsPorts {
40
+ filesystem: DiagnosticsFilesystemPort;
41
+ clock: Clock;
42
+ system: DiagnosticsSystemPort;
43
+ archiveFactory: DiagnosticsArchiveFactoryPort;
44
+ }
45
+ //# sourceMappingURL=ports.d.ts.map
package/dist/ports.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1,44 @@
1
+ /** Secret-only error-display policy. Preserves paths, network addresses, emails, timestamps,
2
+ * tool IDs and ordinary prose. Ordered rules are idempotent; product formats come from policy. */
3
+ /** One (text in, text + count out) redaction pass. `redactions` is the number of values blanked —
4
+ * zero for text with nothing secret-shaped in it. */
5
+ export interface SecretRedaction {
6
+ readonly text: string;
7
+ readonly redactions: number;
8
+ }
9
+ /** One ordered rule: a global pattern and how to rebuild its replacement from the match's capture
10
+ * groups. Private — callers only ever see {@link redactSecretShapes}'s aggregate result. */
11
+ export interface RedactionRule {
12
+ readonly kind: string;
13
+ readonly pattern: RegExp;
14
+ readonly replacement: (required: {
15
+ match: readonly (string | undefined)[];
16
+ }) => string;
17
+ }
18
+ /**
19
+ * Blanks every secret-shaped VALUE in `text`, leaving everything else — including IPs, absolute
20
+ * paths, emails, tool ids, and ordinary prose — untouched.
21
+ *
22
+ * @param required - Text and the caller's redaction policy. The text is arbitrary error text. Never re-interpreted as anything other than plain text (no
23
+ * parsing, no partial JSON awareness).
24
+ * @returns The redacted text plus how many values were blanked. `redactions: 0` means nothing
25
+ * secret-shaped was found — the returned `text` is then reference-identical in content (though
26
+ * not necessarily the same string instance) to the input.
27
+ * @complexity O(r*n): each of the fixed, small rule count `r` makes one linear pass over the
28
+ * (at most `n`-length) text. Rules only ever shrink or hold text length steady, so the total work
29
+ * is bounded by `r` passes over the original length.
30
+ * @example
31
+ * redactSecretShapes({ text: "password=hunter2hunter2", policy: {} }); // { text: "password=[REDACTED:labeled_secret]", redactions: 1 }
32
+ * @overallScore 100
33
+ */
34
+ export interface RedactionPolicy {
35
+ /** Rules for caller-owned formats, applied after vendor/JWT rules and before bearer/labeled rules. Must be idempotent. */
36
+ readonly additionalRules?: readonly RedactionRule[];
37
+ }
38
+ /** Redacts credential values with a required policy; returns text and replacement count. */
39
+ export declare function redactSecretShapes({ text, policy }: {
40
+ text: string;
41
+ policy: RedactionPolicy;
42
+ }): SecretRedaction;
43
+ export { SECRET_SHAPE_PATTERNS as SECRET_PATTERNS, PEM_PATTERN_NAME, type SecretShapePattern as SecretPattern } from "@jini-ai/core";
44
+ //# sourceMappingURL=secrets-only.d.ts.map
@@ -0,0 +1,179 @@
1
+ import { SECRET_SHAPE_PATTERNS } from "@jini-ai/core";
2
+ /** Adds the `g` flag when a source pattern (e.g. one of {@link SECRET_SHAPE_PATTERNS}, authored for a
3
+ * single `RegExp.exec` caller) does not already carry it — `String.replace` only replaces every
4
+ * match when the pattern is global. Mirrors `secret-scan-guard.ts`'s own `scanTextForSecrets`. */
5
+ function withGlobalFlag(flags) {
6
+ return flags.includes("g") ? flags : `${flags}g`;
7
+ }
8
+ /** {@link SECRET_SHAPE_PATTERNS} reused for redaction — see this file's header. Each vendor pattern is
9
+ * wrapped in the same `RedactionRule` shape as every rule below, so the loop in
10
+ * {@link redactSecretShapes} treats them identically. */
11
+ const REUSED_CREDENTIAL_RULES = SECRET_SHAPE_PATTERNS.map((vendor) => ({
12
+ kind: "credential",
13
+ pattern: new RegExp(vendor.pattern.source, withGlobalFlag(vendor.pattern.flags)),
14
+ replacement: () => "[REDACTED:credential]",
15
+ }));
16
+ /** Labels a bare `label=value`, `"label":"value"`, or `?label=value` assignment may carry — see
17
+ * this file's header's Must NOT change list for why a bare prose colon (`password: must be...`)
18
+ * is deliberately excluded from all three shapes below. */
19
+ 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";
20
+ /**
21
+ * Every rule this module applies, in order. Order matters: `private_key` must run before the
22
+ * reused header-only PEM pattern (inside {@link REUSED_CREDENTIAL_RULES}) so a full block is
23
+ * blanked as one unit rather than leaving its header re-matched separately; `auth_header` must run
24
+ * before the bare `bearer_token` rule so a header's own scheme+token is not ALSO caught by the
25
+ * looser bare-token rule.
26
+ */
27
+ const REDACTION_RULES = [
28
+ {
29
+ kind: "private_key",
30
+ // Matches a full PEM block, including a truncated one with no `-----END-----` line (the
31
+ // `$` alternative). `\1` backreferences the captured key type (e.g. "RSA ") so a
32
+ // "BEGIN RSA PRIVATE KEY" block cannot be closed by an unrelated "END EC PRIVATE KEY" line.
33
+ pattern: /-----BEGIN ([A-Z ]*)PRIVATE KEY-----[\s\S]*?(?:-----END \1PRIVATE KEY-----|$)/g,
34
+ replacement: () => "[REDACTED:private_key]",
35
+ },
36
+ {
37
+ kind: "auth_header",
38
+ // The value is ONE token after an optional known scheme, never the rest of the line — a
39
+ // rest-of-line value would eat a trailing IP/cause in a message like `request failed
40
+ // (Authorization: Bearer <tok>): connect ECONNREFUSED 10.0.4.7:443`.
41
+ //
42
+ // Split into two non-overlapping alternatives (scheme+value vs. no-scheme+value) rather than
43
+ // one optional scheme group, for idempotency: with a single optional group, a second pass over
44
+ // already-redacted text (`Authorization: Bearer [REDACTED:auth_header]`) would fail the
45
+ // `(?!\[REDACTED)` lookahead on the "with scheme" attempt, backtrack the optional group away,
46
+ // and then match the bare word "Bearer" itself as the "value" — corrupting already-redacted
47
+ // text. The second alternative's own `(?!(?:Bearer|...)\s)` explicitly refuses to start on a
48
+ // scheme keyword, so when the first alternative's lookahead fails there is no fallback left to
49
+ // backtrack into, and the whole rule correctly finds no match on a second pass.
50
+ 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,
51
+ replacement: ({ match: m }) => `${m[1]}${m[2]}${m[3] ?? ""}[REDACTED:auth_header]`,
52
+ },
53
+ {
54
+ kind: "auth_header",
55
+ pattern: /(?<![A-Za-z0-9-])((?:set-)?cookie)(\s*[:=]\s*)(?!\[REDACTED)[^\s"'),;]+(?:;\s*[^\s"'),;]+)*/gi,
56
+ replacement: ({ match: m }) => `${m[1]}${m[2]}[REDACTED:auth_header]`,
57
+ },
58
+ {
59
+ kind: "url_credentials",
60
+ // Host, port, IP and path all stay — only the `user:pass@` half is replaced. The password class
61
+ // ADMITS `@` and backtracks to the LAST one before the authority ends (2026-09-16 security
62
+ // review): a password that was never percent-encoded — `postgres://u:p@ss4@host/db` — otherwise
63
+ // matched only up to its FIRST `@`, leaving the tail (`ss4`) of the password in the output.
64
+ // `?` is excluded so a query string's own `@` cannot drag the match past the authority.
65
+ pattern: /\b([a-z][a-z0-9+.-]*:\/\/)(?!\[REDACTED)[^\s/@:]+:[^\s/?]+@/gi,
66
+ replacement: ({ match: m }) => `${m[1]}[REDACTED:url_credentials]@`,
67
+ },
68
+ ...REUSED_CREDENTIAL_RULES,
69
+ {
70
+ kind: "stripe_key",
71
+ pattern: /(?<![A-Za-z0-9_])(?:sk|rk)_(?:live|test)_[0-9A-Za-z]{16,}/g,
72
+ replacement: () => "[REDACTED:stripe_key]",
73
+ },
74
+ {
75
+ kind: "stripe_key",
76
+ pattern: /(?<![A-Za-z0-9_])whsec_[A-Za-z0-9]{24,}/g,
77
+ replacement: () => "[REDACTED:stripe_key]",
78
+ },
79
+ {
80
+ kind: "github_token",
81
+ // Covers `ghs_`/`ghu_`/`ghr_` and lengths the exact-length SECRET_SHAPE_PATTERNS entries miss.
82
+ pattern: /(?<![A-Za-z0-9_])gh[pousr]_[A-Za-z0-9]{30,}/g,
83
+ replacement: () => "[REDACTED:github_token]",
84
+ },
85
+ {
86
+ kind: "openai_key",
87
+ pattern: /(?<![A-Za-z0-9_-])sk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{20,}/g,
88
+ replacement: () => "[REDACTED:openai_key]",
89
+ },
90
+ {
91
+ kind: "anthropic_key",
92
+ // SECRET_SHAPE_PATTERNS' own `sk-ant-` entry needs 90+ trailing characters, which is right for the
93
+ // repo-wide static check (a committed key is whole) but wrong here (2026-09-16 security review):
94
+ // an upstream 401 often echoes a TRUNCATED key, and `sk-[A-Za-z0-9]{40,}` cannot cover it either
95
+ // because `sk-ant-api03-` carries hyphens. The prefix alone is specific enough at this length.
96
+ pattern: /(?<![A-Za-z0-9_-])sk-ant-[A-Za-z0-9_-]{20,}/g,
97
+ replacement: () => "[REDACTED:anthropic_key]",
98
+ },
99
+ {
100
+ kind: "google_api_key",
101
+ pattern: /(?<![A-Za-z0-9_.-])AQ\.[A-Za-z0-9_-]{20,}/g,
102
+ replacement: () => "[REDACTED:google_api_key]",
103
+ },
104
+ {
105
+ kind: "aws_access_key",
106
+ pattern: /(?<![0-9A-Z])ASIA[0-9A-Z]{16}(?![0-9A-Z])/g,
107
+ replacement: () => "[REDACTED:aws_access_key]",
108
+ },
109
+ {
110
+ kind: "jwt",
111
+ pattern: /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,
112
+ replacement: () => "[REDACTED:jwt]",
113
+ },
114
+ {
115
+ kind: "bearer_token",
116
+ // Bare scheme outside a header line. The value must be at least 16 characters AND contain a
117
+ // digit, so ordinary prose ("Bearer token", "Basic authentication is not supported") is
118
+ // untouched.
119
+ pattern: /\b(Bearer|Basic|Token)\s+(?!\[REDACTED)(?=[A-Za-z0-9._~+/=:-]*\d)[A-Za-z0-9._~+/=:-]{16,}/g,
120
+ replacement: ({ match: m }) => `${m[1]} [REDACTED:bearer_token]`,
121
+ },
122
+ {
123
+ kind: "labeled_secret",
124
+ // Assignment form only — never a bare prose colon (`password: must be...` is untouched).
125
+ pattern: new RegExp(`(?<![A-Za-z0-9])(${LABELED_SECRET_LABELS})(\\s*=\\s*)(?!\\[REDACTED)([^\\s"'&,;})]+)`, "gi"),
126
+ replacement: ({ match: m }) => `${m[1]}${m[2]}[REDACTED:labeled_secret]`,
127
+ },
128
+ {
129
+ kind: "labeled_secret",
130
+ // JSON form: `"label":"value"`.
131
+ pattern: new RegExp(`"(${LABELED_SECRET_LABELS})"(\\s*:\\s*)"(?!\\[REDACTED)[^"]+"`, "gi"),
132
+ replacement: ({ match: m }) => `"${m[1]}"${m[2]}"[REDACTED:labeled_secret]"`,
133
+ },
134
+ {
135
+ kind: "labeled_secret",
136
+ // Colon form: `api_key: <value>`, `{ api_key: 'value' }`, `\"api_key\":\"value\"` (2026-09-16
137
+ // security review). The `=` and double-quoted-JSON rules above miss every one of these, and they
138
+ // are the shapes a real failure arrives in most often — `util.inspect` of a request config, a
139
+ // YAML/pretty-printed body, or a JSON error body embedded inside ANOTHER JSON string, where the
140
+ // escaped `\"` defeats the plain JSON rule.
141
+ //
142
+ // Prose is kept out by the VALUE's own shape rather than by banning the colon: a quoted value is
143
+ // always taken, an unquoted one only when it is a single ≥12-character token. That is what keeps
144
+ // this file's Must NOT change list intact — `password: must be at least 8 characters` stops at
145
+ // the 4-character `must`, and `token expired at ...` has no colon at all.
146
+ pattern: new RegExp(`(?<![A-Za-z0-9])(${LABELED_SECRET_LABELS})(\\\\?["']?\\s*:\\s*)(?:(\\\\?["'])(?!\\[REDACTED)[^"'\\\\\\r\\n]+\\3|(?!\\[REDACTED)[^\\s"',;}]{12,})`, "gi"),
147
+ replacement: ({ match: m }) => `${m[1]}${m[2]}${m[3] ?? ""}[REDACTED:labeled_secret]${m[3] ?? ""}`,
148
+ },
149
+ {
150
+ kind: "labeled_secret",
151
+ // Query-string form: `?key=value` / `&token=value`.
152
+ pattern: /([?&](?:key|api_key|api-key|token|access_token|sig|signature)=)(?!\[REDACTED)[^&#\s"']+/gi,
153
+ replacement: ({ match: m }) => `${m[1]}[REDACTED:labeled_secret]`,
154
+ },
155
+ ];
156
+ /** Redacts credential values with a required policy; returns text and replacement count. */
157
+ export function redactSecretShapes({ text, policy }) {
158
+ if (text.length === 0)
159
+ return { text, redactions: 0 };
160
+ let redactions = 0;
161
+ let result = text;
162
+ // Preserve the original policy slot: vendor/JWT matches take precedence over host formats.
163
+ const applicationRuleSlot = REDACTION_RULES.findIndex(rule => rule.kind === "bearer_token");
164
+ const rules = [
165
+ ...REDACTION_RULES.slice(0, applicationRuleSlot),
166
+ ...(policy.additionalRules ?? []),
167
+ ...REDACTION_RULES.slice(applicationRuleSlot),
168
+ ];
169
+ for (const rule of rules) {
170
+ result = result.replace(new RegExp(rule.pattern.source, withGlobalFlag(rule.pattern.flags)), (...args) => {
171
+ redactions += 1;
172
+ return rule.replacement({ match: args });
173
+ });
174
+ }
175
+ return { text: result, redactions };
176
+ }
177
+ // Preserve the public scanner vocabulary while core owns the single pattern catalog.
178
+ export { SECRET_SHAPE_PATTERNS as SECRET_PATTERNS, PEM_PATTERN_NAME } from "@jini-ai/core";
179
+ //# sourceMappingURL=secrets-only.js.map
@@ -1,7 +1,16 @@
1
1
  export interface RedactionOptions {
2
2
  username?: string | undefined;
3
3
  }
4
- export declare function redactJsonValue(value: unknown, opts?: RedactionOptions): unknown;
5
- export declare function redactText(text: string, opts?: RedactionOptions): string;
6
- export declare function redactJsonText(text: string, opts?: RedactionOptions): string;
4
+ /** Returns a redacted copy; the required input value is separate from optional path policy. */
5
+ export declare function redactJsonValue({ value }: {
6
+ value: unknown;
7
+ }, opts?: RedactionOptions): unknown;
8
+ /** Redacts credentials while optional username policy masks that user's home paths. */
9
+ export declare function redactText({ text }: {
10
+ text: string;
11
+ }, opts?: RedactionOptions): string;
12
+ /** Redacts valid JSON recursively and falls back to text redaction for invalid JSON. */
13
+ export declare function redactJsonText({ text }: {
14
+ text: string;
15
+ }, opts?: RedactionOptions): string;
7
16
  //# sourceMappingURL=redaction.d.ts.map
package/dist/redaction.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { SECRET_SHAPE_PATTERNS } from "@jini-ai/core";
1
2
  const SENSITIVE_KEY_RE = /token|password|secret|key|dsn|authorization|cookie/i;
2
3
  const URL_QUERY_SECRET_RE = /([?&#])(token|password|secret|key|dsn|api[_-]?key|auth|access_token|refresh_token|id_token)(=)([^&\s#"']*)/gi;
3
4
  // Catch loose key=value pairs in log lines that aren't inside a URL — e.g. env
@@ -16,9 +17,10 @@ const BARE_SECRET_RE = /(^|[\s,;])(access_token|refresh_token|id_token|api[_-]?k
16
17
  // previously left tokens like `Bearer abcd~efgh` partially exposed.
17
18
  const HTTP_AUTH_SCHEME_RE = /\b(Bearer|Token|Basic)\s+([A-Za-z0-9._~\-+/=:]{4,})/gi;
18
19
  const REDACTED = "[REDACTED]";
19
- export function redactJsonValue(value, opts = {}) {
20
+ /** Returns a redacted copy; the required input value is separate from optional path policy. */
21
+ export function redactJsonValue({ value }, opts = {}) {
20
22
  if (Array.isArray(value))
21
- return value.map((entry) => redactJsonValue(entry, opts));
23
+ return value.map((entry) => redactJsonValue({ value: entry }, opts));
22
24
  if (value !== null && typeof value === "object") {
23
25
  const out = {};
24
26
  for (const [key, raw] of Object.entries(value)) {
@@ -26,22 +28,29 @@ export function redactJsonValue(value, opts = {}) {
26
28
  out[key] = REDACTED;
27
29
  }
28
30
  else {
29
- out[key] = redactJsonValue(raw, opts);
31
+ out[key] = redactJsonValue({ value: raw }, opts);
30
32
  }
31
33
  }
32
34
  return out;
33
35
  }
34
36
  if (typeof value === "string")
35
- return redactText(value, opts);
37
+ return redactText({ text: value }, opts);
36
38
  return value;
37
39
  }
38
- export function redactText(text, opts = {}) {
40
+ /** Redacts credentials while optional username policy masks that user's home paths. */
41
+ export function redactText({ text }, opts = {}) {
39
42
  // Run the HTTP auth scheme replacement first so the credential after
40
43
  // `Bearer` / `Token` / `Basic` is captured before BARE_SECRET_RE swallows
41
44
  // the `Authorization: Bearer` prefix and stops at the space.
42
45
  let out = text.replace(HTTP_AUTH_SCHEME_RE, (_match, scheme) => `${scheme} ${REDACTED}`);
43
46
  out = out.replace(URL_QUERY_SECRET_RE, (_match, sep, name, eq) => `${sep}${name}${eq}${REDACTED}`);
44
47
  out = out.replace(BARE_SECRET_RE, (_match, lead, name, sep) => `${lead}${name}${sep}${REDACTED}`);
48
+ // Bundle redaction shares only the credential catalog; diagnostic IDs and paths must remain
49
+ // readable, so the kernel's general-purpose redaction policy is deliberately not invoked.
50
+ for (const { pattern } of SECRET_SHAPE_PATTERNS) {
51
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
52
+ out = out.replace(new RegExp(pattern.source, flags), REDACTED);
53
+ }
45
54
  const username = opts.username;
46
55
  if (username && username.length > 1) {
47
56
  const escaped = username.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -51,14 +60,15 @@ export function redactText(text, opts = {}) {
51
60
  }
52
61
  return out;
53
62
  }
54
- export function redactJsonText(text, opts = {}) {
63
+ /** Redacts valid JSON recursively and falls back to text redaction for invalid JSON. */
64
+ export function redactJsonText({ text }, opts = {}) {
55
65
  let parsed;
56
66
  try {
57
67
  parsed = JSON.parse(text);
58
68
  }
59
69
  catch {
60
- return redactText(text, opts);
70
+ return redactText({ text }, opts);
61
71
  }
62
- return JSON.stringify(redactJsonValue(parsed, opts), null, 2);
72
+ return JSON.stringify(redactJsonValue({ value: parsed }, opts), null, 2);
63
73
  }
64
74
  //# sourceMappingURL=redaction.js.map