Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: add an authenticated owner change for imported Loom videos

Richie McIlroyfb655c543daf
diff --git a/apps/web/__tests__/unit/loom-operator-tools.test.ts b/apps/web/__tests__/unit/loom-operator-tools.test.ts
new file mode 100644
index 000000000..daf484542
--- /dev/null
+++ b/apps/web/__tests__/unit/loom-operator-tools.test.ts
@@ -0,0 +1,320 @@
+import type { HttpApi } from "@effect/platform";
+import { Effect, type Layer as EffectLayer } from "effect";
+import { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ selects: [] as unknown[][],
+ affectedRows: 1,
+ updates: [] as Array<Record<string, unknown>>,
+ deletes: 0,
+ pro: true,
+ process: vi.fn(),
+ objects: [] as Array<{ Key: string; Size: number }>,
+ copies: [] as Array<[string, string]>,
+ removed: [] as string[][],
+ headSize: undefined as number | undefined,
+}));
+
+vi.mock("server-only", () => ({}));
+vi.mock("@cap/database", () => {
+ const selection = {
+ from: () => selection,
+ innerJoin: () => selection,
+ leftJoin: () => selection,
+ where: () => selection,
+ limit: async () => mocks.selects.shift() ?? [],
+ };
+ const tx = {
+ update: () => ({
+ set: (values: Record<string, unknown>) => ({
+ where: async () => {
+ mocks.updates.push(values);
+ return [{ affectedRows: mocks.affectedRows }];
+ },
+ }),
+ }),
+ delete: () => ({
+ where: async () => {
+ mocks.deletes++;
+ },
+ }),
+ };
+ return {
+ db: () => ({
+ select: () => selection,
+ transaction: async (run: (handle: typeof tx) => Promise<unknown>) =>
+ run(tx),
+ }),
+ };
+});
+vi.mock("@cap/database/schema", () => ({
+ importedVideos: { id: "i.id", orgId: "i.orgId", source: "i.source" },
+ organizationMembers: { organizationId: "m.org", userId: "m.user" },
+ organizations: { id: "o.id", ownerId: "o.owner", tombstoneAt: "o.tomb" },
+ sharedVideos: { videoId: "s.video" },
+ spaceVideos: { videoId: "sv.video" },
+ videos: {
+ id: "v.id",
+ ownerId: "v.owner",
+ orgId: "v.org",
+ bucket: "v.bucket",
+ storageIntegrationId: "v.integration",
+ },
+ videoUploads: { videoId: "u.video", phase: "u.phase" },
+}));
+vi.mock("@cap/env", () => ({
+ serverEnv: () => ({ MEDIA_SERVER_WEBHOOK_SECRET: "media-secret" }),
+}));
+vi.mock("@cap/web-backend", () => ({
+ Storage: {
+ getAccessForVideo: () =>
+ Effect.succeed([
+ {
+ bucketName: "capso",
+ listObjects: () =>
+ Effect.succeed({ Contents: mocks.objects, IsTruncated: false }),
+ copyObject: (source: string, destination: string) => {
+ mocks.copies.push([source, destination]);
+ return Effect.succeed({});
+ },
+ headObject: (key: string) =>
+ Effect.succeed({
+ ContentLength:
+ mocks.headSize ??
+ mocks.objects.find((object) =>
+ key.endsWith(object.Key.split("/").slice(2).join("/")),
+ )?.Size,
+ }),
+ deleteObjects: (keys: Array<{ Key: string }>) => {
+ mocks.removed.push(keys.map(({ Key }) => Key));
+ return Effect.succeed({});
+ },
+ },
+ ]),
+ },
+}));
+vi.mock("@/lib/loom-csv-import", () => ({
+ processLoomCsvRows: mocks.process,
+}));
+vi.mock("@/lib/org-pro", () => ({
+ isOrganizationOwnerPro: async () => mocks.pro,
+}));
+
+type ApiLayer = EffectLayer.Layer<HttpApi.Api>;
+
+vi.mock("@/lib/server", async () => {
+ const { HttpApiBuilder, HttpServer } = await import("@effect/platform");
+ const { Effect, Layer } = await import("effect");
+ return {
+ runPromise: (effect: Effect.Effect<unknown>) => Effect.runPromise(effect),
+ apiToHandler: (api: ApiLayer) => {
+ const { handler } = HttpApiBuilder.toWebHandler(
+ Layer.mergeAll(api, HttpServer.layerContext),
+ );
+ return (request: Request) => handler(request);
+ },
+ };
+});
+
+import { POST as importCsv } from "@/app/api/internal/loom-imports/csv/route";
+import { POST as reassign } from "@/app/api/internal/loom-imports/reassign/route";
+import { reassignLoomImport } from "@/lib/loom-import-reassign";
+
+const call = (
+ handler: (request: Request) => Promise<Response>,
+ path: string,
+ body: unknown,
+ secret: string | null = "media-secret",
+) =>
+ handler(
+ new NextRequest(`https://cap.so/api/internal/loom-imports/${path}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...(secret ? { "x-media-server-secret": secret } : {}),
+ },
+ body: JSON.stringify(body),
+ }),
+ );
+
+const ids = {
+ org: "orgaaaaaaaaaaaa",
+ from: "fromaaaaaaaaaaa",
+ to: "toaaaaaaaaaaaaa",
+ video: "videoaaaaaaaaaa",
+};
+const importedVideo = (overrides: Record<string, unknown> = {}) => ({
+ ownerId: ids.from,
+ orgId: ids.org,
+ bucketId: null,
+ storageIntegrationId: null,
+ uploadPhase: null,
+ ...overrides,
+});
+
+beforeEach(() => {
+ mocks.selects = [];
+ mocks.affectedRows = 1;
+ mocks.updates = [];
+ mocks.deletes = 0;
+ mocks.pro = true;
+ mocks.process.mockReset().mockResolvedValue({
+ success: true,
+ importedCount: 1,
+ failedCount: 0,
+ results: [
+ { rowNumber: 2, userEmail: "[email protected]", success: true, videoId: "v1" },
+ ],
+ });
+ mocks.objects = [
+ { Key: `${ids.from}/${ids.video}/result.mp4`, Size: 100 },
+ { Key: `${ids.from}/${ids.video}/screenshot/screen-capture.jpg`, Size: 5 },
+ ];
+ mocks.copies = [];
+ mocks.removed = [];
+ mocks.headSize = undefined;
+});
+
+describe("operator CSV import", () => {
+ const body = {
+ organizationId: ids.org,
+ rows: [
+ {
+ rowNumber: 2,
+ loomUrl: "https://www.loom.com/share/abc",
+ userEmail: "[email protected]",
+ },
+ ],
+ };
+
+ it("requires the media server secret", async () => {
+ expect((await call(importCsv, "csv", body, null)).status).toBe(401);
+ expect((await call(importCsv, "csv", body, "wrong")).status).toBe(401);
+ expect(mocks.process).not.toHaveBeenCalled();
+ });
+
+ it("imports rows as the workspace owner", async () => {
+ mocks.selects = [[{ ownerId: "owneraaaaaaaaaa" }]];
+ const response = await call(importCsv, "csv", body);
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ importedCount: 1 });
+ expect(mocks.process).toHaveBeenCalledWith({
+ rows: [{ ...body.rows[0], spaceName: "" }],
+ orgId: ids.org,
+ actorId: "owneraaaaaaaaaa",
+ });
+ });
+
+ it("refuses missing workspaces and workspaces without Pro", async () => {
+ expect((await call(importCsv, "csv", body)).status).toBe(404);
+ mocks.selects = [[{ ownerId: "owneraaaaaaaaaa" }]];
+ mocks.pro = false;
+ expect((await call(importCsv, "csv", body)).status).toBe(403);
+ expect(mocks.process).not.toHaveBeenCalled();
+ });
+
+ it("rejects batches over 25 rows", async () => {
+ const rows = Array.from({ length: 26 }, (_, index) => ({
+ ...body.rows[0],
+ rowNumber: index + 2,
+ }));
+ expect(
+ (await call(importCsv, "csv", { organizationId: ids.org, rows })).status,
+ ).toBe(400);
+ });
+});
+
+describe("reassignLoomImport", () => {
+ const input = {
+ organizationId: ids.org,
+ videoId: ids.video,
+ fromUserId: ids.from,
+ toUserId: ids.to,
+ };
+
+ it("copies every object, switches owner privately, then removes the old copies", async () => {
+ mocks.selects = [[importedVideo()], [{ userId: ids.to }]];
+ await expect(reassignLoomImport(input)).resolves.toEqual({
+ videoId: ids.video,
+ status: "moved",
+ copiedObjects: 2,
+ });
+ expect(mocks.copies).toEqual([
+ [
+ `capso/${ids.from}/${ids.video}/result.mp4`,
+ `${ids.to}/${ids.video}/result.mp4`,
+ ],
+ [
+ `capso/${ids.from}/${ids.video}/screenshot/screen-capture.jpg`,
+ `${ids.to}/${ids.video}/screenshot/screen-capture.jpg`,
+ ],
+ ]);
+ expect(mocks.updates).toEqual([{ ownerId: ids.to, public: false }]);
+ expect(mocks.deletes).toBe(2);
+ expect(mocks.removed).toEqual([mocks.objects.map(({ Key }) => Key)]);
+ });
+
+ it.each([
+ [[], "not a Loom import here"],
+ [[importedVideo({ orgId: "otheraaaaaaaaaa" })], "not a Loom import here"],
+ [[importedVideo({ ownerId: ids.to })], "already owned"],
+ [[importedVideo({ ownerId: "someoneaaaaaaaa" })], "different owner"],
+ [[importedVideo({ bucketId: "bucket" })], "custom storage"],
+ [[importedVideo({ uploadPhase: "processing" })], "import not finished"],
+ [[importedVideo(), []], "new owner not a member"],
+ ])("leaves unsafe moves alone: %#", async (selects, reason) => {
+ mocks.selects = (selects as unknown[]).map((row) =>
+ Array.isArray(row) ? row : [row],
+ );
+ await expect(reassignLoomImport(input)).resolves.toMatchObject({
+ status: "skipped",
+ reason,
+ });
+ expect(mocks.copies).toEqual([]);
+ expect(mocks.updates).toEqual([]);
+ });
+
+ it("keeps the original when a copy does not match", async () => {
+ mocks.selects = [[importedVideo()], [{ userId: ids.to }]];
+ mocks.headSize = 1;
+ await expect(reassignLoomImport(input)).rejects.toThrow("size mismatch");
+ expect(mocks.updates).toEqual([]);
+ expect(mocks.removed).toEqual([]);
+ });
+
+ it("keeps the original files when the owner changed during the move", async () => {
+ mocks.selects = [[importedVideo()], [{ userId: ids.to }]];
+ mocks.affectedRows = 0;
+ await expect(reassignLoomImport(input)).resolves.toMatchObject({
+ status: "failed",
+ });
+ expect(mocks.removed).toEqual([]);
+ });
+});
+
+describe("POST /api/internal/loom-imports/reassign", () => {
+ const body = {
+ organizationId: ids.org,
+ fromUserId: ids.from,
+ toUserId: ids.to,
+ videoIds: [ids.video],
+ };
+
+ it("requires the media server secret", async () => {
+ expect((await call(reassign, "reassign", body, null)).status).toBe(401);
+ expect(mocks.copies).toEqual([]);
+ });
+
+ it("reports each video once", async () => {
+ mocks.selects = [[importedVideo()], [{ userId: ids.to }]];
+ const response = await call(reassign, "reassign", {
+ ...body,
+ videoIds: [ids.video, ids.video],
+ });
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({
+ results: [{ videoId: ids.video, status: "moved", copiedObjects: 2 }],
+ });
+ });
+});
diff --git a/apps/web/app/api/internal/loom-imports/reassign/route.ts b/apps/web/app/api/internal/loom-imports/reassign/route.ts
new file mode 100644
index 000000000..7e4137137
--- /dev/null
+++ b/apps/web/app/api/internal/loom-imports/reassign/route.ts
@@ -0,0 +1,97 @@
+import { createHash, timingSafeEqual } from "node:crypto";
+import { serverEnv } from "@cap/env";
+import {
+ HttpApi,
+ HttpApiBuilder,
+ HttpApiEndpoint,
+ HttpApiError,
+ HttpApiGroup,
+ HttpServerRequest,
+} from "@effect/platform";
+import { Effect, Layer, Schema } from "effect";
+import {
+ type LoomReassignOutcome,
+ reassignLoomImport,
+} from "@/lib/loom-import-reassign";
+import { apiToHandler } from "@/lib/server";
+
+const MAX_VIDEOS_PER_REQUEST = 25;
+const CapId = Schema.String.pipe(Schema.pattern(/^[A-Za-z0-9_-]{15}$/));
+
+class Api extends HttpApi.make("LoomImportReassignApi").add(
+ HttpApiGroup.make("root").add(
+ HttpApiEndpoint.post("reassign")`/api/internal/loom-imports/reassign`
+ .setPayload(
+ Schema.Struct({
+ organizationId: CapId,
+ fromUserId: CapId,
+ toUserId: CapId,
+ videoIds: Schema.Array(CapId).pipe(
+ Schema.minItems(1),
+ Schema.maxItems(MAX_VIDEOS_PER_REQUEST),
+ ),
+ }),
+ )
+ .addSuccess(
+ Schema.Struct({
+ results: Schema.Array(
+ Schema.Struct({
+ videoId: Schema.String,
+ status: Schema.Literal("moved", "skipped", "failed"),
+ copiedObjects: Schema.optional(Schema.Number),
+ reason: Schema.optional(Schema.String),
+ }),
+ ),
+ }),
+ )
+ .addError(HttpApiError.Unauthorized),
+ ),
+) {}
+
+function digest(value: string) {
+ return createHash("sha256").update(value, "utf8").digest();
+}
+
+const ApiLive = HttpApiBuilder.api(Api).pipe(
+ Layer.provide(
+ HttpApiBuilder.group(Api, "root", (handlers) =>
+ handlers.handle("reassign", ({ payload }) =>
+ Effect.gen(function* () {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const secret = serverEnv().MEDIA_SERVER_WEBHOOK_SECRET;
+ const header = request.headers["x-media-server-secret"];
+ if (
+ !secret ||
+ !header ||
+ !timingSafeEqual(digest(header), digest(secret))
+ )
+ return yield* new HttpApiError.Unauthorized();
+ const results = yield* Effect.forEach(
+ [...new Set(payload.videoIds)],
+ (videoId) =>
+ Effect.promise(
+ (): Promise<LoomReassignOutcome> =>
+ reassignLoomImport({
+ organizationId: payload.organizationId,
+ videoId,
+ fromUserId: payload.fromUserId,
+ toUserId: payload.toUserId,
+ }).catch((error) => ({
+ videoId,
+ status: "failed",
+ reason:
+ error instanceof Error ? error.message : String(error),
+ })),
+ ),
+ { concurrency: 5 },
+ );
+ return { results };
+ }),
+ ),
+ ),
+ ),
+);
+
+export const POST = apiToHandler(ApiLive);
+export const maxDuration = 300;
+export const dynamic = "force-dynamic";
diff --git a/apps/web/lib/loom-import-reassign.ts b/apps/web/lib/loom-import-reassign.ts
new file mode 100644
index 000000000..f9b0b747f
--- /dev/null
+++ b/apps/web/lib/loom-import-reassign.ts
@@ -0,0 +1,179 @@
+import "server-only";
+
+import { db } from "@cap/database";
+import {
+ importedVideos,
+ organizationMembers,
+ sharedVideos,
+ spaceVideos,
+ videos,
+ videoUploads,
+} from "@cap/database/schema";
+import { Storage } from "@cap/web-backend";
+import { Organisation, User, Video } from "@cap/web-domain";
+import { and, eq } from "drizzle-orm";
+import { Option } from "effect";
+import { runPromise } from "@/lib/server";
+
+export type LoomReassignOutcome =
+ | { videoId: string; status: "moved"; copiedObjects: number }
+ | { videoId: string; status: "skipped" | "failed"; reason: string };
+
+function getAffectedRows(result: unknown) {
+ const header = Array.isArray(result) ? result[0] : result;
+ return (header as { affectedRows?: number } | undefined)?.affectedRows ?? 0;
+}
+
+function storageVideo(id: string, ownerId: string, orgId: string) {
+ return Video.Video.make({
+ id: Video.VideoId.make(id),
+ ownerId: User.UserId.make(ownerId),
+ orgId: Organisation.OrganisationId.make(orgId),
+ name: "Loom import owner change",
+ public: false,
+ source: { type: "MediaConvert" },
+ metadata: Option.none(),
+ bucketId: Option.none(),
+ storageIntegrationId: Option.none(),
+ folderId: Option.none(),
+ transcriptionStatus: Option.none(),
+ width: Option.none(),
+ height: Option.none(),
+ duration: Option.none(),
+ createdAt: new Date(0),
+ updatedAt: new Date(0),
+ });
+}
+
+async function listObjects(videoId: string, ownerId: string, orgId: string) {
+ const [bucket] = await runPromise(
+ Storage.getAccessForVideo(storageVideo(videoId, ownerId, orgId)),
+ );
+ const prefix = `${ownerId}/${videoId}/`;
+ const objects: Array<{ key: string; size: number }> = [];
+ let continuationToken: string | undefined;
+ do {
+ const page = await runPromise(
+ bucket.listObjects({ prefix, maxKeys: 1_000, continuationToken }),
+ );
+ for (const object of page.Contents ?? []) {
+ if (!object.Key || object.Size === undefined) continue;
+ objects.push({ key: object.Key, size: object.Size });
+ }
+ continuationToken = page.IsTruncated
+ ? page.NextContinuationToken
+ : undefined;
+ } while (continuationToken);
+ return { bucket, prefix, objects };
+}
+
+export async function reassignLoomImport({
+ organizationId,
+ videoId,
+ fromUserId,
+ toUserId,
+}: {
+ organizationId: string;
+ videoId: string;
+ fromUserId: string;
+ toUserId: string;
+}): Promise<LoomReassignOutcome> {
+ const id = Video.VideoId.make(videoId);
+ const [video] = await db()
+ .select({
+ ownerId: videos.ownerId,
+ orgId: videos.orgId,
+ bucketId: videos.bucket,
+ storageIntegrationId: videos.storageIntegrationId,
+ uploadPhase: videoUploads.phase,
+ })
+ .from(videos)
+ .innerJoin(
+ importedVideos,
+ and(
+ eq(importedVideos.id, videos.id),
+ eq(importedVideos.orgId, videos.orgId),
+ eq(importedVideos.source, "loom"),
+ ),
+ )
+ .leftJoin(videoUploads, eq(videoUploads.videoId, videos.id))
+ .where(eq(videos.id, id))
+ .limit(1);
+ if (!video || video.orgId !== organizationId)
+ return { videoId, status: "skipped", reason: "not a Loom import here" };
+ if (video.ownerId === toUserId)
+ return { videoId, status: "skipped", reason: "already owned" };
+ if (video.ownerId !== fromUserId)
+ return { videoId, status: "skipped", reason: "different owner" };
+ if (video.bucketId || video.storageIntegrationId)
+ return { videoId, status: "skipped", reason: "custom storage" };
+ if (video.uploadPhase)
+ return { videoId, status: "skipped", reason: "import not finished" };
+
+ const [member] = await db()
+ .select({ userId: organizationMembers.userId })
+ .from(organizationMembers)
+ .where(
+ and(
+ eq(
+ organizationMembers.organizationId,
+ Organisation.OrganisationId.make(organizationId),
+ ),
+ eq(organizationMembers.userId, User.UserId.make(toUserId)),
+ ),
+ )
+ .limit(1);
+ if (!member)
+ return { videoId, status: "skipped", reason: "new owner not a member" };
+
+ const source = await listObjects(videoId, fromUserId, organizationId);
+ if (source.objects.length === 0)
+ return { videoId, status: "failed", reason: "no media found" };
+ const destinationPrefix = `${toUserId}/${videoId}/`;
+ let copiedObjects = 0;
+ for (let index = 0; index < source.objects.length; index += 4) {
+ await Promise.all(
+ source.objects.slice(index, index + 4).map(async (object) => {
+ const destinationKey = object.key.replace(
+ source.prefix,
+ destinationPrefix,
+ );
+ await runPromise(
+ source.bucket.copyObject(
+ `${source.bucket.bucketName}/${object.key}`,
+ destinationKey,
+ ),
+ );
+ const head = await runPromise(source.bucket.headObject(destinationKey));
+ if (head.ContentLength !== object.size)
+ throw new Error(`Copied object size mismatch for ${object.key}`);
+ copiedObjects++;
+ }),
+ );
+ }
+
+ const updated = await db().transaction(async (tx) => {
+ const result = await tx
+ .update(videos)
+ .set({ ownerId: User.UserId.make(toUserId), public: false })
+ .where(
+ and(
+ eq(videos.id, id),
+ eq(videos.ownerId, User.UserId.make(fromUserId)),
+ ),
+ );
+ if (getAffectedRows(result) !== 1) return false;
+ await tx.delete(sharedVideos).where(eq(sharedVideos.videoId, id));
+ await tx.delete(spaceVideos).where(eq(spaceVideos.videoId, id));
+ return true;
+ });
+ if (!updated)
+ return { videoId, status: "failed", reason: "owner changed during move" };
+
+ await runPromise(
+ source.bucket.deleteObjects(
+ source.objects.map((object) => ({ Key: object.key })),
+ ),
+ ).catch(() => undefined);
+ return { videoId, status: "moved", copiedObjects };
+}