@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.
package/lib/main.js CHANGED
@@ -1,23 +1,47 @@
1
- import { readFile } from "node:fs/promises";
1
+ import { randomUUID } from "node:crypto";
2
+ import { readFile, rename, unlink, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
2
4
  import { createInterface } from "node:readline/promises";
3
5
  import { analyze, applyLookup, useKnownMalware } from "../engine/index.js";
4
6
  import { KNOWN_AS_OF } from "../engine/known.js";
5
7
  import { discover } from "./discover.js";
6
- import { printReport, printOpenResult, printLookupPreview, printLookupResult } from "./print.js";
8
+ import { printReport, printOpenResult, printSarifResult, printLookupPreview, printLookupResult, oneLine } from "./print.js";
9
+ import { jsonLines, sarif, stringify } from "./formats.js";
10
+ import { loadRules } from "./rule-files.js";
7
11
  import { writeReport, openInBrowser } from "./html.js";
8
12
  import { lookupQueries, osvLookup, installsOnly } from "./lookup.js";
13
+ import { computerSnapshot } from "./computer-snapshot.js";
14
+ import { observe, approve, showApproval, changeText } from "./computer-review.js";
15
+ import { readHistory, updateReview } from "./review-store.js";
16
+ import { claimEdit, earlierBuildNote, historyLine } from "./review-history.js";
17
+ import { withDemo } from "./demo.js";
18
+ import { attributeEdits } from "./edit-attribution.js";
19
+ import { automaticUpdateCheck, packageUpdate, updateMessage } from "./package-update.js";
20
+ import { LIMITS } from "../engine/paths.js";
9
21
 
10
22
  const HELP = `Usage: npx @misconfig/cli [folder] [options]
11
23
 
12
- Finds every file that controls your AI coding agents, on this computer and in
13
- the folder (the current folder by default), and checks them for risky
14
- settings. It also checks the MCP servers, editor extensions, skills and agent
15
- versions installed for known malware and missing security fixes. Everything
24
+ Finds the files that control your AI coding agents on this computer and in
25
+ the folder (the current folder by default). It checks the settings for risks
26
+ and records changes to computer settings. It also checks the installed MCP
27
+ servers, editor extensions, skills and agent versions for known malware and
28
+ missing security fixes. Everything
16
29
  runs here. It downloads today's list of known malware from misconfig.ai
17
- first, a request that carries nothing about your setup. Nothing else is sent
18
- unless you use --lookup.
30
+ first. Interactive computer scans also check for a newer CLI on npm.
31
+ Neither request sends your files or settings. --offline skips both.
32
+ Nothing else is sent unless you use --lookup.
19
33
 
20
34
  Options
35
+ --demo Try the review offline on a disposable sample computer
36
+ --history Show recorded computer changes and who approved them
37
+ --attribute Match edits against recent local Claude and Codex records
38
+ --session FILE Use this local JSONL session for attribution (repeatable)
39
+ --i-edited ID Mark an observed edit (such as e-4) as yours, independently of approval
40
+ --check-update Check npm for a newer stable CLI release
41
+ --no-update-check Skip the automatic npm release check
42
+ --review Review pending computer changes and risks one at a time
43
+ --approve ID Approve one exact change or accept one visible risk
44
+ --no-history Scan without reading or updating computer review history
21
45
  --explain Show everything each file tells your agents: rules,
22
46
  permissions, MCP servers, hooks and hidden text, and
23
47
  what's installed
@@ -28,11 +52,17 @@ Options
28
52
  asks first.
29
53
  --open Save the full report as a page on this computer and
30
54
  open it in your browser. Nothing is uploaded.
31
- --offline Don't download today's list of known malware. The check
32
- uses the list in this release. Same as setting
33
- MISCONFIG_OFFLINE=1.
55
+ --offline Use bundled malware data and skip the npm update check.
56
+ An explicit --lookup still asks to contact OSV.dev.
57
+ Same as setting MISCONFIG_OFFLINE=1.
34
58
  --yes Look up without asking, for scripts and CI
35
59
  --json Print the full result as JSON
60
+ --jsonl Print the findings as JSON Lines, one finding on each
61
+ line, for jq, grep and log collectors
62
+ --sarif FILE Also save the findings in FILE as SARIF 2.1.0, for
63
+ GitHub code scanning and other SARIF viewers
64
+ --rules FILE Also check with your own rules, from a JSON file.
65
+ Repeat it for more files.
36
66
  --project-only Skip the agent settings on this computer
37
67
  --fail-on <level> Exit with code 1 if anything at this level or worse is
38
68
  found: critical, high, medium or low. Useful in CI.
@@ -62,25 +92,163 @@ export async function main(argv) {
62
92
  else if (a === "--offline") opts.offline = true;
63
93
  else if (a === "--yes" || a === "-y") opts.yes = true;
64
94
  else if (a === "--json") opts.json = true;
95
+ else if (a === "--jsonl") opts.jsonl = true;
96
+ else if (a === "--sarif" || a.startsWith("--sarif=")) {
97
+ if (opts.sarif) throw new Error("Choose one file for --sarif.");
98
+ opts.sarif = a === "--sarif" ? argv[++i] : a.slice(8);
99
+ if (!opts.sarif || opts.sarif.startsWith("-")) throw new Error("--sarif needs a file to save the findings in, such as misconfig.sarif.");
100
+ }
101
+ else if (a === "--rules" || a.startsWith("--rules=")) {
102
+ const file = a === "--rules" ? argv[++i] : a.slice(8);
103
+ if (!file || file.startsWith("-")) throw new Error("--rules needs a file of your own rules, such as rules.json.");
104
+ (opts.rules ??= []).push(file);
105
+ }
65
106
  else if (a === "--explain") opts.explain = true;
66
107
  else if (a === "--project-only") opts.projectOnly = true;
108
+ else if (a === "--no-history") opts.noHistory = true;
109
+ else if (a === "--history") opts.history = true;
110
+ else if (a === "--attribute") opts.attribute = true;
111
+ else if (a === "--check-update") opts.checkUpdate = true;
112
+ else if (a === "--no-update-check") opts.noUpdate = true;
113
+ else if (a === "--session") {
114
+ const file = argv[++i];
115
+ if (!file || file.startsWith("-")) throw new Error("--session needs a local session JSONL file.");
116
+ (opts.sessions ??= []).push(file);
117
+ opts.attribute = true;
118
+ }
119
+ else if (a === "--i-edited") {
120
+ const id = argv[++i];
121
+ if (opts.claim || !/^e-[1-9][0-9]*$/.test(id ?? "")) throw new Error("--i-edited needs one observed edit ID from --history.");
122
+ opts.claim = id;
123
+ }
124
+ else if (a === "--demo") opts.demo = true;
125
+ else if (a === "--review") opts.review = true;
126
+ else if (a === "--approve" || a.startsWith("--approve=")) {
127
+ if (opts.approve) throw new Error("Choose one review ID at a time.");
128
+ opts.approve = a === "--approve" ? argv[++i] : a.slice(10);
129
+ if (!/^[cr]-[0-9a-f]{20}$/.test(opts.approve ?? "")) throw new Error("--approve needs the ID beside one computer change or risk.");
130
+ }
67
131
  else if (a === "--fail-on" || a.startsWith("--fail-on=")) {
68
132
  opts.failOn = (a.includes("=") ? a.split("=")[1] : argv[++i] ?? "").toLowerCase();
69
133
  if (!LEVELS.includes(opts.failOn)) throw new Error(`--fail-on needs one of: ${LEVELS.join(", ")}.`);
70
134
  } else if (a.startsWith("-")) throw new Error(`Unknown option ${a}. Run npx @misconfig/cli --help for the options.`);
71
- else opts.dir = a;
135
+ else { opts.dir = a; opts.folderGiven = true; }
72
136
  }
73
137
 
138
+ if (opts.json && opts.jsonl) throw new Error("Choose --json or --jsonl. Each prints on its own.");
139
+ if (opts.history || opts.claim || opts.checkUpdate) {
140
+ if ([opts.history, opts.claim, opts.checkUpdate].filter(Boolean).length > 1 || opts.demo || opts.projectOnly || opts.noHistory || opts.review || opts.approve || opts.open || opts.lookup || opts.explain || opts.failOn || opts.yes || opts.folderGiven || opts.attribute || opts.jsonl || opts.sarif || opts.rules) throw new Error("Use --history, --i-edited ID or --check-update as a separate command. Each supports --json.");
141
+ if (opts.checkUpdate) {
142
+ const update = await packageUpdate(await version(), { force: true, offline: opts.offline });
143
+ console.log(opts.json ? stringify(update, 2) : updateMessage(update, true));
144
+ return ["unavailable", "offline"].includes(update.status) ? 2 : 0;
145
+ }
146
+ if (opts.claim) {
147
+ const event = await updateReview((state) => claimEdit(state.history, opts.claim));
148
+ console.log(opts.json ? stringify(event, 2) : oneLine(historyLine(event)));
149
+ return 0;
150
+ }
151
+ const history = await readHistory();
152
+ if (opts.json) console.log(stringify(history, 2));
153
+ else {
154
+ const lines = ["Computer history (newest first)"];
155
+ if (history.incomplete) lines.push(earlierBuildNote);
156
+ if (!history.events.length) lines.push("No events recorded yet.");
157
+ for (const event of history.events.slice().reverse()) lines.push(historyLine(event));
158
+ console.log(lines.map(oneLine).join("\n"));
159
+ }
160
+ return 0;
161
+ }
162
+ if (opts.demo && (opts.attribute || opts.projectOnly || opts.noHistory || opts.approve || opts.lookup || opts.failOn || opts.yes || opts.folderGiven || opts.jsonl || opts.sarif || opts.rules)) throw new Error("Use --demo to review the sample computer. It also supports --open, --explain and --json.");
163
+ if ((opts.attribute || opts.review || opts.approve) && (opts.noHistory || opts.projectOnly)) throw new Error("Computer review needs a scan with computer history enabled.");
164
+ if (opts.review && (opts.approve || opts.json || opts.jsonl || !process.stdin.isTTY || !process.stdout.isTTY)) throw new Error("Use --review in a terminal, or run --approve ID to choose one item directly.");
165
+ if (opts.demo) return withDemo((demo) => runScan({ ...opts, offline: true }, demo));
166
+ return runScan(opts);
167
+ }
168
+
169
+ async function runScan(opts, demo) {
170
+ // A mistake in a rules file stops the command before anything is checked.
171
+ const rules = opts.rules ? await loadRules(opts.rules) : [];
172
+ const update = automaticUpdateCheck(opts) ? packageUpdate(await version()) : null;
74
173
  const known = opts.offline ? { asOf: `${KNOWN_AS_OF}T00:00:00Z`, from: "offline" } : await todaysList();
75
- const input = await discover({ dir: opts.dir, includeUser: !opts.projectOnly });
76
- let result = { ...check(input), knownMalware: known };
77
- let lookedUp = false;
78
- if (opts.lookup) ({ result, lookedUp } = await lookup(opts, result));
174
+ // A concurrent local scan can cause the transaction to retry. Reuse an
175
+ // OSV answer only for the same packages the user agreed to look up.
176
+ let lookupCache;
177
+ async function scan(state, lookupAuthors = true) {
178
+ const snapshot = state && computerSnapshot(state.key, demo?.discovery);
179
+ const currentFiles = (opts.attribute || demo) && snapshot && lookupAuthors ? new Map() : null;
180
+ const collect = currentFiles ? (file, raw, flags, original) => {
181
+ snapshot.collect(file, raw, flags, original);
182
+ if (typeof original === "string" && original.length <= LIMITS.maxFileBytes && snapshot.verified.has(file)) currentFiles.set(file, original);
183
+ } : snapshot?.collect;
184
+ const input = await discover({ dir: opts.dir, includeUser: !opts.projectOnly, ...demo?.discovery, onComputerFile: collect });
185
+ let result = { ...check(input, rules), knownMalware: known };
186
+ // The rules of your own that the check ran with. Every report says how many.
187
+ if (rules.length) result.customRules = rules.map((rule) => rule.id);
188
+ if (demo) { result.demo = true; input.scanned.demo = true; }
189
+ let lookedUp = false;
190
+ if (opts.lookup) {
191
+ const key = JSON.stringify(lookupQueries(result));
192
+ if (lookupCache?.key !== key) lookupCache = { key, ...await lookup(opts, result) };
193
+ lookedUp = lookupCache.lookedUp;
194
+ if (lookedUp) result = applyLookup(result, lookupCache.hits);
195
+ }
196
+ if (state) {
197
+ snapshot.inventory(input, result.installed);
198
+ await snapshot.checkMissing({ ...state.removedPending, ...state.approved, ...state.seen });
199
+ result.computerReview = observe(state, snapshot, result.findings);
200
+ if (currentFiles) result.computerReview.attribution = await attributeEdits(state, result.computerReview, currentFiles,
201
+ demo ? { ...demo.discovery, sessions: [demo.session] } : { sessions: opts.sessions });
202
+ }
203
+ return { input, result, lookedUp };
204
+ }
205
+ if (demo) {
206
+ await updateReview(async (state) => {
207
+ const { result } = await scan(state);
208
+ for (const row of result.computerReview.pending) approve(state, row.id, "Demo setup");
209
+ }, demo.store);
210
+ await demo.bump();
211
+ if (!opts.json) console.log("Demo · A sample Codex tool record accompanies the calendar update from 1.2.3 to 1.2.4. The mail server has an unpinned package.\nThis run uses a fresh sample profile and deletes it when you finish.");
212
+ }
213
+ let report;
214
+ if (opts.projectOnly || opts.noHistory) report = await scan(null);
215
+ else {
216
+ try {
217
+ report = await updateReview(async (state) => {
218
+ const next = await scan(state);
219
+ if (opts.approve) showApproval(next.result.computerReview, next.result.findings, approve(state, opts.approve));
220
+ return next;
221
+ }, demo?.store);
222
+ }
223
+ catch (err) {
224
+ if (demo || opts.approve || opts.review || !err.reviewStorage) throw err;
225
+ report = await scan(null);
226
+ report.result.computerReviewError = "Computer history unavailable. " + err.message;
227
+ }
228
+ }
229
+ const { input, result, lookedUp } = report;
230
+ const decide = (id, account) => updateReview(async (state) => {
231
+ // A prompt may have been left open while the file changed.
232
+ await scan(state, false);
233
+ return approve(state, id, account);
234
+ }, demo?.store);
235
+ if (opts.review || (demo && process.stdin.isTTY && process.stdout.isTTY && !opts.json)) await reviewAtTerminal(result, decide, Boolean(demo));
236
+ else if (demo) {
237
+ if (!opts.json) console.log("Playing the sample decisions as Demo reviewer.");
238
+ const review = result.computerReview;
239
+ for (const item of [...review.pending, ...review.risks]) showApproval(review, result.findings, await decide(item.id, "Demo reviewer"));
240
+ }
79
241
 
80
- if (opts.json) process.stdout.write(JSON.stringify(result, null, 2) + "\n");
242
+ if (opts.json) process.stdout.write(stringify(result, 2) + "\n");
243
+ else if (opts.jsonl) process.stdout.write(jsonLines(result, { version: await version() }));
81
244
  else printReport(result, { version: await version(), scanned: input.scanned, explain: opts.explain, open: opts.open, lookedUp, known });
245
+ if (update) {
246
+ const notice = updateMessage(await update);
247
+ if (notice) console.error("\n" + notice);
248
+ }
82
249
 
83
250
  if (opts.open) await openReport(opts, input, result);
251
+ if (opts.sarif) await saveSarif(opts, result);
84
252
 
85
253
  if (opts.failOn) {
86
254
  const worst = LEVELS.slice(0, LEVELS.indexOf(opts.failOn) + 1);
@@ -88,7 +256,32 @@ export async function main(argv) {
88
256
  // A check that couldn't see everything shouldn't pass a CI gate.
89
257
  if (result.stats.truncated) return 2;
90
258
  }
91
- return 0;
259
+ return result.computerReviewError ? 2 : 0;
260
+ }
261
+
262
+ async function reviewAtTerminal(result, decide, demo) {
263
+ const review = result.computerReview;
264
+ process.stdout.write("\nReview " + (demo ? "the sample computer" : "this computer") + ". Y approves, Enter skips, and Q finishes. Each decision is saved immediately.\n");
265
+ for (const file of review.unverified) process.stdout.write("Could not fully verify " + oneLine(file) + ".\n");
266
+ const prompts = [
267
+ ...review.pending.map((row) => ({ id: row.id, text: changeText(row), question: "Approve this change?" })),
268
+ ...review.risks.filter((r) => !r.acceptedAt).map((r) => ({ id: r.id, text: r.severity + " · " + r.title + " · " + r.file, question: "Accept this risk and keep its warning visible?" })),
269
+ ];
270
+ for (const p of prompts) {
271
+ process.stdout.write("\n" + oneLine(p.text) + "\n");
272
+ const finding = result.findings.find((f) => f.review?.id === p.id);
273
+ if (finding) process.stdout.write(oneLine(finding.why) + "\nFix: " + oneLine(finding.fix) + "\n");
274
+ else {
275
+ const file = review.pending.find((r) => r.id === p.id)?.file;
276
+ for (const risk of review.risks.filter((r) => r.file === file)) process.stdout.write(" Risk in this file: " + oneLine(risk.title) + "\n");
277
+ }
278
+ const answer = await ask(process.stdout, p.question + " [y/N/q] ");
279
+ if (answer === "q" || answer === "quit") break;
280
+ if (answer !== "y" && answer !== "yes") continue;
281
+ const decision = await decide(p.id, demo ? "Demo reviewer" : undefined);
282
+ showApproval(review, result.findings, decision);
283
+ process.stdout.write(review.confirmation + "\n");
284
+ }
92
285
  }
93
286
 
94
287
  // Today's list of known malware from misconfig.ai, added to the one in this
@@ -126,8 +319,8 @@ async function todaysList() {
126
319
  const doNotTrack = () => (/^(?:1|true)$/i.test(process.env.DO_NOT_TRACK ?? "") ? { dnt: "1" } : {});
127
320
 
128
321
  // Runs the checks, then points findings in reduced files back at real lines.
129
- function check(input) {
130
- const result = analyze(input);
322
+ function check(input, rules) {
323
+ const result = analyze(input, { rules });
131
324
  for (const f of result.findings) {
132
325
  const map = f.file && input.lineMaps?.[f.file];
133
326
  if (map && f.line) f.line = map[f.line - 1] ?? null;
@@ -137,7 +330,7 @@ function check(input) {
137
330
 
138
331
  // Asks OSV.dev about what's installed, after showing exactly what will be sent.
139
332
  async function lookup(opts, result) {
140
- const out = opts.json ? process.stderr : process.stdout;
333
+ const out = notes(opts);
141
334
  const base = serviceBase("MISCONFIG_OSV_URL", "https://api.osv.dev");
142
335
  const queries = lookupQueries(result);
143
336
  printLookupPreview(out, queries);
@@ -146,7 +339,7 @@ async function lookup(opts, result) {
146
339
  const { hits, failed, asked } = await osvLookup(queries, { base, installs: installsOnly(result) });
147
340
  const next = applyLookup(result, hits);
148
341
  printLookupResult(out, { asked, failed, found: next.findings.length - result.findings.length });
149
- return { result: next, lookedUp: true };
342
+ return { result: next, lookedUp: true, hits };
150
343
  }
151
344
 
152
345
  // A yes from someone at the terminal, or --yes. Without a terminal and
@@ -190,10 +383,14 @@ function serviceBase(name = "MISCONFIG_URL", fallback = "https://misconfig.ai")
190
383
  return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
191
384
  }
192
385
 
386
+ // With --json or --jsonl, stdout is for the program reading it, so what the
387
+ // command has to say to a person goes to stderr.
388
+ const notes = (opts) => (opts.json || opts.jsonl ? process.stderr : process.stdout);
389
+
193
390
  // The full report as a file on this computer, opened in the browser for
194
391
  // someone at a terminal. Nothing is uploaded.
195
392
  async function openReport(opts, input, result) {
196
- const out = opts.json ? process.stderr : process.stdout;
393
+ const out = notes(opts);
197
394
  // The list of packages is only for --lookup; the report doesn't show it.
198
395
  const report = { ...result };
199
396
  delete report.packages;
@@ -204,6 +401,23 @@ async function openReport(opts, input, result) {
204
401
  if (opening) openInBrowser(file);
205
402
  }
206
403
 
404
+ // --sarif: the findings as a file. It's written under another name and moved
405
+ // into place, so a link that a project from someone else left at that name
406
+ // is replaced, not followed into a file somewhere else.
407
+ async function saveSarif(opts, result) {
408
+ const file = path.resolve(opts.sarif);
409
+ const temp = `${file}.${randomUUID()}.tmp`;
410
+ try {
411
+ await writeFile(temp, stringify(sarif(result, { version: await version() }), 2) + "\n", { flag: "wx", mode: 0o600 });
412
+ await rename(temp, file);
413
+ } catch (err) {
414
+ await unlink(temp).catch(() => {});
415
+ const why = { ENOENT: "the folder it's in doesn't exist", ENOTDIR: "the folder it's in doesn't exist", EACCES: "this account can't write there", EPERM: "this account can't write there", EROFS: "this account can't write there", EISDIR: "a folder has that name" }[err?.code];
416
+ throw new Error(`The SARIF file wasn't saved at ${opts.sarif}: ${why ?? err?.message ?? err}.`);
417
+ }
418
+ printSarifResult(notes(opts), { file, stopped: result.stats.truncated });
419
+ }
420
+
207
421
  let cachedVersion = null;
208
422
  async function version() {
209
423
  cachedVersion ??= JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")).version;
@@ -0,0 +1,95 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+
6
+ const LATEST = "https://registry.npmjs.org/@misconfig%2fcli/latest";
7
+ const DAY = 86400000;
8
+ const core = "(0|[1-9][0-9]*)";
9
+ const semver = new RegExp("^" + [core, core, core].join("\\.") + "(?:-([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$");
10
+
11
+ function parts(version) {
12
+ if (typeof version !== "string" || version.length > 128) return null;
13
+ const m = semver.exec(version);
14
+ if (!m) return null;
15
+ const pre = m[4]?.split(".");
16
+ if (pre?.some((s) => /^0\d+$/.test(s))) return null;
17
+ return { main: m.slice(1, 4).map((s) => BigInt(s)), pre };
18
+ }
19
+
20
+ export function compareVersions(a, b) {
21
+ const x = parts(a), y = parts(b);
22
+ if (!x || !y) return null;
23
+ for (let i = 0; i < 3; i++) if (x.main[i] !== y.main[i]) return x.main[i] > y.main[i] ? 1 : -1;
24
+ if (!x.pre || !y.pre) return x.pre ? -1 : y.pre ? 1 : 0;
25
+ for (let i = 0; i < Math.min(x.pre.length, y.pre.length); i++) {
26
+ const p = x.pre[i], q = y.pre[i];
27
+ if (p === q) continue;
28
+ const pn = /^\d+$/.test(p), qn = /^\d+$/.test(q);
29
+ if (pn !== qn) return pn ? -1 : 1;
30
+ return (pn ? BigInt(p) > BigInt(q) : p > q) ? 1 : -1;
31
+ }
32
+ return Math.sign(x.pre.length - y.pre.length);
33
+ }
34
+
35
+ async function registryVersion(fetchImpl) {
36
+ const res = await fetchImpl(LATEST, { headers: { accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(1800) });
37
+ if (!res.ok || !res.body) return null;
38
+ const chunks = [];
39
+ let size = 0;
40
+ for await (const chunk of res.body) {
41
+ size += chunk.length;
42
+ if (size > 128 * 1024) return null;
43
+ chunks.push(chunk);
44
+ }
45
+ const data = JSON.parse(Buffer.concat(chunks).toString("utf8"));
46
+ const parsed = parts(data.version);
47
+ return data.name === "@misconfig/cli" && parsed && !parsed.pre ? data.version : null;
48
+ }
49
+
50
+ export function automaticUpdateCheck(opts, env = process.env, terminal = process.stdout.isTTY && process.stdin.isTTY) {
51
+ return Boolean(terminal && !opts.offline && !opts.demo && !opts.json && !opts.jsonl && !opts.projectOnly && !opts.noHistory && !opts.noUpdate
52
+ && !opts.failOn && !env.CI && !env.NO_UPDATE_NOTIFIER && env.MISCONFIG_NO_UPDATE_CHECK !== "1");
53
+ }
54
+
55
+ export async function packageUpdate(installed, { force = false, offline = false, fetchImpl = fetch,
56
+ cache = path.join(homedir(), ".misconfig", "npm-update.json"), now = Date.now() } = {}) {
57
+ if (offline) return { installed, latest: null, status: "offline" };
58
+ let prior;
59
+ try { prior = JSON.parse(await readFile(cache, "utf8")); } catch {}
60
+ const upgradedFrom = compareVersions(installed, prior?.installed) === 1 ? prior.installed : null;
61
+ const fresh = Number.isFinite(prior?.checkedAt) && now >= prior.checkedAt && now - prior.checkedAt < DAY;
62
+ let latest = prior?.latest, checkedAt = prior?.checkedAt;
63
+ if (force || !fresh || !parts(latest) || parts(latest).pre) {
64
+ try { latest = await registryVersion(fetchImpl); } catch { latest = null; }
65
+ if (!latest) return { installed, latest: null, status: "unavailable" };
66
+ checkedAt = now;
67
+ }
68
+ const order = compareVersions(latest, installed);
69
+ const status = order > 0 ? "available" : order < 0 ? "ahead" : "current";
70
+ // An explicit registry query can be consumed as JSON by a script. Leave
71
+ // the first interactive release announcement available for the next scan.
72
+ const firstReleaseNotice = !force && status === "current" && prior?.announced !== installed;
73
+ const announced = firstReleaseNotice ? installed : prior?.announced;
74
+ if (checkedAt !== prior?.checkedAt || installed !== prior?.installed || latest !== prior?.latest || firstReleaseNotice) {
75
+ const tmp = cache + "." + randomUUID();
76
+ try {
77
+ await mkdir(path.dirname(cache), { recursive: true, mode: 0o700 });
78
+ await writeFile(tmp, JSON.stringify({ installed, latest, checkedAt, announced }), { flag: "wx", mode: 0o600 });
79
+ await rename(tmp, cache);
80
+ } catch {} finally { await unlink(tmp).catch(() => {}); }
81
+ }
82
+ return { installed, latest, status, upgradedFrom, firstReleaseNotice };
83
+ }
84
+
85
+ export function updateMessage(update, explicit = false) {
86
+ switch (update.status) {
87
+ case "available": return "misconfig " + update.latest + " is available on npm (installed " + update.installed + "). Run " + (process.platform === "win32" ? "npx.cmd" : "npx") + " @misconfig/cli@latest to use it.";
88
+ case "offline": return explicit ? "Offline mode is on. The npm registry was not contacted." : "";
89
+ case "unavailable": return explicit ? "Could not check the npm registry for a stable release." : "";
90
+ default:
91
+ if (update.upgradedFrom && update.status === "current") return "Now running misconfig " + update.installed + ", updated from " + update.upgradedFrom + ".";
92
+ if (update.firstReleaseNotice) return "You're running misconfig " + update.installed + ", the latest npm release." + (update.installed === "1.4.0" ? " Try --demo to see the new computer review and edit history." : "");
93
+ return explicit ? "Installed misconfig " + update.installed + ". Latest stable release on npm is " + update.latest + "." : "";
94
+ }
95
+ }
package/lib/print.js CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { SCOPES } from "../engine/explain.js";
6
6
  import { INSTALLED_BY } from "../engine/index.js";
7
+ import { reviewLines } from "./computer-review.js";
7
8
 
8
9
  const env = process.env;
9
10
 
@@ -53,7 +54,15 @@ const color = (name) => (s) => (on ? `\x1b[${code(name, "fg")}m${s}\x1b[39m` : S
53
54
  // Text from the files being checked can hold terminal control codes that
54
55
  // would rewrite the screen, or bidirectional marks that reorder it. They're
55
56
  // shown as the replacement character (U+FFFD) instead.
56
- const safe = (s) => String(s ?? "").replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "\ufffd");
57
+ //
58
+ // A CI system also reads parts of its log as commands. GitHub Actions takes
59
+ // ##[name] anywhere in a line, Azure Pipelines takes ##vso[name], and
60
+ // TeamCity reads ##teamcity[name]. A name in a checked file could spell one,
61
+ // so the same character goes inside it and the line stays text.
62
+ const safe = (s) =>
63
+ String(s ?? "")
64
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "\ufffd")
65
+ .replace(/#(?=#[a-z]*\[)/gi, "#\ufffd");
57
66
  // For text printed on one line, such as a title or a path: line breaks in it
58
67
  // would start a new line that looks like part of the report.
59
68
  export const oneLine = (s) => safe(s).replace(/[\t\n]/g, " ");
@@ -90,6 +99,12 @@ function fitPath(p, max) {
90
99
  }
91
100
 
92
101
  const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
102
+
103
+ // A report's lines as one piece of text. GitHub Actions reads a line that
104
+ // starts with ::name:: as a command, spaces before it or not, and a wrapped
105
+ // line can start with a word from a checked file. Such a line gets the
106
+ // replacement character between its colons.
107
+ const page = (lines) => lines.map((line) => line.replace(/^(\s*):(?=:)/, "$1:\ufffd")).join("\n") + "\n";
93
108
  const npx = process.platform === "win32" ? "npx.cmd" : "npx";
94
109
 
95
110
  // --- Report ------------------------------------------------------------------
@@ -101,12 +116,18 @@ export function printReport(result, { version, scanned, explain = false, open =
101
116
  const out = [];
102
117
  // One blank line between blocks, never two.
103
118
  const gap = () => out.length && out[out.length - 1] !== "" && out.push("");
104
- const where = scanned.projectSkipped ? "your home folder" : scanned.project;
119
+ const where = scanned.demo ? "the sample computer" : scanned.projectSkipped ? "your home folder" : scanned.project;
105
120
  const sent = lookedUp ? "Everything ran here. Only package names and versions went to OSV.dev, to look them up." : "Everything ran here; nothing was uploaded.";
106
121
  out.push(`${bold("misconfig")} ${dim(version)}`);
107
- const project = scanned.projectSkipped ? " To check a project, run it in the project's folder." : "";
108
- out.push(...wrap(`Checked ${where}${scanned.user ? " and the agent settings on this computer" : ""}. ${sent}${knownLine(known)}${project}`, 0).map(dim));
122
+ const project = scanned.projectSkipped && !scanned.demo ? " To check a project, run it in the project's folder." : "";
123
+ const ownRules = result.customRules?.length ?? 0;
124
+ const own = ownRules ? ` ${plural(ownRules, "rule")} of your own ${ownRules === 1 ? "was" : "were"} checked too.` : "";
125
+ out.push(...wrap(`Checked ${where}${scanned.user && !scanned.demo ? " and the agent settings on this computer" : ""}. ${sent}${knownLine(known)}${own}${project}`, 0).map(dim));
109
126
  out.push("");
127
+ if (result.computerReview) {
128
+ out.push(bold("Computer review"), ...reviewLines(result.computerReview, scanned.demo).map(oneLine), "");
129
+ }
130
+ if (result.computerReviewError) out.push(oneLine(result.computerReviewError), "");
110
131
 
111
132
  // Every file that directs an agent, where it applies, and what it tells the
112
133
  // agent. Worked out on this computer and shown only here and in the page
@@ -162,6 +183,7 @@ export function printReport(result, { version, scanned, explain = false, open =
162
183
  // Where it is, then the rule, which misconfig.ai/rules explains.
163
184
  const at = f.file ? fitPath(f.file, width() - 16 - f.id.length) + (f.line ? `:${f.line}` : "") : "";
164
185
  out.push(` ${dim(at ? `${at} ${f.id}` : f.id)}`);
186
+ if (f.review) out.push(" " + (f.review.acceptedAt ? "Risk accepted on " + new Date(f.review.acceptedAt).toISOString().slice(0, 10) + " by " + oneLine(f.review.acceptedBy ?? "an unknown account") : scanned.demo ? "Awaiting risk review" : "Accept risk: --approve " + f.review.id));
165
187
  if (sev === "critical" || sev === "high" || sev === "medium") out.push(...wrap(f.why, 6));
166
188
  out.push(...wrap(f.fix, 11, ` ${dim("Fix")} `));
167
189
  }
@@ -173,21 +195,26 @@ export function printReport(result, { version, scanned, explain = false, open =
173
195
  if (!map.length && !findings.length) {
174
196
  out.push(...wrap("No files that control AI agents were found here. Run the check in the folder you open your agent in, usually the project root.", 0));
175
197
  if (result.stats.truncated) out.push("", ...stopped());
176
- process.stdout.write(out.join("\n") + "\n");
198
+ process.stdout.write(page(out));
177
199
  return;
178
200
  }
179
201
  // The verdict, last, where it's on screen when the check finishes.
180
202
  out.push(...verdict(result), "");
181
203
  if (result.stats.truncated) out.push(...stopped(), "");
204
+ if (scanned.demo) {
205
+ out.push("Run --demo again to start a fresh sample.");
206
+ process.stdout.write(page(out));
207
+ return;
208
+ }
182
209
  const next = [];
183
210
  if (!explain && map.some((f) => f.details?.length)) next.push(["Everything each file says", `${npx} @misconfig/cli --explain`]);
184
211
  if (!open) next.push(["Full report in your browser", `${npx} @misconfig/cli --open`]);
185
212
  if (!lookedUp && result.packages?.length) next.push(["Look up installs on OSV.dev", `${npx} @misconfig/cli --lookup`]);
186
- if (findings.length) next.push(["Every rule explained", "https://misconfig.ai/rules"]);
213
+ if (findings.some((f) => !f.custom)) next.push(["Every rule explained", "https://misconfig.ai/rules"]);
187
214
  next.push(["Full details as JSON", `${npx} @misconfig/cli --json`]);
188
215
  const pad = Math.max(...next.map(([label]) => label.length)) + 3;
189
216
  for (const [label, command] of next) out.push(`${dim(label.padEnd(pad))}${command}`);
190
- process.stdout.write(out.join("\n") + "\n");
217
+ process.stdout.write(page(out));
191
218
  }
192
219
 
193
220
  // Which list of known malware the check used.
@@ -231,7 +258,7 @@ export function printLookupPreview(out, queries) {
231
258
  const lines = ["", bold("Look up what's installed on OSV.dev")];
232
259
  if (!queries.length) {
233
260
  lines.push(...wrap("There's nothing to look up: no MCP packages, agent installs or editor extensions were found.", 2), "");
234
- out.write(lines.join("\n") + "\n");
261
+ out.write(page(lines));
235
262
  return;
236
263
  }
237
264
  lines.push(
@@ -245,7 +272,7 @@ export function printLookupPreview(out, queries) {
245
272
  const width = Math.max(...shown.map((q) => registryName(q.ecosystem).length));
246
273
  for (const q of shown) lines.push(oneLine(` ${registryName(q.ecosystem).padEnd(width)} ${q.name}${q.version ? ` ${q.version}` : ""}`) + (q.version ? "" : dim(" (any version)")));
247
274
  if (queries.length > shown.length) lines.push(dim(` and ${queries.length - shown.length} more`));
248
- out.write(lines.join("\n") + "\n");
275
+ out.write(page(lines));
249
276
  }
250
277
 
251
278
  export function printLookupResult(out, { asked, failed, found }) {
@@ -257,7 +284,17 @@ export function printLookupResult(out, { asked, failed, found }) {
257
284
  found ? `${plural(found, "finding")} added to the report.` : "Nothing new turned up.",
258
285
  failed ? `${plural(failed, "package")} couldn't be looked up; try again later.` : "",
259
286
  ];
260
- out.write(["", ...wrap(parts.filter(Boolean).join(" "), 2), ""].join("\n") + "\n");
287
+ out.write(page(["", ...wrap(parts.filter(Boolean).join(" "), 2), ""]));
288
+ }
289
+
290
+ // --- The findings as a file ----------------------------------------------------
291
+
292
+ // Where --sarif saved the findings.
293
+ export function printSarifResult(out, { file, stopped }) {
294
+ const note = stopped
295
+ ? "The check stopped early, and the file says so. Don't upload it to code scanning: findings it didn't reach would be marked as fixed."
296
+ : "Nothing was uploaded. The file names the files with findings and what was found in each, so read it before you share it.";
297
+ out.write(page(["", bold("Findings saved as SARIF"), ` ${oneLine(file)}`, "", ...wrap(note, 2).map(dim), ""]));
261
298
  }
262
299
 
263
300
  // --- The report in a browser ---------------------------------------------------
@@ -265,13 +302,13 @@ export function printLookupResult(out, { asked, failed, found }) {
265
302
  // Where --open saved the report.
266
303
  export function printOpenResult(out, { file, opening }) {
267
304
  out.write(
268
- [
305
+ page([
269
306
  "",
270
307
  bold("Full report saved on this computer"),
271
308
  ` ${file}`,
272
309
  "",
273
310
  ...wrap(`${opening ? "Opening it in your browser. " : ""}Nothing was uploaded. Anyone you send the file to can read everything in it, including the paths and settings on this computer.`, 2).map(dim),
274
311
  "",
275
- ].join("\n") + "\n",
312
+ ]),
276
313
  );
277
314
  }