From da1412c7857f98884a7cdf8fb0600867fb9c9818 Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Fri, 15 Aug 2025 17:05:32 +0300 Subject: [PATCH 01/21] even if video is private, and user is part of view, still see video --- apps/web/app/s/[videoId]/page.tsx | 14 +++++++-- apps/web/utils/auth.ts | 52 ++++++++++++++++++++++++++----- 2 files changed, 56 insertions(+), 10 deletions(-) diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx index aa76037844a..5f85804e47c 100644 --- a/apps/web/app/s/[videoId]/page.tsx +++ b/apps/web/app/s/[videoId]/page.tsx @@ -5,6 +5,7 @@ import { organizationMembers, organizations, sharedVideos, + spaceMembers, spaces, spaceVideos, users, @@ -13,7 +14,7 @@ import { import type { VideoMetadata } from "@cap/database/types"; import { buildEnv } from "@cap/env"; import { Logo } from "@cap/ui"; -import { eq, type InferSelectModel, sql } from "drizzle-orm"; +import { and, eq, type InferSelectModel, sql } from "drizzle-orm"; import type { Metadata } from "next"; import { headers } from "next/headers"; import Link from "next/link"; @@ -301,10 +302,16 @@ export default async function ShareVideoPage(props: Props) { sharedOrganization: { organizationId: sharedVideos.organizationId, }, + spaceId: spaceVideos.spaceId, + isSpaceMember: spaceMembers.userId, }) .from(videos) .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId)) - .where(eq(videos.id, videoId)); + .leftJoin(spaceVideos, eq(videos.id, spaceVideos.videoId)) + .leftJoin(spaceMembers, eq(spaceVideos.spaceId, spaceMembers.spaceId)) + .where( + and(eq(videos.id, videoId), eq(spaceMembers.userId, user?.id ?? "")), + ); if (user && video && user.id !== video.ownerId) { try { @@ -324,7 +331,8 @@ export default async function ShareVideoPage(props: Props) { if (userAccess === "private") { return (
-

This video is private

+ +

This video is private

If you own this video, please sign in to manage sharing. diff --git a/apps/web/utils/auth.ts b/apps/web/utils/auth.ts index cf317941abc..c5153f7337f 100644 --- a/apps/web/utils/auth.ts +++ b/apps/web/utils/auth.ts @@ -12,20 +12,58 @@ async function verifyPasswordCookie(videoPassword: string) { } export async function userHasAccessToVideo( - user: MaybePromise<{ id: string } | undefined | null>, + user: MaybePromise< + { id: string; activeOrganizationId: string } | undefined | null + >, video: Pick< InferSelectModel, "public" | "password" | "ownerId" - >, + > & { + spaceId: string | null; + sharedOrganization: null | { + organizationId: string | null; + }; + isSpaceMember: null | string; + }, ): Promise<"has-access" | "private" | "needs-password" | "not-org-email"> { + // Public videos with no password are always accessible if (video.public && video.password === null) return "has-access"; const _user = await user; - if (video.public === false && (!_user || _user.id !== video.ownerId)) - return "private"; - if (video.password === null) return "has-access"; + // Owner always has access (regardless of space membership) + if (_user && _user.id === video.ownerId) { + if (video.password === null) return "has-access"; + if (await verifyPasswordCookie(video.password)) return "has-access"; + return "needs-password"; + } + + const videoOrgId = video.sharedOrganization?.organizationId; + const userActiveOrgId = _user?.activeOrganizationId; + + // Check organization-level access + if (videoOrgId && userActiveOrgId === videoOrgId) { + // Video shared with "All spaces" (no specific space requirement) + if (video.spaceId === null) { + if (video.password === null) return "has-access"; + if (await verifyPasswordCookie(video.password)) return "has-access"; + return "needs-password"; + } + + // Video shared with specific space (user must be space member) + if (video.spaceId && video.isSpaceMember) { + if (video.password === null) return "has-access"; + if (await verifyPasswordCookie(video.password)) return "has-access"; + return "needs-password"; + } + } + + // Public videos with password + if (video.public && video.password) { + if (await verifyPasswordCookie(video.password)) return "has-access"; + return "needs-password"; + } - if (!(await verifyPasswordCookie(video.password))) return "needs-password"; - return "has-access"; + // No access + return "private"; } From 82130aa41d38be3a3a66e4baa239c05837cff87d Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Fri, 15 Aug 2025 17:15:47 +0300 Subject: [PATCH 02/21] cleanup --- apps/web/utils/auth.ts | 66 +++++++++++++++++------------------------- 1 file changed, 27 insertions(+), 39 deletions(-) diff --git a/apps/web/utils/auth.ts b/apps/web/utils/auth.ts index c5153f7337f..097286879ef 100644 --- a/apps/web/utils/auth.ts +++ b/apps/web/utils/auth.ts @@ -12,58 +12,46 @@ async function verifyPasswordCookie(videoPassword: string) { } export async function userHasAccessToVideo( - user: MaybePromise< - { id: string; activeOrganizationId: string } | undefined | null - >, - video: Pick< - InferSelectModel, - "public" | "password" | "ownerId" - > & { + user: MaybePromise<{ id: string; activeOrganizationId: string } | undefined | null>, + video: Pick, "public" | "password" | "ownerId"> & { spaceId: string | null; - sharedOrganization: null | { - organizationId: string | null; - }; + sharedOrganization: null | { organizationId: string | null }; isSpaceMember: null | string; }, ): Promise<"has-access" | "private" | "needs-password" | "not-org-email"> { - // Public videos with no password are always accessible if (video.public && video.password === null) return "has-access"; const _user = await user; - - // Owner always has access (regardless of space membership) - if (_user && _user.id === video.ownerId) { - if (video.password === null) return "has-access"; - if (await verifyPasswordCookie(video.password)) return "has-access"; - return "needs-password"; - } - const videoOrgId = video.sharedOrganization?.organizationId; const userActiveOrgId = _user?.activeOrganizationId; - // Check organization-level access - if (videoOrgId && userActiveOrgId === videoOrgId) { - // Video shared with "All spaces" (no specific space requirement) - if (video.spaceId === null) { - if (video.password === null) return "has-access"; - if (await verifyPasswordCookie(video.password)) return "has-access"; - return "needs-password"; - } + // If the video is shared and has no space id, it's in the "All spaces" entry + const isVideoSharedWithAllSpaces = videoOrgId && video.spaceId === null; + if ( + !video.isSpaceMember && + userActiveOrgId === videoOrgId && + isVideoSharedWithAllSpaces + ) { + return "has-access"; + } - // Video shared with specific space (user must be space member) - if (video.spaceId && video.isSpaceMember) { - if (video.password === null) return "has-access"; - if (await verifyPasswordCookie(video.password)) return "has-access"; - return "needs-password"; - } + // If the video is shared and has a space id, it's in a specific space + const isVideoSharedWithSpace = videoOrgId && video.spaceId; + if ( + video.isSpaceMember && + userActiveOrgId === videoOrgId && + isVideoSharedWithSpace + ) { + return "has-access"; } - // Public videos with password - if (video.public && video.password) { - if (await verifyPasswordCookie(video.password)) return "has-access"; - return "needs-password"; + if (video.public === false && (!_user || _user.id !== video.ownerId)) { + return "private"; } - // No access - return "private"; + if (video.password === null) return "has-access"; + + if (!(await verifyPasswordCookie(video.password))) return "needs-password"; + + return "has-access"; } From 6815133c902bc347006d29771ed51bf0e49abad6 Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Fri, 15 Aug 2025 17:54:21 +0300 Subject: [PATCH 03/21] Update page.tsx --- apps/web/app/s/[videoId]/page.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx index 5f85804e47c..b0e08fd7df8 100644 --- a/apps/web/app/s/[videoId]/page.tsx +++ b/apps/web/app/s/[videoId]/page.tsx @@ -310,7 +310,7 @@ export default async function ShareVideoPage(props: Props) { .leftJoin(spaceVideos, eq(videos.id, spaceVideos.videoId)) .leftJoin(spaceMembers, eq(spaceVideos.spaceId, spaceMembers.spaceId)) .where( - and(eq(videos.id, videoId), eq(spaceMembers.userId, user?.id ?? "")), + and(eq(videos.id, videoId), eq(spaceMembers.userId, user.id)), ); if (user && video && user.id !== video.ownerId) { From 7ebca8510e216de2ab6fefa4744d4fac59baa9ad Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Fri, 15 Aug 2025 18:14:09 +0300 Subject: [PATCH 04/21] separate query --- apps/web/app/s/[videoId]/page.tsx | 20 ++++++++++++++++---- apps/web/utils/auth.ts | 15 ++++++++++----- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx index b0e08fd7df8..8a09a048030 100644 --- a/apps/web/app/s/[videoId]/page.tsx +++ b/apps/web/app/s/[videoId]/page.tsx @@ -303,14 +303,22 @@ export default async function ShareVideoPage(props: Props) { organizationId: sharedVideos.organizationId, }, spaceId: spaceVideos.spaceId, - isSpaceMember: spaceMembers.userId, }) .from(videos) .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId)) .leftJoin(spaceVideos, eq(videos.id, spaceVideos.videoId)) - .leftJoin(spaceMembers, eq(spaceVideos.spaceId, spaceMembers.spaceId)) + .where(eq(videos.id, videoId)); + + const [space] = await db() + .select({ + isSpaceMember: spaceMembers.userId, + }) + .from(spaceMembers) .where( - and(eq(videos.id, videoId), eq(spaceMembers.userId, user.id)), + and( + eq(spaceMembers.userId, user?.id ?? ""), + eq(spaceMembers.spaceId, video?.spaceId ?? ""), + ), ); if (user && video && user.id !== video.ownerId) { @@ -326,7 +334,11 @@ export default async function ShareVideoPage(props: Props) { return

No video found

; } - const userAccess = await userHasAccessToVideo(user, video); + const userAccess = await userHasAccessToVideo( + user, + video, + space?.isSpaceMember, + ); if (userAccess === "private") { return ( diff --git a/apps/web/utils/auth.ts b/apps/web/utils/auth.ts index 097286879ef..2321fd8075a 100644 --- a/apps/web/utils/auth.ts +++ b/apps/web/utils/auth.ts @@ -12,12 +12,17 @@ async function verifyPasswordCookie(videoPassword: string) { } export async function userHasAccessToVideo( - user: MaybePromise<{ id: string; activeOrganizationId: string } | undefined | null>, - video: Pick, "public" | "password" | "ownerId"> & { + user: MaybePromise< + { id: string; activeOrganizationId: string } | undefined | null + >, + video: Pick< + InferSelectModel, + "public" | "password" | "ownerId" + > & { spaceId: string | null; sharedOrganization: null | { organizationId: string | null }; - isSpaceMember: null | string; }, + isSpaceMember?: string, ): Promise<"has-access" | "private" | "needs-password" | "not-org-email"> { if (video.public && video.password === null) return "has-access"; @@ -28,7 +33,7 @@ export async function userHasAccessToVideo( // If the video is shared and has no space id, it's in the "All spaces" entry const isVideoSharedWithAllSpaces = videoOrgId && video.spaceId === null; if ( - !video.isSpaceMember && + !isSpaceMember && userActiveOrgId === videoOrgId && isVideoSharedWithAllSpaces ) { @@ -38,7 +43,7 @@ export async function userHasAccessToVideo( // If the video is shared and has a space id, it's in a specific space const isVideoSharedWithSpace = videoOrgId && video.spaceId; if ( - video.isSpaceMember && + isSpaceMember && userActiveOrgId === videoOrgId && isVideoSharedWithSpace ) { From 162a876d6a89d0dab3d15f9277717f93c1e3f30d Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Fri, 15 Aug 2025 18:28:23 +0300 Subject: [PATCH 05/21] update generateMetadata --- apps/web/app/s/[videoId]/page.tsx | 42 +++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx index 8a09a048030..f46314db9de 100644 --- a/apps/web/app/s/[videoId]/page.tsx +++ b/apps/web/app/s/[videoId]/page.tsx @@ -96,10 +96,6 @@ type Props = { searchParams: { [key: string]: string | string[] | undefined }; }; -type CommentWithAuthor = typeof comments.$inferSelect & { - authorName: string | null; -}; - type VideoWithOrganization = typeof videos.$inferSelect & { sharedOrganization?: { organizationId: string; @@ -118,7 +114,22 @@ export async function generateMetadata({ params }: Props): Promise { "[generateMetadata] Fetching video metadata for videoId:", videoId, ); - const query = await db().select().from(videos).where(eq(videos.id, videoId)); + const query = await db() + .select({ + id: videos.id, + public: videos.public, + name: videos.name, + password: videos.password, + ownerId: videos.ownerId, + sharedOrganization: { + organizationId: sharedVideos.organizationId, + }, + spaceId: spaceVideos.spaceId, + }) + .from(videos) + .leftJoin(spaceVideos, eq(videos.id, spaceVideos.videoId)) + .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId)) + .where(eq(videos.id, videoId)); if (query.length === 0) { console.log("[generateMetadata] No video found for videoId:", videoId); @@ -131,8 +142,25 @@ export async function generateMetadata({ params }: Props): Promise { return notFound(); } - const userPromise = getCurrentUser(); - const userAccess = await userHasAccessToVideo(userPromise, video); + const user = await getCurrentUser(); + + const [space] = await db() + .select({ + isSpaceMember: spaceMembers.userId, + }) + .from(spaceMembers) + .where( + and( + eq(spaceMembers.userId, user?.id ?? ""), + eq(spaceMembers.spaceId, video?.spaceId ?? ""), + ), + ); + + const userAccess = await userHasAccessToVideo( + user, + video, + space?.isSpaceMember, + ); const headersList = headers(); const referrer = headersList.get("x-referrer") || ""; From 91f4e1937268a2aededc66e0159a174171d506d4 Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Fri, 15 Aug 2025 18:31:07 +0300 Subject: [PATCH 06/21] make isSpaceMember a boolean --- apps/web/app/s/[videoId]/page.tsx | 4 ++-- apps/web/utils/auth.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx index f46314db9de..a1c57fe2a85 100644 --- a/apps/web/app/s/[videoId]/page.tsx +++ b/apps/web/app/s/[videoId]/page.tsx @@ -159,7 +159,7 @@ export async function generateMetadata({ params }: Props): Promise { const userAccess = await userHasAccessToVideo( user, video, - space?.isSpaceMember, + !!space?.isSpaceMember, ); const headersList = headers(); @@ -365,7 +365,7 @@ export default async function ShareVideoPage(props: Props) { const userAccess = await userHasAccessToVideo( user, video, - space?.isSpaceMember, + !!space?.isSpaceMember, ); if (userAccess === "private") { diff --git a/apps/web/utils/auth.ts b/apps/web/utils/auth.ts index 2321fd8075a..6c30935d8a8 100644 --- a/apps/web/utils/auth.ts +++ b/apps/web/utils/auth.ts @@ -22,7 +22,7 @@ export async function userHasAccessToVideo( spaceId: string | null; sharedOrganization: null | { organizationId: string | null }; }, - isSpaceMember?: string, + isSpaceMember?: boolean, ): Promise<"has-access" | "private" | "needs-password" | "not-org-email"> { if (video.public && video.password === null) return "has-access"; From 2d43544a7614af6421bb4ebeaec494685103993a Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Fri, 15 Aug 2025 18:58:09 +0300 Subject: [PATCH 07/21] cleanup --- apps/web/app/s/[videoId]/page.tsx | 40 +++++++++++++------------------ apps/web/utils/auth.ts | 3 ++- 2 files changed, 19 insertions(+), 24 deletions(-) diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx index a1c57fe2a85..243e537aa44 100644 --- a/apps/web/app/s/[videoId]/page.tsx +++ b/apps/web/app/s/[videoId]/page.tsx @@ -152,15 +152,12 @@ export async function generateMetadata({ params }: Props): Promise { .where( and( eq(spaceMembers.userId, user?.id ?? ""), - eq(spaceMembers.spaceId, video?.spaceId ?? ""), + eq(spaceMembers.spaceId, video.spaceId ?? ""), ), ); - const userAccess = await userHasAccessToVideo( - user, - video, - !!space?.isSpaceMember, - ); + const isMember = !!space?.isSpaceMember; + const userAccess = await userHasAccessToVideo(user, video, isMember); const headersList = headers(); const referrer = headersList.get("x-referrer") || ""; @@ -337,18 +334,6 @@ export default async function ShareVideoPage(props: Props) { .leftJoin(spaceVideos, eq(videos.id, spaceVideos.videoId)) .where(eq(videos.id, videoId)); - const [space] = await db() - .select({ - isSpaceMember: spaceMembers.userId, - }) - .from(spaceMembers) - .where( - and( - eq(spaceMembers.userId, user?.id ?? ""), - eq(spaceMembers.spaceId, video?.spaceId ?? ""), - ), - ); - if (user && video && user.id !== video.ownerId) { try { await createNotification({ type: "view", videoId, authorId: user.id }); @@ -362,11 +347,20 @@ export default async function ShareVideoPage(props: Props) { return

No video found

; } - const userAccess = await userHasAccessToVideo( - user, - video, - !!space?.isSpaceMember, - ); + const [space] = await db() + .select({ + isSpaceMember: spaceMembers.userId, + }) + .from(spaceMembers) + .where( + and( + eq(spaceMembers.userId, user?.id ?? ""), + eq(spaceMembers.spaceId, video.spaceId ?? ""), + ), + ); + + const isMember = !!space?.isSpaceMember; + const userAccess = await userHasAccessToVideo(user, video, isMember); if (userAccess === "private") { return ( diff --git a/apps/web/utils/auth.ts b/apps/web/utils/auth.ts index 6c30935d8a8..c558d2dcf7f 100644 --- a/apps/web/utils/auth.ts +++ b/apps/web/utils/auth.ts @@ -41,7 +41,8 @@ export async function userHasAccessToVideo( } // If the video is shared and has a space id, it's in a specific space - const isVideoSharedWithSpace = videoOrgId && video.spaceId; + const isVideoSharedWithSpace = + videoOrgId && video.spaceId && video.spaceId.length > 0; if ( isSpaceMember && userActiveOrgId === videoOrgId && From 49b4ee621d710bbcfce62033e5e0c9effdd2e509 Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Fri, 15 Aug 2025 19:15:00 +0300 Subject: [PATCH 08/21] Update page.tsx --- apps/web/app/s/[videoId]/page.tsx | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx index 243e537aa44..03a4916af70 100644 --- a/apps/web/app/s/[videoId]/page.tsx +++ b/apps/web/app/s/[videoId]/page.tsx @@ -129,7 +129,8 @@ export async function generateMetadata({ params }: Props): Promise { .from(videos) .leftJoin(spaceVideos, eq(videos.id, spaceVideos.videoId)) .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId)) - .where(eq(videos.id, videoId)); + .where(eq(videos.id, videoId)) + .limit(1) if (query.length === 0) { console.log("[generateMetadata] No video found for videoId:", videoId); @@ -144,19 +145,19 @@ export async function generateMetadata({ params }: Props): Promise { const user = await getCurrentUser(); - const [space] = await db() - .select({ - isSpaceMember: spaceMembers.userId, - }) + const [membership] = await db() + .select({ userId: spaceMembers.userId }) .from(spaceMembers) + .innerJoin(spaceVideos, eq(spaceMembers.spaceId, spaceVideos.spaceId)) .where( and( eq(spaceMembers.userId, user?.id ?? ""), - eq(spaceMembers.spaceId, video.spaceId ?? ""), + eq(spaceVideos.videoId, video.id), ), - ); + ) + .limit(1); - const isMember = !!space?.isSpaceMember; + const isMember = !!membership?.userId; const userAccess = await userHasAccessToVideo(user, video, isMember); const headersList = headers(); @@ -347,19 +348,19 @@ export default async function ShareVideoPage(props: Props) { return

No video found

; } - const [space] = await db() - .select({ - isSpaceMember: spaceMembers.userId, - }) + const [membership] = await db() + .select({ userId: spaceMembers.userId }) .from(spaceMembers) + .innerJoin(spaceVideos, eq(spaceMembers.spaceId, spaceVideos.spaceId)) .where( and( eq(spaceMembers.userId, user?.id ?? ""), - eq(spaceMembers.spaceId, video.spaceId ?? ""), + eq(spaceVideos.videoId, video.id), ), - ); + ) + .limit(1); - const isMember = !!space?.isSpaceMember; + const isMember = !!membership?.userId; const userAccess = await userHasAccessToVideo(user, video, isMember); if (userAccess === "private") { From 5847ded24d3a4a6ea582b30c01efefc71f6823ad Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Sat, 16 Aug 2025 01:47:07 +0800 Subject: [PATCH 09/21] add org/space permission check to VideosPolicy --- apps/web/app/s/[videoId]/page.tsx | 2 +- .../src/Organisations/OrganisationsRepo.ts | 34 +++++++++++++++++++ packages/web-backend/src/Spaces/SpacesRepo.ts | 31 +++++++++++++++++ .../web-backend/src/Videos/VideosPolicy.ts | 30 +++++++++++----- 4 files changed, 87 insertions(+), 10 deletions(-) create mode 100644 packages/web-backend/src/Organisations/OrganisationsRepo.ts create mode 100644 packages/web-backend/src/Spaces/SpacesRepo.ts diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx index 03a4916af70..1bbdc645369 100644 --- a/apps/web/app/s/[videoId]/page.tsx +++ b/apps/web/app/s/[videoId]/page.tsx @@ -130,7 +130,7 @@ export async function generateMetadata({ params }: Props): Promise { .leftJoin(spaceVideos, eq(videos.id, spaceVideos.videoId)) .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId)) .where(eq(videos.id, videoId)) - .limit(1) + .limit(1); if (query.length === 0) { console.log("[generateMetadata] No video found for videoId:", videoId); diff --git a/packages/web-backend/src/Organisations/OrganisationsRepo.ts b/packages/web-backend/src/Organisations/OrganisationsRepo.ts new file mode 100644 index 00000000000..c7c341e59cc --- /dev/null +++ b/packages/web-backend/src/Organisations/OrganisationsRepo.ts @@ -0,0 +1,34 @@ +import * as Db from "@cap/database/schema"; +import type { Video } from "@cap/web-domain"; +import * as Dz from "drizzle-orm"; +import { Effect } from "effect"; + +import { Database } from "../Database"; + +export class OrganisationsRepo extends Effect.Service()( + "OrganisationsRepo", + { + effect: Effect.gen(function* () { + const db = yield* Database; + + return { + membershipForVideo: (userId: string, videoId: Video.VideoId) => + db.execute((db) => + db + .select({ membershipId: Db.organizationMembers.id }) + .from(Db.organizationMembers) + .leftJoin( + Db.sharedVideos, + Dz.eq(Db.spaceMembers.spaceId, Db.sharedVideos.id), + ) + .where( + Dz.and( + Dz.eq(Db.spaceMembers.userId, userId), + Dz.eq(Db.sharedVideos.id, videoId), + ), + ), + ), + }; + }), + }, +) {} diff --git a/packages/web-backend/src/Spaces/SpacesRepo.ts b/packages/web-backend/src/Spaces/SpacesRepo.ts new file mode 100644 index 00000000000..0797026ac6b --- /dev/null +++ b/packages/web-backend/src/Spaces/SpacesRepo.ts @@ -0,0 +1,31 @@ +import * as Db from "@cap/database/schema"; +import type { Video } from "@cap/web-domain"; +import * as Dz from "drizzle-orm"; +import { Effect } from "effect"; + +import { Database } from "../Database"; + +export class SpacesRepo extends Effect.Service()("SpacesRepo", { + effect: Effect.gen(function* () { + const db = yield* Database; + + return { + membershipForVideo: (userId: string, videoId: Video.VideoId) => + db.execute((db) => + db + .select({ membershipId: Db.spaceMembers.id }) + .from(Db.spaceMembers) + .leftJoin( + Db.spaceVideos, + Dz.eq(Db.spaceMembers.spaceId, Db.spaceVideos.spaceId), + ) + .where( + Dz.and( + Dz.eq(Db.spaceMembers.userId, userId), + Dz.eq(Db.spaceVideos.videoId, videoId), + ), + ), + ), + }; + }), +}) {} diff --git a/packages/web-backend/src/Videos/VideosPolicy.ts b/packages/web-backend/src/Videos/VideosPolicy.ts index c82edbfa9f0..eb80bdf4f56 100644 --- a/packages/web-backend/src/Videos/VideosPolicy.ts +++ b/packages/web-backend/src/Videos/VideosPolicy.ts @@ -1,6 +1,8 @@ import { Policy, Video } from "@cap/web-domain"; import { Effect, Option } from "effect"; +import { OrganisationsRepo } from "../Organisations/OrganisationsRepo"; +import { SpacesRepo } from "../Spaces/SpacesRepo"; import { VideosRepo } from "./VideosRepo"; export class VideosPolicy extends Effect.Service()( @@ -8,6 +10,8 @@ export class VideosPolicy extends Effect.Service()( { effect: Effect.gen(function* () { const repo = yield* VideosRepo; + const orgsRepo = yield* OrganisationsRepo; + const spacesRepo = yield* SpacesRepo; const canView = (videoId: Video.VideoId) => Policy.publicPolicy( @@ -18,13 +22,21 @@ export class VideosPolicy extends Effect.Service()( const [video, password] = res.value; - if ( - user.pipe( - Option.filter((user) => user.id === video.ownerId), - Option.isSome, - ) - ) - return true; + if (Option.isSome(user)) { + const userId = user.value.id; + if (userId === video.ownerId) return true; + + if (!video.public) { + const [videoOrgShareMembership, videoSpaceShareMembership] = + yield* Effect.all([ + orgsRepo.membershipForVideo(userId, video.id), + spacesRepo.membershipForVideo(userId, video.id), + ]); + + if (!videoSpaceShareMembership || !videoOrgShareMembership) + return false; + } + } yield* Video.verifyPassword(video, password); @@ -46,6 +58,6 @@ export class VideosPolicy extends Effect.Service()( return { canView, isOwner }; }), - dependencies: [VideosRepo.Default], + dependencies: [VideosRepo.Default, OrganisationsRepo.Default, SpacesRepo.Default], }, -) {} +) { } From f3d533584ef821c8a38b94afcf441a4a4eb469f9 Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Tue, 19 Aug 2025 14:52:08 +0800 Subject: [PATCH 10/21] effectify everywhere --- .git-blame-ignore-revs | 2 +- apps/web/actions/videos/get-status.ts | 36 +- apps/web/app/api/playlist/route.ts | 10 +- apps/web/app/embed/[videoId]/page.tsx | 291 ++++++++------- apps/web/app/s/[videoId]/page.tsx | 498 ++++++++++++-------------- apps/web/lib/server.ts | 14 +- apps/web/utils/auth.ts | 63 ---- packages/web-backend/src/Auth.ts | 24 +- packages/web-backend/src/index.ts | 1 + packages/web-domain/src/Video.ts | 8 +- 10 files changed, 418 insertions(+), 529 deletions(-) delete mode 100644 apps/web/utils/auth.ts diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 6c36c92c512..aadbc096c0f 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -1 +1 @@ -d3b3a0bb176ac922bc623271fc64a60cf7f5bd8b +b0773ee5cd650542153d189bc020753467af21a2 diff --git a/apps/web/actions/videos/get-status.ts b/apps/web/actions/videos/get-status.ts index e3103167f80..97d727b68fd 100644 --- a/apps/web/actions/videos/get-status.ts +++ b/apps/web/actions/videos/get-status.ts @@ -5,10 +5,13 @@ import { getCurrentUser } from "@cap/database/auth/session"; import { users, videos } from "@cap/database/schema"; import type { VideoMetadata } from "@cap/database/types"; import { eq } from "drizzle-orm"; -import { userHasAccessToVideo } from "@/utils/auth"; import { isAiGenerationEnabled } from "@/utils/flags"; import { transcribeVideo } from "../../lib/transcribe"; import { generateAiMetadata } from "./generate-ai-metadata"; +import { Cause, Effect, Exit, Option } from "effect"; +import { provideOptionalAuth, VideosPolicy } from "@cap/web-backend"; +import { Policy, Video } from "@cap/web-domain"; +import { EffectRuntime } from "@/lib/server"; const MAX_AI_PROCESSING_TIME = 10 * 60 * 1000; @@ -23,20 +26,26 @@ export interface VideoStatusResult { } export async function getVideoStatus( - videoId: string, -): Promise { - const userPromise = getCurrentUser(); + videoId: Video.VideoId, +): Promise { + if (!videoId) throw new Error("Video ID not provided"); - if (!videoId) { - throw new Error("Video ID not provided"); - } + const exit = await Effect.gen(function* () { + const videosPolicy = yield* VideosPolicy; - const result = await db().select().from(videos).where(eq(videos.id, videoId)); - if (result.length === 0 || !result[0]) { - throw new Error("Video not found"); - } + return yield* Effect.promise(() => + db().select().from(videos).where(eq(videos.id, videoId)) + ).pipe(Policy.withPublicPolicy(videosPolicy.canView(videoId))); + }).pipe( + provideOptionalAuth, + EffectRuntime.runPromiseExit, + ); + + if (Exit.isFailure(exit)) return { success: false } + + const video = exit.value[0]; + if (!video) throw new Error("Video not found"); - const video = result[0]; const metadata: VideoMetadata = (video.metadata as VideoMetadata) || {}; if (!video.transcriptionStatus) { @@ -226,9 +235,6 @@ export async function getVideoStatus( } } - const access = await userHasAccessToVideo(userPromise, video); - if (access !== "has-access") return { success: false, access }; - return { transcriptionStatus: (video.transcriptionStatus as "PROCESSING" | "COMPLETE" | "ERROR") || diff --git a/apps/web/app/api/playlist/route.ts b/apps/web/app/api/playlist/route.ts index b9330229afc..9390952db32 100644 --- a/apps/web/app/api/playlist/route.ts +++ b/apps/web/app/api/playlist/route.ts @@ -41,7 +41,7 @@ class Api extends HttpApi.make("CapWebApi").add( .addError(HttpApiError.InternalServerError) .addError(HttpApiError.NotFound), ), -) {} +) { } const ApiLive = HttpApiBuilder.api(Api).pipe( Layer.provide( @@ -198,13 +198,9 @@ const getPlaylistResponse = ( const generatedPlaylist = generateMasterPlaylist( videoMetadata?.Metadata?.resolution ?? "", videoMetadata?.Metadata?.bandwidth ?? "", - `${serverEnv().WEB_URL}/api/playlist?userId=${ - video.ownerId - }&videoId=${video.id}&videoType=video`, + `${serverEnv().WEB_URL}/api/playlist?videoId=${video.id}&videoType=video`, audioMetadata - ? `${serverEnv().WEB_URL}/api/playlist?userId=${ - video.ownerId - }&videoId=${video.id}&videoType=audio` + ? `${serverEnv().WEB_URL}/api/playlist?videoId=${video.id}&videoType=audio` : null, ); diff --git a/apps/web/app/embed/[videoId]/page.tsx b/apps/web/app/embed/[videoId]/page.tsx index 56c7319686e..4afac15bc68 100644 --- a/apps/web/app/embed/[videoId]/page.tsx +++ b/apps/web/app/embed/[videoId]/page.tsx @@ -14,10 +14,13 @@ import type { Metadata } from "next"; import Link from "next/link"; import { notFound } from "next/navigation"; import { transcribeVideo } from "@/lib/transcribe"; -import { userHasAccessToVideo } from "@/utils/auth"; import { isAiGenerationEnabled } from "@/utils/flags"; import { EmbedVideo } from "./_components/EmbedVideo"; import { PasswordOverlay } from "./_components/PasswordOverlay"; +import { Effect, Option } from "effect"; +import { provideOptionalAuth, Videos, VideosPolicy } from "@cap/web-backend"; +import { Policy, Video } from "@cap/web-domain"; +import { EffectRuntime } from "@/lib/server"; export const dynamic = "auto"; export const dynamicParams = true; @@ -29,174 +32,170 @@ type Props = { }; export async function generateMetadata({ params }: Props): Promise { - const videoId = params.videoId as string; - const query = await db().select().from(videos).where(eq(videos.id, videoId)); + const videoId = params.videoId as Video.VideoId; - if (query.length === 0) { - return notFound(); - } - - const video = query[0]; - - if (!video) { - return notFound(); - } - - const userPromise = getCurrentUser(); - const userAccess = await userHasAccessToVideo(userPromise, video); - - if (video.public === false && userAccess !== "has-access") { - return { - title: "Cap: This video is private", - description: "This video is private and cannot be shared.", - robots: "noindex, nofollow", - }; - } - - if (video.password !== null && userAccess !== "has-access") { - return { - title: "Cap: Password Protected Video", - description: "This video is password protected.", - robots: "noindex, nofollow", - }; - } - - return { - title: video.name + " | Cap Recording", - description: "Watch this video on Cap", - openGraph: { - images: [ - { - url: new URL( - `/api/video/og?videoId=${videoId}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - width: 1200, - height: 630, - }, - ], - videos: [ - { - url: new URL( - `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - width: 1280, - height: 720, - type: "video/mp4", - }, - ], - }, - twitter: { - card: "player", - title: video.name + " | Cap Recording", - description: "Watch this video on Cap", - images: [ - new URL( - `/api/video/og?videoId=${videoId}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - ], - players: { - playerUrl: new URL( - `/embed/${videoId}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - streamUrl: new URL( - `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - width: 1280, - height: 720, - }, - }, - robots: "index, follow", - }; + return Effect.flatMap(Videos, (v) => v.getById(videoId)).pipe( + Effect.map( + Option.match({ + onNone: () => notFound(), + onSome: ([video]) => ({ + title: video.name + " | Cap Recording", + description: "Watch this video on Cap", + openGraph: { + images: [ + { + url: new URL( + `/api/video/og?videoId=${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + width: 1200, + height: 630, + }, + ], + videos: [ + { + url: new URL( + `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + width: 1280, + height: 720, + type: "video/mp4", + }, + ], + }, + twitter: { + card: "player", + title: video.name + " | Cap Recording", + description: "Watch this video on Cap", + images: [ + new URL( + `/api/video/og?videoId=${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + ], + players: { + playerUrl: new URL( + `/embed/${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + streamUrl: new URL( + `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + width: 1280, + height: 720, + }, + }, + robots: "index, follow", + }), + }), + ), + Effect.catchTags({ + PolicyDenied: () => + Effect.succeed({ + title: "Cap: This video is private", + description: "This video is private and cannot be shared.", + robots: "noindex, nofollow", + }), + VerifyVideoPasswordError: () => + Effect.succeed({ + title: "Cap: Password Protected Video", + description: "This video is password protected.", + robots: "noindex, nofollow", + }), + }), + provideOptionalAuth, + EffectRuntime.runPromise, + ); } export default async function EmbedVideoPage(props: Props) { const params = props.params; const searchParams = props.searchParams; - const videoId = params.videoId as string; + const videoId = params.videoId as Video.VideoId; const autoplay = searchParams.autoplay === "true"; - const user = await getCurrentUser(); + return Effect.gen(function* () { + const videosPolicy = yield* VideosPolicy; - const videoWithOrganization = await db() - .select({ - id: videos.id, - name: videos.name, - ownerId: videos.ownerId, - createdAt: videos.createdAt, - updatedAt: videos.updatedAt, - awsRegion: videos.awsRegion, - awsBucket: videos.awsBucket, - bucket: videos.bucket, - metadata: videos.metadata, - public: videos.public, - videoStartTime: videos.videoStartTime, - audioStartTime: videos.audioStartTime, - xStreamInfo: videos.xStreamInfo, - jobId: videos.jobId, - jobStatus: videos.jobStatus, - isScreenshot: videos.isScreenshot, - skipProcessing: videos.skipProcessing, - transcriptionStatus: videos.transcriptionStatus, - password: videos.password, - source: videos.source, - sharedOrganization: { - organizationId: sharedVideos.organizationId, - }, - }) - .from(videos) - .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId)) - .where(eq(videos.id, videoId)) - .execute(); - - const video = videoWithOrganization[0]; - - if (!video) { - return notFound(); - } + const [video] = yield* Effect.promise(() => + db() + .select({ + id: videos.id, + name: videos.name, + ownerId: videos.ownerId, + createdAt: videos.createdAt, + updatedAt: videos.updatedAt, + awsRegion: videos.awsRegion, + awsBucket: videos.awsBucket, + bucket: videos.bucket, + metadata: videos.metadata, + public: videos.public, + videoStartTime: videos.videoStartTime, + audioStartTime: videos.audioStartTime, + xStreamInfo: videos.xStreamInfo, + jobId: videos.jobId, + jobStatus: videos.jobStatus, + isScreenshot: videos.isScreenshot, + skipProcessing: videos.skipProcessing, + transcriptionStatus: videos.transcriptionStatus, + password: videos.password, + source: videos.source, + folderId: videos.folderId, + sharedOrganization: { + organizationId: sharedVideos.organizationId, + }, + }) + .from(videos) + .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId)) + .where(eq(videos.id, videoId)), + ).pipe(Policy.withPublicPolicy(videosPolicy.canView(videoId))); - const userAccess = await userHasAccessToVideo(user, video); - - if (userAccess === "private") { - return ( -
-

This video is private

-

- If you own this video, please sign in to - manage sharing. -

+ return Option.fromNullable(video); + }).pipe( + Effect.flatten, + Effect.map((video) => ({ needsPassword: false, video }) as const), + Effect.catchTag("VerifyVideoPasswordError", () => + Effect.succeed({ needsPassword: true } as const), + ), + Effect.map((data) => ( +
+ + {!data.needsPassword && ( + + )}
- ); - } - - return ( -
- - {userAccess === "has-access" && ( - - )} -
+ )), + Effect.catchTags({ + PolicyDenied: () => + Effect.succeed( +
+

This video is private

+

+ If you own this video, please sign in{" "} + to manage sharing. +

+
, + ), + NoSuchElementException: () => Effect.sync(notFound()), + }), + provideOptionalAuth, + EffectRuntime.runPromise, ); } async function EmbedContent({ video, - user, autoplay, }: { video: typeof videos.$inferSelect & { sharedOrganization: { organizationId: string } | null; }; - user: typeof users.$inferSelect | null; autoplay: boolean; }) { + const user = await getCurrentUser(); + let aiGenerationEnabled = false; const videoOwnerQuery = await db() .select({ diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx index 1bbdc645369..58919b3695d 100644 --- a/apps/web/app/s/[videoId]/page.tsx +++ b/apps/web/app/s/[videoId]/page.tsx @@ -5,7 +5,6 @@ import { organizationMembers, organizations, sharedVideos, - spaceMembers, spaces, spaceVideos, users, @@ -14,7 +13,7 @@ import { import type { VideoMetadata } from "@cap/database/types"; import { buildEnv } from "@cap/env"; import { Logo } from "@cap/ui"; -import { and, eq, type InferSelectModel, sql } from "drizzle-orm"; +import { eq, type InferSelectModel, sql } from "drizzle-orm"; import type { Metadata } from "next"; import { headers } from "next/headers"; import Link from "next/link"; @@ -24,11 +23,15 @@ import { getVideoAnalytics } from "@/actions/videos/get-analytics"; import { getDashboardData } from "@/app/(org)/dashboard/dashboard-data"; import { createNotification } from "@/lib/Notification"; import { transcribeVideo } from "@/lib/transcribe"; -import { userHasAccessToVideo } from "@/utils/auth"; import { isAiGenerationEnabled } from "@/utils/flags"; import { PasswordOverlay } from "./_components/PasswordOverlay"; import { ShareHeader } from "./_components/ShareHeader"; import { Share } from "./Share"; +import { VideosPolicy } from "@cap/web-backend/src/Videos/VideosPolicy"; +import { Effect, Option } from "effect"; +import { Policy, Video } from "@cap/web-domain"; +import { EffectRuntime } from "@/lib/server"; +import { provideOptionalAuth, Videos } from "@cap/web-backend"; export const dynamic = "auto"; export const dynamicParams = true; @@ -107,305 +110,250 @@ type VideoWithOrganization = typeof videos.$inferSelect & { hasPassword?: boolean; }; -export async function generateMetadata({ params }: Props): Promise { - const videoId = params.videoId as string; - - console.log( - "[generateMetadata] Fetching video metadata for videoId:", - videoId, - ); - const query = await db() - .select({ - id: videos.id, - public: videos.public, - name: videos.name, - password: videos.password, - ownerId: videos.ownerId, - sharedOrganization: { - organizationId: sharedVideos.organizationId, - }, - spaceId: spaceVideos.spaceId, - }) - .from(videos) - .leftJoin(spaceVideos, eq(videos.id, spaceVideos.videoId)) - .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId)) - .where(eq(videos.id, videoId)) - .limit(1); - - if (query.length === 0) { - console.log("[generateMetadata] No video found for videoId:", videoId); - return notFound(); - } - - const video = query[0]; - - if (!video) { - return notFound(); - } - - const user = await getCurrentUser(); - - const [membership] = await db() - .select({ userId: spaceMembers.userId }) - .from(spaceMembers) - .innerJoin(spaceVideos, eq(spaceMembers.spaceId, spaceVideos.spaceId)) - .where( - and( - eq(spaceMembers.userId, user?.id ?? ""), - eq(spaceVideos.videoId, video.id), - ), - ) - .limit(1); - - const isMember = !!membership?.userId; - const userAccess = await userHasAccessToVideo(user, video, isMember); - - const headersList = headers(); - const referrer = headersList.get("x-referrer") || ""; - - const allowedReferrers = [ - "x.com", - "twitter.com", - "facebook.com", - "fb.com", - "slack.com", - "notion.so", - "linkedin.com", - ]; - - const isAllowedReferrer = allowedReferrers.some((domain) => +const ALLOWED_REFERRERS = [ + "x.com", + "twitter.com", + "facebook.com", + "fb.com", + "slack.com", + "notion.so", + "linkedin.com", +]; + +export function generateMetadata({ params }: Props): Promise { + const videoId = params.videoId as Video.VideoId; + + const referrer = headers().get("x-referrer") || ""; + const isAllowedReferrer = ALLOWED_REFERRERS.some((domain) => referrer.includes(domain), ); - const robotsDirective = isAllowedReferrer - ? "index, follow" - : "noindex, nofollow"; - - if (video.public === false && userAccess !== "has-access") { - return { - title: "Cap: This video is private", - description: "This video is private and cannot be shared.", - openGraph: { - images: [ - { - url: new URL( - `/api/video/og?videoId=${videoId}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - width: 1200, - height: 630, + return Effect.flatMap(Videos, (v) => v.getById(videoId)).pipe( + Effect.map( + Option.match({ + onNone: () => notFound(), + onSome: ([video]) => ({ + title: video.name + " | Cap Recording", + description: "Watch this video on Cap", + openGraph: { + images: [ + { + url: new URL( + `/api/video/og?videoId=${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + width: 1200, + height: 630, + }, + ], + videos: [ + { + url: new URL( + `/api/playlist?videoId=${video.id}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + width: 1280, + height: 720, + type: "video/mp4", + }, + ], }, - ], - videos: [ - { - url: new URL( - `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - width: 1280, - height: 720, - type: "video/mp4", + twitter: { + card: "player", + title: video.name + " | Cap Recording", + description: "Watch this video on Cap", + images: [ + new URL( + `/api/video/og?videoId=${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + ], + players: { + playerUrl: new URL( + `/s/${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + streamUrl: new URL( + `/api/playlist?videoId=${video.id}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + width: 1280, + height: 720, + }, }, - ], - }, - robots: "noindex, nofollow", - }; - } - - if (video.password !== null && userAccess !== "has-access") { - return { - title: "Cap: Password Protected Video", - description: "This video is password protected.", - openGraph: { - images: [ - { - url: new URL( - `/api/video/og?videoId=${videoId}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - width: 1200, - height: 630, + robots: isAllowedReferrer ? "index, follow" : "noindex, nofollow", + }), + }), + ), + Effect.catchTags({ + PolicyDenied: () => + Effect.succeed({ + title: "Cap: This video is private", + description: "This video is private and cannot be shared.", + openGraph: { + images: [ + { + url: new URL( + `/api/video/og?videoId=${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + width: 1200, + height: 630, + }, + ], + videos: [ + { + url: new URL( + `/api/playlist?videoId=${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + width: 1280, + height: 720, + type: "video/mp4", + }, + ], }, - ], - }, - twitter: { - card: "summary_large_image", - title: "Cap: Password Protected Video", - description: "This video is password protected.", - images: [ - new URL( - `/api/video/og?videoId=${videoId}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - ], - }, - robots: "noindex, nofollow", - }; - } - - return { - title: video.name + " | Cap Recording", - description: "Watch this video on Cap", - openGraph: { - images: [ - { - url: new URL( - `/api/video/og?videoId=${videoId}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - width: 1200, - height: 630, - }, - ], - videos: [ - { - url: new URL( - `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - width: 1280, - height: 720, - type: "video/mp4", - }, - ], - }, - twitter: { - card: "player", - title: video.name + " | Cap Recording", - description: "Watch this video on Cap", - images: [ - new URL( - `/api/video/og?videoId=${videoId}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - ], - players: { - playerUrl: new URL( - `/s/${videoId}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - streamUrl: new URL( - `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`, - buildEnv.NEXT_PUBLIC_WEB_URL, - ).toString(), - width: 1280, - height: 720, - }, - }, - robots: robotsDirective, - }; + robots: "noindex, nofollow", + }), + VerifyVideoPasswordError: () => + Effect.succeed({ + title: "Cap: Password Protected Video", + description: "This video is password protected.", + openGraph: { + images: [ + { + url: new URL( + `/api/video/og?videoId=${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + width: 1200, + height: 630, + }, + ], + }, + twitter: { + card: "summary_large_image", + title: "Cap: Password Protected Video", + description: "This video is password protected.", + images: [ + new URL( + `/api/video/og?videoId=${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL, + ).toString(), + ], + }, + robots: "noindex, nofollow", + }), + }), + provideOptionalAuth, + EffectRuntime.runPromise, + ); } export default async function ShareVideoPage(props: Props) { const params = props.params; const searchParams = props.searchParams; - const videoId = params.videoId as string; + const videoId = params.videoId as Video.VideoId; - const user = await getCurrentUser(); + return Effect.gen(function* () { + const videosPolicy = yield* VideosPolicy; - const [video] = await db() - .select({ - id: videos.id, - name: videos.name, - ownerId: videos.ownerId, - createdAt: videos.createdAt, - updatedAt: videos.updatedAt, - awsRegion: videos.awsRegion, - awsBucket: videos.awsBucket, - bucket: videos.bucket, - metadata: videos.metadata, - public: videos.public, - videoStartTime: videos.videoStartTime, - audioStartTime: videos.audioStartTime, - xStreamInfo: videos.xStreamInfo, - jobId: videos.jobId, - jobStatus: videos.jobStatus, - isScreenshot: videos.isScreenshot, - skipProcessing: videos.skipProcessing, - transcriptionStatus: videos.transcriptionStatus, - password: videos.password, - source: videos.source, - sharedOrganization: { - organizationId: sharedVideos.organizationId, - }, - spaceId: spaceVideos.spaceId, - }) - .from(videos) - .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId)) - .leftJoin(spaceVideos, eq(videos.id, spaceVideos.videoId)) - .where(eq(videos.id, videoId)); - - if (user && video && user.id !== video.ownerId) { - try { - await createNotification({ type: "view", videoId, authorId: user.id }); - } catch (error) { - console.error("Failed to create view notification:", error); - } - } - - if (!video) { - console.log("[ShareVideoPage] No video found for videoId:", videoId); - return

No video found

; - } - - const [membership] = await db() - .select({ userId: spaceMembers.userId }) - .from(spaceMembers) - .innerJoin(spaceVideos, eq(spaceMembers.spaceId, spaceVideos.spaceId)) - .where( - and( - eq(spaceMembers.userId, user?.id ?? ""), - eq(spaceVideos.videoId, video.id), - ), - ) - .limit(1); - - const isMember = !!membership?.userId; - const userAccess = await userHasAccessToVideo(user, video, isMember); - - if (userAccess === "private") { - return ( -
- -

This video is private

-

- If you own this video, please sign in to - manage sharing. -

+ const [video] = yield* Effect.promise(() => + db() + .select({ + id: videos.id, + name: videos.name, + ownerId: videos.ownerId, + createdAt: videos.createdAt, + updatedAt: videos.updatedAt, + awsRegion: videos.awsRegion, + awsBucket: videos.awsBucket, + bucket: videos.bucket, + metadata: videos.metadata, + public: videos.public, + videoStartTime: videos.videoStartTime, + audioStartTime: videos.audioStartTime, + xStreamInfo: videos.xStreamInfo, + jobId: videos.jobId, + jobStatus: videos.jobStatus, + isScreenshot: videos.isScreenshot, + skipProcessing: videos.skipProcessing, + transcriptionStatus: videos.transcriptionStatus, + password: videos.password, + source: videos.source, + sharedOrganization: { + organizationId: sharedVideos.organizationId, + }, + }) + .from(videos) + .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId)) + .where(eq(videos.id, videoId)), + ).pipe(Policy.withPublicPolicy(videosPolicy.canView(videoId))); + + return Option.fromNullable(video); + }).pipe( + Effect.flatten, + Effect.map((video) => ({ needsPassword: false, video }) as const), + Effect.catchTag("VerifyVideoPasswordError", () => + Effect.succeed({ needsPassword: true } as const), + ), + Effect.map((data) => ( +
+ + {!data.needsPassword && ( + + )}
- ); - } - - return ( -
- - {userAccess === "has-access" && ( - - )} -
+ )), + Effect.catchTags({ + PolicyDenied: () => + Effect.succeed( +
+ +

+ This video is private +

+

+ If you own this video, please sign in{" "} + to manage sharing. +

+
, + ), + NoSuchElementException: () => { + console.log("[ShareVideoPage] No video found for videoId:", videoId); + return Effect.succeed(

No video found

); + }, + }), + provideOptionalAuth, + EffectRuntime.runPromise, ); } async function AuthorizedContent({ video, - user: _user, searchParams, }: { video: Omit, "folderId"> & { sharedOrganization: { organizationId: string } | null; }; - user: MaybePromise | null>; searchParams: { [key: string]: string | string[] | undefined }; }) { - const user = await _user; + // will have already been fetched if auth is required + const user = await getCurrentUser(); const videoId = video.id; + + if (user && video && user.id !== video.ownerId) { + try { + await createNotification({ + type: "view", + videoId: video.id, + authorId: user.id, + }); + } catch (error) { + console.error("Failed to create view notification:", error); + } + } + const userId = user?.id; const commentId = searchParams.comment as string | undefined; const replyId = searchParams.reply as string | undefined; diff --git a/apps/web/lib/server.ts b/apps/web/lib/server.ts index df377791187..ce7575aea0a 100644 --- a/apps/web/lib/server.ts +++ b/apps/web/lib/server.ts @@ -8,8 +8,9 @@ import { HttpAuthMiddlewareLive, S3Buckets, Videos, + VideosPolicy, } from "@cap/web-backend"; -import type { HttpAuthMiddleware } from "@cap/web-domain"; +import { Video, type HttpAuthMiddleware } from "@cap/web-domain"; import * as NodeSdk from "@effect/opentelemetry/NodeSdk"; import { type HttpApi, @@ -17,7 +18,8 @@ import { HttpMiddleware, HttpServer, } from "@effect/platform"; -import { Effect, Layer } from "effect"; +import { Effect, Layer, ManagedRuntime, Option } from "effect"; +import { cookies } from "next/headers"; import { allowedOrigins } from "@/utils/cors"; import { getTracingConfig } from "./tracing"; @@ -31,13 +33,21 @@ const DatabaseLive = Layer.sync(Database, () => ({ const TracingLayer = NodeSdk.layer(getTracingConfig); +const CookiesPasswordLive = Layer.sync(Video.VideoPasswordAttachment, () => + ({ password: Option.fromNullable(cookies().get("x-cap-password")?.value) }) +) + export const Dependencies = Layer.mergeAll( S3Buckets.Default, Videos.Default, + VideosPolicy.Default, Folders.Default, TracingLayer, + CookiesPasswordLive ).pipe(Layer.provideMerge(DatabaseLive)); +export const EffectRuntime = ManagedRuntime.make(Dependencies); + const cors = HttpApiBuilder.middlewareCors({ allowedOrigins, credentials: true, diff --git a/apps/web/utils/auth.ts b/apps/web/utils/auth.ts deleted file mode 100644 index c558d2dcf7f..00000000000 --- a/apps/web/utils/auth.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { decrypt } from "@cap/database/crypto"; -import type { videos } from "@cap/database/schema"; -import type { InferSelectModel } from "drizzle-orm"; -import { cookies } from "next/headers"; - -async function verifyPasswordCookie(videoPassword: string) { - const password = cookies().get("x-cap-password")?.value; - if (!password) return false; - - const decrypted = await decrypt(password).catch(() => ""); - return decrypted === videoPassword; -} - -export async function userHasAccessToVideo( - user: MaybePromise< - { id: string; activeOrganizationId: string } | undefined | null - >, - video: Pick< - InferSelectModel, - "public" | "password" | "ownerId" - > & { - spaceId: string | null; - sharedOrganization: null | { organizationId: string | null }; - }, - isSpaceMember?: boolean, -): Promise<"has-access" | "private" | "needs-password" | "not-org-email"> { - if (video.public && video.password === null) return "has-access"; - - const _user = await user; - const videoOrgId = video.sharedOrganization?.organizationId; - const userActiveOrgId = _user?.activeOrganizationId; - - // If the video is shared and has no space id, it's in the "All spaces" entry - const isVideoSharedWithAllSpaces = videoOrgId && video.spaceId === null; - if ( - !isSpaceMember && - userActiveOrgId === videoOrgId && - isVideoSharedWithAllSpaces - ) { - return "has-access"; - } - - // If the video is shared and has a space id, it's in a specific space - const isVideoSharedWithSpace = - videoOrgId && video.spaceId && video.spaceId.length > 0; - if ( - isSpaceMember && - userActiveOrgId === videoOrgId && - isVideoSharedWithSpace - ) { - return "has-access"; - } - - if (video.public === false && (!_user || _user.id !== video.ownerId)) { - return "private"; - } - - if (video.password === null) return "has-access"; - - if (!(await verifyPasswordCookie(video.password))) return "needs-password"; - - return "has-access"; -} diff --git a/packages/web-backend/src/Auth.ts b/packages/web-backend/src/Auth.ts index 6a8b8c29374..2c942dd5c26 100644 --- a/packages/web-backend/src/Auth.ts +++ b/packages/web-backend/src/Auth.ts @@ -3,9 +3,9 @@ import * as Db from "@cap/database/schema"; import { CurrentUser, HttpAuthMiddleware } from "@cap/web-domain"; import { HttpApiError, type HttpApp } from "@effect/platform"; import * as Dz from "drizzle-orm"; -import { Effect, Layer, Option } from "effect"; +import { Cause, Effect, Layer, Option } from "effect"; -import { Database } from "./Database"; +import { Database, DatabaseError } from "./Database"; export const getCurrentUser = Effect.gen(function* () { const db = yield* Database; @@ -57,10 +57,11 @@ export const HttpAuthMiddlewareLive = Layer.effect( }), ); -export const provideOptionalAuth = ( - app: HttpApp.Default, -): HttpApp.Default< - E | HttpApiError.Unauthorized | HttpApiError.InternalServerError, +export const provideOptionalAuth = ( + app: Effect.Effect, +): Effect.Effect< + A, + E | DatabaseError | Cause.UnknownException, R | Database > => Effect.gen(function* () { @@ -77,13 +78,4 @@ export const provideOptionalAuth = ( onSome: (ctx) => app.pipe(Effect.provide(ctx)), }), ); - }).pipe( - Effect.catchTag( - "DatabaseError", - () => new HttpApiError.InternalServerError(), - ), - Effect.catchTag( - "UnknownException", - () => new HttpApiError.InternalServerError(), - ), - ); + }); diff --git a/packages/web-backend/src/index.ts b/packages/web-backend/src/index.ts index 6998f59e049..dde8f5b34f2 100644 --- a/packages/web-backend/src/index.ts +++ b/packages/web-backend/src/index.ts @@ -7,3 +7,4 @@ export * from "./Rpcs"; export { S3Buckets } from "./S3Buckets"; export { S3BucketAccess } from "./S3Buckets/S3BucketAccess"; export { Videos } from "./Videos"; +export { VideosPolicy } from "./Videos/VideosPolicy"; diff --git a/packages/web-domain/src/Video.ts b/packages/web-domain/src/Video.ts index 35984d5ad53..3e78facdb7c 100644 --- a/packages/web-domain/src/Video.ts +++ b/packages/web-domain/src/Video.ts @@ -41,7 +41,7 @@ export class Video extends Schema.Class