import path from "node:path"; import { constants, type Stats } from "node:fs"; import { lstat, open, realpath, stat, type FileHandle } from "node:fs/promises"; import { coerceExternalMediaReference, coerceLocalMediaConfig } from "./localMedia"; export type ExternalMediaOpenResult = | { status: "ready"; handle: FileHandle; bytes: number } | { status: "refused"; reason: "invalid-config" | "invalid-reference" | "source-mismatch" | "playback-disabled" | "unsafe-path" | "not-regular" | "changed-during-open" | "unavailable" }; function contained(root: string, candidate: string): boolean { const relative = path.relative(root, candidate); return !!relative && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative); } // Open EXTERNALLY OWNED media for reading only. No write, unlink, rename, or // source-directory creation is possible through this module. Returning the // verified handle (not a pathname to reopen) preserves file identity for the // caller's eventual stream. The caller MUST close a successful handle. // // Configuration comes from the operator, never a request's supplied root. A // playback opt-in is only one gate: HTTP authentication, site exposure policy, // channel guards and stalled-drive handling belong in the caller before this // low-level helper is used. This slice does not expose an HTTP route. // // TRUST MODEL: roots and their directory entries are operator-controlled. // Refuse symlinks beneath the canonical root, recheck identity after open, and // use O_NOFOLLOW when available. These checks defend against ordinary escapes // and replacements; portable Node path APIs are NOT equivalent to Linux // openat2(RESOLVE_BENEATH) against an adversary concurrently swapping ancestors. // Do not offer this resolver as a hostile multi-user filesystem sandbox. export async function openExternalMedia(options: { config: unknown; reference: unknown; purpose: "inspect" | "playback"; }): Promise { const config = coerceLocalMediaConfig(options.config); if (!config || !path.isAbsolute(config.directory)) return { status: "refused", reason: "invalid-config" }; const ref = coerceExternalMediaReference(options.reference); if (!ref) return { status: "refused", reason: "invalid-reference" }; if (config.sourceId !== ref.sourceId) return { status: "refused", reason: "source-mismatch" }; // Unknown runtime purpose must fail closed, even for an untyped caller. if (options.purpose !== "inspect" && (options.purpose !== "playback" || config.playback !== true)) { return { status: "refused", reason: "playback-disabled" }; } let handle: FileHandle | undefined; try { const root = await realpath(config.directory); if (!(await stat(root)).isDirectory()) return { status: "refused", reason: "unsafe-path" }; const parts = ref.relativePath.split("/"); let candidate = root; let before: Stats | undefined; for (let index = 0; index < parts.length; index++) { candidate = path.join(candidate, parts[index]); if (!contained(root, candidate)) return { status: "refused", reason: "unsafe-path" }; const entry = await lstat(candidate); if (entry.isSymbolicLink()) return { status: "refused", reason: "unsafe-path" }; if (index < parts.length - 1 && !entry.isDirectory()) return { status: "refused", reason: "unsafe-path" }; before = entry; } if (!before?.isFile()) return { status: "refused", reason: "not-regular" }; if (!contained(root, await realpath(candidate))) return { status: "refused", reason: "unsafe-path" }; // NONBLOCK avoids hanging if a regular file is replaced by a FIFO between // lstat and open. File kind is checked again on the opened descriptor. handle = await open(candidate, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)); const opened = await handle.stat(); const after = await lstat(candidate); if (!opened.isFile() || !after.isFile() || after.isSymbolicLink() || opened.dev !== before.dev || opened.ino !== before.ino || opened.dev !== after.dev || opened.ino !== after.ino || opened.size !== before.size || opened.mtimeMs !== before.mtimeMs || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || !contained(root, await realpath(candidate))) { return { status: "refused", reason: "changed-during-open" }; } const result: ExternalMediaOpenResult = { status: "ready", handle, bytes: opened.size }; handle = undefined; // Ownership transfers only on success; finally closes failures. return result; } catch { // A missing, inaccessible or disconnected source is not an absent record. // Return a bounded private-path-free status; never repair or delete it here. return { status: "refused", reason: "unavailable" }; } finally { if (handle) await handle.close(); } }