@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/lib/discover.js CHANGED
@@ -2,29 +2,37 @@
2
2
  // folder and app settings, and in risky folders an agent has been started in.
3
3
  // Everything is read and checked on this computer.
4
4
 
5
- import { promises as fs } from "node:fs";
5
+ import { promises as fs, constants } from "node:fs";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
8
  import { maskSecrets } from "../engine/mask.js";
9
- import { parseTOML } from "../engine/parse.js";
10
- import { classifyPath, isSkippedDir, LIMITS, HOME_MARKERS, DOWNLOADS_LIKE } from "../engine/paths.js";
9
+ import { decodeText } from "../engine/decode.js";
10
+ import { classifyPath, isSkippedDir, insideSkill, computerLikeName, readsInPart, LIMITS, HOME_MARKERS, DOWNLOADS_LIKE, TOOL_ROOT } from "../engine/paths.js";
11
11
  import { LOCATIONS, userPaths } from "../engine/locations.js";
12
- import { riskyPlace } from "../engine/index.js";
12
+ import { riskyPlace, agentFolders } from "../engine/index.js";
13
+ import { namedInstructions, pickNamed, NAMING_SETTINGS } from "../engine/named.js";
14
+ import { TRACES, AGENT_PACKAGES, KNOWN_PACKAGES, VERSION_RE } from "../engine/known.js";
13
15
 
14
16
  export const PLATFORM = process.platform === "win32" ? "windows" : process.platform === "darwin" ? "mac" : "linux";
15
17
  const LOOSE_NAMES = /\.(md|mdc|txt)$/i;
16
18
 
17
- export async function discover({ dir = process.cwd(), includeUser = true, home = os.homedir(), env = process.env } = {}) {
19
+ // `limits` is for tests; the command always uses LIMITS from the engine.
20
+ export async function discover({ dir = process.cwd(), includeUser = true, home = homeDir(), env = process.env, limits = LIMITS } = {}) {
18
21
  const projectDir = path.resolve(dir);
22
+ const info = await fs.stat(projectDir).catch(() => null);
23
+ if (!info?.isDirectory()) throw new Error(`There's no folder at ${projectDir}.`);
24
+ const withUser = includeUser && Boolean(home);
19
25
  const files = [];
20
26
  const seen = new Set();
21
27
  const lineMaps = {};
22
28
  let masked = 0;
23
29
 
24
30
  const tilde = (abs) => {
25
- const rel = path.relative(home, abs);
26
- if (!rel) return "~";
27
- if (!rel.startsWith("..") && !path.isAbsolute(rel)) return "~/" + rel.split(path.sep).join("/");
31
+ if (home) {
32
+ const rel = path.relative(home, abs);
33
+ if (!rel) return "~";
34
+ if (!rel.startsWith("..") && !path.isAbsolute(rel)) return "~/" + rel.split(path.sep).join("/");
35
+ }
28
36
  return abs.split(path.sep).join("/");
29
37
  };
30
38
  const add = (enginePath, raw, size, extra = {}) => {
@@ -35,155 +43,583 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
35
43
  masked += m.count;
36
44
  files.push({ path: enginePath, size, content: m.text, ...extra });
37
45
  };
46
+ // `budget` limits what's read in all from the project.
47
+ const addFile = async (abs, enginePath, kind, maxBytes = LIMITS.maxFileBytes, extra = {}, budget = null) => {
48
+ const stat = await fs.stat(abs).catch(() => null);
49
+ if (!stat?.isFile()) return;
50
+ if (kind === "sensitive") return add(enginePath, null, stat.size, { sensitive: true });
51
+ if (kind === "listed") return add(enginePath, null, stat.size, { listed: true });
52
+ // A loose text file only counts when it reads like orders to an agent,
53
+ // which a file too large to read can't show.
54
+ const room = budget ? Math.min(maxBytes, limits.maxTotalBytes - budget.bytes) : maxBytes;
55
+ // Too large: an instruction file is checked from its start, anything else is listed.
56
+ const tooLarge = async () => {
57
+ if (kind === "loose") return;
58
+ if (stat.size > maxBytes && room === maxBytes && readsInPart(enginePath)) {
59
+ const start = await readLimited(abs, maxBytes, true);
60
+ if (start.text !== null) {
61
+ if (budget) budget.bytes += start.bytes;
62
+ return add(enginePath, start.text, stat.size, { partial: true, ...extra });
63
+ }
64
+ }
65
+ add(enginePath, null, stat.size, { tooLarge: true, ...extra });
66
+ };
67
+ if (stat.size > room) return tooLarge();
68
+ const read = await readLimited(abs, room);
69
+ if (read.tooLarge) return tooLarge();
70
+ if (budget) budget.bytes += read.bytes;
71
+ add(enginePath, read.text, stat.size, kind === "loose" ? { loose: true } : extra);
72
+ };
38
73
 
39
- // --- The project folder -------------------------------------------------------
74
+ // --- The project folder --------------------------------------------------
75
+ // Breadth first, so the files near the top, where agents look, are found
76
+ // even in a folder too big to walk completely.
40
77
  const top = await readdir(projectDir);
41
78
  const topLevel = top.map((d) => d.name);
42
79
  const homeLike = topLevel.filter((n) => HOME_MARKERS.has(n)).length >= 3;
43
80
  const shape = { entries: 0, topLevel: topLevel.slice(0, 200), rootGit: topLevel.includes(".git"), gitRepos: 0, truncated: false };
44
- const scanningHome = samePath(projectDir, home);
81
+ const scanningHome = Boolean(home) && samePath(projectDir, home);
45
82
 
46
83
  if (!scanningHome) {
47
84
  const looseMarkdown = DOWNLOADS_LIKE.test(path.basename(projectDir)) || homeLike;
48
85
  const gitRepos = new Set();
49
- const stack = [[projectDir, 0]];
50
- while (stack.length) {
51
- const [current, depth] = stack.pop();
52
- for (const entry of await readdir(current)) {
53
- if (shape.entries >= LIMITS.maxEntries) {
54
- shape.truncated = true;
55
- break;
86
+ const candidates = [];
87
+ const consider = (abs, rel, entry) => {
88
+ // Linked files count, since agents follow the link (CLAUDE.md is
89
+ // often a link to AGENTS.md). Linked folders aren't followed.
90
+ if (!entry.isFile() && !entry.isSymbolicLink()) return;
91
+ const kind = classifyPath(rel, { looseMarkdown });
92
+ if (kind) candidates.push({ abs, rel, kind, link: entry.isSymbolicLink() });
93
+ // Kept by name, in case a settings file names it as instructions.
94
+ else if (others.length < 120_000) others.push({ abs, rel, kind: "content", link: entry.isSymbolicLink() });
95
+ };
96
+ const others = [];
97
+ // A linked folder is followed when it leads to a folder inside the
98
+ // project, as agents follow it (.claude can be a link to config/claude).
99
+ // Each real folder is walked once, so links can't make a loop.
100
+ const root = await fs.realpath(projectDir).catch(() => projectDir);
101
+ const walked = new Set([root]);
102
+ const linkedFolder = async (abs, entry) => {
103
+ if (!entry.isSymbolicLink() || !(await fs.stat(abs).catch(() => null))?.isDirectory()) return false;
104
+ const real = await fs.realpath(abs).catch(() => null);
105
+ if (!real) return null;
106
+ // Agents follow a link out of the project too, so the check names it.
107
+ if (!isInside(real, root)) return "outside";
108
+ if (walked.has(real)) return null;
109
+ walked.add(real);
110
+ return true;
111
+ };
112
+ const outsideFolders = [];
113
+ // The top of the folder first, all of it, then the agent folders there
114
+ // (.claude, .cursor, .github and so on), each walk with its own
115
+ // allowance, so a folder too big to walk still has them checked.
116
+ const firstDirs = [];
117
+ const otherDirs = [];
118
+ for (const entry of top) {
119
+ shape.entries++;
120
+ if (computerLikeName(entry.name)) continue;
121
+ const abs = path.join(projectDir, entry.name);
122
+ const linked = await linkedFolder(abs, entry);
123
+ if (linked === "outside") outsideFolders.push(entry.name);
124
+ if (linked === null || linked === "outside") continue;
125
+ if (entry.isDirectory() || linked) {
126
+ if (entry.name === ".git") gitRepos.add("");
127
+ if (TOOL_ROOT.test(entry.name)) firstDirs.push([abs, 1]);
128
+ else if (!isSkippedDir(entry.name) || insideSkill(entry.name)) otherDirs.push([abs, 1]);
129
+ continue;
130
+ }
131
+ consider(abs, entry.name, entry);
132
+ }
133
+ const walk = async (starts) => {
134
+ const queue = [...starts];
135
+ let entries = 0;
136
+ for (let q = 0; q < queue.length; q++) {
137
+ const [current, depth] = queue[q];
138
+ for (const entry of await readdir(current)) {
139
+ if (++entries > limits.maxEntries) return true;
140
+ shape.entries++;
141
+ const abs = path.join(current, entry.name);
142
+ const rel = path.relative(projectDir, abs).split(path.sep).join("/");
143
+ const linked = await linkedFolder(abs, entry);
144
+ if (linked === "outside") outsideFolders.push(rel);
145
+ if (linked === null || linked === "outside") continue;
146
+ if (entry.isDirectory() || linked) {
147
+ if (entry.name === ".git") gitRepos.add(path.relative(projectDir, current));
148
+ if ((!isSkippedDir(entry.name) || insideSkill(rel)) && depth < 12) queue.push([abs, depth + 1]);
149
+ continue;
150
+ }
151
+ consider(abs, rel, entry);
56
152
  }
57
- shape.entries++;
58
- const abs = path.join(current, entry.name);
59
- const rel = path.relative(projectDir, abs).split(path.sep).join("/");
60
- if (entry.isDirectory()) {
61
- if (entry.name === ".git") gitRepos.add(path.relative(projectDir, current));
62
- if (!isSkippedDir(entry.name) && depth < 12) stack.push([abs, depth + 1]);
153
+ }
154
+ return false;
155
+ };
156
+ if (await walk(firstDirs)) shape.truncated = true;
157
+ if (await walk(otherDirs)) shape.truncated = true;
158
+ shape.gitRepos = gitRepos.size;
159
+
160
+ // Files that settings name as instructions, such as Gemini CLI's
161
+ // context.fileName: the project's settings, and with the settings on
162
+ // this computer, Gemini CLI's and Codex's own.
163
+ const naming = [];
164
+ for (const c of candidates.filter((x) => x.kind === "content" && !x.link && NAMING_SETTINGS.some((re) => re.test(x.rel)))) {
165
+ const content = await readText(c.abs, limits.maxFileBytes);
166
+ if (content !== null) naming.push({ path: c.rel, content });
167
+ }
168
+ if (withUser) {
169
+ for (const [rel, abs] of [["~/.gemini/settings.json", path.join(home, ".gemini", "settings.json")], ["~/.codex/config.toml", path.join(env.CODEX_HOME || path.join(home, ".codex"), "config.toml")]]) {
170
+ const content = await readText(abs, limits.maxFileBytes);
171
+ if (content !== null) naming.push({ path: rel, content });
172
+ }
173
+ }
174
+ candidates.push(...pickNamed(namedInstructions(naming), others, (o) => o.rel));
175
+ // Read in order of importance, up to LIMITS: agent files, then the
176
+ // .gitignore and package.json files some checks use, then files listed
177
+ // by name, then loose text files.
178
+ const helper = (p) => /(^|\/)(\.gitignore|package\.json)$/i.test(p);
179
+ const order = (c) => (c.kind === "content" ? (helper(c.rel) ? 1 : 0) : c.kind === "sensitive" || c.kind === "listed" ? 2 : 3);
180
+ candidates.sort((a, b) => order(a) - order(b) || a.rel.split("/").length - b.rel.split("/").length || (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
181
+ for (const rel of outsideFolders.slice(0, 20)) add(rel, null, 0, { linked: "outside", folder: true });
182
+ const budget = { files: 0, bytes: 0, loose: 0 };
183
+ for (const c of candidates) {
184
+ if (budget.files >= limits.maxFiles) {
185
+ shape.truncated = true;
186
+ break;
187
+ }
188
+ if (c.kind === "loose" && ++budget.loose > limits.maxLooseMarkdown) continue;
189
+ budget.files++;
190
+ // A link is only followed to a file inside the project that isn't a
191
+ // credential file. Agents follow any link, so the others are reported.
192
+ if (c.link && c.kind !== "sensitive" && c.kind !== "listed") {
193
+ const target = await fs.realpath(c.abs).catch(() => null);
194
+ if (!target) continue;
195
+ const inside = isInside(target, root);
196
+ if (!inside || classifyPath(path.relative(root, target).split(path.sep).join("/")) === "sensitive") {
197
+ if (c.kind !== "loose") add(c.rel, null, 0, { linked: inside ? "secret" : "outside" });
63
198
  continue;
64
199
  }
65
- if (!entry.isFile()) continue;
66
- const kind = classifyPath(rel, { looseMarkdown });
67
- if (!kind) continue;
68
- await addFile(abs, rel, kind);
69
200
  }
201
+ await addFile(c.abs, c.rel, c.kind, limits.maxFileBytes, {}, budget);
70
202
  }
71
- shape.gitRepos = gitRepos.size;
72
203
  }
73
204
 
74
- async function addFile(abs, enginePath, kind) {
75
- const stat = await fs.stat(abs).catch(() => null);
76
- if (!stat) return;
77
- if (kind === "sensitive") return add(enginePath, null, stat.size, { sensitive: true });
78
- if (stat.size > LIMITS.maxFileBytes) return add(enginePath, null, stat.size, { tooLarge: true });
79
- const raw = await fs.readFile(abs, "utf8").catch(() => null);
80
- if (raw !== null) add(enginePath, raw, stat.size, kind === "loose" ? { loose: true } : {});
81
- }
205
+ // git's own ignore lists, so files ignored there aren't reported as
206
+ // exposed. Claude Code adds its local settings to the global one. These
207
+ // apply to the project, so they're read with --project-only too.
208
+ const ignoreLists = [];
209
+ if (shape.rootGit) await readIgnoreList(path.join(projectDir, ".git", "info", "exclude"), ignoreLists);
210
+ if (home) await readIgnoreList(path.join(env.XDG_CONFIG_HOME || path.join(home, ".config"), "git", "ignore"), ignoreLists);
82
211
 
83
- // --- The home folder and app settings -------------------------------------------
212
+ // --- The home folder and app settings ------------------------------------
84
213
  // Each file keeps its usual name (~/.claude/settings.json) even when an
85
- // environment variable moved it, so the checks still recognise it.
86
- const userFiles = [];
87
- if (includeUser) {
214
+ // environment variable moved it, so the checks still recognize it.
215
+ if (withUser) {
216
+ const userFiles = [];
88
217
  for (const entry of LOCATIONS) {
89
218
  for (const p of userPaths(entry, PLATFORM)) {
90
- const abs = resolveUserPath(p, { home, env });
91
- if (!p.endsWith("/")) userFiles.push({ abs, enginePath: p.startsWith("~") ? p : tilde(abs) });
92
- else for (const f of await listFiles(abs, 3)) userFiles.push({ abs: f, enginePath: p + path.relative(abs, f).split(path.sep).join("/") });
219
+ for (const { abs, name } of await expand(resolveUserPath(p, { home, env }), p.startsWith("~") ? p : null)) {
220
+ const enginePath = name ?? tilde(abs);
221
+ if (!p.endsWith("/")) {
222
+ userFiles.push({ abs, enginePath });
223
+ continue;
224
+ }
225
+ // In a folder, only the files agents read.
226
+ const nameOf = (f) => enginePath.replace(/\/?$/, "/") + path.relative(abs, f).split(path.sep).join("/");
227
+ for (const f of await listFiles(abs, 4, (f) => ["content", "listed"].includes(classifyPath(nameOf(f))), (d) => insideSkill(nameOf(d)))) userFiles.push({ abs: f, enginePath: nameOf(f) });
228
+ }
93
229
  }
94
230
  }
231
+ // With CLAUDE_CONFIG_DIR set, ~/.claude.json may live in that folder.
232
+ if (env.CLAUDE_CONFIG_DIR) userFiles.push({ abs: path.join(home, ".claude.json"), enginePath: "~/.claude.json" });
95
233
  for (const { abs, enginePath } of userFiles) {
96
234
  if (seen.has(enginePath)) continue;
97
235
  // Credential files belong in the home folder; only report them inside projects.
98
- if (classifyPath(enginePath) === "sensitive") continue;
99
- const stat = await fs.stat(abs).catch(() => null);
100
- if (!stat?.isFile()) continue;
236
+ const kind = classifyPath(enginePath);
237
+ if (kind === "sensitive") continue;
101
238
  if (/(^|[\\/])\.claude\.json$/.test(abs)) {
102
- const raw = await fs.readFile(abs, "utf8").catch(() => null);
239
+ const stat = await fs.stat(abs).catch(() => null);
240
+ const raw = stat?.isFile() ? await readText(abs) : null;
103
241
  if (raw === null) continue;
104
242
  const reduced = reduceClaudeJson(raw, tilde);
105
243
  add(enginePath, reduced.text, stat.size);
106
244
  if (reduced.lineMap) lineMaps[enginePath] = reduced.lineMap;
107
245
  continue;
108
246
  }
109
- if (stat.size > Math.max(LIMITS.maxFileBytes, 1024 * 1024)) {
110
- add(enginePath, null, stat.size, { tooLarge: true });
111
- continue;
247
+ await addFile(abs, enginePath, kind === "listed" ? "listed" : "content");
248
+ }
249
+ }
250
+
251
+ // --- Claude Code plugins ---------------------------------------------------
252
+ // The hooks, MCP servers, commands and agents of each installed plugin.
253
+ // The user's installed_plugins.json says where each one is; other copies
254
+ // on disk, such as whole marketplaces, aren't in use and aren't read.
255
+ const installed = withUser ? files.find((f) => f.path === "~/.claude/plugins/installed_plugins.json" && f.content) : null;
256
+ if (installed) {
257
+ const root = path.dirname(resolveUserPath("~/.claude/plugins/installed_plugins.json", { home, env }));
258
+ for (const dir of pluginFolders(installed.content, projectDir).slice(0, 100)) {
259
+ const abs = path.resolve(root, dir);
260
+ if (!isInside(abs, root)) continue;
261
+ for (const f of await listFiles(abs, 4, (f) => ["content", "listed"].includes(classifyPath(tilde(f))), (d) => insideSkill(tilde(d)))) await addFile(f, tilde(f), classifyPath(tilde(f)));
262
+ // plugin.json can keep hooks and MCP servers somewhere else in the plugin.
263
+ const manifest = files.find((f) => f.path === tilde(path.join(abs, ".claude-plugin", "plugin.json")) && f.content);
264
+ for (const [key, role] of [["hooks", "claude-hooks"], ["mcpServers", "mcp-servers"]]) {
265
+ const target = manifestPath(manifest?.content, key);
266
+ const file = target && path.resolve(abs, target);
267
+ if (file && isInside(file, abs)) await addFile(file, tilde(file), "content", LIMITS.maxFileBytes, { role });
112
268
  }
113
- const raw = await fs.readFile(abs, "utf8").catch(() => null);
114
- if (raw !== null) add(enginePath, raw, stat.size);
115
269
  }
116
270
  }
117
271
 
118
- // --- Risky folders an agent has been started in -----------------------------------
119
- // If Claude Code or Codex has run in Downloads or the home folder, check the
120
- // loose instruction files sitting there too.
272
+ // --- Risky folders an agent has been started in --------------------------
273
+ // If an agent has run in, or trusts, Downloads or the home folder, check
274
+ // the loose instruction files there too. Only the settings on this
275
+ // computer say where agents have run; a project's own copies don't count.
121
276
  const risky = new Set();
122
- for (const f of files) {
123
- if (/(^|\/)\.claude\.json$/.test(f.path)) {
124
- try {
125
- for (const d of Object.keys(JSON.parse(f.content).projects ?? {})) if (riskyPlace(d)) risky.add(d);
126
- } catch {}
127
- }
128
- if (/(^|\/)\.codex\/config\.toml$/.test(f.path)) {
129
- const projects = parseTOML(f.content)?.projects ?? {};
130
- for (const [d, s] of Object.entries(projects)) if (s?.trust_level === "trusted" && riskyPlace(d)) risky.add(tilde(path.resolve(d)));
131
- }
277
+ for (const f of withUser ? files : []) {
278
+ if (!f.content || !/^(~|\/|[A-Za-z]:)/.test(f.path)) continue;
279
+ for (const d of agentFolders(f.path, f.content)) if (riskyPlace(d)) risky.add(d.startsWith("~") ? d : tilde(path.resolve(d)));
132
280
  }
133
281
  for (const d of risky) {
134
282
  const abs = d === "~" ? home : d.startsWith("~/") ? path.join(home, ...d.slice(2).split("/")) : d;
135
283
  if (samePath(abs, projectDir)) continue;
136
284
  let count = 0;
137
285
  for (const entry of await readdir(abs)) {
138
- if (!entry.isFile() || !LOOSE_NAMES.test(entry.name) || ++count > LIMITS.maxLooseMarkdown) continue;
139
- const full = path.join(abs, entry.name);
140
- const stat = await fs.stat(full).catch(() => null);
141
- if (!stat || stat.size > 200 * 1024) continue;
142
- const raw = await fs.readFile(full, "utf8").catch(() => null);
143
- if (raw !== null) add(tilde(full), raw, stat.size, { loose: true });
286
+ if (!(entry.isFile() || entry.isSymbolicLink()) || !LOOSE_NAMES.test(entry.name) || ++count > LIMITS.maxLooseMarkdown) continue;
287
+ await addFile(path.join(abs, entry.name), tilde(path.join(abs, entry.name)), "loose", 200 * 1024);
144
288
  }
145
289
  }
146
290
 
291
+ // --- What's installed -----------------------------------------------------
292
+ // Agent installs and editor extensions on this computer, and files that
293
+ // attacks leave, by name and version only. The project's own copies of
294
+ // packages that were malware are checked even with --project-only.
295
+ const installs = scanningHome ? [] : await projectPackages(projectDir);
296
+ const locked = scanningHome ? [] : await lockedPackages(projectDir);
297
+ let extensions = [];
298
+ let traces = [];
299
+ if (withUser) {
300
+ installs.push(...(await agentInstalls({ home, env, tilde })));
301
+ extensions = await editorExtensions({ home, env, tilde });
302
+ traces = await traceFiles({ home, env });
303
+ }
304
+
147
305
  return {
148
306
  root: path.basename(projectDir) || projectDir,
149
- home: "~",
150
307
  shape,
151
308
  files,
309
+ ignoreLists,
152
310
  masked: { count: masked },
153
311
  lineMaps,
154
- scanned: { project: tilde(projectDir), projectSkipped: scanningHome, user: includeUser },
312
+ installs,
313
+ locked,
314
+ extensions,
315
+ traces,
316
+ scanned: { project: tilde(projectDir), projectSkipped: scanningHome, user: withUser },
155
317
  };
156
318
  }
157
319
 
158
- // "~/..." and "{config}" style paths from locations.js, honouring the
320
+ const byVersion = (a, b) => a.localeCompare(b, undefined, { numeric: true });
321
+
322
+ // package.json's name and version, or null. Small files only.
323
+ async function packageVersion(file) {
324
+ const stat = await fs.stat(file).catch(() => null);
325
+ if (!stat?.isFile() || stat.size > 512 * 1024) return null;
326
+ try {
327
+ const json = JSON.parse((await readText(file)) ?? "");
328
+ return typeof json?.name === "string" && typeof json?.version === "string" && VERSION_RE.test(json.version) ? { name: json.name, version: json.version } : null;
329
+ } catch {
330
+ return null;
331
+ }
332
+ }
333
+
334
+ // The npm packages known.js lists, including any added from today's list.
335
+ const npmKnown = () => Object.keys(KNOWN_PACKAGES).filter((k) => k.startsWith("npm:")).map((k) => k.slice(4));
336
+
337
+ // The package names in a node_modules folder, scoped ones included.
338
+ async function installedNames(dir) {
339
+ const names = new Set();
340
+ for (const entry of (await readdir(dir)).slice(0, 20_000)) {
341
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
342
+ if (!entry.name.startsWith("@")) names.add(entry.name);
343
+ else for (const inner of (await readdir(path.join(dir, entry.name))).slice(0, 5000)) names.add(`${entry.name}/${inner.name}`);
344
+ }
345
+ return names;
346
+ }
347
+
348
+ // Versions of packages that were malware, in the project's node_modules.
349
+ async function projectPackages(projectDir) {
350
+ const out = [];
351
+ const here = await installedNames(path.join(projectDir, "node_modules"));
352
+ for (const name of npmKnown().filter((n) => here.has(n))) {
353
+ const found = await packageVersion(path.join(projectDir, "node_modules", ...name.split("/"), "package.json"));
354
+ if (found?.name === name) out.push({ package: name, version: found.version, via: "project", path: `node_modules/${name}` });
355
+ }
356
+ // pnpm keeps every package, including ones other packages pulled in, in
357
+ // node_modules/.pnpm, in folders named name@version (@scope+name@version).
358
+ // The names say enough; nothing in them is read.
359
+ const known = new Set(npmKnown());
360
+ for (const entry of (await readdir(path.join(projectDir, "node_modules", ".pnpm"))).slice(0, 30_000)) {
361
+ const m = entry.isDirectory() ? entry.name.match(/^((?:@[^+@/]+\+)?[^+@/]+)@([^_/]+)/) : null;
362
+ const name = m ? m[1].replace("+", "/") : null;
363
+ if (!name || !known.has(name) || !VERSION_RE.test(m[2])) continue;
364
+ if (out.some((i) => i.package === name && i.version === m[2])) continue;
365
+ out.push({ package: name, version: m[2], via: "project", path: `node_modules/.pnpm/${entry.name}/node_modules/${name}` });
366
+ }
367
+ return out;
368
+ }
369
+
370
+ // Versions of packages that were malware, pinned in the project's lockfile,
371
+ // so a check before installing (in CI, say) still finds them. Only names and
372
+ // versions are looked for: in the registry addresses npm and Yarn write
373
+ // (/nx/-/nx-21.5.0.tgz), in npm's entries ("node_modules/nx": { "version":
374
+ // "21.5.0" }, which have no address when omit-lockfile-registry-resolved is
375
+ // set), and in the name@version keys pnpm, Bun and Yarn 2+ write (/nx/21.5.0
376
+ // in pnpm's older lockfiles). Nothing else in the file is kept.
377
+ const LOCKFILES = ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock"];
378
+ const MAX_LOCKFILE_BYTES = 64 * 1024 * 1024;
379
+ const SEMVER = String.raw`\d{1,6}\.\d{1,6}\.\d{1,6}(?:-[0-9A-Za-z.-]{1,40})?`;
380
+ // Any package name; the ones that count are picked out after, so the patterns
381
+ // stay as fast with thousands of known names as with a few.
382
+ const NAME = String.raw`(?:@[a-z0-9][a-z0-9._~-]{0,100}/)?[a-z0-9][a-z0-9._~-]{0,213}`;
383
+ const LOCKED_URL = new RegExp(String.raw`/(${NAME})/-/[a-z0-9][a-z0-9._~-]{0,213}-(${SEMVER})\.tgz`, "g");
384
+ const LOCKED_KEY = new RegExp(String.raw`(?:^|["'/\s])(${NAME})@(?:npm:)?(${SEMVER})(?=["'\s:(_,]|$)`, "gm");
385
+ // npm's own entries, nested or not, and lockfile version 1's "nx": { "version" }.
386
+ const LOCKED_ENTRY = new RegExp(String.raw`"(?:node_modules/(?:[^"\n]{0,400}?/node_modules/)?)?(${NAME})":\s{0,20}\{[^{}]{0,2000}?"version":\s{0,20}"(${SEMVER})"`, "g");
387
+ const LOCKED_PNPM = new RegExp(String.raw`^\s{0,8}['"]?/(${NAME})/(${SEMVER})(?=[:_('"]|$)`, "gm");
388
+ async function lockedPackages(projectDir) {
389
+ const known = new Set(npmKnown());
390
+ const out = [];
391
+ for (const file of LOCKFILES) {
392
+ const abs = path.join(projectDir, file);
393
+ const stat = await fs.stat(abs).catch(() => null);
394
+ if (!stat?.isFile() || stat.size > MAX_LOCKFILE_BYTES) continue;
395
+ const text = await fs.readFile(abs, "utf8").catch(() => "");
396
+ const seen = new Set();
397
+ for (const re of [LOCKED_URL, LOCKED_KEY, LOCKED_ENTRY, LOCKED_PNPM]) {
398
+ for (const m of text.matchAll(re)) {
399
+ const key = `${m[1]}@${m[2]}`;
400
+ // An npm alias ("node_modules/nx": { "name": "other" }) is some other package.
401
+ if (re === LOCKED_ENTRY && m[0].includes('"name":')) continue;
402
+ if (!known.has(m[1]) || seen.has(key) || seen.size >= 200) continue;
403
+ seen.add(key);
404
+ out.push({ file, package: m[1], version: m[2] });
405
+ }
406
+ }
407
+ }
408
+ return out;
409
+ }
410
+
411
+ // Folders where npm, pnpm, bun and Node version managers keep global packages.
412
+ async function globalPackageDirs({ home, env }) {
413
+ const at = (...parts) => path.join(home, ...parts);
414
+ const each = async (pattern) => (await expand(pattern, null)).map((x) => x.abs);
415
+ const dirs =
416
+ PLATFORM === "windows"
417
+ ? [
418
+ env.APPDATA && path.join(env.APPDATA, "npm", "node_modules"),
419
+ env.ProgramFiles && path.join(env.ProgramFiles, "nodejs", "node_modules"),
420
+ ...(env.APPDATA ? await each(path.join(env.APPDATA, "nvm", "v*", "node_modules")) : []),
421
+ env.LOCALAPPDATA && path.join(env.LOCALAPPDATA, "pnpm", "global", "5", "node_modules"),
422
+ at(".bun", "install", "global", "node_modules"),
423
+ ]
424
+ : [
425
+ "/usr/local/lib/node_modules",
426
+ "/opt/homebrew/lib/node_modules",
427
+ "/usr/lib/node_modules",
428
+ at(".npm-global", "lib", "node_modules"),
429
+ at(".local", "lib", "node_modules"),
430
+ at(".bun", "install", "global", "node_modules"),
431
+ ...(await each(at(".nvm", "versions", "node", "*", "lib", "node_modules"))),
432
+ ...(await each(at(".asdf", "installs", "nodejs", "*", "lib", "node_modules"))),
433
+ ...(await each(at(".local", "share", "fnm", "node-versions", "*", "installation", "lib", "node_modules"))),
434
+ ...(await each(at("Library", "Application Support", "fnm", "node-versions", "*", "installation", "lib", "node_modules"))),
435
+ ...(await each(at(".local", "share", "pnpm", "global", "*", "node_modules"))),
436
+ ...(await each(at("Library", "pnpm", "global", "*", "node_modules"))),
437
+ ];
438
+ if (env.NPM_CONFIG_PREFIX) dirs.push(PLATFORM === "windows" ? path.join(env.NPM_CONFIG_PREFIX, "node_modules") : path.join(env.NPM_CONFIG_PREFIX, "lib", "node_modules"));
439
+ return [...new Set(dirs.filter(Boolean))].slice(0, 60);
440
+ }
441
+
442
+ // Installed AI agents and their versions, read from package.json files,
443
+ // version folders and app bundles. Nothing is run.
444
+ async function agentInstalls({ home, env, tilde }) {
445
+ const out = [];
446
+ const seen = new Set();
447
+ const push = (pkg, version, via, abs) => {
448
+ const key = `${pkg}|${version}|${abs}`;
449
+ if (seen.has(key) || !VERSION_RE.test(version)) return;
450
+ seen.add(key);
451
+ out.push({ package: pkg, version, via, path: tilde(abs), platform: PLATFORM });
452
+ };
453
+ const npmPackages = [...Object.keys(AGENT_PACKAGES).filter((p) => p !== "Claude Desktop"), ...npmKnown()];
454
+ for (const dir of await globalPackageDirs({ home, env })) {
455
+ // Only the names installed there are looked at, so a long list of known
456
+ // packages costs one folder listing, not a look for each name.
457
+ const here = await installedNames(dir);
458
+ for (const name of npmPackages.filter((n) => here.has(n))) {
459
+ const found = await packageVersion(path.join(dir, ...name.split("/"), "package.json"));
460
+ if (found?.name === name) push(name, found.version, /pnpm/i.test(dir) ? "pnpm" : /[\\/]\.bun[\\/]/.test(dir) ? "bun" : "npm", path.join(dir, ...name.split("/")));
461
+ }
462
+ }
463
+ const voltaRoot = PLATFORM === "windows" && env.LOCALAPPDATA ? path.join(env.LOCALAPPDATA, "Volta") : path.join(home, ".volta");
464
+ const volta = await installedNames(path.join(voltaRoot, "tools", "image", "packages"));
465
+ for (const name of npmPackages.filter((n) => volta.has(n))) {
466
+ const image = path.join(voltaRoot, "tools", "image", "packages", ...name.split("/"));
467
+ // Volta keeps the package under lib/node_modules, or node_modules on Windows.
468
+ for (const lib of [["lib", "node_modules"], ["node_modules"]]) {
469
+ const found = await packageVersion(path.join(image, ...lib, ...name.split("/"), "package.json"));
470
+ if (found?.name === name) push(name, found.version, "volta", image);
471
+ }
472
+ }
473
+ // Claude Code's own installer keeps each version in a folder named after
474
+ // it and links the one in use from ~/.local/bin. Its older local install
475
+ // has a package.json.
476
+ const versions = path.join(home, ".local", "share", "claude", "versions");
477
+ const launcher = await fs.readlink(path.join(home, ".local", "bin", PLATFORM === "windows" ? "claude.exe" : "claude")).catch(() => null);
478
+ const native = (await readdir(versions)).map((d) => d.name).filter((n) => VERSION_RE.test(n)).sort(byVersion);
479
+ const active = launcher ? path.basename(launcher) : null;
480
+ const current = active && native.includes(active) ? active : native.pop();
481
+ if (current) push("@anthropic-ai/claude-code", current, "native", path.join(versions, current));
482
+ const local = await packageVersion(path.join(home, ".claude", "local", "node_modules", "@anthropic-ai", "claude-code", "package.json"));
483
+ if (local?.name === "@anthropic-ai/claude-code") push("@anthropic-ai/claude-code", local.version, "local", path.join(home, ".claude", "local"));
484
+ // Homebrew formulas and casks, by their version folders.
485
+ if (PLATFORM !== "windows") {
486
+ const brews = [["@anthropic-ai/claude-code", "Caskroom/claude-code"], ["@openai/codex", "Cellar/codex"], ["@openai/codex", "Caskroom/codex"], ["@google/gemini-cli", "Cellar/gemini-cli"]];
487
+ for (const prefix of ["/opt/homebrew", "/usr/local", "/home/linuxbrew/.linuxbrew"]) {
488
+ for (const [pkg, name] of brews) {
489
+ const dir = path.join(prefix, ...name.split("/"));
490
+ // A rebuilt formula's folder ends in _1, _2 and so on.
491
+ const found = (await readdir(dir)).map((d) => d.name).filter((n) => VERSION_RE.test(n.replace(/_\d+$/, ""))).sort(byVersion).pop();
492
+ if (found) push(pkg, found.replace(/_\d+$/, ""), "homebrew", path.join(dir, found));
493
+ }
494
+ }
495
+ }
496
+ // Claude Desktop: the app bundle's version on macOS, the app-<version>
497
+ // folders on Windows.
498
+ if (PLATFORM === "mac") {
499
+ for (const app of ["/Applications/Claude.app", path.join(home, "Applications", "Claude.app")]) {
500
+ const file = path.join(app, "Contents", "Info.plist");
501
+ const stat = await fs.stat(file).catch(() => null);
502
+ const plist = stat?.isFile() && stat.size < 200_000 ? ((await readText(file)) ?? "") : "";
503
+ const m = plist.match(/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]{1,40})<\/string>/);
504
+ if (m) push("Claude Desktop", m[1].trim(), "app", app);
505
+ }
506
+ } else if (PLATFORM === "windows" && env.LOCALAPPDATA) {
507
+ const dir = path.join(env.LOCALAPPDATA, "AnthropicClaude");
508
+ const latest = (await readdir(dir)).map((d) => d.name.match(/^app-(.+)$/)?.[1]).filter((v) => v && VERSION_RE.test(v)).sort(byVersion).pop();
509
+ if (latest) push("Claude Desktop", latest, "app", path.join(dir, `app-${latest}`));
510
+ }
511
+ return out;
512
+ }
513
+
514
+ // Editor extensions: VS Code and the editors built on it keep a list in
515
+ // extensions.json and a folder per extension named publisher.name-version.
516
+ const EDITOR_DIRS = [
517
+ ["VS Code", ".vscode"],
518
+ ["VS Code Insiders", ".vscode-insiders"],
519
+ ["VSCodium", ".vscode-oss"],
520
+ ["Cursor", ".cursor"],
521
+ ["Windsurf", ".windsurf"],
522
+ ["Kiro", ".kiro"],
523
+ ];
524
+ const EXTENSION_FOLDER = /^([a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9._-]*?)-(\d+\.\d+\.\d+(?:-[0-9a-z.]+?)?)(?:-(?:darwin|linux|win32|alpine|web)(?:-[a-z0-9]+)?)?$/i;
525
+ async function editorExtensions({ home, env, tilde }) {
526
+ const out = [];
527
+ for (const [editor, folder] of EDITOR_DIRS) {
528
+ const dir = editor === "VS Code" && env.VSCODE_EXTENSIONS ? env.VSCODE_EXTENSIONS : path.join(home, folder, "extensions");
529
+ const entries = await readdir(dir);
530
+ if (!entries.length) continue;
531
+ const items = new Map();
532
+ const list = path.join(dir, "extensions.json");
533
+ const stat = await fs.stat(list).catch(() => null);
534
+ if (stat?.isFile() && stat.size <= 4 * 1024 * 1024) {
535
+ let json = null;
536
+ try {
537
+ json = JSON.parse((await readText(list)) ?? "");
538
+ } catch {}
539
+ for (const e of Array.isArray(json) ? json.slice(0, 3000) : []) {
540
+ const id = typeof e?.identifier?.id === "string" ? e.identifier.id.toLowerCase() : null;
541
+ const version = typeof e?.version === "string" ? e.version : "";
542
+ const folder = typeof e?.relativeLocation === "string" && /^[^/\\]{1,250}$/.test(e.relativeLocation) && e.relativeLocation !== ".." ? e.relativeLocation : null;
543
+ if (id) items.set(`${id}@${version}`, { id, version, source: typeof e?.metadata?.source === "string" ? e.metadata.source : null, folder });
544
+ }
545
+ }
546
+ // Folders on disk too, including old versions not cleaned up yet.
547
+ for (const entry of entries.slice(0, 3000)) {
548
+ const m = entry.isDirectory() ? entry.name.match(EXTENSION_FOLDER) : null;
549
+ if (m && !items.has(`${m[1].toLowerCase()}@${m[2]}`)) items.set(`${m[1].toLowerCase()}@${m[2]}`, { id: m[1].toLowerCase(), version: m[2], source: null, folder: entry.name });
550
+ }
551
+ const found = [...items.values()];
552
+ for (let i = 0; i < found.length; i += 16) await Promise.all(found.slice(i, i + 16).map(async (x) => (x.published = await publishedId(dir, x))));
553
+ if (found.length) out.push({ editor, dir: tilde(dir), items: found.map(({ folder, ...x }) => x) });
554
+ }
555
+ return out;
556
+ }
557
+
558
+ // An extension's ID with the capitals its publisher gave it, from the
559
+ // publisher and name fields of its package.json, or null. OSV.dev needs it
560
+ // to find the extension; nothing else in the file is kept.
561
+ async function publishedId(dir, item) {
562
+ if (!item.folder) return null;
563
+ const file = path.join(dir, item.folder, "package.json");
564
+ const stat = await fs.stat(file).catch(() => null);
565
+ if (!stat?.isFile() || stat.size > 4 * 1024 * 1024) return null;
566
+ try {
567
+ const json = JSON.parse((await readText(file)) ?? "");
568
+ const id = typeof json?.publisher === "string" && typeof json?.name === "string" ? `${json.publisher}.${json.name}` : "";
569
+ return id.toLowerCase() === item.id ? id : null;
570
+ } catch {
571
+ return null;
572
+ }
573
+ }
574
+
575
+ // Files attacks leave, checked by name only. Their contents are never read.
576
+ async function traceFiles({ home, env }) {
577
+ const found = [];
578
+ for (const t of TRACES) {
579
+ if (t.platforms && !t.platforms.includes(PLATFORM)) continue;
580
+ for (const p of t.paths) {
581
+ if (p.startsWith("~/AppData/") && PLATFORM !== "windows") continue;
582
+ // Where the attack wrote them: the home folder itself, not a folder
583
+ // an environment variable points at.
584
+ const abs = p.startsWith("~/AppData/Roaming/") && env.APPDATA ? path.join(env.APPDATA, ...p.slice("~/AppData/Roaming/".length).split("/")) : p.startsWith("~/") ? path.join(home, ...p.slice(2).split("/")) : path.normalize(p);
585
+ if (await fs.lstat(abs).catch(() => null)) found.push(p);
586
+ }
587
+ }
588
+ return found;
589
+ }
590
+
591
+
592
+ // "~/..." and "{config}" style paths from locations.js, honoring the
159
593
  // environment variables agents use to move their settings.
160
594
  export function resolveUserPath(p, { home, env }) {
161
- let rel = p;
595
+ const rel = p;
596
+ if (env.CLAUDE_CONFIG_DIR && rel === "~/.claude.json") return path.join(env.CLAUDE_CONFIG_DIR, ".claude.json");
162
597
  if (env.CLAUDE_CONFIG_DIR && rel.startsWith("~/.claude/")) return path.join(env.CLAUDE_CONFIG_DIR, rel.slice("~/.claude/".length));
163
598
  if (env.CODEX_HOME && rel.startsWith("~/.codex/")) return path.join(env.CODEX_HOME, rel.slice("~/.codex/".length));
599
+ if (env.COPILOT_HOME && rel.startsWith("~/.copilot/")) return path.join(env.COPILOT_HOME, rel.slice("~/.copilot/".length));
164
600
  if (PLATFORM === "windows" && env.APPDATA && rel.startsWith("~/AppData/Roaming/")) return path.join(env.APPDATA, rel.slice("~/AppData/Roaming/".length));
165
601
  if (PLATFORM === "linux" && env.XDG_CONFIG_HOME && rel.startsWith("~/.config/")) return path.join(env.XDG_CONFIG_HOME, rel.slice("~/.config/".length));
166
602
  if (rel.startsWith("~/")) return path.join(home, ...rel.slice(2).split("/"));
167
603
  return path.normalize(rel);
168
604
  }
169
605
 
606
+ // ~/.claude.json can be large and holds account data. Keep only what the
607
+ // checks need, in the original order: MCP servers, the folders Claude Code
608
+ // has been started in and their tool approvals. lineMap[i] is the line in
609
+ // the real file that reduced line i + 1 came from, so findings point at
610
+ // lines people can open.
170
611
  function reduceClaudeJson(raw, tilde) {
171
- // ~/.claude.json can be large and holds account data. Keep only what the
172
- // checks need, in the original order: MCP servers, the folders Claude Code
173
- // has been started in and their tool approvals. lineMap[i] is the line in
174
- // the real file that reduced line i + 1 came from, so findings point at
175
- // lines people can open.
176
612
  let json;
177
613
  try {
178
614
  json = JSON.parse(raw);
179
615
  } catch {
180
- return { text: raw.slice(0, 400_000), lineMap: null };
616
+ return { text: "{}", lineMap: null };
181
617
  }
182
618
  if (!json || typeof json !== "object") return { text: "{}", lineMap: null };
183
619
  const keys = new Map(); // reduced key, as JSON, -> key in the real file, as JSON
184
620
  const out = {};
185
621
  for (const [k, v] of Object.entries(json)) {
186
- if (k === "mcpServers" || (k === "primaryApiKey" && typeof v === "string")) out[k] = v;
622
+ if (k === "mcpServers") out[k] = v;
187
623
  if (k !== "projects" || !v || typeof v !== "object") continue;
188
624
  out.projects = {};
189
625
  for (const [dir, p] of Object.entries(v)) {
@@ -193,25 +629,148 @@ function reduceClaudeJson(raw, tilde) {
193
629
  }
194
630
  }
195
631
  const text = JSON.stringify(out, null, 2);
196
- const rawLines = raw.split(/\r?\n/);
197
632
  const norm = (line) => line.trim().replace(/,$/, "");
633
+ // Where each line of the real file is, by its text, so finding the next
634
+ // match is a lookup however the file is formatted.
635
+ const at = new Map();
636
+ raw.split(/\r?\n/).forEach((line, i) => {
637
+ const key = norm(line);
638
+ if (!at.has(key)) at.set(key, []);
639
+ at.get(key).push(i);
640
+ });
641
+ const next = (want, from) => {
642
+ const list = at.get(want);
643
+ if (!list) return -1;
644
+ let lo = 0;
645
+ let hi = list.length;
646
+ while (lo < hi) {
647
+ const mid = (lo + hi) >> 1;
648
+ if (list[mid] < from) lo = mid + 1;
649
+ else hi = mid;
650
+ }
651
+ return lo < list.length ? list[lo] : -1;
652
+ };
198
653
  let cursor = 0;
199
654
  const lineMap = text.split("\n").map((line) => {
200
655
  let want = norm(line);
201
656
  const colon = want.indexOf('": ');
202
657
  if (colon > 0 && keys.has(want.slice(0, colon + 1))) want = keys.get(want.slice(0, colon + 1)) + want.slice(colon + 1);
203
- for (let i = cursor; i < rawLines.length; i++) {
204
- const have = norm(rawLines[i]);
205
- if (have === want || (want.endsWith("{}") && have === want.slice(0, -1))) {
206
- cursor = i + 1;
207
- return i + 1;
208
- }
209
- }
210
- return null;
658
+ const exact = next(want, cursor);
659
+ const open = want.endsWith("{}") ? next(want.slice(0, -1), cursor) : -1;
660
+ const i = exact < 0 ? open : open < 0 ? exact : Math.min(exact, open);
661
+ if (i < 0) return null;
662
+ cursor = i + 1;
663
+ return i + 1;
211
664
  });
212
665
  return { text, lineMap };
213
666
  }
214
667
 
668
+ // Where each installed plugin that applies here lives. Version 1 of the file
669
+ // maps each plugin to one install, version 2 to a list: installs for the
670
+ // user apply everywhere, and project and local installs only in their own
671
+ // project. A plugin installed more than once runs from its latest install.
672
+ function pluginFolders(text, projectDir) {
673
+ let json;
674
+ try {
675
+ json = JSON.parse(text);
676
+ } catch {
677
+ return [];
678
+ }
679
+ const plugins = json && typeof json.plugins === "object" && !Array.isArray(json.plugins) ? Object.values(json.plugins) : [];
680
+ const applies = (p) =>
681
+ p && typeof p === "object" && typeof p.installPath === "string" &&
682
+ (p.scope === undefined || p.scope === "user" || p.scope === "managed" || (typeof p.projectPath === "string" && samePath(p.projectPath, projectDir)));
683
+ const when = (p) => Date.parse(p.lastUpdated ?? p.installedAt ?? "") || 0;
684
+ return plugins
685
+ .map((p) => (Array.isArray(p) ? p : [p]).filter(applies))
686
+ .filter((installs) => installs.length)
687
+ .map((installs) => installs.reduce((a, b) => (when(b) >= when(a) ? b : a)).installPath);
688
+ }
689
+
690
+ // A path that plugin.json gives for its hooks or MCP servers, such as
691
+ // "./config/hooks.json". Hooks written into plugin.json itself are checked
692
+ // with the manifest.
693
+ function manifestPath(text, key) {
694
+ try {
695
+ const value = JSON.parse(text ?? "null")?.[key];
696
+ return typeof value === "string" ? value : null;
697
+ } catch {
698
+ return null;
699
+ }
700
+ }
701
+
702
+ function isInside(child, parent) {
703
+ const rel = path.relative(parent, child);
704
+ return Boolean(rel) && !rel.startsWith("..") && !path.isAbsolute(rel);
705
+ }
706
+
707
+ // The real paths a location names, as { abs, name }. "*" matches any one
708
+ // folder or file name. `name` is the "~/..." form with the matches filled
709
+ // in, when the location is written that way.
710
+ async function expand(abs, pattern) {
711
+ // The root, such as /, C:\ or \\server\share\, is kept as it is.
712
+ const { root } = path.parse(abs);
713
+ let found = [{ abs: root, names: [] }];
714
+ for (const part of abs.slice(root.length).split(/[\\/]+/)) {
715
+ if (!part) continue;
716
+ if (!part.includes("*")) {
717
+ found = found.map((f) => ({ ...f, abs: path.join(f.abs, part) }));
718
+ continue;
719
+ }
720
+ const re = new RegExp(`^${part.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "i");
721
+ const next = [];
722
+ for (const f of found) {
723
+ for (const entry of await readdir(f.abs)) if (re.test(entry.name) && next.length < 200) next.push({ abs: path.join(f.abs, entry.name), names: [...f.names, entry.name] });
724
+ }
725
+ found = next;
726
+ }
727
+ return found.map((f) => {
728
+ let i = 0;
729
+ const name = pattern ? pattern.split("/").map((seg) => (seg.includes("*") ? f.names[i++] : seg)).join("/") : null;
730
+ return { abs: f.abs, name };
731
+ });
732
+ }
733
+
734
+ // A file's text, read through one handle and never past `max` bytes, so a
735
+ // file that grows while it's read, or a special file put in its place, can't
736
+ // be read past the limit or hold the check up. `bytes` is how much was read.
737
+ async function readLimited(abs, max, start = false) {
738
+ let handle = null;
739
+ try {
740
+ handle = await fs.open(abs, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
741
+ if (!(await handle.stat()).isFile()) return { text: null, bytes: 0 };
742
+ const chunks = [];
743
+ const chunk = Buffer.alloc(64 * 1024);
744
+ let size = 0;
745
+ for (;;) {
746
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, size);
747
+ if (!bytesRead) break;
748
+ const keep = Math.min(bytesRead, max - size);
749
+ if (start && keep > 0) chunks.push(Buffer.from(chunk.subarray(0, keep)));
750
+ size += bytesRead;
751
+ // With `start`, the first `max` bytes are kept and the rest isn't read.
752
+ if (size > max) return start ? { text: decodeText(Buffer.concat(chunks, max)), bytes: max } : { text: null, bytes: size, tooLarge: true };
753
+ if (!start) chunks.push(Buffer.from(chunk.subarray(0, bytesRead)));
754
+ }
755
+ return { text: decodeText(Buffer.concat(chunks, size)), bytes: size };
756
+ } catch {
757
+ return { text: null, bytes: 0 };
758
+ } finally {
759
+ await handle?.close().catch(() => {});
760
+ }
761
+ }
762
+
763
+ async function readText(abs, max = 32 * 1024 * 1024) {
764
+ return (await readLimited(abs, max)).text;
765
+ }
766
+
767
+ async function readIgnoreList(abs, into) {
768
+ const stat = await fs.stat(abs).catch(() => null);
769
+ if (!stat?.isFile() || stat.size > 64 * 1024) return;
770
+ const content = await readText(abs);
771
+ if (content) into.push({ content });
772
+ }
773
+
215
774
  async function readdir(dir) {
216
775
  try {
217
776
  return await fs.readdir(dir, { withFileTypes: true });
@@ -220,17 +779,36 @@ async function readdir(dir) {
220
779
  }
221
780
  }
222
781
 
223
- async function listFiles(dir, depth) {
782
+ // The files under `dir`, up to `depth` folders down, that `accept` takes.
783
+ // Breadth first, so each skill's SKILL.md is found before the reference
784
+ // files beneath it, and the limits count only accepted files plus a cap on
785
+ // everything looked at, so a folder of thousands of docs can't hide the
786
+ // files after it or hold up the check.
787
+ async function listFiles(dir, depth, accept, enter = () => false) {
224
788
  const out = [];
225
- for (const entry of await readdir(dir)) {
226
- const abs = path.join(dir, entry.name);
227
- if (entry.isDirectory() && depth > 0 && !isSkippedDir(entry.name)) out.push(...(await listFiles(abs, depth - 1)));
228
- else if (entry.isFile()) out.push(abs);
229
- if (out.length > 300) break;
789
+ const queue = [[dir, 0]];
790
+ let looked = 0;
791
+ for (let q = 0; q < queue.length; q++) {
792
+ const [current, level] = queue[q];
793
+ for (const entry of await readdir(current)) {
794
+ if (++looked > 20_000 || out.length >= 300) return out;
795
+ const abs = path.join(current, entry.name);
796
+ if (entry.isDirectory()) {
797
+ if (level < depth && (!isSkippedDir(entry.name) || enter(abs))) queue.push([abs, level + 1]);
798
+ } else if ((entry.isFile() || entry.isSymbolicLink()) && accept(abs)) out.push(abs);
799
+ }
230
800
  }
231
801
  return out;
232
802
  }
233
803
 
804
+ function homeDir() {
805
+ try {
806
+ return os.homedir() || null;
807
+ } catch {
808
+ return null;
809
+ }
810
+ }
811
+
234
812
  function samePath(a, b) {
235
813
  const norm = (p) => path.resolve(p).replace(/[\\/]+$/, "");
236
814
  return PLATFORM === "linux" ? norm(a) === norm(b) : norm(a).toLowerCase() === norm(b).toLowerCase();