@misconfig/cli 1.1.0 → 1.3.1

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,26 +1,43 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { createInterface } from "node:readline/promises";
3
- import { analyze, toShareable } from "../engine/index.js";
3
+ import { analyze, applyLookup, useKnownMalware } from "../engine/index.js";
4
+ import { KNOWN_AS_OF } from "../engine/known.js";
4
5
  import { discover } from "./discover.js";
5
- import { printReport, printSharePreview, printShareResult } from "./print.js";
6
+ import { printReport, printOpenResult, printLookupPreview, printLookupResult } from "./print.js";
7
+ import { writeReport, openInBrowser } from "./html.js";
8
+ import { lookupQueries, osvLookup, installsOnly } from "./lookup.js";
6
9
 
7
10
  const HELP = `Usage: npx @misconfig/cli [folder] [options]
8
11
 
9
12
  Finds every file that controls your AI coding agents, on this computer and in
10
13
  the folder (the current folder by default), and checks them for risky
11
- settings. Everything runs here. Nothing is sent anywhere unless you use --share.
14
+ settings. It also checks the MCP servers, editor extensions, skills and agent
15
+ versions installed for known malware and missing security fixes. Everything
16
+ 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.
12
19
 
13
20
  Options
14
21
  --explain Show everything each file tells your agents: rules,
15
- permissions, MCP servers, hooks and hidden text
16
- --share Publish this project's findings and print a link. Shows
17
- what will be sent and asks first. No file contents are
18
- sent, and nothing from outside the project.
19
- --yes Share without asking, for scripts and CI
22
+ permissions, MCP servers, hooks and hidden text, and
23
+ what's installed
24
+ --lookup Also look up the MCP packages, editor extensions and
25
+ agent versions found on OSV.dev, for malware and known
26
+ vulnerabilities, including ones newer than this
27
+ release. Sends only package names and versions, and
28
+ asks first.
29
+ --open Save the full report as a page on this computer and
30
+ 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.
34
+ --yes Look up without asking, for scripts and CI
20
35
  --json Print the full result as JSON
21
36
  --project-only Skip the agent settings on this computer
22
37
  --fail-on <level> Exit with code 1 if anything at this level or worse is
23
38
  found: critical, high, medium or low. Useful in CI.
39
+ Exits with code 2 if the folder was too big to check
40
+ completely.
24
41
  -v, --version Print the version
25
42
  -h, --help Show this help
26
43
  `;
@@ -28,7 +45,7 @@ Options
28
45
  const LEVELS = ["critical", "high", "medium", "low"];
29
46
 
30
47
  export async function main(argv) {
31
- const opts = { dir: process.cwd(), share: false, yes: false, json: false, explain: false, projectOnly: false, failOn: null };
48
+ const opts = { dir: process.cwd(), open: false, lookup: false, offline: process.env.MISCONFIG_OFFLINE === "1", yes: false, json: false, explain: false, projectOnly: false, failOn: null };
32
49
  for (let i = 0; i < argv.length; i++) {
33
50
  const a = argv[i];
34
51
  if (a === "-h" || a === "--help") {
@@ -39,7 +56,10 @@ export async function main(argv) {
39
56
  console.log(await version());
40
57
  return 0;
41
58
  }
42
- if (a === "--share") opts.share = true;
59
+ if (a === "--share") throw new Error("--share was removed in 1.3.1: misconfig.ai no longer publishes reports. Use --open for the full report on your computer.");
60
+ if (a === "--open") opts.open = true;
61
+ else if (a === "--lookup") opts.lookup = true;
62
+ else if (a === "--offline") opts.offline = true;
43
63
  else if (a === "--yes" || a === "-y") opts.yes = true;
44
64
  else if (a === "--json") opts.json = true;
45
65
  else if (a === "--explain") opts.explain = true;
@@ -51,21 +71,60 @@ export async function main(argv) {
51
71
  else opts.dir = a;
52
72
  }
53
73
 
74
+ const known = opts.offline ? { asOf: `${KNOWN_AS_OF}T00:00:00Z`, from: "offline" } : await todaysList();
54
75
  const input = await discover({ dir: opts.dir, includeUser: !opts.projectOnly });
55
- const result = check(input);
76
+ let result = { ...check(input), knownMalware: known };
77
+ let lookedUp = false;
78
+ if (opts.lookup) ({ result, lookedUp } = await lookup(opts, result));
56
79
 
57
80
  if (opts.json) process.stdout.write(JSON.stringify(result, null, 2) + "\n");
58
- else printReport(result, { version: await version(), scanned: input.scanned, explain: opts.explain });
81
+ else printReport(result, { version: await version(), scanned: input.scanned, explain: opts.explain, open: opts.open, lookedUp, known });
59
82
 
60
- if (opts.share) await share(opts, input, result);
83
+ if (opts.open) await openReport(opts, input, result);
61
84
 
62
85
  if (opts.failOn) {
63
86
  const worst = LEVELS.slice(0, LEVELS.indexOf(opts.failOn) + 1);
64
87
  if (result.findings.some((f) => worst.includes(f.severity))) return 1;
88
+ // A check that couldn't see everything shouldn't pass a CI gate.
89
+ if (result.stats.truncated) return 2;
65
90
  }
66
91
  return 0;
67
92
  }
68
93
 
94
+ // Today's list of known malware from misconfig.ai, added to the one in this
95
+ // release. The request says only which version of the command is asking and
96
+ // the kind of system, which is how misconfig.ai counts runs; with
97
+ // DO_NOT_TRACK=1 it asks not to be counted. If the list doesn't come within
98
+ // a few seconds, the check uses the one in this release and says so.
99
+ async function todaysList() {
100
+ const fallback = { asOf: `${KNOWN_AS_OF}T00:00:00Z`, from: "release" };
101
+ try {
102
+ const system = { darwin: "mac", win32: "windows", linux: "linux" }[process.platform];
103
+ const headers = { "user-agent": `misconfig-cli/${await version()}${system ? ` (${system})` : ""}`, ...doNotTrack() };
104
+ const res = await fetch(`${serviceBase()}/api/known`, { headers, signal: AbortSignal.timeout(5000) });
105
+ if (!res.ok || !res.body) return fallback;
106
+ // Read only up to 4 MB: the list is a few kilobytes.
107
+ const parts = [];
108
+ let size = 0;
109
+ const reader = res.body.getReader();
110
+ for (let part = await reader.read(); !part.done; part = await reader.read()) {
111
+ size += part.value.byteLength;
112
+ if (size > 4 * 1024 * 1024) {
113
+ reader.cancel().catch(() => {});
114
+ return fallback;
115
+ }
116
+ parts.push(part.value);
117
+ }
118
+ const list = useKnownMalware(JSON.parse(Buffer.concat(parts).toString("utf8")));
119
+ return list ? { asOf: list.updated, from: "misconfig.ai" } : fallback;
120
+ } catch {
121
+ return fallback;
122
+ }
123
+ }
124
+
125
+ // DO_NOT_TRACK=1 asks misconfig.ai not to count a run.
126
+ const doNotTrack = () => (/^(?:1|true)$/i.test(process.env.DO_NOT_TRACK ?? "") ? { dnt: "1" } : {});
127
+
69
128
  // Runs the checks, then points findings in reduced files back at real lines.
70
129
  function check(input) {
71
130
  const result = analyze(input);
@@ -76,36 +135,73 @@ function check(input) {
76
135
  return result;
77
136
  }
78
137
 
79
- async function share(opts, input, result) {
80
- // A share link covers the project only. Settings on this computer stay here.
138
+ // Asks OSV.dev about what's installed, after showing exactly what will be sent.
139
+ async function lookup(opts, result) {
81
140
  const out = opts.json ? process.stderr : process.stdout;
82
- if (input.scanned.projectSkipped) {
83
- throw new Error("There's no project to share here. Run npx @misconfig/cli --share inside a project folder. Settings on your computer are never shared.");
84
- }
85
- const project = input.scanned.user ? check(await discover({ dir: opts.dir, includeUser: false })) : result;
86
- const payload = toShareable(project);
87
- printSharePreview(out, payload, project, { includesUser: input.scanned.user });
88
-
89
- if (!opts.yes) {
90
- if (!process.stdin.isTTY) throw new Error("Nothing was sent. Add --yes to share without a prompt, for example in CI.");
91
- const rl = createInterface({ input: process.stdin, output: out });
92
- const answer = (await rl.question("Publish this report? [y/N] ")).trim().toLowerCase();
141
+ const base = serviceBase("MISCONFIG_OSV_URL", "https://api.osv.dev");
142
+ const queries = lookupQueries(result);
143
+ printLookupPreview(out, queries);
144
+ if (!queries.length) return { result, lookedUp: false };
145
+ if (!(await confirmed(opts, out, "\nLook these up on OSV.dev? [y/N] ", "Nothing was sent. Add --yes to look up without a prompt."))) return { result, lookedUp: false };
146
+ const { hits, failed, asked } = await osvLookup(queries, { base, installs: installsOnly(result) });
147
+ const next = applyLookup(result, hits);
148
+ printLookupResult(out, { asked, failed, found: next.findings.length - result.findings.length });
149
+ return { result: next, lookedUp: true };
150
+ }
151
+
152
+ // A yes from someone at the terminal, or --yes. Without a terminal and
153
+ // without --yes, nothing is sent.
154
+ async function confirmed(opts, out, question, refusal) {
155
+ if (opts.yes) return true;
156
+ if (!process.stdin.isTTY) throw new Error(refusal);
157
+ const answer = await ask(out, question);
158
+ if (answer === "y" || answer === "yes") return true;
159
+ out.write("Nothing was sent.\n");
160
+ return false;
161
+ }
162
+
163
+ // A question at the terminal. Ctrl+C, or the input ending, cancels it with an
164
+ // AbortError, which stops the command with nothing sent.
165
+ async function ask(out, question) {
166
+ const rl = createInterface({ input: process.stdin, output: out });
167
+ const stop = new AbortController();
168
+ rl.once("SIGINT", () => stop.abort());
169
+ rl.once("close", () => stop.abort());
170
+ try {
171
+ return (await rl.question(question, { signal: stop.signal })).trim().toLowerCase();
172
+ } finally {
93
173
  rl.close();
94
- if (answer !== "y" && answer !== "yes") {
95
- out.write("Nothing was sent.\n");
96
- return;
97
- }
98
174
  }
175
+ }
176
+
177
+ // Where requests go: misconfig.ai and OSV.dev, or for testing the addresses
178
+ // MISCONFIG_URL and MISCONFIG_OSV_URL name. Only https addresses, or http on
179
+ // this computer.
180
+ function serviceBase(name = "MISCONFIG_URL", fallback = "https://misconfig.ai") {
181
+ const raw = process.env[name] || fallback;
182
+ let url;
183
+ try {
184
+ url = new URL(raw);
185
+ } catch {
186
+ throw new Error(`${name} isn't a web address. Nothing was sent.`);
187
+ }
188
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
189
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) throw new Error(`${name} must start with https://. Nothing was sent.`);
190
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
191
+ }
99
192
 
100
- const base = (process.env.MISCONFIG_URL || "https://misconfig.ai").replace(/\/+$/, "");
101
- const res = await fetch(`${base}/api/share`, {
102
- method: "POST",
103
- headers: { "content-type": "application/json", "user-agent": `misconfig-cli/${await version()}` },
104
- body: JSON.stringify(payload),
105
- });
106
- const data = await res.json().catch(() => ({}));
107
- if (!res.ok) throw new Error(data.error || `Sharing didn't work (error ${res.status}). Your report wasn't published.`);
108
- printShareResult(out, data);
193
+ // The full report as a file on this computer, opened in the browser for
194
+ // someone at a terminal. Nothing is uploaded.
195
+ async function openReport(opts, input, result) {
196
+ const out = opts.json ? process.stderr : process.stdout;
197
+ // The list of packages is only for --lookup; the report doesn't show it.
198
+ const report = { ...result };
199
+ delete report.packages;
200
+ const file = await writeReport(report, { version: await version(), scanned: input.scanned });
201
+ // A browser opens only for someone at a terminal, never in CI or a script.
202
+ const opening = Boolean(process.stdout.isTTY && process.stdin.isTTY);
203
+ printOpenResult(out, { file, opening });
204
+ if (opening) openInBrowser(file);
109
205
  }
110
206
 
111
207
  let cachedVersion = null;
package/lib/print.js CHANGED
@@ -1,147 +1,277 @@
1
- // Terminal output.
1
+ // Terminal output, in misconfig.ai's visual language: quiet text, bold where
2
+ // it matters, and color in two places only, the grade's square and the
3
+ // severity marks.
2
4
 
3
5
  import { SCOPES } from "../engine/explain.js";
6
+ import { INSTALLED_BY } from "../engine/index.js";
4
7
 
5
8
  const env = process.env;
6
- const color = Boolean(env.FORCE_COLOR) || (process.stdout.isTTY && !env.NO_COLOR && env.TERM !== "dumb");
7
- const paint = (code) => (s) => (color ? `\x1b[${code}m${s}\x1b[0m` : String(s));
8
- export const bold = paint("1");
9
- export const dim = paint("2");
10
- const SEV = {
11
- critical: { label: "Critical", paint: paint("1;31") },
12
- high: { label: "High", paint: paint("1;38;5;208") },
13
- medium: { label: "Medium", paint: paint("1;33") },
14
- low: { label: "Low", paint: paint("1;34") },
15
- info: { label: "Info", paint: paint("2") },
9
+
10
+ // --- Color -------------------------------------------------------------------
11
+
12
+ // Color depth in bits: 24, 8, 4, or 1 for none. FORCE_COLOR and NO_COLOR
13
+ // work as in Node, and output that isn't a terminal is plain unless forced.
14
+ function colorDepth(stream) {
15
+ if ("FORCE_COLOR" in env) {
16
+ if (/^(0|false)$/i.test(env.FORCE_COLOR)) return 1;
17
+ if (stream.isTTY && stream.getColorDepth) return Math.max(stream.getColorDepth(), 4);
18
+ return env.FORCE_COLOR === "3" ? 24 : env.FORCE_COLOR === "2" ? 8 : 4;
19
+ }
20
+ if (!stream.isTTY || env.NO_COLOR || env.TERM === "dumb") return 1;
21
+ return stream.getColorDepth?.() ?? 4;
22
+ }
23
+ const depth = colorDepth(process.stdout);
24
+
25
+ // The site's colors, with the nearest of 256 and of 16 for older terminals.
26
+ const COLORS = {
27
+ signal: { rgb: [0xea, 0xff, 0x57], ansi: 93 },
28
+ ink: { rgb: [0x00, 0x00, 0x00], ansi: 30 },
29
+ critical: { rgb: [0xd7, 0x26, 0x3d], ansi: 31 },
30
+ high: { rgb: [0xe8, 0x63, 0x0a], ansi: 91 },
31
+ medium: { rgb: [0xb9, 0x89, 0x00], ansi: 33 },
32
+ low: { rgb: [0x25, 0x63, 0xeb], ansi: 34 },
33
+ info: { rgb: [0x8a, 0x90, 0x9c], ansi: 90 },
16
34
  };
17
- const MARK = process.platform === "win32" && !env.WT_SESSION ? "*" : "■";
35
+ const LEVELS = [0, 95, 135, 175, 215, 255];
36
+ const nearest = (c) => LEVELS.reduce((best, v, i) => (Math.abs(v - c) < Math.abs(LEVELS[best] - c) ? i : best), 0);
37
+ const cube = ([r, g, b]) => 16 + 36 * nearest(r) + 6 * nearest(g) + nearest(b);
38
+ function code(name, layer) {
39
+ const { rgb, ansi } = COLORS[name];
40
+ const base = layer === "bg" ? 48 : 38;
41
+ if (depth >= 24) return `${base};2;${rgb.join(";")}`;
42
+ if (depth >= 8) return `${base};5;${cube(rgb)}`;
43
+ return String(layer === "bg" ? ansi + 10 : ansi);
44
+ }
45
+ const on = depth > 1;
46
+ const style = (open, close) => (s) => (on ? `\x1b[${open}m${s}\x1b[${close}m` : String(s));
47
+ export const bold = style("1", "22");
48
+ export const dim = style("2", "22");
49
+ const color = (name) => (s) => (on ? `\x1b[${code(name, "fg")}m${s}\x1b[39m` : String(s));
18
50
 
19
- const width = () => Math.min(Math.max(process.stdout.columns || 100, 60), 110);
51
+ // --- Text --------------------------------------------------------------------
20
52
 
21
- function wrap(text, indent) {
53
+ // Text from the files being checked can hold terminal control codes that
54
+ // would rewrite the screen, or bidirectional marks that reorder it. They're
55
+ // 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
+ // For text printed on one line, such as a title or a path: line breaks in it
58
+ // would start a new line that looks like part of the report.
59
+ export const oneLine = (s) => safe(s).replace(/[\t\n]/g, " ");
60
+
61
+ const width = () => Math.min(Math.max(process.stdout.columns || Number(env.COLUMNS) || 100, 60), 100);
62
+
63
+ // Words wrapped to the width, each line indented. `first` replaces the
64
+ // indent on the first line, for a bullet or a label.
65
+ function wrap(text, indent, first = null) {
22
66
  const max = width() - indent;
23
- const words = String(text).split(/\s+/);
24
67
  const lines = [];
25
68
  let line = "";
26
- for (const w of words) {
69
+ for (const w of safe(text).split(/\s+/).filter(Boolean)) {
27
70
  if (line && line.length + 1 + w.length > max) {
28
71
  lines.push(line);
29
72
  line = w;
30
73
  } else line = line ? `${line} ${w}` : w;
31
74
  }
32
75
  if (line) lines.push(line);
33
- return lines.map((l) => " ".repeat(indent) + l).join("\n");
76
+ return lines.map((l, i) => (i === 0 && first !== null ? first : " ".repeat(indent)) + l);
34
77
  }
35
78
 
36
- const listText = (items) => (items.length <= 1 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`);
37
-
38
- // A list item whose wrapped lines line up under its text.
39
- function bullet(text, indent) {
40
- const lines = wrap(text, indent + 2).split("\n");
41
- lines[0] = " ".repeat(indent) + "- " + lines[0].slice(indent + 2);
42
- return lines.join("\n");
79
+ // A path that fits the line: long ones keep their start and as much of the
80
+ // end as fits, so the file name and the folders just above it stay visible.
81
+ function fitPath(p, max) {
82
+ const s = oneLine(p);
83
+ if (s.length <= max) return s;
84
+ const parts = s.split("/");
85
+ const head = parts.slice(0, parts[0] === "~" ? 2 : 1).join("/");
86
+ let tail = parts[parts.length - 1];
87
+ for (let i = parts.length - 2; i >= 1 && `${head}/…/${parts[i]}/${tail}`.length <= max; i--) tail = `${parts[i]}/${tail}`;
88
+ const out = `${head}/…/${tail}`;
89
+ return out.length <= max ? out : `…${s.slice(-(max - 1))}`;
43
90
  }
44
91
 
45
- export function printReport(result, { version, scanned, explain = false }) {
92
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
93
+ const npx = process.platform === "win32" ? "npx.cmd" : "npx";
94
+
95
+ // --- Report ------------------------------------------------------------------
96
+
97
+ const SEVERITY = { critical: "Critical", high: "High", medium: "Medium", low: "Low", info: "Info" };
98
+ const MARK = "■";
99
+
100
+ export function printReport(result, { version, scanned, explain = false, open = false, lookedUp = false, known = null }) {
46
101
  const out = [];
102
+ // One blank line between blocks, never two.
103
+ const gap = () => out.length && out[out.length - 1] !== "" && out.push("");
47
104
  const where = scanned.projectSkipped ? "your home folder" : scanned.project;
105
+ 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.";
48
106
  out.push(`${bold("misconfig")} ${dim(version)}`);
49
- out.push(
50
- wrap(
51
- `Checked ${where}${scanned.user ? " and the agent settings on this computer" : ""}. Everything ran here; nothing was uploaded.`,
52
- 0,
53
- ),
54
- );
55
- out.push("");
56
-
57
- // The grade, printed on the brand's chartreuse square.
58
- const badge = color ? `\x1b[1;38;5;16;48;5;191m ${result.grade} \x1b[0m` : `[${result.grade}]`;
59
- const score = typeof result.score === "number" ? `${result.score} out of 100` : "no agent setup files found";
60
- out.push(` ${badge} ${bold(score)}`);
61
- const counts = ["critical", "high", "medium", "low"].filter((s) => result.counts[s]).map((s) => SEV[s].paint(`${result.counts[s]} ${s}`));
62
- out.push(` ${counts.length ? counts.join(dim(", ")) : "No issues found"}`);
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));
63
109
  out.push("");
64
110
 
65
111
  // Every file that directs an agent, where it applies, and what it tells the
66
- // agent. Worked out on this computer; none of it is sent anywhere.
67
- if (result.controlMap.length) {
68
- out.push(bold("What controls your agents"));
112
+ // agent. Worked out on this computer and shown only here and in the page
113
+ // --open saves.
114
+ const map = result.controlMap;
115
+ if (map.length) {
116
+ out.push(`${bold("What controls your agents")} ${dim(plural(map.length, "file"))}`);
69
117
  for (const scope of ["admin", "computer", "project", "loose"]) {
70
- const files = result.controlMap.filter((f) => (f.scope ?? "project") === scope);
118
+ const files = map.filter((f) => (f.scope ?? "project") === scope);
71
119
  if (!files.length) continue;
72
- out.push(` ${SCOPES[scope]}`);
120
+ out.push("", ` ${dim(SCOPES[scope])}`);
73
121
  for (const f of files) {
74
122
  const agents = f.tools.filter((t) => t !== "Any agent started there").join(", ");
75
- out.push(` ${bold(f.path)}${agents ? dim(` ${agents}`) : ""}`);
76
- if (f.summary) out.push(wrap(f.summary, 6));
77
- if (explain) for (const d of f.details ?? []) out.push(dim(bullet(d, 6)));
123
+ const room = width() - 4 - (agents ? agents.length + 2 : 0);
124
+ if (explain) out.push("");
125
+ out.push(` ${bold(fitPath(f.path, Math.max(room, 30)))}${agents ? ` ${dim(oneLine(agents))}` : ""}`);
126
+ if (f.summary) out.push(...wrap(f.summary, 6));
127
+ if (explain) for (const d of f.details ?? []) out.push(...wrap(d, 8, ` ${dim("·")} `));
78
128
  }
79
129
  }
80
- out.push("");
81
130
  }
82
131
 
83
- for (const sev of ["critical", "high", "medium", "low", "info"]) {
84
- const group = result.findings.filter((f) => f.severity === sev);
85
- if (!group.length) continue;
86
- out.push(SEV[sev].paint(`${SEV[sev].label} (${group.length})`));
87
- for (const f of group) {
88
- out.push(` ${SEV[sev].paint(MARK)} ${bold(f.title)}`);
89
- if (f.file) out.push(` ${dim(f.file + (f.line ? `:${f.line}` : ""))}`);
90
- if (sev === "critical" || sev === "high") out.push(wrap(f.why, 4));
91
- out.push(wrap(`Fix: ${f.fix}`, 4));
92
- out.push("");
132
+ // What's installed: agents and editor extensions, with --explain.
133
+ const installed = result.installed ?? { agents: [], editors: [] };
134
+ if (explain && (installed.agents.length || installed.editors.length)) {
135
+ gap();
136
+ out.push(bold("What's installed"));
137
+ if (installed.agents.length) {
138
+ out.push("", ` ${dim("AI agents")}`);
139
+ for (const a of installed.agents) out.push(` ${bold(oneLine(`${a.tool} ${a.version}`))} ${dim(oneLine(`${INSTALLED_BY[a.via] ?? a.via}, ${fitPath(a.path, width() - 30)}`))}`);
140
+ }
141
+ for (const e of installed.editors) {
142
+ out.push("", ` ${dim(oneLine(`${e.editor} extensions, ${e.dir}`))}`);
143
+ const agents = e.agents.map((x) => `${x.name} ${x.version}`.trim());
144
+ const named = agents.length <= 1 ? agents.join("") : `${agents.slice(0, -1).join(", ")} and ${agents.at(-1)}`;
145
+ out.push(...wrap(`${plural(e.count, "extension")}${agents.length ? `, including ${named}` : ""}.`, 4));
146
+ }
147
+ }
148
+
149
+ // What to fix, worst first.
150
+ const findings = result.findings;
151
+ if (findings.length) {
152
+ gap();
153
+ out.push(`${bold("Findings")} ${dim(String(findings.length))}`);
154
+ for (const sev of Object.keys(SEVERITY)) {
155
+ const group = findings.filter((f) => f.severity === sev);
156
+ if (!group.length) continue;
157
+ const paint = color(sev);
158
+ out.push("", ` ${paint(bold(SEVERITY[sev]))} ${dim(String(group.length))}`);
159
+ for (const [n, f] of group.entries()) {
160
+ if (n) out.push("");
161
+ out.push(...wrap(f.title, 6).map((l, i) => `${i === 0 ? ` ${paint(MARK)} ` : " "}${bold(l.slice(6))}`));
162
+ // Where it is, then the rule, which misconfig.ai/rules explains.
163
+ const at = f.file ? fitPath(f.file, width() - 16 - f.id.length) + (f.line ? `:${f.line}` : "") : "";
164
+ out.push(` ${dim(at ? `${at} ${f.id}` : f.id)}`);
165
+ if (sev === "critical" || sev === "high" || sev === "medium") out.push(...wrap(f.why, 6));
166
+ out.push(...wrap(f.fix, 11, ` ${dim("Fix")} `));
167
+ }
93
168
  }
94
169
  }
95
170
 
96
- if (!result.findings.length) out.push(result.controlMap.length ? "No issues found in these files." : "No files that control AI agents were found.", "");
97
- if (!explain && result.controlMap.some((f) => f.details?.length)) out.push(dim("Everything each file says: npx @misconfig/cli --explain"));
98
- out.push(dim("Share this project's report: npx @misconfig/cli --share"));
99
- out.push(dim("Full details as JSON: npx @misconfig/cli --json"));
171
+ gap();
172
+ const stopped = () => wrap(`The check stopped after ${result.stats.entriesScanned.toLocaleString("en-US")} files and folders, so agent files deeper in this folder may have been missed. Run it in a smaller folder to check everything.`, 0);
173
+ if (!map.length && !findings.length) {
174
+ 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
+ if (result.stats.truncated) out.push("", ...stopped());
176
+ process.stdout.write(out.join("\n") + "\n");
177
+ return;
178
+ }
179
+ // The verdict, last, where it's on screen when the check finishes.
180
+ out.push(...verdict(result), "");
181
+ if (result.stats.truncated) out.push(...stopped(), "");
182
+ const next = [];
183
+ if (!explain && map.some((f) => f.details?.length)) next.push(["Everything each file says", `${npx} @misconfig/cli --explain`]);
184
+ if (!open) next.push(["Full report in your browser", `${npx} @misconfig/cli --open`]);
185
+ 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"]);
187
+ next.push(["Full details as JSON", `${npx} @misconfig/cli --json`]);
188
+ const pad = Math.max(...next.map(([label]) => label.length)) + 3;
189
+ for (const [label, command] of next) out.push(`${dim(label.padEnd(pad))}${command}`);
100
190
  process.stdout.write(out.join("\n") + "\n");
101
191
  }
102
192
 
103
- // Everything a share sends, listed before anything is sent.
104
- export function printSharePreview(out, payload, project, { includesUser }) {
105
- const lines = ["", bold("Share this project's report")];
106
- const score = typeof project.score === "number" ? `grade ${project.grade}, ${project.score} out of 100` : "no grade";
193
+ // Which list of known malware the check used.
194
+ function knownLine(known) {
195
+ if (!known) return "";
196
+ const day = new Date(known.asOf).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric", timeZone: "UTC" });
197
+ if (known.from === "misconfig.ai") return ` Known malware as of ${day}.`;
198
+ if (known.from === "offline") return ` Known malware as of ${day}, the list in this release.`;
199
+ return ` Known malware as of ${day}: today's list couldn't be downloaded, so the check used the one in this release.`;
200
+ }
201
+
202
+ // The grade on its square, beside the score, the counts and what was checked.
203
+ // Without color it's plain lines that read the same in a log.
204
+ function verdict(result) {
205
+ const counts = ["critical", "high", "medium", "low"].filter((s) => result.counts[s]);
206
+ const score = `${result.score} out of 100`;
207
+ const s = result.stats;
208
+ const parts = [plural(s.filesChecked, "agent file"), s.mcpServers ? plural(s.mcpServers, "MCP server") : null, s.agentInstalls ? plural(s.agentInstalls, "agent install") : null, s.extensions ? plural(s.extensions, "editor extension") : null].filter(Boolean);
209
+ const checked = `Checked ${parts.length > 1 ? `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}` : parts[0]}.`;
210
+ if (!on) {
211
+ return [`Grade ${result.grade}, ${score}`, counts.length ? counts.map((s) => `${result.counts[s]} ${s}`).join(", ") : "No issues found", checked];
212
+ }
213
+ const tile = (s) => `\x1b[${code("signal", "bg")};${code("ink", "fg")}m${s}\x1b[0m`;
214
+ const tally = counts.length ? counts.map((s) => `${color(s)(MARK)} ${result.counts[s]} ${s}`).join(" ") : "No issues found";
215
+ return [
216
+ ` ${tile(" ")} ${bold(score)}`,
217
+ ` ${tile(` \x1b[1m${result.grade}\x1b[22m `)} ${tally}`,
218
+ ` ${tile(" ")} ${dim(checked)}`,
219
+ ];
220
+ }
221
+
222
+
223
+ // --- Looking up installs ---------------------------------------------------------
224
+
225
+ // Where each package is published, in words, for OSV.dev's ecosystem names.
226
+ const REGISTRIES = { npm: "npm", PyPI: "PyPI", VSCode: "VS Marketplace", "VSCode:https://open-vsx.org": "Open VSX" };
227
+ const registryName = (ecosystem) => (Object.hasOwn(REGISTRIES, ecosystem) ? REGISTRIES[ecosystem] : ecosystem);
228
+
229
+ // Everything --lookup sends, listed before anything is sent.
230
+ export function printLookupPreview(out, queries) {
231
+ const lines = ["", bold("Look up what's installed on OSV.dev")];
232
+ if (!queries.length) {
233
+ 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");
235
+ return;
236
+ }
107
237
  lines.push(
108
- wrap(
109
- includesUser
110
- ? `The link covers this project only (${score}). The settings on this computer aren't included.`
111
- : `The link shows ${score}.`,
238
+ ...wrap(
239
+ `This sends ${plural(queries.length, "package name")} and their versions to OSV.dev, the open source vulnerability database. Nothing else is sent: no paths, file contents, server names or settings. The names come from your setup, so if one is private to your company, answer no.`,
112
240
  2,
113
241
  ),
114
242
  "",
115
- " This is everything that will be sent:",
116
- );
117
- if (!payload.findings.length) lines.push(` ${dim("No findings")}`);
118
- for (const f of payload.findings) {
119
- const where = f.file ? `${f.file}${f.line ? `:${f.line}` : ""}` : "";
120
- const vars = Object.entries(f.vars).map(([k, v]) => `${k}=${v}`).join(", ");
121
- lines.push(` ${f.id}${where ? ` ${where}` : ""}${vars ? dim(` ${vars}`) : ""}`);
122
- }
123
- lines.push(
124
- ` File names: ${payload.controlMap.length ? payload.controlMap.join(", ") : "none"}`,
125
- ` Totals: ${payload.stats.filesChecked} files checked, ${payload.stats.mcpServers} MCP servers`,
126
- "",
127
- wrap(dim("Not sent: file contents, quoted lines, this folder's name and anything outside it."), 2),
128
- "",
129
243
  );
244
+ const shown = queries.slice(0, 40);
245
+ const width = Math.max(...shown.map((q) => registryName(q.ecosystem).length));
246
+ 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
+ if (queries.length > shown.length) lines.push(dim(` and ${queries.length - shown.length} more`));
130
248
  out.write(lines.join("\n") + "\n");
131
249
  }
132
250
 
133
- export function printShareResult(out, data) {
251
+ export function printLookupResult(out, { asked, failed, found }) {
252
+ const parts =
253
+ failed >= asked
254
+ ? ["OSV.dev didn't answer, so nothing was looked up. Try again later."]
255
+ : [
256
+ `Looked up ${plural(asked - failed, "package")} on OSV.dev.`,
257
+ found ? `${plural(found, "finding")} added to the report.` : "Nothing new turned up.",
258
+ failed ? `${plural(failed, "package")} couldn't be looked up; try again later.` : "",
259
+ ];
260
+ out.write(["", ...wrap(parts.filter(Boolean).join(" "), 2), ""].join("\n") + "\n");
261
+ }
262
+
263
+ // --- The report in a browser ---------------------------------------------------
264
+
265
+ // Where --open saved the report.
266
+ export function printOpenResult(out, { file, opening }) {
134
267
  out.write(
135
268
  [
136
269
  "",
137
- bold("Share link created"),
138
- ` Link: ${data.url}`,
139
- ` README badge: [![AI setup](${data.badgeUrl})](${data.url})`,
140
- ` Delete link: ${data.url}#delete=${data.deleteToken}`,
141
- dim(" Save the delete link now. It isn't shown again. The report expires in 30 days."),
270
+ bold("Full report saved on this computer"),
271
+ ` ${file}`,
142
272
  "",
143
- ].join("\n"),
273
+ ...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
+ "",
275
+ ].join("\n") + "\n",
144
276
  );
145
277
  }
146
-
147
- export { listText };