@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,173 @@
1
+ import { fingerprint } from "./computer-snapshot.js";
2
+ import { changeEvent, changeValue, earlierBuildNote, editorText, historyLine, linkEditors, localAccount, riskEvent } from "./review-history.js";
3
+
4
+ function differences(secret, before, after, uncertain) {
5
+ const rows = [];
6
+ for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
7
+ const a = before[key], b = after[key], entry = b ?? a;
8
+ if (a?.hash === b?.hash || uncertain.has(entry.file)) continue;
9
+ const kind = !a ? "added" : !b ? "removed" : "changed";
10
+ const fields = new Set([...Object.keys(a?.parts ?? {}), ...Object.keys(b?.parts ?? {})]);
11
+ const changedFields = [...fields].filter((k) => a?.parts?.[k] !== b?.parts?.[k]).sort();
12
+ rows.push({
13
+ key, id: "c-" + fingerprint(secret, [key, a?.hash ?? null, b?.hash ?? null]).slice(0, 20),
14
+ kind, file: entry.file, label: entry.label, before: a?.summary ?? null, after: b?.summary ?? null, changedFields,
15
+ });
16
+ }
17
+ return rows.sort((a,b) => a.file.localeCompare(b.file) || a.label.localeCompare(b.label) || a.key.localeCompare(b.key));
18
+ }
19
+
20
+ export function observe(state, snapshot, findings) {
21
+ const previousScanAt = state.scannedAt;
22
+ const seen = { ...snapshot.items };
23
+ for (const [key, item] of Object.entries(state.seen)) {
24
+ if (snapshot.uncertain.has(item.file)) seen[key] = item;
25
+ }
26
+ const changes = previousScanAt === null ? [] : differences(state.key, state.seen, seen, snapshot.uncertain);
27
+ for (const row of changes) {
28
+ if (row.kind === "removed" && !state.approved[row.key] && !state.receipts[row.key]) state.removedPending[row.key] = state.seen[row.key];
29
+ else if (row.kind !== "removed") delete state.removedPending[row.key];
30
+ }
31
+ state.seen = seen;
32
+ state.uncertain = [...snapshot.uncertain].sort();
33
+ state.scannedAt = Date.now();
34
+ if (previousScanAt === null) state.history.events.push({ action: "baseline", at: state.scannedAt, actor: null, count: Object.keys(seen).length });
35
+ for (const row of changes) {
36
+ state.history.events.push({ ...changeEvent("observed", row, state.scannedAt), id: "e-" + (state.history.events.length + 1),
37
+ since: previousScanAt, subject: row.key, transition: row.id, editor: null,
38
+ ...(state.fileRevisions ? { priorFile: state.fileRevisions[row.file] ?? null } : {}),
39
+ nextFile: snapshot.fileRevisions.get(row.file) ?? null });
40
+ }
41
+ const revisions = Object.fromEntries(snapshot.fileRevisions);
42
+ for (const file of snapshot.uncertain) if (state.fileRevisions?.[file]) revisions[file] = state.fileRevisions[file];
43
+ state.fileRevisions = revisions;
44
+
45
+ const byFile = new Map();
46
+ for (const [key, item] of Object.entries(seen).sort(([a],[b]) => a.localeCompare(b))) {
47
+ if (!byFile.has(item.file)) byFile.set(item.file, []);
48
+ byFile.get(item.file).push([key, item]);
49
+ }
50
+ state.offeredRisks = {};
51
+ const risks = new Map();
52
+ for (const finding of findings) {
53
+ if (finding.severity === "info" || (!snapshot.verified.has(finding.file) && !snapshot.riskSources.has(finding.file))) continue;
54
+ const entries = byFile.get(finding.file) ?? [];
55
+ const server = finding.vars?.server;
56
+ const owners = server ? entries.filter(([,v]) => v.subject === fingerprint(state.key, ["server", server])) : [];
57
+ const scope = owners.length ? owners : entries;
58
+ const revision = snapshot.riskSources.get(finding.file)
59
+ ?? (!owners.length && finding.evidence ? finding.evidence.trim() : scope.map(([k,v]) => [k,v.hash]));
60
+ const id = "r-" + fingerprint(state.key, [finding.file, finding.id, finding.severity, finding.title, finding.vars, revision]).slice(0, 20);
61
+ state.offeredRisks[id] = { file: finding.file, rule: finding.id, severity: finding.severity, label: owners.length === 1 ? owners[0][1].label : null };
62
+ const accepted = state.acceptedRisks[id];
63
+ finding.review = { id, acceptedAt: accepted?.at ?? null, acceptedBy: accepted?.by ?? null };
64
+ risks.set(id, { ...finding.review, file: finding.file, rule: finding.id, title: finding.title, severity: finding.severity });
65
+ }
66
+ const awaiting = pending(state);
67
+ linkEditors(state.history, [...changes, ...awaiting]);
68
+ const approvalIds = new Map(awaiting.map((r) => [r.key, r.id]));
69
+ for (const row of changes) row.id = approvalIds.get(row.key) ?? null;
70
+ const earlierRisks = Object.entries(state.acceptedRisks).filter(([id]) => !risks.has(id)).map(([id, r]) => ({
71
+ id, file: r.file, rule: r.rule, severity: r.severity, label: r.label, acceptedAt: r.at, acceptedBy: r.by ?? null,
72
+ status: snapshot.uncertain.has(r.file) ? "unverified" : "not observed on this scan",
73
+ }));
74
+ return { previousScanAt, changes, pending: awaiting, unverified: state.uncertain, risks: [...risks.values()], earlierRisks, history: state.history };
75
+ }
76
+
77
+ function pending(state) {
78
+ return differences(state.key, { ...state.removedPending, ...state.approved }, state.seen, new Set(state.uncertain));
79
+ }
80
+
81
+ export function approve(state, id, account = localAccount()) {
82
+ const row = pending(state).find((r) => r.id === id);
83
+ if (row) {
84
+ linkEditors(state.history, [row]);
85
+ if (row.kind === "removed") {
86
+ delete state.approved[row.key];
87
+ delete state.removedPending[row.key];
88
+ }
89
+ else state.approved[row.key] = state.seen[row.key];
90
+ state.receipts[row.key] = id;
91
+ const event = changeEvent("approved", row, Date.now(), account);
92
+ if (row.observationId) Object.assign(event, { observationId: row.observationId, editor: row.editor, editorScope: row.editorScope });
93
+ state.history.events.push(event);
94
+ return { id, kind: "change", history: state.history };
95
+ }
96
+ if (Object.hasOwn(state.offeredRisks, id)) {
97
+ if (!state.acceptedRisks[id]) {
98
+ const risk = { at: Date.now(), by: account, ...state.offeredRisks[id] };
99
+ state.acceptedRisks[id] = risk;
100
+ state.history.events.push(riskEvent(id, risk));
101
+ }
102
+ const risk = state.acceptedRisks[id];
103
+ return { id, kind: "risk", acceptedAt: risk.at, acceptedBy: risk.by ?? null, history: state.history };
104
+ }
105
+ for (const [key, receipt] of Object.entries(state.receipts)) {
106
+ if (receipt !== id || state.approved[key]?.hash !== state.seen[key]?.hash) continue;
107
+ if (state.uncertain.includes(state.approved[key]?.file)) break;
108
+ return { id, kind: "change", history: state.history };
109
+ }
110
+ throw new Error("That review ID is no longer current. Scan again and choose the ID beside the change or risk you just reviewed.");
111
+ }
112
+
113
+ export function showApproval(review, findings, decision) {
114
+ review.history = decision.history;
115
+ if (decision.kind === "risk") {
116
+ const accepted = { acceptedAt: decision.acceptedAt, acceptedBy: decision.acceptedBy };
117
+ for (const risk of review.risks) if (risk.id === decision.id) Object.assign(risk, accepted);
118
+ for (const f of findings) if (f.review?.id === decision.id) Object.assign(f.review, accepted);
119
+ review.confirmation = "Risk accepted. Its severity, score and fix are still shown.";
120
+ } else {
121
+ review.pending = review.pending.filter((r) => r.id !== decision.id);
122
+ for (const row of review.changes) if (row.id === decision.id) row.id = null;
123
+ review.confirmation = "Change approved.";
124
+ }
125
+ }
126
+
127
+ export function changeLabel(row, existing = false) {
128
+ const action = existing ? "Existing" : row.kind[0].toUpperCase() + row.kind.slice(1);
129
+ return action + " " + row.label;
130
+ }
131
+
132
+ export function changeText(row, existing = false) {
133
+ return [changeLabel(row, existing), changeValue(row), row.file, row.observationId ? editorText(row.editor, row.editorScope) + " · " + row.observationId : null].filter(Boolean).join(" · ");
134
+ }
135
+
136
+ export function reviewLines(review, demo = false) {
137
+ const lines = [];
138
+ const displayedIds = new Set();
139
+ if (review.previousScanAt === null) lines.push("First scan on this computer. Review the settings you want to keep.");
140
+ else {
141
+ lines.push(review.changes.length ? "Since your last scan" : review.unverified.length ? "No changes in the settings we could verify." : "No changes since your last scan.");
142
+ for (const row of review.changes) {
143
+ lines.push(" " + changeText(row) + (row.id ? " · awaiting approval " + row.id : ""));
144
+ if (row.id) displayedIds.add(row.id);
145
+ }
146
+ }
147
+ const outstanding = review.pending.filter((r) => !displayedIds.has(r.id));
148
+ if (outstanding.length) lines.push("Awaiting your approval (" + outstanding.length + ")");
149
+ else if (!review.pending.length) lines.push(review.unverified.length ? "Approval is paused for the unverified sources below." : "No computer changes awaiting approval.");
150
+ for (const row of outstanding) lines.push(" " + row.id + " " + changeText(row, review.previousScanAt === null));
151
+ for (const file of review.unverified) lines.push("Could not fully verify " + file + ". Any earlier decision is kept.");
152
+ const accepted = review.risks.filter((r) => r.acceptedAt).length;
153
+ if (accepted) lines.push(accepted + (accepted === 1 ? " accepted risk is" : " accepted risks are") + " still present. See Findings.");
154
+ if (review.earlierRisks.length) {
155
+ lines.push("Earlier risk decisions");
156
+ for (const r of review.earlierRisks) lines.push(" " + [r.rule, r.label, r.file, "accepted " + new Date(r.acceptedAt).toISOString().slice(0, 10) + " by " + (r.acceptedBy ?? "an unknown account"), r.status].filter(Boolean).join(" · "));
157
+ }
158
+ if (!demo && (review.pending.length || review.risks.some((r) => !r.acceptedAt))) lines.push("Run again with --review to decide one at a time, or --approve ID to choose one.");
159
+ if (review.confirmation) lines.push(review.confirmation);
160
+ if (review.attribution && !demo) {
161
+ const { matchedEdits, filesRead, limited } = review.attribution;
162
+ lines.push("Tool records matched " + matchedEdits + " observed edit(s) across " + filesRead + " local session file(s)." + (limited ? " Session coverage was partial." : ""));
163
+ }
164
+ if (demo) {
165
+ lines.push("", "Sample computer history (newest first)", ...review.history.events.slice().reverse().map(historyLine));
166
+ } else {
167
+ if (review.history?.incomplete) lines.push(earlierBuildNote);
168
+ lines.push("Run --history to see changes, approvals and accepted risks on this computer.");
169
+ const unknown = [...review.changes, ...review.pending].find((row) => row.observationId && !row.editor);
170
+ if (unknown) lines.push("Use --attribute to check local tool records. If you made this edit, use --i-edited " + unknown.observationId + ".");
171
+ }
172
+ return lines;
173
+ }
@@ -0,0 +1,232 @@
1
+ import { createHmac } from "node:crypto";
2
+ import { readdir, stat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { controlFor, normalizeServer, packageSpec } from "../engine/index.js";
5
+ import { agentLines } from "../engine/explain.js";
6
+ import { parseJSONC, parseTOML, parseYAML } from "../engine/parse.js";
7
+ import { maskSecrets, isMasked, looksLikeToken } from "../engine/mask.js";
8
+ import { resolveUserPath } from "./discover.js";
9
+ import { LIMITS } from "../engine/paths.js";
10
+
11
+ const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
12
+ const sortKeys = (_key, value) => object(value)
13
+ ? Object.fromEntries(Object.keys(value).sort().map((k) => [k, value[k]]))
14
+ : value;
15
+
16
+ // Only the keyed digest of a value is kept. A credential rotation must change
17
+ // that digest even when both values have the same masked representation.
18
+ export function fingerprint(secret, value) {
19
+ return createHmac("sha256", Buffer.from(secret, "hex")).update(JSON.stringify(value, sortKeys)).digest("hex");
20
+ }
21
+
22
+ function name(text) {
23
+ return maskSecrets(String(text)).text.replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu, "�").slice(0, 160);
24
+ }
25
+
26
+ function word(value) {
27
+ return typeof value === "string" && /^[\w.@/-]{1,100}$/.test(value) && !isMasked(maskSecrets(value).text) && !looksLikeToken(value);
28
+ }
29
+
30
+ function program(command) {
31
+ const first = typeof command === "string" ? command.trim().match(/^[\w./\\-]+/)?.[0] : null;
32
+ const base = first?.split(/[\\/]/).at(-1);
33
+ return word(base) ? base : "command";
34
+ }
35
+
36
+ function serverSummary(def) {
37
+ if (!object(def)) return "server definition";
38
+ const { command, args, url } = normalizeServer("", def, null);
39
+ const pkg = command ? packageSpec(command, args) : null;
40
+ if (pkg && word(pkg.name) && (!pkg.version || /^\d+\.\d+\.\d+(?:[-+][\w.]+)?$/.test(pkg.version))) return pkg.name + (pkg.version ? "@" + pkg.version : " (unpinned)");
41
+ // URLs can carry account names, private hostnames and token-like path
42
+ // components. The history only needs to distinguish a remote server.
43
+ if (typeof url === "string") return "remote server";
44
+ return command ? program(command) : "server definition";
45
+ }
46
+
47
+ function hookSummary(hook) {
48
+ const command = typeof hook === "string" ? hook : hook?.command ?? hook?.bash ?? hook?.powershell;
49
+ if (typeof command !== "string") return typeof hook?.type === "string" && word(hook.type) ? hook.type : "hook definition";
50
+ const exe = program(command);
51
+ const args = command.trim().split(/\s+/);
52
+ if (/^(?:npm|pnpm|yarn|bun)$/.test(exe) && args[1] === "run" && word(args[2])) return exe + " run " + args[2];
53
+ const script = args[1]?.split(/[\\/]/).at(-1);
54
+ if (/^(?:node|python3?|bash|sh|pwsh)$/.test(exe) && word(script) && /\.(js|mjs|cjs|py|sh|ps1)$/i.test(script)) return exe + " " + script;
55
+ return exe;
56
+ }
57
+
58
+ const readableModes = new Set(["workspace-write", "read-only", "danger-full-access", "on-request", "on-failure", "never", "untrusted", "default", "plan", "acceptEdits", "bypassPermissions", "auto", "ask", "allow", "deny"]);
59
+ const privateValueContainer = /^(?:env|environment|envs|headers?|http[_-]?headers?)$/i;
60
+ const shellPolicy = /^shell[_-]?environment[_-]?policy$/i;
61
+ export const PRIVATE_SETTING_SUMMARY = "private setting";
62
+
63
+ function privateValueTrail(trail) {
64
+ const parents = trail.slice(0, -1);
65
+ if (parents.some((part) => privateValueContainer.test(part))) return true;
66
+ return parents.some((part, index) => shellPolicy.test(part) && /^(?:set|env|environment)$/i.test(parents[index + 1] ?? ""));
67
+ }
68
+
69
+ // Kept separate for migration of histories written by the early 1.4 preview.
70
+ export function privateValueLabel(label) {
71
+ const parts = String(label).split(" / ");
72
+ return privateValueTrail(parts);
73
+ }
74
+
75
+ function settingSummary(value, key, privateValue) {
76
+ if (privateValue) return PRIVATE_SETTING_SUMMARY;
77
+ if (/token|secret|passw|credential|api.?key|auth.?key/i.test(key)) return "credential setting";
78
+ if (typeof value === "boolean" || typeof value === "number") return String(value);
79
+ if (readableModes.has(value)) return value;
80
+ if (/^(model|provider|version|logLevel)$/i.test(key) && word(value)) return value;
81
+ if (Array.isArray(value)) return value.length + (value.length === 1 ? " entry" : " entries");
82
+ return value === null ? "unset" : "configured value";
83
+ }
84
+
85
+ // File contents live only during discovery. The ledger receives names, short
86
+ // descriptions and hashes, never argument lists, hook bodies or env values.
87
+ export function computerSnapshot(secret, { home = homedir(), env = process.env } = {}) {
88
+ const items = {};
89
+ const fileRevisions = new Map();
90
+ const verified = new Set();
91
+ const uncertain = new Set();
92
+ const riskSources = new Map();
93
+ const hash = (v) => fingerprint(secret, v);
94
+ function collect(file, raw, flags = {}, original = raw) {
95
+ if (flags.sensitive || flags.listed) return;
96
+ const kind = controlFor(file)?.kind ?? flags.role;
97
+ if (!kind) return;
98
+ if (raw === null || flags.partial || flags.tooLarge || flags.invalid || raw.length > LIMITS.maxFileBytes) {
99
+ uncertain.add(file);
100
+ return;
101
+ }
102
+ const entries = {};
103
+ function add(trail, label, value, summary, fields, subject) {
104
+ const key = hash([file, trail]);
105
+ const parts = fields && Object.fromEntries(Object.entries(fields).map(([k,v]) => [k, hash(v)]));
106
+ entries[key] = { file, label: name(label), summary, hash: hash(value), ...(parts ? { parts } : {}), ...(subject ? { subject } : {}) };
107
+ }
108
+ function server(trail, id, def) {
109
+ const fields = {};
110
+ if (object(def)) for (const [k,v] of Object.entries(def)) {
111
+ const group = /^(env|environment|envs)$/.test(k) ? "environment" : /header/i.test(k) ? "headers" : /^(args|command|cmd)$/.test(k) ? "launch" : /^(url|httpUrl|serverUrl)$/.test(k) ? "address" : "settings";
112
+ (fields[group] ??= []).push([k,v]);
113
+ }
114
+ for (const list of Object.values(fields)) list.sort(([a],[b]) => a < b ? -1 : a > b ? 1 : 0);
115
+ const scope = trail[0] === "projects" ? " in " + name(trail[1]) : "";
116
+ add([...trail, id], "MCP " + name(id) + scope, def, serverSummary(def), fields, hash(["server", id]));
117
+ }
118
+ function hooks(trail, event, nodes) {
119
+ const list = Array.isArray(nodes) ? nodes : [nodes];
120
+ let ordinal = 0;
121
+ for (const node of list) {
122
+ const nested = object(node) && Array.isArray(node.hooks);
123
+ const group = nested ? Object.fromEntries(Object.entries(node).filter(([k]) => k !== "hooks")) : null;
124
+ for (const hook of nested ? node.hooks : [node]) {
125
+ ordinal++;
126
+ add([...trail, event, ordinal], "Hook " + event + " #" + ordinal, [group, hook], hookSummary(hook), { matcher: group, action: hook });
127
+ }
128
+ }
129
+ }
130
+ function visit(value, trail = []) {
131
+ const key = trail.at(-1) ?? "";
132
+ if (trail.length === 1 && kind === "Editor settings" && !/^(mcp$|mcp\.|chat\.|github\.copilot|cursor\.|windsurf\.|codeium\.|claudeCode\.)/i.test(key)) return;
133
+ if (trail.length === 1 && /\/\.cline\/data\/globalState\.json$/i.test(file) && !["yoloModeToggled", "autoApprovalSettings"].includes(key)) return;
134
+ const servers = /^(mcpServers|mcp_servers|context_servers|amp\.mcpServers)$/.test(key)
135
+ || (key === "mcp" && /opencode\.jsonc?$/i.test(file))
136
+ || (key === "servers" && (trail.at(-2) === "mcp" || /mcp\.json$/i.test(file)))
137
+ || (key === "extensions" && /goose\/config\.ya?ml$/i.test(file))
138
+ || (!trail.length && flags.role === "mcp-servers" && !value?.mcpServers);
139
+ if (servers && object(value)) {
140
+ for (const [id, def] of Object.entries(value)) server(trail, id, def);
141
+ } else if (servers && Array.isArray(value)) {
142
+ value.forEach((def, i) => server(trail, typeof def?.name === "string" ? def.name : String(i + 1), def));
143
+ } else if (trail.at(-2) === "permissions" && /^(allow|ask|deny)$/.test(key) && Array.isArray(value) && value.every((v) => typeof v === "string")) {
144
+ for (const rule of new Set(value)) {
145
+ const tool = rule.match(/^([\w.*-]+)(?:\((.*)\))?$/);
146
+ const what = tool && word(tool[1]) ? tool[1] + (tool[2] === "*" ? "(*)" : tool[2] ? " (" + program(tool[2]) + ")" : "") : "tool rule";
147
+ add([...trail, rule], "Permission " + key, rule, what);
148
+ }
149
+ } else if (key === "hooks" && object(value)) {
150
+ for (const [event, nodes] of Object.entries(value)) hooks(trail, event, nodes);
151
+ } else if (key === "hooks" && Array.isArray(value)) {
152
+ hooks(trail, "configured", value);
153
+ } else if (object(value) && trail.length < 32) {
154
+ for (const [k, v] of Object.entries(value)) visit(v, [...trail, k]);
155
+ } else if (!(trail[0] === "projects" && key === "allowedTools" && !value?.length)) {
156
+ add(trail, trail.map(name).join(" / ") || kind, value, settingSummary(value, key, privateValueTrail(trail)));
157
+ }
158
+ }
159
+ try {
160
+ const parser = /\.(jsonc?|kiro\.hook)$/i.test(file) ? parseJSONC : /\.toml$/i.test(file) ? parseTOML : /\.ya?ml$/i.test(file) ? parseYAML : null;
161
+ if (parser) {
162
+ const config = parser(raw);
163
+ const unparsed = object(config) && !Object.keys(config).length && parser !== parseJSONC && raw.split(/\r?\n/).some((l) => l.trim() && !l.trim().startsWith("#") && l.trim() !== "{}");
164
+ if (config === undefined || config === null || typeof config !== "object" || unparsed) {
165
+ uncertain.add(file);
166
+ return;
167
+ }
168
+ visit(config);
169
+ } else if (kind === "Shell profile") {
170
+ const lines = agentLines({ lines: raw.split(/\r?\n/) }).map((l) => l.text.trim());
171
+ if (lines.length) add([], kind, lines, lines.length + " agent-related line(s)");
172
+ } else {
173
+ const text = raw.replace(/\r\n/g, "\n");
174
+ const lines = text === "" ? 0 : text.replace(/\n$/, "").split("\n").length;
175
+ add([], kind, text, lines + (lines === 1 ? " line" : " lines"));
176
+ }
177
+ Object.assign(items, entries);
178
+ verified.add(file);
179
+ if (typeof original === "string" && original.length <= LIMITS.maxFileBytes) fileRevisions.set(file, hash(original.replace(/\r\n/g, "\n")));
180
+ } catch (err) {
181
+ if (!(err instanceof RangeError)) throw err;
182
+ uncertain.add(file);
183
+ }
184
+ }
185
+ function inventory(input, installed) {
186
+ // Use the same versions the scanner found. Native installers commonly
187
+ // name the last path component after the version being replaced.
188
+ for (const agent of installed.agents) {
189
+ if (agent.via === "project") continue;
190
+ const leaf = agent.path.split("/").at(-1);
191
+ const file = [agent.version, "app-" + agent.version].includes(leaf) ? agent.path.slice(0, -(leaf.length + 1)) : agent.path;
192
+ const key = hash(["install", file, agent.tool, agent.via]);
193
+ items[key] = { file, label: agent.tool + " (" + agent.via + ")", summary: agent.version, hash: hash(agent.version) };
194
+ verified.add(file);
195
+ }
196
+ for (const editor of installed.editors) {
197
+ verified.add(editor.dir);
198
+ const versions = new Map();
199
+ for (const agent of editor.agents) {
200
+ if (!versions.has(agent.id)) versions.set(agent.id, new Set());
201
+ versions.get(agent.id).add(agent.version || "unknown version");
202
+ }
203
+ for (const [id, found] of versions) {
204
+ const list = [...found].sort();
205
+ items[hash(["extension", editor.dir, id])] = { file: editor.dir, label: editor.editor + " extension " + id, summary: list.join(", "), hash: hash(list), inventoryDirectory: true };
206
+ }
207
+ }
208
+ for (const inst of input.installs) if (inst.via !== "project") riskSources.set(inst.path, hash([inst.package, inst.version]));
209
+ for (const editor of input.extensions) {
210
+ const items = editor.items.map((v) => [v.id, v.version, v.source]);
211
+ items.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
212
+ riskSources.set(editor.dir, hash(items));
213
+ }
214
+ for (const file of input.traces) riskSources.set(file, hash(["present", file]));
215
+ }
216
+ // Discovery can skip an unreadable file or directory. Only a confirmed
217
+ // missing file is a removal; a file still on disk needs another check.
218
+ async function checkMissing(prior) {
219
+ const files = new Map(Object.values(prior).map((item) => [item.file, item]));
220
+ await Promise.all([...files].filter(([f]) => !verified.has(f) && !uncertain.has(f)).map(async ([file, item]) => {
221
+ try {
222
+ const abs = resolveUserPath(file, { home, env });
223
+ await stat(abs);
224
+ if (item.inventoryDirectory && !(await readdir(abs)).length) return;
225
+ uncertain.add(file);
226
+ } catch (err) {
227
+ if (err.code !== "ENOENT" && err.code !== "ENOTDIR") uncertain.add(file);
228
+ }
229
+ }));
230
+ }
231
+ return { items, verified, uncertain, riskSources, fileRevisions, collect, inventory, checkMissing };
232
+ }
package/lib/demo.js ADDED
@@ -0,0 +1,32 @@
1
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
4
+
5
+ // Each run owns a new sample home. Nothing in the fixture is executed, and
6
+ // the caller uses the normal scanner, review transactions and report writers.
7
+ export async function withDemo(run) {
8
+ const home = await mkdtemp(path.join(tmpdir(), "misconfig-demo-"));
9
+ const file = path.join(home, ".claude.json"), session = path.join(home, "sample-codex.jsonl");
10
+ const config = (version) => JSON.stringify({
11
+ mcpServers: {
12
+ calendar: { command: "npx", args: ["-y", "@example/calendar@" + version] },
13
+ mail: { command: "npx", args: ["-y", "@example/mail"] },
14
+ },
15
+ });
16
+ try {
17
+ await writeFile(file, config("1.2.3") + "\n", { mode: 0o600 });
18
+ return await run({
19
+ discovery: { dir: home, home, env: {}, sampleFiles: ["~/.claude.json"] },
20
+ store: path.join(home, ".misconfig", "computer-v1"),
21
+ session,
22
+ bump: async () => {
23
+ await writeFile(file, config("1.2.4") + "\n");
24
+ const diff = "@@ -1 +1 @@\n-" + config("1.2.3") + "\n+" + config("1.2.4") + "\n";
25
+ const payload = { type: "patch_apply_end", call_id: "demo", success: true, status: "completed", changes: { [file]: { type: "update", unified_diff: diff, move_path: null } } };
26
+ await writeFile(session, JSON.stringify({ timestamp: new Date().toISOString(), type: "event_msg", payload }) + "\n", { mode: 0o600 });
27
+ },
28
+ });
29
+ } finally {
30
+ await rm(home, { recursive: true, force: true });
31
+ }
32
+ }
package/lib/discover.js CHANGED
@@ -16,8 +16,17 @@ import { TRACES, AGENT_PACKAGES, KNOWN_PACKAGES, VERSION_RE } from "../engine/kn
16
16
  export const PLATFORM = process.platform === "win32" ? "windows" : process.platform === "darwin" ? "mac" : "linux";
17
17
  const LOOSE_NAMES = /\.(md|mdc|txt)$/i;
18
18
 
19
+ export function displayUserPath(abs, home) {
20
+ if (home) {
21
+ const rel = path.relative(home, abs);
22
+ if (!rel) return "~";
23
+ if (!rel.startsWith("..") && !path.isAbsolute(rel)) return "~/" + rel.split(path.sep).join("/");
24
+ }
25
+ return abs.split(path.sep).join("/");
26
+ }
27
+
19
28
  // `limits` is for tests; the command always uses LIMITS from the engine.
20
- export async function discover({ dir = process.cwd(), includeUser = true, home = homeDir(), env = process.env, limits = LIMITS } = {}) {
29
+ export async function discover({ dir = process.cwd(), includeUser = true, home = homeDir(), env = process.env, limits = LIMITS, onComputerFile, sampleFiles } = {}) {
21
30
  const projectDir = path.resolve(dir);
22
31
  const info = await fs.stat(projectDir).catch(() => null);
23
32
  if (!info?.isDirectory()) throw new Error(`There's no folder at ${projectDir}.`);
@@ -25,19 +34,14 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
25
34
  const files = [];
26
35
  const seen = new Set();
27
36
  const lineMaps = {};
37
+ let collectingComputer = false;
28
38
  let masked = 0;
29
39
 
30
- const tilde = (abs) => {
31
- if (home) {
32
- const rel = path.relative(home, abs);
33
- if (!rel) return "~";
34
- if (!rel.startsWith("..") && !path.isAbsolute(rel)) return "~/" + rel.split(path.sep).join("/");
35
- }
36
- return abs.split(path.sep).join("/");
37
- };
38
- const add = (enginePath, raw, size, extra = {}) => {
40
+ const tilde = (abs) => displayUserPath(abs, home);
41
+ const add = (enginePath, raw, size, extra = {}, original = raw) => {
39
42
  if (seen.has(enginePath)) return;
40
43
  seen.add(enginePath);
44
+ if (collectingComputer && onComputerFile) onComputerFile(enginePath, raw, extra, original);
41
45
  if (raw === null) return files.push({ path: enginePath, size, ...extra });
42
46
  const m = maskSecrets(raw);
43
47
  masked += m.count;
@@ -212,20 +216,20 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
212
216
  // --- The home folder and app settings ------------------------------------
213
217
  // Each file keeps its usual name (~/.claude/settings.json) even when an
214
218
  // environment variable moved it, so the checks still recognize it.
219
+ collectingComputer = withUser;
215
220
  if (withUser) {
216
221
  const userFiles = [];
217
- for (const entry of LOCATIONS) {
218
- for (const p of userPaths(entry, PLATFORM)) {
219
- for (const { abs, name } of await expand(resolveUserPath(p, { home, env }), p.startsWith("~") ? p : null)) {
220
- const enginePath = name ?? tilde(abs);
221
- if (!p.endsWith("/")) {
222
- userFiles.push({ abs, enginePath });
223
- continue;
224
- }
225
- // In a folder, only the files agents read.
226
- const nameOf = (f) => enginePath.replace(/\/?$/, "/") + path.relative(abs, f).split(path.sep).join("/");
227
- for (const f of await listFiles(abs, 4, (f) => ["content", "listed"].includes(classifyPath(nameOf(f))), (d) => insideSkill(nameOf(d)))) userFiles.push({ abs: f, enginePath: nameOf(f) });
222
+ // The demo supplies only its own fixture paths and skips host inventories.
223
+ for (const p of sampleFiles ?? LOCATIONS.flatMap((entry) => userPaths(entry, PLATFORM))) {
224
+ for (const { abs, name } of await expand(resolveUserPath(p, { home, env }), p.startsWith("~") ? p : null)) {
225
+ const enginePath = name ?? tilde(abs);
226
+ if (!p.endsWith("/")) {
227
+ userFiles.push({ abs, enginePath });
228
+ continue;
228
229
  }
230
+ // In a folder, only the files agents read.
231
+ const nameOf = (f) => enginePath.replace(/\/?$/, "/") + path.relative(abs, f).split(path.sep).join("/");
232
+ for (const f of await listFiles(abs, 4, (f) => ["content", "listed"].includes(classifyPath(nameOf(f))), (d) => insideSkill(nameOf(d)))) userFiles.push({ abs: f, enginePath: nameOf(f) });
229
233
  }
230
234
  }
231
235
  // With CLAUDE_CONFIG_DIR set, ~/.claude.json may live in that folder.
@@ -238,9 +242,12 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
238
242
  if (/(^|[\\/])\.claude\.json$/.test(abs)) {
239
243
  const stat = await fs.stat(abs).catch(() => null);
240
244
  const raw = stat?.isFile() ? await readText(abs) : null;
241
- if (raw === null) continue;
245
+ if (raw === null) {
246
+ if (stat?.isFile()) add(enginePath, null, stat.size, { invalid: true });
247
+ continue;
248
+ }
242
249
  const reduced = reduceClaudeJson(raw, tilde);
243
- add(enginePath, reduced.text, stat.size);
250
+ add(enginePath, reduced.text, stat.size, reduced.invalid ? { invalid: true } : {}, raw);
244
251
  if (reduced.lineMap) lineMaps[enginePath] = reduced.lineMap;
245
252
  continue;
246
253
  }
@@ -273,8 +280,9 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
273
280
  // If an agent has run in, or trusts, Downloads or the home folder, check
274
281
  // the loose instruction files there too. Only the settings on this
275
282
  // computer say where agents have run; a project's own copies don't count.
283
+ collectingComputer = false;
276
284
  const risky = new Set();
277
- for (const f of withUser ? files : []) {
285
+ for (const f of withUser && !sampleFiles ? files : []) {
278
286
  if (!f.content || !/^(~|\/|[A-Za-z]:)/.test(f.path)) continue;
279
287
  for (const d of agentFolders(f.path, f.content)) if (riskyPlace(d)) risky.add(d.startsWith("~") ? d : tilde(path.resolve(d)));
280
288
  }
@@ -296,7 +304,7 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
296
304
  const locked = scanningHome ? [] : await lockedPackages(projectDir);
297
305
  let extensions = [];
298
306
  let traces = [];
299
- if (withUser) {
307
+ if (withUser && !sampleFiles) {
300
308
  installs.push(...(await agentInstalls({ home, env, tilde })));
301
309
  extensions = await editorExtensions({ home, env, tilde });
302
310
  traces = await traceFiles({ home, env });
@@ -608,14 +616,14 @@ export function resolveUserPath(p, { home, env }) {
608
616
  // has been started in and their tool approvals. lineMap[i] is the line in
609
617
  // the real file that reduced line i + 1 came from, so findings point at
610
618
  // lines people can open.
611
- function reduceClaudeJson(raw, tilde) {
619
+ export function reduceClaudeJson(raw, tilde) {
612
620
  let json;
613
621
  try {
614
622
  json = JSON.parse(raw);
615
623
  } catch {
616
- return { text: "{}", lineMap: null };
624
+ return { text: "{}", lineMap: null, invalid: true };
617
625
  }
618
- if (!json || typeof json !== "object") return { text: "{}", lineMap: null };
626
+ if (!json || typeof json !== "object" || Array.isArray(json)) return { text: "{}", lineMap: null, invalid: true };
619
627
  const keys = new Map(); // reduced key, as JSON, -> key in the real file, as JSON
620
628
  const out = {};
621
629
  for (const [k, v] of Object.entries(json)) {