Open source CapCut alternative.
TypeScript
fix(site): harden Cut storage and media probes
David Le6c576d52db7a
diff --git a/site/src/cut/server/frames.ts b/site/src/cut/server/frames.tsindex 634f992b..f2a38a76 100644--- a/site/src/cut/server/frames.ts+++ b/site/src/cut/server/frames.ts@@ -8,17 +8,24 @@ function run(cmd: string, args: string[]): Promise<void> {return new Promise((resolve, reject) => {const p = spawn(cmd, args);let err = "";+ const timer = setTimeout(() => {+ p.kill("SIGKILL");+ reject(new Error(`${cmd} timed out after 60s.`));+ }, 60_000);+ timer.unref();p.stderr.on("data", (d) => (err = (err + d.toString()).slice(-2000)));- p.on("error", (e) =>+ p.on("error", (e) => {+ clearTimeout(timer);reject(e.message.includes("ENOENT")? new Error("ffmpeg was not found. Install it with: brew install ffmpeg"): e- )- );- p.on("close", (code) =>- code === 0 ? resolve() : reject(new Error(err.split("\n").slice(-3).join("\n")))- );+ );+ });+ p.on("close", (code) => {+ clearTimeout(timer);+ code === 0 ? resolve() : reject(new Error(err.split("\n").slice(-3).join("\n")));+ });});}@@ -32,12 +39,21 @@ function probeDims(file: string): Promise<{ width: number; height: number }> {file,]);let out = "";+ const timer = setTimeout(() => {+ p.kill("SIGKILL");+ resolve({ width: 1080, height: 1920 });+ }, 30_000);+ timer.unref();p.stdout.on("data", (d) => (out += d));p.on("close", () => {+ clearTimeout(timer);const [w, h] = out.trim().split(",").map(Number);resolve({ width: w || 1080, height: h || 1920 });});- p.on("error", () => resolve({ width: 1080, height: 1920 }));+ p.on("error", () => {+ clearTimeout(timer);+ resolve({ width: 1080, height: 1920 });+ });});}diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex 0fcfe369..26b4ddd0 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -4,7 +4,7 @@ import path from "node:path";import { cutDataRoot } from "./dataDir";import { assertLocalRuntime } from "./local-only";import { mediaPath as projectMediaPath, readProject } from "./projects";-import { exists, uniqueName } from "./util";+import { exists, uniqueName, writeJsonAtomic } from "./util";/** The shared library: reusable media that lives outside any project. */export const LIBRARY_ROOT = path.join(cutDataRoot(), "library");@@ -35,17 +35,31 @@ export function libMediaPath(fileName: string) {async function readIndex(): Promise<LibraryIndex> {assertLocalRuntime();+ let raw: string;try {- return JSON.parse(await readFile(INDEX, "utf8")) as LibraryIndex;+ raw = await readFile(INDEX, "utf8");} catch {return { assets: [] };}+ try {+ return JSON.parse(raw) as LibraryIndex;+ } catch (err) {+ console.error(`Corrupt library index ${INDEX}:`, err);+ }+ try {+ const idx = JSON.parse(await readFile(`${INDEX}.bak`, "utf8")) as LibraryIndex;+ await writeIndex(idx);+ return idx;+ } catch (err) {+ console.error(`Could not recover ${INDEX} from backup:`, err);+ return { assets: [] };+ }}async function writeIndex(idx: LibraryIndex) {assertLocalRuntime();await mkdir(LIB_MEDIA, { recursive: true });- await writeFile(INDEX, JSON.stringify(idx, null, 2));+ await writeJsonAtomic(INDEX, idx);}export async function listLibrary(): Promise<LibraryAsset[]> {@@ -59,12 +73,18 @@ const AUDIO_RE = /\.(mp3|m4a|aac|wav|ogg|flac)$/i;function ffprobe(args: string[]): Promise<string> {return new Promise((resolve, reject) => {const p = spawn("ffprobe", ["-v", "error", ...args]);+ const timer = setTimeout(() => p.kill("SIGKILL"), 30_000);let out = "";p.stdout.on("data", (d) => (out += d));- p.on("error", reject);- p.on("close", (code) =>- code === 0 ? resolve(out.trim()) : reject(new Error("Could not read this media file."))- );+ p.on("error", (err) => {+ clearTimeout(timer);+ reject(err);+ });+ p.on("close", (code) => {+ clearTimeout(timer);+ if (code === 0) resolve(out.trim());+ else reject(new Error("Could not read this media file."));+ });});}diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.tsindex 33d1d07a..888d3565 100644--- a/site/src/cut/server/projects.ts+++ b/site/src/cut/server/projects.ts@@ -3,7 +3,7 @@ import path from "node:path";import type { ProjectDoc, ProjectSummary } from "@/cut/lib/types";import { cutDataRoot } from "./dataDir";import { assertLocalRuntime } from "./local-only";-import { exists, uniqueName } from "./util";+import { exists, uniqueName, writeJsonAtomic } from "./util";/** All projects live here; each project is one folder holding project.json,* its raw media files, and its exports. */@@ -59,16 +59,31 @@ export async function deleteExport(id: string, fileName: string) {const docPath = (id: string) => path.join(projectDir(id), "project.json");export async function readProject(id: string): Promise<ProjectDoc | null> {+ const file = docPath(id);+ let raw: string;try {- return JSON.parse(await readFile(docPath(id), "utf8")) as ProjectDoc;+ raw = await readFile(file, "utf8");} catch {return null;}+ try {+ return JSON.parse(raw) as ProjectDoc;+ } catch (err) {+ console.error(`Corrupt project doc ${file}:`, err);+ }+ try {+ const doc = JSON.parse(await readFile(`${file}.bak`, "utf8")) as ProjectDoc;+ await writeJsonAtomic(file, doc);+ return doc;+ } catch (err) {+ console.error(`Could not recover ${file} from backup:`, err);+ return null;+ }}export async function writeProject(id: string, doc: ProjectDoc) {doc.updatedAt = Date.now();- await writeFile(docPath(id), JSON.stringify(doc, null, 2));+ await writeJsonAtomic(docPath(id), doc);}export async function createProject(name: string): Promise<ProjectSummary> {@@ -86,7 +101,7 @@ export async function createProject(name: string): Promise<ProjectSummary> {audioClips: [],overlays: [],};- await writeFile(docPath(id), JSON.stringify(doc, null, 2));+ await writeJsonAtomic(docPath(id), doc);return summarize(id, doc);}diff --git a/site/src/cut/server/util.ts b/site/src/cut/server/util.tsindex 7e0f6069..fdd0bbb4 100644--- a/site/src/cut/server/util.ts+++ b/site/src/cut/server/util.ts@@ -1,5 +1,5 @@import { spawn } from "node:child_process";-import { access, constants, stat } from "node:fs/promises";+import { access, constants, rename, stat, writeFile } from "node:fs/promises";import path from "node:path";/** Does a file/dir exist? (stat, coerced to a boolean.) */@@ -10,6 +10,25 @@ export async function exists(p: string) {);}+/**+ * Atomically write `value` as pretty JSON to `filePath`, keeping a `.bak`+ * mirror for corruption recovery. Two invariants make recovery safe by+ * construction:+ * - The temp name is unique per write, so concurrent writers to the same path+ * each rename their own temp in (last writer wins) instead of racing on one+ * shared temp and having the loser's rename hit ENOENT.+ * - `.bak` is written from the very bytes we are committing — never copied+ * from the on-disk file. So a corrupt file can never overwrite a good backup+ * (the failure mode when recovery re-saves a doc recovered *from* the .bak).+ */+export async function writeJsonAtomic(filePath: string, value: unknown) {+ const json = JSON.stringify(value, null, 2);+ const tmp = `${filePath}.${crypto.randomUUID().slice(0, 8)}.tmp`;+ await writeFile(tmp, json);+ await writeFile(`${filePath}.bak`, json).catch(() => {});+ await rename(tmp, filePath);+}+/** First executable *file* named `name` on PATH, or null. Directories carry the* execute bit too, so a like-named directory must not shadow the real CLI. */export async function findOnPath(name: string): Promise<string | null> {@@ -46,6 +65,23 @@ export const num = (n: number) => (Math.round(n * 1000) / 1000).toFixed(3);/** Round to hundredths (cue/timeline times). */export const round = (n: number) => Math.round(n * 100) / 100;+/** An ffmpeg atempo chain reaching `speed`. A single atempo spans only+ * 0.5–2.0×, so factors are chained to cover the full 0.25–4× range. */+export function atempoChain(speed: number) {+ const parts: string[] = [];+ let s = speed;+ while (s > 2) {+ parts.push("atempo=2.0");+ s /= 2;+ }+ while (s < 0.5) {+ parts.push("atempo=0.5");+ s *= 2;+ }+ parts.push(`atempo=${num(s)}`);+ return parts.join(",");+}+/*** Whether a media file carries a stream of the given kind ("a" audio /* "v" video). Resolves false only when ffprobe reports no such stream; a@@ -66,13 +102,22 @@ export function hasStream(file,]);let out = "";+ // A probe that never returns is a probe failure, not "no stream".+ const timer = setTimeout(() => {+ p.kill("SIGKILL");+ onProbeError?.(new Error(`ffprobe timed out for ${file}`));+ resolve(false);+ }, 30_000);+ timer.unref();p.stdout.on("data", (d) => (out += d));p.on("close", (code) => {+ clearTimeout(timer);// A non-zero exit means the probe itself failed, not "no stream".if (code !== 0) onProbeError?.(new Error(`ffprobe exited ${code} for ${file}`));resolve(out.trim().length > 0);});p.on("error", (err) => {+ clearTimeout(timer);onProbeError?.(err);resolve(false);});