Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: viewing private videos through spaces (#892)

Ameer Al Ashhab9bcc095adee7
diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs
index 6c36c92c5..aadbc096c 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 e3103167f..26bc9c06e 100644
--- a/apps/web/actions/videos/get-status.ts
+++ b/apps/web/actions/videos/get-status.ts
@@ -1,11 +1,13 @@
"use server";
import { db } from "@cap/database";
-import { getCurrentUser } from "@cap/database/auth/session";
import { users, videos } from "@cap/database/schema";
import type { VideoMetadata } from "@cap/database/types";
+import { provideOptionalAuth, VideosPolicy } from "@cap/web-backend";
+import { Policy, type Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
-import { userHasAccessToVideo } from "@/utils/auth";
+import { Effect, Exit } from "effect";
+import * as EffectRuntime from "@/lib/server";
import { isAiGenerationEnabled } from "@/utils/flags";
import { transcribeVideo } from "../../lib/transcribe";
import { generateAiMetadata } from "./generate-ai-metadata";
@@ -23,20 +25,23 @@ export interface VideoStatusResult {
}
export async function getVideoStatus(
- videoId: string,
-): Promise<VideoStatusResult | { success: false; access: string }> {
- const userPromise = getCurrentUser();
+ videoId: Video.VideoId,
+): Promise<VideoStatusResult | { success: false }> {
+ 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 +231,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 b9330229a..6a8ea869a 100644
--- a/apps/web/app/api/playlist/route.ts
+++ b/apps/web/app/api/playlist/route.ts
@@ -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 56c731968..16b2b1ec9 100644
--- a/apps/web/app/embed/[videoId]/page.tsx
+++ b/apps/web/app/embed/[videoId]/page.tsx
@@ -9,12 +9,15 @@ import {
} from "@cap/database/schema";
import type { VideoMetadata } from "@cap/database/types";
import { buildEnv } from "@cap/env";
+import { provideOptionalAuth, Videos, VideosPolicy } from "@cap/web-backend";
+import { Policy, type Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
+import { Effect, Option } from "effect";
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
+import * as EffectRuntime from "@/lib/server";
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";
@@ -29,174 +32,169 @@ type Props = {
};
export async function generateMetadata({ params }: Props): Promise<Metadata> {
- 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,
+ 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 (
- <div className="flex flex-col justify-center items-center min-h-screen text-center bg-black text-white">
- <h1 className="mb-4 text-2xl font-bold">This video is private</h1>
- <p className="text-gray-400">
- If you own this video, please <Link href="/login">sign in</Link> to
- manage sharing.
- </p>
+ 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) => (
+ <div className="min-h-screen bg-black">
+ <PasswordOverlay isOpen={data.needsPassword} videoId={videoId} />
+ {!data.needsPassword && (
+ <EmbedContent video={data.video} autoplay={autoplay} />
+ )}
</div>
- );
- }
-
- return (
- <div className="min-h-screen bg-black">
- <PasswordOverlay
- isOpen={userAccess === "needs-password"}
- videoId={video.id}
- />
- {userAccess === "has-access" && (
- <EmbedContent video={video} user={user} autoplay={autoplay} />
- )}
- </div>
+ )),
+ Effect.catchTags({
+ PolicyDenied: () =>
+ Effect.succeed(
+ <div className="flex flex-col justify-center items-center min-h-screen text-center bg-black text-white">
+ <h1 className="mb-4 text-2xl font-bold">This video is private</h1>
+ <p className="text-gray-400">
+ If you own this video, please <Link href="/login">sign in</Link>{" "}
+ to manage sharing.
+ </p>
+ </div>,
+ ),
+ NoSuchElementException: () => Effect.sync(notFound()),
+ }),
+ provideOptionalAuth,
+ EffectRuntime.runPromise,
);
}
async function EmbedContent({
video,
- user,
autoplay,
}: {
- video: typeof videos.$inferSelect & {
+ video: Omit<typeof videos.$inferSelect, "password"> & {
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 aa7603784..d1725e78c 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -13,7 +13,11 @@ import {
import type { VideoMetadata } from "@cap/database/types";
import { buildEnv } from "@cap/env";
import { Logo } from "@cap/ui";
+import { provideOptionalAuth, Videos } from "@cap/web-backend";
+import { VideosPolicy } from "@cap/web-backend/src/Videos/VideosPolicy";
+import { Policy, type Video } from "@cap/web-domain";
import { eq, type InferSelectModel, sql } from "drizzle-orm";
+import { Effect, Option } from "effect";
import type { Metadata } from "next";
import { headers } from "next/headers";
import Link from "next/link";
@@ -22,8 +26,8 @@ import { generateAiMetadata } from "@/actions/videos/generate-ai-metadata";
import { getVideoAnalytics } from "@/actions/videos/get-analytics";
import { getDashboardData } from "@/app/(org)/dashboard/dashboard-data";
import { createNotification } from "@/lib/Notification";
+import * as EffectRuntime from "@/lib/server";
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";
@@ -95,10 +99,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;
@@ -110,259 +110,249 @@ type VideoWithOrganization = typeof videos.$inferSelect & {
hasPassword?: boolean;
};
-export async function generateMetadata({ params }: Props): Promise<Metadata> {
- const videoId = params.videoId as string;
-
- console.log(
- "[generateMetadata] Fetching video metadata for videoId:",
- videoId,
- );
- const query = await db().select().from(videos).where(eq(videos.id, videoId));
-
- if (query.length === 0) {
- console.log("[generateMetadata] No video found for videoId:", videoId);
- return notFound();
- }
-
- const video = query[0];
-
- if (!video) {
- return notFound();
- }
-
- const userPromise = getCurrentUser();
- const userAccess = await userHasAccessToVideo(userPromise, video);
-
- 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<Metadata> {
+ 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 user = await getCurrentUser();
-
- 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,
- },
- })
- .from(videos)
- .leftJoin(sharedVideos, eq(videos.id, sharedVideos.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 <p>No video found</p>;
- }
+ const videoId = params.videoId as Video.VideoId;
- const userAccess = await userHasAccessToVideo(user, video);
+ return Effect.gen(function* () {
+ const videosPolicy = yield* VideosPolicy;
- if (userAccess === "private") {
- return (
- <div className="flex flex-col justify-center items-center p-4 min-h-screen text-center">
- <h1 className="mb-4 text-2xl font-bold">This video is private</h1>
- <p className="text-gray-400">
- If you own this video, please <Link href="/login">sign in</Link> to
- manage sharing.
- </p>
+ 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,
+ 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) => (
+ <div className="min-h-screen flex flex-col bg-[#F7F8FA]">
+ <PasswordOverlay isOpen={data.needsPassword} videoId={videoId} />
+ {!data.needsPassword && (
+ <AuthorizedContent video={data.video} searchParams={searchParams} />
+ )}
</div>
- );
- }
-
- return (
- <div className="min-h-screen flex flex-col bg-[#F7F8FA]">
- <PasswordOverlay
- isOpen={userAccess === "needs-password"}
- videoId={video.id}
- />
- {userAccess === "has-access" && (
- <AuthorizedContent
- video={video}
- user={user}
- searchParams={searchParams}
- />
- )}
- </div>
+ )),
+ Effect.catchTags({
+ PolicyDenied: () =>
+ Effect.succeed(
+ <div className="flex flex-col justify-center items-center p-4 min-h-screen text-center">
+ <Logo className="size-32" />
+ <h1 className="mb-2 text-2xl font-semibold">
+ This video is private
+ </h1>
+ <p className="text-gray-400">
+ If you own this video, please <Link href="/login">sign in</Link>{" "}
+ to manage sharing.
+ </p>
+ </div>,
+ ),
+ NoSuchElementException: () => {
+ console.log("[ShareVideoPage] No video found for videoId:", videoId);
+ return Effect.succeed(<p>No video found</p>);
+ },
+ }),
+ provideOptionalAuth,
+ EffectRuntime.runPromise,
);
}
async function AuthorizedContent({
video,
- user: _user,
searchParams,
}: {
- video: Omit<InferSelectModel<typeof videos>, "folderId"> & {
+ video: Omit<InferSelectModel<typeof videos>, "folderId" | "password"> & {
sharedOrganization: { organizationId: string } | null;
};
- user: MaybePromise<InferSelectModel<typeof users> | 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 df3777911..db5ad9e77 100644
--- a/apps/web/lib/server.ts
+++ b/apps/web/lib/server.ts
@@ -1,6 +1,7 @@
import "server-only";
import { db } from "@cap/database";
+import { decrypt } from "@cap/database/crypto";
import {
Database,
DatabaseError,
@@ -8,8 +9,9 @@ import {
HttpAuthMiddlewareLive,
S3Buckets,
Videos,
+ VideosPolicy,
} from "@cap/web-backend";
-import type { HttpAuthMiddleware } from "@cap/web-domain";
+import { type HttpAuthMiddleware, Video } from "@cap/web-domain";
import * as NodeSdk from "@effect/opentelemetry/NodeSdk";
import {
type HttpApi,
@@ -17,7 +19,9 @@ import {
HttpMiddleware,
HttpServer,
} from "@effect/platform";
-import { Effect, Layer } from "effect";
+import { Cause, Effect, Exit, Layer, ManagedRuntime, Option } from "effect";
+import { isNotFoundError } from "next/dist/client/components/not-found";
+import { cookies } from "next/headers";
import { allowedOrigins } from "@/utils/cors";
import { getTracingConfig } from "./tracing";
@@ -31,13 +35,64 @@ const DatabaseLive = Layer.sync(Database, () => ({
const TracingLayer = NodeSdk.layer(getTracingConfig);
+const CookiePasswordAttachmentLive = Layer.effect(
+ Video.VideoPasswordAttachment,
+ Effect.gen(function* () {
+ const password = Option.fromNullable(
+ yield* Effect.promise(async () => {
+ const pw = cookies().get("x-cap-password")?.value;
+ if (pw) return decrypt(pw);
+ }),
+ );
+ return { password };
+ }),
+);
+
export const Dependencies = Layer.mergeAll(
S3Buckets.Default,
Videos.Default,
+ VideosPolicy.Default,
Folders.Default,
TracingLayer,
).pipe(Layer.provideMerge(DatabaseLive));
+// purposefully not exposed
+const EffectRuntime = ManagedRuntime.make(Dependencies);
+
+export const runPromise = <A, E>(
+ effect: Effect.Effect<A, E, Layer.Layer.Success<typeof Dependencies>>,
+) =>
+ EffectRuntime.runPromiseExit(
+ effect.pipe(Effect.provide(CookiePasswordAttachmentLive)),
+ ).then((res) => {
+ if (Exit.isFailure(res)) {
+ if (Cause.isDieType(res.cause) && isNotFoundError(res.cause.defect)) {
+ throw res.cause.defect;
+ }
+
+ throw res;
+ }
+
+ return res.value;
+ });
+
+export const runPromiseExit = <A, E>(
+ effect: Effect.Effect<A, E, Layer.Layer.Success<typeof Dependencies>>,
+) =>
+ EffectRuntime.runPromiseExit(
+ effect.pipe(Effect.provide(CookiePasswordAttachmentLive)),
+ ).then((res) => {
+ if (
+ Exit.isFailure(res) &&
+ Cause.isDieType(res.cause) &&
+ isNotFoundError(res.cause.defect)
+ ) {
+ throw res.cause.defect;
+ }
+
+ return res;
+ });
+
const cors = HttpApiBuilder.middlewareCors({
allowedOrigins,
credentials: true,
@@ -58,5 +113,8 @@ export const apiToHandler = (
Layer.provideMerge(Dependencies),
Layer.merge(HttpServer.layerContext),
Layer.provide(cors),
+ Layer.provide(
+ HttpApiBuilder.middleware(Effect.provide(CookiePasswordAttachmentLive)),
+ ),
HttpApiBuilder.toWebHandler,
);
diff --git a/apps/web/utils/auth.ts b/apps/web/utils/auth.ts
deleted file mode 100644
index cf317941a..000000000
--- a/apps/web/utils/auth.ts
+++ /dev/null
@@ -1,31 +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 } | undefined | null>,
- video: Pick<
- InferSelectModel<typeof videos>,
- "public" | "password" | "ownerId"
- >,
-): Promise<"has-access" | "private" | "needs-password" | "not-org-email"> {
- 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";
-
- 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 6a8b8c293..23c7115a7 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 { type Cause, Effect, Layer, Option } from "effect";
-import { Database } from "./Database";
+import { Database, type DatabaseError } from "./Database";
export const getCurrentUser = Effect.gen(function* () {
const db = yield* Database;
@@ -57,14 +57,15 @@ export const HttpAuthMiddlewareLive = Layer.effect(
}),
);
-export const provideOptionalAuth = <E, R>(
- app: HttpApp.Default<E, R>,
-): HttpApp.Default<
- E | HttpApiError.Unauthorized | HttpApiError.InternalServerError,
- R | Database
-> =>
+export const provideOptionalAuth = <A, E, R>(
+ app: Effect.Effect<A, E, R>,
+): Effect.Effect<A, E | DatabaseError | Cause.UnknownException, R | Database> =>
Effect.gen(function* () {
const user = yield* getCurrentUser;
+
+ if (Option.isSome(user))
+ yield* Effect.log(`Providing auth for user ${user.value.id}`);
+
return yield* user.pipe(
Option.map((user) =>
CurrentUser.context({
@@ -77,13 +78,4 @@ export const provideOptionalAuth = <E, R>(
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/Organisations/OrganisationsRepo.ts b/packages/web-backend/src/Organisations/OrganisationsRepo.ts
new file mode 100644
index 000000000..314b46d3a
--- /dev/null
+++ b/packages/web-backend/src/Organisations/OrganisationsRepo.ts
@@ -0,0 +1,37 @@
+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>()(
+ "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.organizationMembers.organizationId,
+ Db.sharedVideos.organizationId,
+ ),
+ )
+ .where(
+ Dz.and(
+ Dz.eq(Db.organizationMembers.userId, userId),
+ Dz.eq(Db.sharedVideos.videoId, videoId),
+ ),
+ ),
+ ),
+ };
+ }),
+ },
+) {}
diff --git a/packages/web-backend/src/Spaces/SpacesRepo.ts b/packages/web-backend/src/Spaces/SpacesRepo.ts
new file mode 100644
index 000000000..0797026ac
--- /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>()("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 c82edbfa9..c6cb0ea30 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 { Array, Effect, Option } from "effect";
+import { OrganisationsRepo } from "../Organisations/OrganisationsRepo";
+import { SpacesRepo } from "../Spaces/SpacesRepo";
import { VideosRepo } from "./VideosRepo";
export class VideosPolicy extends Effect.Service<VideosPolicy>()(
@@ -8,23 +10,62 @@ export class VideosPolicy extends Effect.Service<VideosPolicy>()(
{
effect: Effect.gen(function* () {
const repo = yield* VideosRepo;
+ const orgsRepo = yield* OrganisationsRepo;
+ const spacesRepo = yield* SpacesRepo;
const canView = (videoId: Video.VideoId) =>
Policy.publicPolicy(
Effect.fn(function* (user) {
const res = yield* repo.getById(videoId);
- if (Option.isNone(res)) return true;
+ if (Option.isNone(res)) {
+ yield* Effect.log("Video not found. Access granted.");
+ return true;
+ }
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)
+ .pipe(Effect.map(Array.get(0))),
+ spacesRepo
+ .membershipForVideo(userId, video.id)
+ .pipe(Effect.map(Array.get(0))),
+ ]);
+
+ if (
+ Option.isNone(videoOrgShareMembership) &&
+ Option.isNone(videoSpaceShareMembership)
+ ) {
+ yield* Effect.log(
+ "Neither org nor space sharing found. Access denied.",
+ );
+ return false;
+ }
+
+ if (Option.isSome(videoOrgShareMembership)) {
+ yield* Effect.log("Org sharing found.");
+ }
+
+ if (Option.isSome(videoSpaceShareMembership)) {
+ yield* Effect.log("Space sharing found.");
+ }
+ }
+ } else {
+ if (!video.public) {
+ yield* Effect.log(
+ "Video is private and user is not logged in. Access denied.",
+ );
+ return false;
+ }
+ }
yield* Video.verifyPassword(video, password);
@@ -46,6 +87,10 @@ export class VideosPolicy extends Effect.Service<VideosPolicy>()(
return { canView, isOwner };
}),
- dependencies: [VideosRepo.Default],
+ dependencies: [
+ VideosRepo.Default,
+ OrganisationsRepo.Default,
+ SpacesRepo.Default,
+ ],
},
) {}
diff --git a/packages/web-backend/src/index.ts b/packages/web-backend/src/index.ts
index 6998f59e0..dde8f5b34 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 35984d5ad..8df0deb36 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<Video>("Video")({
*/
export class VideoPasswordAttachment extends Context.Tag(
"VideoPasswordAttachment",
-)<VideoPasswordAttachment, { password: string }>() {}
+)<VideoPasswordAttachment, { password: Option.Option<string> }>() {}
export class VerifyVideoPasswordError extends Schema.TaggedError<VerifyVideoPasswordError>()(
"VerifyVideoPasswordError",
@@ -59,13 +59,16 @@ export const verifyPassword = (video: Video, password: Option.Option<string>) =>
if (Option.isNone(password)) return;
- if (Option.isNone(passwordAttachment))
+ if (
+ Option.isNone(passwordAttachment) ||
+ Option.isNone(passwordAttachment.value.password)
+ )
return yield* new VerifyVideoPasswordError({
id: video.id,
cause: "not-provided",
});
- if (passwordAttachment.value.password !== password.value)
+ if (passwordAttachment.value.password.value !== password.value)
return yield* new VerifyVideoPasswordError({
id: video.id,
cause: "wrong-password",