diff --git a/apps/web/__tests__/unit/video-domain-info-route.test.ts b/apps/web/__tests__/unit/video-domain-info-route.test.ts new file mode 100644 index 00000000000..4ab1fd42095 --- /dev/null +++ b/apps/web/__tests__/unit/video-domain-info-route.test.ts @@ -0,0 +1,151 @@ +import type { Effect as EffectTypes } from "effect"; +import { NextRequest } from "next/server"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + view: "allowed", + viewerId: "owner" as string | null, + query: vi.fn(), +})); + +vi.mock("@cap/web-backend", async () => { + const { CurrentUser, Organisation, Policy, User, Video } = await import( + "@cap/web-domain" + ); + const { drizzle } = await import("drizzle-orm/mysql-proxy"); + const { Effect, Option } = await import("effect"); + const database = drizzle(mocks.query); + return { + Database: Effect.succeed({ + use: (query: (db: typeof database) => PromiseLike) => + Effect.tryPromise(() => Promise.resolve(query(database))), + }), + provideOptionalAuth: (effect: EffectTypes.Effect) => + mocks.viewerId + ? effect.pipe( + Effect.provideService(CurrentUser, { + id: User.UserId.make(mocks.viewerId), + email: "viewer@example.com", + activeOrganizationId: Organisation.OrganisationId.make("active"), + iconUrlOrKey: Option.none(), + }), + ) + : effect, + Videos: Effect.succeed({ + getByIdForViewing: (id: string) => { + if (mocks.view === "denied") { + return Effect.fail(new Policy.PolicyDeniedError()); + } + if (mocks.view === "password-required") { + return Effect.fail( + new Video.VerifyVideoPasswordError({ + id: Video.VideoId.make(id), + cause: "not-provided", + }), + ); + } + if (mocks.view === "missing") return Effect.succeed(Option.none()); + return Effect.succeed( + Option.some([{ id, ownerId: "owner", orgId: "recording-org" }]), + ); + }, + }), + }; +}); +vi.mock("@/lib/server", async () => { + const { HttpApiBuilder, HttpServer } = await import("@effect/platform"); + const { Layer } = await import("effect"); + return { + apiToHandler: (api: Parameters[0]) => + HttpApiBuilder.toWebHandler( + Layer.mergeAll(api, HttpServer.layerContext) as never, + ).handler, + }; +}); + +import { GET } from "@/app/api/video/domain-info/route"; + +describe("video domain information", () => { + const request = () => + new NextRequest("https://cap.test/api/video/domain-info?videoId=video"); + + beforeEach(() => { + mocks.view = "allowed"; + mocks.viewerId = "owner"; + mocks.query.mockReset(); + }); + + it("returns the existing error response when the video ID is missing", async () => { + const response = await GET( + new NextRequest("https://cap.test/api/video/domain-info"), + ); + + expect(response.status).toBe(400); + expect(response.headers.get("cache-control")).toBe("private, no-store"); + expect(await response.json()).toEqual({ error: "Video ID is required" }); + }); + + it.each(["missing", "denied", "password-required"])( + "returns not found for %s videos", + async (view) => { + mocks.view = view; + const response = await GET(request()); + + expect(response.status).toBe(404); + expect(response.headers.get("cache-control")).toBe("private, no-store"); + expect(await response.json()).toEqual({ error: "Video not found" }); + expect(mocks.query).not.toHaveBeenCalled(); + }, + ); + + it.each(["member", null])( + "keeps workspace metadata private from an authorized viewer (%s)", + async (viewerId) => { + mocks.viewerId = viewerId; + + const response = await GET(request()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + customDomain: null, + domainVerified: false, + }); + expect(mocks.query).not.toHaveBeenCalled(); + }, + ); + + it("returns only the verified domain of the recording's workspace to its owner", async () => { + mocks.query.mockResolvedValue({ + rows: [["video.example.com", "2026-01-01 00:00:00"]], + }); + + const response = await GET(request()); + + expect(response.status).toBe(200); + expect(response.headers.get("cache-control")).toBe("private, no-store"); + expect(await response.json()).toEqual({ + customDomain: "video.example.com", + domainVerified: true, + }); + expect(mocks.query).toHaveBeenCalledTimes(1); + expect(mocks.query).toHaveBeenCalledWith( + expect.stringContaining( + "`organizations`.`id` = ? and `organizations`.`tombstoneAt` is null", + ), + ["recording-org", 1], + expect.anything(), + ); + }); + + it("keeps an unverified domain private", async () => { + mocks.query.mockResolvedValue({ rows: [["unverified.example.com", null]] }); + + const response = await GET(request()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + customDomain: null, + domainVerified: false, + }); + }); +}); diff --git a/apps/web/__tests__/unit/video-preview-route.test.ts b/apps/web/__tests__/unit/video-preview-route.test.ts new file mode 100644 index 00000000000..c8c8258109e --- /dev/null +++ b/apps/web/__tests__/unit/video-preview-route.test.ts @@ -0,0 +1,138 @@ +import { NextRequest } from "next/server"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + video: { id: "video", ownerId: "owner" }, + view: "allowed", + hasPreview: true, + storage: vi.fn(), + signedUrl: "https://storage.example.com/preview.gif?signature=example", +})); + +vi.mock("@cap/web-backend", async () => { + const { Policy, Video } = await import("@cap/web-domain"); + const { Effect, Option } = await import("effect"); + return { + provideOptionalAuth: (effect: unknown) => effect, + Storage: { + getAccessForVideo: () => { + mocks.storage(); + return Effect.succeed([ + { + headObject: () => + mocks.hasPreview + ? Effect.void + : Effect.fail(new Error("Preview unavailable")), + getSignedObjectUrl: () => Effect.succeed(mocks.signedUrl), + }, + ]); + }, + }, + Videos: Effect.succeed({ + getByIdForViewing: () => { + if (mocks.view === "denied") + return Effect.fail(new Policy.PolicyDeniedError()); + if (mocks.view === "password-required") + return Effect.fail( + new Video.VerifyVideoPasswordError({ + id: Video.VideoId.make(mocks.video.id), + cause: "not-provided", + }), + ); + return Effect.succeed( + mocks.view === "missing" ? Option.none() : Option.some([mocks.video]), + ); + }, + }), + }; +}); + +vi.mock("@/lib/loom-preview-gif", () => ({})); +vi.mock("@/lib/server", async () => { + const { Effect } = await import("effect"); + return { runPromise: Effect.runPromise }; +}); + +import { GET, HEAD } from "@/app/api/video/preview/route"; + +describe("video preview redirects", () => { + beforeEach(() => { + mocks.view = "allowed"; + mocks.hasPreview = true; + mocks.storage.mockClear(); + }); + + it.each([ + ["GET", GET], + ["HEAD", HEAD], + ] as const)( + "keeps signed preview redirects private for %s", + async (method, handler) => { + const response = await handler( + new NextRequest("https://cap.test/api/video/preview?videoId=video", { + method, + }), + ); + + expect(response.status).toBe(302); + expect(response.headers.get("location")).toBe(mocks.signedUrl); + expect(response.headers.get("cache-control")).toBe( + "private, no-store, max-age=0", + ); + }, + ); + + it.each(["missing-video", "missing-preview"])( + "keeps the Open Graph fallback for %s", + async (reason) => { + if (reason === "missing-video") mocks.view = "missing"; + else mocks.hasPreview = false; + const response = await GET( + new NextRequest( + "https://cap.test/api/video/preview?videoId=video&fallback=og", + ), + ); + + expect(response.status).toBe(302); + expect(response.headers.get("location")).toBe( + "https://cap.test/api/video/og?videoId=video", + ); + expect(response.headers.get("cache-control")).toBe( + "private, no-store, max-age=0", + ); + }, + ); + + it.each(["denied", "password-required"])( + "returns a private 404 when access is %s", + async (view) => { + mocks.view = view; + const response = await GET( + new NextRequest( + "https://cap.test/api/video/preview?videoId=video&fallback=og", + ), + ); + + expect(response.status).toBe(404); + expect(response.headers.get("location")).toBeNull(); + expect(response.headers.get("cache-control")).toBe( + "private, no-store, max-age=0", + ); + expect(mocks.storage).not.toHaveBeenCalled(); + }, + ); + + it("keeps a missing video private without an Open Graph fallback", async () => { + mocks.view = "missing"; + const response = await GET( + new NextRequest( + "https://cap.test/api/video/preview?videoId=video&fallback=none", + ), + ); + + expect(response.status).toBe(404); + expect(response.headers.get("cache-control")).toBe( + "private, no-store, max-age=0", + ); + }); +}); diff --git a/apps/web/app/api/video/domain-info/route.ts b/apps/web/app/api/video/domain-info/route.ts index 803bb33af35..6f04f1a3261 100644 --- a/apps/web/app/api/video/domain-info/route.ts +++ b/apps/web/app/api/video/domain-info/route.ts @@ -1,102 +1,106 @@ -import { db } from "@cap/database"; -import { organizations, sharedVideos, videos } from "@cap/database/schema"; -import { Video } from "@cap/web-domain"; -import { eq } from "drizzle-orm"; -import type { NextRequest } from "next/server"; +import { organizations } from "@cap/database/schema"; +import { Database, provideOptionalAuth, Videos } from "@cap/web-backend"; +import { CurrentUser, Video } from "@cap/web-domain"; +import { + HttpApi, + HttpApiBuilder, + HttpApiEndpoint, + HttpApiGroup, + HttpServerResponse, +} from "@effect/platform"; +import { and, eq, isNull } from "drizzle-orm"; +import { Effect, Layer, Option, Schema } from "effect"; +import { apiToHandler } from "@/lib/server"; -export async function GET(request: NextRequest) { - const { searchParams } = request.nextUrl; - const videoId = searchParams.get("videoId"); +const privateHeaders = { "Cache-Control": "private, no-store" }; - if (!videoId) { - return Response.json({ error: "Video ID is required" }, { status: 400 }); - } +class Api extends HttpApi.make("VideoDomainInfo").add( + HttpApiGroup.make("video").add( + HttpApiEndpoint.get("domainInfo")`/api/video/domain-info`.setUrlParams( + Schema.Struct({ videoId: Schema.optional(Schema.String) }), + ), + ), +) {} - try { - // First, get the video to find the owner or shared space - const [video] = await db() - .select({ - id: videos.id, - ownerId: videos.ownerId, - }) - .from(videos) - .where(eq(videos.id, Video.VideoId.make(videoId))) - .limit(1); - - if (!video) { - return Response.json({ error: "Video not found" }, { status: 404 }); +const getDomainInfo = (videoId: string | undefined) => + Effect.gen(function* () { + if (!videoId) { + return HttpServerResponse.unsafeJson( + { error: "Video ID is required" }, + { status: 400, headers: privateHeaders }, + ); } - if (!video.ownerId) { - return Response.json({ error: "Invalid video data" }, { status: 500 }); + const videos = yield* Videos; + const viewable = yield* videos + .getByIdForViewing(Video.VideoId.make(videoId)) + .pipe( + Effect.catchTags({ + PolicyDenied: () => Effect.succeedNone, + VerifyVideoPasswordError: () => Effect.succeedNone, + }), + ); + if (Option.isNone(viewable)) { + return HttpServerResponse.unsafeJson( + { error: "Video not found" }, + { status: 404, headers: privateHeaders }, + ); } - // Check if the video is shared with a space - const sharedVideo = await db() - .select({ - organizationId: sharedVideos.organizationId, - }) - .from(sharedVideos) - .where(eq(sharedVideos.videoId, Video.VideoId.make(videoId))) - .limit(1); - - let organizationId = null; - if ( - sharedVideo.length > 0 && - sharedVideo[0] && - sharedVideo[0].organizationId - ) { - organizationId = sharedVideo[0].organizationId; - } + const [video] = viewable.value; + const viewer = yield* Effect.serviceOption(CurrentUser); + if (Option.exists(viewer, (user) => user.id === video.ownerId)) { + const database = yield* Database; + const [organization] = yield* database.use((db) => + db + .select({ + customDomain: organizations.customDomain, + domainVerified: organizations.domainVerified, + }) + .from(organizations) + .where( + and( + eq(organizations.id, video.orgId), + isNull(organizations.tombstoneAt), + ), + ) + .limit(1), + ); - if (organizationId) { - const organization = await db() - .select({ - customDomain: organizations.customDomain, - domainVerified: organizations.domainVerified, - }) - .from(organizations) - .where(eq(organizations.id, organizationId)) - .limit(1); - - if ( - organization.length > 0 && - organization[0] && - organization[0].customDomain - ) { - return Response.json({ - customDomain: organization[0].customDomain, - domainVerified: organization[0].domainVerified || false, - }); + if (organization?.customDomain && organization.domainVerified) { + return HttpServerResponse.unsafeJson( + { customDomain: organization.customDomain, domainVerified: true }, + { headers: privateHeaders }, + ); } } - const ownerOrganizations = await db() - .select({ - customDomain: organizations.customDomain, - domainVerified: organizations.domainVerified, - }) - .from(organizations) - .where(eq(organizations.ownerId, video.ownerId)) - .limit(1); + return HttpServerResponse.unsafeJson( + { customDomain: null, domainVerified: false }, + { headers: privateHeaders }, + ); + }).pipe( + provideOptionalAuth, + Effect.catchAll((error) => + Effect.logError("Failed to resolve video domain", error).pipe( + Effect.as( + HttpServerResponse.unsafeJson( + { error: "Internal server error" }, + { status: 500, headers: privateHeaders }, + ), + ), + ), + ), + ); - if ( - ownerOrganizations.length > 0 && - ownerOrganizations[0] && - ownerOrganizations[0].customDomain - ) { - return Response.json({ - customDomain: ownerOrganizations[0].customDomain, - domainVerified: ownerOrganizations[0].domainVerified || false, - }); - } +const ApiLive = HttpApiBuilder.api(Api).pipe( + Layer.provide( + HttpApiBuilder.group(Api, "video", (handlers) => + handlers.handle("domainInfo", ({ urlParams }) => + getDomainInfo(urlParams.videoId), + ), + ), + ), +); - return Response.json({ - customDomain: null, - domainVerified: false, - }); - } catch (error) { - console.error("Error fetching domain info:", error); - return Response.json({ error: "Internal server error" }, { status: 500 }); - } -} +export const GET = apiToHandler(ApiLive); diff --git a/apps/web/app/api/video/preview/route.ts b/apps/web/app/api/video/preview/route.ts index 0ede7f221a8..347ed1960c5 100644 --- a/apps/web/app/api/video/preview/route.ts +++ b/apps/web/app/api/video/preview/route.ts @@ -9,6 +9,14 @@ export const dynamic = "force-dynamic"; export const maxDuration = 120; const PREVIEW_GIF_EXPIRES_SECONDS = 60 * 60; +const uncachedHeaders = { "Cache-Control": "private, no-store, max-age=0" }; + +function redirectWithoutCaching(url: string | URL) { + return NextResponse.redirect(url, { + status: 302, + headers: uncachedHeaders, + }); +} function getPreviewGifKey(ownerId: string, videoId: string) { return `${ownerId}/${videoId}/preview/animated-preview.gif`; @@ -16,20 +24,18 @@ function getPreviewGifKey(ownerId: string, videoId: string) { function getFallbackResponse(request: NextRequest, videoId: string) { if (request.nextUrl.searchParams.get("fallback") !== "og") { - return new NextResponse(null, { status: 404 }); + return new NextResponse(null, { status: 404, headers: uncachedHeaders }); } const fallbackUrl = new URL("/api/video/og", request.url); fallbackUrl.searchParams.set("videoId", videoId); - const response = NextResponse.redirect(fallbackUrl, 302); - response.headers.set("Cache-Control", "private, no-store, max-age=0"); - return response; + return redirectWithoutCaching(fallbackUrl); } export async function GET(request: NextRequest) { const rawVideoId = request.nextUrl.searchParams.get("videoId"); if (!rawVideoId) { - return new NextResponse(null, { status: 400 }); + return new NextResponse(null, { status: 400, headers: uncachedHeaders }); } const videoId = Video.VideoId.make(rawVideoId); @@ -63,16 +69,14 @@ export async function GET(request: NextRequest) { }).pipe(provideOptionalAuth, runPromise); } catch (error) { console.warn("[video/preview] Failed to resolve preview GIF:", error); - return new NextResponse(null, { status: 404 }); + return new NextResponse(null, { status: 404, headers: uncachedHeaders }); } if (!previewUrl) { return getFallbackResponse(request, rawVideoId); } - const response = NextResponse.redirect(previewUrl, 302); - response.headers.set("Cache-Control", "public, max-age=300"); - return response; + return redirectWithoutCaching(previewUrl); } export const HEAD = GET;