@misconfig/cli 1.3.2 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/README.md +63 -12
- package/bin/misconfig.js +2 -3
- package/demo.cmd +13 -0
- package/engine/index.js +1 -1
- package/lib/computer-review.js +173 -0
- package/lib/computer-snapshot.js +232 -0
- package/lib/demo.js +32 -0
- package/lib/discover.js +36 -28
- package/lib/edit-attribution.js +122 -0
- package/lib/edit-records.js +125 -0
- package/lib/findings.js +12 -4
- package/lib/html.js +42 -4
- package/lib/main.js +182 -17
- package/lib/package-update.js +95 -0
- package/lib/print.js +14 -3
- package/lib/review-history.js +99 -0
- package/lib/review-store.js +142 -0
- package/package.json +3 -2
- package/report/styles.css +35 -0
package/lib/discover.js
CHANGED
|
@@ -16,8 +16,17 @@ import { TRACES, AGENT_PACKAGES, KNOWN_PACKAGES, VERSION_RE } from "../engine/kn
|
|
|
16
16
|
export const PLATFORM = process.platform === "win32" ? "windows" : process.platform === "darwin" ? "mac" : "linux";
|
|
17
17
|
const LOOSE_NAMES = /\.(md|mdc|txt)$/i;
|
|
18
18
|
|
|
19
|
+
export function displayUserPath(abs, home) {
|
|
20
|
+
if (home) {
|
|
21
|
+
const rel = path.relative(home, abs);
|
|
22
|
+
if (!rel) return "~";
|
|
23
|
+
if (!rel.startsWith("..") && !path.isAbsolute(rel)) return "~/" + rel.split(path.sep).join("/");
|
|
24
|
+
}
|
|
25
|
+
return abs.split(path.sep).join("/");
|
|
26
|
+
}
|
|
27
|
+
|
|
19
28
|
// `limits` is for tests; the command always uses LIMITS from the engine.
|
|
20
|
-
export async function discover({ dir = process.cwd(), includeUser = true, home = homeDir(), env = process.env, limits = LIMITS } = {}) {
|
|
29
|
+
export async function discover({ dir = process.cwd(), includeUser = true, home = homeDir(), env = process.env, limits = LIMITS, onComputerFile, sampleFiles } = {}) {
|
|
21
30
|
const projectDir = path.resolve(dir);
|
|
22
31
|
const info = await fs.stat(projectDir).catch(() => null);
|
|
23
32
|
if (!info?.isDirectory()) throw new Error(`There's no folder at ${projectDir}.`);
|
|
@@ -25,19 +34,14 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
|
|
|
25
34
|
const files = [];
|
|
26
35
|
const seen = new Set();
|
|
27
36
|
const lineMaps = {};
|
|
37
|
+
let collectingComputer = false;
|
|
28
38
|
let masked = 0;
|
|
29
39
|
|
|
30
|
-
const tilde = (abs) =>
|
|
31
|
-
|
|
32
|
-
const rel = path.relative(home, abs);
|
|
33
|
-
if (!rel) return "~";
|
|
34
|
-
if (!rel.startsWith("..") && !path.isAbsolute(rel)) return "~/" + rel.split(path.sep).join("/");
|
|
35
|
-
}
|
|
36
|
-
return abs.split(path.sep).join("/");
|
|
37
|
-
};
|
|
38
|
-
const add = (enginePath, raw, size, extra = {}) => {
|
|
40
|
+
const tilde = (abs) => displayUserPath(abs, home);
|
|
41
|
+
const add = (enginePath, raw, size, extra = {}, original = raw) => {
|
|
39
42
|
if (seen.has(enginePath)) return;
|
|
40
43
|
seen.add(enginePath);
|
|
44
|
+
if (collectingComputer && onComputerFile) onComputerFile(enginePath, raw, extra, original);
|
|
41
45
|
if (raw === null) return files.push({ path: enginePath, size, ...extra });
|
|
42
46
|
const m = maskSecrets(raw);
|
|
43
47
|
masked += m.count;
|
|
@@ -212,20 +216,20 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
|
|
|
212
216
|
// --- The home folder and app settings ------------------------------------
|
|
213
217
|
// Each file keeps its usual name (~/.claude/settings.json) even when an
|
|
214
218
|
// environment variable moved it, so the checks still recognize it.
|
|
219
|
+
collectingComputer = withUser;
|
|
215
220
|
if (withUser) {
|
|
216
221
|
const userFiles = [];
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
}
|
|
225
|
-
// In a folder, only the files agents read.
|
|
226
|
-
const nameOf = (f) => enginePath.replace(/\/?$/, "/") + path.relative(abs, f).split(path.sep).join("/");
|
|
227
|
-
for (const f of await listFiles(abs, 4, (f) => ["content", "listed"].includes(classifyPath(nameOf(f))), (d) => insideSkill(nameOf(d)))) userFiles.push({ abs: f, enginePath: nameOf(f) });
|
|
222
|
+
// The demo supplies only its own fixture paths and skips host inventories.
|
|
223
|
+
for (const p of sampleFiles ?? LOCATIONS.flatMap((entry) => userPaths(entry, PLATFORM))) {
|
|
224
|
+
for (const { abs, name } of await expand(resolveUserPath(p, { home, env }), p.startsWith("~") ? p : null)) {
|
|
225
|
+
const enginePath = name ?? tilde(abs);
|
|
226
|
+
if (!p.endsWith("/")) {
|
|
227
|
+
userFiles.push({ abs, enginePath });
|
|
228
|
+
continue;
|
|
228
229
|
}
|
|
230
|
+
// In a folder, only the files agents read.
|
|
231
|
+
const nameOf = (f) => enginePath.replace(/\/?$/, "/") + path.relative(abs, f).split(path.sep).join("/");
|
|
232
|
+
for (const f of await listFiles(abs, 4, (f) => ["content", "listed"].includes(classifyPath(nameOf(f))), (d) => insideSkill(nameOf(d)))) userFiles.push({ abs: f, enginePath: nameOf(f) });
|
|
229
233
|
}
|
|
230
234
|
}
|
|
231
235
|
// With CLAUDE_CONFIG_DIR set, ~/.claude.json may live in that folder.
|
|
@@ -238,9 +242,12 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
|
|
|
238
242
|
if (/(^|[\\/])\.claude\.json$/.test(abs)) {
|
|
239
243
|
const stat = await fs.stat(abs).catch(() => null);
|
|
240
244
|
const raw = stat?.isFile() ? await readText(abs) : null;
|
|
241
|
-
if (raw === null)
|
|
245
|
+
if (raw === null) {
|
|
246
|
+
if (stat?.isFile()) add(enginePath, null, stat.size, { invalid: true });
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
242
249
|
const reduced = reduceClaudeJson(raw, tilde);
|
|
243
|
-
add(enginePath, reduced.text, stat.size);
|
|
250
|
+
add(enginePath, reduced.text, stat.size, reduced.invalid ? { invalid: true } : {}, raw);
|
|
244
251
|
if (reduced.lineMap) lineMaps[enginePath] = reduced.lineMap;
|
|
245
252
|
continue;
|
|
246
253
|
}
|
|
@@ -273,8 +280,9 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
|
|
|
273
280
|
// If an agent has run in, or trusts, Downloads or the home folder, check
|
|
274
281
|
// the loose instruction files there too. Only the settings on this
|
|
275
282
|
// computer say where agents have run; a project's own copies don't count.
|
|
283
|
+
collectingComputer = false;
|
|
276
284
|
const risky = new Set();
|
|
277
|
-
for (const f of withUser ? files : []) {
|
|
285
|
+
for (const f of withUser && !sampleFiles ? files : []) {
|
|
278
286
|
if (!f.content || !/^(~|\/|[A-Za-z]:)/.test(f.path)) continue;
|
|
279
287
|
for (const d of agentFolders(f.path, f.content)) if (riskyPlace(d)) risky.add(d.startsWith("~") ? d : tilde(path.resolve(d)));
|
|
280
288
|
}
|
|
@@ -296,7 +304,7 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
|
|
|
296
304
|
const locked = scanningHome ? [] : await lockedPackages(projectDir);
|
|
297
305
|
let extensions = [];
|
|
298
306
|
let traces = [];
|
|
299
|
-
if (withUser) {
|
|
307
|
+
if (withUser && !sampleFiles) {
|
|
300
308
|
installs.push(...(await agentInstalls({ home, env, tilde })));
|
|
301
309
|
extensions = await editorExtensions({ home, env, tilde });
|
|
302
310
|
traces = await traceFiles({ home, env });
|
|
@@ -608,14 +616,14 @@ export function resolveUserPath(p, { home, env }) {
|
|
|
608
616
|
// has been started in and their tool approvals. lineMap[i] is the line in
|
|
609
617
|
// the real file that reduced line i + 1 came from, so findings point at
|
|
610
618
|
// lines people can open.
|
|
611
|
-
function reduceClaudeJson(raw, tilde) {
|
|
619
|
+
export function reduceClaudeJson(raw, tilde) {
|
|
612
620
|
let json;
|
|
613
621
|
try {
|
|
614
622
|
json = JSON.parse(raw);
|
|
615
623
|
} catch {
|
|
616
|
-
return { text: "{}", lineMap: null };
|
|
624
|
+
return { text: "{}", lineMap: null, invalid: true };
|
|
617
625
|
}
|
|
618
|
-
if (!json || typeof json !== "object") return { text: "{}", lineMap: null };
|
|
626
|
+
if (!json || typeof json !== "object" || Array.isArray(json)) return { text: "{}", lineMap: null, invalid: true };
|
|
619
627
|
const keys = new Map(); // reduced key, as JSON, -> key in the real file, as JSON
|
|
620
628
|
const out = {};
|
|
621
629
|
for (const [k, v] of Object.entries(json)) {
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { lstat, open, opendir } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { LIMITS } from "../engine/paths.js";
|
|
5
|
+
import { computerSnapshot, fingerprint } from "./computer-snapshot.js";
|
|
6
|
+
import { displayUserPath, reduceClaudeJson, resolveUserPath } from "./discover.js";
|
|
7
|
+
import { visitEdits } from "./edit-records.js";
|
|
8
|
+
import { addEditorEvidence, linkEditors } from "./review-history.js";
|
|
9
|
+
|
|
10
|
+
const WEEK = 7 * 86400000;
|
|
11
|
+
const TAIL = 4 * 1024 * 1024;
|
|
12
|
+
const BUDGET = 32 * 1024 * 1024;
|
|
13
|
+
const pathKey = (s) => process.platform === "win32" ? s.toLowerCase() : s;
|
|
14
|
+
|
|
15
|
+
async function recentSessions(home, env, since, report) {
|
|
16
|
+
const roots = [path.join(env.CLAUDE_CONFIG_DIR || path.join(home, ".claude"), "projects"),
|
|
17
|
+
...["sessions", "archived_sessions"].map((dir) => path.join(env.CODEX_HOME || path.join(home, ".codex"), dir))];
|
|
18
|
+
const queue = roots.slice(), found = [];
|
|
19
|
+
let entries = 0;
|
|
20
|
+
for (let i = 0; i < queue.length; i++) {
|
|
21
|
+
try {
|
|
22
|
+
if (!(await lstat(queue[i])).isDirectory()) continue;
|
|
23
|
+
const dir = await opendir(queue[i]);
|
|
24
|
+
for await (const entry of dir) {
|
|
25
|
+
if (++entries > 8192) { report.limited = true; break; }
|
|
26
|
+
const file = path.join(queue[i], entry.name);
|
|
27
|
+
if (entry.isDirectory()) queue.push(file);
|
|
28
|
+
if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
|
|
29
|
+
const info = await lstat(file);
|
|
30
|
+
if (info.mtimeMs >= since) found.push({ file, time: info.mtimeMs });
|
|
31
|
+
}
|
|
32
|
+
} catch (e) { if (e.code !== "ENOENT") report.limited = true; }
|
|
33
|
+
if (entries > 8192) break;
|
|
34
|
+
}
|
|
35
|
+
return found.sort((a,b) => b.time - a.time).map((x) => x.file);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function readTail(file, room, report) {
|
|
39
|
+
if (!(await lstat(file)).isFile()) { report.limited = true; return; }
|
|
40
|
+
const fd = await open(file, "r");
|
|
41
|
+
try {
|
|
42
|
+
const stat = await fd.stat();
|
|
43
|
+
if (!stat.isFile()) { report.limited = true; return; }
|
|
44
|
+
const size = Math.min(room, TAIL, stat.size);
|
|
45
|
+
const data = Buffer.alloc(size);
|
|
46
|
+
let length = 0;
|
|
47
|
+
while (length < size) {
|
|
48
|
+
const { bytesRead } = await fd.read(data, length, size - length, stat.size - size + length);
|
|
49
|
+
if (!bytesRead) break;
|
|
50
|
+
length += bytesRead;
|
|
51
|
+
}
|
|
52
|
+
if (length < size) report.limited = true;
|
|
53
|
+
let text = data.toString("utf8", 0, length);
|
|
54
|
+
if (size < stat.size) {
|
|
55
|
+
report.limited = true;
|
|
56
|
+
const newline = text.indexOf("\n");
|
|
57
|
+
text = newline < 0 ? "" : text.slice(newline + 1);
|
|
58
|
+
}
|
|
59
|
+
return { length, text };
|
|
60
|
+
} finally { await fd.close(); }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function itemsFor(key, file, raw, home) {
|
|
64
|
+
if (raw === null) return {};
|
|
65
|
+
if (typeof raw !== "string" || Buffer.byteLength(raw) > LIMITS.maxFileBytes) return;
|
|
66
|
+
if (file === "~/.claude.json") {
|
|
67
|
+
const reduced = reduceClaudeJson(raw, (p) => displayUserPath(p, home));
|
|
68
|
+
if (reduced.invalid) return;
|
|
69
|
+
raw = reduced.text;
|
|
70
|
+
}
|
|
71
|
+
const snapshot = computerSnapshot(key);
|
|
72
|
+
snapshot.collect(file, raw);
|
|
73
|
+
if (snapshot.verified.has(file)) return snapshot.items;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function attributeEdits(state, review, currentFiles, { sessions = [], home = homedir(), env = process.env } = {}) {
|
|
77
|
+
const report = { filesRead: 0, matchedEdits: 0, limited: false };
|
|
78
|
+
const since = sessions.length ? 0 : Date.now() - WEEK;
|
|
79
|
+
const targets = new Map();
|
|
80
|
+
for (const event of state.history.events) {
|
|
81
|
+
if (event.action !== "observed" || !event.transition || event.at < since) continue;
|
|
82
|
+
const abs = pathKey(resolveUserPath(event.file, { home, env }));
|
|
83
|
+
if (!targets.has(abs)) targets.set(abs, { file: event.file, events: [] });
|
|
84
|
+
targets.get(abs).events.push(event);
|
|
85
|
+
}
|
|
86
|
+
if (!targets.size) return report;
|
|
87
|
+
const matched = new Set();
|
|
88
|
+
function visit(target, at, name, reconstruct) {
|
|
89
|
+
const eligible = target.events.filter((e) => e.since <= at && at <= e.at);
|
|
90
|
+
if (!eligible.length || at < since) return;
|
|
91
|
+
const pair = reconstruct(currentFiles.get(target.file));
|
|
92
|
+
if (!pair) return;
|
|
93
|
+
// A hunk alone cannot prove which occurrence it changed after files
|
|
94
|
+
// have moved around. Bind reconstructed text to both scan snapshots.
|
|
95
|
+
const digests = pair[2] ? pair.slice(0, 2).map((s) => s === null ? null : fingerprint(state.key, s.replace(/\r\n/g, "\n"))) : null;
|
|
96
|
+
const before = itemsFor(state.key, target.file, pair[0], home);
|
|
97
|
+
const after = itemsFor(state.key, target.file, pair[1], home);
|
|
98
|
+
if (!before || !after) return;
|
|
99
|
+
for (const e of eligible) {
|
|
100
|
+
if (digests && (digests[0] !== e.priorFile || digests[1] !== e.nextFile)) continue;
|
|
101
|
+
const a = before[e.subject]?.hash ?? null, b = after[e.subject]?.hash ?? null;
|
|
102
|
+
if (a === b || e.transition !== "c-" + fingerprint(state.key, [e.subject, a, b]).slice(0, 20)) continue;
|
|
103
|
+
addEditorEvidence(state.history, e, { name, basis: "tool-record", at });
|
|
104
|
+
matched.add(e.id);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const files = sessions.length ? [...new Set(sessions)] : await recentSessions(home, env, since, report);
|
|
108
|
+
let remaining = BUDGET;
|
|
109
|
+
if (files.length > 48) report.limited = true;
|
|
110
|
+
for (const file of files.slice(0, 48)) {
|
|
111
|
+
if (!remaining) { report.limited = true; break; }
|
|
112
|
+
let part;
|
|
113
|
+
try { part = await readTail(file, remaining, report); } catch { report.limited = true; }
|
|
114
|
+
if (!part) continue;
|
|
115
|
+
remaining -= part.length;
|
|
116
|
+
report.filesRead++;
|
|
117
|
+
visitEdits(part.text, (abs) => abs && targets.get(pathKey(abs)), visit);
|
|
118
|
+
}
|
|
119
|
+
report.matchedEdits = matched.size;
|
|
120
|
+
linkEditors(state.history, [...review.changes, ...review.pending]);
|
|
121
|
+
return report;
|
|
122
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { LIMITS } from "../engine/paths.js";
|
|
3
|
+
|
|
4
|
+
function absolute(file, cwd) {
|
|
5
|
+
if (typeof file !== "string" || !file || file.includes("\0")) return null;
|
|
6
|
+
if (path.isAbsolute(file)) return path.normalize(file);
|
|
7
|
+
return typeof cwd === "string" && path.isAbsolute(cwd) ? path.resolve(cwd, file) : null;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// Reverse only numbered, exact unified-diff hunks. A context or line-count
|
|
11
|
+
// mismatch means the current file cannot establish the earlier setting.
|
|
12
|
+
export function beforePatch(after, diff) {
|
|
13
|
+
if (typeof after !== "string" || typeof diff !== "string") return;
|
|
14
|
+
if (diff.length > LIMITS.maxFileBytes * 3) return;
|
|
15
|
+
const current = after.replace(/\r\n/g, "\n").match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
16
|
+
const patch = diff.replace(/\r\n/g, "\n").split("\n");
|
|
17
|
+
if (patch.at(-1) === "") patch.pop();
|
|
18
|
+
let i = 0, cursor = 0, hunks = 0;
|
|
19
|
+
const original = [];
|
|
20
|
+
if (patch[0]?.startsWith("--- ") && patch[1]?.startsWith("+++ ")) i = 2;
|
|
21
|
+
while (i < patch.length) {
|
|
22
|
+
const h = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@.*$/.exec(patch[i++]);
|
|
23
|
+
if (!h) return;
|
|
24
|
+
const oldCount = Number(h[2] ?? 1), newCount = Number(h[4] ?? 1);
|
|
25
|
+
const start = Number(h[3]) - (newCount ? 1 : 0);
|
|
26
|
+
if (start < cursor || start > current.length || original.length + start - cursor !== Number(h[1]) - (oldCount ? 1 : 0)) return;
|
|
27
|
+
while (cursor < start) original.push(current[cursor++]);
|
|
28
|
+
let oldLines = 0, newLines = 0;
|
|
29
|
+
while (i < patch.length && !patch[i].startsWith("@@ ")) {
|
|
30
|
+
const line = patch[i++], op = line[0];
|
|
31
|
+
if (![" ", "+", "-"].includes(op)) return;
|
|
32
|
+
let value = line.slice(1) + "\n";
|
|
33
|
+
if (patch[i] === "\") { value = line.slice(1); i++; }
|
|
34
|
+
if (op !== "-") { if (current[cursor++] !== value) return; newLines++; }
|
|
35
|
+
if (op !== "+") { original.push(value); oldLines++; }
|
|
36
|
+
}
|
|
37
|
+
if (oldLines !== oldCount || newLines !== newCount) return;
|
|
38
|
+
hunks++;
|
|
39
|
+
}
|
|
40
|
+
if (hunks) return original.join("") + current.slice(cursor).join("");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function replaceLiteral(text, oldValue, newValue, all) {
|
|
44
|
+
if (typeof text !== "string" || typeof oldValue !== "string" || !oldValue || typeof newValue !== "string") return;
|
|
45
|
+
if ([text, oldValue, newValue].some((s) => s.length > LIMITS.maxFileBytes)) return;
|
|
46
|
+
const at = text.indexOf(oldValue);
|
|
47
|
+
if (at < 0 || (!all && text.indexOf(oldValue, at + 1) !== -1)) return;
|
|
48
|
+
if (!all) return text.slice(0, at) + newValue + text.slice(at + oldValue.length);
|
|
49
|
+
const fragments = text.split(oldValue);
|
|
50
|
+
if (text.length + (fragments.length - 1) * (newValue.length - oldValue.length) > LIMITS.maxFileBytes) return;
|
|
51
|
+
return fragments.join(newValue);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function claudeEdit(call, result, current) {
|
|
55
|
+
const { input, name } = call;
|
|
56
|
+
if (result.userModified === true || result.success === false || result.is_error || result.error) return;
|
|
57
|
+
if (name === "Write") {
|
|
58
|
+
if (typeof input.content !== "string" || (result.content !== undefined && result.content !== input.content)) return;
|
|
59
|
+
if (typeof result.originalFile === "string") return [result.originalFile, input.content];
|
|
60
|
+
if (result.type === "create" && result.originalFile == null) return [null, input.content];
|
|
61
|
+
} else {
|
|
62
|
+
const { old_string: oldValue, new_string: newValue, replace_all: all } = input;
|
|
63
|
+
if (typeof oldValue !== "string" || typeof newValue !== "string" || oldValue === newValue) return;
|
|
64
|
+
if ((result.oldString !== undefined && result.oldString !== oldValue) || (result.newString !== undefined && result.newString !== newValue)) return;
|
|
65
|
+
if (typeof result.originalFile === "string") {
|
|
66
|
+
const after = replaceLiteral(result.originalFile, oldValue, newValue, all);
|
|
67
|
+
if (after !== undefined) return [result.originalFile, after];
|
|
68
|
+
} else if (result.success === true && !all) {
|
|
69
|
+
const before = replaceLiteral(current, newValue, oldValue, false);
|
|
70
|
+
if (before !== undefined) return [before, current, true];
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Only completed file-tool records qualify. Conversations, shell commands,
|
|
76
|
+
// pending patches and user-modified tool calls cannot establish an editor.
|
|
77
|
+
export function visitEdits(text, targetFor, visit) {
|
|
78
|
+
const calls = new Map();
|
|
79
|
+
let cwd;
|
|
80
|
+
for (const line of text.split("\n")) {
|
|
81
|
+
if (!line.includes("tool_use") && !line.includes("tool_result") && !line.includes("patch_apply_end") && !line.includes("item_completed") && !line.includes("session_meta") && !line.includes("turn_context")) continue;
|
|
82
|
+
let r;
|
|
83
|
+
try { r = JSON.parse(line); } catch { continue; }
|
|
84
|
+
if (!r || typeof r !== "object") continue;
|
|
85
|
+
const p = r.payload;
|
|
86
|
+
if ((r.type === "session_meta" || r.type === "turn_context") && typeof p?.cwd === "string") { cwd = p.cwd; continue; }
|
|
87
|
+
if (r.type === "assistant" && r.message?.role === "assistant" && Array.isArray(r.message.content)) {
|
|
88
|
+
for (const call of r.message.content) {
|
|
89
|
+
if (call?.type !== "tool_use" || !["Edit", "Write"].includes(call.name) || typeof call.id !== "string") continue;
|
|
90
|
+
const target = targetFor(absolute(call.input?.file_path, r.cwd));
|
|
91
|
+
if (target) calls.set(call.id, { ...call, target, session: r.sessionId });
|
|
92
|
+
}
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const at = typeof r.timestamp === "string" ? Date.parse(r.timestamp) : NaN;
|
|
96
|
+
if (!Number.isFinite(at)) continue;
|
|
97
|
+
if (r.type === "user" && r.message?.role === "user" && Array.isArray(r.message.content) && r.toolUseResult) {
|
|
98
|
+
const replies = r.message.content.filter((c) => c?.type === "tool_result");
|
|
99
|
+
if (replies.length !== 1) continue;
|
|
100
|
+
const reply = replies[0], call = calls.get(reply.tool_use_id);
|
|
101
|
+
calls.delete(reply.tool_use_id);
|
|
102
|
+
if (!call || call.session !== r.sessionId || reply.is_error === true || typeof r.toolUseResult !== "object") continue;
|
|
103
|
+
const target = targetFor(absolute(r.toolUseResult.filePath, r.cwd));
|
|
104
|
+
if (target !== call.target) continue;
|
|
105
|
+
visit(target, at, "Claude Code", (current) => claudeEdit(call, r.toolUseResult, current));
|
|
106
|
+
}
|
|
107
|
+
if (r.type !== "event_msg" || !p) continue;
|
|
108
|
+
let changes;
|
|
109
|
+
if (p.type === "patch_apply_end" && p.success === true && (p.status === undefined || p.status === "completed")) changes = p.changes;
|
|
110
|
+
if (p.type === "item_completed" && p.item?.type === "FileChange" && p.item.status === "completed") changes = p.item.changes;
|
|
111
|
+
if (!changes || typeof changes !== "object" || Array.isArray(changes)) continue;
|
|
112
|
+
for (const [name, change] of Object.entries(changes)) {
|
|
113
|
+
const target = targetFor(absolute(name, cwd));
|
|
114
|
+
if (!target || !change || change.move_path) continue;
|
|
115
|
+
visit(target, at, "Codex", (current) => {
|
|
116
|
+
if (change.type === "add" && typeof change.content === "string") return [null, change.content, true];
|
|
117
|
+
if (change.type === "delete" && typeof change.content === "string") return [change.content, null, true];
|
|
118
|
+
if (change.type === "update") {
|
|
119
|
+
const before = beforePatch(current, change.unified_diff);
|
|
120
|
+
if (before !== undefined) return [before, current, true];
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
package/lib/findings.js
CHANGED
|
@@ -25,7 +25,7 @@ const esc = (value) =>
|
|
|
25
25
|
const RULE_ID = /^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+){0,6}$/;
|
|
26
26
|
const OPEN = new Set(["critical", "high"]);
|
|
27
27
|
|
|
28
|
-
function findingHtml(f, id = "") {
|
|
28
|
+
function findingHtml(f, id = "", demo = false) {
|
|
29
29
|
const sev = Object.hasOwn(LABEL, f.severity) ? f.severity : "info";
|
|
30
30
|
const where = f.file ? f.file + (f.line ? `:${f.line}` : "") : "";
|
|
31
31
|
const evidence = f.evidence
|
|
@@ -33,9 +33,17 @@ function findingHtml(f, id = "") {
|
|
|
33
33
|
: "";
|
|
34
34
|
const rule = typeof f.id === "string" && RULE_ID.test(f.id) ? `<a class="f-rule" href="https://misconfig.ai/rules#${f.id}" target="_blank" rel="noopener noreferrer">${f.id}</a>` : "";
|
|
35
35
|
const meta = [f.tool ? `<span>Affects ${esc(f.tool)}</span>` : "", rule].filter(Boolean).join("");
|
|
36
|
+
let review = "";
|
|
37
|
+
if (f.review) {
|
|
38
|
+
const accepted = f.review.acceptedAt;
|
|
39
|
+
const decision = accepted ? esc(new Date(accepted).toISOString().slice(0, 10)) + " by " + esc(f.review.acceptedBy ?? "an unknown account")
|
|
40
|
+
: demo ? "" : `<code>--approve ${esc(f.review.id)}</code>`;
|
|
41
|
+
review = `<p><b>${accepted ? "Risk accepted" : "Awaiting risk review"}</b> ${decision}</p>`;
|
|
42
|
+
}
|
|
36
43
|
return `<details class="finding sev-${sev}"${id ? ` id="${esc(id)}"` : ""}${OPEN.has(sev) ? " open" : ""}>
|
|
37
|
-
<summary><span class="sq" aria-hidden="true"></span><span class="f-title">${esc(f.title)}</span>${where ? `<span class="f-where">${esc(where)}</span>` : ""}</summary>
|
|
44
|
+
<summary><span class="sq" aria-hidden="true"></span><span class="f-title">${esc(f.title)}${f.review?.acceptedAt ? " · Risk accepted" : ""}</span>${where ? `<span class="f-where">${esc(where)}</span>` : ""}</summary>
|
|
38
45
|
<div class="f-body">
|
|
46
|
+
${review}
|
|
39
47
|
<p><b>Why it matters.</b> ${esc(f.why)}</p>
|
|
40
48
|
<p><b>Fix.</b> ${esc(f.fix)}</p>
|
|
41
49
|
${evidence}
|
|
@@ -83,7 +91,7 @@ function fixFirstHtml(findings, anchorOf) {
|
|
|
83
91
|
// What to fix first, then the findings in groups, worst first, after the
|
|
84
92
|
// legend. In each group, findings in the same file sit together, so a file
|
|
85
93
|
// can be fixed in one pass.
|
|
86
|
-
export function findingsHtml(findings) {
|
|
94
|
+
export function findingsHtml(findings, demo = false) {
|
|
87
95
|
const groups = SEVERITIES.map((sev) => [
|
|
88
96
|
sev,
|
|
89
97
|
findings
|
|
@@ -101,7 +109,7 @@ export function findingsHtml(findings) {
|
|
|
101
109
|
.map(
|
|
102
110
|
([sev, group]) => `<section class="group">
|
|
103
111
|
<h3 class="group-title"><span class="sq sev-${sev}" aria-hidden="true"></span>${LABEL[sev]}<span class="group-count">${group.length}</span></h3>
|
|
104
|
-
${group.map((f) => findingHtml(f, anchorOf.get(f))).join("")}
|
|
112
|
+
${group.map((f) => findingHtml(f, anchorOf.get(f), demo)).join("")}
|
|
105
113
|
</section>`,
|
|
106
114
|
)
|
|
107
115
|
.join("")
|
package/lib/html.js
CHANGED
|
@@ -13,6 +13,8 @@ import { spawn } from "node:child_process";
|
|
|
13
13
|
import { SCOPES } from "../engine/explain.js";
|
|
14
14
|
import { INSTALLED_BY } from "../engine/index.js";
|
|
15
15
|
import { findingsHtml, LABEL } from "./findings.js";
|
|
16
|
+
import { changeLabel } from "./computer-review.js";
|
|
17
|
+
import { changeValue, earlierBuildNote, editorText, historyDescription } from "./review-history.js";
|
|
16
18
|
|
|
17
19
|
const ASSETS = new URL("../report/", import.meta.url);
|
|
18
20
|
// Lines of what a file says shown in the report; --explain shows them all.
|
|
@@ -82,7 +84,7 @@ ${body(result, { version, scanned, checkedAt })}
|
|
|
82
84
|
}
|
|
83
85
|
|
|
84
86
|
function body(r, { version, scanned }) {
|
|
85
|
-
const where = scanned.projectSkipped ? "your home folder" : scanned.project || "a project";
|
|
87
|
+
const where = scanned.demo ? "the sample computer" : scanned.projectSkipped ? "your home folder" : scanned.project || "a project";
|
|
86
88
|
const checked = [
|
|
87
89
|
plural(r.stats.filesChecked, "agent file"),
|
|
88
90
|
r.stats.mcpServers ? plural(r.stats.mcpServers, "MCP server") : null,
|
|
@@ -101,7 +103,7 @@ function body(r, { version, scanned }) {
|
|
|
101
103
|
${countsList(r.counts)}
|
|
102
104
|
<div class="result-meta">
|
|
103
105
|
${typeof r.score === "number" ? `<p>Score ${esc(r.score)} out of 100.</p>` : ""}
|
|
104
|
-
<p>Checked ${scanned.projectSkipped || !scanned.project ? esc(where) : `<code>${esc(where)}</code>`}${scanned.user ? " and the agent settings on this computer" : ""}.${esc(known)}</p>
|
|
106
|
+
<p>Checked ${scanned.projectSkipped || !scanned.project ? esc(where) : `<code>${esc(where)}</code>`}${scanned.user && !scanned.demo ? " and the agent settings on this computer" : ""}.${esc(known)}</p>
|
|
105
107
|
<p>${esc(listText(checked))}.${r.tools.length ? ` Agents found: ${esc(listText(r.tools))}.` : ""}</p>
|
|
106
108
|
</div>
|
|
107
109
|
</div>
|
|
@@ -115,10 +117,11 @@ function body(r, { version, scanned }) {
|
|
|
115
117
|
</div>
|
|
116
118
|
</section>
|
|
117
119
|
|
|
120
|
+
${computerReviewHtml(r.computerReview, r.computerReviewError, scanned.demo)}
|
|
118
121
|
<section class="chapter" aria-labelledby="findings-title">
|
|
119
122
|
<h2 id="findings-title">Findings</h2>
|
|
120
|
-
${r.findings.length ? findingsHtml(r.findings) : '<p class="empty">No issues found in these agent files.</p>'}
|
|
121
|
-
${r.findings.length ? `<p class="next-step">After you change
|
|
123
|
+
${r.findings.length ? findingsHtml(r.findings, scanned.demo) : '<p class="empty">No issues found in these agent files.</p>'}
|
|
124
|
+
${r.findings.length && !scanned.demo ? `<p class="next-step">After you change a setting, run this version again with <code>--open</code> to see the updated report.</p>` : ""}
|
|
122
125
|
</section>
|
|
123
126
|
|
|
124
127
|
<section class="chapter" aria-labelledby="map-title">
|
|
@@ -129,6 +132,41 @@ function body(r, { version, scanned }) {
|
|
|
129
132
|
${installedSection(r.installed ?? { agents: [], editors: [] })}`;
|
|
130
133
|
}
|
|
131
134
|
|
|
135
|
+
function computerReviewHtml(review, error, demo) {
|
|
136
|
+
if (!review && !error) return "";
|
|
137
|
+
const heading = '<h2 id="computer-review-title">Computer review</h2>';
|
|
138
|
+
const section = (content) => `<section class="chapter" aria-labelledby="computer-review-title">${heading}${content}</section>`;
|
|
139
|
+
if (error) return section(`<p class="chapter-intro">${esc(error)}</p>`);
|
|
140
|
+
const first = review.previousScanAt === null;
|
|
141
|
+
const shown = new Set(review.changes.map((r) => r.id));
|
|
142
|
+
const outstanding = review.pending.filter((r) => !shown.has(r.id));
|
|
143
|
+
const intro = first ? "First scan on this computer." : review.changes.length ? plural(review.changes.length, "change") + " since your last scan." :
|
|
144
|
+
review.unverified.length ? "No changes in the settings we could verify." : "No changes since your last scan.";
|
|
145
|
+
const rows = (list, existing) => `<ul class="computer-changes">${list.map((row) => `<li>
|
|
146
|
+
<div><strong>${esc(changeLabel(row, existing))}</strong><p class="computer-value"><code>${esc(changeValue(row))}</code></p><p class="computer-file">${esc(row.file)}</p>${row.observationId ? `<p class="computer-file">${esc(editorText(row.editor, row.editorScope))} · ${esc(row.observationId)}</p>` : ""}</div>
|
|
147
|
+
<div class="computer-decision">${row.id ? `Awaiting approval<code>${esc(row.id)}</code>` : "Approved"}</div>
|
|
148
|
+
</li>`).join("")}</ul>`;
|
|
149
|
+
const notes = review.unverified.map((f) => "Could not fully verify " + f + ". Any earlier decision is kept.");
|
|
150
|
+
const accepted = review.risks.filter((r) => r.acceptedAt).length;
|
|
151
|
+
if (accepted) notes.push(plural(accepted, "accepted risk") + (accepted === 1 ? " is" : " are") + " still present. See Findings.");
|
|
152
|
+
if (review.confirmation) notes.push(review.confirmation);
|
|
153
|
+
const past = review.earlierRisks.map((r) => `<li><code>${esc(r.rule)}</code> · ${esc(r.file)} · accepted ${esc(fmtDate(r.acceptedAt))} by ${esc(r.acceptedBy ?? "an unknown account")} · ${esc(r.status)}</li>`).join("");
|
|
154
|
+
const history = review.history ?? { events: [], incomplete: true };
|
|
155
|
+
const events = history.events.slice().reverse().map((e) => {
|
|
156
|
+
const iso = new Date(e.at).toISOString();
|
|
157
|
+
return `<li><time datetime="${iso}">${iso.replace("T", " ").replace("Z", " UTC")}</time><span>${esc(historyDescription(e))}</span></li>`;
|
|
158
|
+
}).join("");
|
|
159
|
+
return section(`<p class="chapter-intro">${esc(intro)}</p>
|
|
160
|
+
${review.changes.length ? rows(review.changes, false) : ""}
|
|
161
|
+
${outstanding.length ? `<h3 class="map-scope">Awaiting your approval (${outstanding.length})</h3>${rows(outstanding, first)}` : ""}
|
|
162
|
+
${notes.map((n) => `<p class="computer-note">${esc(n)}</p>`).join("")}
|
|
163
|
+
${past ? `<h3 class="map-scope">Earlier risk decisions</h3><ul>${past}</ul>` : ""}
|
|
164
|
+
${!demo && (review.pending.length || review.risks.some((r) => !r.acceptedAt)) ? '<p class="next-step">Run again with <code>--review</code> to decide one at a time, or <code>--approve ID</code> to choose one.</p>' : ""}
|
|
165
|
+
<details class="computer-history"${demo ? " open" : ""}><summary>Computer history (${history.events.length})</summary>
|
|
166
|
+
${history.incomplete ? `<p>${esc(earlierBuildNote)}</p>` : ""}
|
|
167
|
+
${events ? `<ol aria-label="Newest events first">${events}</ol>` : "<p>No events recorded yet.</p>"}</details>`);
|
|
168
|
+
}
|
|
169
|
+
|
|
132
170
|
function countsList(counts) {
|
|
133
171
|
const items = ["critical", "high", "medium", "low"]
|
|
134
172
|
.filter((s) => counts[s])
|