// src/addons/ai-tools.ts // AI tools on this machine that are not agents node9 hooks (layer L1 of the // CISO gap map): chat apps, local model runtimes, coding agents node9 has no // hook for, and AI browser extensions. Part of the add-ons report, so the // dashboard can answer "which AI tools run on my machines". // // What leaves the machine: the tools of ai-tools-catalog.ts that are // installed (id, name, version, where found), local model names, and one // kind of extension outside the catalog: one whose manifest asks for access // to an AI chat site, with its id, the name it gives itself and those sites. // What never leaves: the list of installed apps or extensions, a file path, // a browser profile name, the OS user name. // // File and directory reads only: no process is started, no registry is // read, no network call is made. Bounded; every failure yields less data, // never a throw. For the daemon's snapshot, never an agent hook. import fs from 'fs'; import os from 'os'; import path from 'path'; import { AI_CHAT_HOSTS, AI_TOOLS, type CatalogTool, type ToolKind } from './ai-tools-catalog'; export interface AddonTool { /** Catalog id (`chatgpt-desktop`, `cline`), or `ext:` for an * extension outside the catalog that asks for access to an AI chat site. */ id: string; kind: ToolKind; /** Catalog name; for an `ext:` row the name the extension gives itself. */ name: string; vendor?: string; version?: string; /** Where it was found: `desktop`, `path`, a browser or an editor. */ where: string[]; /** `ext:` rows only: the AI chat sites the extension asks access to. */ aiHosts?: string[]; /** `models` only: names of the models on disk. */ models?: string[]; } export const MAX_TOOLS = 60; const MAX_PROFILES = 8; const MAX_MANIFESTS = 300; const MAX_MANIFEST_BYTES = 256 * 1024; const MAX_EXTENSIONS_JSON_BYTES = 2 * 1024 * 1024; const MAX_EXTENSIONS_PER_PROFILE = 400; const MAX_PATH_DIRS = 40; const MAX_DIR_ENTRIES = 5000; const MAX_MODELS = 20; const MAX_AI_HOSTS = 8; const MAX_NAME = 80; export interface AiToolsOptions { /** Prefix for the absolute system folders (`/Applications`, `/usr/share`), * so a test can point them at a temp folder. */ root?: string; /** The catalog to match against; the built-in one by default. */ catalog?: CatalogTool[]; /** Counts the manifests read, for the bound's test. */ stats?: { manifests: number }; } // ── Small bounded readers ─────────────────────────────────────────────────── /** A regular file's text up to `max` bytes, read through one descriptor (the * type and size checked are those of the file read). Null on anything else. */ function readCapped(file: string, max: number): string | null { let fd: number | undefined; try { const c = fs.constants; // No symlink is followed: a planted link must not make another file read. fd = fs.openSync(file, c.O_RDONLY | (c.O_NOFOLLOW ?? 0) | (c.O_NONBLOCK ?? 0)); const st = fs.fstatSync(fd); if (!st.isFile() || st.size > max) return null; const buf = Buffer.alloc(st.size); const n = fs.readSync(fd, buf, 0, st.size, 0); return buf.subarray(0, n).toString('utf8'); } catch { return null; } finally { if (fd !== undefined) { try { fs.closeSync(fd); } catch { /* nothing to do */ } } } } function readJson(file: string, max: number): unknown { const text = readCapped(file, max); if (text === null) return null; try { return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text); } catch { return null; } } /** The names in a folder (bounded), or []. */ function names(dir: string, max = MAX_DIR_ENTRIES): string[] { try { return fs.readdirSync(dir).slice(0, max); } catch { return []; } } /** The sub-folders of a folder (bounded, sorted), or []. */ function subDirs(dir: string, max = MAX_DIR_ENTRIES): string[] { try { return fs .readdirSync(dir, { withFileTypes: true }) .filter((e) => e.isDirectory()) .map((e) => e.name) .sort() .slice(0, max); } catch { return []; } } function exists(p: string): boolean { try { fs.statSync(p); return true; } catch { return false; } } /** A program a shell would run: a regular file, executable where the * platform has the bit (Windows has none; the name's suffix says it). */ function isProgram(p: string, platform: NodeJS.Platform): boolean { try { if (!fs.statSync(p).isFile()) return false; if (platform !== 'win32') fs.accessSync(p, fs.constants.X_OK); return true; } catch { return false; } } function isRecord(v: unknown): v is Record { return typeof v === 'object' && v !== null && !Array.isArray(v); } /** A name fit to send: one line, no control characters, bounded. */ function cleanName(v: unknown): string { if (typeof v !== 'string') return ''; // Control and format characters (line breaks, direction overrides) out. return v .replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu, ' ') .replace(/\s+/g, ' ') .trim() .slice(0, MAX_NAME); } function cleanVersion(v: unknown): string | undefined { return typeof v === 'string' && /^[0-9A-Za-z][0-9A-Za-z.+_-]{0,39}$/.test(v) ? v : undefined; } // ── The result under construction ─────────────────────────────────────────── class Found { private readonly byId = new Map(); add(tool: Omit, where: string): void { const row = this.byId.get(tool.id); if (!row) { this.byId.set(tool.id, { ...tool, where: [where] }); return; } if (!row.where.includes(where)) row.where.push(where); if (!row.version && tool.version) row.version = tool.version; if (tool.models?.length) row.models = [...new Set([...(row.models ?? []), ...tool.models])] .sort() .slice(0, MAX_MODELS); if (tool.aiHosts?.length) row.aiHosts = [...new Set([...(row.aiHosts ?? []), ...tool.aiHosts])] .sort() .slice(0, MAX_AI_HOSTS); } addCatalog(t: CatalogTool, where: string, extra: { version?: string; models?: string[] } = {}) { this.add( { id: t.id, kind: t.kind, name: t.name, ...(t.vendor ? { vendor: t.vendor } : {}), ...(extra.version ? { version: extra.version } : {}), ...(extra.models?.length ? { models: extra.models } : {}), }, where ); } /** Catalog rows first, then the extensions outside it, each by id: a cut * list drops those last, and two reports of one machine compare equal. */ list(): { tools: AddonTool[]; capped: boolean } { const rows = [...this.byId.values()].map((r) => ({ ...r, where: [...r.where].sort() })); const rank = (r: AddonTool): number => (r.id.startsWith('ext:') ? 1 : 0); rows.sort((a, b) => rank(a) - rank(b) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); return { tools: rows.slice(0, MAX_TOOLS), capped: rows.length > MAX_TOOLS }; } } // ── Desktop apps ──────────────────────────────────────────────────────────── function lowerSet(list: string[]): Set { return new Set(list.map((n) => n.toLowerCase())); } function desktopApps( found: Found, catalog: CatalogTool[], home: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform, root: string ): void { if (platform === 'darwin') { const apps = lowerSet([ ...names(path.join(root, '/Applications')), ...names(path.join(home, 'Applications')), ]); for (const t of catalog) if (t.macApps?.some((a) => apps.has(a.toLowerCase()))) found.addCatalog(t, 'desktop'); return; } if (platform === 'win32') { const local = env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'); const packages = names(path.join(local, 'Packages')).map((n) => n.toLowerCase()); const dirs = lowerSet([ ...names(path.join(local, 'Programs')), ...(env.ProgramFiles ? names(env.ProgramFiles) : []), ...(env['ProgramFiles(x86)'] ? names(env['ProgramFiles(x86)'] as string) : []), ]); for (const t of catalog) { const store = t.winPackages?.some((p) => packages.some((n) => n.startsWith(p.toLowerCase()))); const plain = t.winDirs?.some((d) => dirs.has(d.toLowerCase())); if (store || plain) found.addCatalog(t, 'desktop'); } return; } const data = env.XDG_DATA_HOME || path.join(home, '.local', 'share'); const launchers: string[] = []; for (const dir of [ path.join(root, '/usr/share/applications'), path.join(root, '/usr/local/share/applications'), path.join(root, '/var/lib/snapd/desktop/applications'), path.join(root, '/var/lib/flatpak/exports/share/applications'), path.join(data, 'applications'), path.join(data, 'flatpak', 'exports', 'share', 'applications'), ]) for (const n of names(dir)) if (n.toLowerCase().endsWith('.desktop')) launchers.push(n.slice(0, -8).toLowerCase()); for (const t of catalog) { const hit = t.desktopFiles?.some((want) => { const w = want.toLowerCase(); // A snap's launcher is `_.desktop`. return launchers.some((l) => l === w || l.startsWith(`${w}_`)); }); if (hit) found.addCatalog(t, 'desktop'); } } // ── Command-line tools ────────────────────────────────────────────────────── function pathDirs(home: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform, root: string) { const sep = platform === 'win32' ? ';' : ':'; const fromEnv = (env.PATH ?? env.Path ?? '').split(sep); // A daemon started by the service manager has a short PATH. const common = platform === 'win32' ? [] : [ path.join(home, '.local', 'bin'), path.join(home, 'bin'), path.join(home, '.bun', 'bin'), path.join(home, '.npm-global', 'bin'), path.join(home, '.cargo', 'bin'), path.join(root, '/usr/local/bin'), path.join(root, '/opt/homebrew/bin'), ]; return [...new Set([...fromEnv, ...common].filter((d) => d && path.isAbsolute(d)))].slice( 0, MAX_PATH_DIRS ); } function commandTools( found: Found, catalog: CatalogTool[], home: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform, root: string ): void { const wanted = catalog.filter((t) => t.bins?.length); if (wanted.length === 0) return; const dirs = pathDirs(home, env, platform, root); const suffixes = platform === 'win32' ? ['.exe', '.cmd', '.bat'] : ['']; for (const t of wanted) { const hit = t.bins!.some((bin) => dirs.some((dir) => suffixes.some((s) => isProgram(path.join(dir, bin + s), platform))) ); if (hit) found.addCatalog(t, 'path'); } } // ── Local models ──────────────────────────────────────────────────────────── const MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._/:-]{0,79}$/; /** `/manifests////`, and the same * under `manifests-v2` (newer Ollama builds). */ function ollamaModels(modelsDir: string): string[] { return [ ...ollamaManifests(path.join(modelsDir, 'manifests')), ...ollamaManifests(path.join(modelsDir, 'manifests-v2')), ]; } function ollamaManifests(manifests: string): string[] { const out: string[] = []; for (const registry of subDirs(manifests, 8)) for (const ns of subDirs(path.join(manifests, registry), 50)) for (const model of subDirs(path.join(manifests, registry, ns), 200)) for (const tag of names(path.join(manifests, registry, ns, model), 20)) { const name = `${ns === 'library' ? '' : `${ns}/`}${model}:${tag}`; if (MODEL_NAME.test(name)) out.push(name); if (out.length >= MAX_MODELS * 4) return out; } return out; } /** GPT4All keeps model files in one folder: their names, `.gguf` dropped. */ function fileModels(modelsDir: string): string[] { return names(modelsDir, 500) .filter((n) => n.toLowerCase().endsWith('.gguf')) .map((n) => n.slice(0, -5)) .filter((n) => MODEL_NAME.test(n)); } /** `///...`: the two folder levels name a model. */ function folderModels(modelsDir: string): string[] { const out: string[] = []; for (const publisher of subDirs(modelsDir, 100)) for (const repo of subDirs(path.join(modelsDir, publisher), 100)) { const name = `${publisher}/${repo}`; if (MODEL_NAME.test(name)) out.push(name); if (out.length >= MAX_MODELS * 4) return out; } return out; } function localModels( found: Found, catalog: CatalogTool[], home: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform, root: string ): void { for (const t of catalog) { if (!t.models) continue; let dirs: string[] = []; let read = folderModels; if (t.models === 'ollama') { read = ollamaModels; const own = env.OLLAMA_MODELS; dirs = [ ...(own && path.isAbsolute(own) ? [own] : []), path.join(home, '.ollama', 'models'), ...(platform === 'linux' ? [path.join(root, '/usr/share/ollama/.ollama/models')] : []), ]; } else if (t.models === 'lmstudio') { dirs = [path.join(home, '.lmstudio', 'models')]; } else if (t.models === 'gpt4all') { read = fileModels; dirs = [ platform === 'darwin' ? path.join(home, 'Library', 'Application Support', 'nomic.ai', 'GPT4All') : platform === 'win32' ? path.join( env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), 'nomic.ai', 'GPT4All' ) : path.join( env.XDG_DATA_HOME || path.join(home, '.local', 'share'), 'nomic.ai', 'GPT4All' ), ]; } const present = dirs.filter((d) => exists(d)); if (present.length === 0) continue; const models = [...new Set(present.flatMap((d) => read(d)))].sort().slice(0, MAX_MODELS); found.addCatalog(t, 'models', { models }); } } // ── Editor extensions ─────────────────────────────────────────────────────── const EDITORS: Array<{ where: string; dir: string[] }> = [ { where: 'vscode', dir: ['.vscode', 'extensions'] }, { where: 'vscode-insiders', dir: ['.vscode-insiders', 'extensions'] }, { where: 'vscodium', dir: ['.vscode-oss', 'extensions'] }, { where: 'vscode-server', dir: ['.vscode-server', 'extensions'] }, { where: 'cursor', dir: ['.cursor', 'extensions'] }, { where: 'windsurf', dir: ['.windsurf', 'extensions'] }, ]; /** The extensions an editor has: `extensions.json` when it is there, else the * folder names (`publisher.name-1.2.3`). */ function editorExtensionIds(dir: string): Map { const out = new Map(); const listed = readJson(path.join(dir, 'extensions.json'), MAX_EXTENSIONS_JSON_BYTES); if (Array.isArray(listed)) { for (const e of listed.slice(0, 2000)) { if (!isRecord(e) || !isRecord(e.identifier)) continue; const id = e.identifier.id; if (typeof id === 'string') out.set(id.toLowerCase(), cleanVersion(e.version)); } if (out.size > 0) return out; } // Folders VS Code keeps after an uninstall are listed in `.obsolete`. const obsolete = readJson(path.join(dir, '.obsolete'), MAX_MANIFEST_BYTES); const removed = isRecord(obsolete) ? obsolete : {}; for (const n of subDirs(dir, 2000)) { if (removed[n] === true) continue; const m = /^([a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9._-]*?)-(\d[0-9A-Za-z.+_-]*)$/i.exec(n); if (m) out.set(m[1].toLowerCase(), cleanVersion(m[2])); } return out; } function editorExtensions(found: Found, catalog: CatalogTool[], home: string): void { const wanted = new Map(); for (const t of catalog) for (const id of t.editorExtensions ?? []) wanted.set(id.toLowerCase(), t); if (wanted.size === 0) return; for (const editor of EDITORS) { const ids = editorExtensionIds(path.join(home, ...editor.dir)); for (const [id, version] of ids) { const t = wanted.get(id); if (t) found.addCatalog(t, editor.where, { version }); } } } // ── Browser extensions ────────────────────────────────────────────────────── /** The AI chat site a host pattern is about, or null. A pattern that is * wider than the site (``, `*://*.google.com/*`) is about nothing * in particular: every ad blocker has one. */ export function aiHostOf(pattern: unknown): string | null { if (typeof pattern !== 'string' || pattern.length > 300) return null; const m = /^(?:\*|https?|wss?):\/\/([^/]+)(?:\/|$)/i.exec(pattern); if (!m) return null; let host = m[1].toLowerCase(); if (host.startsWith('*.')) host = host.slice(2); host = host.replace(/:\d+$|:\*$/, ''); if (!/^[a-z0-9.-]+$/.test(host)) return null; for (const site of AI_CHAT_HOSTS) if (host === site || host.endsWith(`.${site}`)) return site; return null; } function aiHostsOf(patterns: unknown[]): string[] { const out = new Set(); for (const p of patterns.slice(0, 500)) { const site = aiHostOf(p); if (site) out.add(site); } return [...out].sort().slice(0, MAX_AI_HOSTS); } function strings(v: unknown): unknown[] { return Array.isArray(v) ? v : []; } /** A manifest's name; a `__MSG_key__` placeholder is looked up in the * extension's default locale. */ function manifestName(manifest: Record, versionDir: string): string { const raw = manifest.name; const m = typeof raw === 'string' ? /^__MSG_(.+)__$/.exec(raw) : null; if (!m) return cleanName(raw); const locale = typeof manifest.default_locale === 'string' ? manifest.default_locale : 'en'; if (!/^[A-Za-z0-9_-]{1,20}$/.test(locale)) return ''; const messages = readJson( path.join(versionDir, '_locales', locale, 'messages.json'), MAX_MANIFEST_BYTES ); if (!isRecord(messages)) return ''; const key = Object.keys(messages).find((k) => k.toLowerCase() === m[1].toLowerCase()); const entry = key ? messages[key] : null; return isRecord(entry) ? cleanName(entry.message) : ''; } function chromiumRoots( home: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform ): Array<{ where: string; dir: string }> { if (platform === 'darwin') { const base = path.join(home, 'Library', 'Application Support'); return [ { where: 'chrome', dir: path.join(base, 'Google', 'Chrome') }, { where: 'chromium', dir: path.join(base, 'Chromium') }, { where: 'edge', dir: path.join(base, 'Microsoft Edge') }, { where: 'brave', dir: path.join(base, 'BraveSoftware', 'Brave-Browser') }, { where: 'arc', dir: path.join(base, 'Arc', 'User Data') }, ]; } if (platform === 'win32') { const local = env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'); return [ { where: 'chrome', dir: path.join(local, 'Google', 'Chrome', 'User Data') }, { where: 'chromium', dir: path.join(local, 'Chromium', 'User Data') }, { where: 'edge', dir: path.join(local, 'Microsoft', 'Edge', 'User Data') }, { where: 'brave', dir: path.join(local, 'BraveSoftware', 'Brave-Browser', 'User Data') }, ]; } const config = env.XDG_CONFIG_HOME || path.join(home, '.config'); return [ { where: 'chrome', dir: path.join(config, 'google-chrome') }, { where: 'chromium', dir: path.join(config, 'chromium') }, { where: 'chromium', dir: path.join(home, 'snap', 'chromium', 'common', 'chromium') }, { where: 'edge', dir: path.join(config, 'microsoft-edge') }, { where: 'brave', dir: path.join(config, 'BraveSoftware', 'Brave-Browser') }, ]; } /** `6.55.0_0` -> `6.55.0`; the newest of an extension's version folders. */ function newestVersionDir(dirs: string[]): string | undefined { const key = (d: string): number[] => d .replace(/_\d+$/, '') .split('.') .map((n) => Number.parseInt(n, 10) || 0); return [...dirs].sort((a, b) => { const [x, y] = [key(a), key(b)]; for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) - (y[i] ?? 0); return a < b ? -1 : a > b ? 1 : 0; })[dirs.length - 1]; } function chromiumExtensions( found: Found, catalog: CatalogTool[], home: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform, stats: { manifests: number } ): void { const known = new Map(); for (const t of catalog) for (const id of t.chromeExtensions ?? []) known.set(id, t); for (const browser of chromiumRoots(home, env, platform)) { const profiles = subDirs(browser.dir, 200) .filter((d) => d === 'Default' || /^Profile \d+$/.test(d)) .slice(0, MAX_PROFILES); for (const profile of profiles) { const extRoot = path.join(browser.dir, profile, 'Extensions'); for (const id of subDirs(extRoot, MAX_EXTENSIONS_PER_PROFILE)) { if (!/^[a-p]{32}$/.test(id)) continue; const versionDir = newestVersionDir(subDirs(path.join(extRoot, id), 20)); if (!versionDir) continue; const version = cleanVersion(versionDir.replace(/_\d+$/, '')); const t = known.get(id); if (t) { found.addCatalog(t, browser.where, { version }); continue; } // Outside the catalog: read locally, report only for an AI chat site. if (stats.manifests >= MAX_MANIFESTS) continue; stats.manifests++; const dir = path.join(extRoot, id, versionDir); const manifest = readJson(path.join(dir, 'manifest.json'), MAX_MANIFEST_BYTES); if (!isRecord(manifest)) continue; const patterns = [ ...strings(manifest.host_permissions), ...strings(manifest.permissions), ...strings(manifest.content_scripts) .slice(0, 50) .flatMap((c) => (isRecord(c) ? strings(c.matches) : [])), ]; const aiHosts = aiHostsOf(patterns); if (aiHosts.length === 0) continue; found.add( { id: `ext:${id}`, kind: 'extension', name: manifestName(manifest, dir) || 'Unnamed extension', ...(version ? { version } : {}), aiHosts, }, browser.where ); } } } } function firefoxProfileRoots( home: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform ): string[] { if (platform === 'darwin') return [path.join(home, 'Library', 'Application Support', 'Firefox', 'Profiles')]; if (platform === 'win32') return [ path.join( env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'Mozilla', 'Firefox', 'Profiles' ), ]; return [ path.join(home, '.mozilla', 'firefox'), path.join(home, 'snap', 'firefox', 'common', '.mozilla', 'firefox'), path.join(home, '.var', 'app', 'org.mozilla.firefox', '.mozilla', 'firefox'), ]; } function firefoxExtensions( found: Found, catalog: CatalogTool[], home: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform ): void { const known = new Map(); for (const t of catalog) for (const id of t.firefoxExtensions ?? []) known.set(id.toLowerCase(), t); let profilesRead = 0; for (const root of firefoxProfileRoots(home, env, platform)) for (const profile of subDirs(root, 50)) { if (profilesRead >= MAX_PROFILES) return; const data = readJson(path.join(root, profile, 'extensions.json'), MAX_EXTENSIONS_JSON_BYTES); if (!isRecord(data) || !Array.isArray(data.addons)) continue; profilesRead++; for (const a of data.addons.slice(0, MAX_EXTENSIONS_PER_PROFILE)) { if (!isRecord(a) || a.type !== 'extension' || typeof a.id !== 'string') continue; // Firefox's own built-in add-ons are not something a person installed. if (typeof a.location === 'string' && a.location !== 'app-profile') continue; const version = cleanVersion(a.version); const t = known.get(a.id.toLowerCase()); if (t) { found.addCatalog(t, 'firefox', { version }); continue; } const origins = isRecord(a.userPermissions) ? strings(a.userPermissions.origins) : []; const aiHosts = aiHostsOf(origins); if (aiHosts.length === 0) continue; if (!/^[A-Za-z0-9@{}._-]{1,80}$/.test(a.id)) continue; const name = isRecord(a.defaultLocale) ? cleanName(a.defaultLocale.name) : ''; found.add( { id: `ext:${a.id.toLowerCase()}`, kind: 'extension', name: name || 'Unnamed extension', ...(version ? { version } : {}), aiHosts, }, 'firefox' ); } } } // ── Entry point ───────────────────────────────────────────────────────────── /** The AI tools of the catalog found on this machine, and the extensions * outside it that ask for an AI chat site. Never throws. */ export function collectAiTools( home: string = os.homedir(), env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform, opts: AiToolsOptions = {} ): { tools: AddonTool[]; capped: boolean } { const found = new Found(); const catalog = opts.catalog ?? AI_TOOLS; const root = opts.root ?? ''; const stats = opts.stats ?? { manifests: 0 }; const steps: Array<() => void> = [ () => desktopApps(found, catalog, home, env, platform, root), () => commandTools(found, catalog, home, env, platform, root), () => localModels(found, catalog, home, env, platform, root), () => editorExtensions(found, catalog, home), () => chromiumExtensions(found, catalog, home, env, platform, stats), () => firefoxExtensions(found, catalog, home, env, platform), ]; for (const step of steps) { try { step(); } catch { /* one unreadable source never drops the others */ } } return found.list(); }