@misconfig/cli 1.3.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
+ }
@@ -0,0 +1,63 @@
1
+ // --rules: a company's own rules, from the files named on the command line.
2
+ // A file is JSON: one rule, a list of rules, or { "rules": [...] }, each in
3
+ // the form templates.js reads. Nothing looks for rules files by itself, so a
4
+ // checked project can't bring rules of its own.
5
+
6
+ import { open, stat } from "node:fs/promises";
7
+ import { readTemplate } from "../engine/templates.js";
8
+
9
+ const MAX_BYTES = 256 * 1024;
10
+ const MAX_RULES = 200;
11
+ const isObj = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
12
+
13
+ async function readText(file) {
14
+ let handle;
15
+ try {
16
+ handle = await open(file, "r");
17
+ const info = await handle.stat();
18
+ if (info.isDirectory()) throw Object.assign(new Error(), { code: "EISDIR" });
19
+ // A pipe or a device has no size to check before it's read.
20
+ if (!info.isFile()) throw new Error("it isn't a file");
21
+ if (info.size > MAX_BYTES) throw new Error("it's larger than 256 KB");
22
+ return (await handle.readFile("utf8")).replace(/^\ufeff/, "");
23
+ } catch (err) {
24
+ let code = err?.code;
25
+ // Windows won't open a folder, and says so the way it does for a file this account can't read.
26
+ if ((code === "EPERM" || code === "EACCES") && (await stat(file).then((info) => info.isDirectory(), () => false))) code = "EISDIR";
27
+ const why = { ENOENT: "there's no file there", ENOTDIR: "there's no file there", EISDIR: "it's a folder", EACCES: "this account can't read it", EPERM: "this account can't read it" }[code] ?? (code ? `the system answered ${code}` : err.message);
28
+ throw new Error(`The rules file ${file} couldn't be read: ${why}.`);
29
+ } finally {
30
+ await handle?.close();
31
+ }
32
+ }
33
+
34
+ // The rules in these files, ready for a check. Throws an Error that names
35
+ // the file, the rule and what to change.
36
+ export async function loadRules(files) {
37
+ const rules = [];
38
+ const from = new Map();
39
+ for (const file of files) {
40
+ const text = await readText(file);
41
+ let data;
42
+ try {
43
+ data = JSON.parse(text);
44
+ } catch {
45
+ throw new Error(`The rules file ${file} isn't valid JSON.`);
46
+ }
47
+ const list = Array.isArray(data) ? data : isObj(data) && Array.isArray(data.rules) && Object.keys(data).length === 1 ? data.rules : isObj(data) && !Object.hasOwn(data, "rules") ? [data] : null;
48
+ if (!list?.length) throw new Error(`The rules file ${file} needs one rule, a list of rules, or a list of them under "rules" and nothing beside it.`);
49
+ for (const [i, raw] of list.entries()) {
50
+ let rule;
51
+ try {
52
+ rule = readTemplate(raw);
53
+ } catch (err) {
54
+ throw new Error(`${file}, rule ${i + 1}: ${err.message}`);
55
+ }
56
+ if (from.has(rule.id)) throw new Error(`${file}, rule ${i + 1}: ${rule.id} is already a rule in ${from.get(rule.id)}. Each rule needs its own ID.`);
57
+ from.set(rule.id, file);
58
+ rules.push(rule);
59
+ if (rules.length > MAX_RULES) throw new Error(`--rules takes up to ${MAX_RULES} rules.`);
60
+ }
61
+ }
62
+ return rules;
63
+ }
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.5.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",
package/report/styles.css CHANGED
@@ -1373,6 +1373,12 @@ p {
1373
1373
  color: var(--signal);
1374
1374
  text-decoration-color: currentColor;
1375
1375
  }
1376
+ /* One of your own rules with nowhere to link to. */
1377
+ span.f-rule,
1378
+ span.f-rule:hover {
1379
+ color: var(--text-3);
1380
+ text-decoration: none;
1381
+ }
1376
1382
 
1377
1383
  /* What to fix first: one line per rule, most points first. */
1378
1384
  .fix-first {
@@ -1574,6 +1580,41 @@ td code {
1574
1580
  .map-group + .map-group {
1575
1581
  margin-top: 32px;
1576
1582
  }
1583
+ .computer-changes {
1584
+ list-style: none;
1585
+ padding: 0;
1586
+ margin: 1rem 0;
1587
+ }
1588
+ .computer-changes li {
1589
+ display: grid;
1590
+ grid-template-columns: minmax(0, 1fr) auto;
1591
+ gap: 0.5rem 1.5rem;
1592
+ padding: 0.9rem 0;
1593
+ border-bottom: 1px solid currentColor;
1594
+ border-color: color-mix(in srgb, currentColor 17%, transparent);
1595
+ overflow-wrap: anywhere;
1596
+ }
1597
+ .computer-value {
1598
+ margin: 0.3rem 0;
1599
+ font-size: 0.9rem;
1600
+ }
1601
+ .computer-file, .computer-decision, .computer-note {
1602
+ font-size: 0.9rem;
1603
+ }
1604
+ .computer-file, .computer-decision code { opacity: 0.75; }
1605
+ .computer-decision { text-align: right; }
1606
+ .computer-decision code { display: block; font-size: 0.8rem; }
1607
+ .computer-note { margin: 0.75rem 0; }
1608
+ .computer-history { margin-top: 1.25rem; }
1609
+ .computer-history summary { cursor: pointer; font-weight: 600; }
1610
+ .computer-history ol { list-style: none; padding: 0; }
1611
+ .computer-history li { margin: 0.8rem 0; overflow-wrap: anywhere; }
1612
+ .computer-history time { display: block; color: var(--text-3); font: 0.8rem/1.5 var(--mono); }
1613
+ @media (max-width: 640px) {
1614
+ .computer-changes li { grid-template-columns: 1fr; }
1615
+ .computer-decision { text-align: left; }
1616
+ .computer-decision code { display: inline; margin-left: 0.5rem; }
1617
+ }
1577
1618
  .map-scope {
1578
1619
  color: var(--text-3);
1579
1620
  font: 500 12.5px/1.3 var(--mono);