Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: verify remote recording content and upload identity

Richie McIlroy4d896fa576bb
diff --git a/apps/media-server/src/__tests__/lib/job-manager.test.ts b/apps/media-server/src/__tests__/lib/job-manager.test.ts
index c138649fd..9bed6f602 100644
--- a/apps/media-server/src/__tests__/lib/job-manager.test.ts
+++ b/apps/media-server/src/__tests__/lib/job-manager.test.ts
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, test } from "bun:test";
import {
+ beginRecordingVerification,
cleanupExpiredJobs,
createJob,
deleteJob,
@@ -21,6 +22,31 @@ afterEach(() => {
});
describe("job cleanup", () => {
+ test("gives verification a separate finite budget after a long mux", () => {
+ const job = createTrackedJob("job-verification-budget");
+ job.phase = "uploading";
+ job.createdAt = Date.now() - 55 * 60 * 1000;
+ expect(beginRecordingVerification(job.jobId, 50 * 60 * 1000)).toBe(true);
+ job.createdAt -= 10 * 60 * 1000;
+ expect(cleanupExpiredJobs()).toBe(0);
+ const deadline = job.recordingVerificationDeadlineAt;
+ touchJob(job.jobId);
+ expect(beginRecordingVerification(job.jobId, 50 * 60 * 1000)).toBe(false);
+ expect(job.recordingVerificationDeadlineAt).toBe(deadline);
+ job.recordingVerificationDeadlineAt = Date.now() - 1;
+ expect(cleanupExpiredJobs()).toBe(1);
+ expect(job.error).toBe("Recording verification timed out");
+ });
+
+ test("cannot revive an aborted job for verification", () => {
+ const job = createTrackedJob("job-verification-cancelled");
+ job.phase = "uploading";
+ job.abortController = new AbortController();
+ job.abortController.abort();
+ expect(beginRecordingVerification(job.jobId, 50 * 60 * 1000)).toBe(false);
+ expect(job.recordingVerificationDeadlineAt).toBeUndefined();
+ });
+
test("keeps a processing job alive after a heartbeat", () => {
const job = createTrackedJob("job-heartbeat");
const now = Date.now();
diff --git a/apps/media-server/src/__tests__/lib/recording-verification.integration.test.ts b/apps/media-server/src/__tests__/lib/recording-verification.integration.test.ts
new file mode 100644
index 000000000..9b78ab6e8
--- /dev/null
+++ b/apps/media-server/src/__tests__/lib/recording-verification.integration.test.ts
@@ -0,0 +1,537 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ isRetryableRecordingVerificationError,
+ verifyRecording,
+ verifyRemoteRecording,
+} from "../../lib/recording-verification";
+
+const FIXTURES = join(import.meta.dir, "..", "fixtures");
+let directory: string;
+let silent: string;
+let shortAudio: string;
+let corruptTail: string;
+let truncatedTail: string;
+let audioGap: string;
+let variableFrameRate: string;
+let silentBytes: Uint8Array<ArrayBuffer>;
+let corruptBytes: Uint8Array<ArrayBuffer>;
+
+async function run(command: string[]): Promise<string> {
+ const proc = Bun.spawn(command, { stdout: "pipe", stderr: "pipe" });
+ const [output, error, exitCode] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ proc.exited,
+ ]);
+ if (exitCode !== 0) throw new Error(error);
+ return output;
+}
+
+async function generate(path: string, audio: string, filters: string[] = []) {
+ await run([
+ "ffmpeg",
+ "-v",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc2=size=320x180:rate=30:duration=5",
+ "-f",
+ "lavfi",
+ "-i",
+ audio,
+ ...filters,
+ "-c:v",
+ "libx264",
+ "-preset",
+ "ultrafast",
+ "-pix_fmt",
+ "yuv420p",
+ "-c:a",
+ "aac",
+ "-movflags",
+ "+faststart",
+ path,
+ ]);
+}
+
+beforeAll(async () => {
+ directory = await mkdtemp(join(tmpdir(), "cap-recording-verification-"));
+ silent = join(directory, "silent.mp4");
+ shortAudio = join(directory, "short-audio.mp4");
+ audioGap = join(directory, "audio-gap.mp4");
+ variableFrameRate = join(directory, "variable-frame-rate.mp4");
+ corruptTail = join(directory, "corrupt-tail.mp4");
+ truncatedTail = join(directory, "truncated-tail.mp4");
+ await generate(silent, "anullsrc=r=48000:cl=mono:d=5");
+ await generate(
+ shortAudio,
+ "sine=frequency=700:sample_rate=48000:duration=0.1",
+ );
+ await generate(audioGap, "sine=frequency=700:sample_rate=48000:duration=4", [
+ "-af",
+ "asetpts=PTS+if(gte(T\\,2)\\,1/TB\\,0)",
+ ]);
+ await generate(variableFrameRate, "anullsrc=r=48000:cl=mono:d=5", [
+ "-vf",
+ "select=not(mod(n\\,3))+not(mod(n\\,5))",
+ "-fps_mode",
+ "vfr",
+ "-video_track_timescale",
+ "90000",
+ ]);
+ silentBytes = new Uint8Array(await readFile(silent));
+ const packets: {
+ packets: { pos: string; size: string; pts_time: string }[];
+ } = JSON.parse(
+ await run([
+ "ffprobe",
+ "-v",
+ "error",
+ "-select_streams",
+ "v:0",
+ "-show_packets",
+ "-show_entries",
+ "packet=pos,size,pts_time",
+ "-of",
+ "json",
+ silent,
+ ]),
+ );
+ const last = packets.packets.at(-1);
+ if (!last || Number(last.pts_time) < 4.5) {
+ throw new Error("Fault fixture has no late video packet");
+ }
+ const damaged = silentBytes.slice();
+ damaged.fill(0, Number(last.pos), Number(last.pos) + Number(last.size));
+ corruptBytes = damaged;
+ await writeFile(corruptTail, damaged);
+ await writeFile(
+ truncatedTail,
+ silentBytes.subarray(0, Math.floor(silentBytes.length * 0.9)),
+ );
+}, 30_000);
+
+afterAll(async () => {
+ if (directory) await rm(directory, { recursive: true, force: true });
+});
+
+describe("complete recording decode", () => {
+ test("counts real decoded frames and samples, including valid silent audio", async () => {
+ const evidence = await verifyRecording(silent, {
+ expectedDuration: 5,
+ requireAudio: true,
+ });
+ expect(evidence.fullDecode).toBe(true);
+ expect(evidence.video.frameCount).toBe(150);
+ expect(evidence.video.duration).toBeCloseTo(5, 3);
+ expect(evidence.audio?.sampleCount).toBeGreaterThanOrEqual(240_000);
+ expect(evidence.audio?.sampleRate).toBe(48_000);
+ expect(evidence.audio?.decodedDuration).toBeCloseTo(5, 1);
+ });
+
+ test("accepts legacy video without audio only when audio was not requested", async () => {
+ const input = join(FIXTURES, "test-no-audio.mp4");
+ const evidence = await verifyRecording(input, {
+ expectedDuration: 1,
+ requireAudio: false,
+ });
+ expect(evidence.video.frameCount).toBe(25);
+ expect(evidence.audio).toBeNull();
+ await expect(
+ verifyRecording(input, { expectedDuration: 1, requireAudio: true }),
+ ).rejects.toThrow("missing required audio coverage");
+ });
+
+ test("preserves the source timebase for variable frame rate video", async () => {
+ const evidence = await verifyRecording(variableFrameRate, {
+ expectedDuration: 5,
+ requireAudio: true,
+ });
+ expect(evidence.video.frameCount).toBe(70);
+ expect(evidence.video.duration).toBeGreaterThan(4.8);
+ });
+
+ test.each(["corrupt", "truncated"])(
+ "rejects a %s tail even with a readable complete-duration header",
+ async (damage) => {
+ const input = damage === "corrupt" ? corruptTail : truncatedTail;
+ const header = await run([
+ "ffprobe",
+ "-v",
+ "error",
+ "-show_entries",
+ "format=duration",
+ "-of",
+ "json",
+ input,
+ ]);
+ expect(Number(JSON.parse(header).format.duration)).toBe(5);
+ const error = await verifyRecording(input, {
+ expectedDuration: 5,
+ requireAudio: true,
+ }).catch((error: unknown) => error);
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toContain(
+ "Recording full decode failed",
+ );
+ expect(isRetryableRecordingVerificationError(error)).toBe(false);
+ },
+ );
+
+ test("rejects a readable short audio track and a missing middle interval", async () => {
+ for (const input of [shortAudio, audioGap]) {
+ await expect(
+ verifyRecording(input, { expectedDuration: 5, requireAudio: true }),
+ ).rejects.toThrow("missing required audio coverage");
+ }
+ });
+
+ test("rejects a completely decodable video that is shorter than expected", async () => {
+ await expect(
+ verifyRecording(join(FIXTURES, "test-with-audio.mp4"), {
+ expectedDuration: 5,
+ requireAudio: true,
+ }),
+ ).rejects.toThrow("does not cover its expected duration");
+ });
+
+ test("does not follow local symlinks", async () => {
+ const link = join(directory, "linked.mp4");
+ await symlink(silent, link);
+ await expect(
+ verifyRecording(link, { expectedDuration: 5, requireAudio: true }),
+ ).rejects.toThrow("regular MP4 file");
+ });
+});
+
+async function decoderPids(input: string): Promise<number[]> {
+ const output = await run(["ps", "-axo", "pid=,command="]);
+ return output
+ .split("\n")
+ .filter((line) => line.includes("ffmpeg") && line.includes(input))
+ .map((line) => Number.parseInt(line.trim(), 10));
+}
+
+function expectExited(pid: number) {
+ expect(() => process.kill(pid, 0)).toThrow();
+}
+
+describe("recording verification lifetime", () => {
+ test("does not start work for an already cancelled request", async () => {
+ const controller = new AbortController();
+ controller.abort();
+ await expect(
+ verifyRecording(silent, {
+ expectedDuration: 5,
+ requireAudio: true,
+ abortSignal: controller.signal,
+ }),
+ ).rejects.toThrow("cancelled");
+ });
+
+ test.each(["cancel", "timeout"])(
+ "joins its real decoder after %s while the input is stalled",
+ async (cause) => {
+ let received: (() => void) | undefined;
+ const request = new Promise<void>((resolve) => {
+ received = resolve;
+ });
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch() {
+ received?.();
+ return new Response(
+ new ReadableStream({
+ start(controller) {
+ controller.enqueue(silentBytes.subarray(0, 16_384));
+ },
+ }),
+ { headers: { "Content-Type": "video/mp4" } },
+ );
+ },
+ });
+ const controller = new AbortController();
+ const input = `http://127.0.0.1:${server.port}/${crypto.randomUUID()}.mp4`;
+ try {
+ const outcome = verifyRecording(input, {
+ expectedDuration: 5,
+ requireAudio: true,
+ abortSignal: controller.signal,
+ timeoutMs: cause === "timeout" ? 1_000 : 5_000,
+ }).then(
+ () => new Error("Unexpected successful verification"),
+ (error: unknown) => error,
+ );
+ await request;
+ const pids = await decoderPids(input);
+ expect(pids.length).toBe(1);
+ if (cause === "cancel") controller.abort();
+ const error = await outcome;
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toContain(
+ cause === "cancel" ? "cancelled" : "timed out",
+ );
+ for (const pid of pids) expectExited(pid);
+ } finally {
+ controller.abort();
+ await server.stop(true);
+ }
+ },
+ 10_000,
+ );
+
+ test("decodes remote output and never includes signed query values in failures", async () => {
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ return new URL(request.url).pathname === "/valid.mp4"
+ ? new Response(silentBytes, {
+ headers: { "Content-Type": "video/mp4" },
+ })
+ : new Response("Missing", { status: 404 });
+ },
+ });
+ try {
+ const evidence = await verifyRecording(
+ `http://127.0.0.1:${server.port}/valid.mp4`,
+ { expectedDuration: 5, requireAudio: true },
+ );
+ expect(evidence.video.frameCount).toBe(150);
+ const result = await verifyRecording(
+ `http://127.0.0.1:${server.port}/missing.mp4?signature=private-value`,
+ { expectedDuration: 5, requireAudio: true },
+ ).catch((error: unknown) => error);
+ expect(result).toBeInstanceOf(Error);
+ expect((result as Error).message).not.toContain("private-value");
+ } finally {
+ await server.stop(true);
+ }
+ });
+});
+
+function objectResponse(
+ request: Request,
+ identity?: string,
+ honorCondition = true,
+ bytes = silentBytes,
+) {
+ if (
+ honorCondition &&
+ request.headers.has("if-match") &&
+ request.headers.get("if-match") !== identity
+ ) {
+ return new Response("Object changed", { status: 412 });
+ }
+ const headers: Record<string, string> = {
+ "Content-Type": "video/mp4",
+ };
+ if (identity !== undefined) headers.ETag = identity;
+ if (request.headers.get("range") === "bytes=0-0") {
+ headers["Content-Range"] = `bytes 0-0/${bytes.byteLength}`;
+ return new Response(bytes.subarray(0, 1), { status: 206, headers });
+ }
+ return new Response(bytes, { headers });
+}
+
+describe("remote recording object identity", () => {
+ test("binds the decode and receipt to a strong opaque object version", async () => {
+ const requests: { match: string | null; optIn: string | null }[] = [];
+ const identity = '"drive-file:42"';
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ requests.push({
+ match: request.headers.get("if-match"),
+ optIn: request.headers.get("x-cap-recording-verification"),
+ });
+ return objectResponse(request, identity);
+ },
+ });
+ try {
+ const evidence = await verifyRemoteRecording(
+ `http://127.0.0.1:${server.port}/recording.mp4`,
+ {
+ expectedDuration: 5,
+ requireAudio: true,
+ expectedObjectIdentity: identity,
+ },
+ );
+ expect(evidence.fullDecode).toBe(true);
+ expect(evidence.video.frameCount).toBe(150);
+ expect(evidence.objectIdentity).toBe(identity);
+ expect(evidence.fileSize).toBe(silentBytes.byteLength);
+ expect(requests.length).toBeGreaterThanOrEqual(3);
+ expect(requests.every((request) => request.match === identity)).toBe(
+ true,
+ );
+ expect(requests.every((request) => request.optIn === "1")).toBe(true);
+ } finally {
+ await server.stop(true);
+ }
+ });
+
+ test.each([undefined, 'W/"weak-version"'])(
+ "refuses a missing or weak object identity (%s) before decoding",
+ async (identity) => {
+ let decoderRequests = 0;
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ if (request.headers.get("range") !== "bytes=0-0") decoderRequests++;
+ return objectResponse(request, identity);
+ },
+ });
+ try {
+ await expect(
+ verifyRemoteRecording(
+ `http://127.0.0.1:${server.port}/recording.mp4`,
+ {
+ expectedDuration: 5,
+ requireAudio: true,
+ },
+ ),
+ ).rejects.toThrow("does not expose a strong object identity");
+ expect(decoderRequests).toBe(0);
+ } finally {
+ await server.stop(true);
+ }
+ },
+ );
+
+ test.each(["before-decode", "after-decode", "ignored-condition"])(
+ "rejects same-size corrupt replacement of a valid object (%s)",
+ async (when) => {
+ let probes = 0;
+ let decoderRequests = 0;
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ const probe = request.headers.get("range") === "bytes=0-0";
+ if (probe) probes++;
+ else decoderRequests++;
+ const changed = probes > 1 || (when === "before-decode" && !probe);
+ return objectResponse(
+ request,
+ changed ? '"new-version"' : '"original-version"',
+ when !== "ignored-condition",
+ changed ? corruptBytes : silentBytes,
+ );
+ },
+ });
+ try {
+ const error = await verifyRemoteRecording(
+ `http://127.0.0.1:${server.port}/recording.mp4`,
+ { expectedDuration: 5, requireAudio: true },
+ ).catch((error: unknown) => error);
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toContain(
+ when === "before-decode" ? "full decode failed" : "object changed",
+ );
+ expect(isRetryableRecordingVerificationError(error)).toBe(false);
+ expect(decoderRequests).toBeGreaterThan(0);
+ if (when !== "before-decode") expect(probes).toBe(2);
+ } finally {
+ await server.stop(true);
+ }
+ },
+ );
+
+ test.each(["cancel", "timeout"])(
+ "keeps decoder cleanup effective across remote identity checks on %s",
+ async (cause) => {
+ let started: (() => void) | undefined;
+ const decoding = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ let probes = 0;
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ if (request.headers.get("range") === "bytes=0-0") {
+ probes++;
+ return objectResponse(request, '"original-version"');
+ }
+ started?.();
+ return new Response(
+ new ReadableStream({
+ start(controller) {
+ controller.enqueue(silentBytes.subarray(0, 16_384));
+ },
+ }),
+ { headers: { "Content-Type": "video/mp4" } },
+ );
+ },
+ });
+ const controller = new AbortController();
+ const input = `http://127.0.0.1:${server.port}/${crypto.randomUUID()}.mp4`;
+ try {
+ const outcome = verifyRemoteRecording(input, {
+ expectedDuration: 5,
+ requireAudio: true,
+ abortSignal: controller.signal,
+ timeoutMs: cause === "timeout" ? 1_000 : 5_000,
+ }).then(
+ () => new Error("Unexpected successful verification"),
+ (error: unknown) => error,
+ );
+ await decoding;
+ const pids = await decoderPids(input);
+ expect(pids.length).toBe(1);
+ if (cause === "cancel") controller.abort();
+ const error = await outcome;
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toContain(
+ cause === "cancel" ? "cancelled" : "timed out",
+ );
+ expect(probes).toBe(1);
+ expect(isRetryableRecordingVerificationError(error)).toBe(
+ cause === "timeout",
+ );
+ for (const pid of pids) expectExited(pid);
+ } finally {
+ controller.abort();
+ await server.stop(true);
+ }
+ },
+ 10_000,
+ );
+
+ test.each(["identity-read", "decoder-read"])(
+ "classifies HTTP503 during %s as retryable without a receipt",
+ async (stage) => {
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ if (
+ stage === "identity-read" ||
+ request.headers.get("range") !== "bytes=0-0"
+ ) {
+ return new Response("Unavailable", { status: 503 });
+ }
+ return objectResponse(request, '"original-version"');
+ },
+ });
+ try {
+ const error = await verifyRemoteRecording(
+ `http://127.0.0.1:${server.port}/recording.mp4`,
+ { expectedDuration: 5, requireAudio: true },
+ ).catch((error: unknown) => error);
+ expect(error).toBeInstanceOf(Error);
+ expect(isRetryableRecordingVerificationError(error)).toBe(true);
+ } finally {
+ await server.stop(true);
+ }
+ },
+ );
+});
diff --git a/apps/media-server/src/__tests__/lib/storage-upload.test.ts b/apps/media-server/src/__tests__/lib/storage-upload.test.ts
index f49f23771..3ad2ae5fd 100644
--- a/apps/media-server/src/__tests__/lib/storage-upload.test.ts
+++ b/apps/media-server/src/__tests__/lib/storage-upload.test.ts
@@ -27,6 +27,112 @@ describe("uploadFileToStorage", () => {
globalThis.fetch = originalFetch;
});
+ test("returns the successful PUT identity without a later HEAD lookup", async () => {
+ const uploadFile = await createTempUploadFile(11);
+ const methods: string[] = [];
+ globalThis.fetch = (async (_input, init) => {
+ methods.push(init?.method ?? "GET");
+ return methods.length === 1
+ ? new Response("Unavailable", {
+ status: 503,
+ headers: { ETag: '"failed-attempt"' },
+ })
+ : new Response(null, {
+ status: 200,
+ headers: { ETag: '"written-version"' },
+ });
+ }) as typeof fetch;
+ try {
+ const receipt = await uploadFileToStorage(
+ uploadFile.path,
+ { type: "put", url: "https://storage.example.com/recording.mp4" },
+ "video/mp4",
+ );
+ expect(receipt.objectIdentity).toBe('"written-version"');
+ expect(methods).toEqual(["PUT", "PUT"]);
+ } finally {
+ await uploadFile.cleanup();
+ }
+ });
+
+ test.each([undefined, 'W/"weak-version"'])(
+ "keeps successful legacy uploads compatible without claiming identity (%s)",
+ async (identity) => {
+ const uploadFile = await createTempUploadFile(11);
+ globalThis.fetch = (async (_input, _init) =>
+ new Response(null, {
+ headers: identity ? { ETag: identity } : {},
+ })) as typeof fetch;
+ try {
+ const receipt = await uploadFileToStorage(
+ uploadFile.path,
+ { type: "put", url: "https://storage.example.com/recording.mp4" },
+ "video/mp4",
+ );
+ expect(receipt.objectIdentity).toBeUndefined();
+ } finally {
+ await uploadFile.cleanup();
+ }
+ },
+ );
+
+ test("binds a Drive upload to its completed response version without rounding", async () => {
+ const uploadFile = await createTempUploadFile(11);
+ const methods: string[] = [];
+ globalThis.fetch = (async (_input, init) => {
+ methods.push(init?.method ?? "GET");
+ expect(new Headers(init?.headers).get("content-range")).toBe(
+ "bytes 0-10/11",
+ );
+ return Response.json({
+ id: "drive-file-1",
+ version: "9007199254740993",
+ size: "11",
+ });
+ }) as typeof fetch;
+ try {
+ const receipt = await uploadFileToStorage(
+ uploadFile.path,
+ {
+ type: "put",
+ url: "https://www.googleapis.com/upload/drive/v3/files?upload_id=session",
+ },
+ "video/mp4",
+ );
+ expect(receipt.objectIdentity).toBe('"drive-file-1:9007199254740993"');
+ expect(methods).toEqual(["PUT"]);
+ } finally {
+ await uploadFile.cleanup();
+ }
+ });
+
+ test.each([
+ { id: "drive-file-1", size: "11" },
+ { id: 'invalid"id', version: "1", size: "11" },
+ { id: "drive-file-1", version: "0", size: "11" },
+ { id: "drive-file-1", version: "1", size: "12" },
+ ])(
+ "withholds incomplete or inconsistent Drive upload identity: %j",
+ async (metadata) => {
+ const uploadFile = await createTempUploadFile(11);
+ globalThis.fetch = (async (_input, _init) =>
+ Response.json(metadata)) as typeof fetch;
+ try {
+ const receipt = await uploadFileToStorage(
+ uploadFile.path,
+ {
+ type: "put",
+ url: "https://www.googleapis.com/upload/drive/v3/files?upload_id=session",
+ },
+ "video/mp4",
+ );
+ expect(receipt.objectIdentity).toBeUndefined();
+ } finally {
+ await uploadFile.cleanup();
+ }
+ },
+ );
+
test("uploads multipart files in signed parts and completes them", async () => {
const uploadFile = await createTempUploadFile(partSize + 3);
const requests: Array<{
@@ -57,7 +163,10 @@ describe("uploadFileToStorage", () => {
});
}
- return Response.json({ success: true });
+ return Response.json({
+ success: true,
+ objectIdentity: '"completed-object-version"',
+ });
}
const body = init?.body as Blob;
@@ -75,7 +184,7 @@ describe("uploadFileToStorage", () => {
}) as typeof fetch;
try {
- await uploadFileToStorage(
+ const receipt = await uploadFileToStorage(
uploadFile.path,
{
type: "multipart",
@@ -90,6 +199,7 @@ describe("uploadFileToStorage", () => {
},
"video/mp4",
);
+ expect(receipt.objectIdentity).toBe('"completed-object-version"');
} finally {
await uploadFile.cleanup();
}
diff --git a/apps/media-server/src/__tests__/routes/recording-verification.test.ts b/apps/media-server/src/__tests__/routes/recording-verification.test.ts
new file mode 100644
index 000000000..a6da439ac
--- /dev/null
+++ b/apps/media-server/src/__tests__/routes/recording-verification.test.ts
@@ -0,0 +1,283 @@
+import {
+ afterAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ mock,
+ spyOn,
+ test,
+} from "bun:test";
+import type { JobProgress, VideoMetadata } from "../../lib/job-manager";
+import * as jobManager from "../../lib/job-manager";
+import * as mediaProbe from "../../lib/media-probe";
+import type { RemoteRecordingVerificationResult } from "../../lib/recording-verification";
+import * as recordingVerification from "../../lib/recording-verification";
+import video from "../../routes/video";
+
+const originalFetch = globalThis.fetch;
+const originalSecret = process.env.MEDIA_SERVER_WEBHOOK_SECRET;
+const realVerifyRemoteRecording = recordingVerification.verifyRemoteRecording;
+const secret = "isolated-recording-verification-test";
+const headers = {
+ "Content-Type": "application/json",
+ "x-media-server-secret": secret,
+};
+const body = {
+ videoId: "owned-verification-video",
+ userId: "owned-verification-user",
+ videoUrl: "https://storage.example.test/recording.mp4",
+ fileSize: 128,
+ duration: 5,
+ requiredAudio: false,
+ objectIdentity: '"uploaded-generation"',
+ webhookUrl: "https://webhook.example.test/progress",
+ webhookSecret: secret,
+};
+const metadata: VideoMetadata = {
+ duration: 5,
+ width: 320,
+ height: 180,
+ fps: 30,
+ videoCodec: "h264",
+ audioCodec: "aac",
+ audioChannels: 1,
+ sampleRate: 48_000,
+ bitrate: 200_000,
+ fileSize: 128,
+};
+const evidence: RemoteRecordingVerificationResult = {
+ fullDecode: true,
+ objectIdentity: body.objectIdentity,
+ fileSize: body.fileSize,
+ video: { frameCount: 148, startTime: 0, endTime: 4.95, duration: 4.95 },
+ audio: null,
+};
+const jobs: string[] = [];
+let webhooks: JobProgress[] = [];
+let requests: { url: string; method: string }[] = [];
+let identityResponse: Response | undefined;
+const probe = spyOn(mediaProbe, "probeVideo");
+const verify = spyOn(recordingVerification, "verifyRemoteRecording");
+const capacity = spyOn(jobManager, "canAcceptNewVideoProcess");
+const memoryPressure = spyOn(jobManager, "hasCriticalMemoryPressure");
+
+async function waitFor(predicate: () => boolean) {
+ const deadline = performance.now() + 2_500;
+ while (!predicate()) {
+ if (performance.now() >= deadline) {
+ throw new Error("Verification job did not settle within the test budget");
+ }
+ await Bun.sleep(5);
+ }
+}
+
+async function startJob() {
+ const response = await video.request("/verify-recording", {
+ method: "POST",
+ headers,
+ body: JSON.stringify(body),
+ });
+ expect(response.status).toBe(200);
+ const accepted = (await response.json()) as { jobId: string };
+ expect(Object.keys(accepted)).toEqual(["jobId"]);
+ expect(typeof accepted.jobId).toBe("string");
+ jobs.push(accepted.jobId);
+ return accepted.jobId;
+}
+
+async function status(jobId: string): Promise<JobProgress> {
+ const response = await video.request(`/process/${jobId}/status`);
+ expect(response.status).toBe(200);
+ return response.json();
+}
+
+async function terminalWebhook(jobId: string): Promise<JobProgress> {
+ await waitFor(() => webhooks.some((payload) => payload.jobId === jobId));
+ const payload = webhooks.find((item) => item.jobId === jobId);
+ if (!payload) throw new Error("Missing terminal webhook");
+ return payload;
+}
+
+function waitForDecoderCancellation() {
+ let joined = false;
+ verify.mockImplementation(async (_input, options) => {
+ await new Promise<void>((_resolve, reject) => {
+ const abort = () =>
+ reject(new Error("Recording verification was cancelled"));
+ if (options.abortSignal?.aborted) abort();
+ else
+ options.abortSignal?.addEventListener("abort", abort, { once: true });
+ }).finally(() => {
+ joined = true;
+ });
+ return evidence;
+ });
+ return () => joined;
+}
+
+beforeEach(() => {
+ process.env.MEDIA_SERVER_WEBHOOK_SECRET = secret;
+ webhooks = [];
+ requests = [];
+ identityResponse = undefined;
+ probe.mockReset().mockResolvedValue(metadata);
+ verify.mockReset().mockResolvedValue(evidence);
+ capacity.mockReset().mockReturnValue(true);
+ memoryPressure.mockReset().mockReturnValue(false);
+ globalThis.fetch = (async (input, init) => {
+ const request = new Request(input, init);
+ requests.push({ url: request.url, method: request.method });
+ if (request.url === body.webhookUrl && request.method === "POST") {
+ expect(request.headers.get("x-media-server-secret")).toBe(secret);
+ webhooks.push((await request.json()) as JobProgress);
+ return new Response(null, { status: 200 });
+ }
+ if (
+ request.url === body.videoUrl &&
+ request.method === "GET" &&
+ identityResponse
+ ) {
+ return identityResponse;
+ }
+ throw new Error(
+ `Unexpected test request: ${request.method} ${request.url}`,
+ );
+ }) as typeof fetch;
+});
+
+afterEach(async () => {
+ for (const jobId of jobs.splice(0)) {
+ jobManager.getJob(jobId)?.abortController?.abort();
+ await waitFor(() => webhooks.some((payload) => payload.jobId === jobId));
+ jobManager.deleteJob(jobId);
+ }
+ globalThis.fetch = originalFetch;
+});
+
+afterAll(() => {
+ mock.restore();
+ if (originalSecret === undefined)
+ delete process.env.MEDIA_SERVER_WEBHOOK_SECRET;
+ else process.env.MEDIA_SERVER_WEBHOOK_SECRET = originalSecret;
+});
+
+describe("asynchronous recording verification", () => {
+ test("acceptance is not proof and completed metadata comes from decoded evidence", async () => {
+ let finish:
+ | ((value: RemoteRecordingVerificationResult) => void)
+ | undefined;
+ verify.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const jobId = await startJob();
+ await waitFor(() => verify.mock.calls.length === 1);
+ try {
+ const pending = await status(jobId);
+ expect(pending.phase).toBe("processing");
+ expect(pending.recordingVerification).toBeUndefined();
+ expect(webhooks).toHaveLength(0);
+ expect(verify.mock.calls[0]?.[1]).toMatchObject({
+ expectedDuration: body.duration,
+ requireAudio: body.requiredAudio,
+ expectedObjectIdentity: body.objectIdentity,
+ });
+ } finally {
+ finish?.(evidence);
+ }
+ const completed = await terminalWebhook(jobId);
+ expect(completed.phase).toBe("complete");
+ expect(completed.metadata?.duration).toBe(evidence.video.duration);
+ expect(completed.metadata?.audioCodec).toBeNull();
+ expect(completed.recordingVerification).toEqual({
+ request: {
+ version: 1,
+ artifact: {
+ kind: "mp4",
+ fileSize: body.fileSize,
+ duration: body.duration,
+ objectIdentity: body.objectIdentity,
+ },
+ requiredAudio: false,
+ },
+ fullDecode: true,
+ objectIdentity: evidence.objectIdentity,
+ });
+ expect((await status(jobId)).recordingVerification).toEqual(
+ completed.recordingVerification,
+ );
+ });
+
+ test("probe unavailability publishes a retryable error without issuing proof or storage writes", async () => {
+ probe.mockRejectedValue(new Error("Media input is not accessible (503)"));
+ const jobId = await startJob();
+ const failed = await terminalWebhook(jobId);
+ expect(failed.phase).toBe("error");
+ expect(failed.error).toBe(
+ "Recording verification temporarily unavailable (503)",
+ );
+ expect(failed.recordingVerification).toBeUndefined();
+ expect(verify).not.toHaveBeenCalled();
+ expect(requests).toEqual([{ url: body.webhookUrl, method: "POST" }]);
+ expect((await status(jobId)).recordingVerification).toBeUndefined();
+ });
+
+ test("typed remote storage503 remains retryable after a successful probe", async () => {
+ identityResponse = new Response("Unavailable", { status: 503 });
+ verify.mockImplementation(realVerifyRemoteRecording);
+ const failed = await terminalWebhook(await startJob());
+ expect(failed.phase).toBe("error");
+ expect(failed.error).toBe(
+ "Recording verification temporarily unavailable (503)",
+ );
+ expect(failed.recordingVerification).toBeUndefined();
+ expect(requests).toEqual([
+ { url: body.videoUrl, method: "GET" },
+ { url: body.webhookUrl, method: "POST" },
+ ]);
+ });
+
+ test("memory pressure joins cancelled decoding and remains a retryable error", async () => {
+ const joined = waitForDecoderCancellation();
+ memoryPressure.mockReturnValue(true);
+ const failed = await terminalWebhook(await startJob());
+ expect(joined()).toBe(true);
+ expect(failed.phase).toBe("error");
+ expect(failed.error).toBe(
+ "Recording verification temporarily unavailable (503)",
+ );
+ expect(failed.recordingVerification).toBeUndefined();
+ });
+
+ test("explicit owner cancellation is not classified as a transient storage failure", async () => {
+ const joined = waitForDecoderCancellation();
+ const jobId = await startJob();
+ await waitFor(() => verify.mock.calls.length === 1);
+ jobManager.getJob(jobId)?.abortController?.abort();
+ const cancelled = await terminalWebhook(jobId);
+ expect(joined()).toBe(true);
+ expect(cancelled.phase).toBe("cancelled");
+ expect(cancelled.error).not.toContain("503");
+ expect(cancelled.recordingVerification).toBeUndefined();
+ });
+
+ test.each([
+ "Recording object changed during verification",
+ "Recording decoding failed: corrupt input packet",
+ ])(
+ "withholds proof after permanent verification failure: %s",
+ async (message) => {
+ verify.mockRejectedValue(new Error(message));
+ const failed = await terminalWebhook(await startJob());
+ expect(failed.phase).toBe("error");
+ expect(failed.error).toBe(
+ "Uploaded recording content could not be verified; retain the local recording",
+ );
+ expect(failed.recordingVerification).toBeUndefined();
+ expect(failed.metadata).toBeUndefined();
+ },
+ );
+});
diff --git a/apps/media-server/src/lib/job-manager.ts b/apps/media-server/src/lib/job-manager.ts
index c998af9f9..43faf3287 100644
--- a/apps/media-server/src/lib/job-manager.ts
+++ b/apps/media-server/src/lib/job-manager.ts
@@ -19,7 +19,28 @@ export type JobPhase =
| "error"
| "cancelled";
+export interface RecordingVerificationRequest {
+ version: 1;
+ artifact:
+ | { kind: "segments"; manifestSha256: string }
+ | {
+ kind: "mp4";
+ fileSize: number;
+ duration: number;
+ objectIdentity: string;
+ };
+ requiredAudio: boolean;
+}
+
+export interface RecordingVerificationProof {
+ request: RecordingVerificationRequest;
+ fullDecode: true;
+ objectIdentity: string;
+}
+
export interface JobProgress {
+ recordingVerification?: RecordingVerificationProof;
+ manifestSha256?: string;
jobId: string;
videoId: string;
phase: JobPhase;
@@ -44,6 +65,9 @@ export interface VideoMetadata {
}
export interface Job {
+ recordingVerificationDeadlineAt?: number;
+ recordingVerification?: RecordingVerificationProof;
+ manifestSha256?: string;
jobId: string;
videoId: string;
userId: string;
@@ -285,6 +309,8 @@ export function updateJob(
| "message"
| "error"
| "metadata"
+ | "manifestSha256"
+ | "recordingVerification"
| "outputUrl"
| "inputTempFile"
| "outputTempFile"
@@ -308,6 +334,28 @@ export function touchJob(jobId: string): Job | undefined {
return job;
}
+export function beginRecordingVerification(
+ jobId: string,
+ budgetMs: number,
+): boolean {
+ const job = jobs.get(jobId);
+ const now = Date.now();
+ if (
+ !job ||
+ !isActivePhase(job.phase) ||
+ job.abortController?.signal.aborted ||
+ job.recordingVerificationDeadlineAt !== undefined ||
+ now > job.createdAt + MAX_JOB_LIFETIME_MS ||
+ !Number.isSafeInteger(budgetMs) ||
+ budgetMs <= 0 ||
+ budgetMs > MAX_JOB_LIFETIME_MS
+ )
+ return false;
+ job.recordingVerificationDeadlineAt = now + budgetMs;
+ job.updatedAt = now;
+ return true;
+}
+
export function deleteJob(jobId: string): boolean {
const job = jobs.get(jobId);
if (job) {
@@ -384,13 +432,19 @@ export function cleanupExpiredJobs(): number {
continue;
}
- if (isActivePhase(job.phase) && age > MAX_JOB_LIFETIME_MS) {
+ const deadline =
+ job.recordingVerificationDeadlineAt ??
+ job.createdAt + MAX_JOB_LIFETIME_MS;
+ if (isActivePhase(job.phase) && now > deadline) {
console.warn(
`[job-manager] Marking long-running job ${jobId} as error (phase=${job.phase}, age=${Math.round(age / 60000)}m)`,
);
job.abortController?.abort();
job.phase = "error";
- job.error = `Job exceeded maximum lifetime of ${Math.round(MAX_JOB_LIFETIME_MS / 60000)} minutes`;
+ job.error =
+ job.recordingVerificationDeadlineAt === undefined
+ ? `Job exceeded maximum lifetime of ${Math.round(MAX_JOB_LIFETIME_MS / 60000)} minutes`
+ : "Recording verification timed out";
job.message = "Processing failed (timeout)";
job.updatedAt = now;
void sendWebhook(job);
@@ -403,6 +457,8 @@ export function cleanupExpiredJobs(): number {
export function getJobProgress(job: Job): JobProgress {
return {
+ manifestSha256: job.manifestSha256,
+ recordingVerification: job.recordingVerification,
jobId: job.jobId,
videoId: job.videoId,
phase: job.phase,
diff --git a/apps/media-server/src/lib/media-video.ts b/apps/media-server/src/lib/media-video.ts
index e4d107ae7..c365de918 100644
--- a/apps/media-server/src/lib/media-video.ts
+++ b/apps/media-server/src/lib/media-video.ts
@@ -60,6 +60,10 @@ export type StorageUploadTarget =
webhookSecret?: string;
};
+export interface StorageUploadReceipt {
+ objectIdentity?: string;
+}
+
type UploadedPart = {
partNumber: number;
etag: string;
@@ -1951,7 +1955,58 @@ function isRetryableUploadStatus(status: number): boolean {
}
function isGoogleDriveResumableUrl(url: string): boolean {
- return url.includes("googleapis.com/upload/drive/");
+ const parsed = new URL(url);
+ return (
+ (parsed.hostname === "googleapis.com" ||
+ parsed.hostname.endsWith(".googleapis.com")) &&
+ parsed.pathname.startsWith("/upload/drive/")
+ );
+}
+
+function strongUploadIdentity(value: unknown): string | undefined {
+ return typeof value === "string" &&
+ value.length <= 1_024 &&
+ /^"[\x21\x23-\x7E\x80-\xFF]+"$/.test(value)
+ ? value
+ : undefined;
+}
+
+async function readUploadReceipt(
+ response: Response,
+ url: string,
+ contentLength: number,
+): Promise<StorageUploadReceipt> {
+ if (!isGoogleDriveResumableUrl(url)) {
+ await response.body?.cancel().catch(() => {});
+ return {
+ objectIdentity: strongUploadIdentity(response.headers.get("etag")),
+ };
+ }
+ const body = response.body
+ ? await readStreamWithLimit(response.body, MAX_STDERR_BYTES).catch(() => "")
+ : "";
+ let metadata: unknown;
+ try {
+ metadata = JSON.parse(body);
+ } catch {
+ return {};
+ }
+ if (!metadata || typeof metadata !== "object") return {};
+ const { id, version, size } = metadata as Record<string, unknown>;
+ if (
+ typeof id !== "string" ||
+ !/^[a-zA-Z0-9_-]{1,200}$/.test(id) ||
+ typeof version !== "string" ||
+ !/^[1-9]\d{0,19}$/.test(version) ||
+ typeof size !== "string" ||
+ !/^\d+$/.test(size) ||
+ !Number.isSafeInteger(Number(size)) ||
+ Number(size) !== contentLength ||
+ contentLength <= 0
+ ) {
+ return {};
+ }
+ return { objectIdentity: `"${id}:${version}"` };
}
async function sleep(ms: number): Promise<void> {
@@ -1963,7 +2018,7 @@ async function uploadWithRetry(
contentType: string,
contentLength: number,
bodyFactory: () => Blob | BunFile,
-): Promise<void> {
+): Promise<StorageUploadReceipt> {
let lastError: Error | undefined;
for (let attempt = 0; attempt <= UPLOAD_MAX_RETRIES; attempt++) {
@@ -1998,7 +2053,7 @@ async function uploadWithRetry(
}
if (response.ok) {
- return;
+ return readUploadReceipt(response, presignedUrl, contentLength);
}
const responseError = await storageResponseError(
@@ -2037,10 +2092,10 @@ export async function uploadFileToS3(
filePath: string,
presignedUrl: string,
contentType: string,
-): Promise<void> {
+): Promise<StorageUploadReceipt> {
const fileHandle = file(filePath);
- await uploadWithRetry(presignedUrl, contentType, fileHandle.size, () =>
+ return uploadWithRetry(presignedUrl, contentType, fileHandle.size, () =>
file(filePath),
);
}
@@ -2156,7 +2211,7 @@ async function uploadMultipartPart(
async function completeMultipartUpload(
target: Extract<StorageUploadTarget, { type: "multipart" }>,
parts: UploadedPart[],
-): Promise<void> {
+): Promise<StorageUploadReceipt> {
const response = await postMultipartJson(
target.completeUrl,
{
@@ -2174,6 +2229,14 @@ async function completeMultipartUpload(
response,
);
}
+ const result: unknown = await response.json().catch(() => null);
+ return {
+ objectIdentity: strongUploadIdentity(
+ result && typeof result === "object" && "objectIdentity" in result
+ ? result.objectIdentity
+ : undefined,
+ ),
+ };
}
async function abortMultipartUpload(
@@ -2197,7 +2260,7 @@ async function abortMultipartUpload(
async function uploadFileMultipart(
filePath: string,
target: Extract<StorageUploadTarget, { type: "multipart" }>,
-): Promise<void> {
+): Promise<StorageUploadReceipt> {
const fileHandle = file(filePath);
const contentLength = fileHandle.size;
const partSize = Math.floor(target.partSize);
@@ -2233,7 +2296,7 @@ async function uploadFileMultipart(
parts.push({ partNumber, etag, size: partLength });
}
- await completeMultipartUpload(target, parts);
+ return await completeMultipartUpload(target, parts);
} catch (error) {
await abortMultipartUpload(target).catch((abortError) => {
console.warn(
@@ -2256,13 +2319,12 @@ export async function uploadFileToStorage(
filePath: string,
target: StorageUploadTarget,
contentType: string,
-): Promise<void> {
+): Promise<StorageUploadReceipt> {
if (target.type === "put") {
- await uploadFileToS3(filePath, target.url, contentType);
- return;
+ return uploadFileToS3(filePath, target.url, contentType);
}
- await uploadFileMultipart(filePath, target);
+ return uploadFileMultipart(filePath, target);
}
export async function copyFileToMp4(
diff --git a/apps/media-server/src/lib/recording-verification.ts b/apps/media-server/src/lib/recording-verification.ts
new file mode 100644
index 000000000..9072b69c5
--- /dev/null
+++ b/apps/media-server/src/lib/recording-verification.ts
@@ -0,0 +1,564 @@
+import { lstat } from "node:fs/promises";
+import { isAbsolute } from "node:path";
+import { spawn } from "bun";
+import { PROCESS_TIMEOUT_MS } from "./media-common";
+import { registerSubprocess, unregisterSubprocess } from "./subprocess";
+
+const MAX_OUTPUT_LINE_LENGTH = 16_384;
+const MAX_ERROR_LENGTH = 2_048;
+const MAX_STDERR_LENGTH = 64 * 1_024;
+
+class RecordingVerificationError extends Error {
+ constructor(
+ message: string,
+ readonly retryable: boolean,
+ ) {
+ super(message);
+ this.name = "RecordingVerificationError";
+ }
+}
+
+export function isRetryableRecordingVerificationError(error: unknown): boolean {
+ return error instanceof RecordingVerificationError && error.retryable;
+}
+
+export interface RecordingVerificationOptions {
+ expectedDuration: number;
+ requireAudio: boolean;
+ abortSignal?: AbortSignal;
+ timeoutMs?: number;
+}
+
+export interface DecodedVideoEvidence {
+ frameCount: number;
+ startTime: number;
+ endTime: number;
+ duration: number;
+}
+
+export interface DecodedAudioEvidence extends DecodedVideoEvidence {
+ sampleCount: number;
+ sampleRate: number;
+ decodedDuration: number;
+}
+
+export interface RecordingVerificationResult {
+ fullDecode: true;
+ video: DecodedVideoEvidence;
+ audio: DecodedAudioEvidence | null;
+}
+
+export interface RemoteRecordingVerificationOptions
+ extends RecordingVerificationOptions {
+ expectedObjectIdentity?: string;
+}
+
+export interface RemoteRecordingVerificationResult
+ extends RecordingVerificationResult {
+ objectIdentity: string;
+ fileSize: number;
+}
+
+interface DecodedStream {
+ kind?: "video" | "audio";
+ timeBase?: number;
+ sampleRate?: number;
+ frameCount: number;
+ sampleCount: number;
+ startTime: number;
+ endTime: number;
+ previousTime: number;
+ maximumGap: number;
+}
+
+function positiveNumber(value: number): boolean {
+ return Number.isFinite(value) && value > 0;
+}
+
+function streamEvidence(stream: DecodedStream): DecodedVideoEvidence {
+ return {
+ frameCount: stream.frameCount,
+ startTime: stream.startTime,
+ endTime: stream.endTime,
+ duration: stream.endTime - stream.startTime,
+ };
+}
+
+function decodeLine(line: string, streams: Map<number, DecodedStream>): void {
+ if (!line) return;
+ const metadata = line.match(/^#(tb|media_type|sample_rate) (\d+):\s*(.+)$/);
+ if (metadata) {
+ const index = Number(metadata[2]);
+ if (index > 1) throw new Error("Unexpected decoded recording stream");
+ const stream = streams.get(index) ?? {
+ frameCount: 0,
+ sampleCount: 0,
+ startTime: Number.POSITIVE_INFINITY,
+ endTime: Number.NEGATIVE_INFINITY,
+ previousTime: Number.NEGATIVE_INFINITY,
+ maximumGap: 0,
+ };
+ streams.set(index, stream);
+ if (metadata[1] === "tb") {
+ const ratio = metadata[3].split("/").map(Number);
+ if (
+ ratio.length !== 2 ||
+ !ratio.every((value) => Number.isSafeInteger(value) && value > 0)
+ ) {
+ throw new Error("Invalid decoded recording timebase");
+ }
+ stream.timeBase = ratio[0] / ratio[1];
+ } else if (metadata[1] === "media_type") {
+ if (metadata[3] !== "video" && metadata[3] !== "audio") {
+ throw new Error("Invalid decoded recording stream type");
+ }
+ stream.kind = metadata[3];
+ } else {
+ stream.sampleRate = Number(metadata[3]);
+ if (!Number.isSafeInteger(stream.sampleRate) || stream.sampleRate <= 0) {
+ throw new Error("Invalid decoded recording sample rate");
+ }
+ }
+ return;
+ }
+ if (line.startsWith("#")) return;
+ const columns = line.split(",").map((value) => value.trim());
+ const [index, dts, pts, ticks, bytes] = columns.slice(0, 5).map(Number);
+ if (
+ columns.length < 6 ||
+ ![index, dts, pts, ticks, bytes].every(Number.isSafeInteger) ||
+ !/^[a-f0-9]{8}$/i.test(columns[5]) ||
+ ticks <= 0 ||
+ bytes <= 0
+ ) {
+ throw new Error("Invalid decoded recording frame");
+ }
+ const stream = streams.get(index);
+ if (!stream?.kind || !stream.timeBase) {
+ throw new Error("Decoded recording frame has no stream metadata");
+ }
+ const startTime = pts * stream.timeBase;
+ const duration = ticks * stream.timeBase;
+ const endTime = startTime + duration;
+ if (!Number.isFinite(endTime) || startTime <= stream.previousTime) {
+ throw new Error("Decoded recording timestamps are invalid");
+ }
+ stream.maximumGap = Math.max(
+ stream.maximumGap,
+ stream.frameCount === 0 ? 0 : startTime - stream.endTime,
+ );
+ stream.startTime = Math.min(stream.startTime, startTime);
+ stream.endTime = Math.max(stream.endTime, endTime);
+ stream.previousTime = startTime;
+ stream.frameCount++;
+ if (stream.kind === "audio") {
+ if (!stream.sampleRate) {
+ throw new Error("Decoded recording audio has no sample rate");
+ }
+ const samples = duration * stream.sampleRate;
+ if (
+ Math.abs(samples - Math.round(samples)) > 0.000_001 ||
+ !Number.isSafeInteger(stream.sampleCount + Math.round(samples))
+ ) {
+ throw new Error("Invalid decoded recording sample count");
+ }
+ stream.sampleCount += Math.round(samples);
+ }
+}
+
+async function readFrameEvidence(
+ stream: ReadableStream<Uint8Array>,
+ streams: Map<number, DecodedStream>,
+): Promise<void> {
+ const decoder = new TextDecoder();
+ let pending = "";
+ for await (const chunk of stream) {
+ pending += decoder.decode(chunk, { stream: true });
+ let newline = pending.indexOf("\n");
+ while (newline !== -1) {
+ if (newline > MAX_OUTPUT_LINE_LENGTH) {
+ throw new Error("Recording decoder output exceeded its limit");
+ }
+ decodeLine(pending.slice(0, newline).trim(), streams);
+ pending = pending.slice(newline + 1);
+ newline = pending.indexOf("\n");
+ }
+ if (pending.length > MAX_OUTPUT_LINE_LENGTH) {
+ throw new Error("Recording decoder output exceeded its limit");
+ }
+ }
+ pending += decoder.decode();
+ decodeLine(pending.trim(), streams);
+}
+
+async function readDecoderErrors(
+ stream: ReadableStream<Uint8Array>,
+ input: string,
+): Promise<string> {
+ const decoder = new TextDecoder();
+ let output = "";
+ let truncated = false;
+ for await (const chunk of stream) {
+ const text = decoder.decode(chunk, { stream: true });
+ truncated ||= output.length + text.length > MAX_STDERR_LENGTH;
+ output += text.slice(0, Math.max(0, MAX_STDERR_LENGTH - output.length));
+ }
+ output += decoder.decode();
+ if (truncated) output = output.slice(0, output.lastIndexOf("\n") + 1);
+ return (
+ output
+ .replaceAll(input, "<recording input>")
+ .replace(/https?:\/\/\S+/g, "<redacted URL>")
+ .trim()
+ .slice(-MAX_ERROR_LENGTH) ||
+ (truncated ? "Decoder error output exceeded its limit" : "")
+ );
+}
+
+function validateEvidence(
+ streams: Map<number, DecodedStream>,
+ options: RecordingVerificationOptions,
+): RecordingVerificationResult {
+ const video = streams.get(0);
+ const audio = streams.get(1);
+ if (video?.kind !== "video" || video.frameCount === 0) {
+ throw new Error("Recording has no decoded video frames");
+ }
+ const videoEvidence = streamEvidence(video);
+ const durationTolerance = Math.max(
+ 0.5,
+ Math.min(5, options.expectedDuration * 0.01),
+ );
+ if (
+ Math.abs(videoEvidence.duration - options.expectedDuration) >
+ durationTolerance
+ ) {
+ throw new Error(
+ "Decoded recording video does not cover its expected duration",
+ );
+ }
+ let audioEvidence: DecodedAudioEvidence | null = null;
+ if (audio?.kind === "audio" && audio.frameCount > 0 && audio.sampleRate) {
+ audioEvidence = {
+ ...streamEvidence(audio),
+ sampleCount: audio.sampleCount,
+ sampleRate: audio.sampleRate,
+ decodedDuration: audio.sampleCount / audio.sampleRate,
+ };
+ }
+ if (options.requireAudio) {
+ const tolerance = Math.min(0.5, videoEvidence.duration * 0.1);
+ if (
+ !audioEvidence ||
+ audioEvidence.startTime > videoEvidence.startTime + tolerance ||
+ audioEvidence.endTime < videoEvidence.endTime - tolerance ||
+ audioEvidence.decodedDuration < videoEvidence.duration - tolerance ||
+ (audio?.maximumGap ?? 0) > tolerance
+ ) {
+ throw new Error("Decoded recording is missing required audio coverage");
+ }
+ }
+ return { fullDecode: true, video: videoEvidence, audio: audioEvidence };
+}
+
+export async function verifyRecording(
+ input: string,
+ options: RecordingVerificationOptions,
+): Promise<RecordingVerificationResult> {
+ return decodeRecording(input, options);
+}
+
+async function decodeRecording(
+ input: string,
+ options: RecordingVerificationOptions,
+ objectIdentity?: string,
+): Promise<RecordingVerificationResult> {
+ const timeoutMs = options.timeoutMs ?? PROCESS_TIMEOUT_MS;
+ if (
+ !positiveNumber(options.expectedDuration) ||
+ !positiveNumber(timeoutMs) ||
+ timeoutMs > PROCESS_TIMEOUT_MS
+ ) {
+ throw new Error("Invalid recording verification budget or duration");
+ }
+ if (options.abortSignal?.aborted) {
+ throw new Error("Recording verification was cancelled");
+ }
+ let remote = false;
+ if (isAbsolute(input)) {
+ const metadata = await lstat(input);
+ if (!metadata.isFile()) {
+ throw new Error("Recording verification requires a regular MP4 file");
+ }
+ } else {
+ const url = new URL(input);
+ if (
+ (url.protocol !== "http:" && url.protocol !== "https:") ||
+ url.username ||
+ url.password
+ ) {
+ throw new Error("Recording verification requires an HTTP(S) MP4 URL");
+ }
+ remote = true;
+ }
+ if (options.abortSignal?.aborted) {
+ throw new Error("Recording verification was cancelled");
+ }
+ const proc = registerSubprocess(
+ spawn({
+ cmd: [
+ "ffmpeg",
+ "-hide_banner",
+ "-nostdin",
+ "-v",
+ "error",
+ "-xerror",
+ "-err_detect",
+ "explode+crccheck",
+ "-filter_threads",
+ "1",
+ "-filter_complex_threads",
+ "1",
+ "-threads",
+ "1",
+ "-protocol_whitelist",
+ remote ? "http,https,tcp,tls" : "file",
+ "-f",
+ "mov",
+ ...(objectIdentity
+ ? [
+ "-headers",
+ `If-Match: ${objectIdentity}\r\nX-Cap-Recording-Verification: 1\r\n`,
+ ]
+ : []),
+ "-i",
+ input,
+ "-map",
+ "0:v:0",
+ "-map",
+ "0:a:0?",
+ "-fps_mode",
+ "passthrough",
+ "-enc_time_base:v",
+ "-1",
+ "-c:v",
+ "rawvideo",
+ "-c:a",
+ "pcm_s16le",
+ "-threads",
+ "1",
+ "-f",
+ "framehash",
+ "-hash",
+ "adler32",
+ "-",
+ ],
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ }),
+ );
+ let failure: Error | undefined;
+ const stop = () => {
+ if (proc.exitCode === null) {
+ try {
+ proc.kill("SIGKILL");
+ } catch {
+ failure ??= new Error("Recording decoder termination failed");
+ }
+ }
+ };
+ const cancel = () => {
+ failure ??= new Error("Recording verification was cancelled");
+ stop();
+ };
+ options.abortSignal?.addEventListener("abort", cancel, { once: true });
+ const timeout = setTimeout(() => {
+ failure ??= new RecordingVerificationError(
+ "Recording verification timed out",
+ true,
+ );
+ stop();
+ }, timeoutMs);
+ const streams = new Map<number, DecodedStream>();
+ const frames = readFrameEvidence(proc.stdout, streams);
+ const errors = readDecoderErrors(proc.stderr, input);
+ let result: RecordingVerificationResult;
+ try {
+ if (options.abortSignal?.aborted) cancel();
+ const [, stderr, exitCode] = await Promise.all([
+ frames,
+ errors,
+ proc.exited,
+ ]);
+ if (failure) throw failure;
+ if (exitCode !== 0 || stderr || proc.signalCode) {
+ throw new RecordingVerificationError(
+ `Recording full decode failed: ${stderr || exitCode}`,
+ /HTTP error (?:408|429|5\d\d)\b|Server returned (?:408|429|5\d\d|5XX)\b|Connection reset by peer|Connection timed out|Connection refused|Network is unreachable|Temporary failure in name resolution/i.test(
+ stderr,
+ ),
+ );
+ }
+ result = validateEvidence(streams, options);
+ } finally {
+ clearTimeout(timeout);
+ options.abortSignal?.removeEventListener("abort", cancel);
+ stop();
+ await proc.exited;
+ await Promise.allSettled([frames, errors]);
+ unregisterSubprocess(proc);
+ }
+ if (failure) throw failure;
+ if (options.abortSignal?.aborted) {
+ throw new Error("Recording verification was cancelled");
+ }
+ return result;
+}
+
+function isStrongObjectIdentity(value: string | null): value is string {
+ return (
+ value !== null &&
+ value.length <= 1_024 &&
+ /^"[\x21\x23-\x7E\x80-\xFF]+"$/.test(value)
+ );
+}
+
+async function readRemoteIdentity(
+ input: string,
+ abortSignal: AbortSignal,
+ expectedObjectIdentity?: string,
+): Promise<{ objectIdentity: string; fileSize: number }> {
+ const headers: Record<string, string> = {
+ Range: "bytes=0-0",
+ "X-Cap-Recording-Verification": "1",
+ };
+ if (expectedObjectIdentity) headers["If-Match"] = expectedObjectIdentity;
+ let response: Response;
+ try {
+ response = await fetch(input, { headers, signal: abortSignal });
+ } catch {
+ throw new RecordingVerificationError(
+ "Recording object identity could not be read",
+ true,
+ );
+ }
+ try {
+ if (response.status === 412) {
+ throw new Error("Recording object changed during verification");
+ }
+ if (response.status !== 200 && response.status !== 206) {
+ throw new RecordingVerificationError(
+ `Recording object identity read failed: ${response.status}`,
+ response.status === 408 ||
+ response.status === 429 ||
+ response.status >= 500,
+ );
+ }
+ const objectIdentity = response.headers.get("etag");
+ if (!isStrongObjectIdentity(objectIdentity)) {
+ throw new Error(
+ "Recording storage does not expose a strong object identity",
+ );
+ }
+ if (expectedObjectIdentity && expectedObjectIdentity !== objectIdentity) {
+ throw new Error("Recording object changed during verification");
+ }
+ const range = response.headers.get("content-range");
+ const length =
+ response.status === 206
+ ? range?.match(/^bytes 0-0\/(\d+)$/)?.[1]
+ : response.headers.get("content-length");
+ const fileSize = Number(length);
+ if (!Number.isSafeInteger(fileSize) || fileSize <= 0) {
+ throw new Error(
+ "Recording storage does not expose the complete object size",
+ );
+ }
+ return { objectIdentity, fileSize };
+ } finally {
+ await response.body?.cancel();
+ }
+}
+
+export async function verifyRemoteRecording(
+ input: string,
+ options: RemoteRecordingVerificationOptions,
+): Promise<RemoteRecordingVerificationResult> {
+ const timeoutMs = options.timeoutMs ?? PROCESS_TIMEOUT_MS;
+ if (
+ !Number.isSafeInteger(timeoutMs) ||
+ timeoutMs <= 0 ||
+ timeoutMs > PROCESS_TIMEOUT_MS ||
+ !positiveNumber(options.expectedDuration)
+ ) {
+ throw new Error("Invalid recording verification budget or duration");
+ }
+ const url = new URL(input);
+ if (
+ (url.protocol !== "http:" && url.protocol !== "https:") ||
+ url.username ||
+ url.password
+ ) {
+ throw new Error(
+ "Remote recording verification requires an HTTP(S) MP4 URL",
+ );
+ }
+ if (
+ options.expectedObjectIdentity !== undefined &&
+ !isStrongObjectIdentity(options.expectedObjectIdentity)
+ ) {
+ throw new Error(
+ "Recording storage does not expose a strong object identity",
+ );
+ }
+ const deadline = new AbortController();
+ const startedAt = performance.now();
+ const timeout = setTimeout(() => deadline.abort(), timeoutMs);
+ const signal = options.abortSignal
+ ? AbortSignal.any([deadline.signal, options.abortSignal])
+ : deadline.signal;
+ try {
+ if (signal.aborted) throw new Error("Recording verification was cancelled");
+ const before = await readRemoteIdentity(
+ input,
+ signal,
+ options.expectedObjectIdentity,
+ );
+ const remainingMs = timeoutMs - (performance.now() - startedAt);
+ if (remainingMs <= 0) {
+ throw new RecordingVerificationError(
+ "Recording verification timed out",
+ true,
+ );
+ }
+ const evidence = await decodeRecording(
+ input,
+ { ...options, abortSignal: signal, timeoutMs: remainingMs },
+ before.objectIdentity,
+ );
+ const after = await readRemoteIdentity(
+ input,
+ signal,
+ before.objectIdentity,
+ );
+ if (before.fileSize !== after.fileSize) {
+ throw new Error("Recording object changed during verification");
+ }
+ if (signal.aborted) throw new Error("Recording verification was cancelled");
+ return { ...evidence, ...after };
+ } catch (error) {
+ if (options.abortSignal?.aborted) {
+ throw new Error("Recording verification was cancelled");
+ }
+ if (deadline.signal.aborted) {
+ throw new RecordingVerificationError(
+ "Recording verification timed out",
+ true,
+ );
+ }
+ throw error;
+ } finally {
+ clearTimeout(timeout);
+ }
+}
diff --git a/apps/media-server/src/routes/video.ts b/apps/media-server/src/routes/video.ts
index 5185d6caa..b81bddab7 100644
--- a/apps/media-server/src/routes/video.ts
+++ b/apps/media-server/src/routes/video.ts
@@ -4,6 +4,7 @@ import { z } from "zod";
import { validateMediaServerSecret } from "../lib/auth";
import type { VideoMetadata } from "../lib/job-manager";
import {
+ beginRecordingVerification,
canAcceptNewVideoProcess,
createJob,
deleteJob,
@@ -20,6 +21,7 @@ import {
touchJob,
updateJob,
} from "../lib/job-manager";
+import { PROCESS_TIMEOUT_MS } from "../lib/media-common";
import { renderEditedVideo } from "../lib/media-edit";
import {
canAcceptNewProbeOperation as canAcceptNewProbeProcess,
@@ -43,6 +45,10 @@ import {
uploadFileToStorage,
uploadToS3,
} from "../lib/media-video";
+import {
+ isRetryableRecordingVerificationError,
+ verifyRemoteRecording,
+} from "../lib/recording-verification";
import type { TempFileHandle } from "../lib/temp-files";
import { cleanupStaleTempFiles } from "../lib/temp-files";
import {
@@ -54,6 +60,9 @@ import {
const video = new Hono();
const PROCESSING_HEARTBEAT_MS = 60 * 1000;
+const POST_VERIFICATION_ASSET_BUDGET_MS = 5 * 60 * 1000;
+const RECORDING_VERIFICATION_RETRY_ERROR =
+ "Recording verification temporarily unavailable (503)";
const MEDIA_ENGINE_ERROR_CODE = ["FF", "MPEG_ERROR"].join("");
const PROBE_ERROR_CODE = ["FF", "PROBE_ERROR"].join("");
const VIDEO_BUSY_RETRY_AFTER_SECONDS = 15;
@@ -1558,8 +1567,130 @@ const muxSegmentsOutputUploadSchema = z.discriminatedUnion("type", [
}),
]);
+const recordingVerificationSchema = z.object({
+ videoId: z.string(),
+ userId: z.string(),
+ videoUrl: z.string().url(),
+ fileSize: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
+ duration: z.number().finite().positive(),
+ requiredAudio: z.boolean(),
+ objectIdentity: z.string().min(1),
+ webhookUrl: z.string().url(),
+ webhookSecret: z.string().optional(),
+});
+
+video.post("/verify-recording", async (c) => {
+ if (!validateMediaServerSecret(c))
+ return c.json({ error: "Unauthorized" }, 401);
+ const parsed = recordingVerificationSchema.safeParse(await c.req.json());
+ if (!parsed.success)
+ return c.json({ error: "Invalid verification request" }, 400);
+ if (!canAcceptNewVideoProcess()) {
+ c.header("Retry-After", VIDEO_BUSY_RETRY_AFTER_SECONDS.toString());
+ return c.json(getMuxBusyResponseBody(getVideoCapacitySnapshot()), 503);
+ }
+ const body = parsed.data;
+ const jobId = generateJobId();
+ createJob(
+ jobId,
+ body.videoId,
+ body.userId,
+ body.webhookUrl,
+ body.webhookSecret,
+ );
+ void verifyUploadedRecordingAsync(jobId, body);
+ return c.json({ jobId });
+});
+
+async function verifyUploadedRecordingAsync(
+ jobId: string,
+ body: z.infer<typeof recordingVerificationSchema>,
+) {
+ const abortController = new AbortController();
+ updateJob(jobId, { abortController, phase: "processing", progress: 0 });
+ try {
+ const metadata = await probeVideo(body.videoUrl).catch(() => {
+ throw new Error(RECORDING_VERIFICATION_RETRY_ERROR);
+ });
+ if (
+ metadata.fileSize !== body.fileSize ||
+ !isDurationClose(metadata.duration, body.duration) ||
+ (body.requiredAudio && !metadata.audioCodec)
+ ) {
+ throw new Error(
+ "Uploaded recording does not match the completed local file",
+ );
+ }
+ if (
+ !beginRecordingVerification(
+ jobId,
+ PROCESS_TIMEOUT_MS + POST_VERIFICATION_ASSET_BUDGET_MS,
+ )
+ )
+ throw new Error("Recording verification job is no longer active");
+ const verified = await withJobHeartbeat(jobId, () =>
+ withMuxMemoryGuard(abortController, () =>
+ verifyRemoteRecording(body.videoUrl, {
+ expectedDuration: body.duration,
+ requireAudio: body.requiredAudio,
+ expectedObjectIdentity: body.objectIdentity,
+ abortSignal: abortController.signal,
+ }),
+ ),
+ );
+ if (verified.fileSize !== body.fileSize)
+ throw new Error("Verified recording size does not match the local file");
+ updateJob(jobId, {
+ phase: "complete",
+ progress: 100,
+ metadata: {
+ ...metadata,
+ duration: verified.video.duration,
+ audioCodec: verified.audio ? (metadata.audioCodec ?? "unknown") : null,
+ fileSize: verified.fileSize,
+ },
+ recordingVerification: {
+ request: {
+ version: 1,
+ artifact: {
+ kind: "mp4",
+ fileSize: body.fileSize,
+ duration: body.duration,
+ objectIdentity: body.objectIdentity,
+ },
+ requiredAudio: body.requiredAudio,
+ },
+ fullDecode: true,
+ objectIdentity: verified.objectIdentity,
+ },
+ });
+ } catch (error) {
+ const retryable =
+ isRetryableRecordingVerificationError(error) ||
+ (error instanceof Error &&
+ (error.message === VIDEO_MEMORY_PRESSURE_ERROR ||
+ error.message === RECORDING_VERIFICATION_RETRY_ERROR));
+ updateJob(jobId, {
+ phase:
+ !retryable && abortController.signal.aborted ? "cancelled" : "error",
+ error: retryable
+ ? RECORDING_VERIFICATION_RETRY_ERROR
+ : "Uploaded recording content could not be verified; retain the local recording",
+ });
+ }
+ const job = getJob(jobId);
+ if (job) await sendWebhook(job);
+ setTimeout(() => deleteJob(jobId), 5 * 60 * 1000);
+}
+
const muxSegmentsSchema = z
.object({
+ manifestSha256: z
+ .string()
+ .regex(/^[a-f0-9]{64}$/)
+ .optional(),
+ expectedDuration: z.number().finite().positive().optional(),
+ outputVerificationUrl: z.string().url().optional(),
videoId: z.string(),
userId: z.string(),
outputPresignedUrl: z.string().url().optional(),
@@ -1625,6 +1756,7 @@ video.post("/mux-segments", async (c) => {
audioSegmentUrls: audioSegUrls,
} = body.data;
const outputUpload = getMuxSegmentsOutputUpload(body.data);
+ updateJob(jobId, { manifestSha256: body.data.manifestSha256 });
muxSegmentsAsync(
jobId,
@@ -1636,6 +1768,8 @@ video.post("/mux-segments", async (c) => {
videoSegUrls,
audioInitUrl ?? null,
audioSegUrls ?? null,
+ body.data.expectedDuration,
+ body.data.outputVerificationUrl,
).catch((err) => {
console.error(`[mux-segments] Async mux error for job ${jobId}:`, err);
const currentJob = getJob(jobId);
@@ -1896,6 +2030,8 @@ async function muxSegmentsAsync(
videoSegmentUrls: string[],
audioInitUrl: string | null,
audioSegmentUrls: string[] | null,
+ expectedDuration?: number,
+ outputVerificationUrl?: string,
): Promise<void> {
const { ensureTempDir } = await import("../lib/temp-files");
const { mkdir, rm } = await import("node:fs/promises");
@@ -2016,17 +2152,78 @@ async function muxSegmentsAsync(
resources: getSystemResources(),
});
+ let metadata = await probeVideoFile(resultPath);
+ if (
+ !Number.isFinite(metadata.duration) ||
+ metadata.duration <= 0 ||
+ metadata.fileSize !== file(resultPath).size ||
+ metadata.fileSize <= 0 ||
+ metadata.width <= 0 ||
+ metadata.height <= 0 ||
+ !metadata.videoCodec ||
+ (audioInput && !metadata.audioCodec) ||
+ (expectedDuration !== undefined &&
+ !isDurationClose(metadata.duration, expectedDuration))
+ ) {
+ throw new Error(
+ "Muxed recording is incomplete or missing a required track",
+ );
+ }
+
updateJob(jobId, { phase: "uploading", progress: 80 });
sendCurrentJobWebhook(jobId);
outputUploadStarted = true;
- await uploadFileToStorage(resultPath, outputUpload, "video/mp4");
-
- let metadata: VideoMetadata | undefined;
- try {
- const probeResult = await probeVideoFile(resultPath);
- metadata = probeResult;
- } catch {}
+ const uploadReceipt = await uploadFileToStorage(
+ resultPath,
+ outputUpload,
+ "video/mp4",
+ );
+ if (outputVerificationUrl) {
+ if (!uploadReceipt.objectIdentity)
+ throw new Error("Recording upload did not return an object identity");
+ if (
+ !beginRecordingVerification(
+ jobId,
+ PROCESS_TIMEOUT_MS + POST_VERIFICATION_ASSET_BUDGET_MS,
+ )
+ )
+ throw new Error("Recording verification job is no longer active");
+ const verified = await withJobHeartbeat(jobId, () =>
+ withMuxMemoryGuard(abortController, () =>
+ verifyRemoteRecording(outputVerificationUrl, {
+ expectedDuration: expectedDuration ?? metadata.duration,
+ requireAudio: Boolean(audioInput),
+ expectedObjectIdentity: uploadReceipt.objectIdentity,
+ abortSignal: abortController.signal,
+ }),
+ ),
+ );
+ if (verified.fileSize !== metadata.fileSize)
+ throw new Error(
+ "Uploaded recording size does not match the muxed file",
+ );
+ metadata = {
+ ...metadata,
+ duration: verified.video.duration,
+ audioCodec: verified.audio ? (metadata.audioCodec ?? "unknown") : null,
+ fileSize: verified.fileSize,
+ };
+ const manifestSha256 = getJob(jobId)?.manifestSha256;
+ if (manifestSha256) {
+ updateJob(jobId, {
+ recordingVerification: {
+ request: {
+ version: 1,
+ artifact: { kind: "segments", manifestSha256 },
+ requiredAudio: Boolean(audioInput),
+ },
+ fullDecode: true,
+ objectIdentity: verified.objectIdentity,
+ },
+ });
+ }
+ }
if (thumbnailPresignedUrl || previewGifPresignedUrl) {
updateJob(jobId, {
@@ -2092,7 +2289,11 @@ async function muxSegmentsAsync(
console.error(`Mux-segments job ${jobId} failed:`, error);
updateJob(jobId, {
phase: "error",
- error: error instanceof Error ? error.message : "Unknown error",
+ error: isRetryableRecordingVerificationError(error)
+ ? "Recording verification temporarily unavailable (503)"
+ : error instanceof Error
+ ? error.message
+ : "Unknown error",
});
sendCurrentJobWebhook(jobId);
} finally {