Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: require verified upload receipts before desktop cleanup

Richie McIlroy8e644830295c
diff --git a/apps/web/__tests__/unit/desktop-recording-job-status.test.ts b/apps/web/__tests__/unit/desktop-recording-job-status.test.ts
new file mode 100644
index 000000000..b9443bf43
--- /dev/null
+++ b/apps/web/__tests__/unit/desktop-recording-job-status.test.ts
@@ -0,0 +1,72 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { reconcileDesktopRecordingJob } from "@/lib/desktop-recording-job-status";
+
+const input = {
+ videoId: "video",
+ jobId: "job",
+ mediaServerUrl: "https://media.cap.test",
+ webhookUrl:
+ "https://cap.test/api/webhooks/media-server/progress?retryable=true",
+ secret: "test-secret",
+};
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe("recording job completion reconciliation", () => {
+ it("redelivers a lost completion through the validated webhook", async () => {
+ const proof = {
+ request: { version: 1 },
+ fullDecode: true,
+ objectIdentity: '"object"',
+ };
+ const payload = {
+ jobId: "job",
+ videoId: "video",
+ phase: "complete",
+ recordingVerification: proof,
+ };
+ const fetcher = vi
+ .fn()
+ .mockResolvedValueOnce(Response.json(payload))
+ .mockResolvedValueOnce(Response.json({ success: true }));
+ vi.stubGlobal("fetch", fetcher);
+ expect(await reconcileDesktopRecordingJob(input)).toBe(true);
+ expect(fetcher).toHaveBeenLastCalledWith(
+ input.webhookUrl,
+ expect.objectContaining({
+ body: JSON.stringify(payload),
+ method: "POST",
+ }),
+ );
+ });
+
+ it.each([
+ { jobId: "other", videoId: "video", phase: "complete" },
+ { jobId: "job", videoId: "other", phase: "complete" },
+ { jobId: "job", videoId: "video", phase: "processing" },
+ ])(
+ "does not complete from an unrelated or unfinished job %j",
+ async (payload) => {
+ const fetcher = vi.fn().mockResolvedValueOnce(Response.json(payload));
+ vi.stubGlobal("fetch", fetcher);
+ expect(await reconcileDesktopRecordingJob(input)).toBe(false);
+ expect(fetcher).toHaveBeenCalledOnce();
+ },
+ );
+
+ it("retains pending state when the media server cannot be reached", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("offline")));
+ expect(await reconcileDesktopRecordingJob(input)).toBe(false);
+ });
+
+ it("does not acknowledge completion if the webhook rejects its proof", async () => {
+ const fetcher = vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json({ jobId: "job", videoId: "video", phase: "complete" }),
+ )
+ .mockResolvedValueOnce(new Response(null, { status: 503 }));
+ vi.stubGlobal("fetch", fetcher);
+ expect(await reconcileDesktopRecordingJob(input)).toBe(false);
+ });
+});
diff --git a/apps/web/__tests__/unit/desktop-recording-verification.test.ts b/apps/web/__tests__/unit/desktop-recording-verification.test.ts
new file mode 100644
index 000000000..ea6fa2104
--- /dev/null
+++ b/apps/web/__tests__/unit/desktop-recording-verification.test.ts
@@ -0,0 +1,183 @@
+import { describe, expect, it } from "vitest";
+import {
+ assertRecordingObjectIdentity,
+ readCompletedRecordingManifest,
+ recordingUploadReceiptSchema,
+ recordingVerificationSchema,
+ validateRecordingOutput,
+} from "@/lib/desktop-recording-verification";
+
+const manifest = {
+ version: 2,
+ video_init_uploaded: true,
+ audio_init_uploaded: true,
+ video_segments: [
+ { index: 1, duration: 3 },
+ { index: 2, duration: 2 },
+ ],
+ audio_segments: [{ index: 1, duration: 5 }],
+ is_complete: true,
+};
+
+const output = {
+ fileSize: 4096,
+ duration: 5,
+ width: 1920,
+ height: 1080,
+ videoCodec: "h264",
+ audioCodec: "aac",
+};
+
+describe("desktop recording verification", () => {
+ it("binds verification to the exact final manifest bytes", () => {
+ const first = readCompletedRecordingManifest(JSON.stringify(manifest));
+ const second = readCompletedRecordingManifest(
+ JSON.stringify({
+ ...manifest,
+ audio_init_uploaded: false,
+ audio_segments: [],
+ }),
+ );
+ expect(first).toMatchObject({ duration: 5, hasAudio: true });
+ expect(first.manifestSha256).not.toBe(second.manifestSha256);
+ });
+
+ it.each([
+ { is_complete: false },
+ { video_init_uploaded: false },
+ { video_segments: [] },
+ { video_segments: [{ index: 2, duration: 3 }] },
+ { video_segments: [{ index: 1, duration: 0 }] },
+ {
+ video_segments: [
+ { index: 1, duration: 2 },
+ { index: 1, duration: 3 },
+ ],
+ },
+ { audio_segments: [] },
+ { audio_init_uploaded: false },
+ ])("refuses incomplete or inconsistent manifest %j", (change) => {
+ expect(() =>
+ readCompletedRecordingManifest(
+ JSON.stringify({ ...manifest, ...change }),
+ ),
+ ).toThrow();
+ });
+
+ it("accepts intact output and optional absent audio", () => {
+ expect(() =>
+ validateRecordingOutput(output, {
+ fileSize: 4096,
+ duration: 5,
+ requiredAudio: true,
+ }),
+ ).not.toThrow();
+ expect(() =>
+ validateRecordingOutput(
+ { ...output, audioCodec: null },
+ { duration: 5, requiredAudio: false },
+ ),
+ ).not.toThrow();
+ });
+
+ it.each([
+ { fileSize: 4095 },
+ { duration: 3 },
+ { duration: Number.NaN },
+ { width: 0 },
+ { audioCodec: null },
+ { videoCodec: "" },
+ ])("rejects incomplete or inconsistent output metadata %j", (change) => {
+ expect(() =>
+ validateRecordingOutput(
+ { ...output, ...change },
+ { fileSize: 4096, duration: 5, requiredAudio: true },
+ ),
+ ).toThrow();
+ });
+
+ it("refuses stale or overwritten cloud objects even when their size matches", () => {
+ const expected = { fileSize: 4096, objectIdentity: "current-generation" };
+ expect(() =>
+ assertRecordingObjectIdentity(
+ { ContentLength: 4096, ETag: "current-generation" },
+ expected,
+ ),
+ ).not.toThrow();
+ for (const head of [
+ { ContentLength: 4096, ETag: "old-generation" },
+ { ContentLength: 4095, ETag: "current-generation" },
+ { ContentLength: 4096 },
+ ]) {
+ expect(() => assertRecordingObjectIdentity(head, expected)).toThrow();
+ }
+ });
+
+ it("rejects unknown versions and nonpositive MP4 identity", () => {
+ const request = {
+ version: 1,
+ artifact: {
+ kind: "mp4",
+ fileSize: 4096,
+ duration: 5,
+ objectIdentity: '"generation"',
+ },
+ requiredAudio: false,
+ };
+ expect(recordingVerificationSchema.safeParse(request).success).toBe(true);
+ expect(
+ recordingVerificationSchema.safeParse({ ...request, version: 2 }).success,
+ ).toBe(false);
+ expect(
+ recordingVerificationSchema.safeParse({
+ ...request,
+ artifact: { ...request.artifact, fileSize: 0 },
+ }).success,
+ ).toBe(false);
+ for (const objectIdentity of [
+ undefined,
+ "",
+ 'W/"weak"',
+ "discovered-later",
+ ]) {
+ expect(
+ recordingVerificationSchema.safeParse({
+ ...request,
+ artifact: { ...request.artifact, objectIdentity },
+ }).success,
+ ).toBe(false);
+ }
+ });
+
+ it("never accepts a header-only receipt as full content verification", () => {
+ const receipt = {
+ version: 1,
+ artifact: {
+ kind: "mp4",
+ fileSize: 4096,
+ duration: 5,
+ objectIdentity: '"generation"',
+ },
+ fileSize: 4096,
+ duration: 5,
+ hasAudio: true,
+ objectIdentity: '"generation"',
+ };
+ expect(recordingUploadReceiptSchema.safeParse(receipt).success).toBe(false);
+ expect(
+ recordingUploadReceiptSchema.safeParse({ ...receipt, fullDecode: false })
+ .success,
+ ).toBe(false);
+ expect(
+ recordingUploadReceiptSchema.safeParse({ ...receipt, fullDecode: true })
+ .success,
+ ).toBe(true);
+ expect(
+ recordingUploadReceiptSchema.safeParse({
+ ...receipt,
+ fullDecode: true,
+ objectIdentity: '"other-generation"',
+ }).success,
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/__tests__/unit/recording-complete.test.ts b/apps/web/__tests__/unit/recording-complete.test.ts
new file mode 100644
index 000000000..cb8b9c6c4
--- /dev/null
+++ b/apps/web/__tests__/unit/recording-complete.test.ts
@@ -0,0 +1,170 @@
+import type { Context, Next } from "hono";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ rows: [] as unknown[][],
+ queue: vi.fn(),
+ verify: vi.fn(),
+ validate: vi.fn(),
+}));
+
+vi.mock("@cap/database", () => ({
+ db: () => ({
+ select: () => ({
+ from: () => ({ where: async () => mocks.rows.shift() ?? [] }),
+ }),
+ }),
+}));
+vi.mock("@cap/database/schema", () => ({
+ videos: { id: "id", ownerId: "ownerId" },
+ videoUploads: { videoId: "videoId", phase: "phase" },
+}));
+vi.mock("@cap/web-domain", () => ({
+ Video: { VideoId: { make: (id: string) => id } },
+}));
+vi.mock("@/app/api/utils", () => ({
+ withAuth: async (context: Context, next: Next) => {
+ context.set("user", { id: "owner" });
+ await next();
+ },
+}));
+vi.mock("@/lib/desktop-segments-finalization", () => ({
+ queueDesktopSegmentsFinalization: mocks.queue,
+}));
+vi.mock("@/lib/desktop-recording-upload-status", () => ({
+ verifyDesktopRecordingUpload: mocks.verify,
+ validateDesktopRecordingRequest: mocks.validate,
+}));
+
+import { app } from "@/app/api/upload/[...route]/recording-complete";
+
+const verification = {
+ version: 1,
+ artifact: { kind: "segments", manifestSha256: "a".repeat(64) },
+ requiredAudio: true,
+};
+
+function request(verify = true) {
+ return app.request("/", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ videoId: "recording",
+ ...(verify ? { verification } : {}),
+ }),
+ });
+}
+
+describe("recording completion acknowledgement", () => {
+ beforeEach(() => {
+ mocks.rows = [
+ [{ id: "recording", ownerId: "owner", source: { type: "desktopMP4" } }],
+ [],
+ ];
+ mocks.queue.mockResolvedValue("queued");
+ mocks.verify.mockResolvedValue(null);
+ mocks.validate.mockResolvedValue(undefined);
+ });
+
+ it("preserves the legacy client acknowledgement without granting verified cleanup", async () => {
+ const response = await request(false);
+ expect(await response.json()).toEqual({
+ success: true,
+ status: "already-complete",
+ });
+ expect(mocks.queue).not.toHaveBeenCalled();
+ });
+
+ it("reconciles a legacy completed upload missing its verification receipt", async () => {
+ const response = await request();
+ expect(await response.json()).toEqual({ success: true, status: "queued" });
+ expect(mocks.validate).toHaveBeenCalledOnce();
+ expect(mocks.queue).toHaveBeenCalledWith({
+ videoId: "recording",
+ userId: "owner",
+ verification,
+ });
+ });
+
+ it("does not enqueue a second job while verification is processing", async () => {
+ mocks.rows[1] = [{ videoId: "recording", phase: "processing" }];
+ const response = await request();
+ expect(await response.json()).toEqual({
+ success: true,
+ status: "already-processing",
+ });
+ expect(mocks.queue).not.toHaveBeenCalled();
+ });
+
+ it("queues verification after upload bytes finish but the progress row remains", async () => {
+ mocks.rows[1] = [{ videoId: "recording", phase: "uploading" }];
+ const response = await request();
+ expect(await response.json()).toEqual({ success: true, status: "queued" });
+ expect(mocks.queue).toHaveBeenCalledOnce();
+ });
+
+ it("validates required tracks before finalizing a segmented upload", async () => {
+ mocks.rows[0] = [
+ {
+ id: "recording",
+ ownerId: "owner",
+ source: { type: "desktopSegments" },
+ },
+ ];
+ mocks.validate.mockRejectedValueOnce(new Error("Missing final audio"));
+ const response = await request();
+ expect(response.status).toBe(503);
+ expect(mocks.queue).not.toHaveBeenCalled();
+ });
+
+ it("requests retransmission after a segmented upload failed verification", async () => {
+ mocks.rows[0] = [
+ {
+ id: "recording",
+ ownerId: "owner",
+ source: { type: "desktopSegments" },
+ },
+ ];
+ mocks.rows[1] = [{ videoId: "recording", phase: "error" }];
+ const response = await request();
+ expect(response.status).toBe(409);
+ expect(mocks.queue).not.toHaveBeenCalled();
+ });
+
+ it("asks for retransmission when a completed remote recording failed validation", async () => {
+ mocks.rows[1] = [{ videoId: "recording", phase: "error" }];
+ const response = await request();
+ expect(response.status).toBe(409);
+ expect(await response.json()).toEqual({
+ success: false,
+ status: "reupload-required",
+ });
+ });
+
+ it("does not issue a ready receipt when verification or manifest validation fails", async () => {
+ mocks.validate.mockRejectedValueOnce(new Error("Missing final audio"));
+ const response = await request();
+ expect(response.status).toBe(503);
+ expect(mocks.queue).not.toHaveBeenCalled();
+ });
+
+ it("returns only the verified result for the owned recording", async () => {
+ const receipt = {
+ version: 1,
+ videoId: "recording",
+ artifact: verification.artifact,
+ fileSize: 4096,
+ duration: 5,
+ hasAudio: true,
+ fullDecode: true,
+ };
+ mocks.verify.mockResolvedValueOnce(receipt);
+ const response = await request();
+ expect(await response.json()).toEqual({
+ success: true,
+ status: "verified",
+ verification: receipt,
+ });
+ expect(mocks.queue).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/__tests__/unit/storage-object-verification.test.ts b/apps/web/__tests__/unit/storage-object-verification.test.ts
new file mode 100644
index 000000000..9a43973c6
--- /dev/null
+++ b/apps/web/__tests__/unit/storage-object-verification.test.ts
@@ -0,0 +1,97 @@
+import { Effect } from "effect";
+import { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ head: vi.fn(),
+ read: vi.fn(),
+}));
+
+vi.mock("@cap/web-backend", async () => {
+ const { Effect, Option } = await import("effect");
+ return {
+ provideOptionalAuth: (effect: unknown) => effect,
+ Storage: {
+ getAccessForVideo: () =>
+ Effect.succeed([
+ { headObject: mocks.head, getObjectResponse: mocks.read },
+ ]),
+ },
+ Videos: {},
+ VideosRepo: Effect.succeed({
+ getById: () =>
+ Effect.succeed(Option.some([{ id: "video", ownerId: "owner" }])),
+ }),
+ verifyStorageObjectToken: () => ({
+ videoId: "video",
+ key: "owner/video/result.mp4",
+ }),
+ };
+});
+vi.mock("@/lib/server", async () => {
+ const { Effect } = await import("effect");
+ return { runPromise: Effect.runPromise };
+});
+vi.mock("@/utils/helpers", () => ({ CACHE_CONTROL_HEADERS: {} }));
+
+import { GET } from "@/app/api/storage/object/route";
+
+function request(headers: Record<string, string> = {}) {
+ return GET(
+ new NextRequest(
+ "https://cap.test/api/storage/object?videoId=video&key=owner/video/result.mp4&token=test",
+ { headers },
+ ),
+ );
+}
+
+describe("recording verification object reads", () => {
+ beforeEach(() => {
+ mocks.head.mockReturnValue(
+ Effect.succeed({ ETag: '"drive-file:42"', ContentLength: 100 }),
+ );
+ mocks.read.mockImplementation(() =>
+ Effect.succeed(
+ new Response("data", {
+ status: 206,
+ headers: { "Content-Range": "bytes 0-3/100" },
+ }),
+ ),
+ );
+ });
+
+ it("does not add metadata requests to ordinary playback", async () => {
+ const response = await request();
+ expect(response.status).toBe(206);
+ expect(mocks.head).not.toHaveBeenCalled();
+ });
+
+ it("returns the provider version with a verification read", async () => {
+ const response = await request({
+ "X-Cap-Recording-Verification": "1",
+ Range: "bytes=0-3",
+ });
+ expect(response.headers.get("ETag")).toBe('"drive-file:42"');
+ expect(await response.text()).toBe("data");
+ expect(mocks.read).toHaveBeenCalledWith(
+ "owner/video/result.mp4",
+ "bytes=0-3",
+ );
+ });
+
+ it("refuses a replaced object before streaming its bytes", async () => {
+ const response = await request({
+ "X-Cap-Recording-Verification": "1",
+ "If-Match": '"drive-file:41"',
+ });
+ expect(response.status).toBe(412);
+ expect(mocks.read).not.toHaveBeenCalled();
+ });
+
+ it("refuses verification when no stable provider version exists", async () => {
+ mocks.head.mockReturnValue(Effect.succeed({ ContentLength: 100 }));
+ const response = await request({ "X-Cap-Recording-Verification": "1" });
+ expect(response.status).toBe(503);
+ expect(mocks.read).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/app/api/storage/object/route.ts b/apps/web/app/api/storage/object/route.ts
index 0a1d70e50..c2409f42c 100644
--- a/apps/web/app/api/storage/object/route.ts
+++ b/apps/web/app/api/storage/object/route.ts
@@ -129,11 +129,28 @@ export async function GET(request: NextRequest) {
return Response.redirect(url);
}
+ const verificationRequested =
+ request.headers.get("x-cap-recording-verification") === "1";
+ const identity = verificationRequested
+ ? (yield* storage.headObject(key)).ETag
+ : undefined;
+ if (verificationRequested && !identity) {
+ return new Response("Object identity is unavailable", { status: 503 });
+ }
+ const expectedIdentity = request.headers.get("if-match");
+ if (
+ verificationRequested &&
+ expectedIdentity &&
+ expectedIdentity !== identity
+ ) {
+ return new Response("Object changed", { status: 412 });
+ }
const upstream = yield* storage.getObjectResponse(
key,
request.headers.get("range"),
);
const headers = new Headers(CACHE_CONTROL_HEADERS);
+ if (identity) headers.set("ETag", identity);
copyHeader(upstream.headers, headers, "content-type", "Content-Type");
copyHeader(upstream.headers, headers, "content-length", "Content-Length");
copyHeader(upstream.headers, headers, "content-range", "Content-Range");
diff --git a/apps/web/app/api/upload/[...route]/multipart.ts b/apps/web/app/api/upload/[...route]/multipart.ts
index 50c54c7df..b1b90eda9 100644
--- a/apps/web/app/api/upload/[...route]/multipart.ts
+++ b/apps/web/app/api/upload/[...route]/multipart.ts
@@ -465,6 +465,7 @@ app.post(
});
return yield* Effect.gen(function* () {
+ let objectIdentity = result.ETag;
console.log(
`Multipart upload completed successfully: ${
result.Location || "no location"
@@ -531,6 +532,7 @@ app.post(
return c.json({
location: result.Location,
+ objectIdentity,
success: true,
fileKey,
processingStarted,
@@ -546,11 +548,16 @@ app.post(
.copyObject(`${bucket.bucketName}/${fileKey}`, fileKey, {
ContentType: "video/mp4",
MetadataDirective: "REPLACE",
+ ...(result.ETag ? { CopySourceIfMatch: result.ETag } : {}),
})
.pipe(
- Effect.tap((result) =>
- Effect.log("Copy for metadata fix successful:", result),
- ),
+ Effect.tap((copyResult) => {
+ objectIdentity = copyResult.CopyObjectResult?.ETag;
+ return Effect.log(
+ "Copy for metadata fix successful:",
+ copyResult,
+ );
+ }),
Effect.catchAll((e) =>
Effect.logError(
"Warning: Failed to copy object to fix metadata:",
@@ -697,6 +704,7 @@ app.post(
return c.json({
location: result.Location,
+ objectIdentity,
success: true,
fileKey,
});
diff --git a/apps/web/app/api/upload/[...route]/recording-complete.ts b/apps/web/app/api/upload/[...route]/recording-complete.ts
index 5709bf183..78b176b03 100644
--- a/apps/web/app/api/upload/[...route]/recording-complete.ts
+++ b/apps/web/app/api/upload/[...route]/recording-complete.ts
@@ -5,6 +5,11 @@ import { zValidator } from "@hono/zod-validator";
import { and, eq } from "drizzle-orm";
import { Hono } from "hono";
import { z } from "zod";
+import {
+ validateDesktopRecordingRequest,
+ verifyDesktopRecordingUpload,
+} from "@/lib/desktop-recording-upload-status";
+import { recordingVerificationSchema } from "@/lib/desktop-recording-verification";
import { queueDesktopSegmentsFinalization } from "@/lib/desktop-segments-finalization";
import { withAuth } from "../../utils";
@@ -15,11 +20,12 @@ export const app = new Hono().post(
"json",
z.object({
videoId: z.string(),
+ verification: recordingVerificationSchema.optional(),
}),
),
async (c) => {
const user = c.get("user");
- const { videoId: videoIdRaw } = c.req.valid("json");
+ const { videoId: videoIdRaw, verification } = c.req.valid("json");
const videoId = Video.VideoId.make(videoIdRaw);
const [video] = await db()
@@ -31,12 +37,62 @@ export const app = new Hono().post(
return c.json({ error: "Video not found" }, 404);
}
- if (video.source?.type === "desktopMP4") {
- return c.json({ success: true, status: "already-complete" });
+ if (
+ video.source?.type !== "desktopMP4" &&
+ video.source?.type !== "desktopSegments"
+ ) {
+ return c.json({ error: "Video is not a desktop recording" }, 400);
+ }
+
+ if (verification) {
+ const [upload] = await db()
+ .select({
+ videoId: Db.videoUploads.videoId,
+ phase: Db.videoUploads.phase,
+ })
+ .from(Db.videoUploads)
+ .where(eq(Db.videoUploads.videoId, videoId));
+ if (upload?.phase === "error") {
+ return c.json({ success: false, status: "reupload-required" }, 409);
+ }
+ if (
+ upload?.phase === "processing" ||
+ upload?.phase === "generating_thumbnail"
+ ) {
+ return c.json({ success: true, status: "already-processing" });
+ }
+ try {
+ const receipt =
+ video.source.type === "desktopMP4"
+ ? await verifyDesktopRecordingUpload(video, verification)
+ : null;
+ if (!receipt) {
+ await validateDesktopRecordingRequest(video, verification);
+ const status = await queueDesktopSegmentsFinalization({
+ videoId,
+ userId: user.id,
+ verification,
+ });
+ return c.json({ success: true, status });
+ }
+ return c.json({
+ success: true,
+ status: "verified",
+ verification: receipt,
+ });
+ } catch {
+ return c.json(
+ {
+ error:
+ "Recording verification is unavailable; retain the local recording",
+ },
+ 503,
+ );
+ }
}
- if (video.source?.type !== "desktopSegments") {
- return c.json({ error: "Video is not a segmented recording" }, 400);
+ if (video.source.type === "desktopMP4") {
+ return c.json({ success: true, status: "already-complete" });
}
try {
diff --git a/apps/web/app/api/webhooks/media-server/multipart/[action]/route.ts b/apps/web/app/api/webhooks/media-server/multipart/[action]/route.ts
index 13b2487f9..4d56f8cd9 100644
--- a/apps/web/app/api/webhooks/media-server/multipart/[action]/route.ts
+++ b/apps/web/app/api/webhooks/media-server/multipart/[action]/route.ts
@@ -159,7 +159,11 @@ export async function POST(
})
.pipe(runPromise);
- return NextResponse.json({ success: true, location: result.Location });
+ return NextResponse.json({
+ success: true,
+ location: result.Location,
+ objectIdentity: result.ETag,
+ });
}
if (action === "abort") {
diff --git a/apps/web/app/api/webhooks/media-server/progress/route.ts b/apps/web/app/api/webhooks/media-server/progress/route.ts
index 2365a59b9..d8efd7083 100644
--- a/apps/web/app/api/webhooks/media-server/progress/route.ts
+++ b/apps/web/app/api/webhooks/media-server/progress/route.ts
@@ -3,8 +3,13 @@ import { db } from "@cap/database";
import { videos, videoUploads } from "@cap/database/schema";
import { serverEnv } from "@cap/env";
import type { Video } from "@cap/web-domain";
-import { eq } from "drizzle-orm";
+import { eq, sql } from "drizzle-orm";
import { type NextRequest, NextResponse } from "next/server";
+import { createVerifiedRecordingReceipt } from "@/lib/desktop-recording-upload-status";
+import {
+ type RecordingVerification,
+ recordingVerificationSchema,
+} from "@/lib/desktop-recording-verification";
import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota";
import {
queueVideoTranscription,
@@ -13,6 +18,12 @@ import {
import { isEditSourceKey } from "@/lib/video-edit-processing";
interface ProgressWebhookPayload {
+ manifestSha256?: string;
+ recordingVerification?: {
+ request: RecordingVerification;
+ fullDecode: boolean;
+ objectIdentity?: string;
+ };
jobId: string;
videoId: string;
phase:
@@ -101,6 +112,30 @@ export async function POST(request: NextRequest) {
const dbPhase = mapPhaseToDbPhase(payload.phase);
if (dbPhase === "complete") {
+ const [currentVideo] = await db()
+ .select()
+ .from(videos)
+ .where(eq(videos.id, payload.videoId as Video.VideoId));
+ const proof = payload.recordingVerification;
+ const receipt = proof
+ ? currentVideo && payload.metadata
+ ? await createVerifiedRecordingReceipt(
+ currentVideo,
+ recordingVerificationSchema.parse(proof.request),
+ payload.metadata,
+ proof.fullDecode,
+ proof.objectIdentity,
+ )
+ : null
+ : undefined;
+ if (receipt === null) {
+ return NextResponse.json(
+ {
+ error: "Recording completion is missing required verification data",
+ },
+ { status: 503 },
+ );
+ }
if (payload.metadata) {
const duration = getValidDuration(payload.metadata.duration);
await db()
@@ -114,19 +149,22 @@ export async function POST(request: NextRequest) {
.where(eq(videos.id, payload.videoId as Video.VideoId));
}
- const [currentVideo] = await db()
- .select()
- .from(videos)
- .where(eq(videos.id, payload.videoId as Video.VideoId));
const [currentUpload] = await db()
.select({ rawFileKey: videoUploads.rawFileKey })
.from(videoUploads)
.where(eq(videoUploads.videoId, payload.videoId as Video.VideoId));
- if (currentVideo?.source?.type === "desktopSegments") {
+ if (currentVideo?.source?.type === "desktopSegments" || receipt) {
await db()
.update(videos)
- .set({ source: { type: "desktopMP4" as const } })
+ .set({
+ source: { type: "desktopMP4" as const },
+ ...(receipt
+ ? {
+ metadata: sql`JSON_SET(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.desktopRecordingUpload', JSON_OBJECT('version', ${receipt.version}, 'artifact', JSON_EXTRACT(${JSON.stringify(receipt.artifact)}, '$'), 'fileSize', ${receipt.fileSize}, 'duration', ${receipt.duration}, 'hasAudio', JSON_EXTRACT(${JSON.stringify(receipt.hasAudio)}, '$'), 'fullDecode', JSON_EXTRACT('true', '$'), 'objectIdentity', ${receipt.objectIdentity}))`,
+ }
+ : {}),
+ })
.where(eq(videos.id, payload.videoId as Video.VideoId));
}
diff --git a/apps/web/lib/desktop-recording-job-status.ts b/apps/web/lib/desktop-recording-job-status.ts
new file mode 100644
index 000000000..751d533db
--- /dev/null
+++ b/apps/web/lib/desktop-recording-job-status.ts
@@ -0,0 +1,52 @@
+import { z } from "zod";
+
+const terminalJobSchema = z
+ .object({
+ jobId: z.string(),
+ videoId: z.string(),
+ phase: z.enum(["complete", "error", "cancelled"]),
+ })
+ .passthrough();
+
+export async function reconcileDesktopRecordingJob({
+ videoId,
+ jobId,
+ mediaServerUrl,
+ webhookUrl,
+ secret,
+}: {
+ videoId: string;
+ jobId: string;
+ mediaServerUrl: string;
+ webhookUrl: string;
+ secret?: string;
+}): Promise<boolean> {
+ if (!secret) return false;
+ try {
+ const headers = { "x-media-server-secret": secret };
+ const response = await fetch(
+ `${mediaServerUrl.replace(/\/$/, "")}/video/process/${encodeURIComponent(jobId)}/status`,
+ {
+ headers,
+ signal: AbortSignal.timeout(10_000),
+ },
+ );
+ if (!response.ok) return false;
+ const job = terminalJobSchema.safeParse(await response.json());
+ if (
+ !job.success ||
+ job.data.jobId !== jobId ||
+ job.data.videoId !== videoId
+ )
+ return false;
+ const delivered = await fetch(webhookUrl, {
+ method: "POST",
+ headers: { ...headers, "Content-Type": "application/json" },
+ body: JSON.stringify(job.data),
+ signal: AbortSignal.timeout(30_000),
+ });
+ return delivered.ok;
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/web/lib/desktop-recording-upload-status.ts b/apps/web/lib/desktop-recording-upload-status.ts
new file mode 100644
index 000000000..881dbdf94
--- /dev/null
+++ b/apps/web/lib/desktop-recording-upload-status.ts
@@ -0,0 +1,136 @@
+import type { videos } from "@cap/database/schema";
+import { Storage } from "@cap/web-backend";
+import { Video } from "@cap/web-domain";
+import { Effect, Option } from "effect";
+import {
+ assertRecordingObjectIdentity,
+ type RecordingOutput,
+ type RecordingUploadReceipt,
+ type RecordingVerification,
+ readCompletedRecordingManifest,
+ recordingUploadReceiptSchema,
+ validateRecordingOutput,
+} from "@/lib/desktop-recording-verification";
+import * as EffectRuntime from "@/lib/server";
+import { decodeStorageVideo } from "@/lib/video-storage";
+
+export async function validateDesktopRecordingRequest(
+ video: typeof videos.$inferSelect,
+ request: RecordingVerification,
+) {
+ const [bucket] = await EffectRuntime.runPromise(
+ Effect.gen(function* () {
+ return yield* Storage.getAccessForVideo(decodeStorageVideo(video));
+ }),
+ );
+ if (request.artifact.kind === "mp4") {
+ return {
+ bucket,
+ expected: {
+ fileSize: request.artifact.fileSize,
+ duration: request.artifact.duration,
+ requiredAudio: request.requiredAudio,
+ },
+ };
+ }
+ const source = new Video.SegmentsSource({
+ videoId: video.id,
+ ownerId: video.ownerId,
+ });
+ const content = await EffectRuntime.runPromise(
+ bucket.getObject(source.getManifestKey()),
+ );
+ if (Option.isNone(content))
+ throw new Error("Final recording manifest is missing");
+ const manifest = readCompletedRecordingManifest(content.value);
+ if (
+ manifest.manifestSha256 !== request.artifact.manifestSha256 ||
+ (request.requiredAudio && !manifest.hasAudio)
+ ) {
+ throw new Error("Final recording manifest does not match the upload");
+ }
+ return {
+ bucket,
+ expected: {
+ fileSize: undefined,
+ duration: manifest.duration,
+ requiredAudio: request.requiredAudio || manifest.hasAudio,
+ },
+ };
+}
+
+export async function createVerifiedRecordingReceipt(
+ video: typeof videos.$inferSelect,
+ request: RecordingVerification,
+ output: RecordingOutput,
+ fullDecode: boolean,
+ objectIdentity?: string,
+): Promise<RecordingUploadReceipt> {
+ if (!fullDecode || !objectIdentity)
+ throw new Error("Recording content and identity were not fully verified");
+ if (
+ request.artifact.kind === "mp4" &&
+ request.artifact.objectIdentity !== objectIdentity
+ )
+ throw new Error("Verified recording does not match its upload receipt");
+ const { bucket, expected } = await validateDesktopRecordingRequest(
+ video,
+ request,
+ );
+ validateRecordingOutput(output, expected);
+ const head = await EffectRuntime.runPromise(
+ bucket.headObject(`${video.ownerId}/${video.id}/result.mp4`),
+ );
+ if (!head.ETag || head.ContentLength !== output.fileSize) {
+ throw new Error("Final recording object is not fully uploaded");
+ }
+ if (head.ETag !== objectIdentity) {
+ throw new Error("Recording changed while its content was verified");
+ }
+ return {
+ version: 1,
+ artifact: request.artifact,
+ fileSize: output.fileSize,
+ duration: output.duration,
+ hasAudio: Boolean(output.audioCodec),
+ fullDecode: true,
+ objectIdentity: head.ETag,
+ };
+}
+
+export async function verifyDesktopRecordingUpload(
+ video: typeof videos.$inferSelect,
+ request: RecordingVerification,
+) {
+ const receipt = recordingUploadReceiptSchema.safeParse(
+ video.metadata?.desktopRecordingUpload,
+ );
+ if (
+ !receipt.success ||
+ JSON.stringify(receipt.data.artifact) !== JSON.stringify(request.artifact)
+ ) {
+ return null;
+ }
+ const { bucket, expected } = await validateDesktopRecordingRequest(
+ video,
+ request,
+ );
+ if (expected.requiredAudio && !receipt.data.hasAudio) return null;
+ const head = await EffectRuntime.runPromise(
+ bucket.headObject(`${video.ownerId}/${video.id}/result.mp4`),
+ );
+ try {
+ assertRecordingObjectIdentity(head, receipt.data);
+ } catch {
+ return null;
+ }
+ return {
+ version: 1 as const,
+ videoId: video.id,
+ artifact: request.artifact,
+ fileSize: receipt.data.fileSize,
+ duration: receipt.data.duration,
+ hasAudio: receipt.data.hasAudio,
+ fullDecode: true,
+ };
+}
diff --git a/apps/web/lib/desktop-recording-verification.ts b/apps/web/lib/desktop-recording-verification.ts
new file mode 100644
index 000000000..5b67d11fe
--- /dev/null
+++ b/apps/web/lib/desktop-recording-verification.ts
@@ -0,0 +1,130 @@
+import { createHash } from "node:crypto";
+import { z } from "zod";
+
+const positiveNumber = z.number().finite().positive();
+const positiveSize = positiveNumber.int().max(Number.MAX_SAFE_INTEGER);
+
+export const recordingVerificationSchema = z.object({
+ version: z.literal(1),
+ artifact: z.discriminatedUnion("kind", [
+ z.object({
+ kind: z.literal("segments"),
+ manifestSha256: z.string().regex(/^[a-f0-9]{64}$/),
+ }),
+ z.object({
+ kind: z.literal("mp4"),
+ fileSize: positiveSize,
+ duration: positiveNumber,
+ objectIdentity: z
+ .string()
+ .max(1_024)
+ .regex(/^"[\x21\x23-\x7E\x80-\xFF]+"$/),
+ }),
+ ]),
+ requiredAudio: z.boolean(),
+});
+
+export type RecordingVerification = z.infer<typeof recordingVerificationSchema>;
+
+const segmentSchema = z.union([
+ z.number().int().positive(),
+ z.object({ index: z.number().int().positive(), duration: positiveNumber }),
+]);
+
+const completedManifestSchema = z.object({
+ version: z.number().int().positive(),
+ video_init_uploaded: z.literal(true),
+ audio_init_uploaded: z.boolean(),
+ video_segments: z.array(segmentSchema).min(1),
+ audio_segments: z.array(segmentSchema),
+ is_complete: z.literal(true),
+});
+
+export function readCompletedRecordingManifest(json: string) {
+ const manifest = completedManifestSchema.parse(JSON.parse(json));
+ const normalize = (entry: z.infer<typeof segmentSchema>) =>
+ typeof entry === "number" ? { index: entry, duration: 3 } : entry;
+ const video = manifest.video_segments.map(normalize);
+ const audio = manifest.audio_segments.map(normalize);
+ for (const segments of [video, audio]) {
+ if (segments.some((segment, index) => segment.index !== index + 1)) {
+ throw new Error(
+ "Recording manifest contains missing or unordered segments",
+ );
+ }
+ }
+ if (manifest.audio_init_uploaded !== audio.length > 0) {
+ throw new Error("Recording manifest contains incomplete audio");
+ }
+ return {
+ manifestSha256: createHash("sha256").update(json).digest("hex"),
+ duration: video.reduce((total, segment) => total + segment.duration, 0),
+ hasAudio: audio.length > 0,
+ };
+}
+
+export const recordingOutputSchema = z.object({
+ fileSize: positiveSize,
+ duration: positiveNumber,
+ width: positiveNumber.int(),
+ height: positiveNumber.int(),
+ videoCodec: z.string().min(1),
+ audioCodec: z.string().min(1).nullable(),
+});
+
+export type RecordingOutput = z.infer<typeof recordingOutputSchema>;
+
+export function validateRecordingOutput(
+ output: RecordingOutput,
+ expected: { fileSize?: number; duration: number; requiredAudio: boolean },
+) {
+ recordingOutputSchema.parse(output);
+ const durationTolerance = Math.max(
+ 0.5,
+ Math.min(5, expected.duration * 0.01),
+ );
+ if (
+ !Number.isFinite(expected.duration) ||
+ expected.duration <= 0 ||
+ Math.abs(output.duration - expected.duration) > durationTolerance ||
+ (expected.fileSize !== undefined &&
+ output.fileSize !== expected.fileSize) ||
+ (expected.requiredAudio && !output.audioCodec)
+ ) {
+ throw new Error("Uploaded recording does not match its final local media");
+ }
+}
+
+export const recordingUploadReceiptSchema = z
+ .object({
+ version: z.literal(1),
+ artifact: recordingVerificationSchema.shape.artifact,
+ fileSize: positiveSize,
+ duration: positiveNumber,
+ hasAudio: z.boolean(),
+ fullDecode: z.literal(true),
+ objectIdentity: z.string().min(1),
+ })
+ .refine(
+ (receipt) =>
+ receipt.artifact.kind !== "mp4" ||
+ receipt.artifact.objectIdentity === receipt.objectIdentity,
+ "Receipt does not match the completed upload identity",
+ );
+
+export type RecordingUploadReceipt = z.infer<
+ typeof recordingUploadReceiptSchema
+>;
+
+export function assertRecordingObjectIdentity(
+ head: { ContentLength?: number; ETag?: string },
+ expected: { fileSize: number; objectIdentity: string },
+) {
+ if (
+ head.ContentLength !== expected.fileSize ||
+ !head.ETag ||
+ head.ETag !== expected.objectIdentity
+ ) {
+ throw new Error("Uploaded recording object changed or is incomplete");
+ }
+}
diff --git a/apps/web/lib/desktop-segments-finalization.ts b/apps/web/lib/desktop-segments-finalization.ts
index 8481675ee..f0d5d768f 100644
--- a/apps/web/lib/desktop-segments-finalization.ts
+++ b/apps/web/lib/desktop-segments-finalization.ts
@@ -4,6 +4,7 @@ import type { User, Video } from "@cap/web-domain";
import { and, eq, notInArray } from "drizzle-orm";
import { start } from "workflow/api";
import { isAiGenerationEnabledForUser } from "@/lib/ai-generation-entitlement";
+import type { RecordingVerification } from "@/lib/desktop-recording-verification";
import { transcribeVideo } from "@/lib/transcribe";
import { finalizeDesktopRecordingWorkflow } from "@/workflows/finalize-desktop-recording";
@@ -70,16 +71,22 @@ async function queueEarlySegmentsTranscription({
export async function queueDesktopSegmentsFinalization({
videoId,
userId,
+ verification,
}: {
videoId: Video.VideoId;
userId: User.UserId;
+ verification?: RecordingVerification;
}): Promise<DesktopSegmentsFinalizationStatus> {
+ const processingMessage =
+ verification?.artifact.kind === "mp4"
+ ? "Verifying uploaded recording..."
+ : PROCESSING_MESSAGE;
const result = await db()
.update(videoUploads)
.set({
phase: "processing",
processingProgress: 0,
- processingMessage: PROCESSING_MESSAGE,
+ processingMessage,
processingError: null,
updatedAt: new Date(),
})
@@ -105,7 +112,7 @@ export async function queueDesktopSegmentsFinalization({
videoId,
phase: "processing",
processingProgress: 0,
- processingMessage: PROCESSING_MESSAGE,
+ processingMessage,
});
} catch {
return "already-processing";
@@ -117,20 +124,22 @@ export async function queueDesktopSegmentsFinalization({
{
videoId,
userId,
+ verification,
},
]);
// The segments are fully uploaded at this point, so transcription can
// start right away from the segment audio instead of waiting for the mux
// into result.mp4. Failures here never block finalization: the workflow
// re-queues transcription after the mux exactly as before.
- await queueEarlySegmentsTranscription({ videoId, userId }).catch(
- (error) => {
- console.warn(
- `[queueDesktopSegmentsFinalization] Early transcription queue failed for ${videoId}`,
- error,
- );
- },
- );
+ if (verification?.artifact.kind !== "mp4")
+ await queueEarlySegmentsTranscription({ videoId, userId }).catch(
+ (error) => {
+ console.warn(
+ `[queueDesktopSegmentsFinalization] Early transcription queue failed for ${videoId}`,
+ error,
+ );
+ },
+ );
return "queued";
} catch (error) {
await db()
diff --git a/apps/web/workflows/finalize-desktop-recording.ts b/apps/web/workflows/finalize-desktop-recording.ts
index ba4c5a6de..9a81d4c79 100644
--- a/apps/web/workflows/finalize-desktop-recording.ts
+++ b/apps/web/workflows/finalize-desktop-recording.ts
@@ -7,6 +7,11 @@ import { and, eq } from "drizzle-orm";
import { Effect, Option, Schema } from "effect";
import { FatalError, sleep } from "workflow";
import { isAiGenerationEnabledForUser } from "@/lib/ai-generation-entitlement";
+import { reconcileDesktopRecordingJob } from "@/lib/desktop-recording-job-status";
+import {
+ type RecordingVerification,
+ readCompletedRecordingManifest,
+} from "@/lib/desktop-recording-verification";
import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota-cache";
import {
createMediaServerCapacityError,
@@ -19,6 +24,7 @@ import { runWorkflowPromise } from "@/lib/workflow-runtime";
interface FinalizeDesktopRecordingWorkflowPayload {
videoId: string;
userId: User.UserId;
+ verification?: RecordingVerification;
}
type DesktopSegmentsOutputUpload =
@@ -39,6 +45,9 @@ type DesktopSegmentsOutputUpload =
};
interface DesktopSegmentsMuxBody {
+ manifestSha256?: string;
+ expectedDuration?: number;
+ outputVerificationUrl: string;
videoId: string;
userId: string;
outputPresignedUrl: string;
@@ -55,7 +64,7 @@ interface DesktopSegmentsMuxBody {
const MEDIA_SERVER_START_MAX_ATTEMPTS = 8;
const MEDIA_SERVER_START_RETRY_BASE_MS = 15_000;
-const MEDIA_SERVER_COMPLETION_MAX_ATTEMPTS = 720;
+const MEDIA_SERVER_COMPLETION_MAX_ATTEMPTS = 1_440;
const MEDIA_SERVER_COMPLETION_POLL_INTERVAL_MS = 5_000;
const MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS = 3 * 60 * 60;
const MEDIA_SERVER_PRESIGNED_PUT_EXPIRES_SECONDS = 3 * 60 * 60;
@@ -134,7 +143,7 @@ export async function finalizeDesktopRecordingWorkflow(
): Promise<{ success: true; jobId?: string }> {
"use workflow";
- const { videoId, userId } = payload;
+ const { videoId, userId, verification } = payload;
try {
await validateDesktopSegmentsRecording(videoId, userId);
@@ -147,8 +156,15 @@ export async function finalizeDesktopRecordingWorkflow(
for (let attempt = 0; ; attempt++) {
try {
await markMuxProcessing(videoId);
- const jobId = await startDesktopSegmentsMuxJob(videoId, userId);
- await waitForDesktopSegmentsMuxCompletion(videoId);
+ const jobId =
+ verification?.artifact.kind === "mp4"
+ ? await startDesktopMp4VerificationJob(
+ videoId,
+ userId,
+ verification,
+ )
+ : await startDesktopSegmentsMuxJob(videoId, userId);
+ await waitForDesktopSegmentsMuxCompletion(videoId, jobId);
await queueFinalizedRecordingTranscription(videoId, userId);
return { success: true, jobId };
} catch (error) {
@@ -337,7 +353,7 @@ async function buildDesktopSegmentsMuxBody(
throw new Error("Invalid segment manifest JSON");
}
- let manifest = await Schema.decodeUnknown(Video.SegmentManifest)(parsed)
+ const manifest = await Schema.decodeUnknown(Video.SegmentManifest)(parsed)
.pipe(Effect.mapError(() => new Error("Invalid segment manifest format")))
.pipe(runWorkflowPromise);
@@ -346,18 +362,14 @@ async function buildDesktopSegmentsMuxBody(
}
if (!manifest.is_complete) {
- manifest = {
- ...manifest,
- is_complete: true,
- };
- const body = JSON.stringify(manifest, null, 2);
- await bucket
- .putObject(segSource.getManifestKey(), body, {
- contentType: "application/json",
- contentLength: Buffer.byteLength(body),
- })
- .pipe(runWorkflowPromise);
+ throw new Error("Segment manifest is not marked as complete");
}
+ const completedManifest = [
+ ...manifest.video_segments,
+ ...manifest.audio_segments,
+ ].every((entry) => typeof entry !== "number")
+ ? readCompletedRecordingManifest(manifestJson)
+ : undefined;
const videoInitUrl = await bucket
.getSignedObjectUrl(segSource.getVideoInitKey(), {
@@ -402,6 +414,11 @@ async function buildDesktopSegmentsMuxBody(
}
const outputKey = `${userId}/${videoId}/result.mp4`;
+ const outputVerificationUrl = await bucket
+ .getInternalSignedObjectUrl(outputKey, {
+ expiresIn: MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS,
+ })
+ .pipe(runWorkflowPromise);
const thumbnailKey = `${userId}/${videoId}/screenshot/screen-capture.jpg`;
const previewGifKey = `${userId}/${videoId}/preview/animated-preview.gif`;
const env = serverEnv();
@@ -481,6 +498,9 @@ async function buildDesktopSegmentsMuxBody(
}
return {
+ manifestSha256: completedManifest?.manifestSha256,
+ expectedDuration: completedManifest?.duration,
+ outputVerificationUrl,
videoId,
userId,
outputPresignedUrl,
@@ -496,6 +516,87 @@ async function buildDesktopSegmentsMuxBody(
};
}
+async function startDesktopMp4VerificationJob(
+ videoId: string,
+ userId: User.UserId,
+ verification: RecordingVerification,
+): Promise<string> {
+ "use step";
+
+ if (verification.artifact.kind !== "mp4") {
+ throw new FatalError("An MP4 verification identity is required");
+ }
+ const [video] = await db()
+ .select()
+ .from(videos)
+ .where(
+ and(
+ eq(videos.id, Video.VideoId.make(videoId)),
+ eq(videos.ownerId, userId),
+ ),
+ );
+ if (!video || video.source.type !== "desktopMP4") {
+ throw new FatalError("Completed desktop recording does not exist");
+ }
+ const [bucket] = await Storage.getAccessForVideo(
+ decodeStorageVideo(video),
+ ).pipe(runWorkflowPromise);
+ const key = `${userId}/${videoId}/result.mp4`;
+ const head = await bucket.headObject(key).pipe(runWorkflowPromise);
+ if (
+ head.ETag !== verification.artifact.objectIdentity ||
+ head.ContentLength !== verification.artifact.fileSize
+ ) {
+ throw new Error(
+ "Uploaded recording does not match the completed local file",
+ );
+ }
+ const videoUrl = await bucket
+ .getInternalSignedObjectUrl(key, {
+ expiresIn: MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS,
+ })
+ .pipe(runWorkflowPromise);
+ const env = serverEnv();
+ if (!env.MEDIA_SERVER_URL || !env.MEDIA_SERVER_WEBHOOK_SECRET) {
+ throw new Error("Recording content verification is not configured");
+ }
+ const webhookBaseUrl = env.MEDIA_SERVER_WEBHOOK_URL || env.WEB_URL;
+ const response = await fetch(
+ `${env.MEDIA_SERVER_URL}/video/verify-recording`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "x-media-server-secret": env.MEDIA_SERVER_WEBHOOK_SECRET,
+ },
+ body: JSON.stringify({
+ videoId,
+ userId,
+ videoUrl,
+ fileSize: verification.artifact.fileSize,
+ duration: verification.artifact.duration,
+ requiredAudio: verification.requiredAudio,
+ objectIdentity: verification.artifact.objectIdentity,
+ webhookUrl: getMediaServerWebhookUrl(
+ webhookBaseUrl,
+ "/api/webhooks/media-server/progress?retryable=true",
+ ),
+ webhookSecret: env.MEDIA_SERVER_WEBHOOK_SECRET,
+ }),
+ signal: AbortSignal.timeout(30_000),
+ },
+ );
+ if (!response.ok) {
+ throw new Error(
+ `Failed to start recording verification: ${response.status}`,
+ );
+ }
+ const result: { jobId?: string } = await response.json();
+ if (!result.jobId)
+ throw new Error("Media server did not return a verification job id");
+ return result.jobId;
+}
+
async function startDesktopSegmentsMuxJob(
videoId: string,
userId: User.UserId,
@@ -566,6 +667,7 @@ async function startDesktopSegmentsMuxJob(
async function waitForDesktopSegmentsMuxCompletion(
videoId: string,
+ jobId: string,
): Promise<void> {
"use step";
@@ -630,6 +732,21 @@ async function waitForDesktopSegmentsMuxCompletion(
]
.filter(Boolean)
.join(" ");
+
+ const env = serverEnv();
+ const mediaServerUrl = env.MEDIA_SERVER_URL;
+ if (mediaServerUrl && attempt % 3 === 0) {
+ await reconcileDesktopRecordingJob({
+ videoId,
+ jobId,
+ mediaServerUrl,
+ webhookUrl: getMediaServerWebhookUrl(
+ env.MEDIA_SERVER_WEBHOOK_URL || env.WEB_URL,
+ "/api/webhooks/media-server/progress?retryable=true",
+ ),
+ secret: env.MEDIA_SERVER_WEBHOOK_SECRET,
+ });
+ }
}
throw new Error(`Segment muxing timed out while ${lastStatus}`);
diff --git a/packages/database/types/metadata.ts b/packages/database/types/metadata.ts
index 27f8396ae..4df72d616 100644
--- a/packages/database/types/metadata.ts
+++ b/packages/database/types/metadata.ts
@@ -6,6 +6,22 @@
* Video metadata structure
*/
export interface VideoMetadata {
+ desktopRecordingUpload?: {
+ version: 1;
+ artifact:
+ | { kind: "segments"; manifestSha256: string }
+ | {
+ kind: "mp4";
+ fileSize: number;
+ duration: number;
+ objectIdentity: string;
+ };
+ fileSize: number;
+ duration: number;
+ hasAudio: boolean;
+ fullDecode: true;
+ objectIdentity: string;
+ };
/**
* Custom created date that can be edited by the user
* This overrides the display of the actual createdAt timestamp
diff --git a/packages/web-backend/src/Storage/GoogleDrive.ts b/packages/web-backend/src/Storage/GoogleDrive.ts
index c981dbd91..8e52182a6 100644
--- a/packages/web-backend/src/Storage/GoogleDrive.ts
+++ b/packages/web-backend/src/Storage/GoogleDrive.ts
@@ -25,6 +25,7 @@ export type GoogleDriveFile = {
name?: string;
mimeType?: string;
size?: string;
+ version?: string;
modifiedTime?: string;
};
@@ -1015,7 +1016,7 @@ export const createGoogleDriveResumableUpload = (
driveFetch(
config,
appendSharedDriveCreateParams(
- `${DRIVE_UPLOAD_BASE}/files/${encodeURIComponent(fileId)}?uploadType=resumable&fields=id,name,mimeType,size`,
+ `${DRIVE_UPLOAD_BASE}/files/${encodeURIComponent(fileId)}?uploadType=resumable&fields=id,name,mimeType,size,version`,
),
{
method: "PATCH",
@@ -1035,7 +1036,7 @@ export const createGoogleDriveResumableUpload = (
driveFetch(
config,
appendSharedDriveCreateParams(
- `${DRIVE_UPLOAD_BASE}/files?uploadType=resumable&fields=id,name,mimeType,size`,
+ `${DRIVE_UPLOAD_BASE}/files?uploadType=resumable&fields=id,name,mimeType,size,version`,
),
{
method: "POST",
@@ -1153,7 +1154,7 @@ export const getGoogleDriveFileMetadata = (
driveFetch(
config,
appendSharedDriveCreateParams(
- `${DRIVE_API_BASE}/files/${encodeURIComponent(fileId)}?fields=id,name,mimeType,size`,
+ `${DRIVE_API_BASE}/files/${encodeURIComponent(fileId)}?fields=id,name,mimeType,size,version`,
),
undefined,
tokenStore,
diff --git a/packages/web-backend/src/Storage/index.ts b/packages/web-backend/src/Storage/index.ts
index b8e9a3186..1cd68aa87 100644
--- a/packages/web-backend/src/Storage/index.ts
+++ b/packages/web-backend/src/Storage/index.ts
@@ -57,7 +57,10 @@ type MultipartAccess = {
S3.CompleteMultipartUploadCommandInput,
"Key" | "Bucket" | "UploadId"
>,
- ) => Effect.Effect<{ Location?: string }, StorageDomain.StorageError>;
+ ) => Effect.Effect<
+ { Location?: string; ETag?: string },
+ StorageDomain.StorageError
+ >;
abort: (
key: string,
uploadId: string,
@@ -257,6 +260,7 @@ const makeS3Access = (s3: S3BucketAccess) => ({
ContentLength: result.ContentLength,
ContentType: result.ContentType,
Metadata: result.Metadata,
+ ETag: result.ETag,
})),
),
putObject: (
@@ -268,7 +272,7 @@ const makeS3Access = (s3: S3BucketAccess) => ({
source: string,
key: string,
args?: Omit<S3.CopyObjectCommandInput, "Bucket" | "CopySource" | "Key">,
- ) => mapStorageError(s3.copyObject(source, key, args)).pipe(Effect.asVoid),
+ ) => mapStorageError(s3.copyObject(source, key, args)),
deleteObject: (key: string) =>
mapStorageError(s3.deleteObject(key)).pipe(Effect.asVoid),
deleteObjects: (objects: Array<{ Key?: string }>) =>
@@ -529,6 +533,9 @@ const makeGoogleDriveAccess = ({
: (object.contentLength ?? undefined),
ContentType: metadata.mimeType ?? object.contentType ?? undefined,
Metadata: object.metadata ?? undefined,
+ ETag: metadata.version
+ ? `"${metadata.id}:${metadata.version}"`
+ : undefined,
})),
),
),