@misconfig/cli 1.3.0 → 1.3.2

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/html.js ADDED
@@ -0,0 +1,201 @@
1
+ // --open: the full report as one HTML file, saved in this computer's temp
2
+ // folder and opened in the browser. Nothing is uploaded.
3
+ //
4
+ // The file has no scripts, and its content security policy allows none, so
5
+ // nothing in it can run, whatever a checked file says. Everything that comes
6
+ // from the files is escaped as text. Styles and fonts are inside the file, so
7
+ // it loads nothing from anywhere.
8
+
9
+ import { readFile, writeFile, mkdtemp } from "node:fs/promises";
10
+ import { tmpdir } from "node:os";
11
+ import path from "node:path";
12
+ import { spawn } from "node:child_process";
13
+ import { SCOPES } from "../engine/explain.js";
14
+ import { INSTALLED_BY } from "../engine/index.js";
15
+ import { findingsHtml, LABEL } from "./findings.js";
16
+
17
+ const ASSETS = new URL("../report/", import.meta.url);
18
+ // Lines of what a file says shown in the report; --explain shows them all.
19
+ const MAX_DETAILS = 300;
20
+
21
+ // Text is escaped, and control codes and marks that reorder text, which a
22
+ // checked file can hold, are shown as the replacement character, as in the
23
+ // terminal.
24
+ const esc = (value) =>
25
+ String(value ?? "")
26
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "\ufffd")
27
+ .replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
28
+ const plural = (n, word) => `${n.toLocaleString("en-US")} ${n === 1 ? word : `${word}s`}`;
29
+ const listText = (items) => (items.length <= 1 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`);
30
+ const fmtDate = (ms) => new Date(ms).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
31
+
32
+ // Writes the report and returns the file's path. The folder is new and only
33
+ // readable by you.
34
+ export async function writeReport(result, { version, scanned, checkedAt = Date.now() }) {
35
+ const dir = await mkdtemp(path.join(tmpdir(), "misconfig-report-"));
36
+ const file = path.join(dir, "report.html");
37
+ await writeFile(file, await reportHtml(result, { version, scanned, checkedAt }), { mode: 0o600 });
38
+ return file;
39
+ }
40
+
41
+ export async function reportHtml(result, { version, scanned, checkedAt }) {
42
+ const [css, sans, mono, mark, printMark] = await Promise.all([
43
+ readFile(new URL("styles.css", ASSETS), "utf8"),
44
+ readFile(new URL("fonts/recursive-sans.woff2", ASSETS)),
45
+ readFile(new URL("fonts/recursive-mono.woff2", ASSETS)),
46
+ readFile(new URL("mark.svg", ASSETS)),
47
+ readFile(new URL("mark-black.svg", ASSETS)),
48
+ ]);
49
+ const styles = css
50
+ .replace('url("/fonts/recursive-sans.woff2")', `url("data:font/woff2;base64,${sans.toString("base64")}")`)
51
+ .replace('url("/fonts/recursive-mono.woff2")', `url("data:font/woff2;base64,${mono.toString("base64")}")`)
52
+ .replace('url("/mark-black.svg")', `url("data:image/svg+xml;base64,${printMark.toString("base64")}")`);
53
+ const title = `${result.grade === "–" ? "No grade" : `Grade ${result.grade}`}: misconfig report`;
54
+ return `<!doctype html>
55
+ <html lang="en">
56
+ <head>
57
+ <meta charset="utf-8">
58
+ <meta name="viewport" content="width=device-width, initial-scale=1">
59
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; font-src data:; img-src data:; base-uri 'none'; form-action 'none'">
60
+ <meta name="referrer" content="no-referrer">
61
+ <meta name="robots" content="noindex">
62
+ <title>${esc(title)}</title>
63
+ <style>${styles}</style>
64
+ </head>
65
+ <body>
66
+ <header class="site-header">
67
+ <div class="wrap header-inner">
68
+ <a class="brand" href="https://misconfig.ai" rel="noopener noreferrer"><img src="data:image/svg+xml;base64,${mark.toString("base64")}" alt="" width="38" height="28">misconfig.ai</a>
69
+ </div>
70
+ </header>
71
+ <main class="wrap report-page local-report">
72
+ ${body(result, { version, scanned, checkedAt })}
73
+ </main>
74
+ <footer class="site-footer">
75
+ <div class="wrap footer-base">
76
+ <span>Made by misconfig ${esc(version)} on ${esc(fmtDate(checkedAt))}. To save it as a PDF, print it from your browser.</span>
77
+ </div>
78
+ </footer>
79
+ </body>
80
+ </html>
81
+ `;
82
+ }
83
+
84
+ function body(r, { version, scanned }) {
85
+ const where = scanned.projectSkipped ? "your home folder" : scanned.project || "a project";
86
+ const checked = [
87
+ plural(r.stats.filesChecked, "agent file"),
88
+ r.stats.mcpServers ? plural(r.stats.mcpServers, "MCP server") : null,
89
+ r.stats.agentInstalls ? plural(r.stats.agentInstalls, "agent install") : null,
90
+ r.stats.extensions ? plural(r.stats.extensions, "editor extension") : null,
91
+ ].filter(Boolean);
92
+ const tilt = typeof r.score === "number" ? Math.round(14 * (1 - r.score / 100)) : 0;
93
+ const known = r.knownMalware ? ` Known malware as of ${new Date(r.knownMalware.asOf).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric", timeZone: "UTC" })}.` : "";
94
+ return `
95
+ <section class="result-head" aria-labelledby="report-headline">
96
+ <div class="grade-tile${r.grade === "–" ? " grade-none" : ""}" role="img" aria-label="${esc(typeof r.score === "number" ? `Grade ${r.grade}, score ${r.score} out of 100` : "No grade")}">
97
+ <span class="square grade-square tilt-${tilt}" aria-hidden="true">${esc(r.grade)}</span>
98
+ </div>
99
+ <div>
100
+ <h1 class="result-headline" id="report-headline">${esc(r.headline)}</h1>
101
+ ${countsList(r.counts)}
102
+ <div class="result-meta">
103
+ ${typeof r.score === "number" ? `<p>Score ${esc(r.score)} out of 100.</p>` : ""}
104
+ <p>Checked ${scanned.projectSkipped || !scanned.project ? esc(where) : `<code>${esc(where)}</code>`}${scanned.user ? " and the agent settings on this computer" : ""}.${esc(known)}</p>
105
+ <p>${esc(listText(checked))}.${r.tools.length ? ` Agents found: ${esc(listText(r.tools))}.` : ""}</p>
106
+ </div>
107
+ </div>
108
+ </section>
109
+
110
+ <section class="report-note" aria-label="About this report">
111
+ <span class="note-mark" aria-hidden="true"></span>
112
+ <div>
113
+ <p class="note-title">Saved on this computer only</p>
114
+ <p class="note-detail">misconfig ${esc(version)} wrote this file in your temp folder. Nothing was uploaded, and nobody else can see it unless you send them the file.</p>
115
+ </div>
116
+ </section>
117
+
118
+ <section class="chapter" aria-labelledby="findings-title">
119
+ <h2 id="findings-title">Findings</h2>
120
+ ${r.findings.length ? findingsHtml(r.findings) : '<p class="empty">No issues found in these agent files.</p>'}
121
+ ${r.findings.length ? `<p class="next-step">After you change something, run the check again to see the new grade: <code>npx @misconfig/cli@latest --open</code>.</p>` : ""}
122
+ </section>
123
+
124
+ <section class="chapter" aria-labelledby="map-title">
125
+ <h2 id="map-title">What controls your agents</h2>
126
+ <p class="chapter-intro">${esc(plural(r.controlMap.length, "file"))} that tell agents what to do, and what each one says.</p>
127
+ ${controlMap(r.controlMap)}
128
+ </section>
129
+ ${installedSection(r.installed ?? { agents: [], editors: [] })}`;
130
+ }
131
+
132
+ function countsList(counts) {
133
+ const items = ["critical", "high", "medium", "low"]
134
+ .filter((s) => counts[s])
135
+ .map((s) => `<li><span class="sq sev-${s}" aria-hidden="true"></span><span><b>${esc(counts[s])}</b> ${LABEL[s].toLowerCase()}</span></li>`);
136
+ return `<ul class="counts">${items.length ? items.join("") : '<li><span class="sq sev-none" aria-hidden="true"></span>No issues found</li>'}</ul>`;
137
+ }
138
+
139
+ function controlMap(map) {
140
+ if (!map.length) return '<p class="empty">No files that steer agents were found.</p>';
141
+ return Object.entries(SCOPES)
142
+ // Files with issues first, so they're not lost among the rest.
143
+ .map(([scope, label]) => [label, map.filter((f) => f.scope === scope).sort((a, b) => Number(b.findings > 0) - Number(a.findings > 0))])
144
+ .filter(([, files]) => files.length)
145
+ .map(([label, files]) => `<section class="map-group"><h3 class="map-scope">${esc(label)}</h3><ul class="map-list">${files.map(mapItem).join("")}</ul></section>`)
146
+ .join("");
147
+ }
148
+
149
+ function mapItem(f) {
150
+ const agents = (f.tools ?? []).filter((t) => t !== "Any agent started there").join(", ");
151
+ const issues = f.findings ? `<span class="map-issues has-issues">${esc(plural(f.findings, "issue"))}</span>` : '<span class="map-issues">No issues</span>';
152
+ const details = Array.isArray(f.details) ? f.details : [];
153
+ const more = details.length > MAX_DETAILS ? `<li class="map-more">And ${esc(plural(details.length - MAX_DETAILS, "more line"))}. Run the command with --explain to see them all.</li>` : "";
154
+ const list = details.length
155
+ ? `<details class="map-details"><summary>Everything it says</summary><ul>${details
156
+ .slice(0, MAX_DETAILS)
157
+ .map((d) => `<li>${esc(d)}</li>`)
158
+ .join("")}${more}</ul></details>`
159
+ : "";
160
+ return `<li class="map-item">
161
+ <div class="map-head"><code>${esc(f.path)}</code>${agents ? `<span class="map-agents">${esc(agents)}</span>` : ""}${issues}</div>
162
+ <p class="map-summary">${esc(f.summary || f.kind)}</p>
163
+ ${list}
164
+ </li>`;
165
+ }
166
+
167
+ // AI agents and editor extensions on this computer.
168
+ function installedSection({ agents, editors }) {
169
+ if (!agents.length && !editors.length) return "";
170
+ const item = (name, label, text, place) =>
171
+ `<li class="map-item"><div class="map-head"><code>${esc(name)}</code>${label ? `<span class="map-agents">${esc(label)}</span>` : ""}</div>${text ? `<p class="map-summary">${esc(text)}</p>` : ""}${place ? `<code class="map-path">${esc(place)}</code>` : ""}</li>`;
172
+ const group = (title, items) => (items.length ? `<section class="map-group"><h3 class="map-scope">${esc(title)}</h3><ul class="map-list">${items.join("")}</ul></section>` : "");
173
+ return `<section class="chapter" aria-labelledby="installed-title">
174
+ <h2 id="installed-title">What's installed</h2>
175
+ <p class="chapter-intro">The AI agents on this computer, by name and version, and how many extensions each editor has, with the AI agent extensions among them.</p>
176
+ ${group("AI agents", agents.map((a) => item(`${a.tool} ${a.version}`, INSTALLED_BY[a.via] ?? a.via, "", a.path)))}
177
+ ${group(
178
+ "Editor extensions",
179
+ editors.map((e) => {
180
+ const named = e.agents.map((x) => `${x.name} ${x.version}`.trim());
181
+ return item(`${e.editor} extensions`, "", `${plural(e.count, "extension")}${named.length ? `, including ${listText(named)}` : ""}.`, e.dir);
182
+ }),
183
+ )}
184
+ </section>`;
185
+ }
186
+
187
+ // Opens a file or address in the default browser. Nothing is shown if it
188
+ // can't, and the command has already printed where the report is.
189
+ export function openInBrowser(target) {
190
+ const [command, args] =
191
+ process.platform === "win32"
192
+ ? ["rundll32", ["url.dll,FileProtocolHandler", target]]
193
+ : process.platform === "darwin"
194
+ ? ["open", [target]]
195
+ : ["xdg-open", [target]];
196
+ try {
197
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
198
+ child.on("error", () => {});
199
+ child.unref();
200
+ } catch {}
201
+ }
package/lib/lookup.js CHANGED
@@ -11,14 +11,20 @@
11
11
  import { compareVersions, AGENT_ADVISORIES } from "../engine/known.js";
12
12
 
13
13
  // Package names as each registry writes them. Anything else, such as a path,
14
- // a GitHub repository or a name with spaces, isn't sent.
14
+ // a GitHub repository or a name with spaces, isn't sent. Extension IDs keep
15
+ // their publisher's capitals, since OSV.dev matches them exactly.
16
+ const EXTENSION_RE = /^[a-z0-9][a-z0-9-]{0,99}\.[a-z0-9][a-z0-9._-]{0,99}$/i;
15
17
  const NAME_RE = {
16
18
  npm: /^(?:@[A-Za-z0-9~][A-Za-z0-9._~-]{0,100}\/)?[A-Za-z0-9~][A-Za-z0-9._~-]{0,213}$/,
17
19
  PyPI: /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,98}[A-Za-z0-9])?$/,
18
- VSCode: /^[a-z0-9][a-z0-9-]{0,99}\.[a-z0-9][a-z0-9._-]{0,99}$/,
20
+ // Microsoft's marketplace, and Open VSX, which VSCodium, Cursor, Windsurf
21
+ // and Kiro install from.
22
+ VSCode: EXTENSION_RE,
23
+ "VSCode:https://open-vsx.org": EXTENSION_RE,
19
24
  };
25
+ const isExtension = (ecosystem) => ecosystem.startsWith("VSCode");
20
26
  const ID_RE = /^[A-Z][A-Z0-9]{1,9}-[A-Za-z0-9._:-]{1,60}$/;
21
- const VERSION_RE = /^v?\d{1,6}(?:\.\d{1,6}){1,3}(?:[-+][0-9A-Za-z.-]{1,40})?$/;
27
+ const VERSION_RE = /^v?\d{1,10}(?:\.\d{1,10}){1,3}(?:[-+][0-9A-Za-z.-]{1,40})?$/;
22
28
  const MAX_QUERIES = 500;
23
29
  const MAX_DETAILS = 150;
24
30
  // Advisories the bundled list already counts for an agent install.
@@ -72,7 +78,7 @@ export async function osvLookup(queries, { base = "https://api.osv.dev", timeout
72
78
  // Extensions go in their own request, so a problem with one kind of
73
79
  // package doesn't lose the answers for the others.
74
80
  const answers = new Map();
75
- for (const group of [queries.filter((q) => q.ecosystem !== "VSCode"), queries.filter((q) => q.ecosystem === "VSCode")]) {
81
+ for (const group of [queries.filter((q) => !isExtension(q.ecosystem)), queries.filter((q) => isExtension(q.ecosystem))]) {
76
82
  for (let i = 0; i < group.length; i += 250) {
77
83
  const batch = group.slice(i, i + 250);
78
84
  try {
@@ -87,7 +93,8 @@ export async function osvLookup(queries, { base = "https://api.osv.dev", timeout
87
93
  }
88
94
 
89
95
  // The details of each vulnerability, for its summary and fixed version.
90
- const wanted = [...new Set([...answers.values()].flat())].slice(0, MAX_DETAILS);
96
+ // Malware listings first: whether one applies can depend on them.
97
+ const wanted = [...new Set([...answers.values()].flat())].sort((a, b) => b.startsWith("MAL-") - a.startsWith("MAL-")).slice(0, MAX_DETAILS);
91
98
  const details = new Map();
92
99
  for (let i = 0; i < wanted.length; i += 6) {
93
100
  await Promise.all(
@@ -104,6 +111,12 @@ export async function osvLookup(queries, { base = "https://api.osv.dev", timeout
104
111
  for (const id of ids) {
105
112
  const record = details.get(id);
106
113
  if (record && record.id !== id) continue;
114
+ // OSV.dev answers a question about Microsoft's marketplace with Open
115
+ // VSX listings too, and the same ID there can be someone else's
116
+ // extension, so a listing has to name the marketplace asked about.
117
+ // Without the listing's details that can't be told, so a hit for an
118
+ // extension from Microsoft's marketplace is left out.
119
+ if (isExtension(q.ecosystem) && (record ? !affectedEntries(record, q).length : q.ecosystem === "VSCode")) continue;
107
120
  const malicious = id.startsWith("MAL-");
108
121
  hits.push({
109
122
  ecosystem: q.ecosystem,
@@ -114,6 +127,10 @@ export async function osvLookup(queries, { base = "https://api.osv.dev", timeout
114
127
  severity: malicious ? "critical" : severityOf(record),
115
128
  summary: typeof record?.summary === "string" ? record.summary.slice(0, 300) : "",
116
129
  fixed: q.version && record ? fixedVersion(record, q) : null,
130
+ // Whether the listing covers every version, or names some: a
131
+ // package whose account was taken over has only those versions
132
+ // listed. Unknown without its details.
133
+ allVersions: record ? everyVersion(record, q) : null,
117
134
  // Without its details, whether there's a fix isn't known.
118
135
  detailed: Boolean(record),
119
136
  });
@@ -152,18 +169,32 @@ function severityOf(record) {
152
169
  return word === "CRITICAL" || word === "HIGH" ? "high" : word === "LOW" ? "low" : "medium";
153
170
  }
154
171
 
155
- // The first version that fixes the range the queried version is in.
156
- // PyPI treats -, _ and . alike, and case doesn't matter; npm names are exact,
157
- // apart from case in old packages.
172
+ // Whether two names are the same package. PyPI treats -, _ and . alike, and
173
+ // case doesn't matter; npm names are exact, apart from case in old packages.
158
174
  function sameName(a, b, ecosystem) {
159
175
  const norm = (n) => (ecosystem === "PyPI" ? n.toLowerCase().replace(/[-_.]+/g, "-") : n.toLowerCase());
160
176
  return norm(a) === norm(b);
161
177
  }
162
178
 
179
+ // The parts of a listing about the package asked about.
180
+ function affectedEntries(record, q) {
181
+ return (Array.isArray(record?.affected) ? record.affected.slice(0, 50) : []).filter((a) => a?.package?.ecosystem === q.ecosystem && sameName(String(a.package.name), q.name, q.ecosystem));
182
+ }
183
+
184
+ // True when a listing covers every version: a range from the first version
185
+ // with no fix.
186
+ function everyVersion(record, q) {
187
+ return affectedEntries(record, q).some((a) =>
188
+ (Array.isArray(a.ranges) ? a.ranges.slice(0, 20) : []).some((r) => {
189
+ const events = Array.isArray(r?.events) ? r.events.slice(0, 100) : [];
190
+ return events.some((e) => e?.introduced === "0") && !events.some((e) => e?.fixed !== undefined || e?.last_affected !== undefined);
191
+ }),
192
+ );
193
+ }
194
+
195
+ // The first version that fixes the range the queried version is in.
163
196
  function fixedVersion(record, q) {
164
- for (const affected of Array.isArray(record?.affected) ? record.affected.slice(0, 50) : []) {
165
- const pkg = affected?.package;
166
- if (pkg?.ecosystem !== q.ecosystem || sameName(String(pkg?.name), q.name, q.ecosystem) === false) continue;
197
+ for (const affected of affectedEntries(record, q)) {
167
198
  for (const range of Array.isArray(affected.ranges) ? affected.ranges.slice(0, 20) : []) {
168
199
  if (range?.type !== "SEMVER" && range?.type !== "ECOSYSTEM") continue;
169
200
  let introduced = null;
package/lib/main.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { createInterface } from "node:readline/promises";
3
- import { analyze, toShareable, applyLookup, rulesetIsNewer, RULESET_VERSION, SHARE_MAX_FINDINGS } 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, printOpenPreview, printOpenResult, printLookupPreview, printLookupResult, oneLine } from "./print.js";
6
- import { seal, openInBrowser, MAX_BYTES } from "./private.js";
6
+ import { printReport, printOpenResult, printLookupPreview, printLookupResult } from "./print.js";
7
+ import { writeReport, openInBrowser } from "./html.js";
7
8
  import { lookupQueries, osvLookup, installsOnly } from "./lookup.js";
8
9
 
9
10
  const HELP = `Usage: npx @misconfig/cli [folder] [options]
@@ -12,7 +13,9 @@ Finds every file that controls your AI coding agents, on this computer and in
12
13
  the folder (the current folder by default), and checks them for risky
13
14
  settings. It also checks the MCP servers, editor extensions, skills and agent
14
15
  versions installed for known malware and missing security fixes. Everything
15
- runs here. Nothing is sent anywhere unless you use --lookup, --open or --share.
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.
16
19
 
17
20
  Options
18
21
  --explain Show everything each file tells your agents: rules,
@@ -23,13 +26,12 @@ Options
23
26
  vulnerabilities, including ones newer than this
24
27
  release. Sends only package names and versions, and
25
28
  asks first.
26
- --open Open the full report in your browser at a private
27
- link. It's encrypted on this computer first, and
28
- misconfig.ai can't read it. The link lasts 7 days.
29
- --share Publish this project's findings and print a link. Shows
30
- what will be sent and asks first. No file contents are
31
- sent, and nothing from outside the project.
32
- --yes Look up, share or open without asking, for scripts and CI
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
33
35
  --json Print the full result as JSON
34
36
  --project-only Skip the agent settings on this computer
35
37
  --fail-on <level> Exit with code 1 if anything at this level or worse is
@@ -43,7 +45,7 @@ Options
43
45
  const LEVELS = ["critical", "high", "medium", "low"];
44
46
 
45
47
  export async function main(argv) {
46
- const opts = { dir: process.cwd(), share: false, open: false, lookup: 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 };
47
49
  for (let i = 0; i < argv.length; i++) {
48
50
  const a = argv[i];
49
51
  if (a === "-h" || a === "--help") {
@@ -54,9 +56,10 @@ export async function main(argv) {
54
56
  console.log(await version());
55
57
  return 0;
56
58
  }
57
- if (a === "--share") opts.share = true;
58
- else if (a === "--open") opts.open = 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;
59
61
  else if (a === "--lookup") opts.lookup = true;
62
+ else if (a === "--offline") opts.offline = true;
60
63
  else if (a === "--yes" || a === "-y") opts.yes = true;
61
64
  else if (a === "--json") opts.json = true;
62
65
  else if (a === "--explain") opts.explain = true;
@@ -68,16 +71,16 @@ export async function main(argv) {
68
71
  else opts.dir = a;
69
72
  }
70
73
 
74
+ const known = opts.offline ? { asOf: `${KNOWN_AS_OF}T00:00:00Z`, from: "offline" } : await todaysList();
71
75
  const input = await discover({ dir: opts.dir, includeUser: !opts.projectOnly });
72
- let result = check(input);
76
+ let result = { ...check(input), knownMalware: known };
73
77
  let lookedUp = false;
74
78
  if (opts.lookup) ({ result, lookedUp } = await lookup(opts, result));
75
79
 
76
80
  if (opts.json) process.stdout.write(JSON.stringify(result, null, 2) + "\n");
77
- else printReport(result, { version: await version(), scanned: input.scanned, explain: opts.explain, open: opts.open, lookedUp });
81
+ else printReport(result, { version: await version(), scanned: input.scanned, explain: opts.explain, open: opts.open, lookedUp, known });
78
82
 
79
- if (opts.share) await share(opts, input, result);
80
- if (opts.open) await openPrivate(opts, input, result);
83
+ if (opts.open) await openReport(opts, input, result);
81
84
 
82
85
  if (opts.failOn) {
83
86
  const worst = LEVELS.slice(0, LEVELS.indexOf(opts.failOn) + 1);
@@ -88,6 +91,40 @@ export async function main(argv) {
88
91
  return 0;
89
92
  }
90
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
+
91
128
  // Runs the checks, then points findings in reduced files back at real lines.
92
129
  function check(input) {
93
130
  const result = analyze(input);
@@ -137,55 +174,9 @@ async function ask(out, question) {
137
174
  }
138
175
  }
139
176
 
140
- async function share(opts, input, result) {
141
- // A share link covers the project only. Settings on this computer stay here.
142
- const out = opts.json ? process.stderr : process.stdout;
143
- const base = serviceBase();
144
- if (input.scanned.projectSkipped) {
145
- 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.");
146
- }
147
- const project = input.scanned.user ? check(await discover({ dir: opts.dir, includeUser: false })) : result;
148
- const payload = toShareable(project);
149
- // A link that left out a finding would look better than this check. That
150
- // happens when a finding is in a file a share link can't name, such as a
151
- // file a setting names as instructions, or when there are more findings
152
- // than a shared report holds.
153
- if (payload.findings.length < project.findings.length) {
154
- throw new Error("Some findings here are in files a share link can't name, so a link would look better than this check. Nothing was sent. Use --open for a private report that includes them.");
155
- }
156
- if (payload.findings.length > SHARE_MAX_FINDINGS) {
157
- throw new Error(`This check found ${payload.findings.length} findings, and a share link holds at most ${SHARE_MAX_FINDINGS}, so a link would leave some out. Nothing was sent. Use --open for a private report instead.`);
158
- }
159
- printSharePreview(out, payload, project, { includesUser: input.scanned.user });
160
- if (!(await confirmed(opts, out, "Publish this report? [y/N] ", "Nothing was sent. Add --yes to share without a prompt, for example in CI."))) return;
161
-
162
- const agent = `misconfig-cli/${await version()}`;
163
- // A site on an older set of checks leaves out findings it doesn't know, and
164
- // its link would look better than this check did.
165
- const health = await send(`${base}/api/health`, { headers: { "user-agent": agent } });
166
- const site = health.ok ? await health.json().catch(() => null) : null;
167
- if (rulesetIsNewer(RULESET_VERSION, site?.rules)) {
168
- throw new Error("misconfig.ai still runs an older set of checks than this command, so a link made now would leave findings out. Nothing was sent. Try again later.");
169
- }
170
- const res = await send(`${base}/api/share`, {
171
- method: "POST",
172
- headers: { "content-type": "application/json", "user-agent": agent },
173
- body: JSON.stringify(payload),
174
- });
175
- const data = await res.json().catch(() => ({}));
176
- if (!res.ok) throw new Error(serverError(data) ?? `Sharing didn't work (error ${res.status}). Your report wasn't published.`);
177
- // The links are built here from the ID, so a reply can only ever add an ID
178
- // and a token in the expected format to what's printed.
179
- if (!/^[A-Za-z0-9]{10}$/.test(data.id ?? "") || !/^[A-Za-z0-9]{32}$/.test(data.deleteToken ?? "")) throw new Error(UNEXPECTED);
180
- printShareResult(out, { url: `${base}/r/${data.id}`, deleteToken: data.deleteToken });
181
- }
182
-
183
- const UNEXPECTED = "misconfig.ai sent back something unexpected. Try again in a minute.";
184
-
185
177
  // Where requests go: misconfig.ai and OSV.dev, or for testing the addresses
186
178
  // MISCONFIG_URL and MISCONFIG_OSV_URL name. Only https addresses, or http on
187
- // this computer, so a link the command prints or opens can't point anywhere
188
- // else.
179
+ // this computer.
189
180
  function serviceBase(name = "MISCONFIG_URL", fallback = "https://misconfig.ai") {
190
181
  const raw = process.env[name] || fallback;
191
182
  let url;
@@ -199,70 +190,18 @@ function serviceBase(name = "MISCONFIG_URL", fallback = "https://misconfig.ai")
199
190
  return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
200
191
  }
201
192
 
202
- // An error message from the server, on one line and cut to a sentence or
203
- // two, or null when there isn't one.
204
- function serverError(data) {
205
- return typeof data?.error === "string" && data.error.trim() ? oneLine(data.error).slice(0, 300) : null;
206
- }
207
-
208
- // The whole report, encrypted here, stored at misconfig.ai for a week and
209
- // opened at a link whose key the server never sees.
210
- async function openPrivate(opts, input, result) {
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) {
211
196
  const out = opts.json ? process.stderr : process.stdout;
212
- const base = serviceBase();
213
- printOpenPreview(out, { includesUser: input.scanned.user });
214
- if (!(await confirmed(opts, out, "\nUpload the encrypted report? [y/N] ", "Nothing was sent. Add --yes to upload the encrypted report without a prompt."))) return;
215
- // The list of packages is only for --lookup; the report page doesn't show it.
197
+ // The list of packages is only for --lookup; the report doesn't show it.
216
198
  const report = { ...result };
217
199
  delete report.packages;
218
- const { body, key } = await seal({ v: 1, createdAt: Date.now(), version: await version(), scanned: input.scanned, result: report });
219
- if (!body || body.length > MAX_BYTES) throw new Error("This report is too large to open in a browser. Nothing was sent. Use --json to save it instead.");
220
-
221
- const res = await send(`${base}/api/private`, {
222
- method: "POST",
223
- headers: { "content-type": "application/octet-stream", "user-agent": `misconfig-cli/${await version()}` },
224
- body,
225
- });
226
- // A site from before private reports existed.
227
- if (res.status === 404) throw new Error("misconfig.ai can't open private reports yet. Nothing was stored. Try again later.");
228
- const data = await res.json().catch(() => ({}));
229
- if (!res.ok) throw new Error(serverError(data) ?? `The report couldn't be uploaded (error ${res.status}). Nothing was published.`);
230
- if (!/^[A-Za-z0-9]{16}$/.test(data.id ?? "") || !/^[A-Za-z0-9]{32}$/.test(data.deleteToken ?? "")) throw new Error(UNEXPECTED);
231
- const link = `${base}/p/${data.id}#k=${key}`;
200
+ const file = await writeReport(report, { version: await version(), scanned: input.scanned });
232
201
  // A browser opens only for someone at a terminal, never in CI or a script.
233
202
  const opening = Boolean(process.stdout.isTTY && process.stdin.isTTY);
234
- const expiresAt = Number.isFinite(data.expiresAt) ? data.expiresAt : null;
235
- printOpenResult(out, { link, deleteLink: `${link}&delete=${data.deleteToken}`, expiresAt, opening });
236
- if (opening) openInBrowser(link);
237
- }
238
-
239
- // A request to misconfig.ai with a time limit, and a plain message when the
240
- // network fails rather than "fetch failed".
241
- async function send(url, init) {
242
- try {
243
- return await fetch(url, { ...init, signal: AbortSignal.timeout(30_000) });
244
- } catch (err) {
245
- const code = String(err?.cause?.code ?? err?.name ?? "");
246
- // The only thing that aborts a request here is the time limit, and some
247
- // Node.js versions report it as an abort.
248
- const late = /Timeout|Abort|UND_ERR_(?:CONNECT|HEADERS|BODY)_TIMEOUT/.test(code);
249
- const reason = late
250
- ? "it didn't answer in time"
251
- : /ENOTFOUND|EAI_AGAIN/.test(code)
252
- ? "its address couldn't be found"
253
- : /ECONNREFUSED|ECONNRESET/.test(code)
254
- ? "the connection was refused"
255
- : /CERT|SSL|TLS|SELF_SIGNED/i.test(code)
256
- ? "its certificate couldn't be checked"
257
- : "the network request failed";
258
- const sent = late ? "It may or may not have arrived." : "Nothing was sent.";
259
- const hint = /certificate/.test(reason)
260
- ? " If your network inspects HTTPS, set NODE_EXTRA_CA_CERTS to its certificate file."
261
- : /refused/.test(reason)
262
- ? ""
263
- : " Behind a proxy, set NODE_USE_ENV_PROXY=1 (Node.js 22.21 or newer).";
264
- throw new Error(`Couldn't reach ${new URL(url).host}: ${reason}. ${sent}${hint}`);
265
- }
203
+ printOpenResult(out, { file, opening });
204
+ if (opening) openInBrowser(file);
266
205
  }
267
206
 
268
207
  let cachedVersion = null;