@misconfig/cli 1.3.1 → 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.
@@ -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 something, run the check again to see the new grade: <code>npx @misconfig/cli@latest --open</code>.</p>` : ""}
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])
package/lib/main.js CHANGED
@@ -3,21 +3,41 @@ import { createInterface } from "node:readline/promises";
3
3
  import { analyze, applyLookup, useKnownMalware } from "../engine/index.js";
4
4
  import { KNOWN_AS_OF } from "../engine/known.js";
5
5
  import { discover } from "./discover.js";
6
- import { printReport, printOpenResult, printLookupPreview, printLookupResult } from "./print.js";
6
+ import { printReport, printOpenResult, printLookupPreview, printLookupResult, oneLine } from "./print.js";
7
7
  import { writeReport, openInBrowser } from "./html.js";
8
8
  import { lookupQueries, osvLookup, installsOnly } from "./lookup.js";
9
+ import { computerSnapshot } from "./computer-snapshot.js";
10
+ import { observe, approve, showApproval, changeText } from "./computer-review.js";
11
+ import { readHistory, updateReview } from "./review-store.js";
12
+ import { claimEdit, earlierBuildNote, historyLine } from "./review-history.js";
13
+ import { withDemo } from "./demo.js";
14
+ import { attributeEdits } from "./edit-attribution.js";
15
+ import { automaticUpdateCheck, packageUpdate, updateMessage } from "./package-update.js";
16
+ import { LIMITS } from "../engine/paths.js";
9
17
 
10
18
  const HELP = `Usage: npx @misconfig/cli [folder] [options]
11
19
 
12
- Finds every file that controls your AI coding agents, on this computer and in
13
- the folder (the current folder by default), and checks them for risky
14
- settings. It also checks the MCP servers, editor extensions, skills and agent
15
- versions installed for known malware and missing security fixes. Everything
20
+ Finds the files that control your AI coding agents on this computer and in
21
+ the folder (the current folder by default). It checks the settings for risks
22
+ and records changes to computer settings. It also checks the installed MCP
23
+ servers, editor extensions, skills and agent versions for known malware and
24
+ missing security fixes. Everything
16
25
  runs here. It downloads today's list of known malware from misconfig.ai
17
- first, a request that carries nothing about your setup. Nothing else is sent
18
- unless you use --lookup.
26
+ first. Interactive computer scans also check for a newer CLI on npm.
27
+ Neither request sends your files or settings. --offline skips both.
28
+ Nothing else is sent unless you use --lookup.
19
29
 
20
30
  Options
31
+ --demo Try the review offline on a disposable sample computer
32
+ --history Show recorded computer changes and who approved them
33
+ --attribute Match edits against recent local Claude and Codex records
34
+ --session FILE Use this local JSONL session for attribution (repeatable)
35
+ --i-edited ID Mark an observed edit (such as e-4) as yours, independently of approval
36
+ --check-update Check npm for a newer stable CLI release
37
+ --no-update-check Skip the automatic npm release check
38
+ --review Review pending computer changes and risks one at a time
39
+ --approve ID Approve one exact change or accept one visible risk
40
+ --no-history Scan without reading or updating computer review history
21
41
  --explain Show everything each file tells your agents: rules,
22
42
  permissions, MCP servers, hooks and hidden text, and
23
43
  what's installed
@@ -28,9 +48,9 @@ Options
28
48
  asks first.
29
49
  --open Save the full report as a page on this computer and
30
50
  open it in your browser. Nothing is uploaded.
31
- --offline Don't download today's list of known malware. The check
32
- uses the list in this release. Same as setting
33
- MISCONFIG_OFFLINE=1.
51
+ --offline Use bundled malware data and skip the npm update check.
52
+ An explicit --lookup still asks to contact OSV.dev.
53
+ Same as setting MISCONFIG_OFFLINE=1.
34
54
  --yes Look up without asking, for scripts and CI
35
55
  --json Print the full result as JSON
36
56
  --project-only Skip the agent settings on this computer
@@ -64,21 +84,141 @@ export async function main(argv) {
64
84
  else if (a === "--json") opts.json = true;
65
85
  else if (a === "--explain") opts.explain = true;
66
86
  else if (a === "--project-only") opts.projectOnly = true;
87
+ else if (a === "--no-history") opts.noHistory = true;
88
+ else if (a === "--history") opts.history = true;
89
+ else if (a === "--attribute") opts.attribute = true;
90
+ else if (a === "--check-update") opts.checkUpdate = true;
91
+ else if (a === "--no-update-check") opts.noUpdate = true;
92
+ else if (a === "--session") {
93
+ const file = argv[++i];
94
+ if (!file || file.startsWith("-")) throw new Error("--session needs a local session JSONL file.");
95
+ (opts.sessions ??= []).push(file);
96
+ opts.attribute = true;
97
+ }
98
+ else if (a === "--i-edited") {
99
+ const id = argv[++i];
100
+ if (opts.claim || !/^e-[1-9][0-9]*$/.test(id ?? "")) throw new Error("--i-edited needs one observed edit ID from --history.");
101
+ opts.claim = id;
102
+ }
103
+ else if (a === "--demo") opts.demo = true;
104
+ else if (a === "--review") opts.review = true;
105
+ else if (a === "--approve" || a.startsWith("--approve=")) {
106
+ if (opts.approve) throw new Error("Choose one review ID at a time.");
107
+ opts.approve = a === "--approve" ? argv[++i] : a.slice(10);
108
+ if (!/^[cr]-[0-9a-f]{20}$/.test(opts.approve ?? "")) throw new Error("--approve needs the ID beside one computer change or risk.");
109
+ }
67
110
  else if (a === "--fail-on" || a.startsWith("--fail-on=")) {
68
111
  opts.failOn = (a.includes("=") ? a.split("=")[1] : argv[++i] ?? "").toLowerCase();
69
112
  if (!LEVELS.includes(opts.failOn)) throw new Error(`--fail-on needs one of: ${LEVELS.join(", ")}.`);
70
113
  } else if (a.startsWith("-")) throw new Error(`Unknown option ${a}. Run npx @misconfig/cli --help for the options.`);
71
- else opts.dir = a;
114
+ else { opts.dir = a; opts.folderGiven = true; }
115
+ }
116
+
117
+ if (opts.history || opts.claim || opts.checkUpdate) {
118
+ if ([opts.history, opts.claim, opts.checkUpdate].filter(Boolean).length > 1 || opts.demo || opts.projectOnly || opts.noHistory || opts.review || opts.approve || opts.open || opts.lookup || opts.explain || opts.failOn || opts.yes || opts.folderGiven || opts.attribute) throw new Error("Use --history, --i-edited ID or --check-update as a separate command. Each supports --json.");
119
+ if (opts.checkUpdate) {
120
+ const update = await packageUpdate(await version(), { force: true, offline: opts.offline });
121
+ console.log(opts.json ? JSON.stringify(update, null, 2) : updateMessage(update, true));
122
+ return ["unavailable", "offline"].includes(update.status) ? 2 : 0;
123
+ }
124
+ if (opts.claim) {
125
+ const event = await updateReview((state) => claimEdit(state.history, opts.claim));
126
+ console.log(opts.json ? JSON.stringify(event, null, 2) : oneLine(historyLine(event)));
127
+ return 0;
128
+ }
129
+ const history = await readHistory();
130
+ if (opts.json) console.log(JSON.stringify(history, null, 2));
131
+ else {
132
+ const lines = ["Computer history (newest first)"];
133
+ if (history.incomplete) lines.push(earlierBuildNote);
134
+ if (!history.events.length) lines.push("No events recorded yet.");
135
+ for (const event of history.events.slice().reverse()) lines.push(historyLine(event));
136
+ console.log(lines.map(oneLine).join("\n"));
137
+ }
138
+ return 0;
72
139
  }
140
+ if (opts.demo && (opts.attribute || opts.projectOnly || opts.noHistory || opts.approve || opts.lookup || opts.failOn || opts.yes || opts.folderGiven)) throw new Error("Use --demo to review the sample computer. It also supports --open, --explain and --json.");
141
+ if ((opts.attribute || opts.review || opts.approve) && (opts.noHistory || opts.projectOnly)) throw new Error("Computer review needs a scan with computer history enabled.");
142
+ if (opts.review && (opts.approve || opts.json || !process.stdin.isTTY || !process.stdout.isTTY)) throw new Error("Use --review in a terminal, or run --approve ID to choose one item directly.");
143
+ if (opts.demo) return withDemo((demo) => runScan({ ...opts, offline: true }, demo));
144
+ return runScan(opts);
145
+ }
73
146
 
147
+ async function runScan(opts, demo) {
148
+ const update = automaticUpdateCheck(opts) ? packageUpdate(await version()) : null;
74
149
  const known = opts.offline ? { asOf: `${KNOWN_AS_OF}T00:00:00Z`, from: "offline" } : await todaysList();
75
- const input = await discover({ dir: opts.dir, includeUser: !opts.projectOnly });
76
- let result = { ...check(input), knownMalware: known };
77
- let lookedUp = false;
78
- if (opts.lookup) ({ result, lookedUp } = await lookup(opts, result));
150
+ // A concurrent local scan can cause the transaction to retry. Reuse an
151
+ // OSV answer only for the same packages the user agreed to look up.
152
+ let lookupCache;
153
+ async function scan(state, lookupAuthors = true) {
154
+ const snapshot = state && computerSnapshot(state.key, demo?.discovery);
155
+ const currentFiles = (opts.attribute || demo) && snapshot && lookupAuthors ? new Map() : null;
156
+ const collect = currentFiles ? (file, raw, flags, original) => {
157
+ snapshot.collect(file, raw, flags, original);
158
+ if (typeof original === "string" && original.length <= LIMITS.maxFileBytes && snapshot.verified.has(file)) currentFiles.set(file, original);
159
+ } : snapshot?.collect;
160
+ const input = await discover({ dir: opts.dir, includeUser: !opts.projectOnly, ...demo?.discovery, onComputerFile: collect });
161
+ let result = { ...check(input), knownMalware: known };
162
+ if (demo) { result.demo = true; input.scanned.demo = true; }
163
+ let lookedUp = false;
164
+ if (opts.lookup) {
165
+ const key = JSON.stringify(lookupQueries(result));
166
+ if (lookupCache?.key !== key) lookupCache = { key, ...await lookup(opts, result) };
167
+ lookedUp = lookupCache.lookedUp;
168
+ if (lookedUp) result = applyLookup(result, lookupCache.hits);
169
+ }
170
+ if (state) {
171
+ snapshot.inventory(input, result.installed);
172
+ await snapshot.checkMissing({ ...state.removedPending, ...state.approved, ...state.seen });
173
+ result.computerReview = observe(state, snapshot, result.findings);
174
+ if (currentFiles) result.computerReview.attribution = await attributeEdits(state, result.computerReview, currentFiles,
175
+ demo ? { ...demo.discovery, sessions: [demo.session] } : { sessions: opts.sessions });
176
+ }
177
+ return { input, result, lookedUp };
178
+ }
179
+ if (demo) {
180
+ await updateReview(async (state) => {
181
+ const { result } = await scan(state);
182
+ for (const row of result.computerReview.pending) approve(state, row.id, "Demo setup");
183
+ }, demo.store);
184
+ await demo.bump();
185
+ if (!opts.json) console.log("Demo · A sample Codex tool record accompanies the calendar update from 1.2.3 to 1.2.4. The mail server has an unpinned package.\nThis run uses a fresh sample profile and deletes it when you finish.");
186
+ }
187
+ let report;
188
+ if (opts.projectOnly || opts.noHistory) report = await scan(null);
189
+ else {
190
+ try {
191
+ report = await updateReview(async (state) => {
192
+ const next = await scan(state);
193
+ if (opts.approve) showApproval(next.result.computerReview, next.result.findings, approve(state, opts.approve));
194
+ return next;
195
+ }, demo?.store);
196
+ }
197
+ catch (err) {
198
+ if (demo || opts.approve || opts.review || !err.reviewStorage) throw err;
199
+ report = await scan(null);
200
+ report.result.computerReviewError = "Computer history unavailable. " + err.message;
201
+ }
202
+ }
203
+ const { input, result, lookedUp } = report;
204
+ const decide = (id, account) => updateReview(async (state) => {
205
+ // A prompt may have been left open while the file changed.
206
+ await scan(state, false);
207
+ return approve(state, id, account);
208
+ }, demo?.store);
209
+ if (opts.review || (demo && process.stdin.isTTY && process.stdout.isTTY && !opts.json)) await reviewAtTerminal(result, decide, Boolean(demo));
210
+ else if (demo) {
211
+ if (!opts.json) console.log("Playing the sample decisions as Demo reviewer.");
212
+ const review = result.computerReview;
213
+ for (const item of [...review.pending, ...review.risks]) showApproval(review, result.findings, await decide(item.id, "Demo reviewer"));
214
+ }
79
215
 
80
216
  if (opts.json) process.stdout.write(JSON.stringify(result, null, 2) + "\n");
81
217
  else printReport(result, { version: await version(), scanned: input.scanned, explain: opts.explain, open: opts.open, lookedUp, known });
218
+ if (update) {
219
+ const notice = updateMessage(await update);
220
+ if (notice) console.error("\n" + notice);
221
+ }
82
222
 
83
223
  if (opts.open) await openReport(opts, input, result);
84
224
 
@@ -88,7 +228,32 @@ export async function main(argv) {
88
228
  // A check that couldn't see everything shouldn't pass a CI gate.
89
229
  if (result.stats.truncated) return 2;
90
230
  }
91
- return 0;
231
+ return result.computerReviewError ? 2 : 0;
232
+ }
233
+
234
+ async function reviewAtTerminal(result, decide, demo) {
235
+ const review = result.computerReview;
236
+ process.stdout.write("\nReview " + (demo ? "the sample computer" : "this computer") + ". Y approves, Enter skips, and Q finishes. Each decision is saved immediately.\n");
237
+ for (const file of review.unverified) process.stdout.write("Could not fully verify " + oneLine(file) + ".\n");
238
+ const prompts = [
239
+ ...review.pending.map((row) => ({ id: row.id, text: changeText(row), question: "Approve this change?" })),
240
+ ...review.risks.filter((r) => !r.acceptedAt).map((r) => ({ id: r.id, text: r.severity + " · " + r.title + " · " + r.file, question: "Accept this risk and keep its warning visible?" })),
241
+ ];
242
+ for (const p of prompts) {
243
+ process.stdout.write("\n" + oneLine(p.text) + "\n");
244
+ const finding = result.findings.find((f) => f.review?.id === p.id);
245
+ if (finding) process.stdout.write(oneLine(finding.why) + "\nFix: " + oneLine(finding.fix) + "\n");
246
+ else {
247
+ const file = review.pending.find((r) => r.id === p.id)?.file;
248
+ for (const risk of review.risks.filter((r) => r.file === file)) process.stdout.write(" Risk in this file: " + oneLine(risk.title) + "\n");
249
+ }
250
+ const answer = await ask(process.stdout, p.question + " [y/N/q] ");
251
+ if (answer === "q" || answer === "quit") break;
252
+ if (answer !== "y" && answer !== "yes") continue;
253
+ const decision = await decide(p.id, demo ? "Demo reviewer" : undefined);
254
+ showApproval(review, result.findings, decision);
255
+ process.stdout.write(review.confirmation + "\n");
256
+ }
92
257
  }
93
258
 
94
259
  // Today's list of known malware from misconfig.ai, added to the one in this
@@ -146,7 +311,7 @@ async function lookup(opts, result) {
146
311
  const { hits, failed, asked } = await osvLookup(queries, { base, installs: installsOnly(result) });
147
312
  const next = applyLookup(result, hits);
148
313
  printLookupResult(out, { asked, failed, found: next.findings.length - result.findings.length });
149
- return { result: next, lookedUp: true };
314
+ return { result: next, lookedUp: true, hits };
150
315
  }
151
316
 
152
317
  // A yes from someone at the terminal, or --yes. Without a terminal and