Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: publish recording replacements without overwriting originals
Richie McIlroy091e0a4ededa
diff --git a/apps/desktop-gpui/src/upload.rs b/apps/desktop-gpui/src/upload.rsindex 95f4f2e1e..95f1b1d68 100644--- a/apps/desktop-gpui/src/upload.rs+++ b/apps/desktop-gpui/src/upload.rs@@ -1347,7 +1347,8 @@ async fn upload_video(cancel: &AtomicBool,replace_existing: bool,) -> Result<(String, Option<String>), AuthApiError> {- let initiate = checked_upload_step(cancel, || multipart_initiate(video_id)).await?;+ let initiate =+ checked_upload_step(cancel, || multipart_initiate(video_id, replace_existing)).await?;let is_drive = is_google_drive_upload(initiate.provider.as_deref(), &initiate.upload_id);let parts = upload_parts(video_id,@@ -1394,13 +1395,17 @@ struct InitiateResponse {provider: Option<String>,}-async fn multipart_initiate(video_id: &str) -> Result<InitiateResponse, AuthApiError> {+async fn multipart_initiate(+ video_id: &str,+ replace_existing: bool,+) -> Result<InitiateResponse, AuthApiError> {let response = auth::authed_request(reqwest::Method::POST,"/api/upload/multipart/initiate",Some(json!({"videoId": video_id,- "contentType": "video/mp4"+ "contentType": "video/mp4",+ "replaceExisting": replace_existing})),).awaitdiff --git a/apps/desktop/src-tauri/src/api.rs b/apps/desktop/src-tauri/src/api.rsindex 94c20abc2..229c9219f 100644--- a/apps/desktop/src-tauri/src/api.rs+++ b/apps/desktop/src-tauri/src/api.rs@@ -21,6 +21,7 @@ pub struct MultipartUploadInitiateResponse {pub async fn upload_multipart_initiate(app: &AppHandle,video_id: &str,+ replace_existing: bool,) -> Result<MultipartUploadInitiateResponse, AuthedApiError> {let resp = app.authed_api_request("/api/upload/multipart/initiate", |c, url| {@@ -28,7 +29,8 @@ pub async fn upload_multipart_initiate(.header("Content-Type", "application/json").json(&serde_json::json!({"videoId": video_id,- "contentType": "video/mp4"+ "contentType": "video/mp4",+ "replaceExisting": replace_existing}))}).awaitdiff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex 62df36486..7cdf85422 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -255,7 +255,7 @@ pub async fn upload_video(info!("Uploading video {video_id}...");let start = Instant::now();- let upload = api::upload_multipart_initiate(app, &video_id).await?;+ let upload = api::upload_multipart_initiate(app, &video_id, replace_existing).await?;let is_drive_upload = is_google_drive_upload(upload.provider.as_deref(), &upload.upload_id);let upload_id = upload.upload_id;@@ -726,7 +726,7 @@ impl InstantMultipartUpload {recording_dir: recording_dir.clone(),})?;- let upload = api::upload_multipart_initiate(&app, &video_id).await?;+ let upload = api::upload_multipart_initiate(&app, &video_id, false).await?;let is_drive_upload = is_google_drive_upload(upload.provider.as_deref(), &upload.upload_id);let upload_id = upload.upload_id;@@ -4273,7 +4273,7 @@ pub(crate) mod strict_instant {required_audio: bool,) -> Result<(), AuthedApiError> {let upload = control- .step(|| api::upload_multipart_initiate(app, &video.id))+ .step(|| api::upload_multipart_initiate(app, &video.id, false)).await?;let concurrency = if is_google_drive_upload(upload.provider.as_deref(), &upload.upload_id) {1diff --git a/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts b/apps/web/__tests__/unit/desktop-recording-output-replacement.test.tsindex 6ad4da52f..270f3297a 100644--- a/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts+++ b/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts@@ -1,6 +1,6 @@import type { VideoEditSpec } from "@cap/database/types";import { User, Video } from "@cap/web-domain";-import { Effect, Option } from "effect";+import { Effect, Option, Schema } from "effect";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({@@ -76,6 +76,11 @@ import {invalidateVideoCache,} from "@/actions/admin/replace-video";import { prepareDesktopReupload } from "@/lib/desktop-reupload";+import {+ createDesktopReuploadKey,+ createDesktopReuploadToken,+ decodeDesktopReuploadToken,+} from "@/lib/desktop-reupload-token";import { saveMetadataAndComplete } from "@/workflows/admin-reprocess-video";import {saveEditResultAndComplete,@@ -128,7 +133,13 @@ function createClient() {: [video];return Object.assign(Promise.resolve(rows), {for: async () => {- events.push(table.table === "jobs" ? "lock-job" : "lock-video");+ events.push(+ table.table === "jobs"+ ? "lock-job"+ : table.table === "uploads"+ ? "lock-upload"+ : "lock-video",+ );return rows;},});@@ -145,9 +156,10 @@ function createClient() {updates.push(values);Object.assign(video, values);if (values.source && reorderSourceKeys) {- video.source = Object.fromEntries(- Object.entries(video.source).reverse(),- ) as typeof video.source;+ video.source = Object.assign(+ { type: video.source.type },+ Object.fromEntries(Object.entries(video.source).reverse()),+ );}}return [{ affectedRows: 1 }];@@ -236,6 +248,7 @@ beforeEach(() => {events.push("retire-job");});mocks.env.mockReturnValue({+ NEXTAUTH_SECRET: "test-only-desktop-reupload-signing-key",MEDIA_SERVER_URL: "https://media.test",MEDIA_SERVER_WEBHOOK_SECRET: "secret",WEB_URL: "https://cap.test",@@ -253,35 +266,234 @@ describe("desktop reupload publication", () => {ownerId: User.UserId.make(video.ownerId),bucketId: Option.none(),storageIntegrationId: Option.none(),+ source: Schema.decodeUnknownSync(Video.Video.fields.source)(video.source),});+ const tokenFor = (snapshot = original()) => {+ const token = decodeDesktopReuploadToken(+ createDesktopReuploadToken(snapshot, {+ uploadId: "provider-upload-id",+ provider: "s3",+ outputKey: createDesktopReuploadKey(snapshot),+ }),+ );+ if (!token) throw new Error("Expected a replacement token");+ upload.rawFileKey = token.outputKey;+ return token;+ };+ const transaction = () =>+ createClient() as unknown as Parameters<typeof prepareDesktopReupload>[0];it("replaces processed playback and stale AI while preserving the link's other metadata", async () => {video.source.audioLevelOutputKey ="user/video/.recording/outputs/old-audio.mp4";video.metadata.editProcessing = { token: "old-edit" };- const tx = createClient() as unknown as Parameters<- typeof prepareDesktopReupload- >[0];- const replacement = await prepareDesktopReupload(tx, original());+ video.metadata.completedVideoEdit = { token: "completed-edit" };+ video.metadata.chapters = [{ title: "old chapter" }];+ video.metadata.aiGenerationStatus = "complete";+ const before = structuredClone(video);+ const snapshot = original();+ const token = tokenFor(snapshot);+ const tx = transaction();+ const replacement = await prepareDesktopReupload(tx, snapshot, token);expect(replacement).toEqual({- source: { type: "desktopMP4" },+ source: { type: "desktopMP4", outputKey: token.outputKey },metadata: { customCreatedAt: "2020-01-01T00:00:00Z" },transcriptionStatus: null,});- expect(video.source.outputKey).toBeDefined();- expect(events).toEqual(["retire-job", "lock-video"]);+ expect(video).toEqual(before);+ expect(events).toEqual([+ "lock-job",+ "lock-video",+ "lock-upload",+ "retire-job",+ ]);+ expect(mocks.retire).toHaveBeenCalledWith(tx, {+ videoId: "video",+ userId: "user",+ });+ expect(mocks.head).not.toHaveBeenCalled();+ expect(mocks.access).not.toHaveBeenCalled();});- it("rejects publication if storage changed during upload", async () => {+ it.each(["desktopSegments", "webMP4"])(+ "publishes a %s replacement with its immutable MP4 key",+ async (type) => {+ video.source = { type };+ const replacement = await prepareDesktopReupload(+ transaction(),+ original(),+ tokenFor(),+ );+ expect(replacement?.source.type).toBe(+ type === "webMP4" ? "webMP4" : "desktopMP4",+ );+ expect(replacement?.source.outputKey).toContain(+ "user/video/.recording/outputs/reupload-",+ );+ },+ );++ it.each(["bucket", "storageIntegrationId", "ownerId"] as const)(+ "rejects publication if %s changed during upload before retiring any job",+ async (field) => {+ const snapshot = original();+ const token = tokenFor(snapshot);+ video[field] = "different-identity";+ const before = structuredClone(video);+ await expect(+ prepareDesktopReupload(transaction(), snapshot, token),+ ).rejects.toThrow("storage changed");+ expect(video).toEqual(before);+ expect(updates).toEqual([]);+ expect(events).toEqual(["lock-job", "lock-video"]);+ expect(mocks.retire).not.toHaveBeenCalled();+ },+ );++ it.each([null, "newer-upload"])(+ "rejects canceled or superseded upload %s under the lock",+ async (rawFileKey) => {+ const snapshot = original();+ const token = tokenFor(snapshot);+ upload.rawFileKey = rawFileKey;+ const before = structuredClone(video);+ await expect(+ prepareDesktopReupload(transaction(), snapshot, token),+ ).rejects.toThrow("canceled or superseded");+ expect(video).toEqual(before);+ expect(mocks.retire).not.toHaveBeenCalled();+ expect(events).toEqual(["lock-job", "lock-video", "lock-upload"]);+ },+ );+ it("rejects an older upload completion after another publication", async () => {const snapshot = original();- video.bucket = "different-bucket";- const tx = createClient() as unknown as Parameters<- typeof prepareDesktopReupload- >[0];- await expect(prepareDesktopReupload(tx, snapshot)).rejects.toThrow(- "storage changed",+ const token = tokenFor(snapshot);+ video.source.outputKey = "user/video/.recording/outputs/newer/result.mp4";+ const before = structuredClone(video);+ await expect(+ prepareDesktopReupload(transaction(), snapshot, token),+ ).rejects.toThrow("source changed");+ expect(video).toEqual(before);+ expect(mocks.retire).not.toHaveBeenCalled();+ });++ it("compares normalized source fields under the lock", async () => {+ const snapshot = original();+ const token = tokenFor(snapshot);+ video.source = Object.assign(+ { type: video.source.type },+ Object.fromEntries(Object.entries(video.source).reverse()),+ { legacyExtra: "ignored by Video.source" },);+ await expect(+ prepareDesktopReupload(transaction(), snapshot, token),+ ).resolves.toMatchObject({ source: { outputKey: token.outputKey } });+ expect(events).toEqual([+ "lock-job",+ "lock-video",+ "lock-upload",+ "retire-job",+ ]);+ });++ it("returns no update for the exact already-published attempt without retiring a new job", async () => {+ const snapshot = original();+ const token = tokenFor(snapshot);+ video.source = { type: "desktopMP4", outputKey: token.outputKey };+ video.metadata.summary = "new summary";+ const before = structuredClone(video);+ await expect(+ prepareDesktopReupload(transaction(), snapshot, token),+ ).resolves.toBeNull();+ expect(video).toEqual(before);+ expect(events).toEqual(["lock-job", "lock-video"]);+ expect(mocks.retire).not.toHaveBeenCalled();+ expect(updates).toEqual([]);+ });++ it("still validates storage on an already-published retry", async () => {+ const snapshot = original();+ const token = tokenFor(snapshot);+ video.source = { type: "desktopMP4", outputKey: token.outputKey };+ video.bucket = "changed-bucket";+ await expect(+ prepareDesktopReupload(transaction(), snapshot, token),+ ).rejects.toThrow("storage changed");+ expect(mocks.retire).not.toHaveBeenCalled();+ });++ it("leaves the publication and metadata intact if retiring the job fails", async () => {+ const before = structuredClone(video);+ mocks.retire.mockImplementationOnce(async () => {+ events.push("retire-job");+ throw new Error("Job retirement failed");+ });+ await expect(+ prepareDesktopReupload(transaction(), original(), tokenFor()),+ ).rejects.toThrow("Job retirement failed");+ expect(video).toEqual(before);expect(updates).toEqual([]);+ expect(events).toEqual([+ "lock-job",+ "lock-video",+ "lock-upload",+ "retire-job",+ ]);+ });++ it("keeps job retirement inside the caller's publication transaction", async () => {+ const before = structuredClone(video);+ const retainedJob = {+ generation: "original-generation",+ state: "complete",+ sourceKey: "user/video/original-source.mp4",+ outputKey: video.source.outputKey,+ };+ let job = { ...retainedJob };+ const tx = transaction();+ mocks.retire.mockImplementationOnce(async (owner) => {+ expect(owner).toBe(tx);+ events.push("retire-job");+ job = {+ ...job,+ generation: "retired-generation",+ state: "source-blocked",+ };+ });+ const publishTransaction = async () => {+ events.push("transaction");+ const savedVideo = structuredClone(video);+ const savedJob = { ...job };+ try {+ const replacement = await prepareDesktopReupload(+ tx,+ original(),+ tokenFor(),+ );+ expect(replacement).not.toBeNull();+ expect(job.state).toBe("source-blocked");+ Object.assign(video, replacement);+ events.push("publication-failed");+ throw new Error("Publication failed");+ } catch (error) {+ video = savedVideo;+ job = savedJob;+ events.push("rollback");+ throw error;+ }+ };+ await expect(publishTransaction()).rejects.toThrow("Publication failed");+ expect(video).toEqual(before);+ expect(job).toEqual(retainedJob);+ expect(events).toEqual([+ "transaction",+ "lock-job",+ "lock-video",+ "lock-upload",+ "retire-job",+ "publication-failed",+ "rollback",+ ]);});});diff --git a/apps/web/__tests__/unit/desktop-reupload-token.test.ts b/apps/web/__tests__/unit/desktop-reupload-token.test.tsnew file mode 100644index 000000000..b486d92ce--- /dev/null+++ b/apps/web/__tests__/unit/desktop-reupload-token.test.ts@@ -0,0 +1,358 @@+import { createHash, createHmac } from "node:crypto";+import { S3Bucket, Storage, User, Video } from "@cap/web-domain";+import { Option } from "effect";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({ secret: "" }));+vi.mock("@cap/env", () => ({+ serverEnv: () => ({ NEXTAUTH_SECRET: mocks.secret }),+}));++import {+ assertDesktopReuploadTarget,+ createDesktopReuploadKey,+ createDesktopReuploadToken,+ type DesktopReuploadToken,+ type DesktopReuploadVideo,+ decodeDesktopReuploadToken,+ desktopReuploadSourceIdentity,+} from "@/lib/desktop-reupload-token";++const now = Date.UTC(2026, 8, 11);+const lifetime = 30 * 24 * 60 * 60 * 1000;+const canonicalKey = "user/video/result.mp4";+const outputKey =+ "user/video/.recording/outputs/reupload-11111111-1111-4111-8111-111111111111/result.mp4";+const privateUploadUrl =+ "https://www.googleapis.com/upload/drive/v3/files?upload_id=private-upload";+let video: DesktopReuploadVideo;++function createToken(provider: DesktopReuploadToken["provider"] = "s3") {+ return createDesktopReuploadToken(video, {+ provider,+ uploadId: provider === "s3" ? "provider-upload" : privateUploadUrl,+ outputKey,+ });+}++function decodedToken() {+ const token = decodeDesktopReuploadToken(createToken());+ if (!token) throw new Error("Expected a replacement token");+ return token;+}++function signValue(value: unknown, domain = "cap-desktop-reupload:v1:") {+ const payload = Buffer.from(JSON.stringify(value)).toString("base64url");+ const signature = createHmac("sha256", mocks.secret)+ .update(domain)+ .update(payload)+ .digest("base64url");+ return `cap-reupload.${payload}.${signature}`;+}++beforeEach(() => {+ mocks.secret = "test-only-desktop-reupload-signing-key";+ vi.spyOn(Date, "now").mockReturnValue(now);+ video = {+ id: Video.VideoId.make("video"),+ ownerId: User.UserId.make("user"),+ bucketId: Option.none(),+ storageIntegrationId: Option.none(),+ source: {+ type: "desktopMP4",+ outputKey: "user/video/.recording/outputs/previous/result.mp4",+ thumbnailKey: "user/video/thumbnail.jpg",+ },+ };+});++afterEach(() => vi.restoreAllMocks());++describe("desktop reupload tokens", () => {+ it.each(["s3", "googleDrive"] as const)(+ "round trips an opaque %s upload without losing the backend identifier",+ (provider) => {+ const token = decodeDesktopReuploadToken(createToken(provider));+ expect(token).toEqual({+ version: 1,+ ownerId: "user",+ videoId: "video",+ bucketId: null,+ storageIntegrationId: null,+ provider,+ uploadId: provider === "s3" ? "provider-upload" : privateUploadUrl,+ outputKey,+ sourceIdentity: desktopReuploadSourceIdentity(video.source),+ expiresAt: now + lifetime,+ });+ },+ );++ it("uses a new UUID output key for every attempt", () => {+ const first = createDesktopReuploadKey(video);+ const second = createDesktopReuploadKey(video);+ expect(first).not.toBe(second);+ for (const key of [first, second]) {+ expect(key).toMatch(+ /^user\/video\/\.recording\/outputs\/reupload-[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}\/result\.mp4$/,+ );+ expect(+ decodeDesktopReuploadToken(+ createDesktopReuploadToken(video, {+ uploadId: "upload",+ provider: "s3",+ outputKey: key,+ }),+ )?.outputKey,+ ).toBe(key);+ }+ });++ it.each(["raw-upload-id", privateUploadUrl, ""])(+ "leaves a legacy backend identifier opaque",+ (raw) => expect(decodeDesktopReuploadToken(raw)).toBeNull(),+ );++ it("rejects modified payloads and signatures instead of falling back to legacy", () => {+ const encoded = createToken();+ const [prefix, payload, signature] = encoded.split(".");+ const changed = Buffer.from(+ JSON.stringify({ ...decodedToken(), videoId: "another-video" }),+ ).toString("base64url");+ expect(() =>+ decodeDesktopReuploadToken(`${prefix}.${changed}.${signature}`),+ ).toThrow("Invalid desktop reupload token");+ expect(() =>+ decodeDesktopReuploadToken(`${prefix}.${payload}.${"A".repeat(43)}`),+ ).toThrow("Invalid desktop reupload token");+ });++ it.each([+ "cap-reupload.",+ "cap-reupload.a.b",+ "cap-reupload.a.b.extra",+ `cap-reupload.${"a".repeat(32_768)}`,+ ])("rejects malformed or oversized prefixed tokens", (encoded) => {+ expect(() => decodeDesktopReuploadToken(encoded)).toThrow(+ "Invalid desktop reupload token",+ );+ });++ it("requires the private signing key and the reupload signing domain", () => {+ const token = decodedToken();+ const encoded = createToken("googleDrive");+ expect(() =>+ decodeDesktopReuploadToken(signValue(token, "some-other-token:v1:")),+ ).toThrow("Invalid desktop reupload token");+ mocks.secret = "different-test-only-signing-key";+ expect(() => decodeDesktopReuploadToken(encoded)).toThrow(+ "Invalid desktop reupload token",+ );+ mocks.secret = "";+ expect(() => createToken()).toThrow(+ "Desktop reupload signing is unavailable",+ );+ });++ it.each([+ { version: 2 },+ { provider: "unknown" },+ { ownerId: "../user" },+ { videoId: "video/other" },+ { bucketId: 1 },+ { storageIntegrationId: "" },+ { sourceIdentity: "not-a-hash" },+ { uploadId: "" },+ { uploadId: "a".repeat(8193) },+ { unexpected: "field" },+ { expiresAt: now },+ { expiresAt: now - 1 },+ { expiresAt: now + lifetime + 5 * 60 * 1000 + 1 },+ { expiresAt: now + 0.5 },+ { expiresAt: Number.POSITIVE_INFINITY },+ ])("validates authenticated token fields: %j", (patch) => {+ expect(() =>+ decodeDesktopReuploadToken(signValue({ ...decodedToken(), ...patch })),+ ).toThrow("Invalid desktop reupload token");+ });++ it("accepts a fresh token on a server whose clock is slightly behind", () => {+ const encoded = createToken();+ vi.mocked(Date.now).mockReturnValue(now - 60_000);+ expect(decodeDesktopReuploadToken(encoded)?.outputKey).toBe(outputKey);+ });+ it("expires at the exact lifetime boundary", () => {+ const encoded = createToken();+ vi.mocked(Date.now).mockReturnValue(now + lifetime - 1);+ expect(decodeDesktopReuploadToken(encoded)).not.toBeNull();+ vi.mocked(Date.now).mockReturnValue(now + lifetime);+ expect(() => decodeDesktopReuploadToken(encoded)).toThrow(+ "Invalid desktop reupload token",+ );+ });++ it.each([+ canonicalKey,+ outputKey.replace("user/video/", "other/video/"),+ outputKey.replace("user/video/", "user/other/"),+ outputKey.replace("reupload-", "edit-"),+ outputKey.replace("/result.mp4", "/../result.mp4"),+ outputKey.replace("/result.mp4", "/thumbnail.jpg"),+ outputKey.replace("4111", "1111"),+ `${outputKey}?private=secret`,+ ])("rejects an output outside the attempt key namespace", (key) => {+ expect(() =>+ createDesktopReuploadToken(video, {+ uploadId: "upload",+ provider: "s3",+ outputKey: key,+ }),+ ).toThrow("Invalid desktop reupload token");+ expect(() =>+ decodeDesktopReuploadToken(+ signValue({ ...decodedToken(), outputKey: key }),+ ),+ ).toThrow("Invalid desktop reupload token");+ });++ it("does not expose a private backend URL in validation errors", () => {+ const token = decodeDesktopReuploadToken(createToken("googleDrive"));+ let message = "";+ try {+ decodeDesktopReuploadToken(+ signValue({ ...token, outputKey: privateUploadUrl }),+ );+ } catch (error) {+ message = String(error);+ }+ expect(message).toBe("Error: Invalid desktop reupload token");+ expect(message).not.toContain(privateUploadUrl);+ expect(message).not.toContain(mocks.secret);+ });+});++describe("desktop reupload target identity", () => {+ it("matches the Video.source schema with deterministic field order", () => {+ const source = {+ type: "desktopMP4",+ outputKey: "output",+ audioLevelOutputKey: "audio-output",+ audioLevelSourceKey: "audio-source",+ thumbnailKey: "thumbnail",+ previewKey: "preview",+ };+ const expected = createHash("sha256")+ .update(+ JSON.stringify({+ audioLevelOutputKey: "audio-output",+ audioLevelSourceKey: "audio-source",+ outputKey: "output",+ previewKey: "preview",+ thumbnailKey: "thumbnail",+ type: "desktopMP4",+ }),+ )+ .digest("hex");+ expect(desktopReuploadSourceIdentity(source)).toBe(expected);+ expect(+ desktopReuploadSourceIdentity({+ ...Object.fromEntries(Object.entries(source).reverse()),+ legacyField: "ignored by Video.source",+ }),+ ).toBe(expected);+ expect(+ desktopReuploadSourceIdentity({+ type: "desktopMP4",+ outputKey: undefined,+ }),+ ).toBe(desktopReuploadSourceIdentity({ type: "desktopMP4" }));+ for (const key of Object.keys(source)) {+ const changed = {+ ...source,+ [key]: key === "type" ? "webMP4" : "changed",+ };+ expect(desktopReuploadSourceIdentity(changed)).not.toBe(expected);+ }+ });++ it("rejects malformed known source fields without echoing them", () => {+ expect(() =>+ desktopReuploadSourceIdentity({ type: "desktopMP4", outputKey: 123 }),+ ).toThrow("Invalid recording source");+ });++ it("binds the requested canonical key, owner, and video", () => {+ const token = decodedToken();+ expect(() =>+ assertDesktopReuploadTarget(token, video, canonicalKey, "s3"),+ ).not.toThrow();+ for (const key of [+ outputKey,+ "user/video/raw-upload.mp4",+ "other/video/result.mp4",+ ]) {+ expect(() => assertDesktopReuploadTarget(token, video, key)).toThrow(+ "Recording target changed",+ );+ }+ expect(() =>+ assertDesktopReuploadTarget(+ token,+ { ...video, ownerId: User.UserId.make("other") },+ "other/video/result.mp4",+ ),+ ).toThrow("Recording target changed");+ expect(() =>+ assertDesktopReuploadTarget(+ token,+ { ...video, id: Video.VideoId.make("other") },+ "user/other/result.mp4",+ ),+ ).toThrow("Recording target changed");+ });++ it("binds both storage identifiers and the provider", () => {+ const token = decodedToken();+ for (const target of [+ { ...video, bucketId: Option.some(S3Bucket.S3BucketId.make("bucket")) },+ {+ ...video,+ storageIntegrationId: Option.some(+ Storage.StorageIntegrationId.make("integration"),+ ),+ },+ ]) {+ expect(() =>+ assertDesktopReuploadTarget(token, target, canonicalKey),+ ).toThrow("Recording storage changed");+ }+ expect(() =>+ assertDesktopReuploadTarget(token, video, canonicalKey, "googleDrive"),+ ).toThrow("Recording storage changed");+ });++ it("rejects a changed source but accepts only this attempt's published output", () => {+ const token = decodedToken();+ const changed: DesktopReuploadVideo = {+ ...video,+ source: { type: "desktopMP4", outputKey: "newer-output" },+ };+ expect(() =>+ assertDesktopReuploadTarget(token, changed, canonicalKey),+ ).toThrow("Recording source changed");+ const published: DesktopReuploadVideo = {+ ...changed,+ source: { type: "desktopMP4", outputKey },+ };+ expect(() =>+ assertDesktopReuploadTarget(token, published, canonicalKey),+ ).not.toThrow();+ const moved: DesktopReuploadVideo = {+ ...published,+ bucketId: Option.some(S3Bucket.S3BucketId.make("other-bucket")),+ };+ expect(() =>+ assertDesktopReuploadTarget(token, moved, canonicalKey),+ ).toThrow("Recording storage changed");+ });+});diff --git a/apps/web/__tests__/unit/multipart-presign.test.ts b/apps/web/__tests__/unit/multipart-presign.test.tsindex b66b4c81f..cb9eba7b9 100644--- a/apps/web/__tests__/unit/multipart-presign.test.ts+++ b/apps/web/__tests__/unit/multipart-presign.test.ts@@ -1,3 +1,6 @@+import { S3Bucket, User, Video } from "@cap/web-domain";+import type { SQL } from "drizzle-orm";+import { MySqlDialect } from "drizzle-orm/mysql-core";import { Effect, Option } from "effect";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -11,8 +14,14 @@ const mocks = vi.hoisted(() => ({head: vi.fn(),queueTranscription: vi.fn(),shouldQueueTranscription: vi.fn(),+ complete: vi.fn(),+ create: vi.fn(),+ abort: vi.fn(),+}));+vi.mock("@cap/env", () => ({+ serverEnv: () => ({ NEXTAUTH_SECRET: "test-reupload-secret" }),+ buildEnv: { NEXT_PUBLIC_IS_CAP: true },}));-vi.mock("@cap/env", () => ({ serverEnv: () => ({}) }));vi.mock("@/lib/desktop-reupload", () => ({prepareDesktopReupload: mocks.prepareReplacement,invalidateReuploadedVideo: mocks.invalidate,@@ -70,6 +79,13 @@ vi.mock("@/lib/video-processing", () => ({}));import { app } from "@/app/api/upload/[...route]/multipart";+import {+ assertDesktopReuploadTarget,+ createDesktopReuploadKey,+ createDesktopReuploadToken,+ type DesktopReuploadToken,+ decodeDesktopReuploadToken,+} from "@/lib/desktop-reupload-token";const request = () =>app.request("/presign-part", {@@ -124,122 +140,251 @@ describe("multipart presign ownership failures", () => {});describe("desktop reupload completion", () => {+ const oldKey = "owner/video/.recording/outputs/original/result.mp4";let events: string[];let updates: Record<string, unknown>[];+ let objects: Map<string, { ETag: string; ContentLength: number }>;+ let video: {+ id: Video.VideoId;+ ownerId: User.UserId;+ source: { type: "desktopMP4"; outputKey: string };+ bucketId: Video.Video["bucketId"];+ storageIntegrationId: Video.Video["storageIntegrationId"];+ };+ let outputKey: string;+ let token: string;+ let uploadKey: string | null;+ let rejectCommit: boolean;+ let provider: "s3" | "googleDrive";+ let uploadState: Record<string, unknown>;+ const dialect = new MySqlDialect();+ const mintToken = () => {+ outputKey = createDesktopReuploadKey(video);+ token = createDesktopReuploadToken(video, {+ uploadId: "backend-upload",+ provider,+ outputKey,+ });+ uploadKey = outputKey;+ };beforeEach(() => {vi.clearAllMocks();events = [];updates = [];+ objects = new Map([[oldKey, { ETag: "original", ContentLength: 90 }]]);+ provider = "s3";+ rejectCommit = false;+ uploadState = {+ phase: "error",+ processingError: "recoverable",+ uploaded: 90,+ total: 90,+ };+ video = {+ id: Video.VideoId.make("video"),+ ownerId: User.UserId.make("owner"),+ source: { type: "desktopMP4", outputKey: oldKey },+ bucketId: Option.none(),+ storageIntegrationId: Option.none(),+ };+ mintToken();const client = {- transaction: async (run: (tx: unknown) => Promise<void>) => run(client),- update: () => ({- set: (values: Record<string, unknown>) => ({- where: async () => {- updates.push(values);- events.push("publish");+ select: () => ({+ from: () => ({+ innerJoin: () => ({+ where: () => ({+ limit: async () => [+ {+ stripeSubscriptionStatus: null,+ thirdPartyStripeSubscriptionId: null,+ },+ ],+ }),+ }),+ }),+ }),+ transaction: async (run: (tx: unknown) => Promise<void>) => {+ const pending: Record<string, unknown>[] = [];+ let removeUpload = false;+ await run({+ update: () => ({+ set: (values: Record<string, unknown>) => ({+ where: async () => {+ pending.push(values);+ events.push("publish");+ },+ }),+ }),+ delete: () => ({+ where: async (filter: SQL) => {+ events.push("delete-upload");+ const params = dialect.sqlToQuery(filter).params;+ removeUpload = params.length === 1 || params.includes(uploadKey);+ },+ }),+ });+ if (rejectCommit) throw new Error("Database commit failed");+ for (const values of pending) {+ updates.push(values);+ if (values.source)+ video.source = values.source as typeof video.source;+ }+ if (removeUpload) uploadKey = null;+ },+ insert: () => ({+ values: (values: { rawFileKey?: string | null }) => ({+ onDuplicateKeyUpdate: async ({+ set,+ }: {+ set: Record<string, unknown>;+ }) => {+ Object.assign(uploadState, set);+ uploadKey = values.rawFileKey ?? null;},}),}),delete: () => ({- where: async () => {- events.push("delete-upload");+ where: async (filter: SQL) => {+ if (dialect.sqlToQuery(filter).params.includes(uploadKey))+ uploadKey = null;},}),};mocks.database.mockReturnValue(client);- mocks.getOwnedById.mockReturnValue(- Effect.succeed(- Option.some([- {- id: "video",- ownerId: "owner",- source: { type: "desktopMP4", outputKey: "old.mp4" },- bucketId: Option.none(),- storageIntegrationId: Option.none(),- },- ]),+ mocks.getOwnedById.mockImplementation(() =>+ Effect.sync(() =>+ Option.some([{ ...video, source: { ...video.source } }]),),);- mocks.storage.mockReturnValue(+ mocks.complete.mockImplementation((key: string) =>+ Effect.sync(() => {+ events.push("complete");+ objects.set(key, { ETag: "new-video", ContentLength: 100 });+ return { ETag: "new-video" };+ }),+ );+ mocks.create.mockReturnValue(+ Effect.succeed({ UploadId: "backend-upload" }),+ );+ mocks.abort.mockReturnValue(Effect.succeed({}));+ mocks.head.mockImplementation((key: string) => {+ const value = objects.get(key);+ return value+ ? Effect.succeed(value)+ : Effect.fail(new Error("Object missing"));+ });+ mocks.storage.mockImplementation(() =>Effect.succeed([{- provider: "s3",+ provider,bucketName: "bucket",multipart: {- complete: () =>- Effect.sync(() => {- events.push("complete");- return { ETag: "new-video" };- }),+ complete: mocks.complete,+ create: mocks.create,+ abort: mocks.abort,+ getPresignedUploadPartUrl: mocks.sign,},- headObject: mocks.head,+ headObject: (key: string) => Effect.suspend(() => mocks.head(key)),copyObject: () =>Effect.succeed({ CopyObjectResult: { ETag: "new-video" } }),},]),);- mocks.head.mockReturnValue(- Effect.succeed({ ETag: "new-video", ContentLength: 100 }),+ mocks.sign.mockReturnValue(Effect.succeed("https://uploads.example/part"));+ mocks.prepareReplacement.mockImplementation(+ async (+ _tx: unknown,+ _snapshot: unknown,+ replacement: DesktopReuploadToken,+ ) => {+ assertDesktopReuploadTarget(+ replacement,+ video,+ "owner/video/result.mp4",+ provider,+ );+ if (video.source.outputKey === replacement.outputKey) return null;+ if (uploadKey !== replacement.outputKey)+ throw new Error("Replacement upload was canceled or superseded");+ events.push("retire");+ return {+ source: { type: "desktopMP4", outputKey: replacement.outputKey },+ transcriptionStatus: null,+ };+ },);- mocks.prepareReplacement.mockImplementation(async () => {- events.push("retire");- return { source: { type: "desktopMP4" }, transcriptionStatus: null };- });mocks.invalidate.mockImplementation(async () => {events.push("invalidate");});mocks.shouldQueueTranscription.mockReturnValue(false);mocks.queueTranscription.mockResolvedValue({ success: true });});-- const complete = (replaceExisting?: boolean) =>+ const complete = (+ replaceExisting?: boolean,+ uploadId = token,+ durationInSecs = 5,+ ) =>app.request("/complete", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({videoId: "video",- uploadId: "upload",+ uploadId,parts: [{ partNumber: 1, etag: "part", size: 100 }],- durationInSecs: 5,+ durationInSecs,replaceExisting,}),});-- it("publishes the new canonical bytes at the existing link before invalidating playback", async () => {- const response = await complete(true);- expect(response.status).toBe(200);- expect(events).toEqual([- "complete",- "retire",- "publish",- "delete-upload",- "invalidate",- ]);- expect(mocks.storage).toHaveBeenCalledWith(expect.anything(), {- resolvePublishedOutput: false,- });- expect(updates[0]).toMatchObject({- source: { type: "desktopMP4" },- transcriptionStatus: null,- });- });-- it("keeps a committed reupload successful when cache invalidation fails", async () => {- mocks.invalidate.mockImplementationOnce(async () => {- events.push("invalidate");- throw new Error("CloudFront temporarily unavailable");- });- mocks.shouldQueueTranscription.mockReturnValue(true);- mocks.queueTranscription.mockImplementationOnce(async () => {- events.push("transcribe");- return { success: true };+ const abort = () =>+ app.request("/abort", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ videoId: "video", uploadId: token }),});-- const response = await complete(true);-+ it.each(["s3", "googleDrive"] as const)(+ "initiates isolated %s replacement uploads",+ async (storageProvider) => {+ provider = storageProvider;+ const response = await app.request("/initiate", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ videoId: "video",+ contentType: "video/mp4",+ replaceExisting: true,+ }),+ });+ expect(response.status).toBe(200);+ const body = await response.json();+ const decoded = decodeDesktopReuploadToken(body.uploadId);+ expect(decoded).toMatchObject({+ provider,+ uploadId: "backend-upload",+ videoId: "video",+ });+ expect(decoded?.outputKey).not.toBe(oldKey);+ expect(mocks.create).toHaveBeenCalledWith(+ decoded?.outputKey,+ expect.objectContaining({ ContentType: "video/mp4" }),+ );+ expect(uploadKey).toBe(decoded?.outputKey);+ expect(uploadState).toMatchObject({+ phase: "uploading",+ uploaded: 0,+ total: 0,+ processingProgress: 0,+ processingError: null,+ processingMessage: null,+ });+ expect(video.source.outputKey).toBe(oldKey);+ },+ );+ it("publishes verified replacement bytes without overwriting current playback", async () => {+ const response = await complete();expect(response.status).toBe(200);expect(await response.json()).toMatchObject({success: true,+ fileKey: outputKey,objectIdentity: "new-video",});expect(events).toEqual([@@ -248,48 +393,198 @@ describe("desktop reupload completion", () => {"publish","delete-upload","invalidate",- "transcribe",]);- expect(updates).toHaveLength(1);- expect(mocks.queueTranscription).toHaveBeenCalledExactlyOnceWith("video");+ expect(mocks.complete).toHaveBeenCalledWith(+ outputKey,+ "backend-upload",+ expect.anything(),+ );+ expect(video.source.outputKey).toBe(outputKey);+ expect(objects.get(oldKey)).toEqual({+ ETag: "original",+ ContentLength: 90,+ });+ });+ it("uses a new playback key even when CDN invalidation fails", async () => {+ mocks.invalidate.mockRejectedValueOnce(new Error("CloudFront unavailable"));+ const response = await complete();+ expect(response.status).toBe(200);+ expect(video.source.outputKey).toBe(outputKey);+ expect(video.source.outputKey).not.toBe(oldKey);+ expect(objects.get(oldKey)?.ETag).toBe("original");});-it.each([false, undefined])(- "keeps first uploads on the existing recording completion path: %s",- async (replaceExisting) => {- const response = await complete(replaceExisting);+ "keeps ordinary uploads on their existing path: %s",+ async (replacementFlag) => {+ const response = await complete(replacementFlag, "legacy-upload");expect(response.status).toBe(200);expect(mocks.prepareReplacement).not.toHaveBeenCalled();expect(mocks.invalidate).not.toHaveBeenCalled();expect(updates[0]).not.toHaveProperty("source");},);- it("does not publish an empty or mismatched replacement", async () => {+ it("rejects unsafe legacy replacement completion before storage writes", async () => {+ const response = await complete(true, "legacy-upload");+ expect(response.status).toBe(409);+ expect(mocks.complete).not.toHaveBeenCalled();+ expect(video.source.outputKey).toBe(oldKey);+ });+ it("leaves original bytes and publication intact when storage completion fails", async () => {+ mocks.complete.mockReturnValueOnce(Effect.fail(new Error("Upload failed")));+ expect((await complete()).status).toBe(500);+ expect(video.source.outputKey).toBe(oldKey);+ expect(objects.get(oldKey)?.ETag).toBe("original");+ expect(mocks.prepareReplacement).not.toHaveBeenCalled();+ });+ it("does not publish a mismatched or empty uploaded object", async () => {mocks.head.mockReturnValue(- Effect.succeed({ ETag: "old-video", ContentLength: 0 }),+ Effect.succeed({ ETag: "new-video", ContentLength: 0 }),);- const response = await complete(true);- expect(response.status).toBe(500);+ expect((await complete()).status).toBe(500);+ expect(video.source.outputKey).toBe(oldKey);expect(mocks.prepareReplacement).not.toHaveBeenCalled();- expect(mocks.invalidate).not.toHaveBeenCalled();+ });+ it("preserves old playback and permits retry after database commit failure", async () => {+ rejectCommit = true;+ expect((await complete()).status).toBe(500);+ expect(video.source.outputKey).toBe(oldKey);+ expect(objects.get(oldKey)?.ETag).toBe("original");+ expect(objects.get(outputKey)?.ETag).toBe("new-video");+ rejectCommit = false;+ mocks.complete.mockReturnValueOnce(Effect.fail(new Error("NoSuchUpload")));+ expect((await complete()).status).toBe(200);+ expect(video.source.outputKey).toBe(outputKey);+ });+ it("rejects storage changes after upload without overwriting the old media", async () => {+ mocks.complete.mockImplementationOnce((key: string) =>+ Effect.sync(() => {+ objects.set(key, { ETag: "new-video", ContentLength: 100 });+ video.bucketId = Option.some(+ S3Bucket.S3BucketId.make("different-storage"),+ );+ return { ETag: "new-video" };+ }),+ );+ expect((await complete()).status).toBe(500);+ expect(video.source.outputKey).toBe(oldKey);+ expect(objects.get(oldKey)?.ETag).toBe("original");expect(updates).toEqual([]);});-- it("does not replace playback when storage completion fails", async () => {- mocks.storage.mockReturnValue(- Effect.succeed([- {- provider: "s3",- bucketName: "bucket",- multipart: {- complete: () => Effect.fail(new Error("upload failed")),- },- },- ]),+ it("completes repeated publication requests without recompleting or retiring again", async () => {+ expect((await complete()).status).toBe(200);+ expect((await complete()).status).toBe(200);+ expect(mocks.complete).toHaveBeenCalledTimes(1);+ expect(mocks.prepareReplacement).toHaveBeenCalledTimes(1);+ });+ it("rejects competing replacements after another operation publishes", async () => {+ const competing = createDesktopReuploadToken(video, {+ uploadId: "competing",+ provider,+ outputKey: createDesktopReuploadKey(video),+ });+ expect((await complete()).status).toBe(200);+ expect((await complete(true, competing)).status).toBe(500);+ expect(video.source.outputKey).toBe(outputKey);+ expect(mocks.complete).toHaveBeenCalledTimes(1);+ });+ it("preserves newer upload bookkeeping when an older replacement completes", async () => {+ uploadKey = "newer-operation";+ expect((await complete()).status).toBe(500);+ expect(video.source.outputKey).toBe(oldKey);+ expect(uploadKey).toBe("newer-operation");+ });+ it("does not delete published Drive mappings on a late abort", async () => {+ provider = "googleDrive";+ mintToken();+ expect((await complete()).status).toBe(200);+ expect((await abort()).status).toBe(200);+ expect(mocks.abort).not.toHaveBeenCalled();+ expect(video.source.outputKey).toBe(outputKey);+ });+ it("preserves Drive mappings when abort races with publication", async () => {+ provider = "googleDrive";+ mintToken();+ expect((await abort()).status).toBe(200);+ expect(mocks.abort).not.toHaveBeenCalled();+ });+ it.each(["s3", "googleDrive"] as const)(+ "cancels %s replacement after storage completion and database failure",+ async (storageProvider) => {+ provider = storageProvider;+ mintToken();+ rejectCommit = true;+ expect((await complete()).status).toBe(500);+ mocks.abort.mockReturnValue(Effect.fail(new Error("NoSuchUpload")));+ expect((await abort()).status).toBe(200);+ expect(uploadKey).toBeNull();+ rejectCommit = false;+ mocks.complete.mockReturnValue(Effect.fail(new Error("NoSuchUpload")));+ expect((await complete()).status).toBe(500);+ expect(video.source.outputKey).toBe(oldKey);+ expect(objects.get(oldKey)?.ETag).toBe("original");+ },+ );+ it.each(["s3", "googleDrive"] as const)(+ "rejects over-limit %s replacement without changing original playback",+ async (storageProvider) => {+ provider = storageProvider;+ mintToken();+ expect(+ (+ await complete(+ true,+ token,+ Video.FREE_PLAN_MAX_RECORDING_SECONDS + 100,+ )+ ).status,+ ).toBe(403);+ expect(uploadKey).toBeNull();+ expect(video.source.outputKey).toBe(oldKey);+ expect(objects.get(oldKey)?.ETag).toBe("original");+ if (provider === "googleDrive")+ expect(mocks.abort).not.toHaveBeenCalled();+ else+ expect(mocks.abort).toHaveBeenCalledWith(outputKey, "backend-upload");+ },+ );+ it("preserves a newer upload when rejecting an older over-limit replacement", async () => {+ uploadKey = "newer-operation";+ expect(+ (await complete(true, token, Video.FREE_PLAN_MAX_RECORDING_SECONDS + 100))+ .status,+ ).toBe(403);+ expect(uploadKey).toBe("newer-operation");+ });+ it("signs only the authenticated replacement key and backend session", async () => {+ const response = await app.request("/presign-part", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ videoId: "video",+ uploadId: token,+ partNumber: 1,+ }),+ });+ expect(response.status).toBe(200);+ expect(mocks.sign).toHaveBeenCalledWith(+ outputKey,+ "backend-upload",+ 1,+ expect.anything(),);- const response = await complete(true);+ });+ it("rejects tampered replacement sessions without presigning storage", async () => {+ const tampered = `${token.slice(0, -3)}bad`;+ const response = await app.request("/presign-part", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ videoId: "video",+ uploadId: tampered,+ partNumber: 1,+ }),+ });expect(response.status).toBe(500);- expect(mocks.prepareReplacement).not.toHaveBeenCalled();- expect(updates).toEqual([]);+ expect(mocks.sign).not.toHaveBeenCalled();});});diff --git a/apps/web/app/api/upload/[...route]/multipart.ts b/apps/web/app/api/upload/[...route]/multipart.tsindex 4f5797d5d..f186b2a12 100644--- a/apps/web/app/api/upload/[...route]/multipart.ts+++ b/apps/web/app/api/upload/[...route]/multipart.ts@@ -20,6 +20,12 @@ import {invalidateReuploadedVideo,prepareDesktopReupload,} from "@/lib/desktop-reupload";+import {+ assertDesktopReuploadTarget,+ createDesktopReuploadKey,+ createDesktopReuploadToken,+ decodeDesktopReuploadToken,+} from "@/lib/desktop-reupload-token";import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota";import {queueVideoTranscription,@@ -74,16 +80,21 @@ app.post("/initiate",zValidator("json",- z.object({ contentType: z.string() }).and(- z.union([- z.object({ videoId: z.string(), subpath: z.string().optional() }),- // deprecated- z.object({ fileKey: z.string() }),- ]),- ),+ z+ .object({+ contentType: z.string(),+ replaceExisting: z.boolean().optional(),+ })+ .and(+ z.union([+ z.object({ videoId: z.string(), subpath: z.string().optional() }),+ // deprecated+ z.object({ fileKey: z.string() }),+ ]),+ ),),async (c) => {- const { contentType, ...body } = c.req.valid("json");+ const { contentType, replaceExisting, ...body } = c.req.valid("json");const user = c.get("user");const fileKey = getMultipartFileKey(user.id, body);@@ -93,6 +104,79 @@ app.post(if (!videoIdRaw) return c.text("Video id not found", 400);const videoId = Video.VideoId.make(videoIdRaw);+ if (replaceExisting) {+ if ((getSubpath(body) ?? "result.mp4") !== "result.mp4") {+ return c.json(+ { error: "Replacement uploads must target a recording" },+ 400,+ );+ }+ return Effect.gen(function* () {+ const policy = yield* VideosPolicy;+ const db = yield* Database;+ const owned = yield* policy.getOwnedById(videoId);+ if (Option.isNone(owned))+ return c.json({ error: "Video not found" }, 404);+ const [video] = owned.value;+ const [bucket] = yield* Storage.getAccessForVideo(video, {+ resolvePublishedOutput: false,+ });+ const outputKey = createDesktopReuploadKey(video);+ const result = yield* bucket.multipart.create(outputKey, {+ ContentType: contentType || "video/mp4",+ CacheControl: "public, max-age=31536000, immutable",+ Metadata: { userId: user.id, source: "cap-desktop-reupload" },+ });+ if (!result.UploadId)+ return yield* Effect.fail(new Error("No upload ID returned"));+ const backendUploadId = result.UploadId;+ const uploadId = yield* Effect.gen(function* () {+ const token = yield* Effect.try(() =>+ createDesktopReuploadToken(video, {+ uploadId: backendUploadId,+ provider: bucket.provider,+ outputKey,+ }),+ );+ const state = {+ mode: "multipart" as const,+ rawFileKey: outputKey,+ uploaded: 0,+ total: 0,+ phase: "uploading" as const,+ processingProgress: 0,+ processingMessage: null,+ processingError: null,+ startedAt: new Date(),+ updatedAt: new Date(),+ };+ yield* db.use((db) =>+ db+ .insert(Db.videoUploads)+ .values({ videoId, ...state })+ .onDuplicateKeyUpdate({ set: state }),+ );+ return token;+ }).pipe(+ Effect.onError(() =>+ bucket.multipart+ .abort(outputKey, backendUploadId)+ .pipe(Effect.ignore),+ ),+ );+ return c.json({ uploadId, provider: bucket.provider });+ }).pipe(+ Effect.catchAll(() =>+ Effect.succeed(+ c.json({ error: "Could not initiate replacement upload" }, 500),+ ),+ ),+ Effect.provide(makeCurrentUserLayer(user)),+ provideOptionalAuth,+ runPromiseAnyEnv,+ );+ }+const resp = await Effect.gen(function* () {const policy = yield* VideosPolicy;const db = yield* Database;@@ -110,6 +194,7 @@ app.post(.onDuplicateKeyUpdate({set: {mode: "multipart",+ rawFileKey: null,updatedAt: new Date(),},}),@@ -234,16 +319,36 @@ app.post(return yield* new Video.NotFoundError();}const [video] = maybeVideo.value;- const [bucket] = yield* Storage.getAccessForVideo(video);-- console.log(- `Getting presigned URL for part ${partNumber} of upload ${uploadId}`,+ const replacement = yield* Effect.try(() =>+ decodeDesktopReuploadToken(uploadId),);+ const [bucket] = yield* replacement+ ? Storage.getAccessForVideo(video, {+ resolvePublishedOutput: false,+ })+ : Storage.getAccessForVideo(video);+ if (replacement) {+ yield* Effect.try(() =>+ assertDesktopReuploadTarget(+ replacement,+ video,+ fileKey,+ bucket.provider,+ ),+ );+ yield* Effect.try(() => {+ if (video.source.outputKey === replacement.outputKey) {+ throw new Error("Replacement upload is already complete");+ }+ });+ }++ console.log(`Getting presigned URL for multipart part ${partNumber}`);const presignedUrl =yield* bucket.multipart.getPresignedUploadPartUrl(- fileKey,- uploadId,+ replacement?.outputKey ?? fileKey,+ replacement?.uploadId ?? uploadId,partNumber,{ ContentMD5: body.md5Sum },);@@ -347,6 +452,19 @@ app.post(return c.text(`Video '${encodeURIComponent(videoId)}' not found`);}const [video] = maybeVideo.value;+ const replacement = yield* Effect.try(() =>+ decodeDesktopReuploadToken(uploadId),+ );+ if (replacesVideo && !replacement) {+ return c.json(+ {+ error:+ "Restart this replacement upload to preserve the existing recording",+ code: "REPLACEMENT_RESTART_REQUIRED",+ },+ 409,+ );+ }// Server-side backstop for the free-plan recording cap. First-party// recorders always report durationInSecs and self-stop at the limit@@ -390,18 +508,46 @@ app.post(// "uploading" state. Cleanup is best-effort: the 403 stands// either way.yield* Effect.gen(function* () {- const [bucket] = yield* Storage.getAccessForVideo(video);- yield* bucket.multipart.abort(fileKey, uploadId);- yield* db.use((db) =>- db- .delete(Db.videoUploads)- .where(eq(Db.videoUploads.videoId, videoId)),+ const [bucket] = yield* Storage.getAccessForVideo(+ video,+ replacement ? { resolvePublishedOutput: false } : undefined,);+ if (replacement) {+ yield* Effect.try(() =>+ assertDesktopReuploadTarget(+ replacement,+ video,+ fileKey,+ bucket.provider,+ ),+ );+ yield* db.use((db) =>+ db+ .delete(Db.videoUploads)+ .where(+ and(+ eq(Db.videoUploads.videoId, videoId),+ eq(Db.videoUploads.rawFileKey, replacement.outputKey),+ ),+ ),+ );+ if (bucket.provider === "s3")+ yield* bucket.multipart.abort(+ replacement.outputKey,+ replacement.uploadId,+ );+ } else {+ yield* bucket.multipart.abort(fileKey, uploadId);+ yield* db.use((db) =>+ db+ .delete(Db.videoUploads)+ .where(eq(Db.videoUploads.videoId, videoId)),+ );+ }}).pipe(- Effect.catchAll((error) =>+ Effect.catchAll(() =>Effect.logError("Failed to clean up rejected free-plan multipart upload",- error,),),);@@ -415,6 +561,131 @@ app.post(}}+ if (replacement) {+ return yield* Effect.gen(function* () {+ yield* Effect.try(() =>+ assertDesktopReuploadTarget(replacement, video, fileKey),+ );+ const [bucket] = yield* Storage.getAccessForVideo(video, {+ resolvePublishedOutput: false,+ });+ yield* Effect.try(() =>+ assertDesktopReuploadTarget(+ replacement,+ video,+ fileKey,+ bucket.provider,+ ),+ );+ const outputKey = replacement.outputKey;+ const totalSize = parts.reduce((total, part) => total + part.size, 0);+ const verify = bucket.headObject(outputKey).pipe(+ Effect.filterOrFail(+ (head) => totalSize > 0 && head.ContentLength === totalSize,+ () => new Error("Replacement video could not be verified"),+ ),+ );+ if (video.source.outputKey === outputKey) {+ const head = yield* verify;+ return c.json({+ success: true,+ fileKey: outputKey,+ objectIdentity: head.ETag,+ });+ }+ yield* bucket.multipart+ .complete(outputKey, replacement.uploadId, {+ MultipartUpload: {+ Parts: [...parts]+ .sort((a, b) => a.partNumber - b.partNumber)+ .map((part) => ({+ PartNumber: part.partNumber,+ ETag: part.etag,+ })),+ },+ ...(bucket.provider === "googleDrive"+ ? { MpuObjectSize: totalSize }+ : {}),+ })+ .pipe(+ Effect.catchAll((error) =>+ verify.pipe(Effect.catchAll(() => Effect.fail(error))),+ ),+ );+ const head = yield* verify;+ yield* db.use((db) =>+ db.transaction(async (tx) => {+ const publication = await prepareDesktopReupload(+ tx,+ video,+ replacement,+ );+ if (!publication) return;+ await tx+ .update(Db.videos)+ .set({+ ...publication,+ duration: updateIfDefined(+ body.durationInSecs,+ Db.videos.duration,+ ),+ width: updateIfDefined(body.width, Db.videos.width),+ height: updateIfDefined(body.height, Db.videos.height),+ fps: updateIfDefined(body.fps, Db.videos.fps),+ })+ .where(+ and(+ eq(Db.videos.id, videoId),+ eq(Db.videos.ownerId, user.id),+ ),+ );+ await tx+ .delete(Db.videoUploads)+ .where(+ and(+ eq(Db.videoUploads.videoId, videoId),+ eq(Db.videoUploads.rawFileKey, outputKey),+ ),+ );+ }),+ );+ yield* Effect.tryPromise(() =>+ invalidateGoogleDriveStorageQuotaCache(+ Option.getOrNull(video.storageIntegrationId),+ ),+ ).pipe(Effect.catchAll(Effect.logWarning));+ yield* Effect.tryPromise(() => invalidateReuploadedVideo(video)).pipe(+ Effect.catchAll((error) =>+ Effect.logWarning(+ "Could not refresh derived recording assets; playback uses the new immutable output",+ error,+ ),+ ),+ );+ if (+ shouldQueueTranscriptionAfterMultipartComplete(+ video.source.type,+ false,+ )+ ) {+ yield* Effect.tryPromise(() =>+ queueVideoTranscription(videoId),+ ).pipe(Effect.catchAll(Effect.logWarning));+ }+ return c.json({+ success: true,+ fileKey: outputKey,+ objectIdentity: head.ETag,+ });+ }).pipe(+ Effect.catchAll(() =>+ Effect.succeed(+ c.json({ error: "Could not publish replacement recording" }, 500),+ ),+ ),+ );+ }+return yield* Effect.gen(function* () {const [bucket] = yield* Storage.getAccessForVideo(video, {resolvePublishedOutput: false,@@ -600,13 +871,9 @@ app.post(yield* db.use((db) =>db.transaction(async (tx) => {- const replacement = replacesVideo- ? await prepareDesktopReupload(tx, video)- : {};await tx.update(Db.videos).set({- ...replacement,duration: updateIfDefined(body.durationInSecs,Db.videos.duration,@@ -628,21 +895,6 @@ app.post();}),);- if (replacesVideo) {- yield* Effect.tryPromise(() =>- invalidateReuploadedVideo(video),- ).pipe(- Effect.catchAll((error) =>- Effect.logWarning(- "Published reupload cache invalidation failed",- {- videoId,- error,- },- ),- ),- );- }const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;let mediaProcessingPending = false;@@ -820,6 +1072,62 @@ app.post("/abort", abortRequestValidator, (c) => {}const [video] = maybeVideo.value;+ const replacement = yield* Effect.try(() =>+ decodeDesktopReuploadToken(uploadId),+ );+ if (replacement) {+ yield* Effect.try(() =>+ assertDesktopReuploadTarget(replacement, video, fileKey),+ );+ if (video.source.outputKey === replacement.outputKey) {+ return c.json({+ success: true,+ fileKey: replacement.outputKey,+ uploadId,+ });+ }+ const [bucket] = yield* Storage.getAccessForVideo(video, {+ resolvePublishedOutput: false,+ });+ yield* Effect.try(() =>+ assertDesktopReuploadTarget(+ replacement,+ video,+ fileKey,+ bucket.provider,+ ),+ );++ yield* db.use((db) =>+ db+ .delete(Db.videoUploads)+ .where(+ and(+ eq(Db.videoUploads.videoId, videoId),+ eq(Db.videoUploads.rawFileKey, replacement.outputKey),+ ),+ ),+ );+ // Drive abort deletes the object mapping, which may already be used by a concurrent publication.+ if (bucket.provider === "s3") {+ yield* bucket.multipart+ .abort(replacement.outputKey, replacement.uploadId)+ .pipe(+ Effect.catchAll(() =>+ Effect.logWarning(+ "Could not abort canceled replacement storage upload",+ ),+ ),+ );+ }++ return c.json({+ success: true,+ fileKey: replacement.outputKey,+ uploadId,+ });+ }+const [bucket] = yield* Storage.getAccessForVideo(video);console.log(`Aborting multipart upload ${uploadId} for key: ${fileKey}`);diff --git a/apps/web/lib/desktop-reupload-token.ts b/apps/web/lib/desktop-reupload-token.tsnew file mode 100644index 000000000..fb17333e0--- /dev/null+++ b/apps/web/lib/desktop-reupload-token.ts@@ -0,0 +1,193 @@+import {+ createHash,+ createHmac,+ randomUUID,+ timingSafeEqual,+} from "node:crypto";+import { serverEnv } from "@cap/env";+import { Video } from "@cap/web-domain";+import { Option, Schema } from "effect";+import { z } from "zod";++const TOKEN_PREFIX = "cap-reupload.";+const SIGNING_DOMAIN = "cap-desktop-reupload:v1:";+const TOKEN_LIFETIME_MS = 30 * 24 * 60 * 60 * 1000;+const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;+const MAX_TOKEN_LENGTH = 32_768;+const identifier = z+ .string()+ .min(1)+ .max(255)+ .regex(/^[A-Za-z0-9_-]+$/);+const tokenSchema = z+ .object({+ version: z.literal(1),+ ownerId: identifier,+ videoId: identifier,+ bucketId: z.string().min(1).max(255).nullable(),+ storageIntegrationId: z.string().min(1).max(255).nullable(),+ provider: z.enum(["s3", "googleDrive"]),+ uploadId: z.string().min(1).max(8192),+ outputKey: z.string().min(1).max(1024),+ sourceIdentity: z.string().regex(/^[a-f0-9]{64}$/),+ expiresAt: z.number().int().safe(),+ })+ .strict();++export type DesktopReuploadToken = z.infer<typeof tokenSchema>;+export type DesktopReuploadVideo = Pick<+ Video.Video,+ "id" | "ownerId" | "bucketId" | "storageIntegrationId" | "source"+>;++const decodeSource = Schema.decodeUnknownSync(Video.Video.fields.source);++export function desktopReuploadSourceIdentity(source: unknown): string {+ let normalized: Video.Video["source"];+ try {+ normalized = decodeSource(source);+ } catch {+ throw new Error("Invalid recording source");+ }+ return createHash("sha256")+ .update(JSON.stringify(normalized, Object.keys(normalized).sort()))+ .digest("hex");+}++function hasValidOutputKey(token: DesktopReuploadToken): boolean {+ const prefix = `${token.ownerId}/${token.videoId}/.recording/outputs/reupload-`;+ return (+ token.outputKey.startsWith(prefix) &&+ /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}\/result\.mp4$/.test(+ token.outputKey.slice(prefix.length),+ )+ );+}++function parseToken(value: unknown): DesktopReuploadToken {+ const parsed = tokenSchema.safeParse(value);+ const now = Date.now();+ if (+ !parsed.success ||+ parsed.data.expiresAt <= now ||+ parsed.data.expiresAt > now + TOKEN_LIFETIME_MS + MAX_CLOCK_SKEW_MS ||+ !hasValidOutputKey(parsed.data)+ ) {+ throw new Error("Invalid desktop reupload token");+ }+ return parsed.data;+}++function signature(payload: string): Buffer {+ const secret = serverEnv().NEXTAUTH_SECRET;+ if (!secret) throw new Error("Desktop reupload signing is unavailable");+ return createHmac("sha256", secret)+ .update(SIGNING_DOMAIN)+ .update(payload)+ .digest();+}++export function createDesktopReuploadKey(+ video: Pick<DesktopReuploadVideo, "id" | "ownerId">,+): string {+ if (+ !identifier.safeParse(video.id).success ||+ !identifier.safeParse(video.ownerId).success+ ) {+ throw new Error("Invalid desktop reupload target");+ }+ return `${video.ownerId}/${video.id}/.recording/outputs/reupload-${randomUUID()}/result.mp4`;+}++export function createDesktopReuploadToken(+ video: DesktopReuploadVideo,+ upload: Pick<DesktopReuploadToken, "uploadId" | "provider" | "outputKey">,+): string {+ const token = parseToken({+ version: 1,+ ownerId: video.ownerId,+ videoId: video.id,+ bucketId: Option.getOrNull(video.bucketId),+ storageIntegrationId: Option.getOrNull(video.storageIntegrationId),+ provider: upload.provider,+ uploadId: upload.uploadId,+ outputKey: upload.outputKey,+ sourceIdentity: desktopReuploadSourceIdentity(video.source),+ expiresAt: Date.now() + TOKEN_LIFETIME_MS,+ });+ const payload = Buffer.from(JSON.stringify(token)).toString("base64url");+ const encoded = `${TOKEN_PREFIX}${payload}.${signature(payload).toString("base64url")}`;+ if (encoded.length > MAX_TOKEN_LENGTH) {+ throw new Error("Invalid desktop reupload token");+ }+ return encoded;+}++export function decodeDesktopReuploadToken(+ encoded: string,+): DesktopReuploadToken | null {+ if (!encoded.startsWith(TOKEN_PREFIX)) return null;+ if (encoded.length > MAX_TOKEN_LENGTH) {+ throw new Error("Invalid desktop reupload token");+ }+ const parts = encoded.slice(TOKEN_PREFIX.length).split(".");+ const [payload, signed] = parts;+ if (+ parts.length !== 2 ||+ !payload ||+ !signed ||+ !/^[A-Za-z0-9_-]+$/.test(payload) ||+ !/^[A-Za-z0-9_-]{43}$/.test(signed)+ ) {+ throw new Error("Invalid desktop reupload token");+ }+ const bytes = Buffer.from(payload, "base64url");+ const suppliedSignature = Buffer.from(signed, "base64url");+ if (+ bytes.toString("base64url") !== payload ||+ suppliedSignature.toString("base64url") !== signed ||+ !timingSafeEqual(signature(payload), suppliedSignature)+ ) {+ throw new Error("Invalid desktop reupload token");+ }+ let value: unknown;+ try {+ value = JSON.parse(bytes.toString("utf8"));+ } catch {+ throw new Error("Invalid desktop reupload token");+ }+ return parseToken(value);+}++export function assertDesktopReuploadTarget(+ token: DesktopReuploadToken,+ video: DesktopReuploadVideo,+ requestedCanonicalKey: string,+ provider?: DesktopReuploadToken["provider"],+): void {+ parseToken(token);+ if (+ token.ownerId !== video.ownerId ||+ token.videoId !== video.id ||+ requestedCanonicalKey !== `${video.ownerId}/${video.id}/result.mp4`+ ) {+ throw new Error("Recording target changed during reupload");+ }+ if (+ token.bucketId !== Option.getOrNull(video.bucketId) ||+ token.storageIntegrationId !==+ Option.getOrNull(video.storageIntegrationId) ||+ (provider !== undefined && token.provider !== provider)+ ) {+ throw new Error("Recording storage changed during reupload");+ }+ if (+ (video.source.type === "desktopMP4" || video.source.type === "webMP4") &&+ video.source.outputKey === token.outputKey+ ) {+ return;+ }+ if (desktopReuploadSourceIdentity(video.source) !== token.sourceIdentity) {+ throw new Error("Recording source changed during reupload");+ }+}diff --git a/apps/web/lib/desktop-reupload.ts b/apps/web/lib/desktop-reupload.tsindex cd7a5139f..7ce70d314 100644--- a/apps/web/lib/desktop-reupload.ts+++ b/apps/web/lib/desktop-reupload.ts@@ -3,13 +3,21 @@ import {CreateInvalidationCommand,} from "@aws-sdk/client-cloudfront";import type { db } from "@cap/database";-import { videos } from "@cap/database/schema";+import {+ videoProcessingJobs,+ videos,+ videoUploads,+} from "@cap/database/schema";import { serverEnv } from "@cap/env";import { AwsCredentials } from "@cap/web-backend";import type { Video } from "@cap/web-domain";import { eq } from "drizzle-orm";import { Effect, Option } from "effect";import { retireDesktopRecordingJobForOutputReplacement } from "@/lib/desktop-recording-jobs";+import {+ assertDesktopReuploadTarget,+ type DesktopReuploadToken,+} from "@/lib/desktop-reupload-token";import { runPromise } from "@/lib/server";type ReuploadedVideo = Pick<@@ -20,11 +28,13 @@ type ReuploadedVideo = Pick<export async function prepareDesktopReupload(tx: Parameters<Parameters<ReturnType<typeof db>["transaction"]>[0]>[0],video: ReuploadedVideo,+ token: DesktopReuploadToken,) {- await retireDesktopRecordingJobForOutputReplacement(tx, {- videoId: video.id,- userId: video.ownerId,- });+ await tx+ .select({ videoId: videoProcessingJobs.videoId })+ .from(videoProcessingJobs)+ .where(eq(videoProcessingJobs.videoId, video.id))+ .for("update");const [locked] = await tx.select().from(videos)@@ -32,12 +42,36 @@ export async function prepareDesktopReupload(.for("update");if (!locked ||+ locked.id !== video.id ||locked.ownerId !== video.ownerId ||locked.bucket !== Option.getOrNull(video.bucketId) ||locked.storageIntegrationId !== Option.getOrNull(video.storageIntegrationId)) {throw new Error("Recording storage changed during reupload");}+ assertDesktopReuploadTarget(+ token,+ { ...video, source: locked.source },+ `${video.ownerId}/${video.id}/result.mp4`,+ );+ if (+ (locked.source.type === "desktopMP4" || locked.source.type === "webMP4") &&+ locked.source.outputKey === token.outputKey+ ) {+ return null;+ }+ const [upload] = await tx+ .select({ rawFileKey: videoUploads.rawFileKey })+ .from(videoUploads)+ .where(eq(videoUploads.videoId, video.id))+ .for("update");+ if (upload?.rawFileKey !== token.outputKey) {+ throw new Error("Replacement upload was canceled or superseded");+ }+ await retireDesktopRecordingJobForOutputReplacement(tx, {+ videoId: video.id,+ userId: video.ownerId,+ });const metadata = { ...(locked.metadata ?? {}) };delete metadata.desktopRecordingUpload;delete metadata.summary;@@ -48,8 +82,8 @@ export async function prepareDesktopReupload(return {source:locked.source.type === "webMP4"- ? { type: "webMP4" as const }- : { type: "desktopMP4" as const },+ ? { type: "webMP4" as const, outputKey: token.outputKey }+ : { type: "desktopMP4" as const, outputKey: token.outputKey },metadata,transcriptionStatus: null,};