@misconfig/cli 1.1.0 → 1.3.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/CHANGELOG.md +153 -0
- package/LICENSE +1 -0
- package/README.md +108 -28
- package/bin/misconfig.js +28 -1
- package/engine/catalog.js +498 -99
- package/engine/decode.js +41 -0
- package/engine/explain.js +793 -79
- package/engine/flags.js +124 -0
- package/engine/glob.js +178 -0
- package/engine/index.js +2549 -317
- package/engine/known.js +324 -0
- package/engine/locations.js +96 -47
- package/engine/mask.js +74 -21
- package/engine/named.js +92 -0
- package/engine/parse.js +442 -42
- package/engine/paths.js +80 -16
- package/lib/discover.js +635 -97
- package/lib/lookup.js +178 -0
- package/lib/main.js +180 -23
- package/lib/print.js +251 -74
- package/lib/private.js +47 -0
- package/package.json +21 -20
package/lib/lookup.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
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.
|
|
15
|
+
const NAME_RE = {
|
|
16
|
+
npm: /^(?:@[A-Za-z0-9~][A-Za-z0-9._~-]{0,100}\/)?[A-Za-z0-9~][A-Za-z0-9._~-]{0,213}$/,
|
|
17
|
+
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}$/,
|
|
19
|
+
};
|
|
20
|
+
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})?$/;
|
|
22
|
+
const MAX_QUERIES = 500;
|
|
23
|
+
const MAX_DETAILS = 150;
|
|
24
|
+
// Advisories the bundled list already counts for an agent install.
|
|
25
|
+
const COUNTED = new Set(Object.values(AGENT_ADVISORIES).flat().flatMap((a) => [a.id, a.cve]).filter(Boolean));
|
|
26
|
+
|
|
27
|
+
const queryKey = (q) => `${q.ecosystem}|${q.name}|${typeof q.version === "string" && VERSION_RE.test(q.version) ? q.version.replace(/^v/, "") : null}`;
|
|
28
|
+
|
|
29
|
+
// Queries whose every use is an agent install. The bundled list already
|
|
30
|
+
// counts those agents' advisories, so OSV.dev's copies aren't fetched. An
|
|
31
|
+
// agent package used another way, such as by an MCP server, is looked up in full.
|
|
32
|
+
export function installsOnly(result) {
|
|
33
|
+
const all = new Map();
|
|
34
|
+
for (const p of Array.isArray(result?.packages) ? result.packages : []) all.set(queryKey(p), (all.get(queryKey(p)) ?? true) && p.via === "install");
|
|
35
|
+
return new Set([...all].filter(([, only]) => only).map(([key]) => key));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// The packages a result names, once each, as OSV queries.
|
|
39
|
+
export function lookupQueries(result) {
|
|
40
|
+
const seen = new Set();
|
|
41
|
+
const out = [];
|
|
42
|
+
for (const p of Array.isArray(result?.packages) ? result.packages : []) {
|
|
43
|
+
if (!Object.hasOwn(NAME_RE, p.ecosystem) || typeof p.name !== "string" || p.name.length > 214 || !NAME_RE[p.ecosystem].test(p.name)) continue;
|
|
44
|
+
const version = typeof p.version === "string" && VERSION_RE.test(p.version) ? p.version.replace(/^v/, "") : null;
|
|
45
|
+
const key = queryKey(p);
|
|
46
|
+
if (seen.has(key)) continue;
|
|
47
|
+
seen.add(key);
|
|
48
|
+
out.push({ ecosystem: p.ecosystem, name: p.name, version });
|
|
49
|
+
if (out.length >= MAX_QUERIES) break;
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Asks OSV about each query. Returns { hits, failed } where each hit names
|
|
55
|
+
// the query it answers.
|
|
56
|
+
export async function osvLookup(queries, { base = "https://api.osv.dev", timeoutMs = 20_000, fetchImpl = fetch, installs = new Set() } = {}) {
|
|
57
|
+
const hits = [];
|
|
58
|
+
let failed = 0;
|
|
59
|
+
const post = async (batch) => {
|
|
60
|
+
const res = await fetchImpl(`${base}/v1/querybatch`, {
|
|
61
|
+
method: "POST",
|
|
62
|
+
headers: { "content-type": "application/json" },
|
|
63
|
+
body: JSON.stringify({ queries: batch.map((q) => ({ package: { name: q.name, ecosystem: q.ecosystem }, ...(q.version ? { version: q.version } : {}) })) }),
|
|
64
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
65
|
+
});
|
|
66
|
+
if (!res.ok) throw new Error(`OSV.dev answered ${res.status}`);
|
|
67
|
+
const json = await readJson(res, 8 * 1024 * 1024);
|
|
68
|
+
if (!Array.isArray(json?.results) || json.results.length !== batch.length) throw new Error("OSV.dev's answer didn't match the question");
|
|
69
|
+
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)) : []));
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
// Extensions go in their own request, so a problem with one kind of
|
|
73
|
+
// package doesn't lose the answers for the others.
|
|
74
|
+
const answers = new Map();
|
|
75
|
+
for (const group of [queries.filter((q) => q.ecosystem !== "VSCode"), queries.filter((q) => q.ecosystem === "VSCode")]) {
|
|
76
|
+
for (let i = 0; i < group.length; i += 250) {
|
|
77
|
+
const batch = group.slice(i, i + 250);
|
|
78
|
+
try {
|
|
79
|
+
const ids = await post(batch);
|
|
80
|
+
// What the bundled list already counted isn't fetched again.
|
|
81
|
+
const counted = (q) => q.ecosystem === "npm" && Object.hasOwn(AGENT_ADVISORIES, q.name) && installs.has(queryKey(q));
|
|
82
|
+
batch.forEach((q, k) => answers.set(q, counted(q) ? ids[k].filter((id) => !COUNTED.has(id)) : ids[k]));
|
|
83
|
+
} catch {
|
|
84
|
+
failed += batch.length;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// The details of each vulnerability, for its summary and fixed version.
|
|
90
|
+
const wanted = [...new Set([...answers.values()].flat())].slice(0, MAX_DETAILS);
|
|
91
|
+
const details = new Map();
|
|
92
|
+
for (let i = 0; i < wanted.length; i += 6) {
|
|
93
|
+
await Promise.all(
|
|
94
|
+
wanted.slice(i, i + 6).map(async (id) => {
|
|
95
|
+
try {
|
|
96
|
+
const res = await fetchImpl(`${base}/v1/vulns/${encodeURIComponent(id)}`, { signal: AbortSignal.timeout(timeoutMs) });
|
|
97
|
+
if (res.ok) details.set(id, await readJson(res, 2 * 1024 * 1024));
|
|
98
|
+
} catch {}
|
|
99
|
+
}),
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
for (const [q, ids] of answers) {
|
|
104
|
+
for (const id of ids) {
|
|
105
|
+
const record = details.get(id);
|
|
106
|
+
if (record && record.id !== id) continue;
|
|
107
|
+
const malicious = id.startsWith("MAL-");
|
|
108
|
+
hits.push({
|
|
109
|
+
ecosystem: q.ecosystem,
|
|
110
|
+
name: q.name,
|
|
111
|
+
version: q.version,
|
|
112
|
+
ref: preferredRef(id, record),
|
|
113
|
+
malicious,
|
|
114
|
+
severity: malicious ? "critical" : severityOf(record),
|
|
115
|
+
summary: typeof record?.summary === "string" ? record.summary.slice(0, 300) : "",
|
|
116
|
+
fixed: q.version && record ? fixedVersion(record, q) : null,
|
|
117
|
+
// Without its details, whether there's a fix isn't known.
|
|
118
|
+
detailed: Boolean(record),
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return { hits, failed, asked: queries.length };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// A response body as JSON, read only up to `max` bytes.
|
|
126
|
+
async function readJson(res, max) {
|
|
127
|
+
const reader = res.body?.getReader();
|
|
128
|
+
if (!reader) return null;
|
|
129
|
+
const parts = [];
|
|
130
|
+
let size = 0;
|
|
131
|
+
for (let part = await reader.read(); !part.done; part = await reader.read()) {
|
|
132
|
+
size += part.value.byteLength;
|
|
133
|
+
if (size > max) {
|
|
134
|
+
// Not awaited: stopping the download shouldn't wait on the server.
|
|
135
|
+
reader.cancel().catch(() => {});
|
|
136
|
+
throw new Error("OSV.dev's answer was too large");
|
|
137
|
+
}
|
|
138
|
+
parts.push(part.value);
|
|
139
|
+
}
|
|
140
|
+
return JSON.parse(Buffer.concat(parts).toString("utf8"));
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// The CVE when there is one, since that's the name people search for.
|
|
144
|
+
function preferredRef(id, record) {
|
|
145
|
+
const cve = Array.isArray(record?.aliases) ? record.aliases.find((a) => typeof a === "string" && /^CVE-\d{4}-\d{4,7}$/.test(a)) : null;
|
|
146
|
+
return id.startsWith("MAL-") ? id : (cve ?? id);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// GitHub's advisories give a severity word; others are treated as medium.
|
|
150
|
+
function severityOf(record) {
|
|
151
|
+
const word = typeof record?.database_specific?.severity === "string" ? record.database_specific.severity.toUpperCase() : "";
|
|
152
|
+
return word === "CRITICAL" || word === "HIGH" ? "high" : word === "LOW" ? "low" : "medium";
|
|
153
|
+
}
|
|
154
|
+
|
|
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.
|
|
158
|
+
function sameName(a, b, ecosystem) {
|
|
159
|
+
const norm = (n) => (ecosystem === "PyPI" ? n.toLowerCase().replace(/[-_.]+/g, "-") : n.toLowerCase());
|
|
160
|
+
return norm(a) === norm(b);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
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;
|
|
167
|
+
for (const range of Array.isArray(affected.ranges) ? affected.ranges.slice(0, 20) : []) {
|
|
168
|
+
if (range?.type !== "SEMVER" && range?.type !== "ECOSYSTEM") continue;
|
|
169
|
+
let introduced = null;
|
|
170
|
+
for (const event of Array.isArray(range.events) ? range.events.slice(0, 100) : []) {
|
|
171
|
+
if (typeof event?.introduced === "string") introduced = event.introduced === "0" ? "0.0.0" : event.introduced;
|
|
172
|
+
const fixed = typeof event?.fixed === "string" ? event.fixed : null;
|
|
173
|
+
if (introduced && fixed && VERSION_RE.test(fixed) && VERSION_RE.test(introduced) && compareVersions(q.version, introduced) >= 0 && compareVersions(q.version, fixed) < 0) return fixed;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return null;
|
|
178
|
+
}
|
package/lib/main.js
CHANGED
|
@@ -1,26 +1,41 @@
|
|
|
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, toShareable, applyLookup, rulesetIsNewer, RULESET_VERSION, SHARE_MAX_FINDINGS } from "../engine/index.js";
|
|
4
4
|
import { discover } from "./discover.js";
|
|
5
|
-
import { printReport, printSharePreview, printShareResult } from "./print.js";
|
|
5
|
+
import { printReport, printSharePreview, printShareResult, printOpenPreview, printOpenResult, printLookupPreview, printLookupResult, oneLine } from "./print.js";
|
|
6
|
+
import { seal, openInBrowser, MAX_BYTES } from "./private.js";
|
|
7
|
+
import { lookupQueries, osvLookup, installsOnly } from "./lookup.js";
|
|
6
8
|
|
|
7
9
|
const HELP = `Usage: npx @misconfig/cli [folder] [options]
|
|
8
10
|
|
|
9
11
|
Finds every file that controls your AI coding agents, on this computer and in
|
|
10
12
|
the folder (the current folder by default), and checks them for risky
|
|
11
|
-
settings.
|
|
13
|
+
settings. It also checks the MCP servers, editor extensions, skills and agent
|
|
14
|
+
versions installed for known malware and missing security fixes. Everything
|
|
15
|
+
runs here. Nothing is sent anywhere unless you use --lookup, --open or --share.
|
|
12
16
|
|
|
13
17
|
Options
|
|
14
18
|
--explain Show everything each file tells your agents: rules,
|
|
15
|
-
permissions, MCP servers, hooks and hidden text
|
|
19
|
+
permissions, MCP servers, hooks and hidden text, and
|
|
20
|
+
what's installed
|
|
21
|
+
--lookup Also look up the MCP packages, editor extensions and
|
|
22
|
+
agent versions found on OSV.dev, for malware and known
|
|
23
|
+
vulnerabilities, including ones newer than this
|
|
24
|
+
release. Sends only package names and versions, and
|
|
25
|
+
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.
|
|
16
29
|
--share Publish this project's findings and print a link. Shows
|
|
17
30
|
what will be sent and asks first. No file contents are
|
|
18
31
|
sent, and nothing from outside the project.
|
|
19
|
-
--yes
|
|
32
|
+
--yes Look up, share or open without asking, for scripts and CI
|
|
20
33
|
--json Print the full result as JSON
|
|
21
34
|
--project-only Skip the agent settings on this computer
|
|
22
35
|
--fail-on <level> Exit with code 1 if anything at this level or worse is
|
|
23
36
|
found: critical, high, medium or low. Useful in CI.
|
|
37
|
+
Exits with code 2 if the folder was too big to check
|
|
38
|
+
completely.
|
|
24
39
|
-v, --version Print the version
|
|
25
40
|
-h, --help Show this help
|
|
26
41
|
`;
|
|
@@ -28,7 +43,7 @@ Options
|
|
|
28
43
|
const LEVELS = ["critical", "high", "medium", "low"];
|
|
29
44
|
|
|
30
45
|
export async function main(argv) {
|
|
31
|
-
const opts = { dir: process.cwd(), share: false, yes: false, json: false, explain: false, projectOnly: false, failOn: null };
|
|
46
|
+
const opts = { dir: process.cwd(), share: false, open: false, lookup: false, yes: false, json: false, explain: false, projectOnly: false, failOn: null };
|
|
32
47
|
for (let i = 0; i < argv.length; i++) {
|
|
33
48
|
const a = argv[i];
|
|
34
49
|
if (a === "-h" || a === "--help") {
|
|
@@ -40,6 +55,8 @@ export async function main(argv) {
|
|
|
40
55
|
return 0;
|
|
41
56
|
}
|
|
42
57
|
if (a === "--share") opts.share = true;
|
|
58
|
+
else if (a === "--open") opts.open = true;
|
|
59
|
+
else if (a === "--lookup") opts.lookup = true;
|
|
43
60
|
else if (a === "--yes" || a === "-y") opts.yes = true;
|
|
44
61
|
else if (a === "--json") opts.json = true;
|
|
45
62
|
else if (a === "--explain") opts.explain = true;
|
|
@@ -52,16 +69,21 @@ export async function main(argv) {
|
|
|
52
69
|
}
|
|
53
70
|
|
|
54
71
|
const input = await discover({ dir: opts.dir, includeUser: !opts.projectOnly });
|
|
55
|
-
|
|
72
|
+
let result = check(input);
|
|
73
|
+
let lookedUp = false;
|
|
74
|
+
if (opts.lookup) ({ result, lookedUp } = await lookup(opts, result));
|
|
56
75
|
|
|
57
76
|
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 });
|
|
77
|
+
else printReport(result, { version: await version(), scanned: input.scanned, explain: opts.explain, open: opts.open, lookedUp });
|
|
59
78
|
|
|
60
79
|
if (opts.share) await share(opts, input, result);
|
|
80
|
+
if (opts.open) await openPrivate(opts, input, result);
|
|
61
81
|
|
|
62
82
|
if (opts.failOn) {
|
|
63
83
|
const worst = LEVELS.slice(0, LEVELS.indexOf(opts.failOn) + 1);
|
|
64
84
|
if (result.findings.some((f) => worst.includes(f.severity))) return 1;
|
|
85
|
+
// A check that couldn't see everything shouldn't pass a CI gate.
|
|
86
|
+
if (result.stats.truncated) return 2;
|
|
65
87
|
}
|
|
66
88
|
return 0;
|
|
67
89
|
}
|
|
@@ -76,36 +98,171 @@ function check(input) {
|
|
|
76
98
|
return result;
|
|
77
99
|
}
|
|
78
100
|
|
|
101
|
+
// Asks OSV.dev about what's installed, after showing exactly what will be sent.
|
|
102
|
+
async function lookup(opts, result) {
|
|
103
|
+
const out = opts.json ? process.stderr : process.stdout;
|
|
104
|
+
const base = serviceBase("MISCONFIG_OSV_URL", "https://api.osv.dev");
|
|
105
|
+
const queries = lookupQueries(result);
|
|
106
|
+
printLookupPreview(out, queries);
|
|
107
|
+
if (!queries.length) return { result, lookedUp: false };
|
|
108
|
+
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 };
|
|
109
|
+
const { hits, failed, asked } = await osvLookup(queries, { base, installs: installsOnly(result) });
|
|
110
|
+
const next = applyLookup(result, hits);
|
|
111
|
+
printLookupResult(out, { asked, failed, found: next.findings.length - result.findings.length });
|
|
112
|
+
return { result: next, lookedUp: true };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// A yes from someone at the terminal, or --yes. Without a terminal and
|
|
116
|
+
// without --yes, nothing is sent.
|
|
117
|
+
async function confirmed(opts, out, question, refusal) {
|
|
118
|
+
if (opts.yes) return true;
|
|
119
|
+
if (!process.stdin.isTTY) throw new Error(refusal);
|
|
120
|
+
const answer = await ask(out, question);
|
|
121
|
+
if (answer === "y" || answer === "yes") return true;
|
|
122
|
+
out.write("Nothing was sent.\n");
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// A question at the terminal. Ctrl+C, or the input ending, cancels it with an
|
|
127
|
+
// AbortError, which stops the command with nothing sent.
|
|
128
|
+
async function ask(out, question) {
|
|
129
|
+
const rl = createInterface({ input: process.stdin, output: out });
|
|
130
|
+
const stop = new AbortController();
|
|
131
|
+
rl.once("SIGINT", () => stop.abort());
|
|
132
|
+
rl.once("close", () => stop.abort());
|
|
133
|
+
try {
|
|
134
|
+
return (await rl.question(question, { signal: stop.signal })).trim().toLowerCase();
|
|
135
|
+
} finally {
|
|
136
|
+
rl.close();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
79
140
|
async function share(opts, input, result) {
|
|
80
141
|
// A share link covers the project only. Settings on this computer stay here.
|
|
81
142
|
const out = opts.json ? process.stderr : process.stdout;
|
|
143
|
+
const base = serviceBase();
|
|
82
144
|
if (input.scanned.projectSkipped) {
|
|
83
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.");
|
|
84
146
|
}
|
|
85
147
|
const project = input.scanned.user ? check(await discover({ dir: opts.dir, includeUser: false })) : result;
|
|
86
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
|
+
}
|
|
87
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;
|
|
88
161
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
return;
|
|
97
|
-
}
|
|
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.");
|
|
98
169
|
}
|
|
99
|
-
|
|
100
|
-
const base = (process.env.MISCONFIG_URL || "https://misconfig.ai").replace(/\/+$/, "");
|
|
101
|
-
const res = await fetch(`${base}/api/share`, {
|
|
170
|
+
const res = await send(`${base}/api/share`, {
|
|
102
171
|
method: "POST",
|
|
103
|
-
headers: { "content-type": "application/json", "user-agent":
|
|
172
|
+
headers: { "content-type": "application/json", "user-agent": agent },
|
|
104
173
|
body: JSON.stringify(payload),
|
|
105
174
|
});
|
|
106
175
|
const data = await res.json().catch(() => ({}));
|
|
107
|
-
if (!res.ok) throw new Error(data
|
|
108
|
-
|
|
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
|
+
// Where requests go: misconfig.ai and OSV.dev, or for testing the addresses
|
|
186
|
+
// 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.
|
|
189
|
+
function serviceBase(name = "MISCONFIG_URL", fallback = "https://misconfig.ai") {
|
|
190
|
+
const raw = process.env[name] || fallback;
|
|
191
|
+
let url;
|
|
192
|
+
try {
|
|
193
|
+
url = new URL(raw);
|
|
194
|
+
} catch {
|
|
195
|
+
throw new Error(`${name} isn't a web address. Nothing was sent.`);
|
|
196
|
+
}
|
|
197
|
+
const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
198
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) throw new Error(`${name} must start with https://. Nothing was sent.`);
|
|
199
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
200
|
+
}
|
|
201
|
+
|
|
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) {
|
|
211
|
+
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.
|
|
216
|
+
const report = { ...result };
|
|
217
|
+
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}`;
|
|
232
|
+
// A browser opens only for someone at a terminal, never in CI or a script.
|
|
233
|
+
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
|
+
}
|
|
109
266
|
}
|
|
110
267
|
|
|
111
268
|
let cachedVersion = null;
|