@misconfig/cli 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 the same limits as the browser check.
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,543 @@ 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, as in the browser check.
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 the same limits as the browser
176
+ // check: agent files, then the .gitignore and package.json files some
177
+ // checks use, then files listed 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 },
317
+ };
318
+ }
319
+
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
+ // Versions of packages that were malware, in the project's node_modules.
335
+ const NPM_KNOWN = Object.keys(KNOWN_PACKAGES).filter((k) => k.startsWith("npm:")).map((k) => k.slice(4));
336
+ async function projectPackages(projectDir) {
337
+ const out = [];
338
+ for (const name of NPM_KNOWN) {
339
+ const found = await packageVersion(path.join(projectDir, "node_modules", ...name.split("/"), "package.json"));
340
+ if (found?.name === name) out.push({ package: name, version: found.version, via: "project", path: `node_modules/${name}` });
341
+ }
342
+ // pnpm keeps every package, including ones other packages pulled in, in
343
+ // node_modules/.pnpm, in folders named name@version (@scope+name@version).
344
+ // The names say enough; nothing in them is read.
345
+ const known = new Set(NPM_KNOWN);
346
+ for (const entry of (await readdir(path.join(projectDir, "node_modules", ".pnpm"))).slice(0, 30_000)) {
347
+ const m = entry.isDirectory() ? entry.name.match(/^((?:@[^+@/]+\+)?[^+@/]+)@([^_/]+)/) : null;
348
+ const name = m ? m[1].replace("+", "/") : null;
349
+ if (!name || !known.has(name) || !VERSION_RE.test(m[2])) continue;
350
+ if (out.some((i) => i.package === name && i.version === m[2])) continue;
351
+ out.push({ package: name, version: m[2], via: "project", path: `node_modules/.pnpm/${entry.name}/node_modules/${name}` });
352
+ }
353
+ return out;
354
+ }
355
+
356
+ // Versions of packages that were malware, pinned in the project's lockfile,
357
+ // so a check before installing (in CI, say) still finds them. Only names and
358
+ // versions are looked for: in the registry addresses npm and Yarn write
359
+ // (/nx/-/nx-21.5.0.tgz), in npm's entries ("node_modules/nx": { "version":
360
+ // "21.5.0" }, which have no address when omit-lockfile-registry-resolved is
361
+ // set), and in the name@version keys pnpm, Bun and Yarn 2+ write (/nx/21.5.0
362
+ // in pnpm's older lockfiles). Nothing else in the file is kept.
363
+ const LOCKFILES = ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock"];
364
+ const MAX_LOCKFILE_BYTES = 64 * 1024 * 1024;
365
+ const SEMVER = String.raw`\d{1,6}\.\d{1,6}\.\d{1,6}(?:-[0-9A-Za-z.-]{1,40})?`;
366
+ const LOCKED_URL = new RegExp(String.raw`/((?:@[a-z0-9][a-z0-9._~-]{0,100}/)?[a-z0-9][a-z0-9._~-]{0,213})/-/[a-z0-9][a-z0-9._~-]{0,213}-(${SEMVER})\.tgz`, "g");
367
+ async function lockedPackages(projectDir) {
368
+ const known = new Set(NPM_KNOWN);
369
+ const names = NPM_KNOWN.map((n) => n.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|");
370
+ const keyed = new RegExp(String.raw`(?:^|["'/\s])(${names})@(?:npm:)?(${SEMVER})(?=["'\s:(_,]|$)`, "gm");
371
+ // npm's own entries, nested or not, and lockfile version 1's "nx": { "version" }.
372
+ const entry = new RegExp(String.raw`"(?:node_modules/(?:[^"\n]{0,400}?/node_modules/)?)?(${names})":\s{0,20}\{[^{}]{0,2000}?"version":\s{0,20}"(${SEMVER})"`, "g");
373
+ const pnpmOld = new RegExp(String.raw`^\s{0,8}['"]?/(${names})/(${SEMVER})(?=[:_('"]|$)`, "gm");
374
+ const out = [];
375
+ for (const file of LOCKFILES) {
376
+ const abs = path.join(projectDir, file);
377
+ const stat = await fs.stat(abs).catch(() => null);
378
+ if (!stat?.isFile() || stat.size > MAX_LOCKFILE_BYTES) continue;
379
+ const text = await fs.readFile(abs, "utf8").catch(() => "");
380
+ const seen = new Set();
381
+ for (const re of [LOCKED_URL, keyed, entry, pnpmOld]) {
382
+ for (const m of text.matchAll(re)) {
383
+ const key = `${m[1]}@${m[2]}`;
384
+ // An npm alias ("node_modules/nx": { "name": "other" }) is some other package.
385
+ if (re === entry && m[0].includes('"name":')) continue;
386
+ if (!known.has(m[1]) || seen.has(key) || seen.size >= 200) continue;
387
+ seen.add(key);
388
+ out.push({ file, package: m[1], version: m[2] });
389
+ }
390
+ }
391
+ }
392
+ return out;
393
+ }
394
+
395
+ // Folders where npm, pnpm, bun and Node version managers keep global packages.
396
+ async function globalPackageDirs({ home, env }) {
397
+ const at = (...parts) => path.join(home, ...parts);
398
+ const each = async (pattern) => (await expand(pattern, null)).map((x) => x.abs);
399
+ const dirs =
400
+ PLATFORM === "windows"
401
+ ? [
402
+ env.APPDATA && path.join(env.APPDATA, "npm", "node_modules"),
403
+ env.ProgramFiles && path.join(env.ProgramFiles, "nodejs", "node_modules"),
404
+ ...(env.APPDATA ? await each(path.join(env.APPDATA, "nvm", "v*", "node_modules")) : []),
405
+ env.LOCALAPPDATA && path.join(env.LOCALAPPDATA, "pnpm", "global", "5", "node_modules"),
406
+ at(".bun", "install", "global", "node_modules"),
407
+ ]
408
+ : [
409
+ "/usr/local/lib/node_modules",
410
+ "/opt/homebrew/lib/node_modules",
411
+ "/usr/lib/node_modules",
412
+ at(".npm-global", "lib", "node_modules"),
413
+ at(".local", "lib", "node_modules"),
414
+ at(".bun", "install", "global", "node_modules"),
415
+ ...(await each(at(".nvm", "versions", "node", "*", "lib", "node_modules"))),
416
+ ...(await each(at(".asdf", "installs", "nodejs", "*", "lib", "node_modules"))),
417
+ ...(await each(at(".local", "share", "fnm", "node-versions", "*", "installation", "lib", "node_modules"))),
418
+ ...(await each(at("Library", "Application Support", "fnm", "node-versions", "*", "installation", "lib", "node_modules"))),
419
+ ...(await each(at(".local", "share", "pnpm", "global", "*", "node_modules"))),
420
+ ...(await each(at("Library", "pnpm", "global", "*", "node_modules"))),
421
+ ];
422
+ 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"));
423
+ return [...new Set(dirs.filter(Boolean))].slice(0, 60);
424
+ }
425
+
426
+ // Installed AI agents and their versions, read from package.json files,
427
+ // version folders and app bundles. Nothing is run.
428
+ async function agentInstalls({ home, env, tilde }) {
429
+ const out = [];
430
+ const seen = new Set();
431
+ const push = (pkg, version, via, abs) => {
432
+ const key = `${pkg}|${version}|${abs}`;
433
+ if (seen.has(key) || !VERSION_RE.test(version)) return;
434
+ seen.add(key);
435
+ out.push({ package: pkg, version, via, path: tilde(abs), platform: PLATFORM });
155
436
  };
437
+ const npmPackages = [...Object.keys(AGENT_PACKAGES).filter((p) => p !== "Claude Desktop"), ...NPM_KNOWN];
438
+ for (const dir of await globalPackageDirs({ home, env })) {
439
+ for (const name of npmPackages) {
440
+ const found = await packageVersion(path.join(dir, ...name.split("/"), "package.json"));
441
+ if (found?.name === name) push(name, found.version, /pnpm/i.test(dir) ? "pnpm" : /[\\/]\.bun[\\/]/.test(dir) ? "bun" : "npm", path.join(dir, ...name.split("/")));
442
+ }
443
+ }
444
+ const voltaRoot = PLATFORM === "windows" && env.LOCALAPPDATA ? path.join(env.LOCALAPPDATA, "Volta") : path.join(home, ".volta");
445
+ for (const name of npmPackages) {
446
+ const image = path.join(voltaRoot, "tools", "image", "packages", ...name.split("/"));
447
+ // Volta keeps the package under lib/node_modules, or node_modules on Windows.
448
+ for (const lib of [["lib", "node_modules"], ["node_modules"]]) {
449
+ const found = await packageVersion(path.join(image, ...lib, ...name.split("/"), "package.json"));
450
+ if (found?.name === name) push(name, found.version, "volta", image);
451
+ }
452
+ }
453
+ // Claude Code's own installer keeps each version in a folder named after
454
+ // it and links the one in use from ~/.local/bin. Its older local install
455
+ // has a package.json.
456
+ const versions = path.join(home, ".local", "share", "claude", "versions");
457
+ const launcher = await fs.readlink(path.join(home, ".local", "bin", PLATFORM === "windows" ? "claude.exe" : "claude")).catch(() => null);
458
+ const native = (await readdir(versions)).map((d) => d.name).filter((n) => VERSION_RE.test(n)).sort(byVersion);
459
+ const active = launcher ? path.basename(launcher) : null;
460
+ const current = active && native.includes(active) ? active : native.pop();
461
+ if (current) push("@anthropic-ai/claude-code", current, "native", path.join(versions, current));
462
+ const local = await packageVersion(path.join(home, ".claude", "local", "node_modules", "@anthropic-ai", "claude-code", "package.json"));
463
+ if (local?.name === "@anthropic-ai/claude-code") push("@anthropic-ai/claude-code", local.version, "local", path.join(home, ".claude", "local"));
464
+ // Homebrew formulas and casks, by their version folders.
465
+ if (PLATFORM !== "windows") {
466
+ const brews = [["@anthropic-ai/claude-code", "Caskroom/claude-code"], ["@openai/codex", "Cellar/codex"], ["@openai/codex", "Caskroom/codex"], ["@google/gemini-cli", "Cellar/gemini-cli"]];
467
+ for (const prefix of ["/opt/homebrew", "/usr/local", "/home/linuxbrew/.linuxbrew"]) {
468
+ for (const [pkg, name] of brews) {
469
+ const dir = path.join(prefix, ...name.split("/"));
470
+ // A rebuilt formula's folder ends in _1, _2 and so on.
471
+ const found = (await readdir(dir)).map((d) => d.name).filter((n) => VERSION_RE.test(n.replace(/_\d+$/, ""))).sort(byVersion).pop();
472
+ if (found) push(pkg, found.replace(/_\d+$/, ""), "homebrew", path.join(dir, found));
473
+ }
474
+ }
475
+ }
476
+ // Claude Desktop: the app bundle's version on macOS, the app-<version>
477
+ // folders on Windows.
478
+ if (PLATFORM === "mac") {
479
+ for (const app of ["/Applications/Claude.app", path.join(home, "Applications", "Claude.app")]) {
480
+ const file = path.join(app, "Contents", "Info.plist");
481
+ const stat = await fs.stat(file).catch(() => null);
482
+ const plist = stat?.isFile() && stat.size < 200_000 ? ((await readText(file)) ?? "") : "";
483
+ const m = plist.match(/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]{1,40})<\/string>/);
484
+ if (m) push("Claude Desktop", m[1].trim(), "app", app);
485
+ }
486
+ } else if (PLATFORM === "windows" && env.LOCALAPPDATA) {
487
+ const dir = path.join(env.LOCALAPPDATA, "AnthropicClaude");
488
+ const latest = (await readdir(dir)).map((d) => d.name.match(/^app-(.+)$/)?.[1]).filter((v) => v && VERSION_RE.test(v)).sort(byVersion).pop();
489
+ if (latest) push("Claude Desktop", latest, "app", path.join(dir, `app-${latest}`));
490
+ }
491
+ return out;
492
+ }
493
+
494
+ // Editor extensions: VS Code and the editors built on it keep a list in
495
+ // extensions.json and a folder per extension named publisher.name-version.
496
+ const EDITOR_DIRS = [
497
+ ["VS Code", ".vscode"],
498
+ ["VS Code Insiders", ".vscode-insiders"],
499
+ ["VSCodium", ".vscode-oss"],
500
+ ["Cursor", ".cursor"],
501
+ ["Windsurf", ".windsurf"],
502
+ ["Kiro", ".kiro"],
503
+ ];
504
+ 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;
505
+ async function editorExtensions({ home, env, tilde }) {
506
+ const out = [];
507
+ for (const [editor, folder] of EDITOR_DIRS) {
508
+ const dir = editor === "VS Code" && env.VSCODE_EXTENSIONS ? env.VSCODE_EXTENSIONS : path.join(home, folder, "extensions");
509
+ const entries = await readdir(dir);
510
+ if (!entries.length) continue;
511
+ const items = new Map();
512
+ const list = path.join(dir, "extensions.json");
513
+ const stat = await fs.stat(list).catch(() => null);
514
+ if (stat?.isFile() && stat.size <= 4 * 1024 * 1024) {
515
+ let json = null;
516
+ try {
517
+ json = JSON.parse((await readText(list)) ?? "");
518
+ } catch {}
519
+ for (const e of Array.isArray(json) ? json.slice(0, 3000) : []) {
520
+ const id = typeof e?.identifier?.id === "string" ? e.identifier.id.toLowerCase() : null;
521
+ const version = typeof e?.version === "string" ? e.version : "";
522
+ if (id) items.set(`${id}@${version}`, { id, version, source: typeof e?.metadata?.source === "string" ? e.metadata.source : null });
523
+ }
524
+ }
525
+ // Folders on disk too, including old versions not cleaned up yet.
526
+ for (const entry of entries.slice(0, 3000)) {
527
+ const m = entry.isDirectory() ? entry.name.match(EXTENSION_FOLDER) : null;
528
+ 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 });
529
+ }
530
+ if (items.size) out.push({ editor, dir: tilde(dir), items: [...items.values()] });
531
+ }
532
+ return out;
533
+ }
534
+
535
+ // Files attacks leave, checked by name only. Their contents are never read.
536
+ async function traceFiles({ home, env }) {
537
+ const found = [];
538
+ for (const t of TRACES) {
539
+ if (t.platforms && !t.platforms.includes(PLATFORM)) continue;
540
+ for (const p of t.paths) {
541
+ if (p.startsWith("~/AppData/") && PLATFORM !== "windows") continue;
542
+ // Where the attack wrote them: the home folder itself, not a folder
543
+ // an environment variable points at.
544
+ 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);
545
+ if (await fs.lstat(abs).catch(() => null)) found.push(p);
546
+ }
547
+ }
548
+ return found;
156
549
  }
157
550
 
158
- // "~/..." and "{config}" style paths from locations.js, honouring the
551
+
552
+ // "~/..." and "{config}" style paths from locations.js, honoring the
159
553
  // environment variables agents use to move their settings.
160
554
  export function resolveUserPath(p, { home, env }) {
161
- let rel = p;
555
+ const rel = p;
556
+ if (env.CLAUDE_CONFIG_DIR && rel === "~/.claude.json") return path.join(env.CLAUDE_CONFIG_DIR, ".claude.json");
162
557
  if (env.CLAUDE_CONFIG_DIR && rel.startsWith("~/.claude/")) return path.join(env.CLAUDE_CONFIG_DIR, rel.slice("~/.claude/".length));
163
558
  if (env.CODEX_HOME && rel.startsWith("~/.codex/")) return path.join(env.CODEX_HOME, rel.slice("~/.codex/".length));
559
+ if (env.COPILOT_HOME && rel.startsWith("~/.copilot/")) return path.join(env.COPILOT_HOME, rel.slice("~/.copilot/".length));
164
560
  if (PLATFORM === "windows" && env.APPDATA && rel.startsWith("~/AppData/Roaming/")) return path.join(env.APPDATA, rel.slice("~/AppData/Roaming/".length));
165
561
  if (PLATFORM === "linux" && env.XDG_CONFIG_HOME && rel.startsWith("~/.config/")) return path.join(env.XDG_CONFIG_HOME, rel.slice("~/.config/".length));
166
562
  if (rel.startsWith("~/")) return path.join(home, ...rel.slice(2).split("/"));
167
563
  return path.normalize(rel);
168
564
  }
169
565
 
566
+ // ~/.claude.json can be large and holds account data. Keep only what the
567
+ // checks need, in the original order: MCP servers, the folders Claude Code
568
+ // has been started in and their tool approvals. lineMap[i] is the line in
569
+ // the real file that reduced line i + 1 came from, so findings point at
570
+ // lines people can open.
170
571
  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
572
  let json;
177
573
  try {
178
574
  json = JSON.parse(raw);
179
575
  } catch {
180
- return { text: raw.slice(0, 400_000), lineMap: null };
576
+ return { text: "{}", lineMap: null };
181
577
  }
182
578
  if (!json || typeof json !== "object") return { text: "{}", lineMap: null };
183
579
  const keys = new Map(); // reduced key, as JSON, -> key in the real file, as JSON
184
580
  const out = {};
185
581
  for (const [k, v] of Object.entries(json)) {
186
- if (k === "mcpServers" || (k === "primaryApiKey" && typeof v === "string")) out[k] = v;
582
+ if (k === "mcpServers") out[k] = v;
187
583
  if (k !== "projects" || !v || typeof v !== "object") continue;
188
584
  out.projects = {};
189
585
  for (const [dir, p] of Object.entries(v)) {
@@ -193,25 +589,148 @@ function reduceClaudeJson(raw, tilde) {
193
589
  }
194
590
  }
195
591
  const text = JSON.stringify(out, null, 2);
196
- const rawLines = raw.split(/\r?\n/);
197
592
  const norm = (line) => line.trim().replace(/,$/, "");
593
+ // Where each line of the real file is, by its text, so finding the next
594
+ // match is a lookup however the file is formatted.
595
+ const at = new Map();
596
+ raw.split(/\r?\n/).forEach((line, i) => {
597
+ const key = norm(line);
598
+ if (!at.has(key)) at.set(key, []);
599
+ at.get(key).push(i);
600
+ });
601
+ const next = (want, from) => {
602
+ const list = at.get(want);
603
+ if (!list) return -1;
604
+ let lo = 0;
605
+ let hi = list.length;
606
+ while (lo < hi) {
607
+ const mid = (lo + hi) >> 1;
608
+ if (list[mid] < from) lo = mid + 1;
609
+ else hi = mid;
610
+ }
611
+ return lo < list.length ? list[lo] : -1;
612
+ };
198
613
  let cursor = 0;
199
614
  const lineMap = text.split("\n").map((line) => {
200
615
  let want = norm(line);
201
616
  const colon = want.indexOf('": ');
202
617
  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;
618
+ const exact = next(want, cursor);
619
+ const open = want.endsWith("{}") ? next(want.slice(0, -1), cursor) : -1;
620
+ const i = exact < 0 ? open : open < 0 ? exact : Math.min(exact, open);
621
+ if (i < 0) return null;
622
+ cursor = i + 1;
623
+ return i + 1;
211
624
  });
212
625
  return { text, lineMap };
213
626
  }
214
627
 
628
+ // Where each installed plugin that applies here lives. Version 1 of the file
629
+ // maps each plugin to one install, version 2 to a list: installs for the
630
+ // user apply everywhere, and project and local installs only in their own
631
+ // project. A plugin installed more than once runs from its latest install.
632
+ function pluginFolders(text, projectDir) {
633
+ let json;
634
+ try {
635
+ json = JSON.parse(text);
636
+ } catch {
637
+ return [];
638
+ }
639
+ const plugins = json && typeof json.plugins === "object" && !Array.isArray(json.plugins) ? Object.values(json.plugins) : [];
640
+ const applies = (p) =>
641
+ p && typeof p === "object" && typeof p.installPath === "string" &&
642
+ (p.scope === undefined || p.scope === "user" || p.scope === "managed" || (typeof p.projectPath === "string" && samePath(p.projectPath, projectDir)));
643
+ const when = (p) => Date.parse(p.lastUpdated ?? p.installedAt ?? "") || 0;
644
+ return plugins
645
+ .map((p) => (Array.isArray(p) ? p : [p]).filter(applies))
646
+ .filter((installs) => installs.length)
647
+ .map((installs) => installs.reduce((a, b) => (when(b) >= when(a) ? b : a)).installPath);
648
+ }
649
+
650
+ // A path that plugin.json gives for its hooks or MCP servers, such as
651
+ // "./config/hooks.json". Hooks written into plugin.json itself are checked
652
+ // with the manifest.
653
+ function manifestPath(text, key) {
654
+ try {
655
+ const value = JSON.parse(text ?? "null")?.[key];
656
+ return typeof value === "string" ? value : null;
657
+ } catch {
658
+ return null;
659
+ }
660
+ }
661
+
662
+ function isInside(child, parent) {
663
+ const rel = path.relative(parent, child);
664
+ return Boolean(rel) && !rel.startsWith("..") && !path.isAbsolute(rel);
665
+ }
666
+
667
+ // The real paths a location names, as { abs, name }. "*" matches any one
668
+ // folder or file name. `name` is the "~/..." form with the matches filled
669
+ // in, when the location is written that way.
670
+ async function expand(abs, pattern) {
671
+ // The root, such as /, C:\ or \\server\share\, is kept as it is.
672
+ const { root } = path.parse(abs);
673
+ let found = [{ abs: root, names: [] }];
674
+ for (const part of abs.slice(root.length).split(/[\\/]+/)) {
675
+ if (!part) continue;
676
+ if (!part.includes("*")) {
677
+ found = found.map((f) => ({ ...f, abs: path.join(f.abs, part) }));
678
+ continue;
679
+ }
680
+ const re = new RegExp(`^${part.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "i");
681
+ const next = [];
682
+ for (const f of found) {
683
+ 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] });
684
+ }
685
+ found = next;
686
+ }
687
+ return found.map((f) => {
688
+ let i = 0;
689
+ const name = pattern ? pattern.split("/").map((seg) => (seg.includes("*") ? f.names[i++] : seg)).join("/") : null;
690
+ return { abs: f.abs, name };
691
+ });
692
+ }
693
+
694
+ // A file's text, read through one handle and never past `max` bytes, so a
695
+ // file that grows while it's read, or a special file put in its place, can't
696
+ // be read past the limit or hold the check up. `bytes` is how much was read.
697
+ async function readLimited(abs, max, start = false) {
698
+ let handle = null;
699
+ try {
700
+ handle = await fs.open(abs, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
701
+ if (!(await handle.stat()).isFile()) return { text: null, bytes: 0 };
702
+ const chunks = [];
703
+ const chunk = Buffer.alloc(64 * 1024);
704
+ let size = 0;
705
+ for (;;) {
706
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, size);
707
+ if (!bytesRead) break;
708
+ const keep = Math.min(bytesRead, max - size);
709
+ if (start && keep > 0) chunks.push(Buffer.from(chunk.subarray(0, keep)));
710
+ size += bytesRead;
711
+ // With `start`, the first `max` bytes are kept and the rest isn't read.
712
+ if (size > max) return start ? { text: decodeText(Buffer.concat(chunks, max)), bytes: max } : { text: null, bytes: size, tooLarge: true };
713
+ if (!start) chunks.push(Buffer.from(chunk.subarray(0, bytesRead)));
714
+ }
715
+ return { text: decodeText(Buffer.concat(chunks, size)), bytes: size };
716
+ } catch {
717
+ return { text: null, bytes: 0 };
718
+ } finally {
719
+ await handle?.close().catch(() => {});
720
+ }
721
+ }
722
+
723
+ async function readText(abs, max = 32 * 1024 * 1024) {
724
+ return (await readLimited(abs, max)).text;
725
+ }
726
+
727
+ async function readIgnoreList(abs, into) {
728
+ const stat = await fs.stat(abs).catch(() => null);
729
+ if (!stat?.isFile() || stat.size > 64 * 1024) return;
730
+ const content = await readText(abs);
731
+ if (content) into.push({ content });
732
+ }
733
+
215
734
  async function readdir(dir) {
216
735
  try {
217
736
  return await fs.readdir(dir, { withFileTypes: true });
@@ -220,17 +739,36 @@ async function readdir(dir) {
220
739
  }
221
740
  }
222
741
 
223
- async function listFiles(dir, depth) {
742
+ // The files under `dir`, up to `depth` folders down, that `accept` takes.
743
+ // Breadth first, so each skill's SKILL.md is found before the reference
744
+ // files beneath it, and the limits count only accepted files plus a cap on
745
+ // everything looked at, so a folder of thousands of docs can't hide the
746
+ // files after it or hold up the check.
747
+ async function listFiles(dir, depth, accept, enter = () => false) {
224
748
  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;
749
+ const queue = [[dir, 0]];
750
+ let looked = 0;
751
+ for (let q = 0; q < queue.length; q++) {
752
+ const [current, level] = queue[q];
753
+ for (const entry of await readdir(current)) {
754
+ if (++looked > 20_000 || out.length >= 300) return out;
755
+ const abs = path.join(current, entry.name);
756
+ if (entry.isDirectory()) {
757
+ if (level < depth && (!isSkippedDir(entry.name) || enter(abs))) queue.push([abs, level + 1]);
758
+ } else if ((entry.isFile() || entry.isSymbolicLink()) && accept(abs)) out.push(abs);
759
+ }
230
760
  }
231
761
  return out;
232
762
  }
233
763
 
764
+ function homeDir() {
765
+ try {
766
+ return os.homedir() || null;
767
+ } catch {
768
+ return null;
769
+ }
770
+ }
771
+
234
772
  function samePath(a, b) {
235
773
  const norm = (p) => path.resolve(p).replace(/[\\/]+$/, "");
236
774
  return PLATFORM === "linux" ? norm(a) === norm(b) : norm(a).toLowerCase() === norm(b).toLowerCase();