@jini-ai/diagnostics 0.5.3 → 0.5.4
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.
- package/CHANGELOG.md +4 -0
- package/dist/agent-logs.js +31 -44
- package/dist/core/secrets-only.d.ts +8 -2
- package/dist/core/secrets-only.js +181 -9
- package/dist/discovery-filesystem.d.ts +14 -0
- package/dist/discovery-filesystem.js +19 -0
- package/dist/domain-dns/index.js +7 -3
- package/dist/node-ports.js +14 -10
- package/dist/observability/instrumentation.js +11 -7
- package/dist/redaction.js +16 -12
- package/dist/sources.js +21 -24
- package/dist/web-evidence/browser-port.d.ts +3 -0
- package/dist/web-evidence/browser-port.js +0 -1
- package/dist/web-evidence/collect-page-evidence.d.ts +2 -0
- package/dist/web-evidence/collect-page-evidence.js +58 -56
- package/dist/web-evidence/index.d.ts +1 -0
- package/dist/web-evidence/index.js +1 -0
- package/dist/web-evidence/lazy-browser.js +5 -4
- package/dist/web-evidence/page-performance-script.d.ts +38 -0
- package/dist/web-evidence/page-performance-script.js +80 -0
- package/dist/web-evidence/playwright-browser.d.ts +0 -3
- package/dist/web-evidence/playwright-browser.js +23 -14
- package/dist/web-evidence/playwright-runtime.d.ts +3 -0
- package/dist/web-evidence/playwright-runtime.js +7 -4
- package/dist/web-evidence/public-page.d.ts +2 -3
- package/dist/web-evidence/public-page.js +95 -80
- package/dist/web-evidence/render-page.js +167 -125
- package/dist/web-evidence/request-guard.d.ts +1 -1
- package/dist/web-evidence/request-guard.js +87 -78
- package/package.json +4 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# @jini-ai/diagnostics
|
|
2
2
|
|
|
3
|
+
## 0.5.4 — 2026-10-22
|
|
4
|
+
|
|
5
|
+
- 2026-10-22: Security queue fixes, complexity refactors, coverage.
|
|
6
|
+
|
|
3
7
|
## 0.5.3 — 2026-10-15
|
|
4
8
|
|
|
5
9
|
- The public-page browser capture uses a fixed 1,000,000-char raw-HTML cap instead of `maxChars * 4` (0625844e), so a large style head no longer eats the readable-text budget; `maxChars` still caps the text.
|
package/dist/agent-logs.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
|
+
import { readDirectorySafe, statSafe } from "./discovery-filesystem.js";
|
|
2
3
|
const DEFAULT_RUN_EVENT_TAIL_BYTES = 2 * 1024 * 1024;
|
|
3
4
|
const DEFAULT_MAX_RUN_EVENT_LOGS = 20;
|
|
4
5
|
// CLI session logs can be large (e.g. Codex's `codex-tui.log` grows into the
|
|
@@ -7,15 +8,6 @@ const DEFAULT_MAX_RUN_EVENT_LOGS = 20;
|
|
|
7
8
|
const DEFAULT_AGENT_LOG_TAIL_BYTES = 2 * 1024 * 1024;
|
|
8
9
|
const DEFAULT_MAX_FILES_PER_AGENT = 3;
|
|
9
10
|
const SAFE_DIR_ENTRY = /^[A-Za-z0-9._-]+$/u;
|
|
10
|
-
async function statSafe(path, filesystem) {
|
|
11
|
-
try {
|
|
12
|
-
const info = await filesystem.stat({ absolutePath: path });
|
|
13
|
-
return { mtimeMs: info.mtimeMs, isFile: info.isFile };
|
|
14
|
-
}
|
|
15
|
-
catch {
|
|
16
|
-
return null;
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
11
|
/**
|
|
20
12
|
* Collect the most-recent per-run event logs (`<runsDir>/<runId>/events.jsonl`).
|
|
21
13
|
*
|
|
@@ -29,13 +21,7 @@ export async function buildRunEventLogSources({ runsDir, filesystem }, options =
|
|
|
29
21
|
return [];
|
|
30
22
|
const maxRuns = options.maxRuns ?? DEFAULT_MAX_RUN_EVENT_LOGS;
|
|
31
23
|
const tailBytes = options.tailBytes ?? DEFAULT_RUN_EVENT_TAIL_BYTES;
|
|
32
|
-
|
|
33
|
-
try {
|
|
34
|
-
entries = await filesystem.readDirectory({ absolutePath: runsDir });
|
|
35
|
-
}
|
|
36
|
-
catch {
|
|
37
|
-
return [];
|
|
38
|
-
}
|
|
24
|
+
const entries = await readDirectorySafe({ path: runsDir, filesystem });
|
|
39
25
|
const candidates = [];
|
|
40
26
|
for (const entry of entries) {
|
|
41
27
|
if (!entry.isDirectory)
|
|
@@ -43,7 +29,7 @@ export async function buildRunEventLogSources({ runsDir, filesystem }, options =
|
|
|
43
29
|
if (!SAFE_DIR_ENTRY.test(entry.name))
|
|
44
30
|
continue;
|
|
45
31
|
const absolutePath = join(runsDir, entry.name, "events.jsonl");
|
|
46
|
-
const info = await statSafe(absolutePath, filesystem);
|
|
32
|
+
const info = await statSafe({ path: absolutePath, filesystem });
|
|
47
33
|
if (!info || !info.isFile)
|
|
48
34
|
continue;
|
|
49
35
|
candidates.push({ runId: entry.name, absolutePath, mtimeMs: info.mtimeMs });
|
|
@@ -57,13 +43,7 @@ export async function buildRunEventLogSources({ runsDir, filesystem }, options =
|
|
|
57
43
|
}));
|
|
58
44
|
}
|
|
59
45
|
async function latestLogFilesIn(dir, max, filesystem) {
|
|
60
|
-
|
|
61
|
-
try {
|
|
62
|
-
names = await filesystem.readDirectory({ absolutePath: dir });
|
|
63
|
-
}
|
|
64
|
-
catch {
|
|
65
|
-
return [];
|
|
66
|
-
}
|
|
46
|
+
const names = await readDirectorySafe({ path: dir, filesystem });
|
|
67
47
|
const candidates = [];
|
|
68
48
|
for (const { name } of names) {
|
|
69
49
|
if (!name.endsWith(".log"))
|
|
@@ -71,7 +51,7 @@ async function latestLogFilesIn(dir, max, filesystem) {
|
|
|
71
51
|
if (!SAFE_DIR_ENTRY.test(name))
|
|
72
52
|
continue;
|
|
73
53
|
const absolutePath = join(dir, name);
|
|
74
|
-
const info = await statSafe(absolutePath, filesystem);
|
|
54
|
+
const info = await statSafe({ path: absolutePath, filesystem });
|
|
75
55
|
if (!info || !info.isFile)
|
|
76
56
|
continue;
|
|
77
57
|
candidates.push({ name, absolutePath, mtimeMs: info.mtimeMs });
|
|
@@ -79,24 +59,7 @@ async function latestLogFilesIn(dir, max, filesystem) {
|
|
|
79
59
|
candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
80
60
|
return candidates.slice(0, max).map(({ name, absolutePath }) => ({ name, absolutePath }));
|
|
81
61
|
}
|
|
82
|
-
|
|
83
|
-
* Collect the native on-disk logs of the coding-agent CLIs a host application
|
|
84
|
-
* drives: Claude Code, Codex, OpenCode, and an AMR-style OpenCode runtime.
|
|
85
|
-
* These complement the per-run `events.jsonl` capture with the CLI's own
|
|
86
|
-
* internal diagnostics (provider errors, retries, auth state) that never
|
|
87
|
-
* reach the daemon's stream.
|
|
88
|
-
*
|
|
89
|
-
* Deliberately excluded: secret-bearing files. This only sweeps known *log*
|
|
90
|
-
* directories (`*.log` files) — never `~/.amr/config.json`, `~/.codex/auth.json`,
|
|
91
|
-
* or session transcripts — and the collected text still passes through the
|
|
92
|
-
* bundle's redaction pass.
|
|
93
|
-
*/
|
|
94
|
-
export async function buildAgentCliLogSources({ homeDir, filesystem }, options = {}) {
|
|
95
|
-
const home = homeDir?.trim();
|
|
96
|
-
if (!home)
|
|
97
|
-
return [];
|
|
98
|
-
const maxFiles = options.maxFilesPerAgent ?? DEFAULT_MAX_FILES_PER_AGENT;
|
|
99
|
-
const tailBytes = options.tailBytes ?? DEFAULT_AGENT_LOG_TAIL_BYTES;
|
|
62
|
+
function standardAgentLogDirectories({ home }, options = {}) {
|
|
100
63
|
const xdg = options.xdgDataHome?.trim();
|
|
101
64
|
const openCodeUserLogDir = xdg
|
|
102
65
|
? join(xdg, "opencode", "log")
|
|
@@ -109,7 +72,7 @@ export async function buildAgentCliLogSources({ homeDir, filesystem }, options =
|
|
|
109
72
|
const codexHome = options.codexHome?.trim() || join(home, ".codex");
|
|
110
73
|
// Per-agent log directories. `*.log` only; secret files (auth.json,
|
|
111
74
|
// config.json) live outside these dirs and are never swept.
|
|
112
|
-
|
|
75
|
+
return [
|
|
113
76
|
// Claude Code operational logs (bash-commands / cost-tracker / daemon).
|
|
114
77
|
{ agent: "claude", dir: claudeDir },
|
|
115
78
|
// Codex tracing logs (codex-tui.log can be very large — tail-bounded).
|
|
@@ -117,6 +80,9 @@ export async function buildAgentCliLogSources({ homeDir, filesystem }, options =
|
|
|
117
80
|
// OpenCode session logs (provider errors live here in headless mode).
|
|
118
81
|
{ agent: "opencode", dir: openCodeUserLogDir },
|
|
119
82
|
];
|
|
83
|
+
}
|
|
84
|
+
function agentLogDirectories({ home }, options = {}) {
|
|
85
|
+
const agentDirs = standardAgentLogDirectories({ home }, options);
|
|
120
86
|
// An AMR-style runtime drives a private OpenCode under OPENCODE_TEST_HOME;
|
|
121
87
|
// its session logs land under that home's XDG data dir, where provider
|
|
122
88
|
// failures are recorded. Prefer the effective home a real run resolves
|
|
@@ -132,6 +98,27 @@ export async function buildAgentCliLogSources({ homeDir, filesystem }, options =
|
|
|
132
98
|
dir: join(amrOpenCodeHome, ".local", "share", "opencode", "log"),
|
|
133
99
|
});
|
|
134
100
|
}
|
|
101
|
+
return agentDirs;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Collect the native on-disk logs of the coding-agent CLIs a host application
|
|
105
|
+
* drives: Claude Code, Codex, OpenCode, and an AMR-style OpenCode runtime.
|
|
106
|
+
* These complement the per-run `events.jsonl` capture with the CLI's own
|
|
107
|
+
* internal diagnostics (provider errors, retries, auth state) that never
|
|
108
|
+
* reach the daemon's stream.
|
|
109
|
+
*
|
|
110
|
+
* Deliberately excluded: secret-bearing files. This only sweeps known *log*
|
|
111
|
+
* directories (`*.log` files) — never `~/.amr/config.json`, `~/.codex/auth.json`,
|
|
112
|
+
* or session transcripts — and the collected text still passes through the
|
|
113
|
+
* bundle's redaction pass.
|
|
114
|
+
*/
|
|
115
|
+
export async function buildAgentCliLogSources({ homeDir, filesystem }, options = {}) {
|
|
116
|
+
const home = homeDir?.trim();
|
|
117
|
+
if (!home)
|
|
118
|
+
return [];
|
|
119
|
+
const maxFiles = options.maxFilesPerAgent ?? DEFAULT_MAX_FILES_PER_AGENT;
|
|
120
|
+
const tailBytes = options.tailBytes ?? DEFAULT_AGENT_LOG_TAIL_BYTES;
|
|
121
|
+
const agentDirs = agentLogDirectories({ home }, options);
|
|
135
122
|
const sources = [];
|
|
136
123
|
for (const { agent, dir } of agentDirs) {
|
|
137
124
|
const files = await latestLogFilesIn(dir, maxFiles, filesystem);
|
|
@@ -19,8 +19,8 @@ export interface RedactionRule {
|
|
|
19
19
|
* Blanks every secret-shaped VALUE in `text`, leaving everything else — including IPs, absolute
|
|
20
20
|
* paths, emails, tool ids, and ordinary prose — untouched.
|
|
21
21
|
*
|
|
22
|
-
* @param required - Text and the caller's redaction policy. The
|
|
23
|
-
*
|
|
22
|
+
* @param required - Text and the caller's redaction policy. The default treats arbitrary error text as plain text;
|
|
23
|
+
* code-aware share scans tokenize static literals and comments without evaluating code.
|
|
24
24
|
* @returns The redacted text plus how many values were blanked. `redactions: 0` means nothing
|
|
25
25
|
* secret-shaped was found — the returned `text` is then reference-identical in content (though
|
|
26
26
|
* not necessarily the same string instance) to the input.
|
|
@@ -34,6 +34,12 @@ export interface RedactionRule {
|
|
|
34
34
|
export interface RedactionPolicy {
|
|
35
35
|
/** Rules for caller-owned formats, applied after vendor/JWT rules and before bearer/labeled rules. Must be idempotent. */
|
|
36
36
|
readonly additionalRules?: readonly RedactionRule[];
|
|
37
|
+
/** Opt in only for code-file share scans; logs and arbitrary content must stay strict. */
|
|
38
|
+
readonly codeAware?: boolean;
|
|
39
|
+
/** Opt in only for content-addressed plugin package files: public code, docs and manifests whose
|
|
40
|
+
* field labels ("API token": "Token de API") and placeholders (`Authorization: Bearer <API_KEY>`)
|
|
41
|
+
* are not owner secrets. Applies vendor key formats, PEM, JWT and `additionalRules` only. */
|
|
42
|
+
readonly vendorOnly?: boolean;
|
|
37
43
|
}
|
|
38
44
|
/** Redacts credential values with a required policy; returns text and replacement count. */
|
|
39
45
|
export declare function redactSecretShapes({ text, policy }: {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { SECRET_SHAPE_PATTERNS } from "@jini-ai/core";
|
|
2
|
+
import jsTokens, {} from "js-tokens";
|
|
2
3
|
/** Adds the `g` flag when a source pattern (e.g. one of {@link SECRET_SHAPE_PATTERNS}, authored for a
|
|
3
4
|
* single `RegExp.exec` caller) does not already carry it — `String.replace` only replaces every
|
|
4
5
|
* match when the pattern is global. Mirrors `secret-scan-guard.ts`'s own `scanTextForSecrets`. */
|
|
@@ -153,12 +154,189 @@ const REDACTION_RULES = [
|
|
|
153
154
|
replacement: ({ match: m }) => `${m[1]}[REDACTED:labeled_secret]`,
|
|
154
155
|
},
|
|
155
156
|
];
|
|
157
|
+
// These dotted vendor formats were already part of the opt-in code policy.
|
|
158
|
+
const CODE_VENDOR_RULES = [
|
|
159
|
+
{ kind: "google_oauth", pattern: /ya29\.[\w-]{20,}/g, replacement: () => "[REDACTED:google_oauth]" },
|
|
160
|
+
{ kind: "sendgrid_key", pattern: /SG\.[\w-]{16,}\.[\w-]{16,}/g, replacement: () => "[REDACTED:sendgrid_key]" },
|
|
161
|
+
];
|
|
162
|
+
function applyRedactionRules({ text, rules }, _options = {}) {
|
|
163
|
+
let redactions = 0;
|
|
164
|
+
let result = text;
|
|
165
|
+
for (const rule of rules) {
|
|
166
|
+
result = result.replace(new RegExp(rule.pattern.source, withGlobalFlag(rule.pattern.flags)), (...args) => {
|
|
167
|
+
redactions += 1;
|
|
168
|
+
return rule.replacement({ match: args });
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
return { text: result, redactions };
|
|
172
|
+
}
|
|
173
|
+
function hasCredentialEntropy({ content }, _options = {}) {
|
|
174
|
+
const frequencies = new Map();
|
|
175
|
+
for (const char of content)
|
|
176
|
+
frequencies.set(char, (frequencies.get(char) ?? 0) + 1);
|
|
177
|
+
let entropy = 0;
|
|
178
|
+
for (const count of frequencies.values()) {
|
|
179
|
+
const probability = count / content.length;
|
|
180
|
+
entropy -= probability * Math.log2(probability);
|
|
181
|
+
}
|
|
182
|
+
return entropy >= 3.5;
|
|
183
|
+
}
|
|
184
|
+
/** Detect unlabeled pasted keys without treating a nearby identifier as secret context. */
|
|
185
|
+
function isCredentialLiteral({ content }, _options = {}) {
|
|
186
|
+
if (content.length < 20 || /\s/.test(content) || !/[a-z]/i.test(content) || !/\d/.test(content))
|
|
187
|
+
return false;
|
|
188
|
+
// Keys and tokens are key-alphabet only; selectors, CSS, regex sources and minified code carry
|
|
189
|
+
// brackets, quotes, colons or commas, and theme vendor JS tripped this check on them.
|
|
190
|
+
if (!/^[A-Za-z0-9_\-+/=.]{20,}$/.test(content))
|
|
191
|
+
return false;
|
|
192
|
+
// Shapes alone cannot distinguish hashes/UUIDs from hex keys. Prefer avoiding hash false
|
|
193
|
+
// positives through SHA-1 length; authoritative vendor rules still run before this check.
|
|
194
|
+
if (/^[a-f0-9]{20,40}$/i.test(content))
|
|
195
|
+
return false;
|
|
196
|
+
// URL/path and dotted i18n names are common static code data, not opaque credentials.
|
|
197
|
+
if (content.includes("/") || /^[\w$-]+(?:\.[\w$-]+)+$/.test(content))
|
|
198
|
+
return false;
|
|
199
|
+
return hasCredentialEntropy({ content });
|
|
200
|
+
}
|
|
201
|
+
function isFirstNamedCallArgument({ previous, separator, name }, _options = {}) {
|
|
202
|
+
// A comma in a grouping expression or a later call argument is not a named value pair.
|
|
203
|
+
if (separator !== "," || name.type !== "StringLiteral" || previous.at(-3)?.value !== "(")
|
|
204
|
+
return false;
|
|
205
|
+
const callee = previous.at(-4);
|
|
206
|
+
if (!callee)
|
|
207
|
+
return false;
|
|
208
|
+
return (callee.type === "IdentifierName" && !/^(if|while|for|switch|catch|with|function)$/.test(callee.value)) ||
|
|
209
|
+
callee.value === ")" || callee.value === "]";
|
|
210
|
+
}
|
|
211
|
+
/** Check significant-token adjacency for assignments/properties or a call's first string key.
|
|
212
|
+
* References and function names cannot satisfy the name/separator pair. */
|
|
213
|
+
function hasSecretLiteralContext({ previous }, _options = {}) {
|
|
214
|
+
const separator = previous.at(-1)?.value;
|
|
215
|
+
const name = previous.at(-2);
|
|
216
|
+
if (!name || (name.type !== "IdentifierName" && name.type !== "StringLiteral"))
|
|
217
|
+
return false;
|
|
218
|
+
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))
|
|
220
|
+
return false;
|
|
221
|
+
if (separator === ":" || separator === "=")
|
|
222
|
+
return true;
|
|
223
|
+
return isFirstNamedCallArgument({ previous, separator, name });
|
|
224
|
+
}
|
|
225
|
+
function codeTokenSpan({ token }, _options = {}) {
|
|
226
|
+
switch (token.type) {
|
|
227
|
+
case "StringLiteral":
|
|
228
|
+
case "JSXString":
|
|
229
|
+
case "NoSubstitutionTemplate":
|
|
230
|
+
case "TemplateTail":
|
|
231
|
+
return { start: 1, end: token.value.length - (token.closed ? 1 : 0), literal: true };
|
|
232
|
+
case "TemplateHead":
|
|
233
|
+
case "TemplateMiddle":
|
|
234
|
+
return { start: 1, end: token.value.length - 2, literal: true };
|
|
235
|
+
}
|
|
236
|
+
if (/^(SingleLineComment|MultiLineComment|HashbangComment)$/.test(token.type)) {
|
|
237
|
+
return { start: 0, end: token.value.length, literal: false };
|
|
238
|
+
}
|
|
239
|
+
return undefined;
|
|
240
|
+
}
|
|
241
|
+
function redactUnclassifiedLiteral({ content, adjacentSecret }, _options = {}) {
|
|
242
|
+
const value = content.replace(/^(Bearer|Basic|Token) /i, "");
|
|
243
|
+
// Joined plain words (upload-token, auth.token.label) are names/keys, not credential values.
|
|
244
|
+
if (adjacentSecret && content.length >= 8 && !/\s/.test(value) && !/^[A-Za-z]+(?:[-_.][A-Za-z]+)+$/.test(value)) {
|
|
245
|
+
return { text: "[REDACTED:labeled_secret]", redactions: 1 };
|
|
246
|
+
}
|
|
247
|
+
if (isCredentialLiteral({ content }))
|
|
248
|
+
return { text: "[REDACTED:high_entropy]", redactions: 1 };
|
|
249
|
+
return { text: content, redactions: 0 };
|
|
250
|
+
}
|
|
251
|
+
/** Decodes static JavaScript escapes for classification without evaluating source.
|
|
252
|
+
* O(n) time/space in literal length; nonsecret source keeps its original spelling. */
|
|
253
|
+
function decodeStaticLiteral({ content }, _options = {}) {
|
|
254
|
+
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);
|
|
258
|
+
return point <= 0x10ffff ? String.fromCodePoint(point) : "";
|
|
259
|
+
}
|
|
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))
|
|
265
|
+
return "";
|
|
266
|
+
return escapes[escape] ?? escape;
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
function redactCodeTokenContent({ content, literal, adjacentSecret, policy }, _options = {}) {
|
|
270
|
+
const strict = redactSecretShapes({ text: content, policy: { ...policy, codeAware: false } });
|
|
271
|
+
const vendor = applyRedactionRules({ text: strict.text, rules: CODE_VENDOR_RULES });
|
|
272
|
+
// Do not reclassify an existing replacement marker or count its bytes as another key.
|
|
273
|
+
if (literal && strict.redactions === 0 && vendor.text === content && !content.includes("[REDACTED:")) {
|
|
274
|
+
return redactUnclassifiedLiteral({ content, adjacentSecret });
|
|
275
|
+
}
|
|
276
|
+
return { text: vendor.text, redactions: strict.redactions + vendor.redactions };
|
|
277
|
+
}
|
|
278
|
+
/** Preserves nonsecret source spelling; escaped secrets become one syntax-safe replacement.
|
|
279
|
+
* O(n) time/space in token length. */
|
|
280
|
+
function renderRedactedLiteral({ content, classified, result }, _options = {}) {
|
|
281
|
+
if (result.redactions === 0)
|
|
282
|
+
return content;
|
|
283
|
+
if (content === classified)
|
|
284
|
+
return result.text;
|
|
285
|
+
return result.text.match(/\[REDACTED:[^\]]+\]/)?.[0] ?? "[REDACTED:escaped_secret]";
|
|
286
|
+
}
|
|
287
|
+
/** Keep the last four significant tokens for the next literal's context check. */
|
|
288
|
+
function rememberSignificantCodeToken({ previous, token }, _options = {}) {
|
|
289
|
+
if (/^(WhiteSpace|LineTerminatorSequence|SingleLineComment|MultiLineComment|HashbangComment)$/.test(token.type))
|
|
290
|
+
return;
|
|
291
|
+
previous.push(token);
|
|
292
|
+
if (previous.length > 4)
|
|
293
|
+
previous.shift();
|
|
294
|
+
}
|
|
295
|
+
/** Only tokenizer-delimited static literal text and comments reach the existing strict policy.
|
|
296
|
+
* Regexes, references and interpolation syntax never reach it; nested literals do.
|
|
297
|
+
* O(r*n) time and O(n) space for fixed strict rule count r and source length n. */
|
|
298
|
+
function redactCodeLiterals({ source, policy }, { jsx = true } = {}) {
|
|
299
|
+
const parts = [];
|
|
300
|
+
let redactions = 0;
|
|
301
|
+
const tokens = jsx ? jsTokens(source, { jsx: true }) : jsTokens(source);
|
|
302
|
+
const previous = [];
|
|
303
|
+
for (const token of tokens) {
|
|
304
|
+
const adjacentSecret = /^(StringLiteral|NoSubstitutionTemplate|TemplateHead)$/.test(token.type) &&
|
|
305
|
+
hasSecretLiteralContext({ previous });
|
|
306
|
+
rememberSignificantCodeToken({ previous, token });
|
|
307
|
+
const span = codeTokenSpan({ token });
|
|
308
|
+
if (!span) {
|
|
309
|
+
parts.push(token.value);
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
const { start, end, literal } = span;
|
|
313
|
+
const content = token.value.slice(start, end);
|
|
314
|
+
const classified = literal ? decodeStaticLiteral({ content }) : content;
|
|
315
|
+
const result = redactCodeTokenContent({ content: classified, literal, adjacentSecret, policy });
|
|
316
|
+
redactions += result.redactions;
|
|
317
|
+
parts.push(token.value.slice(0, start), renderRedactedLiteral({ content, classified, result }), token.value.slice(end));
|
|
318
|
+
}
|
|
319
|
+
return { text: parts.join(""), redactions };
|
|
320
|
+
}
|
|
321
|
+
// Context rules guess from labels/headers/prose; on public package files they only produce false
|
|
322
|
+
// positives, while a pasted provider key still has a provider shape.
|
|
323
|
+
const CONTEXT_RULE_KINDS = new Set(["auth_header", "url_credentials", "bearer_token", "labeled_secret"]);
|
|
156
324
|
/** Redacts credential values with a required policy; returns text and replacement count. */
|
|
157
325
|
export function redactSecretShapes({ text, policy }) {
|
|
158
326
|
if (text.length === 0)
|
|
159
327
|
return { text, redactions: 0 };
|
|
160
|
-
|
|
161
|
-
|
|
328
|
+
if (policy.vendorOnly) {
|
|
329
|
+
const vendorRules = REDACTION_RULES.filter(rule => !CONTEXT_RULE_KINDS.has(rule.kind));
|
|
330
|
+
return applyRedactionRules({ text, rules: [...vendorRules, ...CODE_VENDOR_RULES, ...(policy.additionalRules ?? [])] });
|
|
331
|
+
}
|
|
332
|
+
if (policy.codeAware) {
|
|
333
|
+
// The flag covers both TS and TSX, whose angle syntax is ambiguous to a tokenizer:
|
|
334
|
+
// JSX mode consumes <T>'key' as JSX text; JS mode consumes closing JSX tags as regexes.
|
|
335
|
+
// Both library modes are needed; the second pass cannot re-count redacted literals.
|
|
336
|
+
const jsx = redactCodeLiterals({ source: text, policy });
|
|
337
|
+
const plain = redactCodeLiterals({ source: jsx.text, policy }, { jsx: false });
|
|
338
|
+
return { text: plain.text, redactions: jsx.redactions + plain.redactions };
|
|
339
|
+
}
|
|
162
340
|
// Preserve the original policy slot: vendor/JWT matches take precedence over host formats.
|
|
163
341
|
const applicationRuleSlot = REDACTION_RULES.findIndex(rule => rule.kind === "bearer_token");
|
|
164
342
|
const rules = [
|
|
@@ -166,13 +344,7 @@ export function redactSecretShapes({ text, policy }) {
|
|
|
166
344
|
...(policy.additionalRules ?? []),
|
|
167
345
|
...REDACTION_RULES.slice(applicationRuleSlot),
|
|
168
346
|
];
|
|
169
|
-
|
|
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 };
|
|
347
|
+
return applyRedactionRules({ text, rules });
|
|
176
348
|
}
|
|
177
349
|
// Preserve the public scanner vocabulary while core owns the single pattern catalog.
|
|
178
350
|
export { SECRET_SHAPE_PATTERNS as SECRET_PATTERNS, PEM_PATTERN_NAME } from "@jini-ai/core";
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { DiagnosticsFilesystemPort } from "./ports.js";
|
|
2
|
+
/** Discovery is best-effort: an unreadable directory contributes no candidates. */
|
|
3
|
+
export declare function readDirectorySafe({ path, filesystem }: {
|
|
4
|
+
path: string;
|
|
5
|
+
filesystem: DiagnosticsFilesystemPort;
|
|
6
|
+
}, _options?: Record<string, never>): ReturnType<DiagnosticsFilesystemPort["readDirectory"]>;
|
|
7
|
+
export declare function statSafe({ path, filesystem }: {
|
|
8
|
+
path: string;
|
|
9
|
+
filesystem: DiagnosticsFilesystemPort;
|
|
10
|
+
}, _options?: Record<string, never>): Promise<{
|
|
11
|
+
mtimeMs: number;
|
|
12
|
+
isFile: boolean;
|
|
13
|
+
} | null>;
|
|
14
|
+
//# sourceMappingURL=discovery-filesystem.d.ts.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Discovery is best-effort: an unreadable directory contributes no candidates. */
|
|
2
|
+
export async function readDirectorySafe({ path, filesystem }, _options = {}) {
|
|
3
|
+
try {
|
|
4
|
+
return await filesystem.readDirectory({ absolutePath: path });
|
|
5
|
+
}
|
|
6
|
+
catch {
|
|
7
|
+
return [];
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export async function statSafe({ path, filesystem }, _options = {}) {
|
|
11
|
+
try {
|
|
12
|
+
const info = await filesystem.stat({ absolutePath: path });
|
|
13
|
+
return { mtimeMs: info.mtimeMs, isFile: info.isFile };
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=discovery-filesystem.js.map
|
package/dist/domain-dns/index.js
CHANGED
|
@@ -30,9 +30,8 @@ export function readPublicDnsName({ value, errorPrefix }) {
|
|
|
30
30
|
/** Shared normalization keeps URL/IP/internal-name refusals identical for both kinds of public name. */
|
|
31
31
|
function readPublicName(value, toolId, options = {}) {
|
|
32
32
|
const invalid = () => new DomainDnsInputError({ message: `${toolId}: pass a public DNS hostname such as 'example.com', without a URL, IP address, path, or port.` });
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
const domain = domainToASCII(value.replace(/\.$/, "")).toLowerCase();
|
|
33
|
+
const text = readPublicNameText({ value, invalid });
|
|
34
|
+
const domain = domainToASCII(text.replace(/\.$/, "")).toLowerCase();
|
|
36
35
|
const labels = domain.split(".");
|
|
37
36
|
const labelPattern = options.allowUnderscores ? /^[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?$/ : /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
38
37
|
const validLabels = labels.every(label => labelPattern.test(label));
|
|
@@ -42,6 +41,11 @@ function readPublicName(value, toolId, options = {}) {
|
|
|
42
41
|
throw invalid();
|
|
43
42
|
return domain;
|
|
44
43
|
}
|
|
44
|
+
function readPublicNameText({ value, invalid }, _options = {}) {
|
|
45
|
+
if (typeof value !== "string" || value.length > 254 || value.trim() !== value || /[/\\?#@:%\[\]\s]/u.test(value))
|
|
46
|
+
throw invalid();
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
45
49
|
/** Checks the bounded record type selection without silently dropping unknown/duplicate types. */
|
|
46
50
|
function readTypes(value) {
|
|
47
51
|
if (value === undefined)
|
package/dist/node-ports.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { open, readdir, lstat } from "node:fs/promises";
|
|
2
3
|
import { arch, hostname, platform, release, totalmem, type } from "node:os";
|
|
3
4
|
import JSZip from "jszip";
|
|
4
5
|
/** Explicit Node/JSZip adapter. Hosts opt into local filesystem and process access here.
|
|
@@ -8,15 +9,16 @@ export function createNodeDiagnosticsPorts(_required) {
|
|
|
8
9
|
return {
|
|
9
10
|
filesystem: {
|
|
10
11
|
async readFile({ absolutePath }, { tailBytes } = {}) {
|
|
11
|
-
|
|
12
|
-
return await readFile(absolutePath);
|
|
13
|
-
const info = await stat(absolutePath);
|
|
14
|
-
if (info.size <= tailBytes)
|
|
15
|
-
return await readFile(absolutePath);
|
|
16
|
-
const fd = await open(absolutePath, "r");
|
|
12
|
+
const fd = await open(absolutePath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
17
13
|
try {
|
|
18
|
-
const
|
|
19
|
-
|
|
14
|
+
const info = await fd.stat();
|
|
15
|
+
if (!info.isFile())
|
|
16
|
+
throw new Error("Diagnostic source is not a regular file");
|
|
17
|
+
if (tailBytes == null || tailBytes <= 0)
|
|
18
|
+
return await fd.readFile();
|
|
19
|
+
const length = Math.min(info.size, tailBytes);
|
|
20
|
+
const buffer = Buffer.alloc(length);
|
|
21
|
+
const { bytesRead } = await fd.read(buffer, 0, length, info.size - length);
|
|
20
22
|
return buffer.subarray(0, bytesRead);
|
|
21
23
|
}
|
|
22
24
|
finally {
|
|
@@ -24,11 +26,13 @@ export function createNodeDiagnosticsPorts(_required) {
|
|
|
24
26
|
}
|
|
25
27
|
},
|
|
26
28
|
async readDirectory({ absolutePath }) {
|
|
29
|
+
if (!(await lstat(absolutePath)).isDirectory())
|
|
30
|
+
throw new Error("Diagnostic source is not a directory");
|
|
27
31
|
return (await readdir(absolutePath, { withFileTypes: true }))
|
|
28
32
|
.map((entry) => ({ name: entry.name, isDirectory: entry.isDirectory() }));
|
|
29
33
|
},
|
|
30
34
|
async stat({ absolutePath }) {
|
|
31
|
-
const info = await
|
|
35
|
+
const info = await lstat(absolutePath);
|
|
32
36
|
return { isFile: info.isFile(), mtimeMs: info.mtimeMs };
|
|
33
37
|
},
|
|
34
38
|
},
|
|
@@ -10,21 +10,25 @@ function withTable(operation, node) {
|
|
|
10
10
|
const table = tableName(node);
|
|
11
11
|
return table ? { operation, table } : { operation };
|
|
12
12
|
}
|
|
13
|
+
function withFromTable({ operation, from }, _options = {}) {
|
|
14
|
+
return withTable(operation, from?.froms?.[0]);
|
|
15
|
+
}
|
|
16
|
+
function describeRawQuery({ sqlFragments }, _options = {}) {
|
|
17
|
+
// The keyword must end at a boundary: a fragment that opens with a quoted literal is not one.
|
|
18
|
+
const keyword = /^\s*([A-Za-z]+)(?![A-Za-z0-9_'"])/.exec(sqlFragments?.[0] ?? '')?.[1];
|
|
19
|
+
return { operation: keyword ? keyword.toLowerCase() : 'raw' };
|
|
20
|
+
}
|
|
13
21
|
/** Operation and table of one Kysely operation node. Reads node kinds and identifiers only — never
|
|
14
22
|
* parameter values or statement text, so the description is safe to export whatever the query binds.
|
|
15
23
|
* A raw statement contributes its leading keyword alone (`pragma`, `select`), or `raw`. */
|
|
16
24
|
export function describeQueryNode({ node }) {
|
|
17
25
|
const n = node;
|
|
18
26
|
switch (n?.kind) {
|
|
19
|
-
case 'SelectQueryNode': return
|
|
27
|
+
case 'SelectQueryNode': return withFromTable({ operation: 'select', from: n.from });
|
|
20
28
|
case 'InsertQueryNode': return withTable('insert', n.into);
|
|
21
29
|
case 'UpdateQueryNode': return withTable('update', n.table);
|
|
22
|
-
case 'DeleteQueryNode': return
|
|
23
|
-
case 'RawNode': {
|
|
24
|
-
// The keyword must end at a boundary: a fragment that opens with a quoted literal is not one.
|
|
25
|
-
const keyword = /^\s*([A-Za-z]+)(?![A-Za-z0-9_'"])/.exec(n.sqlFragments?.[0] ?? '')?.[1];
|
|
26
|
-
return { operation: keyword ? keyword.toLowerCase() : 'raw' };
|
|
27
|
-
}
|
|
30
|
+
case 'DeleteQueryNode': return withFromTable({ operation: 'delete', from: n.from });
|
|
31
|
+
case 'RawNode': return describeRawQuery({ sqlFragments: n.sqlFragments });
|
|
28
32
|
default:
|
|
29
33
|
if (typeof n?.kind !== 'string')
|
|
30
34
|
return { operation: 'query' };
|
package/dist/redaction.js
CHANGED
|
@@ -17,21 +17,24 @@ const BARE_SECRET_RE = /(^|[\s,;])(access_token|refresh_token|id_token|api[_-]?k
|
|
|
17
17
|
// previously left tokens like `Bearer abcd~efgh` partially exposed.
|
|
18
18
|
const HTTP_AUTH_SCHEME_RE = /\b(Bearer|Token|Basic)\s+([A-Za-z0-9._~\-+/=:]{4,})/gi;
|
|
19
19
|
const REDACTED = "[REDACTED]";
|
|
20
|
+
function redactJsonObject({ value }, opts = {}) {
|
|
21
|
+
const out = {};
|
|
22
|
+
for (const [key, raw] of Object.entries(value)) {
|
|
23
|
+
if (SENSITIVE_KEY_RE.test(key) && typeof raw === "string" && raw.length > 0) {
|
|
24
|
+
out[key] = REDACTED;
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
out[key] = redactJsonValue({ value: raw }, opts);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
20
32
|
/** Returns a redacted copy; the required input value is separate from optional path policy. */
|
|
21
33
|
export function redactJsonValue({ value }, opts = {}) {
|
|
22
34
|
if (Array.isArray(value))
|
|
23
35
|
return value.map((entry) => redactJsonValue({ value: entry }, opts));
|
|
24
36
|
if (value !== null && typeof value === "object") {
|
|
25
|
-
|
|
26
|
-
for (const [key, raw] of Object.entries(value)) {
|
|
27
|
-
if (SENSITIVE_KEY_RE.test(key) && typeof raw === "string" && raw.length > 0) {
|
|
28
|
-
out[key] = REDACTED;
|
|
29
|
-
}
|
|
30
|
-
else {
|
|
31
|
-
out[key] = redactJsonValue({ value: raw }, opts);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
return out;
|
|
37
|
+
return redactJsonObject({ value }, opts);
|
|
35
38
|
}
|
|
36
39
|
if (typeof value === "string")
|
|
37
40
|
return redactText({ text: value }, opts);
|
|
@@ -48,8 +51,9 @@ export function redactText({ text }, opts = {}) {
|
|
|
48
51
|
// Bundle redaction shares only the credential catalog; diagnostic IDs and paths must remain
|
|
49
52
|
// readable, so the kernel's general-purpose redaction policy is deliberately not invoked.
|
|
50
53
|
for (const { pattern } of SECRET_SHAPE_PATTERNS) {
|
|
51
|
-
|
|
52
|
-
|
|
54
|
+
// `String.replace` needs a global pattern to replace every match; strip-then-append keeps a
|
|
55
|
+
// pattern that is already global valid (a duplicated `g` flag would throw).
|
|
56
|
+
out = out.replace(new RegExp(pattern.source, `${pattern.flags.replace("g", "")}g`), REDACTED);
|
|
53
57
|
}
|
|
54
58
|
const username = opts.username;
|
|
55
59
|
if (username && username.length > 1) {
|
package/dist/sources.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
|
+
import { readDirectorySafe, statSafe } from "./discovery-filesystem.js";
|
|
2
3
|
import { redactJsonText, redactText } from "./redaction.js";
|
|
3
4
|
/** Reads through the filesystem port and records read failures as unavailable entries. */
|
|
4
5
|
export async function collectLogSource({ source, filesystem }, opts = {}) {
|
|
@@ -26,6 +27,23 @@ export async function collectLogSources({ sources, filesystem }, opts = {}) {
|
|
|
26
27
|
const DEFAULT_CRASH_DIRS_DARWIN = [
|
|
27
28
|
"/Library/Logs/DiagnosticReports",
|
|
28
29
|
];
|
|
30
|
+
async function crashReportsInDirectory({ dir, matches, cutoff, filesystem }, _options = {}) {
|
|
31
|
+
const entries = await readDirectorySafe({ path: dir, filesystem });
|
|
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;
|
|
37
|
+
const absolutePath = join(dir, entry);
|
|
38
|
+
const info = await statSafe({ path: absolutePath, filesystem });
|
|
39
|
+
if (!info || !info.isFile)
|
|
40
|
+
continue;
|
|
41
|
+
if (info.mtimeMs < cutoff)
|
|
42
|
+
continue;
|
|
43
|
+
found.push({ absolutePath, mtimeMs: info.mtimeMs, name: entry });
|
|
44
|
+
}
|
|
45
|
+
return found;
|
|
46
|
+
}
|
|
29
47
|
/** Scans matching reports with an explicit platform, clock and filesystem. */
|
|
30
48
|
export async function findMacOSCrashReports({ matchSubstrings, filesystem, clock, system }, options = {}) {
|
|
31
49
|
if (system.platform({}) !== "darwin")
|
|
@@ -40,30 +58,9 @@ export async function findMacOSCrashReports({ matchSubstrings, filesystem, clock
|
|
|
40
58
|
const matches = matchSubstrings.map((entry) => entry.toLowerCase());
|
|
41
59
|
const found = [];
|
|
42
60
|
for (const dir of dirs) {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
}
|
|
47
|
-
catch {
|
|
48
|
-
continue;
|
|
49
|
-
}
|
|
50
|
-
for (const { name: entry } of entries) {
|
|
51
|
-
const lower = entry.toLowerCase();
|
|
52
|
-
if (!matches.some((needle) => lower.includes(needle)))
|
|
53
|
-
continue;
|
|
54
|
-
const absolutePath = join(dir, entry);
|
|
55
|
-
try {
|
|
56
|
-
const info = await filesystem.stat({ absolutePath });
|
|
57
|
-
if (!info.isFile)
|
|
58
|
-
continue;
|
|
59
|
-
if (info.mtimeMs < cutoff)
|
|
60
|
-
continue;
|
|
61
|
-
found.push({ absolutePath, mtimeMs: info.mtimeMs, name: entry });
|
|
62
|
-
}
|
|
63
|
-
catch {
|
|
64
|
-
continue;
|
|
65
|
-
}
|
|
66
|
-
}
|
|
61
|
+
const reports = await crashReportsInDirectory({ dir, matches, cutoff, filesystem });
|
|
62
|
+
for (const report of reports)
|
|
63
|
+
found.push(report);
|
|
67
64
|
}
|
|
68
65
|
found.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
69
66
|
return found.slice(0, max).map(({ absolutePath, name }) => ({
|