@misconfig/cli 1.3.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.4.0
4
+
5
+ - An optional `--attribute` scan matches existing Claude Code and Codex file-edit records to observed settings. `--i-edited` records a personal claim. The timeline shows the editor evidence alongside the approving account.
6
+ - Interactive computer scans announce newer stable npm releases. `--check-update` checks on demand, and `--no-update-check` disables automatic checks.
7
+ - `--demo` runs a guided review on a disposable sample profile and shows its history. On Windows, double-click `demo.cmd` to try it.
8
+ - `--history` shows when each config change was detected and which OS account approved a change or accepted a warning. It works offline and can print JSON. HTML scan reports include the timeline.
9
+ - Computer scans show what changed since the previous scan and which settings still await approval. Use `--review` for a guided review or `--approve ID` for one decision.
10
+ - Accepting a risk dates and labels its warning in text, JSON and local HTML. The finding keeps its severity, remediation and score.
11
+ - Review history stays under the current user's home. `--no-history` runs the scanner once without accessing history. Project-only scans retain their 1.3.2 behavior.
12
+
3
13
  ## 1.3.2 (2026-11-03)
4
14
 
5
15
  - misconfig is open source under the Apache License 2.0. The code, its tests and the issue tracker are at https://github.com/gkdataio/misconfig. The name and logo stay trademarks of GK Data LLC.
package/README.md CHANGED
@@ -11,15 +11,53 @@
11
11
 
12
12
  # misconfig
13
13
 
14
- Your coding agents take orders from more files than you think. `CLAUDE.md` and `AGENTS.md` are the ones you see. The rest sit in your home folder and app settings: `~/.claude.json`, `~/.codex/config.toml`, editor settings, plugin and skill folders, shell aliases. Any one of them can turn approvals off, hand an agent your whole disk, or start an MCP server that runs whatever its package publishes next.
14
+ misconfig checks the settings that control Claude Code, Codex and other coding agents. It shows which file sets a permission, starts an MCP server or runs a hook, explains the risk, and gives you a fix. Version 1.4 adds a local history of what changed on your computer and who approved it.
15
15
 
16
- misconfig finds every one of those files, on your computer and in your project, says what each one tells your agents to do, and flags the settings that put your machine at risk, worst first, with the exact fix.
16
+ To hear when a release ships, choose **Watch → Custom → Releases** on the [GitHub repository](https://github.com/gkdataio/misconfig), or subscribe to the [release feed](https://github.com/gkdataio/misconfig/releases.atom). These channels also work for people who keep using 1.3.2.
17
+
18
+ ## New in 1.4
19
+
20
+ The demo requires CLI 1.4 or newer and Node.js 18 or later. Try it on a sample profile. On Windows, use `npx.cmd` if PowerShell blocks `npx`.
21
+
22
+ ```sh
23
+ npx @misconfig/cli@latest --demo
24
+ ```
25
+
26
+ The demo changes a sample calendar server from 1.2.3 to 1.2.4. A sample Codex record identifies the editor. You can approve that update, then accept a separate warning about an unpinned mail server and see it stay in the report. All decisions use the fictional account **Demo reviewer**. The demo runs offline and deletes the sample profile when you finish. Add `--open` to keep an HTML report. From a 1.4 source checkout or the extracted demo bundle, run `node bin/misconfig.js --demo` or double-click `demo.cmd` on Windows.
27
+
28
+ ### Review your computer
17
29
 
18
30
  ```sh
19
- npx @misconfig/cli
31
+ npx @misconfig/cli@1.4.0
32
+ npx @misconfig/cli@1.4.0 --review
33
+ npx @misconfig/cli@1.4.0 --history
20
34
  ```
21
35
 
22
- It runs on your computer. Nothing about your setup is uploaded, and it needs no account or API key.
36
+ Your first scan lists the settings available for review. **Since your last scan** shows later additions, edits and removals. **Awaiting your approval** also includes changes you skipped. The same local history follows you across project folders.
37
+
38
+ Press **Y** to approve the displayed item, **Enter** to skip it, or **Q** to finish. Each decision is saved immediately. To decide one item by ID, run `--approve ID` with the ID shown in your scan. The command checks the current value again before saving your decision.
39
+
40
+ Approving a setting records the value you expect. Accepting a risk separately adds **Risk accepted**, the date and the approving account to that warning. Its severity, fix and effect on the score stay visible in text, JSON and HTML. **Earlier risk decisions** lists accepted findings that have disappeared or whose file could not be verified. A skipped change stays pending until you approve it or the setting returns to its approved value.
41
+
42
+ misconfig compares the computer and administrator settings it discovers, including MCP servers, hooks, permissions, instructions, shell settings, installed agent versions and AI editor extensions. The report names any source it could only partly read and preserves its earlier decision. For full setting values, open the named file.
43
+
44
+ `--history` reads the saved timeline without rescanning. It shows the observation time, any evidence about the editor, and the OS account that approved the change. People sharing a login share that reviewer name. Use `--history --json` for chronological events or expand **Computer history** in an HTML report.
45
+
46
+ ### Who changed a setting?
47
+
48
+ Run `npx @misconfig/cli@1.4.0 --offline --attribute` to match observed edits against local Claude Code or Codex records. This works after approval, too. To read particular sessions, pass `--session "path/to/session.jsonl"` for each one.
49
+
50
+ An agent attribution requires a completed file tool, the same file, the exact change to the setting, and a tool timestamp between the two scans. Supported records include Claude Code’s Edit and Write results and Codex’s completed file changes with numbered diffs. Reconstructed patches must also match the saved file fingerprints. A shell command, file owner, or nearby agent session alone leaves the author unknown. A matching record identifies a recorded edit. Other unlogged writes can produce the same setting, and local records are editable.
51
+
52
+ If you made an edit yourself, use its `e-` ID from `--history`. For example, `npx @misconfig/cli@1.4.0 --i-edited e-4` records your OS account as **self-reported**. Conflicting sources appear as uncertain. An edit with no matching evidence stays **Edit author unknown**.
53
+
54
+ Session records can contain private conversations and tool inputs. Only `--attribute` or `--session` reads them on your computer. Automatic discovery searches the last seven days in Claude’s projects and Codex’s sessions and archived sessions, honoring their config directory overrides. The search reads up to 48 local files, 4 MiB from the end of each, up to 32 MiB total. It reports partial coverage when a limit or read error is encountered. Only matching source labels and timestamps enter the history.
55
+
56
+ ### npm release notices
57
+
58
+ Starting in 1.4, interactive computer scans check the public npm `latest` tag. A successful check is cached for 24 hours. The terminal announces the current release once, or shows both versions and the upgrade command if a newer stable version is available. Run `--check-update` at any time, including with `--json`.
59
+
60
+ `--no-update-check` or `MISCONFIG_NO_UPDATE_CHECK=1` disables automatic release checks. Offline, demo, history, JSON, CI and project-only scans skip them. The registry request contains only the public package name. Installing an update remains your choice.
23
61
 
24
62
  <p align="center">
25
63
  <img src="https://raw.githubusercontent.com/gkdataio/misconfig/main/assets/terminal.png" alt="misconfig checking a sample project: the files that control its agents, two critical findings with their fixes, and a grade of F" width="820">
@@ -53,37 +91,48 @@ npx @misconfig/cli --lookup # also ask OSV.dev about what's installed
53
91
 
54
92
  | Option | What it does |
55
93
  | --- | --- |
94
+ | `--demo` | Try a version change, a risk decision and their history on a disposable sample computer |
95
+ | `--review` | Walk through pending computer changes and risk decisions in a terminal |
96
+ | `--approve ID` | Approve one current change (`c-…`) or accept one current finding (`r-…`) |
97
+ | `--history` | Read the local timeline of observed changes, approvals and risk acceptances. Add `--json` for machine-readable events |
98
+ | `--no-history` | Scan once without reading or writing computer review history |
99
+ | `--attribute` / `--session FILE` | Match observed edits with recent or explicitly chosen local agent records |
100
+ | `--i-edited ID` | Record a self-reported manual edit against its observed event ID |
101
+ | `--check-update` / `--no-update-check` | Check npm now or skip the automatic release check |
56
102
  | `--explain` | Shows everything each file sets: permission modes, allowed and blocked actions, MCP servers and what they run, hooks, trusted folders, hidden text, and the agents and extensions installed |
57
103
  | `--open` | Saves the full report as one page in your temp folder and opens it in your browser. The page has no scripts and loads nothing from the internet |
58
104
  | `--lookup` | Also looks up the MCP packages, extensions and agent versions it found on [OSV.dev](https://osv.dev). It lists the names and versions it would send and asks first |
59
- | `--offline` | Skips the download of today's malware list and uses the one in the release. Same as `MISCONFIG_OFFLINE=1` |
105
+ | `--offline` | Use bundled malware data and skip the npm version check. An explicit `--lookup` still asks to contact OSV.dev. Same as `MISCONFIG_OFFLINE=1` |
60
106
  | `--project-only` | Skips the agent settings on this computer |
61
107
  | `--fail-on <level>` | Exits with code 1 if it finds anything at that level or worse: `critical`, `high`, `medium` or `low` |
62
108
  | `--json` | Prints the full result as JSON |
63
109
  | `--yes` | Runs `--lookup` without asking, for scripts |
110
+ | `--help` / `--version` | Print the supported options or installed version |
64
111
 
65
112
  ### In CI
66
113
 
67
- Run it before installing dependencies, so a lockfile that pins a known malicious package fails the build before the package runs:
114
+ After checkout, run a project-only scan before installing the project's dependencies. Pin the CLI version in your workflow. This mode checks repository findings and skips personal approvals and history.
68
115
 
69
116
  ```sh
70
- npx @misconfig/cli --project-only --fail-on high
117
+ npx --yes @misconfig/cli@1.4.0 --project-only --fail-on high
71
118
  ```
72
119
 
73
- Exit codes: `0` when the check ran and nothing reached `--fail-on`, `1` when something did, `2` for errors, or with `--fail-on` when the folder was too large to check completely, and `130` when you press Ctrl+C at a question.
120
+ On GitHub, copy the [example workflow](https://github.com/gkdataio/misconfig/blob/main/examples/github-actions/misconfig.yml) into `.github/workflows/misconfig.yml`. It checks out the repository, sets up Node.js and runs the CLI as a shell step. The `--yes` before the package name lets npx fetch the pinned CLI.
121
+
122
+ With `--fail-on high`, exit `0` means the scan finished below the threshold, `1` means a high or critical finding, and `2` means an error or an incomplete scan with no finding at the threshold. An interrupted prompt returns `130`.
74
123
 
75
124
  ## Privacy
76
125
 
77
- - The check runs on your computer, and what it works out about your files stays there.
78
- - Its one request on its own downloads today's list of known malware from misconfig.ai. The request carries the command's version and the kind of system, and nothing about your setup. `--offline` skips it, and `DO_NOT_TRACK=1` keeps the run from being counted.
79
- - `--lookup` sends package names and versions to OSV.dev, and only after you approve the list.
126
+ - Computer scans save review history under `~/.misconfig/computer-v1/`. It contains paths, labels, short summaries, keyed fingerprints, observation times and review decisions. The OS account that owns the files can edit them. `--no-history` skips this storage. HTML and JSON reports can include paths and reviewer names, so check the contents before sharing them.
127
+ - The malware-list request to misconfig.ai carries the CLI version and operating system family. Interactive computer scans also check the public package version on npm. `--offline` skips both requests, and `DO_NOT_TRACK=1` keeps the malware-list request from being counted.
128
+ - `--lookup` sends package names and versions to OSV.dev after the prompt, or with the CLI's `--yes`. The `npx` launcher may contact npm to fetch the CLI before its own offline mode starts. An installed copy or the extracted demo works without that download.
80
129
  - Credential files such as `.env` and `id_rsa`, and programs inside skills, are listed by name only and never opened. Secrets inside agent files are masked as they're read.
81
130
 
82
131
  The [privacy policy](https://misconfig.ai/privacy) lists everything misconfig.ai receives and how long it's kept.
83
132
 
84
133
  ## Known malware
85
134
 
86
- Each release bundles every MCP package and editor extension that OSV.dev has listed as malware, the Claude Code, Codex and Claude Desktop versions that are missing security fixes, and the files and workflows that attacks such as s1ngularity and Shai-Hulud leave behind, each with its source. Before every check, the command also downloads today's list, which misconfig.ai rebuilds from OSV.dev every hour, so new listings are caught without waiting for a release.
135
+ Each release bundles known malicious MCP packages and editor extensions, advisories for Claude Code, Codex and Claude Desktop, and traces left by attacks such as s1ngularity and Shai-Hulud. Each entry names its source. An online scan also downloads the malware list that misconfig.ai rebuilds from OSV.dev every hour.
87
136
 
88
137
  misconfig isn't an antivirus. It doesn't scan programs or watch what your agents do while they run, so keep approvals on for anything you can't undo.
89
138
 
@@ -99,6 +148,8 @@ misconfig is plain JavaScript with no dependencies, so what you install is what'
99
148
  | [`engine/locations.js`](https://github.com/gkdataio/misconfig/blob/main/engine/locations.js) | Where each agent keeps its files on macOS, Windows and Linux |
100
149
  | [`lib/discover.js`](https://github.com/gkdataio/misconfig/blob/main/lib/discover.js) | Which files the command reads, and the limits on what it reads |
101
150
  | [`lib/html.js`](https://github.com/gkdataio/misconfig/blob/main/lib/html.js) | The page `--open` saves |
151
+ | [`lib/computer-review.js`](https://github.com/gkdataio/misconfig/blob/main/lib/computer-review.js) | Changes, approvals and accepted risks |
152
+ | [`lib/edit-attribution.js`](https://github.com/gkdataio/misconfig/blob/main/lib/edit-attribution.js) | How optional local edit records are matched |
102
153
 
103
154
  ## Contributing
104
155
 
package/bin/misconfig.js CHANGED
@@ -25,10 +25,9 @@ main(process.argv.slice(2)).then(
25
25
  process.exitCode = code;
26
26
  },
27
27
  (err) => {
28
- // Ctrl+C at a question: nothing was sent, and the shell hears it was
29
- // interrupted.
28
+ // Earlier review decisions may already have been saved.
30
29
  if (err?.code === "ABORT_ERR") {
31
- console.error("\nmisconfig: Stopped. Nothing was sent.");
30
+ console.error("\nmisconfig: Stopped at the prompt.");
32
31
  process.exitCode = 130;
33
32
  return;
34
33
  }
package/demo.cmd ADDED
@@ -0,0 +1,13 @@
1
+ @echo off
2
+ setlocal
3
+ node.exe -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" >nul 2>&1
4
+ if errorlevel 1 (
5
+ echo This demo needs Node.js 18 or newer.
6
+ pause
7
+ exit /b 2
8
+ )
9
+ node.exe "%~dp0bin\misconfig.js" --demo
10
+ set "demoExit=%errorlevel%"
11
+ echo(
12
+ pause
13
+ exit /b %demoExit%
package/engine/index.js CHANGED
@@ -1719,7 +1719,7 @@ function collectMcpServers(ctx, f) {
1719
1719
  }
1720
1720
  }
1721
1721
 
1722
- function normalizeServer(name, def, file) {
1722
+ export function normalizeServer(name, def, file) {
1723
1723
  const d = isObj(def) ? def : {};
1724
1724
  let command = d.command ?? d.cmd;
1725
1725
  let args = scalars(d.args);
@@ -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
+ }