/** * Locate a folder dropped onto the Web composer on this Host. The page only * knows the folder's name and first-level entry names; this module finds the * local folder they describe and answers its absolute path. It reads at most * one bounded directory level per candidate and never walks a dropped * folder's contents. A folder is named only when the search covered every * same-named candidate and one of them stands out; anything less is reported * as ambiguous rather than guessed. */ import { execFile } from "node:child_process"; import { lstat, opendir, readdir, realpath } from "node:fs/promises"; import { homedir } from "node:os"; import { basename, dirname, join, sep } from "node:path"; import { DROPPED_FOLDER_MAX_CANDIDATES, DROPPED_FOLDER_RESOLVE_METHOD, droppedFolderResolveParamsSchema, type DroppedFolderResolveParams, type DroppedFolderResolveResult, } from "@codexhost/shared-contracts"; import { isRemoteWorkspaceScopeId } from "./remote-peer-workspace-files.ts"; import { RpcError, type RpcRegistry } from "./transport.ts"; /** Most candidates verified per request; an unchecked same-named candidate makes the result ambiguous. */ const MAX_VERIFIED = 64; /** Most entries read from one candidate; a larger folder is skipped rather than read whole. */ const MAX_CANDIDATE_ENTRIES = 4_096; const INDEX_TIMEOUT_MS = 2_500; const INDEX_MAX_BUFFER = 1024 * 1024; const SCAN_BUDGET_MS = 2_000; const SCAN_MAX_DEPTH = 5; const SCAN_MAX_DIRECTORIES = 10_000; const MTIME_TOLERANCE_MS = 2_000; /** Concurrent resolutions across all browsers; each may start an index query and directory reads. */ const MAX_CONCURRENT = 2; /** * Home subtrees the fallback scan deliberately leaves out: dependency, cache, * trash, VCS and application-data trees nobody drags a folder from. Other * hidden folders are scanned like any other. */ const SCAN_SKIP = new Set([ "node_modules", "Library", "AppData", "$RECYCLE.BIN", ".Trash", ".git", ".cache", ".npm", ]); /** Path segments that never hold a folder a user drags in. */ const NOISE_SEGMENTS = new Set(["node_modules", ".Trash", ".git", "$RECYCLE.BIN"]); /** System metadata files browsers may or may not list; ignored when counting entries. */ const METADATA_ENTRIES = new Set([".DS_Store", ".localized", "Thumbs.db", "desktop.ini"]); type Folder = Omit & { workspace?: string | undefined }; export interface DroppedFolderSearch { /** * Absolute folder paths named `name` from a platform index, or undefined * when none is available; `complete` is false when the answer was cut short. */ index( name: string, signal: AbortSignal, ): Promise<{ readonly paths: readonly string[]; readonly complete: boolean } | undefined>; home(): string; } interface Match { readonly path: string; /** Same entries as the page reported, ignoring metadata files. */ readonly exact: boolean; readonly mtimeMatch: boolean; readonly mtimeMs: number; } const nfc = (value: string): string => value.normalize("NFC"); /** Whether a filesystem error means the path does not exist or is not a folder. */ function isAbsent(error: unknown): boolean { const code = (error as NodeJS.ErrnoException | undefined)?.code; return code === "ENOENT" || code === "ENOTDIR"; } /** * Resolve one dropped folder description to a local path. * @param folder - the page's description plus the session workspace, searched first. * @param signal - request lifetime. * @param search - index and home-directory seams (tests replace them). */ export async function resolveDroppedFolder( folder: Folder, signal: AbortSignal, search: DroppedFolderSearch = platformSearch, ): Promise { const children = folder.children.map(nfc); const want = { ...folder, name: nfc(folder.name), children }; const seen = new Set(); const matches: Match[] = []; let verified = 0; // Set whenever some same-named folder may have gone unchecked. let incomplete = false; const consider = async (candidates: Iterable): Promise => { for (const candidate of candidates) { signal.throwIfAborted(); if (nfc(basename(candidate)) !== want.name || isNoise(candidate)) continue; let real: string; try { // A link candidate could lead anywhere, including slow mounts; only real folders count. if ((await lstat(candidate)).isSymbolicLink()) continue; real = await realpath(candidate); } catch { continue; } if (seen.has(real)) continue; if (verified >= MAX_VERIFIED) { incomplete = true; return; } seen.add(real); verified += 1; const match = await verify(candidate, want); // A candidate too large to read could be the dropped folder; it leaves the search undecided. if (match === "unverifiable") incomplete = true; else if (match) matches.push(match); } }; await consider(nearby(want, search.home())); const indexed = await search.index(want.name, signal); if (indexed) { if (!indexed.complete) incomplete = true; await consider(indexed.paths); } // Without an index, nearby hits alone cannot show that no other same-named folder exists. if ((indexed === undefined || matches.length === 0) && !incomplete) { const scan = await scanHome(want.name, search.home(), signal); if (!scan.complete) incomplete = true; await consider(scan.found); } return decide(matches, { incomplete, partialRead: !folder.complete }); } /** Whether a path runs through a folder users never drop from (dependencies, trash, VCS internals). */ function isNoise(path: string): boolean { const segments = path.split(/[/\\]/u); if (segments.some((segment) => NOISE_SEGMENTS.has(segment))) return true; // macOS system trees hold same-named folders (`src`, `docs`) that no user drags in. return process.platform === "darwin" && /^\/(?:System|Library|private|usr)\//u.test(path); } /** `/` for the workspace, its ancestors, and the usual user folders. */ function nearby(folder: Folder, home: string): string[] { const roots: string[] = []; if (folder.workspace) { for (let dir = folder.workspace; ; dir = dirname(dir)) { roots.push(dir); if (dirname(dir) === dir) break; } } roots.push(home, join(home, "Desktop"), join(home, "Documents"), join(home, "Downloads")); const paths = roots.map((root) => join(root, folder.name)); if (folder.workspace && nfc(basename(folder.workspace)) === folder.name) paths.unshift(folder.workspace); return paths; } /** * Accept a folder only when every name the page saw exists in it; an empty * description matches only an empty folder. Reads at most * MAX_CANDIDATE_ENTRIES entries; a larger folder is "unverifiable", not a mismatch. */ async function verify(path: string, folder: Folder): Promise { let directory; try { directory = await opendir(path); } catch (error: unknown) { // Gone or not a folder is a mismatch; permission or I/O failures leave it unknown. return isAbsent(error) ? undefined : "unverifiable"; } const present = new Set(); let counted = 0; try { for await (const entry of directory) { if (present.size >= MAX_CANDIDATE_ENTRIES) return "unverifiable"; const name = nfc(entry.name); present.add(name); if (!METADATA_ENTRIES.has(name)) counted += 1; } } catch { return "unverifiable"; } if (!folder.children.every((child) => present.has(child))) return undefined; const reported = folder.children.filter((child) => !METADATA_ENTRIES.has(child)).length; if (reported === 0 && counted > 0) return undefined; let mtimeMs: number; try { mtimeMs = (await lstat(path)).mtimeMs; } catch (error: unknown) { return isAbsent(error) ? undefined : "unverifiable"; } return { path, exact: folder.complete && counted === reported, mtimeMatch: folder.lastModified !== undefined && Math.abs(mtimeMs - folder.lastModified) < MTIME_TOLERANCE_MS, mtimeMs, }; } /** * Name a folder only when the search was complete and one match stands out: * its entries match exactly, or its modification time matches, or the page * could only send a full sample of a large folder. Otherwise list the matches. * @param matches - verified candidates. * @param search - whether candidates went unchecked, and whether the page read only part of the folder. */ export function decide( matches: readonly Match[], search: { readonly incomplete: boolean; readonly partialRead: boolean }, ): DroppedFolderResolveResult { const ranked = [...matches].sort( (a, b) => Number(b.exact) - Number(a.exact) || Number(b.mtimeMatch) - Number(a.mtimeMatch) || b.mtimeMs - a.mtimeMs, ); const [best, second] = ranked; const ambiguous = { status: "ambiguous", candidates: ranked.slice(0, DROPPED_FOLDER_MAX_CANDIDATES).map((match) => match.path), } as const; // An unfinished search cannot rule out a folder it never reached, matched or not. if (search.incomplete) return ambiguous; if (!best) return { status: "not-found" }; const strong = (match: Match) => match.exact || match.mtimeMatch || search.partialRead; if (!strong(best)) return ambiguous; if ( !second || (best.exact && !second.exact) || (best.exact === second.exact && best.mtimeMatch && !second.mtimeMatch) ) return { status: "resolved", path: best.path }; return ambiguous; } /** Bounded breadth-first walk of the home folder for Hosts without a name index. */ async function scanHome( name: string, home: string, signal: AbortSignal, ): Promise<{ found: string[]; complete: boolean }> { const deadline = Date.now() + SCAN_BUDGET_MS; const found: string[] = []; let queued = 0; let complete = true; let level = [home]; for (let depth = 0; depth < SCAN_MAX_DEPTH && level.length > 0; depth++) { const next: string[] = []; for (const dir of level) { if (signal.aborted || Date.now() > deadline) return { found, complete: false }; let entries; try { entries = await readdir(dir, { withFileTypes: true }); } catch (error: unknown) { // An unreadable subtree may hold the dropped folder; keep collecting but stay undecided. if (!isAbsent(error)) complete = false; continue; } for (const entry of entries) { // Links are neither matched nor followed, so the walk cannot cycle or reach slow mounts. if (!entry.isDirectory()) continue; const path = join(dir, entry.name); if (nfc(entry.name) === name) found.push(path); if (SCAN_SKIP.has(entry.name)) continue; if (++queued > SCAN_MAX_DIRECTORIES) return { found, complete: false }; next.push(path); } } level = next; } // Folders left below the depth bound were never reached, so the scan is complete only if none remain. return { found, complete: complete && level.length === 0 }; } const platformSearch: DroppedFolderSearch = { home: homedir, index: (name, signal) => { if (process.platform !== "darwin") return Promise.resolve(undefined); const literal = name.replace(/[\\"*?]/gu, (char) => `\\${char}`); const query = `kMDItemFSName == "${literal}" && kMDItemContentType == "public.folder"`; // Users drop folders from their home or from external volumes, not from system trees. const scopes = ["-onlyin", homedir(), "-onlyin", `${sep}Volumes`]; return new Promise((resolve) => { execFile( "/usr/bin/mdfind", ["-0", ...scopes, query], { timeout: INDEX_TIMEOUT_MS, maxBuffer: INDEX_MAX_BUFFER, signal }, (error, stdout) => { const text = typeof stdout === "string" ? stdout : ""; // A timeout or overflow leaves later paths unseen; the caller treats that as incomplete. resolve({ paths: text.split("\0").filter((path) => path !== ""), complete: error === null, }); }, ); }); }, }; /** Run at most MAX_CONCURRENT resolutions at once. */ function limiter(): (task: () => Promise) => Promise { let running = 0; const waiting: (() => void)[] = []; return async (task) => { if (running >= MAX_CONCURRENT) await new Promise((wake) => waiting.push(wake)); running += 1; try { return await task(); } finally { running -= 1; waiting.shift()?.(); } }; } /** * Register the resolve RPC. * @param workspace - server-owned local workspace of a session or draft, if any. */ export function registerDroppedFolders( rpc: RpcRegistry, workspace: (sessionId: string) => string | undefined, ): void { const limit = limiter(); rpc.register(DROPPED_FOLDER_RESOLVE_METHOD, async (args, context) => { const parsed = droppedFolderResolveParamsSchema.safeParse(args.request); if (!parsed.success) throw new RpcError("gateway/bad-request", "A dropped folder description is required."); const { sessionId, ...folder } = parsed.data; // A folder dropped from another machine's browser cannot be found on this Host. const remote = context.relay || (context.auth !== undefined ? !context.auth.local : context.loopback === false); if (remote || isRemoteWorkspaceScopeId(sessionId)) return { status: "unsupported" } satisfies DroppedFolderResolveResult; const signal = context.signal ?? new AbortController().signal; return limit(() => resolveDroppedFolder({ ...folder, workspace: workspace(sessionId) }, signal), ); }); }