mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 09:36:08 +00:00
The suite that landed in #43/#44 was written against existing behaviour, so a number of tests pinned bugs rather than asserting correct behaviour. This fixes the production code and moves each of those tests onto the fixed behaviour in the same change. Security: - project-download: derive the archive entry extension from the last path segment and restrict it to a short alphanumeric run, so an extensionless allowlisted url can no longer contribute a path separator; validate the r2 branch against the strict proxy-path pattern instead of a `startsWith`, which let `/api/upload/video/clip.mp4/../../etc/passwd` through verbatim. - rate-limit: hash a key or action wider than its column instead of skipping the query. Both the guard and the failing INSERT used to answer "allowed", so the limit stopped applying entirely. Warn at startup when TRUSTED_PROXY_MODE is unset in production. - video uploads: the file name decides the content type; a client-declared video mime no longer makes `payload.exe` acceptable. - email templates: escape in the helpers rather than relying on every caller, with an explicit `rawEmailHtml()` opt-out for the one call site that builds markup. `escapeHtml` now covers the single quote. - CSP: allow loopback object storage outside production only. - route-access: reach the billing redirect only for the workspace owner. Keying it off the owner's billing status alone made the redirect target an oracle for whose subscription had lapsed, and sent members to a page they cannot act on. - search: carry the same billing condition every other read path carries. - logger: check `err.name` as well as `err.constructor.name`, so a re-thrown, deserialised or minified Prisma error is still redacted. - upload tokens: resolve the signing secret outside the try, so a server booted without one fails loudly instead of reporting every grant as a forgery. - invitations: never downgrade an existing membership, and report a scoped invitation that points at nothing as not_found rather than accepted. - auth: resolve the workspace role for every signed-in caller, so checkProjectAccess and computeProjectAccess stop disagreeing about the owner who also owns the workspace. The `intent` option is gone with it. - r2-media-proxy: validate the object key inside the proxy so the guard travels with the function; delete the unused, unanchored `mediaUrlToR2Key`. - r2: sign the content type into presigned PUT grants. Correctness: - frame rate snapping picks the nearest standard, not the first within tolerance, so 24, 30 and 60 fps are reachable at all. - a version upload registers its Bunny cleanup as soon as bunny-init answers, so a failed tus upload no longer leaves a billed video behind. - deleting videos clears storage before the rows, so a refused DELETE leaves a retryable row rather than an orphaned object. - an expired upload session can be cancelled, which is what releases its quota. - `voice/` joins the delete allowlist, so a voice note can be removed by the module that wrote it. - a failed CORS write propagates instead of being mistaken for an empty config and replacing the bucket's rules. - filtering projects by workspace no longer hides projects the unfiltered call returns. - upload retries skip aborts and permanent 4xx; progress no longer divides by zero. - reply edits no longer clear the comment's tag; optimistic resolve rolls back to the state it replaced; the delete snapshot is captured once. - assorted UI fixes: duplicate React keys, double-click guards reading stale closures, the tag list fetched twice per load, a failed member list rendering as an empty one, a stale "Initializing upload..." beside a failure, and a registration banner pointing at an email that never arrives. Consistency and access: - the two download routes answer 404 for an id belonging to another tenant, as the comment export route already did. A caller who does belong still gets 403. - accessible names for the share-link password field, the guest name gates, the version dialog inputs and the comment-tag controls. Repository health: - the runner image installs production dependencies only. - a setup file for the unit project restores stubbed env centrally. - native tsconfig path resolution replaces vite-tsconfig-paths. - `uploadBytesWithProgress` exists once. - admin stats bill Bunny storage to the workspace owner like every other quota, gate on the configured flag, wire up the single-flight guard and count the statuses that belonged to no bucket. - `r2Client.destroy()` releases the presign client too. - `prepare` tolerates a production install, where husky is absent.
392 lines
13 KiB
TypeScript
392 lines
13 KiB
TypeScript
import { NextRequest } from 'next/server';
|
|
import { db } from '@/lib/db';
|
|
import { auth, checkProjectAccess } from '@/lib/auth';
|
|
import { r2Client, R2_BUCKET_NAME } from '@/lib/r2';
|
|
import { DeleteObjectCommand } from '@aws-sdk/client-s3';
|
|
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 { getGuestIdentityFromRequest } from '@/lib/guest-identity';
|
|
import { runWithConcurrency } from '@/lib/async-pool';
|
|
import { validateAnnotationStrokes } from '@/lib/validation';
|
|
import { logError } from '@/lib/logger';
|
|
|
|
const CLEANUP_DELETE_CONCURRENCY = 5;
|
|
|
|
type RouteParams = { params: Promise<{ commentId: string }> };
|
|
|
|
// GET /api/comments/[commentId]
|
|
export async function GET(request: NextRequest, { params }: RouteParams) {
|
|
try {
|
|
const session = await auth();
|
|
const { commentId } = await params;
|
|
|
|
const comment = await db.comment.findUnique({
|
|
where: { id: commentId },
|
|
select: {
|
|
id: true,
|
|
content: true,
|
|
timestamp: true,
|
|
timestampEnd: true,
|
|
createdAt: true,
|
|
updatedAt: true,
|
|
isResolved: true,
|
|
resolvedAt: true,
|
|
voiceUrl: true,
|
|
voiceDuration: true,
|
|
imageUrl: true,
|
|
parentId: true,
|
|
authorId: true,
|
|
tagId: true,
|
|
versionId: true,
|
|
guestName: true,
|
|
author: { select: { id: true, name: true, image: true } },
|
|
tag: { select: { id: true, name: true, color: true } },
|
|
replies: {
|
|
orderBy: { createdAt: 'asc' },
|
|
select: {
|
|
id: true,
|
|
content: true,
|
|
timestamp: true,
|
|
timestampEnd: true,
|
|
createdAt: true,
|
|
updatedAt: true,
|
|
isResolved: true,
|
|
resolvedAt: true,
|
|
voiceUrl: true,
|
|
voiceDuration: true,
|
|
imageUrl: true,
|
|
parentId: true,
|
|
authorId: true,
|
|
tagId: true,
|
|
versionId: true,
|
|
guestName: true,
|
|
author: { select: { id: true, name: true, image: true } },
|
|
tag: { select: { id: true, name: true, color: true } },
|
|
},
|
|
},
|
|
version: {
|
|
include: {
|
|
video: {
|
|
include: {
|
|
project: true,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
if (!comment) {
|
|
return apiErrors.notFound('Comment');
|
|
}
|
|
|
|
// Authorization check: verify user has access to the project
|
|
const project = comment.version.video.project;
|
|
const access = await checkProjectAccess(project, session?.user?.id);
|
|
|
|
if (!access.hasAccess) {
|
|
return apiErrors.forbidden('Access denied');
|
|
}
|
|
|
|
// Strip internal project data from response
|
|
const commentData = { ...comment } as Omit<typeof comment, 'version'> & { version?: unknown };
|
|
delete commentData.version;
|
|
const response = successResponse(commentData);
|
|
return withCacheControl(response, 'private, no-cache');
|
|
} catch (error) {
|
|
logError('Error fetching comment:', error);
|
|
return apiErrors.internalError('Failed to fetch comment');
|
|
}
|
|
}
|
|
|
|
// PATCH /api/comments/[commentId]
|
|
export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
|
try {
|
|
const limited = await rateLimit(request, 'mutate');
|
|
if (limited) return limited;
|
|
|
|
const session = await auth();
|
|
const { commentId } = await params;
|
|
const body = await request.json();
|
|
const { content, isResolved, tagId, annotationData } = body;
|
|
|
|
const comment = await db.comment.findUnique({
|
|
where: { id: commentId },
|
|
include: {
|
|
version: {
|
|
include: {
|
|
video: {
|
|
include: {
|
|
project: true,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
if (!comment) {
|
|
return apiErrors.notFound('Comment');
|
|
}
|
|
|
|
const project = comment.version.video.project;
|
|
const userId = session?.user?.id ?? null;
|
|
const access = await checkProjectAccess(project, userId ?? undefined);
|
|
const isOwner = userId === project.ownerId;
|
|
const isAuthor = !!userId && comment.authorId === userId;
|
|
const guestIdentityId = !userId ? getGuestIdentityFromRequest(request) : null;
|
|
const isGuestAuthor =
|
|
!userId &&
|
|
!comment.authorId &&
|
|
!!comment.guestIdentityId &&
|
|
guestIdentityId === comment.guestIdentityId;
|
|
const canEditOwnContent = isAuthor || isGuestAuthor;
|
|
const canResolveComment = access.canEdit;
|
|
|
|
if (!userId && !isGuestAuthor) {
|
|
const shareSession = getShareSessionFromRequest(request, comment.version.video.id);
|
|
const shareAccess = shareSession
|
|
? await validateShareLinkAccess({
|
|
token: shareSession.token,
|
|
projectId: project.id,
|
|
videoId: comment.version.video.id,
|
|
requiredPermission: 'COMMENT',
|
|
passwordVerified: shareSession.passwordVerified,
|
|
})
|
|
: {
|
|
hasAccess: false,
|
|
canComment: false,
|
|
canDownload: false,
|
|
allowGuests: false,
|
|
requiresPassword: false,
|
|
};
|
|
const hasGuestAccess =
|
|
project.visibility === 'PUBLIC' || (shareAccess.canComment && shareAccess.allowGuests);
|
|
if (!hasGuestAccess) {
|
|
return apiErrors.forbidden('Access denied');
|
|
}
|
|
}
|
|
|
|
// Only author can edit content or tag
|
|
if (
|
|
(content !== undefined || tagId !== undefined || annotationData !== undefined) &&
|
|
!canEditOwnContent
|
|
) {
|
|
return apiErrors.forbidden('Only the author can edit comment content');
|
|
}
|
|
|
|
// Owner, author, members, or workspace members can resolve/unresolve
|
|
if (isResolved !== undefined && !canResolveComment) {
|
|
return apiErrors.forbidden('Only admins can resolve comments');
|
|
}
|
|
|
|
const updateData: Record<string, unknown> = {};
|
|
if (content !== undefined && typeof content === 'string') updateData.content = content.trim();
|
|
if (tagId !== undefined) {
|
|
// Verify tag belongs to this project to prevent cross-project tag leakage (IDOR)
|
|
if (tagId !== null) {
|
|
const tag = await db.commentTag.findFirst({
|
|
where: { id: tagId, projectId: project.id },
|
|
});
|
|
if (!tag) {
|
|
return apiErrors.badRequest('Tag not found');
|
|
}
|
|
}
|
|
updateData.tagId = tagId;
|
|
}
|
|
if (annotationData !== undefined) {
|
|
if (annotationData === null) {
|
|
updateData.annotationData = null;
|
|
} else {
|
|
if (!Array.isArray(annotationData)) {
|
|
return apiErrors.badRequest('annotationData must be an array of valid stroke objects');
|
|
}
|
|
const validStrokes = validateAnnotationStrokes(annotationData);
|
|
if (validStrokes === null) {
|
|
return apiErrors.badRequest('annotationData must be an array of valid stroke objects');
|
|
}
|
|
updateData.annotationData = JSON.stringify(validStrokes);
|
|
}
|
|
}
|
|
if (isResolved !== undefined) {
|
|
updateData.isResolved = isResolved;
|
|
updateData.resolvedAt = isResolved ? new Date() : null;
|
|
}
|
|
|
|
const updatedComment = await db.comment.update({
|
|
where: { id: commentId },
|
|
data: updateData,
|
|
include: {
|
|
author: { select: { id: true, name: true, image: true } },
|
|
tag: { select: { id: true, name: true, color: true } },
|
|
replies: {
|
|
include: {
|
|
author: { select: { id: true, name: true, image: true } },
|
|
tag: { select: { id: true, name: true, color: true } },
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
const updatedCommentData = Object.fromEntries(
|
|
Object.entries(updatedComment).filter(([key]) => key !== 'guestIdentityId')
|
|
);
|
|
const response = successResponse({
|
|
...updatedCommentData,
|
|
canEdit: canEditOwnContent,
|
|
canDelete: canEditOwnContent || isOwner,
|
|
replies: updatedComment.replies.map((reply) => {
|
|
const canEditReply = !!userId
|
|
? reply.authorId === userId
|
|
: !!guestIdentityId &&
|
|
!reply.authorId &&
|
|
!!reply.guestIdentityId &&
|
|
reply.guestIdentityId === guestIdentityId;
|
|
const replyData = Object.fromEntries(
|
|
Object.entries(reply).filter(([key]) => key !== 'guestIdentityId')
|
|
);
|
|
return {
|
|
...replyData,
|
|
canEdit: canEditReply,
|
|
canDelete: canEditReply || isOwner,
|
|
};
|
|
}),
|
|
});
|
|
return withCacheControl(response, 'private, no-store');
|
|
} catch (error) {
|
|
logError('Error updating comment:', error);
|
|
return apiErrors.internalError('Failed to update comment');
|
|
}
|
|
}
|
|
|
|
// DELETE /api/comments/[commentId]
|
|
export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
|
try {
|
|
const limited = await rateLimit(request, 'mutate');
|
|
if (limited) return limited;
|
|
|
|
const session = await auth();
|
|
const { commentId } = await params;
|
|
|
|
const comment = await db.comment.findUnique({
|
|
where: { id: commentId },
|
|
include: {
|
|
version: {
|
|
include: {
|
|
video: {
|
|
include: {
|
|
project: true,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
replies: { select: { voiceUrl: true, imageUrl: true } },
|
|
},
|
|
});
|
|
|
|
if (!comment) {
|
|
return apiErrors.notFound('Comment');
|
|
}
|
|
|
|
const project = comment.version.video.project;
|
|
const userId = session?.user?.id ?? null;
|
|
const isAuthor = !!userId && comment.authorId === userId;
|
|
|
|
// Project owners/admins and workspace admins can delete any comment
|
|
const access = userId ? await checkProjectAccess(project, userId) : null;
|
|
const isPrivilegedUser = !!access?.canEdit;
|
|
|
|
let canDelete = isAuthor || isPrivilegedUser;
|
|
if (!canDelete && !userId) {
|
|
const guestIdentityId = getGuestIdentityFromRequest(request);
|
|
const isGuestAuthor =
|
|
!comment.authorId &&
|
|
!!comment.guestIdentityId &&
|
|
guestIdentityId === comment.guestIdentityId;
|
|
|
|
if (isGuestAuthor) {
|
|
const shareSession = getShareSessionFromRequest(request, comment.version.video.id);
|
|
const shareAccess = shareSession
|
|
? await validateShareLinkAccess({
|
|
token: shareSession.token,
|
|
projectId: project.id,
|
|
videoId: comment.version.video.id,
|
|
requiredPermission: 'COMMENT',
|
|
passwordVerified: shareSession.passwordVerified,
|
|
})
|
|
: {
|
|
hasAccess: false,
|
|
canComment: false,
|
|
canDownload: false,
|
|
allowGuests: false,
|
|
requiresPassword: false,
|
|
};
|
|
const hasGuestAccess =
|
|
project.visibility === 'PUBLIC' || (shareAccess.canComment && shareAccess.allowGuests);
|
|
if (!hasGuestAccess) {
|
|
return apiErrors.forbidden('Access denied');
|
|
}
|
|
canDelete = true;
|
|
}
|
|
}
|
|
|
|
if (!canDelete) {
|
|
return apiErrors.forbidden('You do not have permission to delete this comment');
|
|
}
|
|
|
|
// Collect all media URLs to delete from R2 (comment + its replies)
|
|
const mediaUrls: string[] = [];
|
|
if (comment.voiceUrl) mediaUrls.push(comment.voiceUrl);
|
|
if (comment.imageUrl) mediaUrls.push(comment.imageUrl);
|
|
for (const reply of comment.replies) {
|
|
if (reply.voiceUrl) mediaUrls.push(reply.voiceUrl);
|
|
if (reply.imageUrl) mediaUrls.push(reply.imageUrl);
|
|
}
|
|
|
|
await db.comment.delete({ where: { id: commentId } });
|
|
|
|
// Clean up media files from R2 (best-effort, don't block on failure)
|
|
const AUDIO_PREFIX = '/api/upload/audio/';
|
|
const IMAGE_PREFIX = '/api/upload/image/';
|
|
const mediaKeys = [
|
|
...new Set(
|
|
mediaUrls
|
|
.map((url) => {
|
|
// Extract filename using string parsing (safe against ReDoS)
|
|
if (url.includes(AUDIO_PREFIX)) {
|
|
const filename = url.slice(url.indexOf(AUDIO_PREFIX) + AUDIO_PREFIX.length);
|
|
return filename ? `voice/${filename}` : null;
|
|
}
|
|
if (url.includes(IMAGE_PREFIX)) {
|
|
const filename = url.slice(url.indexOf(IMAGE_PREFIX) + IMAGE_PREFIX.length);
|
|
return filename ? `images/${filename}` : null;
|
|
}
|
|
return null;
|
|
})
|
|
.filter((key): key is string => Boolean(key))
|
|
),
|
|
];
|
|
|
|
await runWithConcurrency(mediaKeys, CLEANUP_DELETE_CONCURRENCY, async (key) => {
|
|
try {
|
|
await r2Client.send(
|
|
new DeleteObjectCommand({
|
|
Bucket: R2_BUCKET_NAME,
|
|
Key: key,
|
|
})
|
|
);
|
|
} catch (err) {
|
|
logError(`Failed to delete media from R2 (key: ${key}):`, err);
|
|
}
|
|
});
|
|
|
|
const response = successResponse({ message: 'Comment deleted' });
|
|
return withCacheControl(response, 'private, no-store');
|
|
} catch (error) {
|
|
logError('Error deleting comment:', error);
|
|
return apiErrors.internalError('Failed to delete comment');
|
|
}
|
|
}
|