Add guest upload tokens and share-session aware permissions

This commit is contained in:
Yusuf İpek
2026-02-23 18:17:22 +03:00
parent 9058317247
commit fe7235052e
21 changed files with 1117 additions and 150 deletions
+61 -1
View File
@@ -5,6 +5,7 @@ import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response
import { rateLimit } from '@/lib/rate-limit';
import { validateShareLinkAccess } from '@/lib/share-links';
import { getShareSessionFromRequest } from '@/lib/share-session';
import { getGuestIdentityFromRequest } from '@/lib/guest-identity';
type RouteParams = { params: Promise<{ videoId: string }> };
@@ -48,6 +49,7 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
annotationData: true,
parentId: true,
authorId: true,
guestIdentityId: true,
tagId: true,
versionId: true,
guestName: true,
@@ -70,6 +72,7 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
annotationData: true,
parentId: true,
authorId: true,
guestIdentityId: true,
tagId: true,
versionId: true,
guestName: true,
@@ -109,7 +112,7 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
requiredPermission: 'VIEW',
passwordVerified: shareSession.passwordVerified,
})
: { hasAccess: false, canComment: false, allowGuests: false, requiresPassword: false };
: { hasAccess: false, canComment: false, canDownload: false, allowGuests: false, requiresPassword: false };
if (!access.hasAccess && !shareAccess.hasAccess) {
return apiErrors.forbidden('Access denied');
@@ -117,10 +120,65 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
// Include auth context so the client knows if the viewer is a guest
const { project, ...videoData } = video;
const viewerUserId = session?.user?.id ?? null;
const viewerGuestIdentityId = viewerUserId ? null : getGuestIdentityFromRequest(request);
const isProjectOwner = viewerUserId === project.ownerId;
const versions = videoData.versions.map((version) => {
if (!('comments' in version)) {
return version;
}
return {
...version,
comments: version.comments.map((comment) => {
const canEditComment = viewerUserId
? comment.authorId === viewerUserId
: !!viewerGuestIdentityId
&& !!comment.guestIdentityId
&& comment.guestIdentityId === viewerGuestIdentityId;
const canDeleteComment = canEditComment || isProjectOwner;
const {
authorId: _commentAuthorId,
guestIdentityId: _commentGuestIdentityId,
replies,
...commentData
} = comment;
return {
...commentData,
canEdit: canEditComment,
canDelete: canDeleteComment,
replies: replies.map((reply) => {
const canEditReply = viewerUserId
? reply.authorId === viewerUserId
: !!viewerGuestIdentityId
&& !!reply.guestIdentityId
&& reply.guestIdentityId === viewerGuestIdentityId;
const canDeleteReply = canEditReply || isProjectOwner;
const {
authorId: _replyAuthorId,
guestIdentityId: _replyGuestIdentityId,
...replyData
} = reply;
return {
...replyData,
canEdit: canEditReply,
canDelete: canDeleteReply,
};
}),
};
}),
};
});
const canCommentWithMembership = access.hasAccess;
const canCommentWithShareLink = shareAccess.canComment && (session?.user?.id ? true : shareAccess.allowGuests);
const canDownloadWithMembership = access.hasAccess;
const canDownloadWithShareLink = shareAccess.hasAccess && shareAccess.canDownload;
const response = successResponse({
...videoData,
versions,
projectId: video.projectId,
project: {
name: project.name,
@@ -131,6 +189,8 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
currentUserId: session?.user?.id || null,
currentUserName: session?.user?.name || null,
canComment: canCommentWithMembership || canCommentWithShareLink,
canDownload: canDownloadWithMembership || canDownloadWithShareLink,
canManageTags: access.canEdit,
});
return withCacheControl(response, 'private, no-cache');
@@ -0,0 +1,101 @@
import { NextRequest } from 'next/server';
import { auth, checkProjectAccess } from '@/lib/auth';
import { db } from '@/lib/db';
import { rateLimit } from '@/lib/rate-limit';
import { validateShareLinkAccess } from '@/lib/share-links';
import { getShareSessionFromRequest } from '@/lib/share-session';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
import {
createGuestUploadToken,
deriveGuestUploadContext,
guestUploadTokenTtlSeconds,
type GuestUploadIntent,
} from '@/lib/guest-upload-token';
type RouteParams = { params: Promise<{ videoId: string }> };
function validateSameOriginRequest(request: NextRequest): Response | null {
const origin = request.headers.get('origin');
if (!origin) {
return apiErrors.forbidden('Missing Origin header');
}
if (origin !== request.nextUrl.origin) {
return apiErrors.forbidden('Cross-origin requests are not allowed');
}
return null;
}
export async function POST(request: NextRequest, { params }: RouteParams) {
try {
const originError = validateSameOriginRequest(request);
if (originError) return originError;
const limited = await rateLimit(request, 'guest-upload-token', {
windowMs: 60 * 1000,
maxRequests: 20,
});
if (limited) return limited;
const session = await auth();
if (session?.user?.id) {
return apiErrors.badRequest('Upload token is only required for guest uploads');
}
const { videoId } = await params;
const body = await request.json().catch(() => ({}));
const intent = body?.intent;
if (intent !== 'audio' && intent !== 'image') {
return apiErrors.badRequest('intent must be "audio" or "image"');
}
const video = await db.video.findUnique({
where: { id: videoId },
include: { project: true },
});
if (!video) {
return apiErrors.notFound('Video');
}
const access = await checkProjectAccess(video.project, session?.user?.id);
const shareSession = getShareSessionFromRequest(request, video.id);
const shareAccess = shareSession
? await validateShareLinkAccess({
token: shareSession.token,
projectId: video.projectId,
videoId: video.id,
requiredPermission: 'COMMENT',
passwordVerified: shareSession.passwordVerified,
})
: { hasAccess: false, canComment: false, canDownload: false, allowGuests: false, requiresPassword: false };
const canCommentWithMembership = !!session?.user?.id && access.hasAccess;
const canCommentWithShareLink = shareAccess.canComment && shareAccess.allowGuests;
if (!canCommentWithMembership && !canCommentWithShareLink) {
return apiErrors.forbidden('Access denied');
}
const context = deriveGuestUploadContext(request, shareSession?.token ?? null);
if (!context) {
return apiErrors.forbidden('Missing trusted client IP header');
}
const token = createGuestUploadToken({
projectId: video.projectId,
videoId: video.id,
intent: intent as GuestUploadIntent,
context,
});
const response = successResponse({
token,
intent,
expiresInSeconds: guestUploadTokenTtlSeconds,
});
return withCacheControl(response, 'private, no-store');
} catch (error) {
console.error('Error issuing guest upload token:', error);
return apiErrors.internalError('Failed to issue upload token');
}
}