Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: verify recording media against preserved source

Richie McIlroya3c68b26a938
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 9bed6f602..39e7f580f 100644
--- a/apps/media-server/src/__tests__/lib/job-manager.test.ts
+++ b/apps/media-server/src/__tests__/lib/job-manager.test.ts
@@ -1,11 +1,14 @@
import { afterEach, describe, expect, test } from "bun:test";
import {
+ beginRecordingProcessing,
beginRecordingVerification,
cleanupExpiredJobs,
createJob,
deleteJob,
getJob,
+ sendWebhook,
touchJob,
+ updateJob,
} from "../../lib/job-manager";
const createdJobs: string[] = [];
@@ -22,6 +25,108 @@ afterEach(() => {
});
describe("job cleanup", () => {
+ test("budgets the complete recording pipeline from execution without extending its deadline", () => {
+ const job = createTrackedJob("job-complete-recording-budget");
+ job.createdAt = Date.now() - 55 * 60 * 1000;
+ job.abortController = new AbortController();
+ const startedAt = Date.now();
+ expect(beginRecordingProcessing(job.jobId, 170 * 60 * 1000)).toBe(true);
+ expect(job.recordingProcessingDeadlineAt).toBeGreaterThanOrEqual(
+ startedAt + 170 * 60 * 1000,
+ );
+ job.phase = "processing";
+ job.createdAt -= 80 * 60 * 1000;
+ expect(cleanupExpiredJobs()).toBe(0);
+ const deadline = job.recordingProcessingDeadlineAt;
+ expect(beginRecordingProcessing(job.jobId, 170 * 60 * 1000)).toBe(false);
+ expect(job.recordingProcessingDeadlineAt).toBe(deadline);
+ job.recordingProcessingDeadlineAt = Date.now() + 15 * 60 * 1000;
+ expect(beginRecordingVerification(job.jobId, 50 * 60 * 1000)).toBe(true);
+ expect(job.recordingVerificationDeadlineAt).toBe(
+ job.recordingProcessingDeadlineAt,
+ );
+ job.recordingVerificationDeadlineAt = Date.now() - 1;
+ touchJob(job.jobId);
+ expect(cleanupExpiredJobs()).toBe(1);
+ expect(job.error).toBe("Recording verification timed out");
+ expect(job.abortController.signal.aborted).toBe(true);
+ });
+
+ test("bounds queued, cancelled, stale, and oversized recording processing budgets", () => {
+ const queued = createTrackedJob("job-recording-queue-expired");
+ queued.createdAt = Date.now() - 61 * 60 * 1000;
+ expect(beginRecordingProcessing(queued.jobId, 170 * 60 * 1000)).toBe(false);
+ const cancelled = createTrackedJob("job-recording-aborted");
+ cancelled.abortController = new AbortController();
+ cancelled.abortController.abort();
+ expect(beginRecordingProcessing(cancelled.jobId, 170 * 60 * 1000)).toBe(
+ false,
+ );
+ const stale = createTrackedJob("job-recording-stale");
+ stale.abortController = new AbortController();
+ expect(beginRecordingProcessing(stale.jobId, 181 * 60 * 1000)).toBe(false);
+ expect(beginRecordingProcessing(stale.jobId, 170 * 60 * 1000)).toBe(true);
+ stale.phase = "processing";
+ stale.updatedAt = Date.now() - 16 * 60 * 1000;
+ cleanupExpiredJobs();
+ expect(getJob(stale.jobId)?.phase).toBe("error");
+ expect(stale.error).toContain("Job stale");
+ expect(stale.abortController.signal.aborted).toBe(true);
+ });
+
+ test("retains and redelivers unacknowledged terminal proof with its generation fence", async () => {
+ const job = createTrackedJob("job-terminal-retry");
+ job.webhookUrl = "https://webhook.example.test/progress";
+ updateJob(job.jobId, {
+ generation: "generation-a",
+ attemptId: "attempt-a",
+ phase: "complete",
+ progress: 100,
+ });
+ const originalFetch = globalThis.fetch;
+ let available = false;
+ const payloads: Record<string, unknown>[] = [];
+ globalThis.fetch = (async (_input, init) => {
+ payloads.push(JSON.parse(String(init?.body)));
+ return new Response(null, { status: available ? 200 : 503 });
+ }) as typeof fetch;
+ try {
+ await sendWebhook(job);
+ expect(job.terminalWebhookAcknowledgedAt).toBeUndefined();
+ job.terminalAt = Date.now() - 2 * 60 * 60 * 1000;
+ job.updatedAt = job.terminalAt;
+ job.webhookLastAttemptAt = Date.now() - 61_000;
+ available = true;
+ expect(cleanupExpiredJobs()).toBe(0);
+ expect(getJob(job.jobId)).toBe(job);
+ await Bun.sleep(10);
+ expect(job.terminalWebhookAcknowledgedAt).toBeNumber();
+ expect(payloads.at(-1)).toMatchObject({
+ generation: "generation-a",
+ attemptId: "attempt-a",
+ phase: "complete",
+ });
+ expect(cleanupExpiredJobs()).toBe(1);
+ expect(getJob(job.jobId)).toBeUndefined();
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
+ test("bounds unacknowledged terminal retention and retains expired active jobs for delivery", () => {
+ const terminal = createTrackedJob("job-terminal-expired");
+ terminal.phase = "complete";
+ terminal.webhookUrl = "https://webhook.example.test/progress";
+ terminal.terminalAt = Date.now() - 25 * 60 * 60 * 1000;
+ expect(cleanupExpiredJobs()).toBe(1);
+ expect(getJob(terminal.jobId)).toBeUndefined();
+ const active = createTrackedJob("job-active-expired");
+ active.phase = "processing";
+ active.updatedAt = Date.now() - 61 * 60 * 1000;
+ expect(cleanupExpiredJobs()).toBe(1);
+ expect(getJob(active.jobId)?.phase).toBe("error");
+ });
+
test("gives verification a separate finite budget after a long mux", () => {
const job = createTrackedJob("job-verification-budget");
job.phase = "uploading";
diff --git a/apps/media-server/src/__tests__/lib/media-routes-real-world.integration.test.ts b/apps/media-server/src/__tests__/lib/media-routes-real-world.integration.test.ts
index 38e0291cd..3ef990c45 100644
--- a/apps/media-server/src/__tests__/lib/media-routes-real-world.integration.test.ts
+++ b/apps/media-server/src/__tests__/lib/media-routes-real-world.integration.test.ts
@@ -5,16 +5,22 @@ import {
describe,
expect,
mock,
+ spyOn,
test,
} from "bun:test";
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
import { mkdtempSync, rmSync } from "node:fs";
-import { writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
+import { readFile, writeFile } from "node:fs/promises";
+import os, { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import type appType from "../../app";
+import * as containerCpu from "../../lib/container-cpu";
+import * as containerMemory from "../../lib/container-memory";
import type { Job } from "../../lib/job-manager";
import { probeVideoFile } from "../../lib/media-probe";
+import * as recordingVerification from "../../lib/recording-verification";
const FIXTURES_DIR = join(import.meta.dir, "..", "fixtures");
const TEST_VIDEO_WITH_AUDIO = join(FIXTURES_DIR, "test-with-audio.mp4");
@@ -33,6 +39,17 @@ let baseUrl = "";
let tempDir = "";
const uploadedArtifacts = new Map<string, Uint8Array>();
+const recordingSources = new Map<string, Uint8Array>();
+const sourceReads: {
+ path: string;
+ ifMatch: string | null;
+ verification: string | null;
+}[] = [];
+const uploadConditions: (string | null)[] = [];
+const multipartCallbacks: { action: string; payload: unknown }[] = [];
+let rejectMultipartSigning = false;
+let sourceFault: "changed" | "missing" | "corrupt" | undefined;
+let corruptRecordingReadback = false;
let transientFixtureFailures = 0;
let permanentFixtureFailures = 0;
let slowFixtureCancellations = 0;
@@ -49,6 +66,39 @@ function uploadUrl(name: string) {
return `${baseUrl}/uploads/${name}`;
}
+function objectIdentity(bytes: Uint8Array): string {
+ return `"${createHash("sha256").update(bytes).digest("hex")}"`;
+}
+
+function fencedMuxRequest(name: string) {
+ return {
+ videoId: name,
+ userId: "fenced-user",
+ generation: "fenced-generation",
+ attemptId: `attempt-${name}`,
+ manifestSha256: "a".repeat(64),
+ inventorySha256: "b".repeat(64),
+ outputKey: `recording-generations/${name}/result.mp4`,
+ outputUpload: {
+ type: "put",
+ url: uploadUrl(`${name}.mp4`),
+ ifNoneMatch: "*",
+ },
+ outputVerificationUrl: uploadUrl(`${name}.mp4`),
+ videoInitUrl: `${baseUrl}/recording-sources/video-init.mp4`,
+ videoSegmentUrls: [`${baseUrl}/recording-sources/video-segment.m4s`],
+ audioInitUrl: `${baseUrl}/recording-sources/audio-init.mp4`,
+ audioSegmentUrls: [`${baseUrl}/recording-sources/audio-segment.m4s`],
+ requiredAudio: true,
+ expectedDuration: 0.1,
+ sourceObjects: [...recordingSources].map(([path, bytes]) => ({
+ url: `${baseUrl}${path}`,
+ objectIdentity: objectIdentity(bytes),
+ size: bytes.byteLength,
+ })),
+ };
+}
+
function mediaPostRequest(path: string, body: unknown): Request {
return new Request(`http://localhost${path}`, {
method: "POST",
@@ -57,6 +107,26 @@ function mediaPostRequest(path: string, body: unknown): Request {
});
}
+function multipartMuxRequest(name: string) {
+ const body = fencedMuxRequest(name);
+ return {
+ ...body,
+ outputUpload: {
+ type: "multipart",
+ videoId: body.videoId,
+ generation: body.generation,
+ attemptId: body.attemptId,
+ key: body.outputKey,
+ uploadId: `upload-${name}`,
+ partSize: 5 * 1024 * 1024,
+ signPartUrl: `${baseUrl}/multipart/${name}/sign-part`,
+ completeUrl: `${baseUrl}/multipart/${name}/complete`,
+ abortUrl: `${baseUrl}/multipart/${name}/abort`,
+ webhookSecret: MEDIA_SERVER_SECRET,
+ },
+ };
+}
+
async function responseBytes(response: Response) {
return new Uint8Array(await response.arrayBuffer());
}
@@ -133,12 +203,100 @@ beforeAll(async () => {
getJob = jobManager.getJob;
deleteJob = jobManager.deleteJob;
tempDir = mkdtempSync(join(tmpdir(), "cap-real-world-routes-"));
+ for (const kind of ["video", "audio"] as const) {
+ const path = join(tempDir, `${kind}-fragmented.mp4`);
+ execFileSync("ffmpeg", [
+ "-v",
+ "error",
+ "-i",
+ TEST_VIDEO_WITH_AUDIO,
+ "-map",
+ kind === "video" ? "0:v:0" : "0:a:0",
+ "-c",
+ "copy",
+ "-movflags",
+ "+empty_moov+frag_keyframe+default_base_moof",
+ path,
+ ]);
+ const bytes = new Uint8Array(await Bun.file(path).arrayBuffer());
+ const view = new DataView(bytes.buffer);
+ let split = 0;
+ while (
+ split + 8 <= bytes.byteLength &&
+ new TextDecoder().decode(bytes.subarray(split + 4, split + 8)) !== "moof"
+ ) {
+ const size = view.getUint32(split);
+ if (size < 8) throw new Error("Invalid fragmented test fixture");
+ split += size;
+ }
+ if (split + 8 > bytes.byteLength)
+ throw new Error("Missing fragmented test fixture media");
+ recordingSources.set(
+ `/recording-sources/${kind}-init.mp4`,
+ bytes.slice(0, split),
+ );
+ recordingSources.set(
+ `/recording-sources/${kind}-segment.m4s`,
+ bytes.slice(split),
+ );
+ }
server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
async fetch(request) {
const url = new URL(request.url);
+ if (request.method === "POST" && url.pathname === "/ignored-webhook")
+ return new Response(null, { status: 200 });
+ if (request.method === "POST" && url.pathname.startsWith("/multipart/")) {
+ const [, , name, action] = url.pathname.split("/");
+ const payload: unknown = await request.json();
+ multipartCallbacks.push({ action, payload });
+ if (
+ request.headers.get("x-media-server-secret") !== MEDIA_SERVER_SECRET
+ )
+ return new Response(null, { status: 401 });
+ if (action === "sign-part")
+ return rejectMultipartSigning
+ ? new Response(null, { status: 403 })
+ : Response.json({ url: uploadUrl(`${name}.part`) });
+ if (action === "complete") {
+ const bytes = uploadedBytes(`/uploads/${name}.part`);
+ uploadedArtifacts.set(`/uploads/${name}.mp4`, bytes);
+ return Response.json({ objectIdentity: objectIdentity(bytes) });
+ }
+ if (action === "abort") return Response.json({ success: true });
+ }
+ const source = recordingSources.get(url.pathname);
+ if (source && request.method === "GET") {
+ sourceReads.push({
+ path: url.pathname,
+ ifMatch: request.headers.get("if-match"),
+ verification: request.headers.get("x-cap-recording-verification"),
+ });
+ const affected = url.pathname.endsWith("video-segment.m4s");
+ if (affected && sourceFault === "missing")
+ return new Response(null, { status: 404 });
+ if (
+ request.headers.get("if-match") !== objectIdentity(source) ||
+ request.headers.get("x-cap-recording-verification") !== "1" ||
+ (affected && sourceFault === "changed")
+ )
+ return new Response(null, { status: 412 });
+ return new Response(
+ Uint8Array.from(
+ affected && sourceFault === "corrupt"
+ ? new Uint8Array(source.byteLength)
+ : source,
+ ).buffer,
+ {
+ headers: {
+ ETag: objectIdentity(source),
+ "Content-Length": String(source.byteLength),
+ },
+ },
+ );
+ }
if (request.method === "GET" || request.method === "HEAD") {
if (url.pathname === "/fixtures/permanent-unavailable.m4s") {
@@ -195,13 +353,36 @@ beforeAll(async () => {
const headers = {
"Content-Type": "video/mp4",
"Content-Length": bytes.byteLength.toString(),
+ ETag: objectIdentity(bytes),
};
+ if (
+ request.headers.has("if-match") &&
+ request.headers.get("if-match") !== headers.ETag
+ )
+ return new Response(null, { status: 412 });
+ if (request.headers.get("range") === "bytes=0-0")
+ return new Response(Uint8Array.from(bytes.subarray(0, 1)).buffer, {
+ status: 206,
+ headers: {
+ ...headers,
+ "Content-Length": "1",
+ "Content-Range": `bytes 0-0/${bytes.byteLength}`,
+ },
+ });
+ if (corruptRecordingReadback)
+ return new Response(new Uint8Array(bytes.byteLength), { headers });
return request.method === "HEAD"
? new Response(null, { headers })
: new Response(Uint8Array.from(bytes).buffer, { headers });
}
if (request.method === "PUT" && url.pathname.startsWith("/uploads/")) {
+ uploadConditions.push(request.headers.get("if-none-match"));
+ if (
+ request.headers.get("if-none-match") === "*" &&
+ uploadedArtifacts.has(url.pathname)
+ )
+ return new Response(null, { status: 412 });
if (url.pathname === "/uploads/stale-edit-output.mp4") {
uploadedArtifacts.set(
url.pathname,
@@ -213,7 +394,11 @@ beforeAll(async () => {
new Uint8Array(await request.arrayBuffer()),
);
}
- return new Response(null, { status: 200, statusText: "OK" });
+ return new Response(null, {
+ status: 200,
+ statusText: "OK",
+ headers: { ETag: objectIdentity(uploadedBytes(url.pathname)) },
+ });
}
return new Response("Not found", { status: 404 });
@@ -224,13 +409,28 @@ beforeAll(async () => {
beforeEach(() => {
mock.restore();
+ spyOn(os, "loadavg").mockReturnValue([0, 0, 0]);
+ spyOn(containerCpu, "getContainerCpuLimit").mockReturnValue(4);
+ spyOn(containerCpu, "getContainerCpuUsageMicros").mockReturnValue(0);
+ spyOn(containerMemory, "getContainerMemoryMetrics").mockReturnValue({
+ usageMB: 256,
+ limitMB: 4096,
+ pressure: 0.0625,
+ });
uploadedArtifacts.clear();
transientFixtureFailures = 0;
permanentFixtureFailures = 0;
slowFixtureCancellations = 0;
+ sourceReads.length = 0;
+ uploadConditions.length = 0;
+ multipartCallbacks.length = 0;
+ rejectMultipartSigning = false;
+ sourceFault = undefined;
+ corruptRecordingReadback = false;
});
afterAll(() => {
+ mock.restore();
server?.stop(true);
if (tempDir) {
rmSync(tempDir, { recursive: true, force: true });
@@ -238,6 +438,346 @@ afterAll(() => {
});
describe("media routes real-world integration tests", () => {
+ test("cancels segmented work at its total deadline without waiting for job cleanup", async () => {
+ const originalSetTimeout = globalThis.setTimeout;
+ const shortenedDeadline = new Proxy(originalSetTimeout, {
+ apply(target, receiver: unknown, parameters: unknown[]) {
+ const adjusted = [...parameters];
+ if (adjusted[1] === 170 * 60 * 1000) adjusted[1] = 1;
+ return Reflect.apply(target, receiver, adjusted);
+ },
+ });
+ const timer = spyOn(globalThis, "setTimeout").mockImplementation(
+ shortenedDeadline,
+ );
+ let jobId: string | undefined;
+ try {
+ const response = await app.fetch(
+ mediaPostRequest("/video/mux-segments", fencedMuxRequest("deadline")),
+ );
+ expect(response.status).toBe(200);
+ jobId = ((await response.json()) as { jobId: string }).jobId;
+ const job = await waitForTerminalJob(jobId);
+ expect(job.phase).toBe("cancelled");
+ expect(job.errorCode).toBe("processing-unavailable");
+ expect(job.abortController?.signal.aborted).toBe(true);
+ expect(job.recordingVerification).toBeUndefined();
+ expect(uploadConditions).toHaveLength(0);
+ } finally {
+ timer.mockRestore();
+ if (jobId) deleteJob(jobId);
+ }
+ });
+
+ test("verifies a fenced legacy MP4 snapshot without trusting an invented duration", async () => {
+ const decode = spyOn(recordingVerification, "verifyRemoteRecording");
+ const bytesOnly = spyOn(
+ recordingVerification,
+ "verifyRemoteRecordingBytes",
+ );
+ const bytes = new Uint8Array(
+ await Bun.file(TEST_VIDEO_WITH_AUDIO).arrayBuffer(),
+ );
+ uploadedArtifacts.set("/uploads/mp4-snapshot.mp4", bytes);
+ const response = await app.fetch(
+ mediaPostRequest("/video/verify-recording", {
+ videoId: "legacy-mp4-snapshot",
+ userId: "legacy-user",
+ generation: "mp4-generation",
+ inventorySha256: "c".repeat(64),
+ attemptId: "mp4-attempt",
+ videoUrl: uploadUrl("mp4-snapshot.mp4"),
+ fileSize: bytes.byteLength,
+ requiredAudio: true,
+ objectIdentity: '"original-source"',
+ originalObjectIdentity: '"original-source"',
+ sourceObjectIdentity: objectIdentity(bytes),
+ outputKey: "recording-generations/mp4-generation/source.mp4",
+ webhookUrl: `${baseUrl}/ignored-webhook`,
+ }),
+ );
+ expect(response.status).toBe(200);
+ const { jobId } = (await response.json()) as { jobId: string };
+ try {
+ const job = await waitForTerminalJob(jobId);
+ expect(job.phase).toBe("complete");
+ expect(job.recordingVerification).toMatchObject({
+ request: {
+ artifact: {
+ kind: "mp4",
+ duration: 1,
+ objectIdentity: '"original-source"',
+ },
+ },
+ objectIdentity: objectIdentity(bytes),
+ outputSha256: createHash("sha256").update(bytes).digest("hex"),
+ });
+ expect(uploadConditions).toHaveLength(0);
+ expect(decode).toHaveBeenCalledTimes(1);
+ expect(bytesOnly).not.toHaveBeenCalled();
+ } finally {
+ decode.mockRestore();
+ bytesOnly.mockRestore();
+ deleteJob(jobId);
+ }
+ }, 30_000);
+
+ test("verifies pinned fragmented sources through immutable upload and exact remote proof", async () => {
+ const sourceDecode = spyOn(
+ recordingVerification,
+ "inspectRecordingSources",
+ );
+ const localDecode = spyOn(recordingVerification, "verifyRecording");
+ const remoteDecode = spyOn(recordingVerification, "verifyRemoteRecording");
+ const bytesOnly = spyOn(
+ recordingVerification,
+ "verifyRemoteRecordingBytes",
+ );
+ const body = fencedMuxRequest("fenced-mux");
+ const response = await app.fetch(
+ mediaPostRequest("/video/mux-segments", body),
+ );
+ expect(response.status).toBe(200);
+ const { jobId } = (await response.json()) as { jobId: string };
+ const replay = await app.fetch(
+ mediaPostRequest("/video/mux-segments", body),
+ );
+ expect(((await replay.json()) as { jobId: string }).jobId).toBe(jobId);
+ try {
+ const job = await waitForTerminalJob(jobId);
+ expect(job.phase).toBe("complete");
+ expect(job.error).toBeUndefined();
+ expect(job.generation).toBe(body.generation);
+ expect(job.attemptId).toBe(body.attemptId);
+ expect(job.inventorySha256).toBe(body.inventorySha256);
+ expect(job.metadata?.duration).toBeCloseTo(1, 3);
+ expect(sourceDecode).toHaveBeenCalledTimes(1);
+ expect(localDecode).toHaveBeenCalledTimes(1);
+ expect(remoteDecode).not.toHaveBeenCalled();
+ expect(bytesOnly).toHaveBeenCalledTimes(1);
+ expect(uploadConditions).toEqual(["*"]);
+ expect(sourceReads).toHaveLength(body.sourceObjects.length);
+ for (const read of sourceReads) {
+ expect(read.ifMatch).toBe(
+ objectIdentity(recordingSources.get(read.path) ?? new Uint8Array()),
+ );
+ expect(read.verification).toBe("1");
+ }
+ const bytes = uploadedBytes("/uploads/fenced-mux.mp4");
+ expect(job.recordingVerification).toMatchObject({
+ fullDecode: true,
+ objectIdentity: objectIdentity(bytes),
+ outputKey: body.outputKey,
+ outputSha256: createHash("sha256").update(bytes).digest("hex"),
+ sourceProof: {
+ version: 1,
+ manifestSha256: body.manifestSha256,
+ inventorySha256: body.inventorySha256,
+ sourcePreserved: true,
+ hasAudio: true,
+ audioVerified: true,
+ },
+ });
+ } finally {
+ sourceDecode.mockRestore();
+ localDecode.mockRestore();
+ remoteDecode.mockRestore();
+ bytesOnly.mockRestore();
+ deleteJob(jobId);
+ }
+ }, 30_000);
+
+ test("refuses a local output changed between full decode and byte binding", async () => {
+ const originalHash = recordingVerification.hashRecordingFile;
+ const hashing = spyOn(
+ recordingVerification,
+ "hashRecordingFile",
+ ).mockImplementation(async (path, signal) => {
+ const digest = await originalHash(path, signal);
+ const bytes = await readFile(path);
+ bytes[bytes.length - 1] ^= 1;
+ await writeFile(path, bytes);
+ return digest;
+ });
+ let jobId: string | undefined;
+ try {
+ const response = await app.fetch(
+ mediaPostRequest(
+ "/video/mux-segments",
+ fencedMuxRequest("changed-local-output"),
+ ),
+ );
+ expect(response.status).toBe(200);
+ jobId = ((await response.json()) as { jobId: string }).jobId;
+ const job = await waitForTerminalJob(jobId);
+ expect(job.phase).toBe("error");
+ expect(job.error).toContain(
+ "Local recording changed during verification",
+ );
+ expect(job.errorCode).toBe("output-invalid");
+ expect(job.recordingVerification).toBeUndefined();
+ expect(uploadConditions).toHaveLength(0);
+ } finally {
+ hashing.mockRestore();
+ if (jobId) deleteJob(jobId);
+ }
+ }, 30_000);
+
+ test.each([false, true])(
+ "preserves multipart attempt fencing through callbacks with signing failure %s",
+ async (rejectSigning) => {
+ rejectMultipartSigning = rejectSigning;
+ const body = multipartMuxRequest(`fenced-multipart-${rejectSigning}`);
+ const response = await app.fetch(
+ mediaPostRequest("/video/mux-segments", body),
+ );
+ expect(response.status).toBe(200);
+ const { jobId } = (await response.json()) as { jobId: string };
+ try {
+ const job = await waitForTerminalJob(jobId);
+ expect(job.phase).toBe(rejectSigning ? "error" : "complete");
+ expect(multipartCallbacks.map(({ action }) => action)).toEqual(
+ rejectSigning ? ["sign-part", "abort"] : ["sign-part", "complete"],
+ );
+ for (const callback of multipartCallbacks)
+ expect(callback.payload).toMatchObject({
+ videoId: body.videoId,
+ generation: body.generation,
+ attemptId: body.attemptId,
+ key: body.outputKey,
+ uploadId: body.outputUpload.uploadId,
+ });
+ if (rejectSigning) expect(job.recordingVerification).toBeUndefined();
+ else
+ expect(job.recordingVerification?.sourceProof?.sourcePreserved).toBe(
+ true,
+ );
+ } finally {
+ deleteJob(jobId);
+ }
+ },
+ 30_000,
+ );
+
+ test.each(["changed", "missing", "corrupt"] as const)(
+ "withholds upload and proof after a pinned source is %s",
+ async (fault) => {
+ sourceFault = fault;
+ const body = fencedMuxRequest(`fenced-source-${fault}`);
+ const response = await app.fetch(
+ mediaPostRequest("/video/mux-segments", body),
+ );
+ expect(response.status).toBe(200);
+ const { jobId } = (await response.json()) as { jobId: string };
+ try {
+ const job = await waitForTerminalJob(jobId);
+ expect(job.phase).toBe("error");
+ expect(job.errorCode).toBe(
+ fault === "corrupt" ? "source-invalid" : `source-${fault}`,
+ );
+ expect(job.recordingVerification).toBeUndefined();
+ expect(uploadConditions).toHaveLength(0);
+ if (fault === "missing")
+ expect(
+ sourceReads.filter((read) =>
+ read.path.endsWith("video-segment.m4s"),
+ ),
+ ).toHaveLength(3);
+ } finally {
+ deleteJob(jobId);
+ }
+ },
+ 30_000,
+ );
+
+ test("withholds proof for corrupt remote output while preserving the source failure distinction", async () => {
+ corruptRecordingReadback = true;
+ const response = await app.fetch(
+ mediaPostRequest(
+ "/video/mux-segments",
+ fencedMuxRequest("fenced-corrupt-output"),
+ ),
+ );
+ expect(response.status).toBe(200);
+ const { jobId } = (await response.json()) as { jobId: string };
+ try {
+ const job = await waitForTerminalJob(jobId);
+ expect(job.phase).toBe("error");
+ expect(job.errorCode).toBe("output-invalid");
+ expect(job.recordingVerification).toBeUndefined();
+ expect(uploadConditions).toEqual(["*"]);
+ } finally {
+ deleteJob(jobId);
+ }
+ }, 30_000);
+
+ test("does not overwrite an existing immutable candidate", async () => {
+ const original = new Uint8Array([1, 2, 3]);
+ uploadedArtifacts.set("/uploads/fenced-existing.mp4", original);
+ const response = await app.fetch(
+ mediaPostRequest(
+ "/video/mux-segments",
+ fencedMuxRequest("fenced-existing"),
+ ),
+ );
+ expect(response.status).toBe(200);
+ const { jobId } = (await response.json()) as { jobId: string };
+ try {
+ const job = await waitForTerminalJob(jobId);
+ expect(job.phase).toBe("error");
+ expect(job.recordingVerification).toBeUndefined();
+ expect(uploadedBytes("/uploads/fenced-existing.mp4")).toEqual(original);
+ expect(uploadConditions).toEqual(["*"]);
+ } finally {
+ deleteJob(jobId);
+ }
+ }, 30_000);
+
+ test("rejects incomplete source inventories and conflicting attempt reuse before another upload", async () => {
+ const body = fencedMuxRequest("fenced-validation");
+ for (const invalid of [
+ { ...body, sourceObjects: body.sourceObjects.slice(1) },
+ { ...body, outputUpload: { type: "put", url: body.outputUpload.url } },
+ { ...body, outputVerificationUrl: undefined },
+ {
+ ...body,
+ outputUpload: {
+ ...multipartMuxRequest(body.videoId).outputUpload,
+ generation: undefined,
+ },
+ },
+ {
+ ...body,
+ outputUpload: {
+ ...multipartMuxRequest(body.videoId).outputUpload,
+ attemptId: "another-attempt",
+ },
+ },
+ ]) {
+ expect(
+ (await app.fetch(mediaPostRequest("/video/mux-segments", invalid)))
+ .status,
+ ).toBe(400);
+ }
+ const response = await app.fetch(
+ mediaPostRequest("/video/mux-segments", body),
+ );
+ expect(response.status).toBe(200);
+ const { jobId } = (await response.json()) as { jobId: string };
+ try {
+ const conflict = await app.fetch(
+ mediaPostRequest("/video/mux-segments", {
+ ...body,
+ inventorySha256: "c".repeat(64),
+ }),
+ );
+ expect(conflict.status).toBe(409);
+ expect((await waitForTerminalJob(jobId)).phase).toBe("complete");
+ } finally {
+ deleteJob(jobId);
+ }
+ }, 30_000);
+
test("checks real audio tracks through the route stack", async () => {
const withAudioResponse = await app.fetch(
mediaPostRequest("/audio/check", {
diff --git a/apps/media-server/src/__tests__/lib/media-video.integration.test.ts b/apps/media-server/src/__tests__/lib/media-video.integration.test.ts
index b688272a9..05117c7e7 100644
--- a/apps/media-server/src/__tests__/lib/media-video.integration.test.ts
+++ b/apps/media-server/src/__tests__/lib/media-video.integration.test.ts
@@ -29,6 +29,7 @@ import {
pickMobileSafeH264Level,
processVideo,
repairContainer,
+ uploadFileToStorage,
uploadToS3,
} from "../../lib/media-video";
@@ -93,6 +94,106 @@ afterAll(() => {
}
});
+describe("recording upload cancellation", () => {
+ test.each(["put", "sign-part", "part", "complete", "complete-body"])(
+ "stops %s without retrying and gives multipart cleanup an independent signal",
+ async (blockedStage) => {
+ const originalFetch = globalThis.fetch;
+ const controller = new AbortController();
+ const calls: string[] = [];
+ let ready: () => void = () => undefined;
+ const started = new Promise<void>((resolve) => {
+ ready = resolve;
+ });
+ let cancelledBodies = 0;
+ globalThis.fetch = (async (input, init) => {
+ const stage = String(input).split("/").at(-1) ?? "";
+ calls.push(stage);
+ const signal = init?.signal;
+ if (!signal) throw new Error("Upload request has no deadline signal");
+ if (stage === "complete" && blockedStage === "complete-body") {
+ return new Response(
+ new ReadableStream({
+ start(stream) {
+ signal.addEventListener(
+ "abort",
+ () => stream.error(signal.reason),
+ {
+ once: true,
+ },
+ );
+ ready();
+ },
+ }),
+ );
+ }
+ if (stage === blockedStage) {
+ return new Promise<Response>((_resolve, reject) => {
+ signal.addEventListener("abort", () => reject(signal.reason), {
+ once: true,
+ });
+ ready();
+ });
+ }
+ if (stage === "sign-part")
+ return Response.json({ url: "https://storage.example/part" });
+ if (stage !== "part" && stage !== "abort")
+ throw new Error(`Unexpected upload request: ${stage}`);
+ if (stage === "abort") expect(signal.aborted).toBe(false);
+ return new Response(
+ new ReadableStream({
+ cancel() {
+ cancelledBodies++;
+ },
+ }),
+ { headers: { ETag: '"part-identity"' } },
+ );
+ }) as typeof fetch;
+ try {
+ const rejected = expectRejected(
+ uploadFileToStorage(
+ TEST_VIDEO_WITH_AUDIO,
+ blockedStage === "put"
+ ? { type: "put", url: "https://storage.example/put" }
+ : {
+ type: "multipart",
+ videoId: "recording",
+ key: "candidate.mp4",
+ uploadId: "upload-id",
+ partSize: 5 * 1024 * 1024,
+ signPartUrl: "https://storage.example/sign-part",
+ completeUrl: "https://storage.example/complete",
+ abortUrl: "https://storage.example/abort",
+ },
+ "video/mp4",
+ controller.signal,
+ ),
+ );
+ await started;
+ controller.abort(new Error("Recording processing deadline expired"));
+ await rejected;
+ const finalStage =
+ blockedStage === "complete-body" ? "complete" : blockedStage;
+ const expected =
+ blockedStage === "put"
+ ? ["put"]
+ : ["sign-part", "part", "complete"].slice(
+ 0,
+ ["sign-part", "part", "complete"].indexOf(finalStage) + 1,
+ );
+ if (blockedStage !== "put") expected.push("abort");
+ expect(calls).toEqual(expected);
+ expect(cancelledBodies).toBe(
+ blockedStage === "put" ? 0 : finalStage === "complete" ? 2 : 1,
+ );
+ } finally {
+ controller.abort();
+ globalThis.fetch = originalFetch;
+ }
+ },
+ );
+});
+
describe("generateThumbnail integration tests", () => {
test("generates JPEG thumbnail from video", async () => {
const metadata = await probeVideo(`file://${TEST_VIDEO_WITH_AUDIO}`);
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
index dfc56ad81..b25e5b66a 100644
--- a/apps/media-server/src/__tests__/lib/recording-verification.integration.test.ts
+++ b/apps/media-server/src/__tests__/lib/recording-verification.integration.test.ts
@@ -1,4 +1,5 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { createHash } from "node:crypto";
import {
mkdtemp,
readdir,
@@ -9,10 +10,13 @@ import {
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { muxMediaTracksToMp4 } from "../../lib/media-video";
import {
+ inspectRecordingSources,
isRetryableRecordingVerificationError,
verifyRecording,
verifyRemoteRecording,
+ verifyRemoteRecordingBytes,
} from "../../lib/recording-verification";
const FIXTURES = join(import.meta.dir, "..", "fixtures");
@@ -138,6 +142,32 @@ describe("complete recording decode", () => {
expect(evidence.audio?.sampleCount).toBeGreaterThanOrEqual(240_000);
expect(evidence.audio?.sampleRate).toBe(48_000);
expect(evidence.audio?.decodedDuration).toBeCloseTo(5, 1);
+ const hashes = await run([
+ "ffmpeg",
+ "-v",
+ "error",
+ "-i",
+ silent,
+ "-map",
+ "0:v:0",
+ "-map",
+ "0:a:0",
+ "-c:v",
+ "rawvideo",
+ "-c:a",
+ "pcm_f64le",
+ "-f",
+ "streamhash",
+ "-hash",
+ "sha256",
+ "-",
+ ]);
+ expect(hashes).toContain(
+ `0,v,SHA256=${evidence.integrity?.video.contentSha256}`,
+ );
+ expect(hashes).toContain(
+ `1,a,SHA256=${evidence.integrity?.audio?.contentSha256}`,
+ );
});
test("accepts legacy video without audio only when audio was not requested", async () => {
@@ -215,6 +245,246 @@ describe("complete recording decode", () => {
});
});
+describe("source-preserving recording mux", () => {
+ test("preserves sparse screenshot timestamps without inventing missing frames", async () => {
+ const input = join(directory, "sparse-video.mp4");
+ await generate(input, "anullsrc=r=48000:cl=mono:d=5", [
+ "-vf",
+ "select=eq(n\\,0)+eq(n\\,149)",
+ "-fps_mode",
+ "vfr",
+ ]);
+ const sourceEvidence = await inspectRecordingSources(input, input);
+ const output = join(directory, "preserved-sparse-video.mp4");
+ await muxMediaTracksToMp4(input, input, output);
+ const verified = await verifyRecording(output, {
+ requireAudio: true,
+ sourceEvidence,
+ });
+ expect(verified.sourcePreserved).toBe(true);
+ expect(verified.video.frameCount).toBe(2);
+ expect(verified.video.duration).toBeCloseTo(5, 3);
+ });
+
+ test("refuses source truth when the source itself does not decode completely", async () => {
+ await expect(inspectRecordingSources(corruptTail, silent)).rejects.toThrow(
+ "full decode failed",
+ );
+ });
+
+ test.each(["vfr", "short-audio", "audio-gap"])(
+ "preserves actual %s media despite an inaccurate legacy duration",
+ async (kind) => {
+ const input =
+ kind === "vfr"
+ ? variableFrameRate
+ : kind === "short-audio"
+ ? shortAudio
+ : audioGap;
+ const sourceEvidence = await inspectRecordingSources(input, input);
+ const output = join(directory, `preserved-${kind}.mp4`);
+ await muxMediaTracksToMp4(input, input, output);
+ const verified = await verifyRecording(output, {
+ expectedDuration: 0.5,
+ requireAudio: true,
+ sourceEvidence,
+ });
+ expect(verified.sourcePreserved).toBe(true);
+ expect(verified.video.frameCount).toBe(sourceEvidence.video.frameCount);
+ expect(verified.audio?.sampleCount).toBe(
+ sourceEvidence.audio?.sampleCount,
+ );
+ expect(verified.integrity).toEqual(sourceEvidence.integrity);
+ },
+ );
+
+ test("preserves an audio tail beyond the video and rejects the old shortest mux", async () => {
+ const input = join(directory, "long-audio.mp4");
+ await generate(input, "sine=frequency=700:sample_rate=48000:duration=6");
+ const sourceEvidence = await inspectRecordingSources(input, input);
+ const output = join(directory, "preserved-audio-tail.mp4");
+ await muxMediaTracksToMp4(input, input, output);
+ const verified = await verifyRecording(output, {
+ requireAudio: true,
+ sourceEvidence,
+ });
+ expect(verified.audio?.decodedDuration).toBeGreaterThan(5.9);
+ expect(verified.sourcePreserved).toBe(true);
+ const truncated = join(directory, "shortest-audio-tail.mp4");
+ await run([
+ "ffmpeg",
+ "-v",
+ "error",
+ "-i",
+ input,
+ "-map",
+ "0:v:0",
+ "-map",
+ "0:a:0",
+ "-c",
+ "copy",
+ "-shortest",
+ truncated,
+ ]);
+ await expect(
+ verifyRecording(truncated, {
+ requireAudio: true,
+ sourceEvidence,
+ }),
+ ).rejects.toThrow("does not preserve source audio");
+ });
+
+ test("preserves AAC priming and a nonzero audio offset", async () => {
+ const input = join(directory, "offset-source.mp4");
+ await generate(input, "sine=frequency=700:sample_rate=48000:duration=5", [
+ "-af",
+ "asetpts=PTS+0.137/TB",
+ "-movie_timescale",
+ "1000000",
+ ]);
+ const sourceEvidence = await inspectRecordingSources(input, input);
+ const output = join(directory, "offset-output.mp4");
+ await muxMediaTracksToMp4(input, input, output);
+ const verified = await verifyRecording(output, {
+ requireAudio: true,
+ sourceEvidence,
+ });
+ expect(verified.sourcePreserved).toBe(true);
+ expect(verified.audio?.startTime).toBeCloseTo(
+ sourceEvidence.audio?.startTime ?? 0,
+ 6,
+ );
+ const shifted = join(directory, "offset-lost.mp4");
+ await run([
+ "ffmpeg",
+ "-v",
+ "error",
+ "-i",
+ output,
+ "-itsoffset",
+ "0.25",
+ "-i",
+ output,
+ "-map",
+ "0:v:0",
+ "-map",
+ "1:a:0",
+ "-c",
+ "copy",
+ shifted,
+ ]);
+ await expect(
+ verifyRecording(shifted, { requireAudio: true, sourceEvidence }),
+ ).rejects.toThrow("source A/V sync");
+ });
+
+ test("compares audio samples independently of PCM packetization", async () => {
+ const input = join(directory, "pcm-source.mp4");
+ const output = join(directory, "pcm-repacketized.mp4");
+ await run([
+ "ffmpeg",
+ "-v",
+ "error",
+ "-i",
+ silent,
+ "-c:v",
+ "copy",
+ "-c:a",
+ "pcm_s16le",
+ "-f",
+ "mov",
+ input,
+ ]);
+ await run([
+ "ffmpeg",
+ "-v",
+ "error",
+ "-copyts",
+ "-i",
+ input,
+ "-c:v",
+ "copy",
+ "-af",
+ "asetnsamples=n=777:p=0",
+ "-c:a",
+ "pcm_s16le",
+ "-f",
+ "mov",
+ output,
+ ]);
+ const sourceEvidence = await inspectRecordingSources(input, input);
+ const verified = await verifyRecording(output, {
+ requireAudio: true,
+ sourceEvidence,
+ });
+ expect(verified.sourcePreserved).toBe(true);
+ expect(verified.audio?.sampleCount).toBe(sourceEvidence.audio?.sampleCount);
+ });
+
+ test("rejects changed video order and changed audio with unchanged durations", async () => {
+ const sourceEvidence = await inspectRecordingSources(silent, silent);
+ const reversed = join(directory, "reversed.mp4");
+ await run([
+ "ffmpeg",
+ "-v",
+ "error",
+ "-i",
+ silent,
+ "-vf",
+ "reverse",
+ "-c:v",
+ "libx264",
+ "-preset",
+ "ultrafast",
+ "-c:a",
+ "copy",
+ reversed,
+ ]);
+ await expect(
+ verifyRecording(reversed, { requireAudio: true, sourceEvidence }),
+ ).rejects.toThrow("does not preserve source video");
+ const changedAudio = join(directory, "changed-audio.mp4");
+ await run([
+ "ffmpeg",
+ "-v",
+ "error",
+ "-i",
+ silent,
+ "-f",
+ "lavfi",
+ "-i",
+ "sine=frequency=300:sample_rate=48000:duration=5",
+ "-map",
+ "0:v:0",
+ "-map",
+ "1:a:0",
+ "-c:v",
+ "copy",
+ "-c:a",
+ "aac",
+ changedAudio,
+ ]);
+ await expect(
+ verifyRecording(changedAudio, { requireAudio: true, sourceEvidence }),
+ ).rejects.toThrow("does not preserve source audio");
+ });
+
+ test("preserves video-only sources without inventing audio", async () => {
+ const sourceEvidence = await inspectRecordingSources(
+ variableFrameRate,
+ null,
+ );
+ const output = join(directory, "preserved-video-only.mp4");
+ await muxMediaTracksToMp4(variableFrameRate, null, output);
+ const verified = await verifyRecording(output, {
+ requireAudio: false,
+ sourceEvidence,
+ });
+ expect(verified.sourcePreserved).toBe(true);
+ expect(verified.audio).toBeNull();
+ });
+});
+
async function decoderPids(input: string): Promise<number[]> {
if (process.platform === "linux") {
const processes = (await readdir("/proc")).filter((name) =>
@@ -371,6 +641,297 @@ function objectResponse(
}
describe("remote recording object identity", () => {
+ test("binds remote bytes without manufacturing decoded evidence", async () => {
+ const identity = '"byte-bound-output"';
+ const sha256 = createHash("sha256").update(silentBytes).digest("hex");
+ const requests: Request[] = [];
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ requests.push(request);
+ return objectResponse(request, identity);
+ },
+ });
+ try {
+ const result = await verifyRemoteRecordingBytes(
+ `http://127.0.0.1:${server.port}/recording.mp4`,
+ {
+ expectedObjectIdentity: identity,
+ expectedSha256: sha256,
+ expectedFileSize: silentBytes.byteLength,
+ },
+ );
+ expect(result).toEqual({
+ objectIdentity: identity,
+ fileSize: silentBytes.byteLength,
+ remoteSha256: sha256,
+ });
+ expect(requests.map((request) => request.headers.get("range"))).toEqual([
+ "bytes=0-0",
+ null,
+ "bytes=0-0",
+ ]);
+ for (const request of requests) {
+ expect(request.headers.get("if-match")).toBe(identity);
+ expect(request.headers.get("x-cap-recording-verification")).toBe("1");
+ }
+ } finally {
+ await server.stop(true);
+ }
+ });
+
+ test.each(["changed", "oversized", "truncated", "post-identity"])(
+ "refuses bytes-only proof for %s storage",
+ async (fault) => {
+ const identity = '"byte-bound-output"';
+ const changed = silentBytes.slice();
+ changed[changed.length - 1] ^= 1;
+ let bodyRead = false;
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ if (request.headers.has("range")) {
+ return objectResponse(
+ request,
+ fault === "post-identity" && bodyRead ? '"changed"' : identity,
+ );
+ }
+ bodyRead = true;
+ const bytes =
+ fault === "changed"
+ ? changed
+ : fault === "oversized"
+ ? new Uint8Array(silentBytes.byteLength + 1)
+ : fault === "truncated"
+ ? silentBytes.subarray(0, -1)
+ : silentBytes;
+ return new Response(bytes, { headers: { ETag: identity } });
+ },
+ });
+ try {
+ await expect(
+ verifyRemoteRecordingBytes(
+ `http://127.0.0.1:${server.port}/recording.mp4`,
+ {
+ expectedObjectIdentity: identity,
+ expectedSha256: createHash("sha256")
+ .update(silentBytes)
+ .digest("hex"),
+ expectedFileSize: silentBytes.byteLength,
+ },
+ ),
+ ).rejects.toThrow(
+ fault === "changed"
+ ? "bytes do not match"
+ : fault === "post-identity"
+ ? "changed during verification"
+ : "size changed",
+ );
+ } finally {
+ await server.stop(true);
+ }
+ },
+ );
+
+ test.each(["cancel", "timeout"])(
+ "stops bytes-only readback on %s",
+ async (cause) => {
+ let started: (() => void) | undefined;
+ const reading = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const identity = '"stalled-byte-output"';
+ const controller = new AbortController();
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ if (request.headers.has("range"))
+ return objectResponse(request, identity);
+ started?.();
+ return new Response(
+ new ReadableStream({
+ start(stream) {
+ stream.enqueue(silentBytes.subarray(0, 32));
+ },
+ }),
+ { headers: { ETag: identity } },
+ );
+ },
+ });
+ try {
+ const result = verifyRemoteRecordingBytes(
+ `http://127.0.0.1:${server.port}/recording.mp4`,
+ {
+ expectedObjectIdentity: identity,
+ expectedSha256: createHash("sha256")
+ .update(silentBytes)
+ .digest("hex"),
+ expectedFileSize: silentBytes.byteLength,
+ abortSignal: controller.signal,
+ timeoutMs: cause === "timeout" ? 100 : 5_000,
+ },
+ ).catch((error: unknown) => error);
+ await reading;
+ if (cause === "cancel") controller.abort();
+ const error = await result;
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toContain(
+ cause === "cancel" ? "cancelled" : "timed out",
+ );
+ expect(isRetryableRecordingVerificationError(error)).toBe(
+ cause === "timeout",
+ );
+ } finally {
+ controller.abort();
+ await server.stop(true);
+ }
+ },
+ );
+
+ test.each(["cancel", "timeout"])(
+ "stops a stalled byte readback after %s without a receipt",
+ async (cause) => {
+ let started: (() => void) | undefined;
+ const reading = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const identity = '"stalled-readback"';
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ if (request.headers.has("range"))
+ return objectResponse(request, identity);
+ started?.();
+ return new Response(
+ new ReadableStream({
+ start(controller) {
+ controller.enqueue(silentBytes.subarray(0, 32));
+ },
+ }),
+ { headers: { ETag: identity } },
+ );
+ },
+ });
+ const controller = new AbortController();
+ try {
+ const outcome = verifyRemoteRecording(
+ `http://127.0.0.1:${server.port}/recording.mp4`,
+ {
+ expectedDuration: 5,
+ requireAudio: true,
+ expectedSha256: createHash("sha256")
+ .update(silentBytes)
+ .digest("hex"),
+ expectedFileSize: silentBytes.byteLength,
+ abortSignal: controller.signal,
+ timeoutMs: cause === "timeout" ? 500 : 5_000,
+ },
+ ).catch((error: unknown) => error);
+ await reading;
+ 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(isRetryableRecordingVerificationError(error)).toBe(
+ cause === "timeout",
+ );
+ } finally {
+ controller.abort();
+ await server.stop(true);
+ }
+ },
+ 10_000,
+ );
+
+ test.each(["changed", "oversized"])(
+ "rejects %s readback bytes even when storage reuses the ETag",
+ async (fault) => {
+ const identity = '"dishonest-storage"';
+ const sha256 = createHash("sha256").update(silentBytes).digest("hex");
+ const changed = silentBytes.slice();
+ changed[changed.length - 1] ^= 1;
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ if (request.headers.has("range")) {
+ return objectResponse(request, identity);
+ }
+ return new Response(
+ fault === "changed"
+ ? changed
+ : new Uint8Array(silentBytes.byteLength + 1),
+ { headers: { ETag: identity } },
+ );
+ },
+ });
+ try {
+ await expect(
+ verifyRemoteRecording(
+ `http://127.0.0.1:${server.port}/recording.mp4`,
+ {
+ expectedDuration: 5,
+ requireAudio: true,
+ expectedObjectIdentity: identity,
+ expectedFileSize: silentBytes.byteLength,
+ expectedSha256: sha256,
+ },
+ ),
+ ).rejects.toThrow(
+ fault === "changed" ? "bytes do not match" : "size changed",
+ );
+ } finally {
+ await server.stop(true);
+ }
+ },
+ );
+
+ test("checks exact remote bytes as well as a stable object identity", async () => {
+ const identity = '"verified-content"';
+ const sha256 = createHash("sha256").update(silentBytes).digest("hex");
+ const sourceEvidence = await inspectRecordingSources(silent, silent);
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ return objectResponse(request, identity);
+ },
+ });
+ try {
+ const options = {
+ requireAudio: true,
+ sourceEvidence,
+ expectedObjectIdentity: identity,
+ expectedFileSize: silentBytes.byteLength,
+ expectedSha256: sha256,
+ };
+ const url = `http://127.0.0.1:${server.port}/recording.mp4`;
+ const verified = await verifyRemoteRecording(url, options);
+ expect(verified.remoteSha256).toBe(sha256);
+ expect(verified.sourcePreserved).toBe(true);
+ await expect(
+ verifyRemoteRecording(url, {
+ ...options,
+ expectedSha256: "0".repeat(64),
+ }),
+ ).rejects.toThrow("bytes do not match");
+ await expect(
+ verifyRemoteRecording(url, {
+ ...options,
+ expectedFileSize: silentBytes.byteLength + 1,
+ }),
+ ).rejects.toThrow("size does not match");
+ } finally {
+ await server.stop(true);
+ }
+ });
+
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"';
diff --git a/apps/media-server/src/__tests__/routes/recording-verification.test.ts b/apps/media-server/src/__tests__/routes/recording-verification.test.ts
index a6da439ac..d530dc976 100644
--- a/apps/media-server/src/__tests__/routes/recording-verification.test.ts
+++ b/apps/media-server/src/__tests__/routes/recording-verification.test.ts
@@ -72,11 +72,11 @@ async function waitFor(predicate: () => boolean) {
}
}
-async function startJob() {
+async function startJob(requestBody: Record<string, unknown> = body) {
const response = await video.request("/verify-recording", {
method: "POST",
headers,
- body: JSON.stringify(body),
+ body: JSON.stringify(requestBody),
});
expect(response.status).toBe(200);
const accepted = (await response.json()) as { jobId: string };
@@ -163,6 +163,103 @@ afterAll(() => {
});
describe("asynchronous recording verification", () => {
+ test("binds a fenced MP4 attempt to the original artifact and verified snapshot", async () => {
+ const snapshotIdentity = '"snapshot-generation"';
+ verify.mockResolvedValue({
+ ...evidence,
+ objectIdentity: snapshotIdentity,
+ remoteSha256: "a".repeat(64),
+ });
+ const request = {
+ ...body,
+ generation: "generation-a",
+ attemptId: "attempt-a",
+ inventorySha256: "c".repeat(64),
+ outputKey: "recording-generations/generation-a/source.mp4",
+ originalObjectIdentity: body.objectIdentity,
+ sourceObjectIdentity: snapshotIdentity,
+ duration: undefined,
+ };
+ const jobId = await startJob(request);
+ const completed = await terminalWebhook(jobId);
+ expect(completed.generation).toBe(request.generation);
+ expect(completed.attemptId).toBe(request.attemptId);
+ expect(completed.inventorySha256).toBe(request.inventorySha256);
+ expect(completed.recordingVerification).toMatchObject({
+ request: {
+ artifact: {
+ objectIdentity: body.objectIdentity,
+ duration: evidence.video.duration,
+ },
+ },
+ objectIdentity: snapshotIdentity,
+ outputKey: request.outputKey,
+ outputSha256: "a".repeat(64),
+ });
+ expect(verify.mock.calls[0]?.[1]).toMatchObject({
+ expectedObjectIdentity: snapshotIdentity,
+ expectedFileSize: body.fileSize,
+ allowObservedDuration: true,
+ hashContent: true,
+ });
+ });
+
+ test("deduplicates a replayed attempt before capacity checks and rejects changed context", async () => {
+ let finish:
+ | ((value: RemoteRecordingVerificationResult) => void)
+ | undefined;
+ verify.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const request = {
+ ...body,
+ generation: "generation-dedup",
+ attemptId: "attempt-dedup",
+ inventorySha256: "d".repeat(64),
+ outputKey: "snapshot.mp4",
+ originalObjectIdentity: body.objectIdentity,
+ sourceObjectIdentity: body.objectIdentity,
+ };
+ const jobId = await startJob(request);
+ await waitFor(() => verify.mock.calls.length === 1);
+ expect(await status(jobId)).toMatchObject({
+ phase: "processing",
+ generation: request.generation,
+ attemptId: request.attemptId,
+ inventorySha256: request.inventorySha256,
+ });
+ try {
+ capacity.mockReturnValue(false);
+ expect(await startJob(request)).toBe(jobId);
+ expect(verify.mock.calls).toHaveLength(1);
+ const conflict = await video.request("/verify-recording", {
+ method: "POST",
+ headers,
+ body: JSON.stringify({
+ ...request,
+ inventorySha256: "e".repeat(64),
+ }),
+ });
+ expect(conflict.status).toBe(409);
+ } finally {
+ finish?.({ ...evidence, remoteSha256: "b".repeat(64) });
+ }
+ expect((await terminalWebhook(jobId)).phase).toBe("complete");
+ });
+
+ test("rejects incomplete fenced context without starting work", async () => {
+ const response = await video.request("/verify-recording", {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ ...body, generation: "generation-only" }),
+ });
+ expect(response.status).toBe(400);
+ expect(verify).not.toHaveBeenCalled();
+ });
+
test("acceptance is not proof and completed metadata comes from decoded evidence", async () => {
let finish:
| ((value: RemoteRecordingVerificationResult) => void)
diff --git a/apps/media-server/src/lib/job-manager.ts b/apps/media-server/src/lib/job-manager.ts
index 43faf3287..a5ac7e9e8 100644
--- a/apps/media-server/src/lib/job-manager.ts
+++ b/apps/media-server/src/lib/job-manager.ts
@@ -19,6 +19,13 @@ export type JobPhase =
| "error"
| "cancelled";
+export type RecordingErrorCode =
+ | "source-invalid"
+ | "source-missing"
+ | "source-changed"
+ | "output-invalid"
+ | "processing-unavailable";
+
export interface RecordingVerificationRequest {
version: 1;
artifact:
@@ -36,9 +43,23 @@ export interface RecordingVerificationProof {
request: RecordingVerificationRequest;
fullDecode: true;
objectIdentity: string;
+ outputKey?: string;
+ outputSha256?: string;
+ sourceProof?: {
+ version: 1;
+ manifestSha256: string;
+ inventorySha256: string;
+ sourcePreserved: true;
+ videoDuration: number;
+ hasAudio: boolean;
+ audioVerified: boolean;
+ };
}
export interface JobProgress {
+ generation?: string;
+ attemptId?: string;
+ inventorySha256?: string;
recordingVerification?: RecordingVerificationProof;
manifestSha256?: string;
jobId: string;
@@ -47,6 +68,7 @@ export interface JobProgress {
progress: number;
message?: string;
error?: string;
+ errorCode?: RecordingErrorCode;
metadata?: VideoMetadata;
outputUrl?: string;
}
@@ -65,7 +87,16 @@ export interface VideoMetadata {
}
export interface Job {
+ generation?: string;
+ attemptId?: string;
+ inventorySha256?: string;
+ recordingRequestKey?: string;
+ terminalAt?: number;
+ terminalWebhookAcknowledgedAt?: number;
+ webhookInFlight?: boolean;
+ webhookLastAttemptAt?: number;
recordingVerificationDeadlineAt?: number;
+ recordingProcessingDeadlineAt?: number;
recordingVerification?: RecordingVerificationProof;
manifestSha256?: string;
jobId: string;
@@ -75,6 +106,7 @@ export interface Job {
progress: number;
message?: string;
error?: string;
+ errorCode?: RecordingErrorCode;
metadata?: VideoMetadata;
outputUrl?: string;
createdAt: number;
@@ -91,9 +123,11 @@ const jobs = new Map<string, Job>();
const JOB_TTL_MS = 60 * 60 * 1000;
const STALE_JOB_MS = 15 * 60 * 1000;
const MAX_JOB_LIFETIME_MS = 60 * 60 * 1000;
+const MAX_RECORDING_PROCESSING_BUDGET_MS = 3 * 60 * 60 * 1000;
const WEBHOOK_MAX_ATTEMPTS = 3;
const WEBHOOK_RETRY_BASE_MS = 500;
const WEBHOOK_TIMEOUT_MS = 5000;
+const UNACKNOWLEDGED_TERMINAL_TTL_MS = 24 * 60 * 60 * 1000;
const configuredMaxProcesses =
Number.parseInt(
@@ -305,9 +339,14 @@ export function updateJob(
Pick<
Job,
| "phase"
+ | "generation"
+ | "attemptId"
+ | "inventorySha256"
+ | "recordingRequestKey"
| "progress"
| "message"
| "error"
+ | "errorCode"
| "metadata"
| "manifestSha256"
| "recordingVerification"
@@ -323,6 +362,7 @@ export function updateJob(
if (!job) return undefined;
Object.assign(job, updates, { updatedAt: Date.now() });
+ if (!isActivePhase(job.phase)) job.terminalAt ??= job.updatedAt;
return job;
}
@@ -345,13 +385,42 @@ export function beginRecordingVerification(
!isActivePhase(job.phase) ||
job.abortController?.signal.aborted ||
job.recordingVerificationDeadlineAt !== undefined ||
- now > job.createdAt + MAX_JOB_LIFETIME_MS ||
+ now >
+ (job.recordingProcessingDeadlineAt ??
+ job.createdAt + MAX_JOB_LIFETIME_MS) ||
!Number.isSafeInteger(budgetMs) ||
budgetMs <= 0 ||
budgetMs > MAX_JOB_LIFETIME_MS
)
return false;
- job.recordingVerificationDeadlineAt = now + budgetMs;
+ job.recordingVerificationDeadlineAt = Math.min(
+ now + budgetMs,
+ job.recordingProcessingDeadlineAt ?? Number.POSITIVE_INFINITY,
+ );
+ job.updatedAt = now;
+ return true;
+}
+
+export function beginRecordingProcessing(
+ jobId: string,
+ budgetMs: number,
+): boolean {
+ const job = jobs.get(jobId);
+ const now = Date.now();
+ if (
+ !job ||
+ !isActivePhase(job.phase) ||
+ job.abortController?.signal.aborted ||
+ job.recordingProcessingDeadlineAt !== undefined ||
+ job.recordingVerificationDeadlineAt !== undefined ||
+ now - job.updatedAt > STALE_JOB_MS ||
+ now - job.createdAt > MAX_JOB_LIFETIME_MS ||
+ !Number.isSafeInteger(budgetMs) ||
+ budgetMs <= 0 ||
+ budgetMs > MAX_RECORDING_PROCESSING_BUDGET_MS
+ )
+ return false;
+ job.recordingProcessingDeadlineAt = now + budgetMs;
job.updatedAt = now;
return true;
}
@@ -400,6 +469,24 @@ export function cleanupExpiredJobs(): number {
for (const [jobId, job] of jobs) {
const age = now - job.createdAt;
const staleness = now - job.updatedAt;
+ if (!isActivePhase(job.phase)) {
+ const terminalAge = now - (job.terminalAt ?? job.updatedAt);
+ const awaitingWebhook =
+ Boolean(job.webhookUrl) && !job.terminalWebhookAcknowledgedAt;
+ if (
+ terminalAge >
+ (awaitingWebhook ? UNACKNOWLEDGED_TERMINAL_TTL_MS : JOB_TTL_MS)
+ ) {
+ deleteJob(jobId);
+ cleaned++;
+ } else if (
+ awaitingWebhook &&
+ now - (job.webhookLastAttemptAt ?? 0) >= 60_000
+ ) {
+ void sendWebhook(job);
+ }
+ continue;
+ }
if (staleness > JOB_TTL_MS) {
if (isActivePhase(job.phase)) {
@@ -411,9 +498,9 @@ export function cleanupExpiredJobs(): number {
job.error = `Job expired: no progress update for ${Math.round(staleness / 60000)} minutes`;
job.message = "Processing failed (expired)";
job.updatedAt = now;
+ job.terminalAt = now;
void sendWebhook(job);
}
- deleteJob(jobId);
cleaned++;
continue;
}
@@ -434,6 +521,7 @@ export function cleanupExpiredJobs(): number {
const deadline =
job.recordingVerificationDeadlineAt ??
+ job.recordingProcessingDeadlineAt ??
job.createdAt + MAX_JOB_LIFETIME_MS;
if (isActivePhase(job.phase) && now > deadline) {
console.warn(
@@ -442,7 +530,8 @@ export function cleanupExpiredJobs(): number {
job.abortController?.abort();
job.phase = "error";
job.error =
- job.recordingVerificationDeadlineAt === undefined
+ job.recordingVerificationDeadlineAt === undefined &&
+ job.recordingProcessingDeadlineAt === undefined
? `Job exceeded maximum lifetime of ${Math.round(MAX_JOB_LIFETIME_MS / 60000)} minutes`
: "Recording verification timed out";
job.message = "Processing failed (timeout)";
@@ -457,6 +546,9 @@ export function cleanupExpiredJobs(): number {
export function getJobProgress(job: Job): JobProgress {
return {
+ generation: job.generation,
+ attemptId: job.attemptId,
+ inventorySha256: job.inventorySha256,
manifestSha256: job.manifestSha256,
recordingVerification: job.recordingVerification,
jobId: job.jobId,
@@ -465,13 +557,16 @@ export function getJobProgress(job: Job): JobProgress {
progress: job.progress,
message: job.message,
error: job.error,
+ errorCode: job.errorCode,
metadata: job.metadata,
outputUrl: job.outputUrl,
};
}
export async function sendWebhook(job: Job): Promise<void> {
- if (!job.webhookUrl) return;
+ if (!job.webhookUrl || job.webhookInFlight) return;
+ job.webhookInFlight = true;
+ job.webhookLastAttemptAt = Date.now();
const payload = getJobProgress(job);
const headers: Record<string, string> = {
@@ -483,37 +578,46 @@ export async function sendWebhook(job: Job): Promise<void> {
let lastError: unknown;
- for (let attempt = 0; attempt < WEBHOOK_MAX_ATTEMPTS; attempt++) {
- try {
- const resp = await fetch(job.webhookUrl, {
- method: "POST",
- headers,
- body: JSON.stringify(payload),
- signal: AbortSignal.timeout(WEBHOOK_TIMEOUT_MS),
- });
-
- if (resp.ok) {
- return;
+ try {
+ for (let attempt = 0; attempt < WEBHOOK_MAX_ATTEMPTS; attempt++) {
+ try {
+ const resp = await fetch(job.webhookUrl, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(WEBHOOK_TIMEOUT_MS),
+ });
+
+ if (resp.ok) {
+ await resp.body?.cancel();
+ if (!isActivePhase(payload.phase) && job.phase === payload.phase) {
+ job.terminalWebhookAcknowledgedAt = Date.now();
+ }
+ return;
+ }
+ await resp.body?.cancel();
+
+ lastError = new Error(
+ `Webhook returned ${resp.status} for job ${job.jobId}`,
+ );
+ } catch (err) {
+ lastError = err;
}
- lastError = new Error(
- `Webhook returned ${resp.status} for job ${job.jobId}`,
- );
- } catch (err) {
- lastError = err;
+ if (attempt < WEBHOOK_MAX_ATTEMPTS - 1) {
+ await new Promise((resolve) =>
+ setTimeout(resolve, WEBHOOK_RETRY_BASE_MS * 2 ** attempt),
+ );
+ }
}
- if (attempt < WEBHOOK_MAX_ATTEMPTS - 1) {
- await new Promise((resolve) =>
- setTimeout(resolve, WEBHOOK_RETRY_BASE_MS * 2 ** attempt),
- );
- }
+ console.error(
+ `[job-manager] Failed to send webhook for job ${job.jobId}:`,
+ lastError,
+ );
+ } finally {
+ job.webhookInFlight = false;
}
-
- console.error(
- `[job-manager] Failed to send webhook for job ${job.jobId}:`,
- lastError,
- );
}
export function forceCleanupActiveJobs(): number {
diff --git a/apps/media-server/src/lib/media-video.ts b/apps/media-server/src/lib/media-video.ts
index c365de918..ef4722439 100644
--- a/apps/media-server/src/lib/media-video.ts
+++ b/apps/media-server/src/lib/media-video.ts
@@ -41,16 +41,20 @@ const MAX_LEVEL_5_1_WIDTH = 4096;
const MAX_LEVEL_5_1_HEIGHT = 2304;
const MULTIPART_MIN_PART_SIZE_BYTES = 5 * 1024 * 1024;
const MULTIPART_MAX_PARTS = 10_000;
+const MULTIPART_ABORT_TIMEOUT_MS = 30_000;
const STORAGE_ERROR_BODY_LIMIT_BYTES = 2_048;
export type StorageUploadTarget =
| {
type: "put";
url: string;
+ ifNoneMatch?: "*";
}
| {
type: "multipart";
videoId: string;
+ generation?: string;
+ attemptId?: string;
key: string;
uploadId: string;
partSize: number;
@@ -2013,15 +2017,23 @@ async function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+function uploadSignal(abortSignal?: AbortSignal) {
+ const timeout = AbortSignal.timeout(UPLOAD_TIMEOUT_MS);
+ return abortSignal ? AbortSignal.any([abortSignal, timeout]) : timeout;
+}
+
async function uploadWithRetry(
presignedUrl: string,
contentType: string,
contentLength: number,
bodyFactory: () => Blob | BunFile,
+ ifNoneMatch?: "*",
+ abortSignal?: AbortSignal,
): Promise<StorageUploadReceipt> {
let lastError: Error | undefined;
for (let attempt = 0; attempt <= UPLOAD_MAX_RETRIES; attempt++) {
+ abortSignal?.throwIfAborted();
let response: Response;
try {
@@ -2029,6 +2041,7 @@ async function uploadWithRetry(
"Content-Type": contentType,
"Content-Length": contentLength.toString(),
};
+ if (ifNoneMatch) headers["If-None-Match"] = ifNoneMatch;
if (isGoogleDriveResumableUrl(presignedUrl) && contentLength > 0) {
headers["Content-Range"] =
`bytes 0-${contentLength - 1}/${contentLength}`;
@@ -2038,9 +2051,10 @@ async function uploadWithRetry(
method: "PUT",
headers,
body: bodyFactory(),
- signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
+ signal: uploadSignal(abortSignal),
});
} catch (err) {
+ abortSignal?.throwIfAborted();
const uploadError = err instanceof Error ? err : new Error(String(err));
if (attempt === UPLOAD_MAX_RETRIES) {
@@ -2053,7 +2067,13 @@ async function uploadWithRetry(
}
if (response.ok) {
- return readUploadReceipt(response, presignedUrl, contentLength);
+ const receipt = await readUploadReceipt(
+ response,
+ presignedUrl,
+ contentLength,
+ );
+ abortSignal?.throwIfAborted();
+ return receipt;
}
const responseError = await storageResponseError(
@@ -2104,7 +2124,9 @@ async function postMultipartJson<TBody extends Record<string, unknown>>(
url: string,
body: TBody,
webhookSecret: string | undefined,
+ abortSignal?: AbortSignal,
): Promise<Response> {
+ abortSignal?.throwIfAborted();
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
@@ -2116,7 +2138,7 @@ async function postMultipartJson<TBody extends Record<string, unknown>>(
method: "POST",
headers,
body: JSON.stringify(body),
- signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
+ signal: uploadSignal(abortSignal),
});
}
@@ -2124,17 +2146,21 @@ async function getMultipartPartUrl(
target: Extract<StorageUploadTarget, { type: "multipart" }>,
partNumber: number,
contentLength: number,
+ abortSignal?: AbortSignal,
): Promise<string> {
const response = await postMultipartJson(
target.signPartUrl,
{
videoId: target.videoId,
+ generation: target.generation,
+ attemptId: target.attemptId,
key: target.key,
uploadId: target.uploadId,
partNumber,
contentLength,
},
target.webhookSecret,
+ abortSignal,
);
if (!response.ok) {
@@ -2142,6 +2168,7 @@ async function getMultipartPartUrl(
}
const data = await response.json().catch(() => null);
+ abortSignal?.throwIfAborted();
const url = (data as { url?: unknown } | null)?.url;
if (typeof url !== "string" || !url) {
throw new Error("Multipart part signing returned an invalid URL");
@@ -2155,10 +2182,12 @@ async function uploadMultipartPart(
body: Blob,
contentLength: number,
partNumber: number,
+ abortSignal?: AbortSignal,
): Promise<string> {
let lastError: Error | undefined;
for (let attempt = 0; attempt <= UPLOAD_MAX_RETRIES; attempt++) {
+ abortSignal?.throwIfAborted();
let response: Response;
try {
response = await fetch(url, {
@@ -2167,9 +2196,10 @@ async function uploadMultipartPart(
"Content-Length": contentLength.toString(),
},
body,
- signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
+ signal: uploadSignal(abortSignal),
});
} catch (err) {
+ abortSignal?.throwIfAborted();
const uploadError = err instanceof Error ? err : new Error(String(err));
if (attempt === UPLOAD_MAX_RETRIES) {
@@ -2183,6 +2213,8 @@ async function uploadMultipartPart(
if (response.ok) {
const etag = response.headers.get("etag");
+ await response.body?.cancel().catch(() => {});
+ abortSignal?.throwIfAborted();
if (!etag) {
throw new Error(`Multipart upload part ${partNumber} missing ETag`);
}
@@ -2211,16 +2243,20 @@ async function uploadMultipartPart(
async function completeMultipartUpload(
target: Extract<StorageUploadTarget, { type: "multipart" }>,
parts: UploadedPart[],
+ abortSignal?: AbortSignal,
): Promise<StorageUploadReceipt> {
const response = await postMultipartJson(
target.completeUrl,
{
videoId: target.videoId,
+ generation: target.generation,
+ attemptId: target.attemptId,
key: target.key,
uploadId: target.uploadId,
parts,
},
target.webhookSecret,
+ abortSignal,
);
if (!response.ok) {
@@ -2230,6 +2266,7 @@ async function completeMultipartUpload(
);
}
const result: unknown = await response.json().catch(() => null);
+ abortSignal?.throwIfAborted();
return {
objectIdentity: strongUploadIdentity(
result && typeof result === "object" && "objectIdentity" in result
@@ -2246,20 +2283,25 @@ async function abortMultipartUpload(
target.abortUrl,
{
videoId: target.videoId,
+ generation: target.generation,
+ attemptId: target.attemptId,
key: target.key,
uploadId: target.uploadId,
},
target.webhookSecret,
+ AbortSignal.timeout(MULTIPART_ABORT_TIMEOUT_MS),
);
if (!response.ok) {
throw await storageResponseError("Multipart upload abort failed", response);
}
+ await response.body?.cancel().catch(() => {});
}
async function uploadFileMultipart(
filePath: string,
target: Extract<StorageUploadTarget, { type: "multipart" }>,
+ abortSignal?: AbortSignal,
): Promise<StorageUploadReceipt> {
const fileHandle = file(filePath);
const contentLength = fileHandle.size;
@@ -2267,6 +2309,7 @@ async function uploadFileMultipart(
const parts: UploadedPart[] = [];
try {
+ abortSignal?.throwIfAborted();
if (contentLength <= 0) {
throw new Error("Multipart upload requires a non-empty file");
}
@@ -2286,17 +2329,23 @@ async function uploadFileMultipart(
const start = (partNumber - 1) * partSize;
const end = Math.min(start + partSize, contentLength);
const partLength = end - start;
- const url = await getMultipartPartUrl(target, partNumber, partLength);
+ const url = await getMultipartPartUrl(
+ target,
+ partNumber,
+ partLength,
+ abortSignal,
+ );
const etag = await uploadMultipartPart(
url,
fileHandle.slice(start, end),
partLength,
partNumber,
+ abortSignal,
);
parts.push({ partNumber, etag, size: partLength });
}
- return await completeMultipartUpload(target, parts);
+ return await completeMultipartUpload(target, parts, abortSignal);
} catch (error) {
await abortMultipartUpload(target).catch((abortError) => {
console.warn(
@@ -2319,12 +2368,20 @@ export async function uploadFileToStorage(
filePath: string,
target: StorageUploadTarget,
contentType: string,
+ abortSignal?: AbortSignal,
): Promise<StorageUploadReceipt> {
if (target.type === "put") {
- return uploadFileToS3(filePath, target.url, contentType);
+ return uploadWithRetry(
+ target.url,
+ contentType,
+ file(filePath).size,
+ () => file(filePath),
+ target.ifNoneMatch,
+ abortSignal,
+ );
}
- return uploadFileMultipart(filePath, target);
+ return uploadFileMultipart(filePath, target, abortSignal);
}
export async function copyFileToMp4(
@@ -2344,11 +2401,13 @@ export async function muxMediaTracksToMp4(
outputPath: string,
abortSignal?: AbortSignal,
): Promise<void> {
+ if (abortSignal?.aborted) throw new Error("Recording mux was cancelled");
const args = audioInputPath
? [
"ffmpeg",
"-hide_banner",
"-y",
+ "-copyts",
"-i",
videoInputPath,
"-i",
@@ -2359,7 +2418,10 @@ export async function muxMediaTracksToMp4(
"1:a:0",
"-c",
"copy",
- "-shortest",
+ "-avoid_negative_ts",
+ "disabled",
+ "-movie_timescale",
+ "1000000",
"-movflags",
"+faststart",
outputPath,
@@ -2368,6 +2430,7 @@ export async function muxMediaTracksToMp4(
"ffmpeg",
"-hide_banner",
"-y",
+ "-copyts",
"-i",
videoInputPath,
"-map",
@@ -2375,6 +2438,10 @@ export async function muxMediaTracksToMp4(
"-c:v",
"copy",
"-an",
+ "-avoid_negative_ts",
+ "disabled",
+ "-movie_timescale",
+ "1000000",
"-movflags",
"+faststart",
outputPath,
diff --git a/apps/media-server/src/lib/recording-verification.ts b/apps/media-server/src/lib/recording-verification.ts
index 9072b69c5..7665f3a8b 100644
--- a/apps/media-server/src/lib/recording-verification.ts
+++ b/apps/media-server/src/lib/recording-verification.ts
@@ -1,3 +1,5 @@
+import { createHash, type Hash } from "node:crypto";
+import { createReadStream } from "node:fs";
import { lstat } from "node:fs/promises";
import { isAbsolute } from "node:path";
import { spawn } from "bun";
@@ -23,8 +25,10 @@ export function isRetryableRecordingVerificationError(error: unknown): boolean {
}
export interface RecordingVerificationOptions {
- expectedDuration: number;
+ expectedDuration?: number;
requireAudio: boolean;
+ sourceEvidence?: RecordingSourceEvidence;
+ allowObservedDuration?: boolean;
abortSignal?: AbortSignal;
timeoutMs?: number;
}
@@ -46,17 +50,52 @@ export interface RecordingVerificationResult {
fullDecode: true;
video: DecodedVideoEvidence;
audio: DecodedAudioEvidence | null;
+ integrity?: RecordingIntegrity;
+ sourcePreserved?: true;
+}
+
+interface StreamIntegrity {
+ contentSha256: string;
+ timelineSha256: string;
+ format: string;
+}
+
+interface RecordingIntegrity {
+ video: StreamIntegrity;
+ audio: StreamIntegrity | null;
+}
+
+export interface RecordingSourceEvidence extends RecordingVerificationResult {
+ integrity: RecordingIntegrity;
}
export interface RemoteRecordingVerificationOptions
extends RecordingVerificationOptions {
expectedObjectIdentity?: string;
+ expectedSha256?: string;
+ expectedFileSize?: number;
+ hashContent?: boolean;
}
export interface RemoteRecordingVerificationResult
extends RecordingVerificationResult {
objectIdentity: string;
fileSize: number;
+ remoteSha256?: string;
+}
+
+export interface RemoteRecordingBytesOptions {
+ expectedObjectIdentity: string;
+ expectedSha256: string;
+ expectedFileSize: number;
+ abortSignal?: AbortSignal;
+ timeoutMs?: number;
+}
+
+export interface RemoteRecordingBytesResult {
+ objectIdentity: string;
+ fileSize: number;
+ remoteSha256: string;
}
interface DecodedStream {
@@ -69,6 +108,10 @@ interface DecodedStream {
endTime: number;
previousTime: number;
maximumGap: number;
+ timeline: Hash;
+ contentSha256?: string;
+ format: string[];
+ previousAudioOffset: number;
}
function positiveNumber(value: number): boolean {
@@ -86,7 +129,18 @@ function streamEvidence(stream: DecodedStream): DecodedVideoEvidence {
function decodeLine(line: string, streams: Map<number, DecodedStream>): void {
if (!line) return;
- const metadata = line.match(/^#(tb|media_type|sample_rate) (\d+):\s*(.+)$/);
+ const digest = line.match(/^(\d+),(v|a),SHA256=([a-f0-9]{64})$/);
+ if (digest) {
+ const stream = streams.get(Number(digest[1]));
+ if (!stream || stream.contentSha256) {
+ throw new Error("Invalid decoded recording content digest");
+ }
+ stream.contentSha256 = digest[3];
+ return;
+ }
+ const metadata = line.match(
+ /^#(tb|media_type|sample_rate|dimensions|sar|channel_layout_name) (\d+):\s*(.+)$/,
+ );
if (metadata) {
const index = Number(metadata[2]);
if (index > 1) throw new Error("Unexpected decoded recording stream");
@@ -97,6 +151,9 @@ function decodeLine(line: string, streams: Map<number, DecodedStream>): void {
endTime: Number.NEGATIVE_INFINITY,
previousTime: Number.NEGATIVE_INFINITY,
maximumGap: 0,
+ timeline: createHash("sha256"),
+ format: [],
+ previousAudioOffset: 0,
};
streams.set(index, stream);
if (metadata[1] === "tb") {
@@ -113,11 +170,13 @@ function decodeLine(line: string, streams: Map<number, DecodedStream>): void {
throw new Error("Invalid decoded recording stream type");
}
stream.kind = metadata[3];
- } else {
+ } else if (metadata[1] === "sample_rate") {
stream.sampleRate = Number(metadata[3]);
if (!Number.isSafeInteger(stream.sampleRate) || stream.sampleRate <= 0) {
throw new Error("Invalid decoded recording sample rate");
}
+ } else {
+ stream.format.push(`${metadata[1]}:${metadata[3]}`);
}
return;
}
@@ -127,7 +186,7 @@ function decodeLine(line: string, streams: Map<number, DecodedStream>): void {
if (
columns.length < 6 ||
![index, dts, pts, ticks, bytes].every(Number.isSafeInteger) ||
- !/^[a-f0-9]{8}$/i.test(columns[5]) ||
+ !/^0x[a-f0-9]{8}$/i.test(columns[5]) ||
ticks <= 0 ||
bytes <= 0
) {
@@ -151,6 +210,11 @@ function decodeLine(line: string, streams: Map<number, DecodedStream>): void {
stream.endTime = Math.max(stream.endTime, endTime);
stream.previousTime = startTime;
stream.frameCount++;
+ if (stream.kind === "video") {
+ stream.timeline.update(
+ `${Math.round((startTime - stream.startTime) * 1e9)},${Math.round(duration * 1e9)},${bytes}\n`,
+ );
+ }
if (stream.kind === "audio") {
if (!stream.sampleRate) {
throw new Error("Decoded recording audio has no sample rate");
@@ -162,6 +226,13 @@ function decodeLine(line: string, streams: Map<number, DecodedStream>): void {
) {
throw new Error("Invalid decoded recording sample count");
}
+ const offset = Math.round(
+ (startTime - stream.startTime) * stream.sampleRate - stream.sampleCount,
+ );
+ if (offset !== stream.previousAudioOffset) {
+ stream.timeline.update(`${stream.sampleCount},${offset}\n`);
+ stream.previousAudioOffset = offset;
+ }
stream.sampleCount += Math.round(samples);
}
}
@@ -218,20 +289,19 @@ async function readDecoderErrors(
function validateEvidence(
streams: Map<number, DecodedStream>,
options: RecordingVerificationOptions,
-): RecordingVerificationResult {
+ inspectingSource: boolean,
+): RecordingSourceEvidence {
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 (
+ !options.sourceEvidence &&
+ options.expectedDuration !== undefined &&
Math.abs(videoEvidence.duration - options.expectedDuration) >
- durationTolerance
+ Math.max(0.5, Math.min(5, options.expectedDuration * 0.01))
) {
throw new Error(
"Decoded recording video does not cover its expected duration",
@@ -246,7 +316,10 @@ function validateEvidence(
decodedDuration: audio.sampleCount / audio.sampleRate,
};
}
- if (options.requireAudio) {
+ if (options.requireAudio && !audioEvidence) {
+ throw new Error("Decoded recording is missing required audio coverage");
+ }
+ if (options.requireAudio && !options.sourceEvidence && !inspectingSource) {
const tolerance = Math.min(0.5, videoEvidence.duration * 0.1);
if (
!audioEvidence ||
@@ -258,7 +331,84 @@ function validateEvidence(
throw new Error("Decoded recording is missing required audio coverage");
}
}
- return { fullDecode: true, video: videoEvidence, audio: audioEvidence };
+ const integrity = (stream: DecodedStream): StreamIntegrity => {
+ if (!stream.contentSha256) {
+ throw new Error("Decoded recording content digest is missing");
+ }
+ return {
+ contentSha256: stream.contentSha256,
+ timelineSha256: stream.timeline.digest("hex"),
+ format: stream.format.join(";"),
+ };
+ };
+ const result: RecordingSourceEvidence = {
+ fullDecode: true,
+ video: videoEvidence,
+ audio: audioEvidence,
+ integrity: {
+ video: integrity(video),
+ audio: audioEvidence && audio ? integrity(audio) : null,
+ },
+ };
+ if (options.sourceEvidence) {
+ assertSourcePreserved(options.sourceEvidence, result);
+ result.sourcePreserved = true;
+ }
+ return result;
+}
+
+function assertSourcePreserved(
+ source: RecordingSourceEvidence,
+ output: RecordingSourceEvidence,
+): void {
+ const sameIntegrity = (a: StreamIntegrity, b: StreamIntegrity) =>
+ a.contentSha256 === b.contentSha256 &&
+ a.timelineSha256 === b.timelineSha256 &&
+ a.format === b.format;
+ if (
+ source.video.frameCount !== output.video.frameCount ||
+ !sameIntegrity(source.integrity.video, output.integrity.video)
+ ) {
+ throw new Error("Recording output does not preserve source video");
+ }
+ if (Boolean(source.audio) !== Boolean(output.audio)) {
+ throw new Error("Recording output does not preserve source audio");
+ }
+ if (source.audio && output.audio) {
+ if (
+ !source.integrity.audio ||
+ !output.integrity.audio ||
+ source.audio.sampleRate !== output.audio.sampleRate ||
+ source.audio.sampleCount !== output.audio.sampleCount ||
+ !sameIntegrity(source.integrity.audio, output.integrity.audio)
+ ) {
+ throw new Error("Recording output does not preserve source audio");
+ }
+ const sourceOffset = source.audio.startTime - source.video.startTime;
+ const outputOffset = output.audio.startTime - output.video.startTime;
+ if (Math.abs(sourceOffset - outputOffset) > 0.000_001) {
+ throw new Error("Recording output does not preserve source A/V sync");
+ }
+ }
+}
+
+export async function inspectRecordingSources(
+ videoInputPath: string,
+ audioInputPath: string | null,
+ options: Pick<RecordingVerificationOptions, "abortSignal" | "timeoutMs"> = {},
+): Promise<RecordingSourceEvidence> {
+ if (
+ !isAbsolute(videoInputPath) ||
+ (audioInputPath !== null && !isAbsolute(audioInputPath))
+ ) {
+ throw new Error("Recording sources must be local regular MP4 files");
+ }
+ return decodeRecording(
+ videoInputPath,
+ { ...options, requireAudio: audioInputPath !== null },
+ undefined,
+ audioInputPath,
+ );
}
export async function verifyRecording(
@@ -272,10 +422,16 @@ async function decodeRecording(
input: string,
options: RecordingVerificationOptions,
objectIdentity?: string,
-): Promise<RecordingVerificationResult> {
+ sourceAudioInput?: string | null,
+): Promise<RecordingSourceEvidence> {
const timeoutMs = options.timeoutMs ?? PROCESS_TIMEOUT_MS;
if (
- !positiveNumber(options.expectedDuration) ||
+ (options.expectedDuration !== undefined &&
+ !positiveNumber(options.expectedDuration)) ||
+ (options.expectedDuration === undefined &&
+ !options.sourceEvidence &&
+ !options.allowObservedDuration &&
+ sourceAudioInput === undefined) ||
!positiveNumber(timeoutMs) ||
timeoutMs > PROCESS_TIMEOUT_MS
) {
@@ -301,6 +457,9 @@ async function decodeRecording(
}
remote = true;
}
+ if (sourceAudioInput && !(await lstat(sourceAudioInput)).isFile()) {
+ throw new Error("Recording verification requires a regular MP4 file");
+ }
if (options.abortSignal?.aborted) {
throw new Error("Recording verification was cancelled");
}
@@ -310,6 +469,7 @@ async function decodeRecording(
"ffmpeg",
"-hide_banner",
"-nostdin",
+ "-copyts",
"-v",
"error",
"-xerror",
@@ -333,10 +493,25 @@ async function decodeRecording(
: []),
"-i",
input,
+ ...(sourceAudioInput
+ ? [
+ "-err_detect",
+ "explode+crccheck",
+ "-threads",
+ "1",
+ "-protocol_whitelist",
+ "file",
+ "-f",
+ "mov",
+ "-i",
+ sourceAudioInput,
+ ]
+ : []),
"-map",
"0:v:0",
- "-map",
- "0:a:0?",
+ ...(sourceAudioInput === null
+ ? []
+ : ["-map", sourceAudioInput ? "1:a:0" : "0:a:0?"]),
"-fps_mode",
"passthrough",
"-enc_time_base:v",
@@ -344,14 +519,12 @@ async function decodeRecording(
"-c:v",
"rawvideo",
"-c:a",
- "pcm_s16le",
+ "pcm_f64le",
"-threads",
"1",
"-f",
- "framehash",
- "-hash",
- "adler32",
- "-",
+ "tee",
+ "[f=framecrc]pipe:1|[f=streamhash:hash=sha256]pipe:1",
],
stdin: "ignore",
stdout: "pipe",
@@ -383,7 +556,7 @@ async function decodeRecording(
const streams = new Map<number, DecodedStream>();
const frames = readFrameEvidence(proc.stdout, streams);
const errors = readDecoderErrors(proc.stderr, input);
- let result: RecordingVerificationResult;
+ let result: RecordingSourceEvidence;
try {
if (options.abortSignal?.aborted) cancel();
const [, stderr, exitCode] = await Promise.all([
@@ -395,12 +568,13 @@ async function decodeRecording(
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,
- ),
+ Boolean(proc.signalCode) ||
+ /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|Cannot allocate memory|Resource temporarily unavailable|No space left on device/i.test(
+ stderr,
+ ),
);
}
- result = validateEvidence(streams, options);
+ result = validateEvidence(streams, options, sourceAudioInput !== undefined);
} finally {
clearTimeout(timeout);
options.abortSignal?.removeEventListener("abort", cancel);
@@ -481,6 +655,68 @@ async function readRemoteIdentity(
}
}
+async function hashRemoteRecording(
+ input: string,
+ objectIdentity: string,
+ fileSize: number,
+ abortSignal: AbortSignal,
+): Promise<string> {
+ let response: Response;
+ try {
+ response = await fetch(input, {
+ headers: {
+ "If-Match": objectIdentity,
+ "X-Cap-Recording-Verification": "1",
+ },
+ signal: abortSignal,
+ });
+ } catch {
+ throw new RecordingVerificationError(
+ "Recording bytes could not be read",
+ true,
+ );
+ }
+ try {
+ if (response.status !== 200) {
+ throw new RecordingVerificationError(
+ `Recording byte verification failed: ${response.status}`,
+ response.status === 408 ||
+ response.status === 429 ||
+ response.status >= 500,
+ );
+ }
+ if (response.headers.get("etag") !== objectIdentity || !response.body) {
+ throw new Error("Recording object changed during byte verification");
+ }
+ const hash = createHash("sha256");
+ let bytesRead = 0;
+ try {
+ for await (const chunk of response.body) {
+ bytesRead += chunk.byteLength;
+ if (bytesRead > fileSize) {
+ throw new RecordingVerificationError(
+ "Recording object size changed during byte verification",
+ false,
+ );
+ }
+ hash.update(chunk);
+ }
+ } catch (error) {
+ if (error instanceof RecordingVerificationError) throw error;
+ throw new RecordingVerificationError(
+ "Recording bytes could not be read completely",
+ true,
+ );
+ }
+ if (bytesRead !== fileSize) {
+ throw new Error("Recording object size changed during byte verification");
+ }
+ return hash.digest("hex");
+ } finally {
+ if (!response.body?.locked) await response.body?.cancel().catch(() => {});
+ }
+}
+
export async function verifyRemoteRecording(
input: string,
options: RemoteRecordingVerificationOptions,
@@ -490,7 +726,16 @@ export async function verifyRemoteRecording(
!Number.isSafeInteger(timeoutMs) ||
timeoutMs <= 0 ||
timeoutMs > PROCESS_TIMEOUT_MS ||
- !positiveNumber(options.expectedDuration)
+ (options.expectedDuration !== undefined &&
+ !positiveNumber(options.expectedDuration)) ||
+ (options.expectedDuration === undefined &&
+ !options.sourceEvidence &&
+ !options.allowObservedDuration) ||
+ (options.expectedFileSize !== undefined &&
+ (!Number.isSafeInteger(options.expectedFileSize) ||
+ options.expectedFileSize <= 0)) ||
+ (options.expectedSha256 !== undefined &&
+ !/^[a-f0-9]{64}$/.test(options.expectedSha256))
) {
throw new Error("Invalid recording verification budget or duration");
}
@@ -525,6 +770,12 @@ export async function verifyRemoteRecording(
signal,
options.expectedObjectIdentity,
);
+ if (
+ options.expectedFileSize !== undefined &&
+ before.fileSize !== options.expectedFileSize
+ ) {
+ throw new Error("Uploaded recording size does not match the muxed file");
+ }
const remainingMs = timeoutMs - (performance.now() - startedAt);
if (remainingMs <= 0) {
throw new RecordingVerificationError(
@@ -537,6 +788,18 @@ export async function verifyRemoteRecording(
{ ...options, abortSignal: signal, timeoutMs: remainingMs },
before.objectIdentity,
);
+ const remoteSha256 =
+ options.expectedSha256 || options.hashContent
+ ? await hashRemoteRecording(
+ input,
+ before.objectIdentity,
+ before.fileSize,
+ signal,
+ )
+ : undefined;
+ if (options.expectedSha256 && remoteSha256 !== options.expectedSha256) {
+ throw new Error("Uploaded recording bytes do not match the muxed file");
+ }
const after = await readRemoteIdentity(
input,
signal,
@@ -546,7 +809,7 @@ export async function verifyRemoteRecording(
throw new Error("Recording object changed during verification");
}
if (signal.aborted) throw new Error("Recording verification was cancelled");
- return { ...evidence, ...after };
+ return { ...evidence, ...after, ...(remoteSha256 ? { remoteSha256 } : {}) };
} catch (error) {
if (options.abortSignal?.aborted) {
throw new Error("Recording verification was cancelled");
@@ -562,3 +825,93 @@ export async function verifyRemoteRecording(
clearTimeout(timeout);
}
}
+
+export async function verifyRemoteRecordingBytes(
+ input: string,
+ options: RemoteRecordingBytesOptions,
+): Promise<RemoteRecordingBytesResult> {
+ const timeoutMs = options.timeoutMs ?? PROCESS_TIMEOUT_MS;
+ if (
+ !Number.isSafeInteger(timeoutMs) ||
+ timeoutMs <= 0 ||
+ timeoutMs > PROCESS_TIMEOUT_MS ||
+ !Number.isSafeInteger(options.expectedFileSize) ||
+ options.expectedFileSize <= 0 ||
+ !/^[a-f0-9]{64}$/.test(options.expectedSha256) ||
+ !isStrongObjectIdentity(options.expectedObjectIdentity)
+ ) {
+ throw new Error("Invalid recording byte verification expectations");
+ }
+ 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",
+ );
+ }
+ const deadline = new AbortController();
+ 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,
+ );
+ if (before.fileSize !== options.expectedFileSize) {
+ throw new Error("Uploaded recording size does not match the muxed file");
+ }
+ const remoteSha256 = await hashRemoteRecording(
+ input,
+ before.objectIdentity,
+ before.fileSize,
+ signal,
+ );
+ if (remoteSha256 !== options.expectedSha256) {
+ throw new Error("Uploaded recording bytes do not match the muxed file");
+ }
+ 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 { ...after, remoteSha256 };
+ } 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);
+ }
+}
+
+export async function hashRecordingFile(
+ input: string,
+ abortSignal?: AbortSignal,
+): Promise<string> {
+ if (!isAbsolute(input) || !(await lstat(input)).isFile()) {
+ throw new Error("Recording hashing requires a local regular file");
+ }
+ const hash = createHash("sha256");
+ for await (const chunk of createReadStream(input, { signal: abortSignal })) {
+ hash.update(chunk);
+ }
+ return hash.digest("hex");
+}
diff --git a/apps/media-server/src/routes/video.ts b/apps/media-server/src/routes/video.ts
index b81bddab7..fa6b05b1d 100644
--- a/apps/media-server/src/routes/video.ts
+++ b/apps/media-server/src/routes/video.ts
@@ -1,9 +1,11 @@
+import { createHash } from "node:crypto";
import { file } from "bun";
import { Hono } from "hono";
import { z } from "zod";
import { validateMediaServerSecret } from "../lib/auth";
-import type { VideoMetadata } from "../lib/job-manager";
+import type { RecordingErrorCode, VideoMetadata } from "../lib/job-manager";
import {
+ beginRecordingProcessing,
beginRecordingVerification,
canAcceptNewVideoProcess,
createJob,
@@ -46,8 +48,12 @@ import {
uploadToS3,
} from "../lib/media-video";
import {
+ hashRecordingFile,
+ inspectRecordingSources,
isRetryableRecordingVerificationError,
+ verifyRecording,
verifyRemoteRecording,
+ verifyRemoteRecordingBytes,
} from "../lib/recording-verification";
import type { TempFileHandle } from "../lib/temp-files";
import { cleanupStaleTempFiles } from "../lib/temp-files";
@@ -60,6 +66,7 @@ import {
const video = new Hono();
const PROCESSING_HEARTBEAT_MS = 60 * 1000;
+const SEGMENTED_RECORDING_TIMEOUT_MS = 3 * PROCESS_TIMEOUT_MS + 35 * 60 * 1000;
const POST_VERIFICATION_ASSET_BUDGET_MS = 5 * 60 * 1000;
const RECORDING_VERIFICATION_RETRY_ERROR =
"Recording verification temporarily unavailable (503)";
@@ -1550,10 +1557,13 @@ const muxSegmentsOutputUploadSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("put"),
url: z.string().url(),
+ ifNoneMatch: z.literal("*").optional(),
}),
z.object({
type: z.literal("multipart"),
videoId: z.string(),
+ generation: z.string().min(1).max(200).optional(),
+ attemptId: z.string().min(1).max(200).optional(),
key: z.string().min(1),
uploadId: z.string().min(1),
partSize: z
@@ -1567,17 +1577,120 @@ 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(),
-});
+const strongObjectIdentitySchema = z
+ .string()
+ .max(1_024)
+ .regex(/^"[\x21\x23-\x7E\x80-\xFF]+"$/);
+const recordingAttemptFields = {
+ generation: z.string().min(1).max(200).optional(),
+ attemptId: z.string().min(1).max(200).optional(),
+ outputKey: z.string().min(1).max(1_024).optional(),
+ inventorySha256: z
+ .string()
+ .regex(/^[a-f0-9]{64}$/)
+ .optional(),
+};
+
+const recordingVerificationSchema = z
+ .object({
+ ...recordingAttemptFields,
+ 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().optional(),
+ requiredAudio: z.boolean(),
+ objectIdentity: strongObjectIdentitySchema,
+ originalObjectIdentity: strongObjectIdentitySchema.optional(),
+ sourceObjectIdentity: strongObjectIdentitySchema.optional(),
+ webhookUrl: z.string().url(),
+ webhookSecret: z.string().optional(),
+ })
+ .refine(
+ (body) => {
+ const fenced = Boolean(
+ body.generation ||
+ body.attemptId ||
+ body.outputKey ||
+ body.inventorySha256 ||
+ body.originalObjectIdentity ||
+ body.sourceObjectIdentity,
+ );
+ return fenced
+ ? Boolean(
+ body.generation &&
+ body.attemptId &&
+ body.outputKey &&
+ body.inventorySha256 &&
+ body.originalObjectIdentity &&
+ body.sourceObjectIdentity,
+ )
+ : body.duration !== undefined;
+ },
+ { message: "Complete recording attempt context is required" },
+ );
+
+function recordingJobId(
+ kind: string,
+ body: {
+ userId: string;
+ videoId: string;
+ generation?: string;
+ attemptId?: string;
+ },
+): string {
+ return body.generation && body.attemptId
+ ? `job_recording_${createHash("sha256")
+ .update(
+ JSON.stringify([
+ kind,
+ body.userId,
+ body.videoId,
+ body.generation,
+ body.attemptId,
+ ]),
+ )
+ .digest("hex")}`
+ : generateJobId();
+}
+
+function recordingRequestKey(values: unknown[]): string {
+ return createHash("sha256").update(JSON.stringify(values)).digest("hex");
+}
+
+function classifySourceError(error: unknown): RecordingErrorCode {
+ if (
+ isRetryableRecordingVerificationError(error) ||
+ isBusyError(error) ||
+ isTimeoutError(error)
+ )
+ return "processing-unavailable";
+ if (!(error instanceof Error)) return "processing-unavailable";
+ if (
+ /Cannot allocate memory|Resource temporarily unavailable|No space left|Unknown encoder|Unknown decoder|Permission denied|Function not implemented|Option not found/i.test(
+ error.message,
+ )
+ )
+ return "processing-unavailable";
+ if (/object changed|HTTP error 412|Server returned 412/.test(error.message))
+ return "source-changed";
+ if (/HTTP error 404|Server returned 404/.test(error.message))
+ return "source-missing";
+ if (
+ /Decoded recording|Invalid decoded recording|Recording has no decoded|does not match the completed local file|Verified recording size/.test(
+ error.message,
+ )
+ )
+ return "source-invalid";
+ if (
+ error.message.includes("Recording full decode failed") &&
+ /invalid|corrupt|error while decoding|moov atom not found|Cannot determine format.*EOF|partial file/i.test(
+ error.message,
+ )
+ )
+ return "source-invalid";
+ return "processing-unavailable";
+}
video.post("/verify-recording", async (c) => {
if (!validateMediaServerSecret(c))
@@ -1585,12 +1698,27 @@ video.post("/verify-recording", async (c) => {
const parsed = recordingVerificationSchema.safeParse(await c.req.json());
if (!parsed.success)
return c.json({ error: "Invalid verification request" }, 400);
+ const body = parsed.data;
+ const jobId = recordingJobId("mp4", body);
+ const requestKey = recordingRequestKey([
+ body.fileSize,
+ body.duration,
+ body.requiredAudio,
+ body.originalObjectIdentity,
+ body.sourceObjectIdentity,
+ body.outputKey,
+ body.inventorySha256,
+ ]);
+ const existing = getJob(jobId);
+ if (existing) {
+ if (existing.recordingRequestKey !== requestKey)
+ return c.json({ error: "Recording attempt context changed" }, 409);
+ return c.json({ jobId });
+ }
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,
@@ -1598,6 +1726,12 @@ video.post("/verify-recording", async (c) => {
body.webhookUrl,
body.webhookSecret,
);
+ updateJob(jobId, {
+ generation: body.generation,
+ attemptId: body.attemptId,
+ inventorySha256: body.inventorySha256,
+ recordingRequestKey: requestKey,
+ });
void verifyUploadedRecordingAsync(jobId, body);
return c.json({ jobId });
});
@@ -1614,7 +1748,8 @@ async function verifyUploadedRecordingAsync(
});
if (
metadata.fileSize !== body.fileSize ||
- !isDurationClose(metadata.duration, body.duration) ||
+ (body.duration !== undefined &&
+ !isDurationClose(metadata.duration, body.duration)) ||
(body.requiredAudio && !metadata.audioCodec)
) {
throw new Error(
@@ -1632,14 +1767,20 @@ async function verifyUploadedRecordingAsync(
withMuxMemoryGuard(abortController, () =>
verifyRemoteRecording(body.videoUrl, {
expectedDuration: body.duration,
+ allowObservedDuration: body.duration === undefined,
requireAudio: body.requiredAudio,
- expectedObjectIdentity: body.objectIdentity,
+ expectedObjectIdentity:
+ body.sourceObjectIdentity ?? body.objectIdentity,
+ expectedFileSize: body.fileSize,
+ hashContent: Boolean(body.generation),
abortSignal: abortController.signal,
}),
),
);
if (verified.fileSize !== body.fileSize)
throw new Error("Verified recording size does not match the local file");
+ if (body.generation && !verified.remoteSha256)
+ throw new Error("Recording byte identity is missing");
updateJob(jobId, {
phase: "complete",
progress: 100,
@@ -1655,13 +1796,16 @@ async function verifyUploadedRecordingAsync(
artifact: {
kind: "mp4",
fileSize: body.fileSize,
- duration: body.duration,
- objectIdentity: body.objectIdentity,
+ duration: body.duration ?? verified.video.duration,
+ objectIdentity: body.originalObjectIdentity ?? body.objectIdentity,
},
requiredAudio: body.requiredAudio,
},
fullDecode: true,
objectIdentity: verified.objectIdentity,
+ ...(body.outputKey
+ ? { outputKey: body.outputKey, outputSha256: verified.remoteSha256 }
+ : {}),
},
});
} catch (error) {
@@ -1676,15 +1820,29 @@ async function verifyUploadedRecordingAsync(
error: retryable
? RECORDING_VERIFICATION_RETRY_ERROR
: "Uploaded recording content could not be verified; retain the local recording",
+ errorCode: retryable
+ ? "processing-unavailable"
+ : classifySourceError(error),
});
}
const job = getJob(jobId);
if (job) await sendWebhook(job);
- setTimeout(() => deleteJob(jobId), 5 * 60 * 1000);
}
const muxSegmentsSchema = z
.object({
+ ...recordingAttemptFields,
+ requiredAudio: z.boolean().optional(),
+ sourceObjects: z
+ .array(
+ z.object({
+ url: z.string().url(),
+ objectIdentity: strongObjectIdentitySchema,
+ size: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
+ }),
+ )
+ .max(100_002)
+ .optional(),
manifestSha256: z
.string()
.regex(/^[a-f0-9]{64}$/)
@@ -1707,8 +1865,95 @@ const muxSegmentsSchema = z
.refine((body) => body.outputPresignedUrl || body.outputUpload, {
message: "outputPresignedUrl or outputUpload is required",
path: ["outputUpload"],
+ })
+ .superRefine((body, ctx) => {
+ const fenced = Boolean(
+ body.generation ||
+ body.attemptId ||
+ body.outputKey ||
+ body.inventorySha256 ||
+ body.sourceObjects,
+ );
+ if (
+ fenced &&
+ !(
+ body.generation &&
+ body.attemptId &&
+ body.outputKey &&
+ body.inventorySha256 &&
+ body.sourceObjects &&
+ body.manifestSha256 &&
+ body.outputVerificationUrl
+ )
+ ) {
+ ctx.addIssue({
+ code: "custom",
+ message: "Complete recording attempt context is required",
+ });
+ }
+ if (
+ Boolean(body.audioInitUrl) !== Boolean(body.audioSegmentUrls?.length) ||
+ (body.requiredAudio && !body.audioSegmentUrls?.length)
+ ) {
+ ctx.addIssue({
+ code: "custom",
+ message: "Required audio sources are incomplete",
+ });
+ }
+ if (body.sourceObjects) {
+ const urls = [
+ body.videoInitUrl,
+ ...body.videoSegmentUrls,
+ ...(body.audioInitUrl
+ ? [body.audioInitUrl, ...(body.audioSegmentUrls ?? [])]
+ : []),
+ ];
+ const indexed = new Map(
+ body.sourceObjects.map((source) => [source.url, source]),
+ );
+ if (
+ indexed.size !== body.sourceObjects.length ||
+ new Set(urls).size !== urls.length ||
+ indexed.size !== urls.length ||
+ urls.some((url) => !indexed.has(url))
+ ) {
+ ctx.addIssue({
+ code: "custom",
+ message:
+ "Recording source inventory does not exactly cover its inputs",
+ });
+ }
+ }
+ if (
+ fenced &&
+ (body.outputUpload?.type === "put"
+ ? body.outputUpload.ifNoneMatch !== "*"
+ : body.outputUpload?.type !== "multipart" ||
+ body.outputUpload.key !== body.outputKey ||
+ body.outputUpload.videoId !== body.videoId ||
+ body.outputUpload.generation !== body.generation ||
+ body.outputUpload.attemptId !== body.attemptId)
+ ) {
+ ctx.addIssue({
+ code: "custom",
+ message: "Recording candidate must use an immutable upload target",
+ });
+ }
});
+type MuxSourceObject = NonNullable<
+ z.infer<typeof muxSegmentsSchema>["sourceObjects"]
+>[number];
+type MuxContext = Pick<
+ z.infer<typeof muxSegmentsSchema>,
+ | "generation"
+ | "attemptId"
+ | "outputKey"
+ | "inventorySha256"
+ | "sourceObjects"
+ | "requiredAudio"
+>;
+
function getMuxSegmentsOutputUpload(
body: z.infer<typeof muxSegmentsSchema>,
): StorageUploadTarget {
@@ -1740,7 +1985,19 @@ video.post("/mux-segments", async (c) => {
webhookUrl,
webhookSecret,
} = body.data;
- const jobId = generateJobId();
+ const jobId = recordingJobId("segments", body.data);
+ const requestKey = recordingRequestKey([
+ body.data.manifestSha256,
+ body.data.inventorySha256,
+ body.data.outputKey,
+ body.data.requiredAudio,
+ ]);
+ const existing = getJob(jobId);
+ if (existing) {
+ if (existing.recordingRequestKey !== requestKey)
+ return c.json({ error: "Recording attempt context changed" }, 409);
+ return c.json({ jobId, status: "queued", videoId });
+ }
if (!canAcceptNewVideoProcess()) {
c.header("Retry-After", VIDEO_BUSY_RETRY_AFTER_SECONDS.toString());
@@ -1756,7 +2013,13 @@ video.post("/mux-segments", async (c) => {
audioSegmentUrls: audioSegUrls,
} = body.data;
const outputUpload = getMuxSegmentsOutputUpload(body.data);
- updateJob(jobId, { manifestSha256: body.data.manifestSha256 });
+ updateJob(jobId, {
+ manifestSha256: body.data.manifestSha256,
+ generation: body.data.generation,
+ attemptId: body.data.attemptId,
+ inventorySha256: body.data.inventorySha256,
+ recordingRequestKey: requestKey,
+ });
muxSegmentsAsync(
jobId,
@@ -1768,8 +2031,8 @@ video.post("/mux-segments", async (c) => {
videoSegUrls,
audioInitUrl ?? null,
audioSegUrls ?? null,
- body.data.expectedDuration,
body.data.outputVerificationUrl,
+ body.data,
).catch((err) => {
console.error(`[mux-segments] Async mux error for job ${jobId}:`, err);
const currentJob = getJob(jobId);
@@ -1796,6 +2059,7 @@ video.post("/mux-segments", async (c) => {
async function streamConcatFiles(
inputPaths: string[],
outputPath: string,
+ abortSignal?: AbortSignal,
): Promise<void> {
const writer = file(outputPath).writer();
let lastMemoryCheckAt = 0;
@@ -1804,9 +2068,11 @@ async function streamConcatFiles(
const reader = file(filePath).stream().getReader();
try {
while (true) {
+ abortSignal?.throwIfAborted();
const { done, value } = await reader.read();
if (done) break;
- writer.write(value);
+ await writer.write(value);
+ await writer.flush();
const now = Date.now();
if (now - lastMemoryCheckAt >= 1000) {
lastMemoryCheckAt = now;
@@ -1816,6 +2082,7 @@ async function streamConcatFiles(
}
}
} finally {
+ await reader.cancel().catch(() => {});
reader.releaseLock();
}
}
@@ -1837,6 +2104,7 @@ class MediaDownloadError extends Error {
constructor(
message: string,
readonly retryable: boolean,
+ readonly errorCode: RecordingErrorCode = "processing-unavailable",
) {
super(message);
}
@@ -1858,10 +2126,17 @@ async function downloadUrlToFileOnce(
url: string,
destPath: string,
abortSignal?: AbortSignal,
+ source?: MuxSourceObject,
): Promise<void> {
const abortController = new AbortController();
const timeoutSignal = AbortSignal.timeout(120_000);
const resp = await fetch(url, {
+ headers: source
+ ? {
+ "If-Match": source.objectIdentity,
+ "X-Cap-Recording-Verification": "1",
+ }
+ : undefined,
signal: abortSignal
? AbortSignal.any([abortController.signal, abortSignal, timeoutSignal])
: AbortSignal.any([abortController.signal, timeoutSignal]),
@@ -1870,7 +2145,27 @@ async function downloadUrlToFileOnce(
await resp.body?.cancel().catch(() => {});
throw new MediaDownloadError(
`Download failed (${resp.status}): ${redactPresignedUrl(url)}`,
- isRetryableDownloadStatus(resp.status),
+ isRetryableDownloadStatus(resp.status) ||
+ (Boolean(source) && resp.status === 404),
+ source && resp.status === 412
+ ? "source-changed"
+ : source && resp.status === 404
+ ? "source-missing"
+ : "processing-unavailable",
+ );
+ }
+ if (
+ source &&
+ (resp.status !== 200 ||
+ resp.headers.get("etag") !== source.objectIdentity ||
+ (resp.headers.has("content-length") &&
+ Number(resp.headers.get("content-length")) !== source.size))
+ ) {
+ await resp.body?.cancel().catch(() => {});
+ throw new MediaDownloadError(
+ "Recording source object changed while downloading",
+ false,
+ "source-changed",
);
}
if (!resp.body) {
@@ -1884,11 +2179,20 @@ async function downloadUrlToFileOnce(
const writer = file(destPath).writer();
let lastMemoryCheckAt = 0;
let failure: unknown;
+ let bytesRead = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
- writer.write(value);
+ bytesRead += value.byteLength;
+ if (source && bytesRead > source.size)
+ throw new MediaDownloadError(
+ "Recording source size changed while downloading",
+ false,
+ "source-changed",
+ );
+ await writer.write(value);
+ await writer.flush();
const now = Date.now();
if (now - lastMemoryCheckAt >= 1000) {
lastMemoryCheckAt = now;
@@ -1897,6 +2201,12 @@ async function downloadUrlToFileOnce(
}
}
}
+ if (source && bytesRead !== source.size)
+ throw new MediaDownloadError(
+ "Recording source size changed while downloading",
+ false,
+ "source-changed",
+ );
} catch (error) {
failure = error;
abortController.abort();
@@ -1923,13 +2233,14 @@ async function downloadUrlToFile(
url: string,
destPath: string,
abortSignal?: AbortSignal,
+ source?: MuxSourceObject,
): Promise<void> {
let lastError: Error | undefined;
for (let attempt = 0; attempt < SEGMENT_DOWNLOAD_MAX_ATTEMPTS; attempt++) {
abortSignal?.throwIfAborted();
try {
- await downloadUrlToFileOnce(url, destPath, abortSignal);
+ await downloadUrlToFileOnce(url, destPath, abortSignal, source);
return;
} catch (error) {
if (abortSignal?.aborted) throw error;
@@ -1957,6 +2268,8 @@ async function downloadSegmentsBatchTracked(
jobId: string,
progressBase: number,
progressRange: number,
+ abortSignal?: AbortSignal,
+ sources?: Map<string, MuxSourceObject>,
): Promise<string[]> {
const { join } = await import("node:path");
let completed = 0;
@@ -1967,6 +2280,9 @@ async function downloadSegmentsBatchTracked(
const pending = [...urls.entries()];
let pendingIndex = 0;
const batchAbortController = new AbortController();
+ const batchSignal = abortSignal
+ ? AbortSignal.any([abortSignal, batchAbortController.signal])
+ : batchAbortController.signal;
const CONCURRENCY = 10;
async function worker() {
@@ -1980,7 +2296,12 @@ async function downloadSegmentsBatchTracked(
`segment_${String(i + 1).padStart(indexWidth, "0")}.m4s`,
);
outputPaths[i] = outputPath;
- await downloadUrlToFile(url, outputPath, batchAbortController.signal);
+ await downloadUrlToFile(
+ url,
+ outputPath,
+ batchSignal,
+ sources?.get(url),
+ );
} catch (err) {
if (!fatalError) {
fatalError = err instanceof Error ? err : new Error(String(err));
@@ -2030,11 +2351,11 @@ async function muxSegmentsAsync(
videoSegmentUrls: string[],
audioInitUrl: string | null,
audioSegmentUrls: string[] | null,
- expectedDuration?: number,
outputVerificationUrl?: string,
+ context: MuxContext = {},
): Promise<void> {
const { ensureTempDir } = await import("../lib/temp-files");
- const { mkdir, rm } = await import("node:fs/promises");
+ const { lstat, mkdir, rm } = await import("node:fs/promises");
const { join } = await import("node:path");
const workDir = join(
@@ -2045,9 +2366,21 @@ async function muxSegmentsAsync(
const abortController = new AbortController();
updateJob(jobId, { abortController });
let outputUploadStarted = false;
+ let processingTimeout: ReturnType<typeof setTimeout> | undefined;
+ let errorCode: RecordingErrorCode = "processing-unavailable";
+ const sources = context.sourceObjects
+ ? new Map(context.sourceObjects.map((source) => [source.url, source]))
+ : undefined;
const startedAt = Date.now();
try {
+ if (!beginRecordingProcessing(jobId, SEGMENTED_RECORDING_TIMEOUT_MS))
+ throw new Error("Recording processing job is no longer active");
+ processingTimeout = setTimeout(() => {
+ errorCode = "processing-unavailable";
+ abortController.abort(new Error("Recording processing timed out"));
+ }, SEGMENTED_RECORDING_TIMEOUT_MS);
+ processingTimeout.unref?.();
logVideoEvent("video_mux_started", {
jobId,
videoId,
@@ -2065,7 +2398,12 @@ async function muxSegmentsAsync(
await mkdir(videoDir, { recursive: true });
await mkdir(audioDir, { recursive: true });
- await downloadUrlToFile(videoInitUrl, join(videoDir, "init.mp4"));
+ await downloadUrlToFile(
+ videoInitUrl,
+ join(videoDir, "init.mp4"),
+ abortController.signal,
+ sources?.get(videoInitUrl),
+ );
updateJob(jobId, { phase: "downloading", progress: 5 });
sendCurrentJobWebhook(jobId);
@@ -2075,6 +2413,8 @@ async function muxSegmentsAsync(
jobId,
5,
45,
+ abortController.signal,
+ sources,
);
const audioInput =
@@ -2085,13 +2425,20 @@ async function muxSegmentsAsync(
: null;
let audioSegmentFiles: string[] = [];
if (audioInput) {
- await downloadUrlToFile(audioInput.initUrl, join(audioDir, "init.mp4"));
+ await downloadUrlToFile(
+ audioInput.initUrl,
+ join(audioDir, "init.mp4"),
+ abortController.signal,
+ sources?.get(audioInput.initUrl),
+ );
audioSegmentFiles = await downloadSegmentsBatchTracked(
audioInput.segmentUrls,
audioDir,
jobId,
50,
10,
+ abortController.signal,
+ sources,
);
}
@@ -2104,6 +2451,7 @@ async function muxSegmentsAsync(
await streamConcatFiles(
[videoInitPath, ...videoSegmentFiles],
combinedVideoPath,
+ abortController.signal,
);
await rm(videoDir, { recursive: true, force: true });
@@ -2116,6 +2464,7 @@ async function muxSegmentsAsync(
await streamConcatFiles(
[audioInitPath, ...audioSegmentFiles],
combinedAudioPath,
+ abortController.signal,
);
await rm(audioDir, { recursive: true, force: true });
}
@@ -2131,15 +2480,57 @@ async function muxSegmentsAsync(
resources: getSystemResources(),
});
+ const sourceEvidence = await withJobHeartbeat(jobId, () =>
+ withMuxMemoryGuard(abortController, () =>
+ inspectRecordingSources(combinedVideoPath, combinedAudioPath, {
+ abortSignal: abortController.signal,
+ }),
+ ),
+ ).catch((error: unknown) => {
+ errorCode = classifySourceError(error);
+ throw error;
+ });
+ const requiredAudio = context.requiredAudio ?? Boolean(audioInput);
const resultPath = join(workDir, "result.mp4");
- await withMuxMemoryGuard(abortController, () =>
- muxMediaTracksToMp4(
- combinedVideoPath,
- combinedAudioPath,
- resultPath,
- abortController.signal,
+ errorCode = "output-invalid";
+ await withJobHeartbeat(jobId, () =>
+ withMuxMemoryGuard(abortController, () =>
+ muxMediaTracksToMp4(
+ combinedVideoPath,
+ combinedAudioPath,
+ resultPath,
+ abortController.signal,
+ ),
+ ),
+ );
+ const beforeDecode = await lstat(resultPath, { bigint: true });
+ if (!beforeDecode.isFile())
+ throw new Error("Recording verification requires a local regular file");
+ const localVerified = await withJobHeartbeat(jobId, () =>
+ withMuxMemoryGuard(abortController, () =>
+ verifyRecording(resultPath, {
+ requireAudio: requiredAudio,
+ sourceEvidence,
+ abortSignal: abortController.signal,
+ }),
),
);
+ if (!localVerified.sourcePreserved)
+ throw new Error("Recording source preservation was not verified");
+ const outputSha256 = await withJobHeartbeat(jobId, () =>
+ hashRecordingFile(resultPath, abortController.signal),
+ );
+ const afterHash = await lstat(resultPath, { bigint: true });
+ if (
+ !afterHash.isFile() ||
+ beforeDecode.dev !== afterHash.dev ||
+ beforeDecode.ino !== afterHash.ino ||
+ beforeDecode.size !== afterHash.size ||
+ beforeDecode.mtimeNs !== afterHash.mtimeNs ||
+ beforeDecode.ctimeNs !== afterHash.ctimeNs
+ ) {
+ throw new Error("Local recording changed during verification");
+ }
await rm(combinedVideoPath, { force: true });
if (combinedAudioPath) {
await rm(combinedAudioPath, { force: true });
@@ -2161,26 +2552,31 @@ async function muxSegmentsAsync(
metadata.width <= 0 ||
metadata.height <= 0 ||
!metadata.videoCodec ||
- (audioInput && !metadata.audioCodec) ||
- (expectedDuration !== undefined &&
- !isDurationClose(metadata.duration, expectedDuration))
+ (audioInput && !metadata.audioCodec)
) {
throw new Error(
"Muxed recording is incomplete or missing a required track",
);
}
+ metadata = { ...metadata, duration: localVerified.video.duration };
updateJob(jobId, { phase: "uploading", progress: 80 });
sendCurrentJobWebhook(jobId);
outputUploadStarted = true;
- const uploadReceipt = await uploadFileToStorage(
- resultPath,
- outputUpload,
- "video/mp4",
+ errorCode = "processing-unavailable";
+ const uploadReceipt = await withJobHeartbeat(jobId, () =>
+ uploadFileToStorage(
+ resultPath,
+ outputUpload,
+ "video/mp4",
+ abortController.signal,
+ ),
);
if (outputVerificationUrl) {
- if (!uploadReceipt.objectIdentity)
+ errorCode = "output-invalid";
+ const uploadObjectIdentity = uploadReceipt.objectIdentity;
+ if (!uploadObjectIdentity)
throw new Error("Recording upload did not return an object identity");
if (
!beginRecordingVerification(
@@ -2189,16 +2585,19 @@ async function muxSegmentsAsync(
)
)
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,
- }),
- ),
+ const remoteBytes = await withJobHeartbeat(jobId, () =>
+ verifyRemoteRecordingBytes(outputVerificationUrl, {
+ expectedSha256: outputSha256,
+ expectedFileSize: metadata.fileSize,
+ expectedObjectIdentity: uploadObjectIdentity,
+ abortSignal: abortController.signal,
+ }),
);
+ const verified = { ...localVerified, ...remoteBytes };
+ if (!verified.sourcePreserved || verified.remoteSha256 !== outputSha256)
+ throw new Error(
+ "Uploaded recording source preservation was not verified",
+ );
if (verified.fileSize !== metadata.fileSize)
throw new Error(
"Uploaded recording size does not match the muxed file",
@@ -2216,10 +2615,25 @@ async function muxSegmentsAsync(
request: {
version: 1,
artifact: { kind: "segments", manifestSha256 },
- requiredAudio: Boolean(audioInput),
+ requiredAudio,
},
fullDecode: true,
objectIdentity: verified.objectIdentity,
+ ...(context.outputKey && context.inventorySha256
+ ? {
+ outputKey: context.outputKey,
+ outputSha256: verified.remoteSha256,
+ sourceProof: {
+ version: 1 as const,
+ manifestSha256,
+ inventorySha256: context.inventorySha256,
+ sourcePreserved: true as const,
+ videoDuration: sourceEvidence.video.duration,
+ hasAudio: Boolean(sourceEvidence.audio),
+ audioVerified: Boolean(sourceEvidence.audio),
+ },
+ }
+ : {}),
},
});
}
@@ -2255,6 +2669,7 @@ async function muxSegmentsAsync(
"mux-segments",
);
+ abortController.signal.throwIfAborted();
updateJob(jobId, {
phase: "complete",
progress: 100,
@@ -2268,8 +2683,6 @@ async function muxSegmentsAsync(
metadata,
resources: getSystemResources(),
});
-
- setTimeout(() => deleteJob(jobId), 5 * 60 * 1000);
} catch (error: unknown) {
logVideoEvent("video_mux_failed", {
jobId,
@@ -2288,7 +2701,18 @@ async function muxSegmentsAsync(
}
console.error(`Mux-segments job ${jobId} failed:`, error);
updateJob(jobId, {
- phase: "error",
+ phase:
+ abortController.signal.aborted && !isBusyError(error)
+ ? "cancelled"
+ : "error",
+ errorCode:
+ error instanceof MediaDownloadError
+ ? error.errorCode
+ : isRetryableRecordingVerificationError(error) ||
+ isBusyError(error) ||
+ isTimeoutError(error)
+ ? "processing-unavailable"
+ : errorCode,
error: isRetryableRecordingVerificationError(error)
? "Recording verification temporarily unavailable (503)"
: error instanceof Error
@@ -2297,6 +2721,7 @@ async function muxSegmentsAsync(
});
sendCurrentJobWebhook(jobId);
} finally {
+ if (processingTimeout) clearTimeout(processingTimeout);
await rm(workDir, { recursive: true, force: true }).catch(() => {});
}
}