@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/findings.js CHANGED
@@ -25,17 +25,28 @@ const esc = (value) =>
25
25
  const RULE_ID = /^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+){0,6}$/;
26
26
  const OPEN = new Set(["critical", "high"]);
27
27
 
28
- function findingHtml(f, id = "") {
28
+ function findingHtml(f, id = "", demo = false) {
29
29
  const sev = Object.hasOwn(LABEL, f.severity) ? f.severity : "info";
30
30
  const where = f.file ? f.file + (f.line ? `:${f.line}` : "") : "";
31
31
  const evidence = f.evidence
32
32
  ? `<pre class="evidence"><span class="evidence-where">${esc(f.file ? `${f.file}${f.line ? `, line ${f.line}` : ""}` : "Evidence")}</span>${esc(describeMasks(f.evidence))}</pre>`
33
33
  : "";
34
- const rule = typeof f.id === "string" && RULE_ID.test(f.id) ? `<a class="f-rule" href="https://misconfig.ai/rules#${f.id}" target="_blank" rel="noopener noreferrer">${f.id}</a>` : "";
34
+ // misconfig.ai/rules explains the built-in rules. One of your own links to
35
+ // its reference, or to nothing without one.
36
+ const link = !f.custom ? `https://misconfig.ai/rules#${f.id}` : typeof f.custom.reference === "string" && /^https:\/\//.test(f.custom.reference) ? f.custom.reference : "";
37
+ const rule = typeof f.id !== "string" || !RULE_ID.test(f.id) ? "" : link ? `<a class="f-rule" href="${esc(link)}" target="_blank" rel="noopener noreferrer">${f.id}</a>` : `<span class="f-rule">${f.id}</span>`;
35
38
  const meta = [f.tool ? `<span>Affects ${esc(f.tool)}</span>` : "", rule].filter(Boolean).join("");
39
+ let review = "";
40
+ if (f.review) {
41
+ const accepted = f.review.acceptedAt;
42
+ const decision = accepted ? esc(new Date(accepted).toISOString().slice(0, 10)) + " by " + esc(f.review.acceptedBy ?? "an unknown account")
43
+ : demo ? "" : `<code>--approve ${esc(f.review.id)}</code>`;
44
+ review = `<p><b>${accepted ? "Risk accepted" : "Awaiting risk review"}</b> ${decision}</p>`;
45
+ }
36
46
  return `<details class="finding sev-${sev}"${id ? ` id="${esc(id)}"` : ""}${OPEN.has(sev) ? " open" : ""}>
37
- <summary><span class="sq" aria-hidden="true"></span><span class="f-title">${esc(f.title)}</span>${where ? `<span class="f-where">${esc(where)}</span>` : ""}</summary>
47
+ <summary><span class="sq" aria-hidden="true"></span><span class="f-title">${esc(f.title)}${f.review?.acceptedAt ? " · Risk accepted" : ""}</span>${where ? `<span class="f-where">${esc(where)}</span>` : ""}</summary>
38
48
  <div class="f-body">
49
+ ${review}
39
50
  <p><b>Why it matters.</b> ${esc(f.why)}</p>
40
51
  <p><b>Fix.</b> ${esc(f.fix)}</p>
41
52
  ${evidence}
@@ -83,7 +94,7 @@ function fixFirstHtml(findings, anchorOf) {
83
94
  // What to fix first, then the findings in groups, worst first, after the
84
95
  // legend. In each group, findings in the same file sit together, so a file
85
96
  // can be fixed in one pass.
86
- export function findingsHtml(findings) {
97
+ export function findingsHtml(findings, demo = false) {
87
98
  const groups = SEVERITIES.map((sev) => [
88
99
  sev,
89
100
  findings
@@ -101,7 +112,7 @@ export function findingsHtml(findings) {
101
112
  .map(
102
113
  ([sev, group]) => `<section class="group">
103
114
  <h3 class="group-title"><span class="sq sev-${sev}" aria-hidden="true"></span>${LABEL[sev]}<span class="group-count">${group.length}</span></h3>
104
- ${group.map((f) => findingHtml(f, anchorOf.get(f))).join("")}
115
+ ${group.map((f) => findingHtml(f, anchorOf.get(f), demo)).join("")}
105
116
  </section>`,
106
117
  )
107
118
  .join("")
package/lib/formats.js ADDED
@@ -0,0 +1,158 @@
1
+ // A finished check in the two formats other programs read: JSON Lines, one
2
+ // finding on each line, and SARIF 2.1.0, which GitHub code scanning and other
3
+ // viewers load. Nothing here reads a file or the network, so the same code
4
+ // can run wherever the engine does.
5
+
6
+ import { LEVELS, RULES } from "../engine/catalog.js";
7
+
8
+ const RULES_URL = "https://misconfig.ai/rules";
9
+
10
+ // JSON that's safe to print and to split into lines. A checked file can hold
11
+ // marks that reorder text on screen, and characters some programs treat as
12
+ // line breaks. A name in one can also spell a command that a CI system reads
13
+ // from its log, such as ##[error] or ##vso[task.setvariable]. JSON.stringify
14
+ // leaves all of these as they are, so they're written as \u escapes, which
15
+ // every JSON parser reads back unchanged.
16
+ const UNSAFE = /[\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
17
+ export const stringify = (value, space) =>
18
+ JSON.stringify(value, null, space)
19
+ .replace(UNSAFE, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`)
20
+ .replace(/##(?=[a-z]*\[)/gi, "#\\u0023");
21
+
22
+ // --- JSON Lines ----------------------------------------------------------------
23
+
24
+ // One finding as a record. The keys are a contract: a 1.x release can add
25
+ // keys, and none is renamed or removed. Every key is always there, null when
26
+ // it doesn't apply. Each record names the check that made it, so lines from
27
+ // different runs and computers can share one file.
28
+ export function findingRecord(f, { version, ruleset, checkedAt }) {
29
+ return {
30
+ type: "finding",
31
+ rule: f.id,
32
+ severity: f.severity,
33
+ category: f.category,
34
+ agent: f.tool ?? null,
35
+ title: f.title,
36
+ why: f.why,
37
+ fix: f.fix,
38
+ file: f.file ?? null,
39
+ line: f.line ?? null,
40
+ evidence: f.evidence ?? null,
41
+ // For one of your own rules, its reference, or null without one.
42
+ ruleUrl: f.custom ? f.custom.reference : `${RULES_URL}#${f.id}`,
43
+ checkedAt: new Date(checkedAt).toISOString(),
44
+ ruleset,
45
+ cli: version,
46
+ };
47
+ }
48
+
49
+ // The findings, worst first, one JSON object on each line.
50
+ export function jsonLines(result, { version }) {
51
+ const run = { version, ruleset: result.version, checkedAt: result.checkedAt };
52
+ return result.findings.map((f) => `${stringify(findingRecord(f, run))}\n`).join("");
53
+ }
54
+
55
+ // --- SARIF -----------------------------------------------------------------------
56
+
57
+ // Each level as SARIF and GitHub read it. SARIF has three levels. GitHub
58
+ // also reads a security severity from 0.1 to 10 and shows it as critical
59
+ // (over 9.0), high (7.0 to 8.9), medium (4.0 to 6.9) or low, so each level
60
+ // gets a number inside its band. Info findings are notes with no number.
61
+ const SARIF_LEVEL = { critical: "error", high: "error", medium: "warning", low: "note", info: "note" };
62
+ const SECURITY_SEVERITY = { critical: "9.5", high: "8.0", medium: "5.5", low: "2.5" };
63
+
64
+ // What each base in a file's address stands for. Neither is spelled out, so
65
+ // an address doesn't carry this computer's folder names.
66
+ const BASES = {
67
+ "%SRCROOT%": "The folder that was checked.",
68
+ HOME: "The home folder of the account that ran the check.",
69
+ };
70
+
71
+ // A rule as SARIF lists it. Its name says what it finds without one
72
+ // finding's values, and misconfig.ai/rules has the rest. One of your own
73
+ // rules isn't in the catalog, so its finding describes it, and its reference
74
+ // is where it's explained.
75
+ function ruleDescriptor(f) {
76
+ const rule = f.custom ? { name: f.custom.name, severity: f.severity, category: f.category } : RULES[f.id];
77
+ const name = rule.name ?? rule.title;
78
+ const url = f.custom ? f.custom.reference : `${RULES_URL}#${f.id}`;
79
+ const help = `What ${f.id} looks for, why it matters and how to fix it`;
80
+ return {
81
+ id: f.id,
82
+ shortDescription: { text: name },
83
+ fullDescription: { text: `${name}. ${LEVELS[rule.severity]}` },
84
+ ...(url ? { help: { text: `${help}: ${url}`, ...(f.custom ? {} : { markdown: `[${help}](${url})` }) }, helpUri: url } : {}),
85
+ defaultConfiguration: { level: SARIF_LEVEL[rule.severity] },
86
+ properties: {
87
+ tags: ["security", rule.category],
88
+ ...(SECURITY_SEVERITY[rule.severity] ? { "security-severity": SECURITY_SEVERITY[rule.severity] } : {}),
89
+ },
90
+ };
91
+ }
92
+
93
+ // A file's address. A file in the checked folder is relative to it, which is
94
+ // how GitHub matches it to the repository. A file under the home folder is
95
+ // relative to HOME, so its address doesn't hold the account's name. Anything
96
+ // else, such as an administrator's settings, is a file: address.
97
+ function artifactLocation(file) {
98
+ // A name can hold half of a character pair, which can't be encoded.
99
+ const whole = (part) => part.replace(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g, "\ufffd");
100
+ const encode = (p) => p.split("/").map((part) => encodeURIComponent(whole(part))).join("/");
101
+ if (file.startsWith("~/")) return { uri: encode(file.slice(2)), uriBaseId: "HOME" };
102
+ if (/^[A-Za-z]:\//.test(file)) return { uri: `file:///${file.slice(0, 2)}${encode(file.slice(2))}` };
103
+ if (file.startsWith("//")) return { uri: `file:${encode(file)}` };
104
+ if (file.startsWith("/")) return { uri: `file://${encode(file)}` };
105
+ return { uri: encode(file), uriBaseId: "%SRCROOT%" };
106
+ }
107
+
108
+ // A finding's own words: its title as a sentence, why it matters, and the
109
+ // fix. SARIF reads [text](address) in a message as a link, and names from a
110
+ // checked file are in these sentences, so the two marks are kept apart and a
111
+ // file can't put a link of its own in an alert.
112
+ function message(f) {
113
+ const title = /[.!?…]$/.test(f.title) ? f.title : `${f.title}.`;
114
+ return [title, f.why, `Fix: ${f.fix}`].join("\n").replace(/\]\(/g, "] (");
115
+ }
116
+
117
+ // GitHub refuses a file with more results than this, so a project crowded
118
+ // with findings can't keep the rest out of code scanning. The worst come
119
+ // first.
120
+ const MAX_RESULTS = 25000;
121
+
122
+ // The whole check as one SARIF run. Only the rules with findings are listed.
123
+ // A finding about a whole file points at its first line, which is where
124
+ // GitHub shows it. GitHub shows no finding that names no file.
125
+ export function sarif(result, { version }) {
126
+ const findings = result.findings.slice(0, MAX_RESULTS);
127
+ const ids = [...new Set(findings.map((f) => f.id))];
128
+ const results = findings.map((f) => ({
129
+ ruleId: f.id,
130
+ ruleIndex: ids.indexOf(f.id),
131
+ level: SARIF_LEVEL[f.severity],
132
+ message: { text: message(f) },
133
+ ...(f.file ? { locations: [{ physicalLocation: { artifactLocation: artifactLocation(f.file), region: { startLine: f.line ?? 1 } } }] } : {}),
134
+ properties: { severity: f.severity, ...(f.tool ? { agent: f.tool } : {}) },
135
+ }));
136
+ const bases = [...new Set(results.map((r) => r.locations?.[0].physicalLocation.artifactLocation.uriBaseId).filter(Boolean))];
137
+ // A check that stopped early is marked as unfinished, so nothing that
138
+ // reads the file takes a finding it didn't reach for one that was fixed.
139
+ const stopped = result.stats.truncated;
140
+ const count = (n) => n.toLocaleString("en-US");
141
+ const notes = [];
142
+ if (stopped) notes.push({ level: "error", message: { text: `The check stopped after ${count(result.stats.entriesScanned)} files and folders, so agent files deeper in the folder may have been missed.` } });
143
+ const left = result.findings.length - MAX_RESULTS;
144
+ if (left > 0) notes.push({ level: "warning", message: { text: `This file has the ${count(MAX_RESULTS)} worst findings. ${count(left)} more ${left === 1 ? "was" : "were"} left out.` } });
145
+ return {
146
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
147
+ version: "2.1.0",
148
+ runs: [
149
+ {
150
+ tool: { driver: { name: "misconfig", semanticVersion: version, informationUri: "https://misconfig.ai", rules: ids.map((id) => ruleDescriptor(findings.find((f) => f.id === id))) } },
151
+ invocations: [{ executionSuccessful: !stopped, ...(notes.length ? { toolExecutionNotifications: notes } : {}) }],
152
+ ...(bases.length ? { originalUriBaseIds: Object.fromEntries(bases.map((b) => [b, { description: { text: BASES[b] } }])) } : {}),
153
+ results,
154
+ properties: { ruleset: result.version },
155
+ },
156
+ ],
157
+ };
158
+ }
package/lib/html.js CHANGED
@@ -13,6 +13,8 @@ import { spawn } from "node:child_process";
13
13
  import { SCOPES } from "../engine/explain.js";
14
14
  import { INSTALLED_BY } from "../engine/index.js";
15
15
  import { findingsHtml, LABEL } from "./findings.js";
16
+ import { changeLabel } from "./computer-review.js";
17
+ import { changeValue, earlierBuildNote, editorText, historyDescription } from "./review-history.js";
16
18
 
17
19
  const ASSETS = new URL("../report/", import.meta.url);
18
20
  // Lines of what a file says shown in the report; --explain shows them all.
@@ -82,7 +84,7 @@ ${body(result, { version, scanned, checkedAt })}
82
84
  }
83
85
 
84
86
  function body(r, { version, scanned }) {
85
- const where = scanned.projectSkipped ? "your home folder" : scanned.project || "a project";
87
+ const where = scanned.demo ? "the sample computer" : scanned.projectSkipped ? "your home folder" : scanned.project || "a project";
86
88
  const checked = [
87
89
  plural(r.stats.filesChecked, "agent file"),
88
90
  r.stats.mcpServers ? plural(r.stats.mcpServers, "MCP server") : null,
@@ -91,6 +93,9 @@ function body(r, { version, scanned }) {
91
93
  ].filter(Boolean);
92
94
  const tilt = typeof r.score === "number" ? Math.round(14 * (1 - r.score / 100)) : 0;
93
95
  const known = r.knownMalware ? ` Known malware as of ${new Date(r.knownMalware.asOf).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric", timeZone: "UTC" })}.` : "";
96
+ // The score counts findings from rules given with --rules, so the page says they were there.
97
+ const ownRules = Array.isArray(r.customRules) ? r.customRules.length : 0;
98
+ const own = ownRules ? ` ${plural(ownRules, "rule")} of your own ${ownRules === 1 ? "was" : "were"} checked too.` : "";
94
99
  return `
95
100
  <section class="result-head" aria-labelledby="report-headline">
96
101
  <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")}">
@@ -101,7 +106,7 @@ function body(r, { version, scanned }) {
101
106
  ${countsList(r.counts)}
102
107
  <div class="result-meta">
103
108
  ${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>
109
+ <p>Checked ${scanned.projectSkipped || !scanned.project ? esc(where) : `<code>${esc(where)}</code>`}${scanned.user && !scanned.demo ? " and the agent settings on this computer" : ""}.${esc(known)}${esc(own)}</p>
105
110
  <p>${esc(listText(checked))}.${r.tools.length ? ` Agents found: ${esc(listText(r.tools))}.` : ""}</p>
106
111
  </div>
107
112
  </div>
@@ -115,10 +120,11 @@ function body(r, { version, scanned }) {
115
120
  </div>
116
121
  </section>
117
122
 
123
+ ${computerReviewHtml(r.computerReview, r.computerReviewError, scanned.demo)}
118
124
  <section class="chapter" aria-labelledby="findings-title">
119
125
  <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>` : ""}
126
+ ${r.findings.length ? findingsHtml(r.findings, scanned.demo) : '<p class="empty">No issues found in these agent files.</p>'}
127
+ ${r.findings.length && !scanned.demo ? `<p class="next-step">After you change a setting, run this version again with <code>--open</code> to see the updated report.</p>` : ""}
122
128
  </section>
123
129
 
124
130
  <section class="chapter" aria-labelledby="map-title">
@@ -129,6 +135,41 @@ function body(r, { version, scanned }) {
129
135
  ${installedSection(r.installed ?? { agents: [], editors: [] })}`;
130
136
  }
131
137
 
138
+ function computerReviewHtml(review, error, demo) {
139
+ if (!review && !error) return "";
140
+ const heading = '<h2 id="computer-review-title">Computer review</h2>';
141
+ const section = (content) => `<section class="chapter" aria-labelledby="computer-review-title">${heading}${content}</section>`;
142
+ if (error) return section(`<p class="chapter-intro">${esc(error)}</p>`);
143
+ const first = review.previousScanAt === null;
144
+ const shown = new Set(review.changes.map((r) => r.id));
145
+ const outstanding = review.pending.filter((r) => !shown.has(r.id));
146
+ const intro = first ? "First scan on this computer." : review.changes.length ? plural(review.changes.length, "change") + " since your last scan." :
147
+ review.unverified.length ? "No changes in the settings we could verify." : "No changes since your last scan.";
148
+ const rows = (list, existing) => `<ul class="computer-changes">${list.map((row) => `<li>
149
+ <div><strong>${esc(changeLabel(row, existing))}</strong><p class="computer-value"><code>${esc(changeValue(row))}</code></p><p class="computer-file">${esc(row.file)}</p>${row.observationId ? `<p class="computer-file">${esc(editorText(row.editor, row.editorScope))} · ${esc(row.observationId)}</p>` : ""}</div>
150
+ <div class="computer-decision">${row.id ? `Awaiting approval<code>${esc(row.id)}</code>` : "Approved"}</div>
151
+ </li>`).join("")}</ul>`;
152
+ const notes = review.unverified.map((f) => "Could not fully verify " + f + ". Any earlier decision is kept.");
153
+ const accepted = review.risks.filter((r) => r.acceptedAt).length;
154
+ if (accepted) notes.push(plural(accepted, "accepted risk") + (accepted === 1 ? " is" : " are") + " still present. See Findings.");
155
+ if (review.confirmation) notes.push(review.confirmation);
156
+ const past = review.earlierRisks.map((r) => `<li><code>${esc(r.rule)}</code> · ${esc(r.file)} · accepted ${esc(fmtDate(r.acceptedAt))} by ${esc(r.acceptedBy ?? "an unknown account")} · ${esc(r.status)}</li>`).join("");
157
+ const history = review.history ?? { events: [], incomplete: true };
158
+ const events = history.events.slice().reverse().map((e) => {
159
+ const iso = new Date(e.at).toISOString();
160
+ return `<li><time datetime="${iso}">${iso.replace("T", " ").replace("Z", " UTC")}</time><span>${esc(historyDescription(e))}</span></li>`;
161
+ }).join("");
162
+ return section(`<p class="chapter-intro">${esc(intro)}</p>
163
+ ${review.changes.length ? rows(review.changes, false) : ""}
164
+ ${outstanding.length ? `<h3 class="map-scope">Awaiting your approval (${outstanding.length})</h3>${rows(outstanding, first)}` : ""}
165
+ ${notes.map((n) => `<p class="computer-note">${esc(n)}</p>`).join("")}
166
+ ${past ? `<h3 class="map-scope">Earlier risk decisions</h3><ul>${past}</ul>` : ""}
167
+ ${!demo && (review.pending.length || review.risks.some((r) => !r.acceptedAt)) ? '<p class="next-step">Run again with <code>--review</code> to decide one at a time, or <code>--approve ID</code> to choose one.</p>' : ""}
168
+ <details class="computer-history"${demo ? " open" : ""}><summary>Computer history (${history.events.length})</summary>
169
+ ${history.incomplete ? `<p>${esc(earlierBuildNote)}</p>` : ""}
170
+ ${events ? `<ol aria-label="Newest events first">${events}</ol>` : "<p>No events recorded yet.</p>"}</details>`);
171
+ }
172
+
132
173
  function countsList(counts) {
133
174
  const items = ["critical", "high", "medium", "low"]
134
175
  .filter((s) => counts[s])