// A FILE OF THE PROJECT, served to a bench ("use a file", lane/reel-bench): a // rendered file -- a take's master first -- that a bench plays, decodes and // draws the envelope of, named by its path RELATIVE to the project. // // The path is lexical first (inside the project, no `..`, a media file by its // extension), then real: the file's real path must stay under the real path // of the project or of one of its own directories on the way to it -- a // take's out/ may be a link to the media drive, and that link is the // project's own decision; nothing else is followed out of it. // // Plain ESM. import { realpath, stat } from "node:fs/promises"; import path from "node:path"; /** What a bench may play. */ export const PROJECT_MEDIA = /\.(mp4|m4v|mov|mkv|webm|m4a|mp3|wav)$/i; /** * @param {{ dir: string }} project * @param {string} rel * @returns {Promise<{ abs: string, rel: string, size: number, mtimeMs: number } | { error: string, status: number }>} */ export async function resolveProjectFile(project, rel) { const r = String(rel ?? "").replace(/\\/g, "/"); if (!r || r.startsWith("/") || r.split("/").some((s) => s === ".." || s === "" || s === ".")) return { error: "path is a file inside the project, relative to it", status: 400 }; if (!PROJECT_MEDIA.test(r)) return { error: "path names a media file (mp4, mov, mkv, webm, m4a, mp3, wav)", status: 400 }; const lexical = path.join(project.dir, ...r.split("/")); const real = await realpath(lexical).catch(() => null); if (!real) return { error: `no ${r} in this project`, status: 404 }; // The project's own directories on the way to the file, each by its real path. const segs = r.split("/").slice(0, -1); const roots = [project.dir]; for (let k = 1; k <= segs.length; k += 1) roots.push(path.join(project.dir, ...segs.slice(0, k))); let ok = false; for (const d of roots) { const rd = await realpath(d).catch(() => null); if (rd && real.startsWith(`${rd}${path.sep}`)) { ok = true; break; } } if (!ok) return { error: "not served", status: 403 }; const st = await stat(real).catch(() => null); if (!st?.isFile()) return { error: "gone", status: 404 }; return { abs: real, rel: r, size: st.size, mtimeMs: Math.round(st.mtimeMs) }; }