@kenkaiiii/ggcoder 5.83.5 → 5.84.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/dist/app-sidecar/history-routes.js +7 -0
- package/dist/app-sidecar/history-routes.js.map +1 -1
- package/dist/app-sidecar/history.d.ts +5 -0
- package/dist/app-sidecar/history.js.map +1 -1
- package/dist/app-sidecar/mcp-rows.d.ts +2 -0
- package/dist/app-sidecar/mcp-rows.js +4 -1
- package/dist/app-sidecar/mcp-rows.js.map +1 -1
- package/dist/app-sidecar/session-routes.js +10 -0
- package/dist/app-sidecar/session-routes.js.map +1 -1
- package/dist/app-sidecar.js +6 -0
- package/dist/app-sidecar.js.map +1 -1
- package/dist/cli/mcp.js +6 -1
- package/dist/cli/mcp.js.map +1 -1
- package/dist/cli.js +6 -2
- package/dist/cli.js.map +1 -1
- package/dist/core/action-threats.d.ts +68 -0
- package/dist/core/action-threats.js +894 -0
- package/dist/core/action-threats.js.map +1 -0
- package/dist/core/agent-session.d.ts +65 -1
- package/dist/core/agent-session.js +188 -2
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/blocked-packages-file.d.ts +33 -0
- package/dist/core/blocked-packages-file.js +274 -0
- package/dist/core/blocked-packages-file.js.map +1 -0
- package/dist/core/event-bus.d.ts +10 -0
- package/dist/core/event-bus.js +2 -0
- package/dist/core/event-bus.js.map +1 -1
- package/dist/core/injection-detect.d.ts +2 -1
- package/dist/core/injection-detect.js +13 -4
- package/dist/core/injection-detect.js.map +1 -1
- package/dist/core/installed-threats.d.ts +23 -0
- package/dist/core/installed-threats.js +71 -0
- package/dist/core/installed-threats.js.map +1 -0
- package/dist/core/mcp/catalog-cache.d.ts +2 -0
- package/dist/core/mcp/catalog-cache.js +4 -0
- package/dist/core/mcp/catalog-cache.js.map +1 -1
- package/dist/core/mcp/client.d.ts +8 -0
- package/dist/core/mcp/client.js +37 -3
- package/dist/core/mcp/client.js.map +1 -1
- package/dist/core/mcp/index.d.ts +2 -0
- package/dist/core/mcp/index.js +1 -0
- package/dist/core/mcp/index.js.map +1 -1
- package/dist/core/mcp/tool-guard.d.ts +58 -0
- package/dist/core/mcp/tool-guard.js +215 -0
- package/dist/core/mcp/tool-guard.js.map +1 -0
- package/dist/core/network-guard.d.ts +0 -20
- package/dist/core/network-guard.js +6 -0
- package/dist/core/network-guard.js.map +1 -1
- package/dist/core/package-cooldown.d.ts +71 -0
- package/dist/core/package-cooldown.js +301 -0
- package/dist/core/package-cooldown.js.map +1 -0
- package/dist/core/package-threats.d.ts +77 -3
- package/dist/core/package-threats.js +1110 -78
- package/dist/core/package-threats.js.map +1 -1
- package/dist/core/process-manager.d.ts +3 -1
- package/dist/core/process-manager.js +4 -2
- package/dist/core/process-manager.js.map +1 -1
- package/dist/core/prompt-commands.js +1 -0
- package/dist/core/prompt-commands.js.map +1 -1
- package/dist/core/session-manager.d.ts +3 -1
- package/dist/core/session-manager.js +2 -1
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +1 -0
- package/dist/core/settings-manager.js +4 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/shell-threats.d.ts +14 -1
- package/dist/core/shell-threats.js +73 -24
- package/dist/core/shell-threats.js.map +1 -1
- package/dist/core/skill-scan.d.ts +112 -0
- package/dist/core/skill-scan.js +781 -0
- package/dist/core/skill-scan.js.map +1 -0
- package/dist/core/skills.d.ts +33 -0
- package/dist/core/skills.js +87 -16
- package/dist/core/skills.js.map +1 -1
- package/dist/core/threat-feed.d.ts +65 -0
- package/dist/core/threat-feed.js +329 -0
- package/dist/core/threat-feed.js.map +1 -0
- package/dist/interactive.js +7 -2
- package/dist/interactive.js.map +1 -1
- package/dist/system-prompt.d.ts +1 -0
- package/dist/system-prompt.js +1 -1
- package/dist/system-prompt.js.map +1 -1
- package/dist/tools/bash.d.ts +3 -1
- package/dist/tools/bash.js +51 -25
- package/dist/tools/bash.js.map +1 -1
- package/dist/tools/checklist.d.ts +3 -3
- package/dist/tools/edit.js +5 -0
- package/dist/tools/edit.js.map +1 -1
- package/dist/tools/index.d.ts +5 -1
- package/dist/tools/index.js +2 -2
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/skill.d.ts +2 -2
- package/dist/tools/skill.js +8 -1
- package/dist/tools/skill.js.map +1 -1
- package/dist/tools/write.js +8 -0
- package/dist/tools/write.js.map +1 -1
- package/dist/ui/mcp.d.ts +2 -0
- package/dist/ui/mcp.js.map +1 -1
- package/package.json +4 -4
|
@@ -1,54 +1,142 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Package-install
|
|
3
|
-
*
|
|
2
|
+
* Package-install guard. Blocks only on concrete signals; everything else
|
|
3
|
+
* passes silently. A catch is a block with one plain line for the agent.
|
|
4
|
+
*
|
|
5
|
+
* - Known malware: local threat feed (instant) + OSV querybatch with the exact
|
|
6
|
+
* version that would install (name-only queries flag every package that
|
|
7
|
+
* ever had one bad release, e.g. chalk/debug).
|
|
8
|
+
* - Lockfile installs (`npm ci`, `pnpm install`, `uv sync`, …): every locked
|
|
9
|
+
* name@version, cached by lockfile hash.
|
|
10
|
+
* - Release age when the manager has no native cooldown (P3).
|
|
11
|
+
* - Provenance downgrade: previous version had attestations, this one not (P4).
|
|
12
|
+
* - Typosquat: one edit from a popular name AND new / missing / barely used (P5).
|
|
13
|
+
*
|
|
14
|
+
* Network only for install commands, parallel, one ≤2.5 s deadline, fail-open.
|
|
15
|
+
* Clean answers are cached on disk (package-verdicts.json in the GG dir).
|
|
4
16
|
*/
|
|
17
|
+
import { createHash } from "node:crypto";
|
|
18
|
+
import fsp from "node:fs/promises";
|
|
19
|
+
import { getAppPaths } from "@kenkaiiii/gg-core";
|
|
20
|
+
import path from "node:path";
|
|
5
21
|
import { log } from "./logger.js";
|
|
6
22
|
import { POPULAR_NPM_PACKAGES, POPULAR_PYPI_PACKAGES } from "./shell-threats-popular-packages.js";
|
|
23
|
+
import { SAFETY_BLOCK_NOTE } from "./action-threats.js";
|
|
24
|
+
import { compareVersions, emptyFeed, feedMatches, loadThreatFeed, writeJsonAtomic, } from "./threat-feed.js";
|
|
25
|
+
import { hasNativeCooldown, managerVersion, usesCustomNpmRegistry, usesCustomPypiIndex, } from "./package-cooldown.js";
|
|
7
26
|
const OSV_URL = "https://api.osv.dev/v1/querybatch";
|
|
8
|
-
const
|
|
27
|
+
const NPM_REGISTRY = "https://registry.npmjs.org";
|
|
28
|
+
const NPM_DOWNLOADS = "https://api.npmjs.org/downloads/point/last-week";
|
|
29
|
+
const PYPI = "https://pypi.org/pypi";
|
|
30
|
+
const TIMEOUT_MS = 2_500;
|
|
31
|
+
const OSV_BATCH = 1000;
|
|
32
|
+
const DAY_MS = 86_400_000;
|
|
33
|
+
const TYPOSQUAT_NEW_DAYS = 90;
|
|
34
|
+
const TYPOSQUAT_MIN_WEEKLY = 500;
|
|
9
35
|
const NPM_INSTALL = new Set(["add", "install", "i"]);
|
|
36
|
+
// Per-process caches; answers are stable within a session.
|
|
37
|
+
/** OSV answers by `eco:name@version`: MAL ids + when asked. Clean answers expire after a day. */
|
|
10
38
|
const osvCache = new Map();
|
|
11
|
-
|
|
12
|
-
|
|
39
|
+
const metaCache = new Map();
|
|
40
|
+
const lockfileCache = new Map();
|
|
41
|
+
// ── Parsing ───────────────────────────────────────────────
|
|
42
|
+
/** Split `react@18`, `@a/b@1`, `requests==2.0`, `x[extra]>=1` into name + spec. */
|
|
43
|
+
function splitSpec(raw, ecosystem) {
|
|
13
44
|
if (ecosystem === "npm") {
|
|
14
|
-
const at =
|
|
15
|
-
const name = at === -1 ?
|
|
16
|
-
|
|
45
|
+
const at = raw.indexOf("@", 1);
|
|
46
|
+
const name = at === -1 ? raw : raw.slice(0, at);
|
|
47
|
+
const spec = at === -1 ? undefined : raw.slice(at + 1) || undefined;
|
|
48
|
+
if (spec?.startsWith("npm:") || spec?.includes(":") || spec?.includes("/"))
|
|
49
|
+
return null;
|
|
50
|
+
return /^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i.test(name)
|
|
51
|
+
? { name: name.toLowerCase(), spec }
|
|
52
|
+
: null;
|
|
17
53
|
}
|
|
18
|
-
const
|
|
19
|
-
|
|
54
|
+
const m = /^([a-z0-9][a-z0-9._-]*)(?:\[[^\]]*\])?(.*)$/i.exec(raw);
|
|
55
|
+
if (!m)
|
|
56
|
+
return null;
|
|
57
|
+
const name = (m[1] ?? "").toLowerCase().replace(/[._]+/g, "-");
|
|
58
|
+
const rest = (m[2] ?? "").split(";")[0]?.trim() ?? "";
|
|
59
|
+
if (rest.startsWith("@"))
|
|
60
|
+
return null; // PEP 508 URL
|
|
61
|
+
const pin = /^===?\s*([^\s,*]+)$/.exec(rest);
|
|
62
|
+
return { name, spec: pin ? pin[1] : rest || undefined };
|
|
63
|
+
}
|
|
64
|
+
function tokenize(segment) {
|
|
65
|
+
const tokens = segment
|
|
66
|
+
.trim()
|
|
67
|
+
.split(/\s+/)
|
|
68
|
+
.map((t) => t.replace(/^['"]|['"]$/g, ""))
|
|
69
|
+
.filter((t) => t.length > 0);
|
|
70
|
+
while (tokens[0] === "sudo" || /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0] ?? ""))
|
|
71
|
+
tokens.shift();
|
|
72
|
+
return tokens;
|
|
73
|
+
}
|
|
74
|
+
function segments(command) {
|
|
75
|
+
return command.split(/(?:&&|\|\||[;|\n])/);
|
|
20
76
|
}
|
|
21
|
-
|
|
77
|
+
const VALUE_FLAGS = /^(?:-r|-c|-e|--requirement|--constraint|--editable|--registry|-i|--index-url|--extra-index-url|--filter|-F|-C|--dir|--prefix|-w|--workspace|--python|-p|--package|--with|--from)$/;
|
|
78
|
+
/** Packages named by install commands in `command`. Local paths/URLs/git are skipped. */
|
|
22
79
|
export function parsePackageInstalls(command) {
|
|
23
80
|
const refs = [];
|
|
24
|
-
for (const segment of command
|
|
25
|
-
const
|
|
26
|
-
.trim()
|
|
27
|
-
.split(/\s+/)
|
|
28
|
-
.map((t) => t.replace(/^['"]|['"]$/g, ""))
|
|
29
|
-
.filter((t) => t.length > 0);
|
|
30
|
-
if (tokens[0] === "sudo")
|
|
31
|
-
tokens.shift();
|
|
32
|
-
const [program, sub, ...rest] = tokens;
|
|
81
|
+
for (const segment of segments(command)) {
|
|
82
|
+
const [program, sub, ...rest] = tokenize(segment);
|
|
33
83
|
let ecosystem = null;
|
|
84
|
+
let manager = "npm";
|
|
34
85
|
let args = [];
|
|
35
|
-
|
|
86
|
+
let first = false;
|
|
87
|
+
if ((program === "npx" || program === "bunx") && sub !== undefined) {
|
|
88
|
+
ecosystem = "npm";
|
|
89
|
+
manager = program === "npx" ? "npx" : "bun";
|
|
90
|
+
args = [sub, ...rest];
|
|
91
|
+
first = true;
|
|
92
|
+
}
|
|
93
|
+
else if ((program === "pnpm" || program === "yarn" || program === "npm") &&
|
|
94
|
+
(sub === "dlx" || sub === "exec") &&
|
|
95
|
+
program !== "yarn") {
|
|
36
96
|
ecosystem = "npm";
|
|
37
|
-
|
|
97
|
+
manager = program === "npm" ? "npx" : "pnpm";
|
|
98
|
+
args = rest;
|
|
99
|
+
first = true;
|
|
38
100
|
}
|
|
39
101
|
else if ((program === "npm" || program === "pnpm" || program === "yarn" || program === "bun") &&
|
|
40
102
|
sub !== undefined &&
|
|
41
103
|
NPM_INSTALL.has(sub)) {
|
|
42
104
|
ecosystem = "npm";
|
|
105
|
+
manager = program;
|
|
43
106
|
args = rest;
|
|
44
107
|
}
|
|
45
108
|
else if ((program === "pip" || program === "pip3") && sub === "install") {
|
|
46
109
|
ecosystem = "PyPI";
|
|
110
|
+
manager = "pip";
|
|
111
|
+
args = rest;
|
|
112
|
+
}
|
|
113
|
+
else if (program === "pipx" && (sub === "run" || sub === "install")) {
|
|
114
|
+
ecosystem = "PyPI";
|
|
115
|
+
manager = "pip";
|
|
47
116
|
args = rest;
|
|
117
|
+
first = sub === "run";
|
|
48
118
|
}
|
|
49
119
|
else if (program === "uv" && sub === "pip" && rest[0] === "install") {
|
|
50
120
|
ecosystem = "PyPI";
|
|
121
|
+
manager = "uv";
|
|
122
|
+
args = rest.slice(1);
|
|
123
|
+
}
|
|
124
|
+
else if (program === "uv" && sub === "add") {
|
|
125
|
+
ecosystem = "PyPI";
|
|
126
|
+
manager = "uv";
|
|
127
|
+
args = rest;
|
|
128
|
+
}
|
|
129
|
+
else if (program === "uvx" && sub !== undefined) {
|
|
130
|
+
ecosystem = "PyPI";
|
|
131
|
+
manager = "uvx";
|
|
132
|
+
args = [sub, ...rest];
|
|
133
|
+
first = true;
|
|
134
|
+
}
|
|
135
|
+
else if (program === "uv" && sub === "tool" && (rest[0] === "run" || rest[0] === "install")) {
|
|
136
|
+
ecosystem = "PyPI";
|
|
137
|
+
manager = "uvx";
|
|
51
138
|
args = rest.slice(1);
|
|
139
|
+
first = rest[0] === "run";
|
|
52
140
|
}
|
|
53
141
|
if (!ecosystem)
|
|
54
142
|
continue;
|
|
@@ -58,20 +146,303 @@ export function parsePackageInstalls(command) {
|
|
|
58
146
|
skipNext = false;
|
|
59
147
|
continue;
|
|
60
148
|
}
|
|
61
|
-
|
|
62
|
-
|
|
149
|
+
if (arg === "--") {
|
|
150
|
+
if (first)
|
|
151
|
+
break;
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (VALUE_FLAGS.test(arg)) {
|
|
63
155
|
skipNext = true;
|
|
64
156
|
continue;
|
|
65
157
|
}
|
|
66
|
-
if (arg.startsWith("-")
|
|
158
|
+
if (arg.startsWith("-"))
|
|
67
159
|
continue;
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
160
|
+
const local = /[/\\:]/.test(arg.replace(/^@[^/]+\//, "")) || arg.startsWith(".");
|
|
161
|
+
const parsed = local ? null : splitSpec(arg, ecosystem);
|
|
162
|
+
if (parsed)
|
|
163
|
+
refs.push({ ecosystem, manager, ...parsed });
|
|
164
|
+
if (first)
|
|
165
|
+
break; // npx/uvx: only the package positional
|
|
71
166
|
}
|
|
72
167
|
}
|
|
73
168
|
return refs;
|
|
74
169
|
}
|
|
170
|
+
/** No-arg installs that install a whole lockfile. */
|
|
171
|
+
export function parseLockfileInstalls(command) {
|
|
172
|
+
const out = [];
|
|
173
|
+
let dir = "";
|
|
174
|
+
for (const segment of segments(command)) {
|
|
175
|
+
const tokens = tokenize(segment);
|
|
176
|
+
const [program, sub, ...rest] = tokens;
|
|
177
|
+
if (program === "cd" && sub !== undefined) {
|
|
178
|
+
dir = path.join(dir, sub);
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
const positional = rest.filter((a) => !a.startsWith("-"));
|
|
182
|
+
const at = (file) => path.join(dir, file);
|
|
183
|
+
if (program === "npm" &&
|
|
184
|
+
(sub === "ci" || ((sub === "install" || sub === "i") && positional.length === 0))) {
|
|
185
|
+
out.push({ ecosystem: "npm", manager: "npm", file: at("package-lock.json") });
|
|
186
|
+
}
|
|
187
|
+
else if (program === "pnpm" &&
|
|
188
|
+
(sub === "install" || sub === "i") &&
|
|
189
|
+
positional.length === 0) {
|
|
190
|
+
out.push({ ecosystem: "npm", manager: "pnpm", file: at("pnpm-lock.yaml") });
|
|
191
|
+
}
|
|
192
|
+
else if (program === "yarn" &&
|
|
193
|
+
(sub === undefined || sub.startsWith("-") || (sub === "install" && positional.length === 0))) {
|
|
194
|
+
out.push({ ecosystem: "npm", manager: "yarn", file: at("yarn.lock") });
|
|
195
|
+
}
|
|
196
|
+
else if (program === "bun" && (sub === "install" || sub === "i") && positional.length === 0) {
|
|
197
|
+
out.push({ ecosystem: "npm", manager: "bun", file: at("bun.lock") });
|
|
198
|
+
}
|
|
199
|
+
else if (program === "uv" && sub === "sync") {
|
|
200
|
+
const resolves = rest.some((a) => a === "--upgrade" || a.startsWith("--upgrade-package") || a === "-U" || a === "-P");
|
|
201
|
+
out.push({ ecosystem: "PyPI", manager: "uv", file: at("uv.lock"), resolves });
|
|
202
|
+
}
|
|
203
|
+
else if (((program === "pip" || program === "pip3") && sub === "install") ||
|
|
204
|
+
(program === "uv" && sub === "pip" && (rest[0] === "install" || rest[0] === "sync"))) {
|
|
205
|
+
const args = program === "uv" ? rest.slice(1) : rest;
|
|
206
|
+
for (let i = 0; i < args.length; i++) {
|
|
207
|
+
const a = args[i] ?? "";
|
|
208
|
+
if ((a === "-r" || a === "--requirement") && args[i + 1]) {
|
|
209
|
+
out.push({
|
|
210
|
+
ecosystem: "PyPI",
|
|
211
|
+
manager: program === "uv" ? "uv" : "pip",
|
|
212
|
+
file: at(args[i + 1] ?? ""),
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
else if (a.startsWith("--requirement=")) {
|
|
216
|
+
out.push({ ecosystem: "PyPI", manager: "pip", file: at(a.slice(14)) });
|
|
217
|
+
}
|
|
218
|
+
else if (program === "uv" && rest[0] === "sync" && !a.startsWith("-")) {
|
|
219
|
+
out.push({ ecosystem: "PyPI", manager: "uv", file: at(a) });
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return out;
|
|
225
|
+
}
|
|
226
|
+
/** The line reader met a package-lock shape it can't read exactly. */
|
|
227
|
+
class UnsupportedLockShape extends Error {
|
|
228
|
+
}
|
|
229
|
+
/** Per-line parser for the line-oriented lockfile formats (state kept in the closure). */
|
|
230
|
+
function lineParser(base, add) {
|
|
231
|
+
if (base === "pnpm-lock.yaml") {
|
|
232
|
+
let inPackages = false;
|
|
233
|
+
return (line) => {
|
|
234
|
+
if (/^\S/.test(line))
|
|
235
|
+
inPackages = line === "packages:" || line === "snapshots:";
|
|
236
|
+
if (!inPackages)
|
|
237
|
+
return;
|
|
238
|
+
const m = /^ {2}'?\/?((?:@[^@/'\s]+\/)?[^@/'\s]+)@([^('\s:]+)/.exec(line);
|
|
239
|
+
if (m)
|
|
240
|
+
add(m[1] ?? "", m[2] ?? "");
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
if (base === "yarn.lock") {
|
|
244
|
+
let names = [];
|
|
245
|
+
return (line) => {
|
|
246
|
+
if (/^\S/.test(line) && line.endsWith(":")) {
|
|
247
|
+
names = line
|
|
248
|
+
.slice(0, -1)
|
|
249
|
+
.split(",")
|
|
250
|
+
.map((s) => s.trim().replace(/^"|"$/g, ""))
|
|
251
|
+
.map((s) => s.slice(0, s.indexOf("@", 1)))
|
|
252
|
+
.filter((s) => s.length > 0);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
const v = /^ {2}version:? "?([^"\s]+)"?/.exec(line);
|
|
256
|
+
if (v && names[0])
|
|
257
|
+
add(names[0], v[1] ?? "");
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
if (base === "bun.lock") {
|
|
261
|
+
return (line) => {
|
|
262
|
+
const m = /^\s*"[^"]+":\s*\[\s*"((?:@[^@/"]+\/)?[^@/"]+)@([^"]+)"/.exec(line);
|
|
263
|
+
if (m)
|
|
264
|
+
add(m[1] ?? "", m[2] ?? "");
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
if (base === "uv.lock") {
|
|
268
|
+
let name = "";
|
|
269
|
+
return (line) => {
|
|
270
|
+
if (line === "[[package]]")
|
|
271
|
+
name = "";
|
|
272
|
+
const n = /^name = "([^"]+)"/.exec(line);
|
|
273
|
+
if (n)
|
|
274
|
+
name = n[1] ?? "";
|
|
275
|
+
const v = /^version = "([^"]+)"/.exec(line);
|
|
276
|
+
if (v && name)
|
|
277
|
+
add(name.replace(/[._]+/g, "-"), v[1] ?? "");
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
if (base === "package-lock.json" || base === "npm-shrinkwrap.json") {
|
|
281
|
+
// Pretty-printed (2-space) package-lock, read line by line so a huge one
|
|
282
|
+
// never needs one long JSON.parse. Same answers as the JSON walk.
|
|
283
|
+
let section = "";
|
|
284
|
+
let key = null;
|
|
285
|
+
let fields = {};
|
|
286
|
+
return (line) => {
|
|
287
|
+
const top = /^ {2}"([^"]+)": \{/.exec(line);
|
|
288
|
+
if (top) {
|
|
289
|
+
section = top[1] ?? "";
|
|
290
|
+
key = null;
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
if (section !== "packages" && section !== "dependencies")
|
|
294
|
+
return;
|
|
295
|
+
const open = /^ {4}"((?:[^"\\]|\\.)*)": \{(\}?),?$/.exec(line);
|
|
296
|
+
// An entry line we don't fully recognise (hand-formatted, inline
|
|
297
|
+
// objects): let the caller fall back to the exact JSON walk.
|
|
298
|
+
if (!open && /^ {4}"/.test(line))
|
|
299
|
+
throw new UnsupportedLockShape();
|
|
300
|
+
if (open) {
|
|
301
|
+
key = open[1] ?? "";
|
|
302
|
+
fields = {};
|
|
303
|
+
if (!open[2])
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
else if (key !== null && /^ {4}\},?$/.test(line)) {
|
|
307
|
+
// close: fall through to emit
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
if (key === null)
|
|
311
|
+
return;
|
|
312
|
+
const f = /^ {6}"(version|name|link)": (?:"((?:[^"\\]|\\.)*)"|(true|false)),?$/.exec(line);
|
|
313
|
+
if (!f && /^ {6}"(?:version|name|link)"/.test(line))
|
|
314
|
+
throw new UnsupportedLockShape();
|
|
315
|
+
if (f?.[1] === "link")
|
|
316
|
+
fields.link = f[3] === "true";
|
|
317
|
+
else if (f?.[1] === "version")
|
|
318
|
+
fields.version = f[2];
|
|
319
|
+
else if (f?.[1] === "name")
|
|
320
|
+
fields.name = f[2];
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
const k = key ?? "";
|
|
324
|
+
key = null;
|
|
325
|
+
if (section === "dependencies") {
|
|
326
|
+
add(k, fields.version ?? "");
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
const idx = k.lastIndexOf("node_modules/");
|
|
330
|
+
if (idx < 0 || fields.link || !fields.version)
|
|
331
|
+
return;
|
|
332
|
+
add(fields.name ?? k.slice(idx + 13), fields.version);
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
// requirements file: only exact pins
|
|
336
|
+
return (line) => {
|
|
337
|
+
const m = /^\s*([A-Za-z0-9][A-Za-z0-9._-]*)(?:\[[^\]]*\])?\s*===?\s*([^\s;#,]+)/.exec(line);
|
|
338
|
+
if (m)
|
|
339
|
+
add((m[1] ?? "").replace(/[._]+/g, "-"), m[2] ?? "");
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
function lockedCollector() {
|
|
343
|
+
const out = new Map();
|
|
344
|
+
return {
|
|
345
|
+
out,
|
|
346
|
+
add: (name, version) => {
|
|
347
|
+
if (!name || !/^\d/.test(version))
|
|
348
|
+
return;
|
|
349
|
+
out.set(`${name}@${version}`, { name: name.toLowerCase(), version });
|
|
350
|
+
},
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
const stripBom = (raw) => (raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw);
|
|
354
|
+
const isNpmLock = (base) => base === "package-lock.json" || base === "npm-shrinkwrap.json";
|
|
355
|
+
/** A package-lock the line reader handles: 2-space pretty JSON that is complete. */
|
|
356
|
+
function npmLockByLines(text) {
|
|
357
|
+
return /^\{\r?\n {2}"/.test(text) && /\}\s*$/.test(text);
|
|
358
|
+
}
|
|
359
|
+
/** JSON walk of a package-lock (minified or odd indentation). */
|
|
360
|
+
function parseNpmLockJson(text, add) {
|
|
361
|
+
try {
|
|
362
|
+
const json = JSON.parse(text);
|
|
363
|
+
for (const [key, v] of Object.entries(json.packages ?? {})) {
|
|
364
|
+
const idx = key.lastIndexOf("node_modules/");
|
|
365
|
+
if (idx < 0 || v.link || !v.version)
|
|
366
|
+
continue;
|
|
367
|
+
add(v.name ?? key.slice(idx + 13), v.version);
|
|
368
|
+
}
|
|
369
|
+
for (const [name, v] of Object.entries(json.dependencies ?? {}))
|
|
370
|
+
add(name, v.version ?? "");
|
|
371
|
+
return true;
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
return false;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
/** Parse name@version pairs from a lockfile's text. Unknown shapes yield []. */
|
|
378
|
+
export function parseLockfile(file, raw) {
|
|
379
|
+
const text = stripBom(raw); // BOM (Windows editors)
|
|
380
|
+
const base = path.basename(file);
|
|
381
|
+
const { add, out } = lockedCollector();
|
|
382
|
+
if (isNpmLock(base))
|
|
383
|
+
return parseNpmLockJson(text, add) ? [...out.values()] : [];
|
|
384
|
+
const onLine = lineParser(base, add);
|
|
385
|
+
for (const line of text.split(/\r?\n/))
|
|
386
|
+
onLine(line);
|
|
387
|
+
return [...out.values()];
|
|
388
|
+
}
|
|
389
|
+
const SLICE_MS = 4;
|
|
390
|
+
const yieldToLoop = () => new Promise((resolve) => setImmediate(resolve));
|
|
391
|
+
/**
|
|
392
|
+
* `parseLockfile` for the event loop's sake: walks lines in slices of a few
|
|
393
|
+
* ms with a yield in between, so a 50k-entry lockfile never stalls the
|
|
394
|
+
* sidecar (shared by every app window). Same results.
|
|
395
|
+
*/
|
|
396
|
+
export async function parseLockfileAsync(file, raw) {
|
|
397
|
+
const text = stripBom(raw);
|
|
398
|
+
const base = path.basename(file);
|
|
399
|
+
const { add, out } = lockedCollector();
|
|
400
|
+
if (isNpmLock(base) && !npmLockByLines(text)) {
|
|
401
|
+
// Truncated (no closing brace) can't be valid JSON: skip the long parse.
|
|
402
|
+
if (!/\}\s*$/.test(text))
|
|
403
|
+
return [];
|
|
404
|
+
return parseNpmLockJson(text, add) ? [...out.values()] : [];
|
|
405
|
+
}
|
|
406
|
+
try {
|
|
407
|
+
await readLinesInSlices(text, lineParser(base, add));
|
|
408
|
+
}
|
|
409
|
+
catch (err) {
|
|
410
|
+
if (!(err instanceof UnsupportedLockShape))
|
|
411
|
+
throw err;
|
|
412
|
+
const exact = lockedCollector();
|
|
413
|
+
return parseNpmLockJson(text, exact.add) ? [...exact.out.values()] : [];
|
|
414
|
+
}
|
|
415
|
+
return [...out.values()];
|
|
416
|
+
}
|
|
417
|
+
/** Feed `text` line by line to `onLine`, yielding to the event loop every few ms. */
|
|
418
|
+
async function readLinesInSlices(text, onLine) {
|
|
419
|
+
let start = 0;
|
|
420
|
+
let sliceAt = performance.now();
|
|
421
|
+
let n = 0;
|
|
422
|
+
while (start <= text.length) {
|
|
423
|
+
const nl = text.indexOf("\n", start);
|
|
424
|
+
const end = nl < 0 ? text.length : nl;
|
|
425
|
+
const line = text.slice(start, end > start && text.charCodeAt(end - 1) === 13 ? end - 1 : end);
|
|
426
|
+
onLine(line);
|
|
427
|
+
start = end + 1;
|
|
428
|
+
if (++n % 128 === 0 && performance.now() - sliceAt > SLICE_MS) {
|
|
429
|
+
await yieldToLoop();
|
|
430
|
+
sliceAt = performance.now();
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
/** sha256 of a big text in slices with yields (hashing 13 MB at once is ~20 ms). */
|
|
435
|
+
async function hashInSlices(text) {
|
|
436
|
+
const h = createHash("sha256");
|
|
437
|
+
const step = 1 << 20;
|
|
438
|
+
for (let i = 0; i < text.length; i += step) {
|
|
439
|
+
h.update(text.slice(i, i + step));
|
|
440
|
+
if (i + step < text.length)
|
|
441
|
+
await yieldToLoop();
|
|
442
|
+
}
|
|
443
|
+
return h.digest("hex");
|
|
444
|
+
}
|
|
445
|
+
// ── Typosquat (local candidate) ──────────────────────────
|
|
75
446
|
/** Optimal-string-alignment Damerau-Levenshtein distance. */
|
|
76
447
|
export function damerauLevenshtein(a, b) {
|
|
77
448
|
const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
|
|
@@ -91,78 +462,739 @@ export function damerauLevenshtein(a, b) {
|
|
|
91
462
|
}
|
|
92
463
|
return at(a.length, b.length);
|
|
93
464
|
}
|
|
94
|
-
|
|
465
|
+
const popularSets = {
|
|
466
|
+
npm: new Set(POPULAR_NPM_PACKAGES),
|
|
467
|
+
PyPI: new Set(POPULAR_PYPI_PACKAGES),
|
|
468
|
+
};
|
|
469
|
+
/** The popular name `ref` is one edit away from, or null. Local only. */
|
|
470
|
+
export function typosquatCandidate(ref) {
|
|
95
471
|
const popular = ref.ecosystem === "npm" ? POPULAR_NPM_PACKAGES : POPULAR_PYPI_PACKAGES;
|
|
96
|
-
if (
|
|
472
|
+
if (popularSets[ref.ecosystem].has(ref.name))
|
|
97
473
|
return null;
|
|
98
474
|
return (popular.find((p) => Math.abs(p.length - ref.name.length) <= 1 && damerauLevenshtein(p, ref.name) === 1) ?? null);
|
|
99
475
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
osvCache.set(key(r), ids);
|
|
125
|
-
});
|
|
476
|
+
function isExact(spec) {
|
|
477
|
+
return spec !== undefined && /^v?\d+(?:\.\d+)*(?:[-.+][0-9A-Za-z.-]+)?$/.test(spec);
|
|
478
|
+
}
|
|
479
|
+
function label(ref, version) {
|
|
480
|
+
return version ? `${ref.name}@${version}` : ref.name;
|
|
481
|
+
}
|
|
482
|
+
/** Instant part of the check: parsing, typosquat candidates and local feed hits. */
|
|
483
|
+
export function localPackageCheck(command, feedOrLoad) {
|
|
484
|
+
const refs = parsePackageInstalls(command);
|
|
485
|
+
const lockfiles = refs.length === 0 ? parseLockfileInstalls(command) : [];
|
|
486
|
+
if (refs.length === 0 && lockfiles.length === 0) {
|
|
487
|
+
return { refs, lockfiles, threats: [], typosquats: [], flagged: new Set(), feed: emptyFeed() };
|
|
488
|
+
}
|
|
489
|
+
const feed = typeof feedOrLoad === "function" ? feedOrLoad() : feedOrLoad;
|
|
490
|
+
const threats = [];
|
|
491
|
+
const typosquats = [];
|
|
492
|
+
const flagged = new Set();
|
|
493
|
+
for (const ref of refs) {
|
|
494
|
+
const version = isExact(ref.spec) ? ref.spec.replace(/^v/, "") : undefined;
|
|
495
|
+
const ids = feedMatches(feed, ref.ecosystem, ref.name, version);
|
|
496
|
+
if (ids.length > 0) {
|
|
497
|
+
threats.push(malwareThreat(ref, version, ids, null, 0));
|
|
498
|
+
flagged.add(ref.name);
|
|
499
|
+
continue;
|
|
126
500
|
}
|
|
127
|
-
|
|
128
|
-
|
|
501
|
+
const popular = typosquatCandidate(ref);
|
|
502
|
+
if (popular)
|
|
503
|
+
typosquats.push({ ref, popular });
|
|
504
|
+
}
|
|
505
|
+
return { refs, lockfiles, threats, typosquats, flagged, feed };
|
|
506
|
+
}
|
|
507
|
+
function malwareThreat(ref, version, ids, safe, days) {
|
|
508
|
+
const instead = safe
|
|
509
|
+
? `use ${ref.name}@${safe}, the last version older than ${days} days`
|
|
510
|
+
: "pick a different version or package";
|
|
511
|
+
return {
|
|
512
|
+
rule: "malicious-package",
|
|
513
|
+
severity: "block",
|
|
514
|
+
detail: `${label(ref, version)} is flagged as malware (${ids.join(", ")}); ${instead}.`,
|
|
515
|
+
blocked: [
|
|
516
|
+
{
|
|
517
|
+
ecosystem: ref.ecosystem,
|
|
518
|
+
name: ref.name,
|
|
519
|
+
...(version ? { version } : {}),
|
|
520
|
+
reason: `known malware (${ids.join(", ")})`,
|
|
521
|
+
},
|
|
522
|
+
],
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
class NotFound {
|
|
526
|
+
}
|
|
527
|
+
async function getJson(url, ctx, headers = {}) {
|
|
528
|
+
const key = `${headers.accept ?? ""} ${url}`;
|
|
529
|
+
let hit = metaCache.get(key);
|
|
530
|
+
if (!hit) {
|
|
531
|
+
hit = fetchJson(url, { headers }, ctx, true);
|
|
532
|
+
metaCache.set(key, hit);
|
|
533
|
+
// A failed fetch should be retried next install, not cached.
|
|
534
|
+
hit.catch(() => metaCache.delete(key));
|
|
535
|
+
}
|
|
536
|
+
return hit;
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Hosts that just failed or stalled: skipped (fail-open, instantly) for a
|
|
540
|
+
* short while so an offline machine or a hung registry costs the deadline
|
|
541
|
+
* once, not on every install.
|
|
542
|
+
*/
|
|
543
|
+
const downHosts = new Map();
|
|
544
|
+
const DOWN_MS = 2 * 60_000;
|
|
545
|
+
/** Key for "nothing answered before the deadline" (offline, dead proxy): every host waits. */
|
|
546
|
+
const ALL_HOSTS = "*";
|
|
547
|
+
/** After a deadline cut: if no host answered at all, the network itself is down for a while. */
|
|
548
|
+
function noteDeadline(ctx) {
|
|
549
|
+
if (!ctx.cancelled() && !ctx.reached.value)
|
|
550
|
+
downHosts.set(ALL_HOSTS, Date.now() + DOWN_MS);
|
|
551
|
+
}
|
|
552
|
+
function hostOf(url) {
|
|
553
|
+
try {
|
|
554
|
+
return new URL(url).host;
|
|
555
|
+
}
|
|
556
|
+
catch {
|
|
557
|
+
return url;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
/** fetch + status + JSON, honouring and feeding the down-host memory. 404 → NotFound when asked. */
|
|
561
|
+
async function fetchJson(url, init, ctx, notFound = false) {
|
|
562
|
+
const host = hostOf(url);
|
|
563
|
+
const down = Math.max(downHosts.get(host) ?? 0, downHosts.get(ALL_HOSTS) ?? 0);
|
|
564
|
+
if (Date.now() < down)
|
|
565
|
+
throw new Error(`${host} recently unreachable`);
|
|
566
|
+
try {
|
|
567
|
+
// Raced with the signal too: a fetch that ignores aborts must not hang us.
|
|
568
|
+
return await Promise.race([
|
|
569
|
+
(async () => {
|
|
570
|
+
const res = await ctx.fetch(url, { ...init, signal: ctx.signal });
|
|
571
|
+
if (res.status < 500)
|
|
572
|
+
ctx.reached.value = true;
|
|
573
|
+
if (notFound && res.status === 404)
|
|
574
|
+
return new NotFound();
|
|
575
|
+
if (!res.ok)
|
|
576
|
+
throw new Error(`HTTP ${res.status} for ${url}`);
|
|
577
|
+
return res.json();
|
|
578
|
+
})(),
|
|
579
|
+
deadline(ctx.signal),
|
|
580
|
+
]);
|
|
581
|
+
}
|
|
582
|
+
catch (err) {
|
|
583
|
+
// A cancel by the caller says nothing about the host; a network error,
|
|
584
|
+
// 4xx other than 404 (429, proxy 403/407), 5xx, bad JSON or our deadline does.
|
|
585
|
+
if (!ctx.cancelled())
|
|
586
|
+
downHosts.set(host, Date.now() + DOWN_MS);
|
|
587
|
+
throw err;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
const enc = (name) => name.replace("/", "%2F");
|
|
591
|
+
/** Abbreviated packument (no publish times); the full one only when times are needed. */
|
|
592
|
+
function npmDoc(name, full, ctx) {
|
|
593
|
+
const accept = full ? "application/json" : "application/vnd.npm.install-v1+json";
|
|
594
|
+
// A full doc already fetched answers abbreviated questions too.
|
|
595
|
+
const fullKey = `application/json ${NPM_REGISTRY}/${enc(name)}`;
|
|
596
|
+
if (!full && metaCache.has(fullKey))
|
|
597
|
+
return getJson(`${NPM_REGISTRY}/${enc(name)}`, ctx, { accept: "application/json" });
|
|
598
|
+
return getJson(`${NPM_REGISTRY}/${enc(name)}`, ctx, { accept });
|
|
599
|
+
}
|
|
600
|
+
function pypiDoc(name, ctx) {
|
|
601
|
+
return getJson(`${PYPI}/${name}/json`, ctx);
|
|
602
|
+
}
|
|
603
|
+
function isStable(v) {
|
|
604
|
+
return /^\d+(?:\.\d+)*$/.test(v);
|
|
605
|
+
}
|
|
606
|
+
/** Highest version satisfying a simple npm range (exact, ^, ~, x, >=). Null if unsupported. */
|
|
607
|
+
function maxSatisfying(versions, range) {
|
|
608
|
+
const r = range.trim();
|
|
609
|
+
const m = /^(\^|~|>=)?\s*v?(\d+)(?:\.(\d+|x|\*))?(?:\.(\d+|x|\*))?$/.exec(r);
|
|
610
|
+
if (r === "*" || r === "x" || r === "")
|
|
611
|
+
return pickMax(versions.filter(isStable));
|
|
612
|
+
if (!m)
|
|
613
|
+
return null;
|
|
614
|
+
const op = m[1] ?? "";
|
|
615
|
+
const nums = [m[2], m[3], m[4]].map((n) => n === undefined || n === "x" || n === "*" ? null : Number(n));
|
|
616
|
+
const [maj, min, pat] = nums;
|
|
617
|
+
const ok = (v) => {
|
|
618
|
+
if (!isStable(v))
|
|
619
|
+
return false;
|
|
620
|
+
const [a = 0, b = 0, c = 0] = v.split(".").map(Number);
|
|
621
|
+
const lo = `${maj ?? 0}.${min ?? 0}.${pat ?? 0}`;
|
|
622
|
+
if (compareVersions(v, lo) < 0)
|
|
623
|
+
return false;
|
|
624
|
+
if (op === ">=")
|
|
625
|
+
return true;
|
|
626
|
+
if (op === "^") {
|
|
627
|
+
if ((maj ?? 0) > 0)
|
|
628
|
+
return a === maj;
|
|
629
|
+
if ((min ?? 0) > 0)
|
|
630
|
+
return a === 0 && b === min;
|
|
631
|
+
return a === 0 && b === 0 && (pat === null || c === pat);
|
|
129
632
|
}
|
|
633
|
+
if (op === "~")
|
|
634
|
+
return a === maj && (min === null || b === min);
|
|
635
|
+
return a === maj && (min === null || b === min) && (pat === null || c === pat);
|
|
636
|
+
};
|
|
637
|
+
return pickMax(versions.filter(ok));
|
|
638
|
+
}
|
|
639
|
+
function pickMax(versions) {
|
|
640
|
+
let best = null;
|
|
641
|
+
for (const v of versions)
|
|
642
|
+
if (best === null || compareVersions(v, best) > 0)
|
|
643
|
+
best = v;
|
|
644
|
+
return best;
|
|
645
|
+
}
|
|
646
|
+
async function resolveRef(ref, full, ctx) {
|
|
647
|
+
if (ref.ecosystem === "npm") {
|
|
648
|
+
const doc = await npmDoc(ref.name, full, ctx);
|
|
649
|
+
if (doc instanceof NotFound)
|
|
650
|
+
return { ref, version: null, missing: true };
|
|
651
|
+
const npm = doc;
|
|
652
|
+
const tags = npm["dist-tags"] ?? {};
|
|
653
|
+
const all = Object.keys(npm.versions ?? {});
|
|
654
|
+
let version;
|
|
655
|
+
if (ref.spec === undefined)
|
|
656
|
+
version = tags.latest ?? null;
|
|
657
|
+
else if (tags[ref.spec])
|
|
658
|
+
version = tags[ref.spec] ?? null;
|
|
659
|
+
else if (isExact(ref.spec))
|
|
660
|
+
version = ref.spec.replace(/^v/, "");
|
|
661
|
+
else
|
|
662
|
+
version = maxSatisfying(all, ref.spec);
|
|
663
|
+
return { ref, version, missing: false, npm, full: npm.time !== undefined };
|
|
130
664
|
}
|
|
665
|
+
const doc = await pypiDoc(ref.name, ctx);
|
|
666
|
+
if (doc instanceof NotFound)
|
|
667
|
+
return { ref, version: null, missing: true };
|
|
668
|
+
const pypi = doc;
|
|
669
|
+
const version = ref.spec === undefined ? (pypi.info?.version ?? null) : isExact(ref.spec) ? ref.spec : null;
|
|
670
|
+
return { ref, version, missing: false, pypi };
|
|
671
|
+
}
|
|
672
|
+
/** Publish time (ms) per version. npm needs the full packument (fetched only when required). */
|
|
673
|
+
async function publishTimes(r, ctx) {
|
|
131
674
|
const out = new Map();
|
|
132
|
-
|
|
133
|
-
const
|
|
675
|
+
if (r.ref.ecosystem === "npm") {
|
|
676
|
+
const full = r.full ? r.npm : await npmDoc(r.ref.name, true, ctx);
|
|
677
|
+
if (!full || full instanceof NotFound)
|
|
678
|
+
return out;
|
|
679
|
+
for (const [v, t] of Object.entries(full.time ?? {})) {
|
|
680
|
+
if (v === "created" || v === "modified")
|
|
681
|
+
continue;
|
|
682
|
+
out.set(v, Date.parse(t));
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
else {
|
|
686
|
+
for (const [v, files] of Object.entries(r.pypi?.releases ?? {})) {
|
|
687
|
+
const times = files
|
|
688
|
+
.filter((f) => !f.yanked)
|
|
689
|
+
.map((f) => Date.parse(f.upload_time_iso_8601 ?? ""))
|
|
690
|
+
.filter((t) => !Number.isNaN(t));
|
|
691
|
+
if (times.length > 0)
|
|
692
|
+
out.set(v, Math.min(...times));
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
return out;
|
|
696
|
+
}
|
|
697
|
+
/** Newest stable version published before the cutoff, skipping `bad`. */
|
|
698
|
+
/** The compatible release line of a version, as `^` reads it: `5` for 5.6.1, `0.30` for 0.30.4. */
|
|
699
|
+
function releaseLine(version) {
|
|
700
|
+
const [major = "", minor = ""] = version.replace(/^v/, "").split(".");
|
|
701
|
+
return major === "0" ? `0.${minor}` : major;
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* The version to suggest instead: the newest stable release older than
|
|
705
|
+
* `cutoff`, not in `bad`, preferring the same release line as `near` so the
|
|
706
|
+
* agent isn't steered into a breaking major upgrade. Falls back to any line.
|
|
707
|
+
*/
|
|
708
|
+
function lastOlderThan(times, cutoff, bad, near) {
|
|
709
|
+
const ok = [...times]
|
|
710
|
+
.filter(([v, t]) => t <= cutoff && isStable(v) && !bad.has(v))
|
|
711
|
+
.map(([v]) => v);
|
|
712
|
+
if (near) {
|
|
713
|
+
const line = releaseLine(near);
|
|
714
|
+
const same = pickMax(ok.filter((v) => releaseLine(v) === line));
|
|
715
|
+
if (same)
|
|
716
|
+
return same;
|
|
717
|
+
}
|
|
718
|
+
return pickMax(ok);
|
|
719
|
+
}
|
|
720
|
+
/** Versions of a package the local feed flags, so a suggestion never names one. */
|
|
721
|
+
function feedFlagged(ctx, ref, versions) {
|
|
722
|
+
const out = new Set();
|
|
723
|
+
for (const v of versions) {
|
|
724
|
+
if (feedMatches(ctx.feed, ref.ecosystem, ref.name, v).length > 0)
|
|
725
|
+
out.add(v);
|
|
726
|
+
}
|
|
727
|
+
return out;
|
|
728
|
+
}
|
|
729
|
+
const VERDICT_FILE = "package-verdicts.json";
|
|
730
|
+
const OSV_TTL_MS = DAY_MS;
|
|
731
|
+
const MAX_LOCKS = 50;
|
|
732
|
+
class VerdictCache {
|
|
733
|
+
file;
|
|
734
|
+
data = { osvClean: {}, locks: {} };
|
|
735
|
+
loaded = null;
|
|
736
|
+
saving = Promise.resolve();
|
|
737
|
+
dirty = false;
|
|
738
|
+
constructor(file) {
|
|
739
|
+
this.file = file;
|
|
740
|
+
}
|
|
741
|
+
load() {
|
|
742
|
+
if (!this.loaded) {
|
|
743
|
+
this.loaded = this.file
|
|
744
|
+
? fsp
|
|
745
|
+
.readFile(this.file, "utf8")
|
|
746
|
+
.then((text) => {
|
|
747
|
+
const raw = JSON.parse(text);
|
|
748
|
+
this.data = { osvClean: raw.osvClean ?? {}, locks: raw.locks ?? {} };
|
|
749
|
+
})
|
|
750
|
+
.catch(() => undefined)
|
|
751
|
+
: Promise.resolve();
|
|
752
|
+
}
|
|
753
|
+
return this.loaded;
|
|
754
|
+
}
|
|
755
|
+
osvFresh(key, now) {
|
|
756
|
+
const at = this.data.osvClean[key];
|
|
757
|
+
return at !== undefined && now - at < OSV_TTL_MS;
|
|
758
|
+
}
|
|
759
|
+
markClean(key, now) {
|
|
760
|
+
this.data.osvClean[key] = now;
|
|
761
|
+
this.dirty = true;
|
|
762
|
+
}
|
|
763
|
+
lock(key) {
|
|
764
|
+
return this.data.locks[key];
|
|
765
|
+
}
|
|
766
|
+
setLock(key, v) {
|
|
767
|
+
this.data.locks[key] = v;
|
|
768
|
+
this.dirty = true;
|
|
769
|
+
}
|
|
770
|
+
/** Write in the background (atomic rename); never on the caller's critical path. */
|
|
771
|
+
save(now) {
|
|
772
|
+
if (!this.file || !this.dirty)
|
|
773
|
+
return;
|
|
774
|
+
this.dirty = false;
|
|
775
|
+
const file = this.file;
|
|
776
|
+
this.saving = this.saving.then(async () => {
|
|
777
|
+
const osvClean = Object.fromEntries(Object.entries(this.data.osvClean).filter(([, at]) => now - at < OSV_TTL_MS));
|
|
778
|
+
const locks = Object.fromEntries(Object.entries(this.data.locks)
|
|
779
|
+
.sort(([, a], [, b]) => b.at - a.at)
|
|
780
|
+
.slice(0, MAX_LOCKS));
|
|
781
|
+
this.data = { osvClean, locks };
|
|
782
|
+
try {
|
|
783
|
+
await writeJsonAtomic(file, this.data);
|
|
784
|
+
}
|
|
785
|
+
catch (err) {
|
|
786
|
+
log("WARN", "package-threats", `verdict cache write failed: ${String(err)}`);
|
|
787
|
+
}
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
flush() {
|
|
791
|
+
return this.saving;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
const verdictCaches = new Map();
|
|
795
|
+
function verdictCache(dir) {
|
|
796
|
+
const file = dir === null ? null : path.join(dir, VERDICT_FILE);
|
|
797
|
+
const key = file ?? "";
|
|
798
|
+
let hit = verdictCaches.get(key);
|
|
799
|
+
if (!hit) {
|
|
800
|
+
hit = new VerdictCache(file);
|
|
801
|
+
verdictCaches.set(key, hit);
|
|
802
|
+
}
|
|
803
|
+
return hit;
|
|
804
|
+
}
|
|
805
|
+
const osvKey = (i) => `${i.ecosystem}:${i.name}@${i.version}`;
|
|
806
|
+
/** MAL- IDs per `eco:name@version`, one request per 1000 queries, cached (memory + disk). */
|
|
807
|
+
/** A remembered OSV answer still holds: malware stays malware; "clean" is re-asked daily. */
|
|
808
|
+
function osvKnown(key, now) {
|
|
809
|
+
const hit = osvCache.get(key);
|
|
810
|
+
if (!hit)
|
|
811
|
+
return false;
|
|
812
|
+
return hit.ids.length > 0 || now - hit.at < OSV_TTL_MS;
|
|
813
|
+
}
|
|
814
|
+
async function osvMalware(items, ctx) {
|
|
815
|
+
const pending = [
|
|
816
|
+
...new Map(items
|
|
817
|
+
.filter((i) => !osvKnown(osvKey(i), ctx.now) && !ctx.cache.osvFresh(osvKey(i), ctx.now))
|
|
818
|
+
.map((i) => [osvKey(i), i])).values(),
|
|
819
|
+
];
|
|
820
|
+
for (let start = 0; start < pending.length; start += OSV_BATCH) {
|
|
821
|
+
const batch = pending.slice(start, start + OSV_BATCH);
|
|
822
|
+
const body = (await fetchJson(OSV_URL, {
|
|
823
|
+
method: "POST",
|
|
824
|
+
headers: { "content-type": "application/json" },
|
|
825
|
+
body: JSON.stringify({
|
|
826
|
+
queries: batch.map((i) => ({
|
|
827
|
+
package: { ecosystem: i.ecosystem, name: i.name },
|
|
828
|
+
version: i.version,
|
|
829
|
+
})),
|
|
830
|
+
}),
|
|
831
|
+
}, ctx));
|
|
832
|
+
batch.forEach((item, i) => {
|
|
833
|
+
const ids = (body.results?.[i]?.vulns ?? [])
|
|
834
|
+
.map((v) => v.id ?? "")
|
|
835
|
+
.filter((id) => id.startsWith("MAL-"));
|
|
836
|
+
osvCache.set(osvKey(item), { ids, at: ctx.now });
|
|
837
|
+
if (ids.length === 0)
|
|
838
|
+
ctx.cache.markClean(osvKey(item), ctx.now);
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
const out = new Map();
|
|
842
|
+
for (const i of items) {
|
|
843
|
+
const ids = osvCache.get(osvKey(i))?.ids;
|
|
134
844
|
if (ids && ids.length > 0)
|
|
135
|
-
out.set(
|
|
845
|
+
out.set(osvKey(i), ids);
|
|
136
846
|
}
|
|
137
847
|
return out;
|
|
138
848
|
}
|
|
139
|
-
/**
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
849
|
+
/** Swallow network failures: the guard is fail-open (the cooldown still applies). */
|
|
850
|
+
async function safe(what, fn) {
|
|
851
|
+
try {
|
|
852
|
+
return await fn();
|
|
853
|
+
}
|
|
854
|
+
catch (err) {
|
|
855
|
+
log("WARN", "package-threats", `${what} failed, allowing: ${String(err)}`);
|
|
856
|
+
return null;
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
function resolvedItem(r) {
|
|
860
|
+
return { ecosystem: r.ref.ecosystem, name: r.ref.name, version: r.version ?? "" };
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* Named installs. Everything independent runs at once, so a clean install
|
|
864
|
+
* costs one registry round trip (+ one OSV round trip for unpinned refs whose
|
|
865
|
+
* version isn't known until the registry answers):
|
|
866
|
+
* - registry docs for every ref (full packument only for typosquat
|
|
867
|
+
* candidates; abbreviated otherwise),
|
|
868
|
+
* - OSV for exactly pinned refs, concurrently with the registry,
|
|
869
|
+
* - weekly downloads for npm typosquat candidates,
|
|
870
|
+
* - the manager version (native cooldown?) — spawned once per process.
|
|
871
|
+
*/
|
|
872
|
+
async function checkNamed(local, ctx) {
|
|
144
873
|
const threats = [];
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
874
|
+
const refs = local.refs.filter((r) => !local.flagged.has(r.name));
|
|
875
|
+
const squats = new Map(local.typosquats.map((t) => [t.ref.name, t.popular]));
|
|
876
|
+
const native = new Map();
|
|
877
|
+
for (const r of refs) {
|
|
878
|
+
if (!native.has(r.manager))
|
|
879
|
+
native.set(r.manager, nativeCooldown(r.manager, ctx));
|
|
880
|
+
}
|
|
881
|
+
const pinned = refs
|
|
882
|
+
.filter((r) => isExact(r.spec))
|
|
883
|
+
.map((r) => ({
|
|
884
|
+
ecosystem: r.ecosystem,
|
|
885
|
+
name: r.name,
|
|
886
|
+
version: (r.spec ?? "").replace(/^v/, ""),
|
|
887
|
+
}));
|
|
888
|
+
const earlyOsv = pinned.length > 0 ? safe("OSV lookup", () => osvMalware(pinned, ctx)) : null;
|
|
889
|
+
const downloads = new Map(refs
|
|
890
|
+
.filter((r) => r.ecosystem === "npm" && squats.has(r.name))
|
|
891
|
+
.map((r) => [
|
|
892
|
+
r.name,
|
|
893
|
+
safe(`downloads ${r.name}`, () => getJson(`${NPM_DOWNLOADS}/${r.name}`, ctx)),
|
|
894
|
+
]));
|
|
895
|
+
const resolved = (await Promise.all(refs.map((r) => safe(`lookup ${r.name}`, () => resolveRef(r, squats.has(r.name), ctx))))).filter((r) => r !== null);
|
|
896
|
+
// P5: typosquat → block only if missing, new or barely used.
|
|
897
|
+
const squatted = new Set();
|
|
898
|
+
for (const r of resolved) {
|
|
899
|
+
const popular = squats.get(r.ref.name);
|
|
900
|
+
if (!popular)
|
|
901
|
+
continue;
|
|
902
|
+
const reason = await safe(`typosquat ${r.ref.name}`, () => typosquatReason(r, downloads.get(r.ref.name) ?? Promise.resolve(null), ctx));
|
|
903
|
+
if (reason) {
|
|
904
|
+
squatted.add(r.ref.name);
|
|
148
905
|
threats.push({
|
|
149
906
|
rule: "typosquat",
|
|
150
|
-
severity: "
|
|
151
|
-
detail: `${
|
|
907
|
+
severity: "block",
|
|
908
|
+
detail: `${r.ref.name} looks like a typosquat of popular "${popular}" (${reason}); use ${popular} if that is what you meant.`,
|
|
909
|
+
blocked: [
|
|
910
|
+
{ ecosystem: r.ref.ecosystem, name: r.ref.name, reason: `lookalike of "${popular}"` },
|
|
911
|
+
],
|
|
152
912
|
});
|
|
153
913
|
}
|
|
154
914
|
}
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
915
|
+
const live = resolved.filter((r) => !r.missing && r.version !== null && !squatted.has(r.ref.name));
|
|
916
|
+
// Malware: local feed with the resolved version, then OSV with exact versions.
|
|
917
|
+
const pinnedKeys = new Set(pinned.map(osvKey));
|
|
918
|
+
const late = live.map(resolvedItem).filter((i) => !pinnedKeys.has(osvKey(i)));
|
|
919
|
+
const [early, rest] = await Promise.all([
|
|
920
|
+
earlyOsv,
|
|
921
|
+
late.length > 0 ? safe("OSV lookup", () => osvMalware(late, ctx)) : null,
|
|
922
|
+
]);
|
|
923
|
+
const osv = new Map([...(early ?? []), ...(rest ?? [])]);
|
|
924
|
+
const malware = new Set();
|
|
925
|
+
for (const r of live) {
|
|
926
|
+
const version = r.version ?? "";
|
|
927
|
+
const ids = [
|
|
928
|
+
...new Set([
|
|
929
|
+
...feedMatches(ctx.feed, r.ref.ecosystem, r.ref.name, version),
|
|
930
|
+
...(osv.get(osvKey(resolvedItem(r))) ?? []),
|
|
931
|
+
]),
|
|
932
|
+
];
|
|
933
|
+
if (ids.length === 0)
|
|
934
|
+
continue;
|
|
935
|
+
malware.add(r.ref.name);
|
|
936
|
+
const times = (await safe("publish times", () => publishTimes(r, ctx))) ?? new Map();
|
|
937
|
+
const cutoff = ctx.now - Math.max(ctx.days, 0) * DAY_MS;
|
|
938
|
+
const bad = feedFlagged(ctx, r.ref, times.keys()).add(version);
|
|
939
|
+
const suggestion = lastOlderThan(times, cutoff, bad, version);
|
|
940
|
+
threats.push(malwareThreat(r.ref, version, ids, suggestion, ctx.days));
|
|
941
|
+
}
|
|
942
|
+
for (const r of live) {
|
|
943
|
+
if (malware.has(r.ref.name))
|
|
944
|
+
continue;
|
|
945
|
+
const version = r.version ?? "";
|
|
946
|
+
// P4: provenance downgrade (npm).
|
|
947
|
+
if (r.npm?.versions) {
|
|
948
|
+
const all = Object.keys(r.npm.versions);
|
|
949
|
+
const prev = pickMax(all.filter((v) => isStable(v) && compareVersions(v, version) < 0));
|
|
950
|
+
const had = prev ? r.npm.versions[prev]?.dist?.attestations : undefined;
|
|
951
|
+
const has = r.npm.versions[version]?.dist?.attestations;
|
|
952
|
+
if (prev && had && !has && r.npm.versions[version]) {
|
|
953
|
+
threats.push({
|
|
954
|
+
rule: "provenance-downgrade",
|
|
955
|
+
severity: "block",
|
|
956
|
+
detail: `${r.ref.name}@${version} was published without the provenance attestation ${r.ref.name}@${prev} had (a hijacked-release signal); use ${r.ref.name}@${prev}.`,
|
|
957
|
+
blocked: [
|
|
958
|
+
{
|
|
959
|
+
ecosystem: r.ref.ecosystem,
|
|
960
|
+
name: r.ref.name,
|
|
961
|
+
version,
|
|
962
|
+
reason: "published without its usual signature (likely hijacked)",
|
|
963
|
+
},
|
|
964
|
+
],
|
|
965
|
+
});
|
|
966
|
+
continue;
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
// P3: own release-age check only when the manager can't enforce the cooldown.
|
|
970
|
+
if (ctx.days > 0 && !(await (native.get(r.ref.manager) ?? Promise.resolve(true)))) {
|
|
971
|
+
const times = (await safe("publish times", () => publishTimes(r, ctx))) ?? new Map();
|
|
972
|
+
const published = times.get(version);
|
|
973
|
+
const cutoff = ctx.now - ctx.days * DAY_MS;
|
|
974
|
+
if (published !== undefined && published > cutoff) {
|
|
975
|
+
const older = lastOlderThan(times, cutoff, feedFlagged(ctx, r.ref, times.keys()), version);
|
|
976
|
+
const hours = Math.max(1, Math.round((ctx.now - published) / 3_600_000));
|
|
977
|
+
const instead = older
|
|
978
|
+
? `use ${r.ref.name}@${older}, the last version older than ${ctx.days} days`
|
|
979
|
+
: `wait until it is ${ctx.days} days old`;
|
|
980
|
+
threats.push({
|
|
981
|
+
rule: "release-age",
|
|
982
|
+
severity: "block",
|
|
983
|
+
detail: `${r.ref.name}@${version} was published ${hours}h ago (cooldown ${ctx.days} days); ${instead}.`,
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
}
|
|
161
987
|
}
|
|
162
988
|
return threats;
|
|
163
989
|
}
|
|
164
|
-
|
|
990
|
+
async function nativeCooldown(manager, ctx) {
|
|
991
|
+
const m = manager === "npx" ? "npm" : manager === "uvx" ? "uv" : manager;
|
|
992
|
+
if (m === "uv")
|
|
993
|
+
return true;
|
|
994
|
+
return hasNativeCooldown(m, await ctx.managerVersion(m));
|
|
995
|
+
}
|
|
996
|
+
async function typosquatReason(r, downloads, ctx) {
|
|
997
|
+
if (r.missing)
|
|
998
|
+
return ctx.privateSource(r.ref.ecosystem) ? null : "it does not exist on the registry";
|
|
999
|
+
const times = await publishTimes(r, ctx);
|
|
1000
|
+
const first = Math.min(...times.values());
|
|
1001
|
+
if (Number.isFinite(first) && ctx.now - first < TYPOSQUAT_NEW_DAYS * DAY_MS) {
|
|
1002
|
+
return `first published ${Math.max(0, Math.floor((ctx.now - first) / DAY_MS))} days ago`;
|
|
1003
|
+
}
|
|
1004
|
+
const dl = (await downloads);
|
|
1005
|
+
if (dl &&
|
|
1006
|
+
!(dl instanceof NotFound) &&
|
|
1007
|
+
typeof dl.downloads === "number" &&
|
|
1008
|
+
dl.downloads < TYPOSQUAT_MIN_WEEKLY) {
|
|
1009
|
+
return `only ${dl.downloads} downloads last week`;
|
|
1010
|
+
}
|
|
1011
|
+
return null;
|
|
1012
|
+
}
|
|
1013
|
+
async function checkLockfile(lock, cwd, ctx) {
|
|
1014
|
+
const file = path.resolve(cwd, lock.file);
|
|
1015
|
+
let text;
|
|
1016
|
+
try {
|
|
1017
|
+
text = await fsp.readFile(file, "utf8");
|
|
1018
|
+
}
|
|
1019
|
+
catch {
|
|
1020
|
+
return [];
|
|
1021
|
+
}
|
|
1022
|
+
const hash = await hashInSlices(text);
|
|
1023
|
+
const cacheKey = `${lock.ecosystem}:${hash}:${Object.keys(ctx.feed.entries).length}`;
|
|
1024
|
+
const remembered = lockfileCache.get(cacheKey) ?? ctx.cache.lock(cacheKey);
|
|
1025
|
+
// A lockfile verdict is re-asked of OSV at most once a day, so a package
|
|
1026
|
+
// flagged after the last check is still caught even if the feed is unchanged.
|
|
1027
|
+
const cached = remembered && ctx.now - remembered.at < DAY_MS ? remembered : undefined;
|
|
1028
|
+
if (cached) {
|
|
1029
|
+
lockfileCache.set(cacheKey, cached);
|
|
1030
|
+
return cached.threats;
|
|
1031
|
+
}
|
|
1032
|
+
const pkgs = await parseLockfileAsync(file, text);
|
|
1033
|
+
const hits = new Map();
|
|
1034
|
+
for (const p of pkgs) {
|
|
1035
|
+
const ids = feedMatches(ctx.feed, lock.ecosystem, p.name, p.version);
|
|
1036
|
+
if (ids.length > 0)
|
|
1037
|
+
hits.set(`${p.name}@${p.version}`, ids);
|
|
1038
|
+
}
|
|
1039
|
+
const osv = await safe("OSV lockfile lookup", () => osvMalware(pkgs.map((p) => ({ ecosystem: lock.ecosystem, name: p.name, version: p.version })), ctx));
|
|
1040
|
+
for (const [key, ids] of osv ?? []) {
|
|
1041
|
+
const short = key.slice(key.indexOf(":") + 1);
|
|
1042
|
+
hits.set(short, [...new Set([...(hits.get(short) ?? []), ...ids])]);
|
|
1043
|
+
}
|
|
1044
|
+
const threats = hits.size === 0
|
|
1045
|
+
? []
|
|
1046
|
+
: [
|
|
1047
|
+
{
|
|
1048
|
+
rule: "malicious-package",
|
|
1049
|
+
severity: "block",
|
|
1050
|
+
packages: [...hits].map(([k, ids]) => `${k} (${ids.join(", ")})`),
|
|
1051
|
+
blocked: [...hits].map(([k, ids]) => {
|
|
1052
|
+
const at = k.lastIndexOf("@");
|
|
1053
|
+
return {
|
|
1054
|
+
ecosystem: lock.ecosystem,
|
|
1055
|
+
name: k.slice(0, at),
|
|
1056
|
+
version: k.slice(at + 1),
|
|
1057
|
+
reason: `known malware (${ids.join(", ")})`,
|
|
1058
|
+
};
|
|
1059
|
+
}),
|
|
1060
|
+
detail: `${path.basename(file)} pins malware: ${[...hits]
|
|
1061
|
+
.slice(0, 5)
|
|
1062
|
+
.map(([k, ids]) => `${k} (${ids.join(", ")})`)
|
|
1063
|
+
.join(", ")}${hits.size > 5 ? ` and ${hits.size - 5} more` : ""}; update those packages to a clean version and regenerate the lockfile.`,
|
|
1064
|
+
},
|
|
1065
|
+
];
|
|
1066
|
+
// Only cache a complete answer (OSV reached); offline answers are retried.
|
|
1067
|
+
if (osv !== null) {
|
|
1068
|
+
const verdict = { at: ctx.now, threats };
|
|
1069
|
+
lockfileCache.set(cacheKey, verdict);
|
|
1070
|
+
ctx.cache.setLock(cacheKey, verdict);
|
|
1071
|
+
}
|
|
1072
|
+
return threats;
|
|
1073
|
+
}
|
|
1074
|
+
/** Rejects with the deadline so no network wait can stack past it (fail-open). */
|
|
1075
|
+
function deadline(signal) {
|
|
1076
|
+
return new Promise((_, reject) => {
|
|
1077
|
+
if (signal.aborted)
|
|
1078
|
+
reject(new Error("package check deadline"));
|
|
1079
|
+
signal.addEventListener("abort", () => reject(new Error("package check deadline")), {
|
|
1080
|
+
once: true,
|
|
1081
|
+
});
|
|
1082
|
+
});
|
|
1083
|
+
}
|
|
1084
|
+
/** Context for one check, under ONE deadline shared by every lookup. */
|
|
1085
|
+
function makeCtx(options, feed, command = "") {
|
|
1086
|
+
const timeout = AbortSignal.timeout(TIMEOUT_MS);
|
|
1087
|
+
const cache = verdictCache(options.cacheDir !== undefined
|
|
1088
|
+
? options.cacheDir
|
|
1089
|
+
: process.env.VITEST
|
|
1090
|
+
? null // tests never write to the real GG dir
|
|
1091
|
+
: getAppPaths().agentDir);
|
|
1092
|
+
return {
|
|
1093
|
+
fetch: options.fetch ?? fetch,
|
|
1094
|
+
signal: options.signal ? AbortSignal.any([timeout, options.signal]) : timeout,
|
|
1095
|
+
cancelled: () => options.signal?.aborted === true,
|
|
1096
|
+
reached: { value: false },
|
|
1097
|
+
now: (options.now ?? Date.now)(),
|
|
1098
|
+
days: options.cooldownDays ?? 2,
|
|
1099
|
+
feed,
|
|
1100
|
+
cache,
|
|
1101
|
+
managerVersion: options.managerVersion ?? ((m) => managerVersion(m, options.cwd)),
|
|
1102
|
+
privateSource: (eco) => eco === "npm"
|
|
1103
|
+
? usesCustomNpmRegistry(command, options.cwd ?? process.cwd(), options.env)
|
|
1104
|
+
: usesCustomPypiIndex(command, options.env),
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
/** Lockfile names checked for already-installed packages, with their ecosystem. */
|
|
1108
|
+
export const PROJECT_LOCKFILES = [
|
|
1109
|
+
{ ecosystem: "npm", manager: "npm", file: "package-lock.json" },
|
|
1110
|
+
{ ecosystem: "npm", manager: "pnpm", file: "pnpm-lock.yaml" },
|
|
1111
|
+
{ ecosystem: "npm", manager: "yarn", file: "yarn.lock" },
|
|
1112
|
+
{ ecosystem: "npm", manager: "bun", file: "bun.lock" },
|
|
1113
|
+
{ ecosystem: "PyPI", manager: "uv", file: "uv.lock", resolves: true },
|
|
1114
|
+
{ ecosystem: "PyPI", manager: "pip", file: "requirements.txt" },
|
|
1115
|
+
];
|
|
1116
|
+
/**
|
|
1117
|
+
* Malware check of one existing lockfile (already-installed packages): the
|
|
1118
|
+
* local feed plus one batched OSV lookup, cached by content hash and re-asked
|
|
1119
|
+
* at most once a day. No release-age check. Fail-open like every other check.
|
|
1120
|
+
*/
|
|
1121
|
+
export async function checkLockfileMalware(lock, cwd, options = {}) {
|
|
1122
|
+
const ctx = makeCtx(options, options.feed ?? loadThreatFeed());
|
|
1123
|
+
const work = (async () => {
|
|
1124
|
+
await ctx.cache.load();
|
|
1125
|
+
return checkLockfile({ ...lock, resolves: true }, cwd, ctx);
|
|
1126
|
+
})();
|
|
1127
|
+
const out = await Promise.race([work, deadline(ctx.signal)]).catch((err) => {
|
|
1128
|
+
log("WARN", "package-threats", `lockfile check cut short: ${String(err)}`);
|
|
1129
|
+
noteDeadline(ctx);
|
|
1130
|
+
return [];
|
|
1131
|
+
});
|
|
1132
|
+
ctx.cache.save(ctx.now);
|
|
1133
|
+
return out;
|
|
1134
|
+
}
|
|
1135
|
+
/** Full check for one bash command. Returns blocks only; [] when clean or not an install. */
|
|
1136
|
+
export async function checkPackageInstall(command, options = {}) {
|
|
1137
|
+
const local = localPackageCheck(command, () => options.feed ?? loadThreatFeed());
|
|
1138
|
+
if (local.refs.length === 0 && local.lockfiles.length === 0)
|
|
1139
|
+
return [];
|
|
1140
|
+
const ctx = makeCtx(options, local.feed, command);
|
|
1141
|
+
const cache = ctx.cache;
|
|
1142
|
+
const threats = [...local.threats];
|
|
1143
|
+
const cwd = options.cwd ?? process.cwd();
|
|
1144
|
+
const work = (async () => {
|
|
1145
|
+
await cache.load();
|
|
1146
|
+
const parts = await Promise.all([
|
|
1147
|
+
local.refs.length > 0 ? checkNamed(local, ctx) : [],
|
|
1148
|
+
...local.lockfiles.map((lock) => checkLockfile(lock, cwd, ctx)),
|
|
1149
|
+
]);
|
|
1150
|
+
return parts.flat();
|
|
1151
|
+
})();
|
|
1152
|
+
const out = await Promise.race([work, deadline(ctx.signal)]).catch((err) => {
|
|
1153
|
+
log("WARN", "package-threats", `check cut short, allowing: ${String(err)}`);
|
|
1154
|
+
noteDeadline(ctx);
|
|
1155
|
+
return [];
|
|
1156
|
+
});
|
|
1157
|
+
cache.save(ctx.now);
|
|
1158
|
+
return [...threats, ...out];
|
|
1159
|
+
}
|
|
1160
|
+
/** One plain line for the agent, or null when nothing blocks. */
|
|
1161
|
+
export function packageBlockMessage(threats) {
|
|
1162
|
+
const blocks = threats.filter((t) => t.severity === "block");
|
|
1163
|
+
if (blocks.length === 0)
|
|
1164
|
+
return null;
|
|
1165
|
+
return `Blocked install (${blocks[0]?.rule}): ${blocks.map((t) => t.detail).join(" ")} ${SAFETY_BLOCK_NOTE}`;
|
|
1166
|
+
}
|
|
1167
|
+
/**
|
|
1168
|
+
* Check an MCP stdio launch (`npx -y pkg`, `uvx pkg`) before spawning.
|
|
1169
|
+
* Returns the block line, or null to allow.
|
|
1170
|
+
*/
|
|
1171
|
+
export async function checkMcpLaunch(command, args, options = {}) {
|
|
1172
|
+
const base = path
|
|
1173
|
+
.basename(command)
|
|
1174
|
+
.toLowerCase()
|
|
1175
|
+
.replace(/\.(cmd|exe)$/, "");
|
|
1176
|
+
if (!["npx", "uvx", "bunx", "pnpm", "npm", "uv"].includes(base))
|
|
1177
|
+
return null;
|
|
1178
|
+
const line = [base, ...args].map((a) => (/\s/.test(a) ? `"${a}"` : a)).join(" ");
|
|
1179
|
+
// MCP launches get no bun flag, so bunx gets the own age check.
|
|
1180
|
+
const versions = options.managerVersion ?? ((m) => managerVersion(m));
|
|
1181
|
+
const message = packageBlockMessage(await checkPackageInstall(line, {
|
|
1182
|
+
...options,
|
|
1183
|
+
managerVersion: (m) => (m === "bun" ? Promise.resolve(null) : versions(m)),
|
|
1184
|
+
}));
|
|
1185
|
+
// Shown to the user on the MCP settings row, not to the agent.
|
|
1186
|
+
return message?.replace(` ${SAFETY_BLOCK_NOTE}`, "") ?? null;
|
|
1187
|
+
}
|
|
1188
|
+
/** Wait for pending verdict-cache writes (tests). */
|
|
1189
|
+
export async function flushPackageVerdicts() {
|
|
1190
|
+
await Promise.all([...verdictCaches.values()].map((c) => c.flush()));
|
|
1191
|
+
}
|
|
1192
|
+
/** Test hook: forget cached answers (memory only; the disk file is left alone). */
|
|
165
1193
|
export function clearPackageThreatCache() {
|
|
166
1194
|
osvCache.clear();
|
|
1195
|
+
metaCache.clear();
|
|
1196
|
+
lockfileCache.clear();
|
|
1197
|
+
verdictCaches.clear();
|
|
1198
|
+
downHosts.clear();
|
|
167
1199
|
}
|
|
168
1200
|
//# sourceMappingURL=package-threats.js.map
|