@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/CHANGELOG.md +187 -0
- package/LICENSE +1 -0
- package/README.md +110 -30
- package/bin/misconfig.js +29 -1
- package/engine/catalog.js +504 -99
- package/engine/decode.js +41 -0
- package/engine/explain.js +792 -79
- package/engine/flags.js +121 -0
- package/engine/glob.js +178 -0
- package/engine/index.js +2108 -376
- package/engine/known.js +587 -0
- package/engine/locations.js +96 -49
- package/engine/mask.js +74 -21
- package/engine/named.js +91 -0
- package/engine/parse.js +442 -42
- package/engine/paths.js +83 -20
- package/lib/discover.js +675 -97
- package/lib/findings.js +109 -0
- package/lib/html.js +201 -0
- package/lib/lookup.js +209 -0
- package/lib/main.js +135 -39
- package/lib/print.js +223 -93
- package/package.json +22 -20
- package/report/fonts/OFL.txt +93 -0
- package/report/fonts/recursive-mono.woff2 +0 -0
- package/report/fonts/recursive-sans.woff2 +0 -0
- package/report/mark-black.svg +1 -0
- package/report/mark.svg +1 -0
- package/report/styles.css +2656 -0
package/lib/findings.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// How findings are drawn in the report --open writes. It makes HTML text
|
|
2
|
+
// only, with no page or DOM.
|
|
3
|
+
//
|
|
4
|
+
// A short list of what to fix first comes before the findings, with what each
|
|
5
|
+
// rule takes off the score. Critical and high findings open with why they
|
|
6
|
+
// matter and the fix showing; the rest open on a click. Each names its rule,
|
|
7
|
+
// which misconfig.ai/rules explains, and the levels are explained beside the
|
|
8
|
+
// list. Everything that comes from the files is escaped as text.
|
|
9
|
+
|
|
10
|
+
import { LEVELS } from "../engine/catalog.js";
|
|
11
|
+
import { SCORING, pointsOff } from "../engine/index.js";
|
|
12
|
+
import { describeMasks } from "../engine/mask.js";
|
|
13
|
+
|
|
14
|
+
export const LABEL = { critical: "Critical", high: "High", medium: "Medium", low: "Low", info: "Info" };
|
|
15
|
+
const SEVERITIES = Object.keys(LABEL);
|
|
16
|
+
|
|
17
|
+
// Text is escaped, and control codes and marks that reorder text, which a
|
|
18
|
+
// checked file can hold, are shown as the replacement character, as in the
|
|
19
|
+
// terminal.
|
|
20
|
+
const esc = (value) =>
|
|
21
|
+
String(value ?? "")
|
|
22
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "\ufffd")
|
|
23
|
+
.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
24
|
+
// Rule IDs are capitals, digits and hyphens, such as CC-BYPASS.
|
|
25
|
+
const RULE_ID = /^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+){0,6}$/;
|
|
26
|
+
const OPEN = new Set(["critical", "high"]);
|
|
27
|
+
|
|
28
|
+
function findingHtml(f, id = "") {
|
|
29
|
+
const sev = Object.hasOwn(LABEL, f.severity) ? f.severity : "info";
|
|
30
|
+
const where = f.file ? f.file + (f.line ? `:${f.line}` : "") : "";
|
|
31
|
+
const evidence = f.evidence
|
|
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
|
+
: "";
|
|
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>` : "";
|
|
35
|
+
const meta = [f.tool ? `<span>Affects ${esc(f.tool)}</span>` : "", rule].filter(Boolean).join("");
|
|
36
|
+
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>
|
|
38
|
+
<div class="f-body">
|
|
39
|
+
<p><b>Why it matters.</b> ${esc(f.why)}</p>
|
|
40
|
+
<p><b>Fix.</b> ${esc(f.fix)}</p>
|
|
41
|
+
${evidence}
|
|
42
|
+
${meta ? `<p class="f-meta">${meta}</p>` : ""}
|
|
43
|
+
</div>
|
|
44
|
+
</details>`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// What the levels mean and how the score is worked out, folded away under
|
|
48
|
+
// one line.
|
|
49
|
+
function legendHtml() {
|
|
50
|
+
return `<details class="legend">
|
|
51
|
+
<summary>What the levels mean</summary>
|
|
52
|
+
<dl>${SEVERITIES.map((s) => `<div><dt><span class="sq sev-${s}" aria-hidden="true"></span>${LABEL[s]}</dt><dd>${esc(LEVELS[s])}</dd></div>`).join("")}</dl>
|
|
53
|
+
<p>${esc(SCORING)}</p>
|
|
54
|
+
<p><a href="https://misconfig.ai/rules" target="_blank" rel="noopener noreferrer">Every rule, what it checks and how to fix it</a></p>
|
|
55
|
+
</details>`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const points = (n) => `${n} ${n === 1 ? "point" : "points"}`;
|
|
59
|
+
const FIX_FIRST_MAX = 12;
|
|
60
|
+
|
|
61
|
+
// The rules to fix, most points first, each linked to its first finding.
|
|
62
|
+
function fixFirstHtml(findings, anchorOf) {
|
|
63
|
+
const { rules, total } = pointsOff(findings);
|
|
64
|
+
if (!rules.length) return "";
|
|
65
|
+
const off = Math.round(total);
|
|
66
|
+
const score = Math.max(0, 100 - off);
|
|
67
|
+
const shown = rules.slice(0, FIX_FIRST_MAX);
|
|
68
|
+
const rest = rules.length - shown.length;
|
|
69
|
+
const item = (r) => {
|
|
70
|
+
const f = r.findings[0];
|
|
71
|
+
const where = f.file ? f.file + (f.line ? `:${f.line}` : "") : "";
|
|
72
|
+
const more = r.findings.length > 1 ? `<span class="ff-more">and ${r.findings.length - 1} more like it</span>` : "";
|
|
73
|
+
return `<li class="sev-${r.severity}"><span class="sq" aria-hidden="true"></span><span class="ff-main"><a href="#${anchorOf.get(f)}">${esc(f.title)}</a>${more}${where ? `<span class="ff-where">${esc(where)}</span>` : ""}</span><span class="ff-points">${points(Math.round(r.points))}</span></li>`;
|
|
74
|
+
};
|
|
75
|
+
return `<section class="fix-first" aria-labelledby="fix-first-title">
|
|
76
|
+
<h3 id="fix-first-title">Where to start</h3>
|
|
77
|
+
<p>${off >= 100 ? `Together these take off ${points(off)}, more than the 100 a check starts with, so the score is 0.` : `Together these take off ${points(off)}, for a score of ${score}.`} Each fix gives its points back.</p>
|
|
78
|
+
<ol>${shown.map(item).join("")}</ol>
|
|
79
|
+
${rest > 0 ? `<p class="ff-rest">Plus ${rest} smaller ${rest === 1 ? "one" : "ones"} in the list below.</p>` : ""}
|
|
80
|
+
</section>`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// What to fix first, then the findings in groups, worst first, after the
|
|
84
|
+
// legend. In each group, findings in the same file sit together, so a file
|
|
85
|
+
// can be fixed in one pass.
|
|
86
|
+
export function findingsHtml(findings) {
|
|
87
|
+
const groups = SEVERITIES.map((sev) => [
|
|
88
|
+
sev,
|
|
89
|
+
findings
|
|
90
|
+
.filter((f) => f.severity === sev)
|
|
91
|
+
.map((f, i) => [f, i])
|
|
92
|
+
.sort(([a, i], [b, j]) => (a.file ?? "\uffff").localeCompare(b.file ?? "\uffff") || (a.line ?? 0) - (b.line ?? 0) || i - j)
|
|
93
|
+
.map(([f]) => f),
|
|
94
|
+
]).filter(([, group]) => group.length);
|
|
95
|
+
const anchorOf = new Map();
|
|
96
|
+
for (const [, group] of groups) for (const f of group) anchorOf.set(f, `finding-${anchorOf.size + 1}`);
|
|
97
|
+
return (
|
|
98
|
+
fixFirstHtml(findings, anchorOf) +
|
|
99
|
+
legendHtml() +
|
|
100
|
+
groups
|
|
101
|
+
.map(
|
|
102
|
+
([sev, group]) => `<section class="group">
|
|
103
|
+
<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("")}
|
|
105
|
+
</section>`,
|
|
106
|
+
)
|
|
107
|
+
.join("")
|
|
108
|
+
);
|
|
109
|
+
}
|
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) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[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
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// --lookup: asks OSV.dev, the open source vulnerability database, about the
|
|
2
|
+
// MCP packages, editor extensions and agent installs the check found. Only
|
|
3
|
+
// package names, ecosystems and versions are sent: no paths, file contents,
|
|
4
|
+
// server names or settings. OSV.dev includes the OpenSSF list of malicious
|
|
5
|
+
// packages (IDs starting MAL-) and GitHub's advisories.
|
|
6
|
+
//
|
|
7
|
+
// Everything that comes back is checked before it's used: IDs must look like
|
|
8
|
+
// IDs, versions like versions, and text is cut to size. Anything else is
|
|
9
|
+
// dropped.
|
|
10
|
+
|
|
11
|
+
import { compareVersions, AGENT_ADVISORIES } from "../engine/known.js";
|
|
12
|
+
|
|
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. 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;
|
|
17
|
+
const NAME_RE = {
|
|
18
|
+
npm: /^(?:@[A-Za-z0-9~][A-Za-z0-9._~-]{0,100}\/)?[A-Za-z0-9~][A-Za-z0-9._~-]{0,213}$/,
|
|
19
|
+
PyPI: /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,98}[A-Za-z0-9])?$/,
|
|
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,
|
|
24
|
+
};
|
|
25
|
+
const isExtension = (ecosystem) => ecosystem.startsWith("VSCode");
|
|
26
|
+
const ID_RE = /^[A-Z][A-Z0-9]{1,9}-[A-Za-z0-9._:-]{1,60}$/;
|
|
27
|
+
const VERSION_RE = /^v?\d{1,10}(?:\.\d{1,10}){1,3}(?:[-+][0-9A-Za-z.-]{1,40})?$/;
|
|
28
|
+
const MAX_QUERIES = 500;
|
|
29
|
+
const MAX_DETAILS = 150;
|
|
30
|
+
// Advisories the bundled list already counts for an agent install.
|
|
31
|
+
const COUNTED = new Set(Object.values(AGENT_ADVISORIES).flat().flatMap((a) => [a.id, a.cve]).filter(Boolean));
|
|
32
|
+
|
|
33
|
+
const queryKey = (q) => `${q.ecosystem}|${q.name}|${typeof q.version === "string" && VERSION_RE.test(q.version) ? q.version.replace(/^v/, "") : null}`;
|
|
34
|
+
|
|
35
|
+
// Queries whose every use is an agent install. The bundled list already
|
|
36
|
+
// counts those agents' advisories, so OSV.dev's copies aren't fetched. An
|
|
37
|
+
// agent package used another way, such as by an MCP server, is looked up in full.
|
|
38
|
+
export function installsOnly(result) {
|
|
39
|
+
const all = new Map();
|
|
40
|
+
for (const p of Array.isArray(result?.packages) ? result.packages : []) all.set(queryKey(p), (all.get(queryKey(p)) ?? true) && p.via === "install");
|
|
41
|
+
return new Set([...all].filter(([, only]) => only).map(([key]) => key));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// The packages a result names, once each, as OSV queries.
|
|
45
|
+
export function lookupQueries(result) {
|
|
46
|
+
const seen = new Set();
|
|
47
|
+
const out = [];
|
|
48
|
+
for (const p of Array.isArray(result?.packages) ? result.packages : []) {
|
|
49
|
+
if (!Object.hasOwn(NAME_RE, p.ecosystem) || typeof p.name !== "string" || p.name.length > 214 || !NAME_RE[p.ecosystem].test(p.name)) continue;
|
|
50
|
+
const version = typeof p.version === "string" && VERSION_RE.test(p.version) ? p.version.replace(/^v/, "") : null;
|
|
51
|
+
const key = queryKey(p);
|
|
52
|
+
if (seen.has(key)) continue;
|
|
53
|
+
seen.add(key);
|
|
54
|
+
out.push({ ecosystem: p.ecosystem, name: p.name, version });
|
|
55
|
+
if (out.length >= MAX_QUERIES) break;
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Asks OSV about each query. Returns { hits, failed } where each hit names
|
|
61
|
+
// the query it answers.
|
|
62
|
+
export async function osvLookup(queries, { base = "https://api.osv.dev", timeoutMs = 20_000, fetchImpl = fetch, installs = new Set() } = {}) {
|
|
63
|
+
const hits = [];
|
|
64
|
+
let failed = 0;
|
|
65
|
+
const post = async (batch) => {
|
|
66
|
+
const res = await fetchImpl(`${base}/v1/querybatch`, {
|
|
67
|
+
method: "POST",
|
|
68
|
+
headers: { "content-type": "application/json" },
|
|
69
|
+
body: JSON.stringify({ queries: batch.map((q) => ({ package: { name: q.name, ecosystem: q.ecosystem }, ...(q.version ? { version: q.version } : {}) })) }),
|
|
70
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
71
|
+
});
|
|
72
|
+
if (!res.ok) throw new Error(`OSV.dev answered ${res.status}`);
|
|
73
|
+
const json = await readJson(res, 8 * 1024 * 1024);
|
|
74
|
+
if (!Array.isArray(json?.results) || json.results.length !== batch.length) throw new Error("OSV.dev's answer didn't match the question");
|
|
75
|
+
return json.results.map((r) => (Array.isArray(r?.vulns) ? r.vulns.slice(0, 50).map((v) => v?.id).filter((id) => typeof id === "string" && ID_RE.test(id)) : []));
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// Extensions go in their own request, so a problem with one kind of
|
|
79
|
+
// package doesn't lose the answers for the others.
|
|
80
|
+
const answers = new Map();
|
|
81
|
+
for (const group of [queries.filter((q) => !isExtension(q.ecosystem)), queries.filter((q) => isExtension(q.ecosystem))]) {
|
|
82
|
+
for (let i = 0; i < group.length; i += 250) {
|
|
83
|
+
const batch = group.slice(i, i + 250);
|
|
84
|
+
try {
|
|
85
|
+
const ids = await post(batch);
|
|
86
|
+
// What the bundled list already counted isn't fetched again.
|
|
87
|
+
const counted = (q) => q.ecosystem === "npm" && Object.hasOwn(AGENT_ADVISORIES, q.name) && installs.has(queryKey(q));
|
|
88
|
+
batch.forEach((q, k) => answers.set(q, counted(q) ? ids[k].filter((id) => !COUNTED.has(id)) : ids[k]));
|
|
89
|
+
} catch {
|
|
90
|
+
failed += batch.length;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// The details of each vulnerability, for its summary and fixed version.
|
|
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);
|
|
98
|
+
const details = new Map();
|
|
99
|
+
for (let i = 0; i < wanted.length; i += 6) {
|
|
100
|
+
await Promise.all(
|
|
101
|
+
wanted.slice(i, i + 6).map(async (id) => {
|
|
102
|
+
try {
|
|
103
|
+
const res = await fetchImpl(`${base}/v1/vulns/${encodeURIComponent(id)}`, { signal: AbortSignal.timeout(timeoutMs) });
|
|
104
|
+
if (res.ok) details.set(id, await readJson(res, 2 * 1024 * 1024));
|
|
105
|
+
} catch {}
|
|
106
|
+
}),
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
for (const [q, ids] of answers) {
|
|
111
|
+
for (const id of ids) {
|
|
112
|
+
const record = details.get(id);
|
|
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;
|
|
120
|
+
const malicious = id.startsWith("MAL-");
|
|
121
|
+
hits.push({
|
|
122
|
+
ecosystem: q.ecosystem,
|
|
123
|
+
name: q.name,
|
|
124
|
+
version: q.version,
|
|
125
|
+
ref: preferredRef(id, record),
|
|
126
|
+
malicious,
|
|
127
|
+
severity: malicious ? "critical" : severityOf(record),
|
|
128
|
+
summary: typeof record?.summary === "string" ? record.summary.slice(0, 300) : "",
|
|
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,
|
|
134
|
+
// Without its details, whether there's a fix isn't known.
|
|
135
|
+
detailed: Boolean(record),
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return { hits, failed, asked: queries.length };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// A response body as JSON, read only up to `max` bytes.
|
|
143
|
+
async function readJson(res, max) {
|
|
144
|
+
const reader = res.body?.getReader();
|
|
145
|
+
if (!reader) return null;
|
|
146
|
+
const parts = [];
|
|
147
|
+
let size = 0;
|
|
148
|
+
for (let part = await reader.read(); !part.done; part = await reader.read()) {
|
|
149
|
+
size += part.value.byteLength;
|
|
150
|
+
if (size > max) {
|
|
151
|
+
// Not awaited: stopping the download shouldn't wait on the server.
|
|
152
|
+
reader.cancel().catch(() => {});
|
|
153
|
+
throw new Error("OSV.dev's answer was too large");
|
|
154
|
+
}
|
|
155
|
+
parts.push(part.value);
|
|
156
|
+
}
|
|
157
|
+
return JSON.parse(Buffer.concat(parts).toString("utf8"));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// The CVE when there is one, since that's the name people search for.
|
|
161
|
+
function preferredRef(id, record) {
|
|
162
|
+
const cve = Array.isArray(record?.aliases) ? record.aliases.find((a) => typeof a === "string" && /^CVE-\d{4}-\d{4,7}$/.test(a)) : null;
|
|
163
|
+
return id.startsWith("MAL-") ? id : (cve ?? id);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// GitHub's advisories give a severity word; others are treated as medium.
|
|
167
|
+
function severityOf(record) {
|
|
168
|
+
const word = typeof record?.database_specific?.severity === "string" ? record.database_specific.severity.toUpperCase() : "";
|
|
169
|
+
return word === "CRITICAL" || word === "HIGH" ? "high" : word === "LOW" ? "low" : "medium";
|
|
170
|
+
}
|
|
171
|
+
|
|
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.
|
|
174
|
+
function sameName(a, b, ecosystem) {
|
|
175
|
+
const norm = (n) => (ecosystem === "PyPI" ? n.toLowerCase().replace(/[-_.]+/g, "-") : n.toLowerCase());
|
|
176
|
+
return norm(a) === norm(b);
|
|
177
|
+
}
|
|
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.
|
|
196
|
+
function fixedVersion(record, q) {
|
|
197
|
+
for (const affected of affectedEntries(record, q)) {
|
|
198
|
+
for (const range of Array.isArray(affected.ranges) ? affected.ranges.slice(0, 20) : []) {
|
|
199
|
+
if (range?.type !== "SEMVER" && range?.type !== "ECOSYSTEM") continue;
|
|
200
|
+
let introduced = null;
|
|
201
|
+
for (const event of Array.isArray(range.events) ? range.events.slice(0, 100) : []) {
|
|
202
|
+
if (typeof event?.introduced === "string") introduced = event.introduced === "0" ? "0.0.0" : event.introduced;
|
|
203
|
+
const fixed = typeof event?.fixed === "string" ? event.fixed : null;
|
|
204
|
+
if (introduced && fixed && VERSION_RE.test(fixed) && VERSION_RE.test(introduced) && compareVersions(q.version, introduced) >= 0 && compareVersions(q.version, fixed) < 0) return fixed;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return null;
|
|
209
|
+
}
|