Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): auto-provision personal org when video create finds none

Richie McIlroya3c99061f879
diff --git a/apps/web/__tests__/unit/desktop-video-create.test.ts b/apps/web/__tests__/unit/desktop-video-create.test.ts
new file mode 100644
index 000000000..f398346e5
--- /dev/null
+++ b/apps/web/__tests__/unit/desktop-video-create.test.ts
@@ -0,0 +1,250 @@
+import { getCurrentUser } from "@cap/database/auth/session";
+import { Option } from "effect";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const schema = {
+ organizations: { table: "organizations" },
+ organizationMembers: { table: "organizationMembers" },
+ users: { table: "users" },
+ videos: { table: "videos" },
+ videoUploads: { table: "videoUploads" },
+ importedVideos: { table: "importedVideos" },
+};
+
+const mockDb = {
+ select: vi.fn(),
+ from: vi.fn(),
+ innerJoin: vi.fn(),
+ insert: vi.fn(),
+ values: vi.fn(),
+ update: vi.fn(),
+ set: vi.fn(),
+ where: vi.fn(),
+ delete: vi.fn(),
+ for: vi.fn(),
+ limit: vi.fn(),
+ transaction: vi.fn(),
+};
+
+vi.mock("@cap/database", () => ({
+ db: () => mockDb,
+}));
+
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: vi.fn(),
+}));
+
+vi.mock("@cap/database/schema", () => schema);
+
+vi.mock("@cap/database/emails/config", () => ({
+ sendEmail: vi.fn(),
+}));
+
+vi.mock("@cap/database/emails/first-shareable-link", () => ({
+ FirstShareableLink: () => null,
+}));
+
+vi.mock("@cap/env", () => ({
+ serverEnv: () => ({
+ CAP_VIDEOS_DEFAULT_PUBLIC: true,
+ WEB_URL: "https://cap.test",
+ }),
+ buildEnv: {
+ NEXT_PUBLIC_IS_CAP: true,
+ NEXT_PUBLIC_WEB_URL: "https://cap.test",
+ },
+}));
+
+vi.mock("@cap/utils", () => ({
+ userIsPro: vi.fn(() => true),
+}));
+
+vi.mock("@cap/web-backend", () => ({
+ Storage: {
+ getOrganizationWritableAccess: vi.fn(),
+ getS3WritableAccessForUser: vi.fn(),
+ },
+}));
+
+vi.mock("@/lib/server", () => ({
+ runPromise: vi.fn(async (value: unknown) => value),
+}));
+
+vi.mock("@/lib/video-storage", () => ({
+ decodeStorageVideo: vi.fn(() => null),
+}));
+
+vi.mock("@/lib/google-drive-storage-quota", () => ({
+ invalidateGoogleDriveStorageQuotaCache: vi.fn(),
+}));
+
+vi.mock("drizzle-orm", () => ({
+ and: vi.fn((...args: unknown[]) => args),
+ eq: vi.fn((field: unknown, value: unknown) => ({ field, value })),
+ count: vi.fn(() => "count()"),
+ lte: vi.fn(() => "lte()"),
+}));
+
+const mockGetCurrentUser = getCurrentUser as ReturnType<typeof vi.fn>;
+const { Storage } = await import("@cap/web-backend");
+
+const effectLike = <T>(value: T) => ({
+ pipe: (fn: (value: T) => unknown) => fn(value),
+});
+
+function resetMockDb() {
+ for (const key of Object.keys(mockDb)) {
+ const fn = mockDb[key as keyof typeof mockDb];
+ if (typeof fn?.mockClear === "function") {
+ fn.mockClear();
+ }
+ }
+ mockDb.select.mockReturnValue(mockDb);
+ mockDb.from.mockReturnValue(mockDb);
+ mockDb.innerJoin.mockReturnValue(mockDb);
+ mockDb.insert.mockReturnValue(mockDb);
+ mockDb.values.mockResolvedValue([]);
+ mockDb.update.mockReturnValue(mockDb);
+ mockDb.set.mockReturnValue(mockDb);
+ mockDb.where.mockResolvedValue([]);
+ mockDb.for.mockResolvedValue([]);
+ mockDb.limit.mockResolvedValue([]);
+ mockDb.transaction.mockImplementation(
+ async (fn: (tx: typeof mockDb) => unknown) => fn(mockDb),
+ );
+}
+
+function insertedValues(table: unknown) {
+ const index = mockDb.insert.mock.calls.findIndex(([t]) => t === table);
+ if (index === -1) return undefined;
+ return mockDb.values.mock.calls[index]?.[0] as
+ | Record<string, unknown>
+ | undefined;
+}
+
+function stubStorage() {
+ const getOrganizationWritableAccess =
+ Storage.getOrganizationWritableAccess as ReturnType<typeof vi.fn>;
+ const getS3WritableAccessForUser =
+ Storage.getS3WritableAccessForUser as ReturnType<typeof vi.fn>;
+ getOrganizationWritableAccess.mockReturnValue(effectLike(Option.none()));
+ getS3WritableAccessForUser.mockReturnValue(
+ effectLike({
+ bucketId: Option.some("bucket-1"),
+ storageIntegrationId: Option.none(),
+ }),
+ );
+}
+
+describe("GET /create", () => {
+ let app: typeof import("@/app/api/desktop/[...route]/video")["app"];
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ resetMockDb();
+ stubStorage();
+ const mod = await import("@/app/api/desktop/[...route]/video");
+ app = mod.app;
+ });
+
+ it("provisions a personal org and creates the video there when the user has none", async () => {
+ mockGetCurrentUser.mockResolvedValue({
+ id: "user-1",
+ email: "[email protected]",
+ defaultOrgId: null,
+ activeOrganizationId: "",
+ });
+ mockDb.where
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([{ count: 5 }]);
+
+ const response = await app.request("https://cap.test/create");
+
+ expect(response.status).toBe(200);
+ expect(mockDb.transaction).toHaveBeenCalledTimes(1);
+
+ const orgValues = insertedValues(schema.organizations) as
+ | { id: string; ownerId: string; name: string }
+ | undefined;
+ expect(orgValues).toMatchObject({
+ ownerId: "user-1",
+ name: "My Organization",
+ });
+
+ expect(insertedValues(schema.organizationMembers)).toMatchObject({
+ userId: "user-1",
+ role: "owner",
+ organizationId: orgValues?.id,
+ });
+
+ expect(mockDb.set).toHaveBeenCalledWith(
+ expect.objectContaining({
+ activeOrganizationId: orgValues?.id,
+ defaultOrgId: orgValues?.id,
+ }),
+ );
+
+ expect(insertedValues(schema.videos)).toMatchObject({
+ orgId: orgValues?.id,
+ ownerId: "user-1",
+ });
+
+ const body = await response.json();
+ expect(body.id).toBeTruthy();
+ });
+
+ it("does not provision when the user already belongs to an org", async () => {
+ mockGetCurrentUser.mockResolvedValue({
+ id: "user-1",
+ email: "[email protected]",
+ defaultOrgId: "org-1",
+ activeOrganizationId: "org-1",
+ });
+ mockDb.where
+ .mockResolvedValueOnce([
+ { id: "org-1", name: "Acme", createdAt: new Date() },
+ ])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([{ count: 5 }]);
+
+ const response = await app.request("https://cap.test/create");
+
+ expect(response.status).toBe(200);
+ expect(mockDb.transaction).not.toHaveBeenCalled();
+
+ expect(insertedValues(schema.videos)).toMatchObject({
+ orgId: "org-1",
+ ownerId: "user-1",
+ });
+ });
+
+ it("heals a dangling defaultOrgId when the user has no remaining orgs", async () => {
+ mockGetCurrentUser.mockResolvedValue({
+ id: "user-1",
+ email: "[email protected]",
+ defaultOrgId: "org-stale",
+ activeOrganizationId: "",
+ });
+ mockDb.where
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([{ count: 5 }]);
+
+ const response = await app.request("https://cap.test/create");
+
+ expect(response.status).toBe(200);
+ expect(mockDb.transaction).toHaveBeenCalledTimes(1);
+
+ const orgValues = insertedValues(schema.organizations) as
+ | { id: string }
+ | undefined;
+
+ expect(insertedValues(schema.videos)).toMatchObject({
+ orgId: orgValues?.id,
+ });
+ });
+});
diff --git a/apps/web/app/api/desktop/[...route]/video.ts b/apps/web/app/api/desktop/[...route]/video.ts
index 4d22e637b..aeb97f303 100644
--- a/apps/web/app/api/desktop/[...route]/video.ts
+++ b/apps/web/app/api/desktop/[...route]/video.ts
@@ -183,6 +183,35 @@ app.get(
ownedOrganizations,
memberOrganizations,
);
+
+ // Accounts can end up org-less (e.g. after declining a team invite or
+ // being removed from their last org); provision a personal org like
+ // signup does instead of failing every upload.
+ if (userOrganizations.length === 0) {
+ const organizationId = Organisation.OrganisationId.make(nanoId());
+ await db().transaction(async (tx) => {
+ await tx.insert(organizations).values({
+ id: organizationId,
+ ownerId: user.id,
+ name: "My Organization",
+ });
+ await tx.insert(organizationMembers).values({
+ id: nanoId(),
+ organizationId,
+ userId: user.id,
+ role: "owner",
+ });
+ await tx
+ .update(users)
+ .set({
+ activeOrganizationId: organizationId,
+ defaultOrgId: organizationId,
+ })
+ .where(eq(users.id, user.id));
+ });
+ userOrganizations.push({ id: organizationId, name: "My Organization" });
+ }
+
const userOrgIds = userOrganizations.map((org) => org.id);
let videoOrgId: Organisation.OrganisationId;