Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 53 additions & 10 deletions apps/web/app/s/[videoId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
organizationMembers,
organizations,
sharedVideos,
spaceMembers,
spaces,
spaceVideos,
users,
Expand All @@ -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";
Expand Down Expand Up @@ -95,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;
Expand All @@ -117,7 +114,23 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
"[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))
.limit(1);

if (query.length === 0) {
console.log("[generateMetadata] No video found for videoId:", videoId);
Expand All @@ -130,8 +143,22 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
return notFound();
}

const userPromise = getCurrentUser();
const userAccess = await userHasAccessToVideo(userPromise, video);
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") || "";
Expand Down Expand Up @@ -301,9 +328,11 @@ export default async function ShareVideoPage(props: Props) {
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) {
Expand All @@ -319,12 +348,26 @@ export default async function ShareVideoPage(props: Props) {
return <p>No video found</p>;
}

const userAccess = await userHasAccessToVideo(user, video);
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 (
<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>
<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.
Expand Down
38 changes: 35 additions & 3 deletions apps/web/utils/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,52 @@ 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<typeof videos>,
"public" | "password" | "ownerId"
>,
> & {
spaceId: string | null;
sharedOrganization: null | { organizationId: string | null };
},
isSpaceMember?: boolean,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Undefined isSpaceMember defaults to “not a member.” Ensure all call sites pass it if needed.

When omitted, !isSpaceMember evaluates truthy, which can affect access logic. Please verify all call sites were updated to pass the correct membership value.


🏁 Script executed:

#!/bin/bash
# Verify all TS/TSX call sites updated to the new signature (3rd arg)
rg -nP --type=ts --type=tsx -C3 '\buserHasAccessToVideo\s*\('

Length of output: 91


🏁 Script executed:

#!/bin/bash
# Re-run search for all call sites of userHasAccessToVideo in .ts and .tsx files
rg -nP -C3 '\buserHasAccessToVideo\s*\(' -g '*.ts' -g '*.tsx'

Length of output: 2677


🏁 Script executed:

#!/bin/bash
# Show the userHasAccessToVideo function implementation including isSpaceMember usage
sed -n '1,80p' apps/web/utils/auth.ts

Length of output: 1924


Ensure all call sites pass the new isSpaceMember argument

The isSpaceMember parameter now drives shared‐space access logic, and omitting it leaves it undefined (treated as “not a member”) via !isSpaceMember. Call sites outside of a space context should explicitly pass false, and pages within a space should continue passing their computed flag. Please update:

• apps/web/actions/videos/get-status.ts (line 229)
Change
await userHasAccessToVideo(userPromise, video)
to
await userHasAccessToVideo(userPromise, video, false)

• apps/web/app/embed/[videoId]/page.tsx
– line 46:
await userHasAccessToVideo(userPromise, video)
await userHasAccessToVideo(userPromise, video, false)
– line 162:
await userHasAccessToVideo(user, video)
await userHasAccessToVideo(user, video, false)

🤖 Prompt for AI Agents
In apps/web/utils/auth.ts around line 25 the new optional parameter
isSpaceMember controls shared-space access and must be passed explicitly; update
the three call sites noted in the review: in
apps/web/actions/videos/get-status.ts at line 229 change await
userHasAccessToVideo(userPromise, video) to pass false as the third arg; in
apps/web/app/embed/[videoId]/page.tsx at line 46 change await
userHasAccessToVideo(userPromise, video) to pass false; and in the same file at
line 162 change await userHasAccessToVideo(user, video) to pass false so that
non-space contexts explicitly provide isSpaceMember = false.

): 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))
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";
}
34 changes: 34 additions & 0 deletions packages/web-backend/src/Organisations/OrganisationsRepo.ts
Original file line number Diff line number Diff line change
@@ -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>()(
"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),
),
),
),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Critical: Incorrect table references in organization membership query

The query uses Db.spaceMembers instead of Db.organizationMembers for table references and joins on incorrect columns. This will cause runtime errors when checking organization membership.

Apply this diff to fix the table references:

 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),
+        Dz.eq(Db.organizationMembers.organizationId, Db.sharedVideos.organizationId),
       )
       .where(
         Dz.and(
-          Dz.eq(Db.spaceMembers.userId, userId),
-          Dz.eq(Db.sharedVideos.id, videoId),
+          Dz.eq(Db.organizationMembers.userId, userId),
+          Dz.eq(Db.sharedVideos.videoId, videoId),
         ),
       ),
   ),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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),
),
),
),
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),
),
),
),
🤖 Prompt for AI Agents
In packages/web-backend/src/Organisations/OrganisationsRepo.ts around lines 15
to 30, the query incorrectly references Db.spaceMembers and joins on the wrong
columns; replace all Db.spaceMembers references with Db.organizationMembers,
update the leftJoin to join sharedVideos on the matching organization id columns
(e.g. Db.organizationMembers.organizationId = Db.sharedVideos.organizationId),
and use Db.organizationMembers.userId in the where clause while keeping the
membershipId select—this ensures the query checks organization membership for
the given user and video using the correct table and join keys.

};
}),
},
) {}
31 changes: 31 additions & 0 deletions packages/web-backend/src/Spaces/SpacesRepo.ts
Original file line number Diff line number Diff line change
@@ -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),
),
),
),
};
}),
}) {}
30 changes: 21 additions & 9 deletions packages/web-backend/src/Videos/VideosPolicy.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
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<VideosPolicy>()(
"VideosPolicy",
{
effect: Effect.gen(function* () {
const repo = yield* VideosRepo;
const orgsRepo = yield* OrganisationsRepo;
const spacesRepo = yield* SpacesRepo;

const canView = (videoId: Video.VideoId) =>
Policy.publicPolicy(
Expand All @@ -18,13 +22,21 @@ export class VideosPolicy extends Effect.Service<VideosPolicy>()(

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);

Expand All @@ -46,6 +58,6 @@ export class VideosPolicy extends Effect.Service<VideosPolicy>()(

return { canView, isOwner };
}),
dependencies: [VideosRepo.Default],
dependencies: [VideosRepo.Default, OrganisationsRepo.Default, SpacesRepo.Default],
},
) {}
) { }
Loading