@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/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
@@ -0,0 +1,95 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+
6
+ const LATEST = "https://registry.npmjs.org/@misconfig%2fcli/latest";
7
+ const DAY = 86400000;
8
+ const core = "(0|[1-9][0-9]*)";
9
+ const semver = new RegExp("^" + [core, core, core].join("\\.") + "(?:-([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$");
10
+
11
+ function parts(version) {
12
+ if (typeof version !== "string" || version.length > 128) return null;
13
+ const m = semver.exec(version);
14
+ if (!m) return null;
15
+ const pre = m[4]?.split(".");
16
+ if (pre?.some((s) => /^0\d+$/.test(s))) return null;
17
+ return { main: m.slice(1, 4).map((s) => BigInt(s)), pre };
18
+ }
19
+
20
+ export function compareVersions(a, b) {
21
+ const x = parts(a), y = parts(b);
22
+ if (!x || !y) return null;
23
+ for (let i = 0; i < 3; i++) if (x.main[i] !== y.main[i]) return x.main[i] > y.main[i] ? 1 : -1;
24
+ if (!x.pre || !y.pre) return x.pre ? -1 : y.pre ? 1 : 0;
25
+ for (let i = 0; i < Math.min(x.pre.length, y.pre.length); i++) {
26
+ const p = x.pre[i], q = y.pre[i];
27
+ if (p === q) continue;
28
+ const pn = /^\d+$/.test(p), qn = /^\d+$/.test(q);
29
+ if (pn !== qn) return pn ? -1 : 1;
30
+ return (pn ? BigInt(p) > BigInt(q) : p > q) ? 1 : -1;
31
+ }
32
+ return Math.sign(x.pre.length - y.pre.length);
33
+ }
34
+
35
+ async function registryVersion(fetchImpl) {
36
+ const res = await fetchImpl(LATEST, { headers: { accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(1800) });
37
+ if (!res.ok || !res.body) return null;
38
+ const chunks = [];
39
+ let size = 0;
40
+ for await (const chunk of res.body) {
41
+ size += chunk.length;
42
+ if (size > 128 * 1024) return null;
43
+ chunks.push(chunk);
44
+ }
45
+ const data = JSON.parse(Buffer.concat(chunks).toString("utf8"));
46
+ const parsed = parts(data.version);
47
+ return data.name === "@misconfig/cli" && parsed && !parsed.pre ? data.version : null;
48
+ }
49
+
50
+ export function automaticUpdateCheck(opts, env = process.env, terminal = process.stdout.isTTY && process.stdin.isTTY) {
51
+ return Boolean(terminal && !opts.offline && !opts.demo && !opts.json && !opts.projectOnly && !opts.noHistory && !opts.noUpdate
52
+ && !opts.failOn && !env.CI && !env.NO_UPDATE_NOTIFIER && env.MISCONFIG_NO_UPDATE_CHECK !== "1");
53
+ }
54
+
55
+ export async function packageUpdate(installed, { force = false, offline = false, fetchImpl = fetch,
56
+ cache = path.join(homedir(), ".misconfig", "npm-update.json"), now = Date.now() } = {}) {
57
+ if (offline) return { installed, latest: null, status: "offline" };
58
+ let prior;
59
+ try { prior = JSON.parse(await readFile(cache, "utf8")); } catch {}
60
+ const upgradedFrom = compareVersions(installed, prior?.installed) === 1 ? prior.installed : null;
61
+ const fresh = Number.isFinite(prior?.checkedAt) && now >= prior.checkedAt && now - prior.checkedAt < DAY;
62
+ let latest = prior?.latest, checkedAt = prior?.checkedAt;
63
+ if (force || !fresh || !parts(latest) || parts(latest).pre) {
64
+ try { latest = await registryVersion(fetchImpl); } catch { latest = null; }
65
+ if (!latest) return { installed, latest: null, status: "unavailable" };
66
+ checkedAt = now;
67
+ }
68
+ const order = compareVersions(latest, installed);
69
+ const status = order > 0 ? "available" : order < 0 ? "ahead" : "current";
70
+ // An explicit registry query can be consumed as JSON by a script. Leave
71
+ // the first interactive release announcement available for the next scan.
72
+ const firstReleaseNotice = !force && status === "current" && prior?.announced !== installed;
73
+ const announced = firstReleaseNotice ? installed : prior?.announced;
74
+ if (checkedAt !== prior?.checkedAt || installed !== prior?.installed || latest !== prior?.latest || firstReleaseNotice) {
75
+ const tmp = cache + "." + randomUUID();
76
+ try {
77
+ await mkdir(path.dirname(cache), { recursive: true, mode: 0o700 });
78
+ await writeFile(tmp, JSON.stringify({ installed, latest, checkedAt, announced }), { flag: "wx", mode: 0o600 });
79
+ await rename(tmp, cache);
80
+ } catch {} finally { await unlink(tmp).catch(() => {}); }
81
+ }
82
+ return { installed, latest, status, upgradedFrom, firstReleaseNotice };
83
+ }
84
+
85
+ export function updateMessage(update, explicit = false) {
86
+ switch (update.status) {
87
+ case "available": return "misconfig " + update.latest + " is available on npm (installed " + update.installed + "). Run " + (process.platform === "win32" ? "npx.cmd" : "npx") + " @misconfig/cli@latest to use it.";
88
+ case "offline": return explicit ? "Offline mode is on. The npm registry was not contacted." : "";
89
+ case "unavailable": return explicit ? "Could not check the npm registry for a stable release." : "";
90
+ default:
91
+ if (update.upgradedFrom && update.status === "current") return "Now running misconfig " + update.installed + ", updated from " + update.upgradedFrom + ".";
92
+ if (update.firstReleaseNotice) return "You're running misconfig " + update.installed + ", the latest npm release." + (update.installed === "1.4.0" ? " Try --demo to see the new computer review and edit history." : "");
93
+ return explicit ? "Installed misconfig " + update.installed + ". Latest stable release on npm is " + update.latest + "." : "";
94
+ }
95
+ }
package/lib/print.js CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { SCOPES } from "../engine/explain.js";
6
6
  import { INSTALLED_BY } from "../engine/index.js";
7
+ import { reviewLines } from "./computer-review.js";
7
8
 
8
9
  const env = process.env;
9
10
 
@@ -101,12 +102,16 @@ export function printReport(result, { version, scanned, explain = false, open =
101
102
  const out = [];
102
103
  // One blank line between blocks, never two.
103
104
  const gap = () => out.length && out[out.length - 1] !== "" && out.push("");
104
- const where = scanned.projectSkipped ? "your home folder" : scanned.project;
105
+ const where = scanned.demo ? "the sample computer" : scanned.projectSkipped ? "your home folder" : scanned.project;
105
106
  const sent = lookedUp ? "Everything ran here. Only package names and versions went to OSV.dev, to look them up." : "Everything ran here; nothing was uploaded.";
106
107
  out.push(`${bold("misconfig")} ${dim(version)}`);
107
- const project = scanned.projectSkipped ? " To check a project, run it in the project's folder." : "";
108
- out.push(...wrap(`Checked ${where}${scanned.user ? " and the agent settings on this computer" : ""}. ${sent}${knownLine(known)}${project}`, 0).map(dim));
108
+ const project = scanned.projectSkipped && !scanned.demo ? " To check a project, run it in the project's folder." : "";
109
+ out.push(...wrap(`Checked ${where}${scanned.user && !scanned.demo ? " and the agent settings on this computer" : ""}. ${sent}${knownLine(known)}${project}`, 0).map(dim));
109
110
  out.push("");
111
+ if (result.computerReview) {
112
+ out.push(bold("Computer review"), ...reviewLines(result.computerReview, scanned.demo).map(oneLine), "");
113
+ }
114
+ if (result.computerReviewError) out.push(oneLine(result.computerReviewError), "");
110
115
 
111
116
  // Every file that directs an agent, where it applies, and what it tells the
112
117
  // agent. Worked out on this computer and shown only here and in the page
@@ -162,6 +167,7 @@ export function printReport(result, { version, scanned, explain = false, open =
162
167
  // Where it is, then the rule, which misconfig.ai/rules explains.
163
168
  const at = f.file ? fitPath(f.file, width() - 16 - f.id.length) + (f.line ? `:${f.line}` : "") : "";
164
169
  out.push(` ${dim(at ? `${at} ${f.id}` : f.id)}`);
170
+ if (f.review) out.push(" " + (f.review.acceptedAt ? "Risk accepted on " + new Date(f.review.acceptedAt).toISOString().slice(0, 10) + " by " + oneLine(f.review.acceptedBy ?? "an unknown account") : scanned.demo ? "Awaiting risk review" : "Accept risk: --approve " + f.review.id));
165
171
  if (sev === "critical" || sev === "high" || sev === "medium") out.push(...wrap(f.why, 6));
166
172
  out.push(...wrap(f.fix, 11, ` ${dim("Fix")} `));
167
173
  }
@@ -179,6 +185,11 @@ export function printReport(result, { version, scanned, explain = false, open =
179
185
  // The verdict, last, where it's on screen when the check finishes.
180
186
  out.push(...verdict(result), "");
181
187
  if (result.stats.truncated) out.push(...stopped(), "");
188
+ if (scanned.demo) {
189
+ out.push("Run --demo again to start a fresh sample.");
190
+ process.stdout.write(out.join("\n") + "\n");
191
+ return;
192
+ }
182
193
  const next = [];
183
194
  if (!explain && map.some((f) => f.details?.length)) next.push(["Everything each file says", `${npx} @misconfig/cli --explain`]);
184
195
  if (!open) next.push(["Full report in your browser", `${npx} @misconfig/cli --open`]);
@@ -0,0 +1,99 @@
1
+ import { userInfo } from "node:os";
2
+
3
+ const observation = { added: "addition of ", changed: "change to ", removed: "removal of " };
4
+ const approval = { added: "", changed: "the change to ", removed: "removing " };
5
+
6
+ // Read the effective OS account only when a decision is made. A scan cannot
7
+ // identify the person or process that wrote a config file.
8
+ export function localAccount() {
9
+ try { return userInfo().username || null; }
10
+ catch { return null; }
11
+ }
12
+
13
+ export function changeEvent(action, row, at, actor = null) {
14
+ const { kind, label, file, before, after, changedFields } = row;
15
+ return { action, at, actor, kind, label, file, before, after, changedFields, ...(action === "approved" ? { reviewId: row.id } : {}) };
16
+ }
17
+
18
+ export function editorText(editor, scope) {
19
+ if (!editor) return "Edit author unknown";
20
+ if (editor.basis === "conflicting") return "Edit author uncertain (" + editor.sources.map((s) => s.name + ", " + (s.basis === "tool-record" ? "tool record" : "self-reported")).join(" / ") + ")";
21
+ if (scope === "latest") return "Latest observed edit by " + editor.name + (editor.basis === "tool-record" ? " (local tool record)" : " (self-reported)");
22
+ return "Edited by " + editor.name + (editor.basis === "tool-record" ? " (local tool record)" : " (self-reported)");
23
+ }
24
+
25
+ // Approvals keep pointing at the same observed edit even after another scan,
26
+ // or when the user imports evidence after approving.
27
+ export function linkEditors(history, rows) {
28
+ const latest = new Map();
29
+ for (const e of history.events) if (e.action === "observed" && e.subject) latest.set(e.subject, e);
30
+ for (const row of rows) {
31
+ const observed = latest.get(row.key);
32
+ if (observed) {
33
+ if (row.observationId !== observed.id) row.editorScope = observed.transition === row.id ? "change" : "latest";
34
+ Object.assign(row, { observationId: observed.id, editor: observed.editor ?? null });
35
+ }
36
+ }
37
+ }
38
+
39
+ export function addEditorEvidence(history, observed, source) {
40
+ const existing = observed.editor;
41
+ const sources = existing?.basis === "conflicting" ? existing.sources : existing ? [existing] : [];
42
+ if (sources.some((s) => s.name === source.name && s.basis === source.basis)) return;
43
+ observed.editor = sources.length ? { name: null, basis: "conflicting", sources: [...sources, source] } : source;
44
+ for (const e of history.events) if (e.action === "approved" && e.observationId === observed.id) e.editor = observed.editor;
45
+ }
46
+
47
+ export function claimEdit(history, id, account = localAccount()) {
48
+ const observed = history.events.find((e) => e.id === id && e.action === "observed");
49
+ if (!observed) throw new Error("Choose an observed edit ID from --history.");
50
+ if (!account) throw new Error("The OS account name is unavailable. The edit could not be claimed.");
51
+ addEditorEvidence(history, observed, { name: account, basis: "self-reported", at: Date.now() });
52
+ return observed;
53
+ }
54
+
55
+ export function riskEvent(id, risk) {
56
+ const { at, file, rule, severity, label } = risk;
57
+ return { action: "accepted-risk", at, actor: risk.by ?? null, file, rule, severity, label: label ?? null, reviewId: id };
58
+ }
59
+
60
+ export function validHistory(history) {
61
+ if (typeof history?.incomplete !== "boolean" || !Array.isArray(history.events)) return false;
62
+ return history.events.every((e) => {
63
+ if (!e || !Number.isFinite(e.at) || Number.isNaN(new Date(e.at).getTime()) || !(e.actor === null || typeof e.actor === "string")) return false;
64
+ if (e.editor != null) {
65
+ const sources = e.editor.basis === "conflicting" ? e.editor.sources : [e.editor];
66
+ if (!Array.isArray(sources) || !sources.length || !sources.every((s) => s && typeof s.name === "string" && ["self-reported", "tool-record"].includes(s.basis) && Number.isFinite(s.at))) return false;
67
+ }
68
+ if (e.action === "baseline") return e.actor === null && Number.isInteger(e.count) && e.count >= 0;
69
+ if (typeof e.file !== "string") return false;
70
+ if (e.action === "accepted-risk") return typeof e.rule === "string" && typeof e.severity === "string" && (e.label === null || typeof e.label === "string") && typeof e.reviewId === "string";
71
+ return (e.action === "observed" && e.actor === null || e.action === "approved" && typeof e.reviewId === "string")
72
+ && ["added", "changed", "removed"].includes(e.kind) && typeof e.label === "string"
73
+ && [e.before, e.after].every((s) => s === null || typeof s === "string") && Array.isArray(e.changedFields) && e.changedFields.every((s) => typeof s === "string");
74
+ });
75
+ }
76
+
77
+ export function changeValue(row) {
78
+ if (row.kind === "changed" && row.before === row.after) {
79
+ const detail = row.changedFields.length ? row.changedFields.join(", ") + " changed" : "content changed";
80
+ return row.after + " (" + detail + ")";
81
+ }
82
+ return [row.before, row.after].filter((v) => v !== null).join(" → ");
83
+ }
84
+
85
+ export const earlierBuildNote = "Earlier builds recorded some risk acceptance dates. They did not record review accounts or a full change history.";
86
+
87
+ export function historyDescription(event) {
88
+ if (event.action === "baseline") return "First scan recorded " + event.count + (event.count === 1 ? " setting." : " settings.");
89
+ const account = event.actor ?? "Account unknown";
90
+ if (event.action === "accepted-risk") return [account + " accepted " + event.severity + " risk " + event.rule, event.label, event.file].filter(Boolean).join(" · ");
91
+ const action = event.action === "approved" ? account + " approved " + approval[event.kind] + event.label
92
+ : "Observed " + observation[event.kind] + event.label;
93
+ const authorship = event.action === "observed" || event.observationId ? editorText(event.editor, event.editorScope) : null;
94
+ return [action, changeValue(event), event.file, authorship, event.action === "observed" ? event.id : null].filter(Boolean).join(" · ");
95
+ }
96
+
97
+ export function historyLine(event) {
98
+ return new Date(event.at).toISOString() + " " + historyDescription(event);
99
+ }
@@ -0,0 +1,142 @@
1
+ import { randomBytes, randomUUID } from "node:crypto";
2
+ import { link, mkdir, open, readdir, readFile, unlink } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+ import { riskEvent, validHistory } from "./review-history.js";
6
+ import { privateValueLabel, PRIVATE_SETTING_SUMMARY } from "./computer-snapshot.js";
7
+
8
+ const revisionName = (n) => "state-" + n + ".json";
9
+ const dict = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
10
+ const hex = (s) => typeof s === "string" && /^[0-9a-f]{64}$/.test(s);
11
+ const entries = (map) => dict(map) && Object.entries(map).every(([k,v]) => hex(k) && dict(v) && hex(v.hash)
12
+ && typeof v.file === "string" && typeof v.label === "string" && typeof v.summary === "string");
13
+
14
+ async function storage(operation) {
15
+ try { return await operation(); }
16
+ catch (err) { err.reviewStorage = true; throw err; }
17
+ }
18
+
19
+ function fresh() {
20
+ return { schema: 2, key: randomBytes(32).toString("hex"), scannedAt: null, seen: {}, approved: {}, removedPending: {}, receipts: {}, uncertain: [], offeredRisks: {}, acceptedRisks: {}, history: { incomplete: false, events: [] } };
21
+ }
22
+
23
+ // Preview builds could store a readable value below a general environment or
24
+ // header table. New snapshots preserve the HMAC but use a fixed summary. A
25
+ // normal scan writes the cleaned state back without changing its decisions.
26
+ function redactLegacySummaries(state) {
27
+ let changed = false;
28
+ const privateSummary = (label, value) => privateValueLabel(label) ? PRIVATE_SETTING_SUMMARY
29
+ : /^MCP /.test(label) && /^[a-z][a-z0-9+.-]*:\/\//i.test(value) ? "remote server" : null;
30
+ for (const collection of [state.seen, state.approved, state.removedPending ?? {}]) {
31
+ for (const item of Object.values(collection)) {
32
+ const summary = privateSummary(item.label, item.summary);
33
+ if (summary && item.summary !== summary) {
34
+ item.summary = summary;
35
+ changed = true;
36
+ }
37
+ }
38
+ }
39
+ for (const event of state.history?.events ?? []) {
40
+ for (const field of ["before", "after"]) {
41
+ if (typeof event[field] !== "string") continue;
42
+ const summary = privateSummary(event.label, event[field]);
43
+ if (summary && event[field] !== summary) {
44
+ event[field] = summary;
45
+ changed = true;
46
+ }
47
+ }
48
+ }
49
+ return changed;
50
+ }
51
+
52
+ async function revisions(dir, clean = false) {
53
+ const files = await readdir(dir);
54
+ if (clean) {
55
+ for (const f of files) {
56
+ const writing = /^\.writing-(\d+)-[0-9a-f-]{36}$/.exec(f);
57
+ if (!writing || Number(writing[1]) === process.pid) continue;
58
+ try { process.kill(Number(writing[1]), 0); }
59
+ catch (err) {
60
+ if (err.code === "ESRCH") await unlink(path.join(dir, f)).catch(() => {});
61
+ }
62
+ }
63
+ }
64
+ return files.filter((f) => /^state-[1-9]\d{0,14}\.json$/.test(f))
65
+ .map((f) => Number(f.slice(6, -5))).sort((a,b) => b - a);
66
+ }
67
+
68
+ async function latest(dir) {
69
+ for (;;) {
70
+ const [revision = 0] = await revisions(dir);
71
+ if (!revision) return { revision, state: fresh() };
72
+ const file = path.join(dir, revisionName(revision));
73
+ try {
74
+ const state = JSON.parse(await readFile(file, "utf8"));
75
+ if (!dict(state) || ![1, 2].includes(state.schema) || !hex(state.key) || !Array.isArray(state.uncertain)
76
+ || !entries(state.seen) || !entries(state.approved) || !entries(state.removedPending ?? {}) || ![state.receipts, state.offeredRisks, state.acceptedRisks].every(dict)
77
+ || !Object.values(state.acceptedRisks).every((r) => dict(r) && Number.isFinite(r.at) && !Number.isNaN(new Date(r.at).getTime()))) throw new Error("Unexpected state format");
78
+ state.removedPending ??= {};
79
+ if (state.schema === 1) {
80
+ const events = Object.entries(state.acceptedRisks).map(([id, risk]) => riskEvent(id, risk)).sort((a,b) => a.at - b.at);
81
+ state.history = { incomplete: state.scannedAt !== null, events };
82
+ state.schema = 2;
83
+ }
84
+ if (!validHistory(state.history)) throw new Error("Unexpected event history format");
85
+ for (const [index, event] of state.history.events.entries()) if (event.action === "observed") event.id ??= "e-" + (index + 1);
86
+ const legacyRedacted = redactLegacySummaries(state);
87
+ return { revision, state, legacyRedacted };
88
+ } catch (err) {
89
+ if (err.code === "ENOENT") continue;
90
+ throw new Error("Could not read computer review history at " + file + ". Your saved approvals were left in place.", { cause: err });
91
+ }
92
+ }
93
+ }
94
+
95
+ const reviewDirectory = () => path.join(homedir(), ".misconfig", "computer-v1");
96
+
97
+ // A history lookup never scans, creates a directory or publishes a revision.
98
+ export async function readHistory(dir = reviewDirectory()) {
99
+ try { return (await latest(dir)).state.history; }
100
+ catch (err) {
101
+ if (err.code === "ENOENT") return { incomplete: false, events: [] };
102
+ throw err;
103
+ }
104
+ }
105
+
106
+ // Publishing the next generation with an exclusive hard link is atomic on
107
+ // Windows, macOS and Linux. Readers can only open completed JSON. A competing
108
+ // writer rereads the winner and replays its edit, with no abandoned lock.
109
+ export async function updateReview(edit, dir = reviewDirectory()) {
110
+ await storage(() => mkdir(dir, { mode: 0o700, recursive: true }));
111
+ for (let attempt = 0; attempt < 16; attempt++) {
112
+ const { revision, state, legacyRedacted } = await storage(() => latest(dir));
113
+ const result = await edit(state);
114
+ const next = revision + 1;
115
+ const temp = path.join(dir, ".writing-" + process.pid + "-" + randomUUID());
116
+ const handle = await storage(() => open(temp, "wx", 0o600));
117
+ try {
118
+ try {
119
+ await storage(() => handle.writeFile(JSON.stringify(state)));
120
+ await storage(() => handle.sync());
121
+ } finally {
122
+ await handle.close();
123
+ }
124
+ try {
125
+ await storage(() => link(temp, path.join(dir, revisionName(next))));
126
+ } catch (err) {
127
+ if (err.code === "EEXIST") continue;
128
+ throw err;
129
+ }
130
+ const versions = await storage(() => revisions(dir, true));
131
+ if (versions[0] > next) continue;
132
+ // Keep the previous complete file as well. Never clean up a newer
133
+ // generation that another scanner has just published.
134
+ await Promise.all(versions.filter((n) => n < next - (legacyRedacted ? 0 : 1)).map((n) =>
135
+ unlink(path.join(dir, revisionName(n))).catch(() => {})));
136
+ return result;
137
+ } finally {
138
+ await unlink(temp).catch(() => {});
139
+ }
140
+ }
141
+ throw new Error("Other scans are updating your computer review. Run the command again.");
142
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@misconfig/cli",
3
- "version": "1.3.2",
4
- "description": "See every file that controls your AI coding agents, what each one tells them to do, which settings put your machine at risk, and whether anything they run is known malware. Runs on your computer.",
3
+ "version": "1.4.0",
4
+ "description": "Check AI agent settings for risks and known malware. Review changes since your last scan and keep a local history of approvals and accepted risks.",
5
5
  "keywords": [
6
6
  "claude-code",
7
7
  "codex",
@@ -34,6 +34,7 @@
34
34
  },
35
35
  "files": [
36
36
  "bin",
37
+ "demo.cmd",
37
38
  "lib",
38
39
  "engine",
39
40
  "report",