Skip to content
Open
Changes from all 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
35 changes: 33 additions & 2 deletions apps/web/actions/videos/new-comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { nanoId } from "@cap/database/helpers";
import { comments } from "@cap/database/schema";
import { comments, videos } from "@cap/database/schema";
import { provideOptionalAuth, VideosPolicy } from "@cap/web-backend";
import type { ImageUpload } from "@cap/web-domain";
import { Comment, type Video } from "@cap/web-domain";
import { Comment, Policy, type Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { Effect, Exit } from "effect";
import { revalidatePath } from "next/cache";
import { createNotification } from "@/lib/Notification";
import * as EffectRuntime from "@/lib/server";

export async function newComment(data: {
content: string;
Expand Down Expand Up @@ -37,6 +41,33 @@ export async function newComment(data: {
if (!content || !videoId) {
throw new Error("Content and videoId are required");
}

// Authentication alone isn't authorization: without this, any logged-in user could
// comment on someone else's private video by guessing its id.
//
// This also fetches the video row (rather than gating a no-op) because
// canView returns true for a nonexistent videoId by design, so a bogus id
// would otherwise reach the insert below.
const accessExit = await Effect.gen(function* () {
const videosPolicy = yield* VideosPolicy;
return yield* Effect.promise(() =>
db()
.select({ id: videos.id })
.from(videos)
.where(eq(videos.id, videoId))
.limit(1),
).pipe(Policy.withPublicPolicy(videosPolicy.canView(videoId)));
}).pipe(provideOptionalAuth, EffectRuntime.runPromiseExit);

if (Exit.isFailure(accessExit)) {
console.error("Video access check failed:", accessExit);
throw new Error("Video not found");
}

if (accessExit.value.length === 0) {
throw new Error("Video not found");
}

const id = Comment.CommentId.make(nanoId());

const newComment = {
Expand Down