mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 17:46:06 +00:00
refactor: eslint and prettier conflict will be resolved and formatted
This commit is contained in:
@@ -26,42 +26,57 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
}
|
||||
|
||||
const { feedbackId } = await params;
|
||||
const userFeedbackDelegate = (db as unknown as {
|
||||
userFeedback?: {
|
||||
findUnique: (args: unknown) => Promise<{
|
||||
id: string;
|
||||
screenshotUrl: string | null;
|
||||
screenshots?: Array<{ url: string }>;
|
||||
} | null>;
|
||||
delete: (args: { where: { id: string } }) => Promise<{ id: string }>;
|
||||
findFirst: (args: { where: { screenshotUrl: string }; select: { id: true } }) => Promise<{ id: string } | null>;
|
||||
};
|
||||
userFeedbackScreenshot?: {
|
||||
findFirst: (args: { where: { url: string }; select: { id: true } }) => Promise<{ id: string } | null>;
|
||||
};
|
||||
}).userFeedback;
|
||||
const userFeedbackScreenshotDelegate = (db as unknown as {
|
||||
userFeedbackScreenshot?: {
|
||||
findFirst: (args: { where: { url: string }; select: { id: true } }) => Promise<{ id: string } | null>;
|
||||
};
|
||||
}).userFeedbackScreenshot;
|
||||
const userFeedbackDelegate = (
|
||||
db as unknown as {
|
||||
userFeedback?: {
|
||||
findUnique: (args: unknown) => Promise<{
|
||||
id: string;
|
||||
screenshotUrl: string | null;
|
||||
screenshots?: Array<{ url: string }>;
|
||||
} | null>;
|
||||
delete: (args: { where: { id: string } }) => Promise<{ id: string }>;
|
||||
findFirst: (args: {
|
||||
where: { screenshotUrl: string };
|
||||
select: { id: true };
|
||||
}) => Promise<{ id: string } | null>;
|
||||
};
|
||||
userFeedbackScreenshot?: {
|
||||
findFirst: (args: {
|
||||
where: { url: string };
|
||||
select: { id: true };
|
||||
}) => Promise<{ id: string } | null>;
|
||||
};
|
||||
}
|
||||
).userFeedback;
|
||||
const userFeedbackScreenshotDelegate = (
|
||||
db as unknown as {
|
||||
userFeedbackScreenshot?: {
|
||||
findFirst: (args: {
|
||||
where: { url: string };
|
||||
select: { id: true };
|
||||
}) => Promise<{ id: string } | null>;
|
||||
};
|
||||
}
|
||||
).userFeedbackScreenshot;
|
||||
|
||||
if (!userFeedbackDelegate) {
|
||||
return apiErrors.internalError('Feedback model is not available yet');
|
||||
}
|
||||
|
||||
let feedbackRecord = await userFeedbackDelegate.findUnique({
|
||||
where: { id: feedbackId },
|
||||
include: {
|
||||
screenshots: {
|
||||
select: { url: true },
|
||||
let feedbackRecord = await userFeedbackDelegate
|
||||
.findUnique({
|
||||
where: { id: feedbackId },
|
||||
include: {
|
||||
screenshots: {
|
||||
select: { url: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
}).catch((error) => {
|
||||
const message = error instanceof Error ? error.message : '';
|
||||
if (message.includes('Unknown field `screenshots`')) return null;
|
||||
throw error;
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
const message = error instanceof Error ? error.message : '';
|
||||
if (message.includes('Unknown field `screenshots`')) return null;
|
||||
throw error;
|
||||
});
|
||||
|
||||
if (!feedbackRecord) {
|
||||
feedbackRecord = await userFeedbackDelegate.findUnique({
|
||||
@@ -88,31 +103,34 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
const filename = extractImageFilenameFromProxyUrl(url);
|
||||
if (!filename) return;
|
||||
|
||||
const [commentReferenced, feedbackReferenced, feedbackAttachmentReferenced] = await Promise.all([
|
||||
db.comment.findFirst({
|
||||
where: { imageUrl: url },
|
||||
select: { id: true },
|
||||
}),
|
||||
userFeedbackDelegate.findFirst({
|
||||
where: { screenshotUrl: url },
|
||||
select: { id: true },
|
||||
}),
|
||||
userFeedbackScreenshotDelegate
|
||||
? userFeedbackScreenshotDelegate.findFirst({
|
||||
where: { url },
|
||||
const [commentReferenced, feedbackReferenced, feedbackAttachmentReferenced] =
|
||||
await Promise.all([
|
||||
db.comment.findFirst({
|
||||
where: { imageUrl: url },
|
||||
select: { id: true },
|
||||
})
|
||||
: Promise.resolve(null),
|
||||
]);
|
||||
}),
|
||||
userFeedbackDelegate.findFirst({
|
||||
where: { screenshotUrl: url },
|
||||
select: { id: true },
|
||||
}),
|
||||
userFeedbackScreenshotDelegate
|
||||
? userFeedbackScreenshotDelegate.findFirst({
|
||||
where: { url },
|
||||
select: { id: true },
|
||||
})
|
||||
: Promise.resolve(null),
|
||||
]);
|
||||
|
||||
if (commentReferenced || feedbackReferenced || feedbackAttachmentReferenced) return;
|
||||
|
||||
await r2Client.send(
|
||||
new DeleteObjectCommand({
|
||||
Bucket: R2_BUCKET_NAME,
|
||||
Key: `images/${filename}`,
|
||||
})
|
||||
).catch(() => undefined);
|
||||
await r2Client
|
||||
.send(
|
||||
new DeleteObjectCommand({
|
||||
Bucket: R2_BUCKET_NAME,
|
||||
Key: `images/${filename}`,
|
||||
})
|
||||
)
|
||||
.catch(() => undefined);
|
||||
})
|
||||
);
|
||||
|
||||
|
||||
@@ -29,7 +29,9 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
include: {
|
||||
video: {
|
||||
include: {
|
||||
project: { select: { id: true, ownerId: true, workspaceId: true, visibility: true } },
|
||||
project: {
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -38,7 +40,11 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
});
|
||||
if (!approvalRequest) return apiErrors.notFound('Approval request');
|
||||
|
||||
const access = await checkProjectAccess(approvalRequest.version.video.project, session.user.id, { intent: 'manage' });
|
||||
const access = await checkProjectAccess(
|
||||
approvalRequest.version.video.project,
|
||||
session.user.id,
|
||||
{ intent: 'manage' }
|
||||
);
|
||||
const canCancel = approvalRequest.requestedById === session.user.id || access.canEdit;
|
||||
if (!canCancel) return apiErrors.forbidden('Access denied');
|
||||
|
||||
@@ -46,33 +52,36 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.conflict('Only pending approval requests can be canceled');
|
||||
}
|
||||
|
||||
const updated = await db.$transaction(async (tx) => {
|
||||
const current = await tx.approvalRequest.findUnique({
|
||||
where: { id: requestId },
|
||||
select: { status: true },
|
||||
});
|
||||
if (!current) throw new Error('__NOT_FOUND__');
|
||||
if (current.status !== 'PENDING') throw new Error('__NOT_PENDING__');
|
||||
const updated = await db.$transaction(
|
||||
async (tx) => {
|
||||
const current = await tx.approvalRequest.findUnique({
|
||||
where: { id: requestId },
|
||||
select: { status: true },
|
||||
});
|
||||
if (!current) throw new Error('__NOT_FOUND__');
|
||||
if (current.status !== 'PENDING') throw new Error('__NOT_PENDING__');
|
||||
|
||||
return tx.approvalRequest.update({
|
||||
where: { id: requestId },
|
||||
data: {
|
||||
status: 'CANCELED',
|
||||
canceledAt: new Date(),
|
||||
canceledById: session.user.id,
|
||||
},
|
||||
include: {
|
||||
requestedBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
canceledBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
decisions: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
include: { approver: { select: { id: true, name: true, email: true, image: true } } },
|
||||
return tx.approvalRequest.update({
|
||||
where: { id: requestId },
|
||||
data: {
|
||||
status: 'CANCELED',
|
||||
canceledAt: new Date(),
|
||||
canceledById: session.user.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
}, {
|
||||
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
|
||||
});
|
||||
include: {
|
||||
requestedBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
canceledBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
decisions: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
include: { approver: { select: { id: true, name: true, email: true, image: true } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
{
|
||||
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
|
||||
}
|
||||
);
|
||||
|
||||
const response = successResponse({ request: updated });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
|
||||
@@ -41,7 +41,15 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
include: {
|
||||
video: {
|
||||
include: {
|
||||
project: { select: { id: true, name: true, ownerId: true, workspaceId: true, visibility: true } },
|
||||
project: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
ownerId: true,
|
||||
workspaceId: true,
|
||||
visibility: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -66,102 +74,105 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.conflict('You have already responded to this request');
|
||||
}
|
||||
|
||||
const updated = await db.$transaction(async (tx) => {
|
||||
const currentRequest = await tx.approvalRequest.findUnique({
|
||||
where: { id: requestId },
|
||||
include: {
|
||||
decisions: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
include: {
|
||||
approver: { select: { id: true, name: true, email: true, image: true } },
|
||||
const updated = await db.$transaction(
|
||||
async (tx) => {
|
||||
const currentRequest = await tx.approvalRequest.findUnique({
|
||||
where: { id: requestId },
|
||||
include: {
|
||||
decisions: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
include: {
|
||||
approver: { select: { id: true, name: true, email: true, image: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
requestedBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
version: {
|
||||
include: {
|
||||
video: {
|
||||
include: {
|
||||
project: { select: { id: true, name: true } },
|
||||
requestedBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
version: {
|
||||
include: {
|
||||
video: {
|
||||
include: {
|
||||
project: { select: { id: true, name: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!currentRequest) {
|
||||
throw new Error('__NOT_FOUND__');
|
||||
}
|
||||
if (currentRequest.status !== 'PENDING') {
|
||||
throw new Error('__NOT_PENDING__');
|
||||
}
|
||||
});
|
||||
if (!currentRequest) {
|
||||
throw new Error('__NOT_FOUND__');
|
||||
}
|
||||
if (currentRequest.status !== 'PENDING') {
|
||||
throw new Error('__NOT_PENDING__');
|
||||
}
|
||||
|
||||
const decisionRow = await tx.approvalDecision.findUnique({
|
||||
where: { requestId_approverId: { requestId, approverId: session.user.id } },
|
||||
select: { status: true },
|
||||
});
|
||||
if (!decisionRow) throw new Error('__NOT_APPROVER__');
|
||||
if (decisionRow.status !== 'PENDING') throw new Error('__ALREADY_RESPONDED__');
|
||||
const decisionRow = await tx.approvalDecision.findUnique({
|
||||
where: { requestId_approverId: { requestId, approverId: session.user.id } },
|
||||
select: { status: true },
|
||||
});
|
||||
if (!decisionRow) throw new Error('__NOT_APPROVER__');
|
||||
if (decisionRow.status !== 'PENDING') throw new Error('__ALREADY_RESPONDED__');
|
||||
|
||||
await tx.approvalDecision.update({
|
||||
where: { requestId_approverId: { requestId, approverId: session.user.id } },
|
||||
data: {
|
||||
status: decision,
|
||||
note: note || null,
|
||||
respondedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
if (decision === 'REJECTED') {
|
||||
await tx.approvalRequest.update({
|
||||
where: { id: requestId },
|
||||
await tx.approvalDecision.update({
|
||||
where: { requestId_approverId: { requestId, approverId: session.user.id } },
|
||||
data: {
|
||||
status: 'REJECTED',
|
||||
resolvedAt: new Date(),
|
||||
status: decision,
|
||||
note: note || null,
|
||||
respondedAt: new Date(),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const pendingCount = await tx.approvalDecision.count({
|
||||
where: { requestId, status: 'PENDING' },
|
||||
});
|
||||
const rejectedCount = await tx.approvalDecision.count({
|
||||
where: { requestId, status: 'REJECTED' },
|
||||
});
|
||||
if (pendingCount === 0 && rejectedCount === 0) {
|
||||
|
||||
if (decision === 'REJECTED') {
|
||||
await tx.approvalRequest.update({
|
||||
where: { id: requestId },
|
||||
data: {
|
||||
status: 'APPROVED',
|
||||
status: 'REJECTED',
|
||||
resolvedAt: new Date(),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const pendingCount = await tx.approvalDecision.count({
|
||||
where: { requestId, status: 'PENDING' },
|
||||
});
|
||||
const rejectedCount = await tx.approvalDecision.count({
|
||||
where: { requestId, status: 'REJECTED' },
|
||||
});
|
||||
if (pendingCount === 0 && rejectedCount === 0) {
|
||||
await tx.approvalRequest.update({
|
||||
where: { id: requestId },
|
||||
data: {
|
||||
status: 'APPROVED',
|
||||
resolvedAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tx.approvalRequest.findUnique({
|
||||
where: { id: requestId },
|
||||
include: {
|
||||
requestedBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
canceledBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
decisions: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
include: {
|
||||
approver: { select: { id: true, name: true, email: true, image: true } },
|
||||
return tx.approvalRequest.findUnique({
|
||||
where: { id: requestId },
|
||||
include: {
|
||||
requestedBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
canceledBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
decisions: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
include: {
|
||||
approver: { select: { id: true, name: true, email: true, image: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
version: {
|
||||
include: {
|
||||
video: {
|
||||
include: {
|
||||
project: { select: { id: true, name: true } },
|
||||
version: {
|
||||
include: {
|
||||
video: {
|
||||
include: {
|
||||
project: { select: { id: true, name: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}, {
|
||||
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
|
||||
});
|
||||
});
|
||||
},
|
||||
{
|
||||
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
|
||||
}
|
||||
);
|
||||
|
||||
if (!updated) return apiErrors.notFound('Approval request');
|
||||
|
||||
@@ -212,9 +223,12 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
if (error.message === '__NOT_PENDING__') return apiErrors.conflict('This approval request is no longer pending');
|
||||
if (error.message === '__ALREADY_RESPONDED__') return apiErrors.conflict('You have already responded to this request');
|
||||
if (error.message === '__NOT_APPROVER__') return apiErrors.forbidden('You are not an approver on this request');
|
||||
if (error.message === '__NOT_PENDING__')
|
||||
return apiErrors.conflict('This approval request is no longer pending');
|
||||
if (error.message === '__ALREADY_RESPONDED__')
|
||||
return apiErrors.conflict('You have already responded to this request');
|
||||
if (error.message === '__NOT_APPROVER__')
|
||||
return apiErrors.forbidden('You are not an approver on this request');
|
||||
if (error.message === '__NOT_FOUND__') return apiErrors.notFound('Approval request');
|
||||
}
|
||||
if (isSerializableConflict(error)) {
|
||||
|
||||
@@ -6,9 +6,9 @@ export const { GET } = handlers;
|
||||
|
||||
// Wrap NextAuth POST with login rate limiting
|
||||
export async function POST(request: Request) {
|
||||
const limited = await rateLimit(request, 'login');
|
||||
if (limited) return limited;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const response = await handlers.POST(request as any);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
const limited = await rateLimit(request, 'login');
|
||||
if (limited) return limited;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const response = await handlers.POST(request as any);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
}
|
||||
|
||||
+146
-138
@@ -2,149 +2,157 @@ import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { acceptInvitationTokenForUser, getValidInvitationByToken } from '@/lib/invitations';
|
||||
import { checkRateLimit, getClientIp, rateLimitHeaders, RATE_LIMIT_CONFIGS } from '@/lib/rate-limit';
|
||||
import {
|
||||
checkRateLimit,
|
||||
getClientIp,
|
||||
rateLimitHeaders,
|
||||
RATE_LIMIT_CONFIGS,
|
||||
} from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { isInviteCodeRequired } from '@/lib/feature-flags';
|
||||
import { logError } from '@/lib/logger';
|
||||
import { createVerificationToken, isEmailVerificationEnabled, sendVerificationEmail } from '@/lib/email-verification';
|
||||
import {
|
||||
createVerificationToken,
|
||||
isEmailVerificationEnabled,
|
||||
sendVerificationEmail,
|
||||
} from '@/lib/email-verification';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
// Rate limiting by IP
|
||||
const clientIp = getClientIp(request);
|
||||
const rateLimitKey = `register:${clientIp}`;
|
||||
const rateLimit = await checkRateLimit(rateLimitKey, 'register');
|
||||
try {
|
||||
// Rate limiting by IP
|
||||
const clientIp = getClientIp(request);
|
||||
const rateLimitKey = `register:${clientIp}`;
|
||||
const rateLimit = await checkRateLimit(rateLimitKey, 'register');
|
||||
|
||||
if (!rateLimit.allowed) {
|
||||
return apiErrors.rateLimited('Too many registration attempts. Please try again later.');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, email, password, inviteCode, invitationToken } = body;
|
||||
|
||||
// Validate required fields
|
||||
if (!name || typeof name !== 'string' || name.trim().length < 2 || name.trim().length > 100) {
|
||||
return apiErrors.badRequest('Name must be between 2 and 100 characters');
|
||||
}
|
||||
|
||||
if (!email || typeof email !== 'string') {
|
||||
return apiErrors.badRequest('Email is required');
|
||||
}
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.validationError('Invalid email format');
|
||||
}
|
||||
|
||||
// Allow registration via a valid invitation token OR global invite code.
|
||||
let invitationIsValid = false;
|
||||
let validatedInvitationToken: string | null = null;
|
||||
if (typeof invitationToken === 'string' && invitationToken.trim()) {
|
||||
const normalizedToken = invitationToken.trim();
|
||||
const invitation = await getValidInvitationByToken(normalizedToken);
|
||||
if (invitation && invitation.email === normalizedEmail) {
|
||||
invitationIsValid = true;
|
||||
validatedInvitationToken = normalizedToken;
|
||||
} else {
|
||||
return apiErrors.forbidden('Invalid or expired invitation token');
|
||||
}
|
||||
}
|
||||
|
||||
if (!invitationIsValid && isInviteCodeRequired()) {
|
||||
// Validate invite code using constant-time comparison to prevent timing attacks
|
||||
const validInviteCode = process.env.INVITE_CODE;
|
||||
if (!validInviteCode || !inviteCode) {
|
||||
return apiErrors.forbidden('Invalid invite code');
|
||||
}
|
||||
|
||||
// Constant-time comparison
|
||||
const { timingSafeEqual } = await import('crypto');
|
||||
const validBuffer = Buffer.from(validInviteCode);
|
||||
const providedBuffer = Buffer.from(String(inviteCode));
|
||||
|
||||
// Ensure same length for comparison (prevents length-based timing leak)
|
||||
const isValidLength = validBuffer.length === providedBuffer.length;
|
||||
const compareBuffer = isValidLength ? providedBuffer : validBuffer;
|
||||
const isValidCode = isValidLength && timingSafeEqual(validBuffer, compareBuffer);
|
||||
|
||||
if (!isValidCode) {
|
||||
return apiErrors.forbidden('Invalid invite code');
|
||||
}
|
||||
}
|
||||
|
||||
if (!password || typeof password !== 'string' || password.length < 8 || password.length > 128) {
|
||||
return apiErrors.badRequest('Password must be between 8 and 128 characters');
|
||||
}
|
||||
|
||||
// Check if email already exists
|
||||
const existingUser = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
return apiErrors.conflict('An account with this email already exists');
|
||||
}
|
||||
|
||||
// Hash password
|
||||
const hashedPassword = await bcrypt.hash(password, 12);
|
||||
|
||||
// If SMTP is not configured, auto-verify the email so users aren't locked out
|
||||
const emailVerificationRequired = isEmailVerificationEnabled();
|
||||
|
||||
// Create user
|
||||
const user = await db.user.create({
|
||||
data: {
|
||||
name: name.trim(),
|
||||
email: normalizedEmail,
|
||||
password: hashedPassword,
|
||||
emailVerified: emailVerificationRequired ? null : new Date(),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (validatedInvitationToken) {
|
||||
const result = await acceptInvitationTokenForUser({
|
||||
token: validatedInvitationToken,
|
||||
userId: user.id,
|
||||
email: normalizedEmail,
|
||||
});
|
||||
if (result !== 'accepted') {
|
||||
await db.user.delete({ where: { id: user.id } });
|
||||
return apiErrors.conflict('Invitation could not be accepted. Please request a new invitation.');
|
||||
}
|
||||
}
|
||||
|
||||
// Send verification email if SMTP is configured
|
||||
if (emailVerificationRequired) {
|
||||
const verificationToken = await createVerificationToken(normalizedEmail);
|
||||
await sendVerificationEmail(normalizedEmail, verificationToken);
|
||||
}
|
||||
|
||||
const message = emailVerificationRequired
|
||||
? 'Account created. Please check your email to verify your address before signing in.'
|
||||
: 'Account created successfully';
|
||||
|
||||
const response = successResponse(
|
||||
{ message, user, emailVerificationRequired },
|
||||
201
|
||||
);
|
||||
|
||||
// Add rate limit headers to successful response
|
||||
const headers = rateLimitHeaders(rateLimit, RATE_LIMIT_CONFIGS.register.maxRequests);
|
||||
Object.entries(headers).forEach(([key, value]) => {
|
||||
response.headers.set(key, value);
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Registration error:', error);
|
||||
return apiErrors.internalError('Failed to create account');
|
||||
if (!rateLimit.allowed) {
|
||||
return apiErrors.rateLimited('Too many registration attempts. Please try again later.');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, email, password, inviteCode, invitationToken } = body;
|
||||
|
||||
// Validate required fields
|
||||
if (!name || typeof name !== 'string' || name.trim().length < 2 || name.trim().length > 100) {
|
||||
return apiErrors.badRequest('Name must be between 2 and 100 characters');
|
||||
}
|
||||
|
||||
if (!email || typeof email !== 'string') {
|
||||
return apiErrors.badRequest('Email is required');
|
||||
}
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.validationError('Invalid email format');
|
||||
}
|
||||
|
||||
// Allow registration via a valid invitation token OR global invite code.
|
||||
let invitationIsValid = false;
|
||||
let validatedInvitationToken: string | null = null;
|
||||
if (typeof invitationToken === 'string' && invitationToken.trim()) {
|
||||
const normalizedToken = invitationToken.trim();
|
||||
const invitation = await getValidInvitationByToken(normalizedToken);
|
||||
if (invitation && invitation.email === normalizedEmail) {
|
||||
invitationIsValid = true;
|
||||
validatedInvitationToken = normalizedToken;
|
||||
} else {
|
||||
return apiErrors.forbidden('Invalid or expired invitation token');
|
||||
}
|
||||
}
|
||||
|
||||
if (!invitationIsValid && isInviteCodeRequired()) {
|
||||
// Validate invite code using constant-time comparison to prevent timing attacks
|
||||
const validInviteCode = process.env.INVITE_CODE;
|
||||
if (!validInviteCode || !inviteCode) {
|
||||
return apiErrors.forbidden('Invalid invite code');
|
||||
}
|
||||
|
||||
// Constant-time comparison
|
||||
const { timingSafeEqual } = await import('crypto');
|
||||
const validBuffer = Buffer.from(validInviteCode);
|
||||
const providedBuffer = Buffer.from(String(inviteCode));
|
||||
|
||||
// Ensure same length for comparison (prevents length-based timing leak)
|
||||
const isValidLength = validBuffer.length === providedBuffer.length;
|
||||
const compareBuffer = isValidLength ? providedBuffer : validBuffer;
|
||||
const isValidCode = isValidLength && timingSafeEqual(validBuffer, compareBuffer);
|
||||
|
||||
if (!isValidCode) {
|
||||
return apiErrors.forbidden('Invalid invite code');
|
||||
}
|
||||
}
|
||||
|
||||
if (!password || typeof password !== 'string' || password.length < 8 || password.length > 128) {
|
||||
return apiErrors.badRequest('Password must be between 8 and 128 characters');
|
||||
}
|
||||
|
||||
// Check if email already exists
|
||||
const existingUser = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
return apiErrors.conflict('An account with this email already exists');
|
||||
}
|
||||
|
||||
// Hash password
|
||||
const hashedPassword = await bcrypt.hash(password, 12);
|
||||
|
||||
// If SMTP is not configured, auto-verify the email so users aren't locked out
|
||||
const emailVerificationRequired = isEmailVerificationEnabled();
|
||||
|
||||
// Create user
|
||||
const user = await db.user.create({
|
||||
data: {
|
||||
name: name.trim(),
|
||||
email: normalizedEmail,
|
||||
password: hashedPassword,
|
||||
emailVerified: emailVerificationRequired ? null : new Date(),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (validatedInvitationToken) {
|
||||
const result = await acceptInvitationTokenForUser({
|
||||
token: validatedInvitationToken,
|
||||
userId: user.id,
|
||||
email: normalizedEmail,
|
||||
});
|
||||
if (result !== 'accepted') {
|
||||
await db.user.delete({ where: { id: user.id } });
|
||||
return apiErrors.conflict(
|
||||
'Invitation could not be accepted. Please request a new invitation.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Send verification email if SMTP is configured
|
||||
if (emailVerificationRequired) {
|
||||
const verificationToken = await createVerificationToken(normalizedEmail);
|
||||
await sendVerificationEmail(normalizedEmail, verificationToken);
|
||||
}
|
||||
|
||||
const message = emailVerificationRequired
|
||||
? 'Account created. Please check your email to verify your address before signing in.'
|
||||
: 'Account created successfully';
|
||||
|
||||
const response = successResponse({ message, user, emailVerificationRequired }, 201);
|
||||
|
||||
// Add rate limit headers to successful response
|
||||
const headers = rateLimitHeaders(rateLimit, RATE_LIMIT_CONFIGS.register.maxRequests);
|
||||
Object.entries(headers).forEach(([key, value]) => {
|
||||
response.headers.set(key, value);
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Registration error:', error);
|
||||
return apiErrors.internalError('Failed to create account');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,54 +2,63 @@ import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { checkRateLimit, getClientIp } from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { createVerificationToken, isEmailVerificationEnabled, sendVerificationEmail } from '@/lib/email-verification';
|
||||
import {
|
||||
createVerificationToken,
|
||||
isEmailVerificationEnabled,
|
||||
sendVerificationEmail,
|
||||
} from '@/lib/email-verification';
|
||||
import { logError } from '@/lib/logger';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
if (!isEmailVerificationEnabled()) {
|
||||
return apiErrors.badRequest('Email verification is not enabled');
|
||||
}
|
||||
|
||||
// Rate-limit by IP to prevent abuse
|
||||
const clientIp = getClientIp(request);
|
||||
const rateLimitResult = await checkRateLimit(`resend-verification:${clientIp}`, 'resend-verification');
|
||||
if (!rateLimitResult.allowed) {
|
||||
return apiErrors.rateLimited('Too many requests. Please try again later.');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { email } = body;
|
||||
|
||||
if (!email || typeof email !== 'string' || email.length > 254 || !email.includes('@')) {
|
||||
return apiErrors.badRequest('Valid email is required');
|
||||
}
|
||||
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.badRequest('Valid email is required');
|
||||
}
|
||||
|
||||
// Look up user — return a generic success regardless of whether the email
|
||||
// exists to avoid user enumeration
|
||||
const user = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
select: { id: true, emailVerified: true },
|
||||
});
|
||||
|
||||
if (user && !user.emailVerified) {
|
||||
const token = await createVerificationToken(normalizedEmail);
|
||||
await sendVerificationEmail(normalizedEmail, token);
|
||||
}
|
||||
|
||||
return withCacheControl(
|
||||
successResponse({ message: 'If that email has an unverified account, a new verification link has been sent.' }),
|
||||
'private, no-store'
|
||||
);
|
||||
} catch (err) {
|
||||
logError('Resend verification error:', err);
|
||||
return apiErrors.internalError('Failed to resend verification email');
|
||||
try {
|
||||
if (!isEmailVerificationEnabled()) {
|
||||
return apiErrors.badRequest('Email verification is not enabled');
|
||||
}
|
||||
|
||||
// Rate-limit by IP to prevent abuse
|
||||
const clientIp = getClientIp(request);
|
||||
const rateLimitResult = await checkRateLimit(
|
||||
`resend-verification:${clientIp}`,
|
||||
'resend-verification'
|
||||
);
|
||||
if (!rateLimitResult.allowed) {
|
||||
return apiErrors.rateLimited('Too many requests. Please try again later.');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { email } = body;
|
||||
|
||||
if (!email || typeof email !== 'string' || email.length > 254 || !email.includes('@')) {
|
||||
return apiErrors.badRequest('Valid email is required');
|
||||
}
|
||||
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.badRequest('Valid email is required');
|
||||
}
|
||||
|
||||
// Look up user — return a generic success regardless of whether the email
|
||||
// exists to avoid user enumeration
|
||||
const user = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
select: { id: true, emailVerified: true },
|
||||
});
|
||||
|
||||
if (user && !user.emailVerified) {
|
||||
const token = await createVerificationToken(normalizedEmail);
|
||||
await sendVerificationEmail(normalizedEmail, token);
|
||||
}
|
||||
|
||||
return withCacheControl(
|
||||
successResponse({
|
||||
message: 'If that email has an unverified account, a new verification link has been sent.',
|
||||
}),
|
||||
'private, no-store'
|
||||
);
|
||||
} catch (err) {
|
||||
logError('Resend verification error:', err);
|
||||
return apiErrors.internalError('Failed to resend verification email');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,26 +7,26 @@ import { logError } from '@/lib/logger';
|
||||
const TOKEN_REGEX = /^[0-9a-f]{64}$/;
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// Rate-limit by IP to prevent token enumeration attacks.
|
||||
const limited = await rateLimit(request, 'verify-email');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
// Rate-limit by IP to prevent token enumeration attacks.
|
||||
const limited = await rateLimit(request, 'verify-email');
|
||||
if (limited) return limited;
|
||||
|
||||
const token = request.nextUrl.searchParams.get('token');
|
||||
const token = request.nextUrl.searchParams.get('token');
|
||||
|
||||
if (!token || !TOKEN_REGEX.test(token.trim())) {
|
||||
return NextResponse.redirect(new URL('/login?error=InvalidVerificationToken', request.url));
|
||||
}
|
||||
|
||||
const email = await consumeVerificationToken(token.trim());
|
||||
|
||||
if (!email) {
|
||||
return NextResponse.redirect(new URL('/login?error=InvalidVerificationToken', request.url));
|
||||
}
|
||||
|
||||
return NextResponse.redirect(new URL('/login?verified=true', request.url));
|
||||
} catch (err) {
|
||||
logError('Email verification error:', err);
|
||||
return NextResponse.redirect(new URL('/login?error=VerificationFailed', request.url));
|
||||
if (!token || !TOKEN_REGEX.test(token.trim())) {
|
||||
return NextResponse.redirect(new URL('/login?error=InvalidVerificationToken', request.url));
|
||||
}
|
||||
|
||||
const email = await consumeVerificationToken(token.trim());
|
||||
|
||||
if (!email) {
|
||||
return NextResponse.redirect(new URL('/login?error=InvalidVerificationToken', request.url));
|
||||
}
|
||||
|
||||
return NextResponse.redirect(new URL('/login?verified=true', request.url));
|
||||
} catch (err) {
|
||||
logError('Email verification error:', err);
|
||||
return NextResponse.redirect(new URL('/login?error=VerificationFailed', request.url));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,8 @@ export async function GET() {
|
||||
cancelAt: billing.subscription.cancelAt?.toISOString() ?? null,
|
||||
trialEndsAt: billing.subscription.trialEndsAt?.toISOString() ?? null,
|
||||
billingAccessEndedAt: billing.subscription.billingAccessEndedAt?.toISOString() ?? null,
|
||||
storageCleanupEligibleAt: billing.subscription.storageCleanupEligibleAt?.toISOString() ?? null,
|
||||
storageCleanupEligibleAt:
|
||||
billing.subscription.storageCleanupEligibleAt?.toISOString() ?? null,
|
||||
},
|
||||
workspaceCreation: billing.workspaceCreation,
|
||||
});
|
||||
|
||||
@@ -18,349 +18,374 @@ 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;
|
||||
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,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
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');
|
||||
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;
|
||||
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 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,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
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, { intent: 'manage' });
|
||||
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');
|
||||
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, { intent: 'manage' });
|
||||
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;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { commentId } = await params;
|
||||
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 } },
|
||||
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');
|
||||
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, { intent: 'manage' }) : 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;
|
||||
}
|
||||
}
|
||||
|
||||
const project = comment.version.video.project;
|
||||
const userId = session?.user?.id ?? null;
|
||||
const isAuthor = !!userId && comment.authorId === userId;
|
||||
if (!canDelete) {
|
||||
return apiErrors.forbidden('You do not have permission to delete this comment');
|
||||
}
|
||||
|
||||
// Project owners/admins and workspace admins can delete any comment
|
||||
const access = userId ? await checkProjectAccess(project, userId, { intent: 'manage' }) : null;
|
||||
const isPrivilegedUser = !!access?.canEdit;
|
||||
// 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);
|
||||
}
|
||||
|
||||
let canDelete = isAuthor || isPrivilegedUser;
|
||||
if (!canDelete && !userId) {
|
||||
const guestIdentityId = getGuestIdentityFromRequest(request);
|
||||
const isGuestAuthor = !comment.authorId
|
||||
&& !!comment.guestIdentityId
|
||||
&& guestIdentityId === comment.guestIdentityId;
|
||||
await db.comment.delete({ where: { id: commentId } });
|
||||
|
||||
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) => {
|
||||
// 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;
|
||||
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;
|
||||
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)))];
|
||||
})
|
||||
.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);
|
||||
}
|
||||
});
|
||||
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');
|
||||
}
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
+37
-22
@@ -35,9 +35,11 @@ export async function POST(request: NextRequest) {
|
||||
const legacyScreenshotUrl = body.screenshotUrl?.trim() ?? null;
|
||||
const screenshotUrls = Array.isArray(body.screenshotUrls)
|
||||
? body.screenshotUrls
|
||||
.map((url) => (typeof url === 'string' ? url.trim() : ''))
|
||||
.filter((url) => !!url)
|
||||
: (legacyScreenshotUrl ? [legacyScreenshotUrl] : []);
|
||||
.map((url) => (typeof url === 'string' ? url.trim() : ''))
|
||||
.filter((url) => !!url)
|
||||
: legacyScreenshotUrl
|
||||
? [legacyScreenshotUrl]
|
||||
: [];
|
||||
|
||||
if (type !== FeedbackEntryType.FEEDBACK && type !== FeedbackEntryType.REVIEW) {
|
||||
return apiErrors.badRequest('Invalid entry type');
|
||||
@@ -70,7 +72,11 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
if (type === FeedbackEntryType.REVIEW) {
|
||||
if (!Number.isInteger(body.rating) || (body.rating as number) < 1 || (body.rating as number) > 5) {
|
||||
if (
|
||||
!Number.isInteger(body.rating) ||
|
||||
(body.rating as number) < 1 ||
|
||||
(body.rating as number) > 5
|
||||
) {
|
||||
return apiErrors.badRequest('Review rating must be between 1 and 5');
|
||||
}
|
||||
}
|
||||
@@ -83,17 +89,19 @@ export async function POST(request: NextRequest) {
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
type,
|
||||
category: type === FeedbackEntryType.FEEDBACK ? (body.category as FeedbackCategory) : null,
|
||||
category:
|
||||
type === FeedbackEntryType.FEEDBACK ? (body.category as FeedbackCategory) : null,
|
||||
title,
|
||||
message,
|
||||
screenshotUrl: type === FeedbackEntryType.FEEDBACK ? (screenshotUrls[0] ?? null) : null,
|
||||
rating: type === FeedbackEntryType.REVIEW ? body.rating : null,
|
||||
allowShowcase: type === FeedbackEntryType.REVIEW ? !!body.allowShowcase : false,
|
||||
screenshots: type === FeedbackEntryType.FEEDBACK
|
||||
? {
|
||||
create: screenshotUrls.map((url) => ({ url })),
|
||||
}
|
||||
: undefined,
|
||||
screenshots:
|
||||
type === FeedbackEntryType.FEEDBACK
|
||||
? {
|
||||
create: screenshotUrls.map((url) => ({ url })),
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
@@ -112,7 +120,8 @@ export async function POST(request: NextRequest) {
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
type,
|
||||
category: type === FeedbackEntryType.FEEDBACK ? (body.category as FeedbackCategory) : null,
|
||||
category:
|
||||
type === FeedbackEntryType.FEEDBACK ? (body.category as FeedbackCategory) : null,
|
||||
title,
|
||||
message,
|
||||
screenshotUrl: type === FeedbackEntryType.FEEDBACK ? (screenshotUrls[0] ?? null) : null,
|
||||
@@ -128,19 +137,25 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
if (usedLegacyCreatePath && type === FeedbackEntryType.FEEDBACK && screenshotUrls.length > 1) {
|
||||
const screenshotDelegate = (db as unknown as {
|
||||
userFeedbackScreenshot?: {
|
||||
createMany: (args: { data: Array<{ feedbackId: string; url: string }> }) => Promise<unknown>;
|
||||
};
|
||||
}).userFeedbackScreenshot;
|
||||
const screenshotDelegate = (
|
||||
db as unknown as {
|
||||
userFeedbackScreenshot?: {
|
||||
createMany: (args: {
|
||||
data: Array<{ feedbackId: string; url: string }>;
|
||||
}) => Promise<unknown>;
|
||||
};
|
||||
}
|
||||
).userFeedbackScreenshot;
|
||||
|
||||
if (screenshotDelegate) {
|
||||
await screenshotDelegate.createMany({
|
||||
data: screenshotUrls.map((url) => ({
|
||||
feedbackId: entry.id,
|
||||
url,
|
||||
})),
|
||||
}).catch(() => undefined);
|
||||
await screenshotDelegate
|
||||
.createMany({
|
||||
data: screenshotUrls.map((url) => ({
|
||||
feedbackId: entry.id,
|
||||
url,
|
||||
})),
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import { r2Client, R2_BUCKET_NAME } from '@/lib/r2';
|
||||
import { logError } from '@/lib/logger';
|
||||
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
|
||||
const MAX_MULTIPART_BODY_SIZE = MAX_FILE_SIZE + (512 * 1024); // file + multipart overhead
|
||||
const MAX_MULTIPART_BODY_SIZE = MAX_FILE_SIZE + 512 * 1024; // file + multipart overhead
|
||||
|
||||
// POST /api/feedback/upload
|
||||
export async function POST(request: NextRequest) {
|
||||
|
||||
@@ -4,24 +4,24 @@ import { apiErrors, successResponse } from '@/lib/api-response';
|
||||
import { checkRateLimit, rateLimitHeaders, RATE_LIMIT_CONFIGS } from '@/lib/rate-limit';
|
||||
|
||||
export async function POST() {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const cfg = RATE_LIMIT_CONFIGS['onboarding-complete'];
|
||||
const rl = await checkRateLimit(session.user.id, 'onboarding-complete', cfg);
|
||||
if (!rl.allowed) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Too many requests. Please try again later.' }),
|
||||
{ status: 429, headers: { 'Content-Type': 'application/json', ...rateLimitHeaders(rl, cfg.maxRequests) } }
|
||||
);
|
||||
}
|
||||
|
||||
await db.user.update({
|
||||
where: { id: session.user.id },
|
||||
data: { onboardingCompletedAt: new Date() },
|
||||
const cfg = RATE_LIMIT_CONFIGS['onboarding-complete'];
|
||||
const rl = await checkRateLimit(session.user.id, 'onboarding-complete', cfg);
|
||||
if (!rl.allowed) {
|
||||
return new Response(JSON.stringify({ error: 'Too many requests. Please try again later.' }), {
|
||||
status: 429,
|
||||
headers: { 'Content-Type': 'application/json', ...rateLimitHeaders(rl, cfg.maxRequests) },
|
||||
});
|
||||
}
|
||||
|
||||
return successResponse({ completed: true });
|
||||
await db.user.update({
|
||||
where: { id: session.user.id },
|
||||
data: { onboardingCompletedAt: new Date() },
|
||||
});
|
||||
|
||||
return successResponse({ completed: true });
|
||||
}
|
||||
|
||||
@@ -10,114 +10,114 @@ type RouteParams = { params: Promise<{ projectId: string; memberId: string }> };
|
||||
|
||||
// PATCH /api/projects/[projectId]/members/[memberId] - Update member role
|
||||
export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'manage-member');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'manage-member');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId, memberId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId, memberId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { role } = body;
|
||||
|
||||
const validRoles = ['ADMIN', 'COMMENTATOR'];
|
||||
if (!validRoles.includes(role)) {
|
||||
return apiErrors.badRequest('Invalid role. Must be ADMIN or COMMENTATOR.');
|
||||
}
|
||||
|
||||
const member = await db.projectMember.findFirst({
|
||||
where: { id: memberId, projectId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!member) {
|
||||
return apiErrors.notFound('Member');
|
||||
}
|
||||
|
||||
const updatedMember = await db.projectMember.update({
|
||||
where: { id: member.id },
|
||||
data: { role: role as ProjectMemberRole },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, image: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(updatedMember);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating member role:', error);
|
||||
return apiErrors.internalError('Failed to update member role');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { role } = body;
|
||||
|
||||
const validRoles = ['ADMIN', 'COMMENTATOR'];
|
||||
if (!validRoles.includes(role)) {
|
||||
return apiErrors.badRequest('Invalid role. Must be ADMIN or COMMENTATOR.');
|
||||
}
|
||||
|
||||
const member = await db.projectMember.findFirst({
|
||||
where: { id: memberId, projectId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!member) {
|
||||
return apiErrors.notFound('Member');
|
||||
}
|
||||
|
||||
const updatedMember = await db.projectMember.update({
|
||||
where: { id: member.id },
|
||||
data: { role: role as ProjectMemberRole },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, image: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(updatedMember);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating member role:', error);
|
||||
return apiErrors.internalError('Failed to update member role');
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/projects/[projectId]/members/[memberId] - Remove member
|
||||
export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'manage-member');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'manage-member');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId, memberId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId, memberId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
const memberToRemove = await db.projectMember.findFirst({
|
||||
where: { id: memberId, projectId },
|
||||
select: { id: true, userId: true },
|
||||
});
|
||||
|
||||
if (!memberToRemove) {
|
||||
return apiErrors.notFound('Member');
|
||||
}
|
||||
|
||||
const isSelf = memberToRemove.userId === session.user.id;
|
||||
|
||||
if ((!access.canEdit || (!isOwner && !isAdmin)) && !isSelf) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
await db.projectMember.delete({ where: { id: memberToRemove.id } });
|
||||
|
||||
const response = successResponse({ message: 'Member removed' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error removing member:', error);
|
||||
return apiErrors.internalError('Failed to remove member');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
const memberToRemove = await db.projectMember.findFirst({
|
||||
where: { id: memberId, projectId },
|
||||
select: { id: true, userId: true },
|
||||
});
|
||||
|
||||
if (!memberToRemove) {
|
||||
return apiErrors.notFound('Member');
|
||||
}
|
||||
|
||||
const isSelf = memberToRemove.userId === session.user.id;
|
||||
|
||||
if ((!access.canEdit || (!isOwner && !isAdmin)) && !isSelf) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
await db.projectMember.delete({ where: { id: memberToRemove.id } });
|
||||
|
||||
const response = successResponse({ message: 'Member removed' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error removing member:', error);
|
||||
return apiErrors.internalError('Failed to remove member');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,11 @@ import { db } from '@/lib/db';
|
||||
import { auth, checkProjectAccess } from '@/lib/auth';
|
||||
import { InvitationRole, ProjectMemberRole } from '@prisma/client';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { buildInvitationUrl, createOrRefreshInvitation, sendInvitationEmail } from '@/lib/invitations';
|
||||
import {
|
||||
buildInvitationUrl,
|
||||
createOrRefreshInvitation,
|
||||
sendInvitationEmail,
|
||||
} from '@/lib/invitations';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { logError } from '@/lib/logger';
|
||||
|
||||
@@ -11,169 +15,169 @@ type RouteParams = { params: Promise<{ projectId: string }> };
|
||||
|
||||
// GET /api/projects/[projectId]/members - List members
|
||||
export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
try {
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
include: {
|
||||
members: { where: { userId: session.user.id } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id);
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isMember = project.members.length > 0;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!access.hasAccess || (!isOwner && !isMember)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const canViewPendingInvitations = isOwner || isAdmin;
|
||||
const [members, owner, pendingInvitations] = await Promise.all([
|
||||
db.projectMember.findMany({
|
||||
where: { projectId },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true, image: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}),
|
||||
db.user.findUnique({
|
||||
where: { id: project.ownerId },
|
||||
select: { id: true, name: true, email: true, image: true },
|
||||
}),
|
||||
canViewPendingInvitations
|
||||
? db.invitation.findMany({
|
||||
where: {
|
||||
projectId,
|
||||
scope: 'PROJECT',
|
||||
status: 'PENDING',
|
||||
expiresAt: { gt: now },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
expiresAt: true,
|
||||
invitedBy: {
|
||||
select: { id: true, name: true, email: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
|
||||
const response = successResponse({ members, owner, pendingInvitations });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error fetching project members:', error);
|
||||
return apiErrors.internalError('Failed to fetch members');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
include: {
|
||||
members: { where: { userId: session.user.id } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id);
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isMember = project.members.length > 0;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!access.hasAccess || (!isOwner && !isMember)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const canViewPendingInvitations = isOwner || isAdmin;
|
||||
const [members, owner, pendingInvitations] = await Promise.all([
|
||||
db.projectMember.findMany({
|
||||
where: { projectId },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true, image: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}),
|
||||
db.user.findUnique({
|
||||
where: { id: project.ownerId },
|
||||
select: { id: true, name: true, email: true, image: true },
|
||||
}),
|
||||
canViewPendingInvitations
|
||||
? db.invitation.findMany({
|
||||
where: {
|
||||
projectId,
|
||||
scope: 'PROJECT',
|
||||
status: 'PENDING',
|
||||
expiresAt: { gt: now },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
expiresAt: true,
|
||||
invitedBy: {
|
||||
select: { id: true, name: true, email: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
|
||||
const response = successResponse({ members, owner, pendingInvitations });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error fetching project members:', error);
|
||||
return apiErrors.internalError('Failed to fetch members');
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/projects/[projectId]/members - Invite a member
|
||||
export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'invite-member');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'invite-member');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
// Check if user is owner or admin
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Only project owners and admins can invite members');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { email, role } = body;
|
||||
|
||||
if (!email || typeof email !== 'string') {
|
||||
return apiErrors.badRequest('Email is required');
|
||||
}
|
||||
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.validationError('Invalid email format');
|
||||
}
|
||||
|
||||
// Validate role
|
||||
const validRoles = ['ADMIN', 'COMMENTATOR'];
|
||||
const memberRole = validRoles.includes(role) ? role : 'COMMENTATOR';
|
||||
|
||||
// If this email belongs to an existing user, validate owner/member conflicts.
|
||||
const userToInvite = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (userToInvite?.id === project.ownerId) {
|
||||
return apiErrors.badRequest('Cannot invite the project owner as a member');
|
||||
}
|
||||
|
||||
if (userToInvite) {
|
||||
const existingMember = await db.projectMember.findUnique({
|
||||
where: { projectId_userId: { projectId, userId: userToInvite.id } },
|
||||
});
|
||||
|
||||
if (existingMember) {
|
||||
return apiErrors.conflict('User is already a member of this project');
|
||||
}
|
||||
}
|
||||
|
||||
const invitation = await createOrRefreshInvitation({
|
||||
email: normalizedEmail,
|
||||
scope: 'PROJECT',
|
||||
role: memberRole as InvitationRole,
|
||||
invitedById: session.user.id,
|
||||
projectId,
|
||||
});
|
||||
|
||||
const invitationUrl = buildInvitationUrl(invitation.token);
|
||||
void sendInvitationEmail({
|
||||
to: normalizedEmail,
|
||||
inviterName: session.user.name || 'A team member',
|
||||
role: invitation.role,
|
||||
scope: invitation.scope,
|
||||
targetName: project.name,
|
||||
invitationUrl,
|
||||
});
|
||||
|
||||
const response = successResponse({ message: 'Invitation email sent.' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error inviting project member:', error);
|
||||
return apiErrors.internalError('Failed to invite member');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
// Check if user is owner or admin
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Only project owners and admins can invite members');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { email, role } = body;
|
||||
|
||||
if (!email || typeof email !== 'string') {
|
||||
return apiErrors.badRequest('Email is required');
|
||||
}
|
||||
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.validationError('Invalid email format');
|
||||
}
|
||||
|
||||
// Validate role
|
||||
const validRoles = ['ADMIN', 'COMMENTATOR'];
|
||||
const memberRole = validRoles.includes(role) ? role : 'COMMENTATOR';
|
||||
|
||||
// If this email belongs to an existing user, validate owner/member conflicts.
|
||||
const userToInvite = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (userToInvite?.id === project.ownerId) {
|
||||
return apiErrors.badRequest('Cannot invite the project owner as a member');
|
||||
}
|
||||
|
||||
if (userToInvite) {
|
||||
const existingMember = await db.projectMember.findUnique({
|
||||
where: { projectId_userId: { projectId, userId: userToInvite.id } },
|
||||
});
|
||||
|
||||
if (existingMember) {
|
||||
return apiErrors.conflict('User is already a member of this project');
|
||||
}
|
||||
}
|
||||
|
||||
const invitation = await createOrRefreshInvitation({
|
||||
email: normalizedEmail,
|
||||
scope: 'PROJECT',
|
||||
role: memberRole as InvitationRole,
|
||||
invitedById: session.user.id,
|
||||
projectId,
|
||||
});
|
||||
|
||||
const invitationUrl = buildInvitationUrl(invitation.token);
|
||||
void sendInvitationEmail({
|
||||
to: normalizedEmail,
|
||||
inviterName: session.user.name || 'A team member',
|
||||
role: invitation.role,
|
||||
scope: invitation.scope,
|
||||
targetName: project.name,
|
||||
invitationUrl,
|
||||
});
|
||||
|
||||
const response = successResponse({ message: 'Invitation email sent.' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error inviting project member:', error);
|
||||
return apiErrors.internalError('Failed to invite member');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,230 +12,230 @@ type RouteParams = { params: Promise<{ projectId: string }> };
|
||||
|
||||
// GET /api/projects/[projectId] - Get a single project
|
||||
export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
const MAX_LIMIT = 100;
|
||||
const MAX_OFFSET = 10000;
|
||||
try {
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
const MAX_LIMIT = 100;
|
||||
const MAX_OFFSET = 10000;
|
||||
|
||||
// Parse pagination params
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const limitParam = searchParams.get('limit');
|
||||
const offsetParam = searchParams.get('offset');
|
||||
// Parse pagination params
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const limitParam = searchParams.get('limit');
|
||||
const offsetParam = searchParams.get('offset');
|
||||
|
||||
const limitRaw = limitParam === null ? 20 : Number(limitParam);
|
||||
if (!Number.isSafeInteger(limitRaw) || limitRaw < 1 || limitRaw > MAX_LIMIT) {
|
||||
return apiErrors.badRequest('Invalid limit. Must be a positive integer between 1 and 100.');
|
||||
}
|
||||
|
||||
const offset = offsetParam === null ? 0 : Number(offsetParam);
|
||||
if (!Number.isSafeInteger(offset) || offset < 0 || offset > MAX_OFFSET) {
|
||||
return apiErrors.badRequest('Invalid offset. Must be a non-negative integer up to 10000.');
|
||||
}
|
||||
|
||||
const limit = limitRaw;
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
members: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true, image: true } },
|
||||
},
|
||||
},
|
||||
videos: {
|
||||
orderBy: { position: 'asc' },
|
||||
skip: offset,
|
||||
take: limit,
|
||||
include: {
|
||||
versions: {
|
||||
where: { isActive: true },
|
||||
orderBy: { versionNumber: 'desc' },
|
||||
take: 1,
|
||||
select: {
|
||||
id: true,
|
||||
thumbnailUrl: true,
|
||||
duration: true,
|
||||
versionNumber: true,
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
},
|
||||
_count: { select: { versions: true } },
|
||||
},
|
||||
},
|
||||
_count: { select: { videos: true, members: true, shareLinks: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session?.user?.id);
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const response = successResponse(project);
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error fetching project:', error);
|
||||
return apiErrors.internalError('Failed to fetch project');
|
||||
const limitRaw = limitParam === null ? 20 : Number(limitParam);
|
||||
if (!Number.isSafeInteger(limitRaw) || limitRaw < 1 || limitRaw > MAX_LIMIT) {
|
||||
return apiErrors.badRequest('Invalid limit. Must be a positive integer between 1 and 100.');
|
||||
}
|
||||
|
||||
const offset = offsetParam === null ? 0 : Number(offsetParam);
|
||||
if (!Number.isSafeInteger(offset) || offset < 0 || offset > MAX_OFFSET) {
|
||||
return apiErrors.badRequest('Invalid offset. Must be a non-negative integer up to 10000.');
|
||||
}
|
||||
|
||||
const limit = limitRaw;
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
members: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true, image: true } },
|
||||
},
|
||||
},
|
||||
videos: {
|
||||
orderBy: { position: 'asc' },
|
||||
skip: offset,
|
||||
take: limit,
|
||||
include: {
|
||||
versions: {
|
||||
where: { isActive: true },
|
||||
orderBy: { versionNumber: 'desc' },
|
||||
take: 1,
|
||||
select: {
|
||||
id: true,
|
||||
thumbnailUrl: true,
|
||||
duration: true,
|
||||
versionNumber: true,
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
},
|
||||
_count: { select: { versions: true } },
|
||||
},
|
||||
},
|
||||
_count: { select: { videos: true, members: true, shareLinks: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session?.user?.id);
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const response = successResponse(project);
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error fetching project:', error);
|
||||
return apiErrors.internalError('Failed to fetch project');
|
||||
}
|
||||
}
|
||||
|
||||
// PATCH /api/projects/[projectId] - Update a project
|
||||
export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const projectAccessTarget = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
const access = projectAccessTarget
|
||||
? await checkProjectAccess(projectAccessTarget, session.user.id, { intent: 'manage' })
|
||||
: null;
|
||||
if (!access?.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, description, visibility } = body;
|
||||
|
||||
if (name !== undefined) {
|
||||
if (typeof name !== 'string' || name.trim().length === 0) {
|
||||
return apiErrors.badRequest('Name must be a non-empty string');
|
||||
}
|
||||
if (name.trim().length > 100) {
|
||||
return apiErrors.badRequest('Name must be 100 characters or fewer');
|
||||
}
|
||||
}
|
||||
if (description !== undefined && description !== null) {
|
||||
if (typeof description !== 'string') {
|
||||
return apiErrors.badRequest('Description must be a string');
|
||||
}
|
||||
if (description.trim().length > 1000) {
|
||||
return apiErrors.badRequest('Description must be 1000 characters or fewer');
|
||||
}
|
||||
}
|
||||
|
||||
const VALID_VISIBILITY = ['PRIVATE', 'INVITE', 'PUBLIC'] as const;
|
||||
if (visibility !== undefined && !VALID_VISIBILITY.includes(visibility)) {
|
||||
return apiErrors.badRequest('Invalid visibility value');
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (name !== undefined) updateData.name = name.trim();
|
||||
if (description !== undefined) updateData.description = description?.trim() || null;
|
||||
if (visibility !== undefined) updateData.visibility = visibility;
|
||||
|
||||
const project = await db.project.update({
|
||||
where: { id: projectId },
|
||||
data: updateData,
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
_count: { select: { videos: true, members: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(project);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating project:', error);
|
||||
return apiErrors.internalError('Failed to update project');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const projectAccessTarget = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
const access = projectAccessTarget
|
||||
? await checkProjectAccess(projectAccessTarget, session.user.id, { intent: 'manage' })
|
||||
: null;
|
||||
if (!access?.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, description, visibility } = body;
|
||||
|
||||
if (name !== undefined) {
|
||||
if (typeof name !== 'string' || name.trim().length === 0) {
|
||||
return apiErrors.badRequest('Name must be a non-empty string');
|
||||
}
|
||||
if (name.trim().length > 100) {
|
||||
return apiErrors.badRequest('Name must be 100 characters or fewer');
|
||||
}
|
||||
}
|
||||
if (description !== undefined && description !== null) {
|
||||
if (typeof description !== 'string') {
|
||||
return apiErrors.badRequest('Description must be a string');
|
||||
}
|
||||
if (description.trim().length > 1000) {
|
||||
return apiErrors.badRequest('Description must be 1000 characters or fewer');
|
||||
}
|
||||
}
|
||||
|
||||
const VALID_VISIBILITY = ['PRIVATE', 'INVITE', 'PUBLIC'] as const;
|
||||
if (visibility !== undefined && !VALID_VISIBILITY.includes(visibility)) {
|
||||
return apiErrors.badRequest('Invalid visibility value');
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (name !== undefined) updateData.name = name.trim();
|
||||
if (description !== undefined) updateData.description = description?.trim() || null;
|
||||
if (visibility !== undefined) updateData.visibility = visibility;
|
||||
|
||||
const project = await db.project.update({
|
||||
where: { id: projectId },
|
||||
data: updateData,
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
_count: { select: { videos: true, members: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(project);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating project:', error);
|
||||
return apiErrors.internalError('Failed to update project');
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/projects/[projectId] - Delete a project
|
||||
export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'delete' });
|
||||
if (!access.canDelete) {
|
||||
return apiErrors.forbidden('Only the project owner can delete it');
|
||||
}
|
||||
|
||||
const [projectVersionRefs, projectAssetRefs, mediaUrls] = await Promise.all([
|
||||
db.videoVersion.findMany({
|
||||
where: {
|
||||
video: { projectId },
|
||||
},
|
||||
select: {
|
||||
providerId: true,
|
||||
videoId: true,
|
||||
},
|
||||
}),
|
||||
db.videoAsset.findMany({
|
||||
where: {
|
||||
video: { projectId },
|
||||
provider: 'BUNNY',
|
||||
providerVideoId: { not: null },
|
||||
},
|
||||
select: {
|
||||
providerVideoId: true,
|
||||
},
|
||||
}),
|
||||
collectProjectMediaUrls(projectId),
|
||||
]);
|
||||
|
||||
const bunnyRefs = [
|
||||
...projectVersionRefs,
|
||||
...projectAssetRefs.map((asset) => ({
|
||||
providerId: 'bunny',
|
||||
videoId: asset.providerVideoId as string,
|
||||
})),
|
||||
];
|
||||
|
||||
await db.project.delete({ where: { id: projectId } });
|
||||
|
||||
const [bunnyCleanupResult, r2CleanupResult] = await Promise.all([
|
||||
cleanupBunnyStreamVideosBestEffort(bunnyRefs),
|
||||
deleteMediaFilesBestEffort(mediaUrls),
|
||||
]);
|
||||
|
||||
const cleanupInput = {
|
||||
bunny: bunnyCleanupResult,
|
||||
r2: r2CleanupResult,
|
||||
};
|
||||
const cleanupWarnings = buildCleanupWarnings(cleanupInput);
|
||||
if (cleanupWarnings) {
|
||||
logCleanupWarnings({ entityType: 'project', entityId: projectId }, cleanupInput);
|
||||
}
|
||||
|
||||
const response = successResponse({
|
||||
message: 'Project deleted',
|
||||
...(cleanupWarnings ? { cleanupWarnings } : {}),
|
||||
});
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error deleting project:', error);
|
||||
return apiErrors.internalError('Failed to delete project');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'delete' });
|
||||
if (!access.canDelete) {
|
||||
return apiErrors.forbidden('Only the project owner can delete it');
|
||||
}
|
||||
|
||||
const [projectVersionRefs, projectAssetRefs, mediaUrls] = await Promise.all([
|
||||
db.videoVersion.findMany({
|
||||
where: {
|
||||
video: { projectId },
|
||||
},
|
||||
select: {
|
||||
providerId: true,
|
||||
videoId: true,
|
||||
},
|
||||
}),
|
||||
db.videoAsset.findMany({
|
||||
where: {
|
||||
video: { projectId },
|
||||
provider: 'BUNNY',
|
||||
providerVideoId: { not: null },
|
||||
},
|
||||
select: {
|
||||
providerVideoId: true,
|
||||
},
|
||||
}),
|
||||
collectProjectMediaUrls(projectId),
|
||||
]);
|
||||
|
||||
const bunnyRefs = [
|
||||
...projectVersionRefs,
|
||||
...projectAssetRefs.map((asset) => ({
|
||||
providerId: 'bunny',
|
||||
videoId: asset.providerVideoId as string,
|
||||
})),
|
||||
];
|
||||
|
||||
await db.project.delete({ where: { id: projectId } });
|
||||
|
||||
const [bunnyCleanupResult, r2CleanupResult] = await Promise.all([
|
||||
cleanupBunnyStreamVideosBestEffort(bunnyRefs),
|
||||
deleteMediaFilesBestEffort(mediaUrls),
|
||||
]);
|
||||
|
||||
const cleanupInput = {
|
||||
bunny: bunnyCleanupResult,
|
||||
r2: r2CleanupResult,
|
||||
};
|
||||
const cleanupWarnings = buildCleanupWarnings(cleanupInput);
|
||||
if (cleanupWarnings) {
|
||||
logCleanupWarnings({ entityType: 'project', entityId: projectId }, cleanupInput);
|
||||
}
|
||||
|
||||
const response = successResponse({
|
||||
message: 'Project deleted',
|
||||
...(cleanupWarnings ? { cleanupWarnings } : {}),
|
||||
});
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error deleting project:', error);
|
||||
return apiErrors.internalError('Failed to delete project');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,114 +9,114 @@ type RouteParams = { params: Promise<{ projectId: string; tagId: string }> };
|
||||
|
||||
// PATCH /api/projects/[projectId]/tags/[tagId] - Update a tag
|
||||
export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId, tagId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId, tagId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
// Verify tag belongs to this project
|
||||
const existingTag = await db.commentTag.findUnique({
|
||||
where: { id: tagId },
|
||||
});
|
||||
if (!existingTag || existingTag.projectId !== projectId) {
|
||||
return apiErrors.notFound('Tag');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, color, position } = body;
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (name !== undefined) {
|
||||
if (!name.trim()) {
|
||||
return apiErrors.badRequest('Name cannot be empty');
|
||||
}
|
||||
updateData.name = name.trim();
|
||||
}
|
||||
if (color !== undefined) {
|
||||
if (!/^#[0-9A-Fa-f]{6}$/.test(color)) {
|
||||
return apiErrors.badRequest('Invalid color format');
|
||||
}
|
||||
updateData.color = color.toUpperCase();
|
||||
}
|
||||
if (position !== undefined) {
|
||||
updateData.position = position;
|
||||
}
|
||||
|
||||
const tag = await db.commentTag.update({
|
||||
where: { id: tagId },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
const response = successResponse(tag);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating tag:', error);
|
||||
if ((error as { code?: string }).code === 'P2002') {
|
||||
return apiErrors.conflict('Tag name already exists');
|
||||
}
|
||||
return apiErrors.internalError('Failed to update tag');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
// Verify tag belongs to this project
|
||||
const existingTag = await db.commentTag.findUnique({
|
||||
where: { id: tagId },
|
||||
});
|
||||
if (!existingTag || existingTag.projectId !== projectId) {
|
||||
return apiErrors.notFound('Tag');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, color, position } = body;
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (name !== undefined) {
|
||||
if (!name.trim()) {
|
||||
return apiErrors.badRequest('Name cannot be empty');
|
||||
}
|
||||
updateData.name = name.trim();
|
||||
}
|
||||
if (color !== undefined) {
|
||||
if (!/^#[0-9A-Fa-f]{6}$/.test(color)) {
|
||||
return apiErrors.badRequest('Invalid color format');
|
||||
}
|
||||
updateData.color = color.toUpperCase();
|
||||
}
|
||||
if (position !== undefined) {
|
||||
updateData.position = position;
|
||||
}
|
||||
|
||||
const tag = await db.commentTag.update({
|
||||
where: { id: tagId },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
const response = successResponse(tag);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating tag:', error);
|
||||
if ((error as { code?: string }).code === 'P2002') {
|
||||
return apiErrors.conflict('Tag name already exists');
|
||||
}
|
||||
return apiErrors.internalError('Failed to update tag');
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/projects/[projectId]/tags/[tagId] - Delete a tag
|
||||
export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId, tagId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId, tagId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
// Verify tag belongs to this project
|
||||
const existingTag = await db.commentTag.findUnique({
|
||||
where: { id: tagId },
|
||||
});
|
||||
if (!existingTag || existingTag.projectId !== projectId) {
|
||||
return apiErrors.notFound('Tag');
|
||||
}
|
||||
|
||||
await db.commentTag.delete({ where: { id: tagId } });
|
||||
|
||||
const response = successResponse({ message: 'Tag deleted' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error deleting tag:', error);
|
||||
return apiErrors.internalError('Failed to delete tag');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
// Verify tag belongs to this project
|
||||
const existingTag = await db.commentTag.findUnique({
|
||||
where: { id: tagId },
|
||||
});
|
||||
if (!existingTag || existingTag.projectId !== projectId) {
|
||||
return apiErrors.notFound('Tag');
|
||||
}
|
||||
|
||||
await db.commentTag.delete({ where: { id: tagId } });
|
||||
|
||||
const response = successResponse({ message: 'Tag deleted' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error deleting tag:', error);
|
||||
return apiErrors.internalError('Failed to delete tag');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,125 +11,131 @@ type RouteParams = { params: Promise<{ projectId: string }> };
|
||||
|
||||
// GET /api/projects/[projectId]/tags - Get all tags for a project
|
||||
export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
const videoId = request.nextUrl.searchParams.get('videoId');
|
||||
try {
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
const videoId = request.nextUrl.searchParams.get('videoId');
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
if (!project) return apiErrors.notFound('Project');
|
||||
|
||||
if (session?.user?.id) {
|
||||
const access = await checkProjectAccess(project, session.user.id);
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
} else {
|
||||
let hasGuestAccess = project.visibility === 'PUBLIC';
|
||||
if (!hasGuestAccess && videoId) {
|
||||
const video = await db.video.findFirst({
|
||||
where: { id: videoId, projectId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!project) return apiErrors.notFound('Project');
|
||||
|
||||
if (session?.user?.id) {
|
||||
const access = await checkProjectAccess(project, session.user.id);
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
} else {
|
||||
let hasGuestAccess = project.visibility === 'PUBLIC';
|
||||
if (!hasGuestAccess && videoId) {
|
||||
const video = await db.video.findFirst({
|
||||
where: { id: videoId, projectId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (video) {
|
||||
const shareSession = getShareSessionFromRequest(request, video.id);
|
||||
const shareAccess = shareSession
|
||||
? await validateShareLinkAccess({
|
||||
token: shareSession.token,
|
||||
projectId,
|
||||
videoId: video.id,
|
||||
requiredPermission: 'COMMENT',
|
||||
passwordVerified: shareSession.passwordVerified,
|
||||
})
|
||||
: { hasAccess: false, canComment: false, canDownload: false, allowGuests: false, requiresPassword: false };
|
||||
hasGuestAccess = shareAccess.canComment && shareAccess.allowGuests;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasGuestAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
if (video) {
|
||||
const shareSession = getShareSessionFromRequest(request, video.id);
|
||||
const shareAccess = shareSession
|
||||
? await validateShareLinkAccess({
|
||||
token: shareSession.token,
|
||||
projectId,
|
||||
videoId: video.id,
|
||||
requiredPermission: 'COMMENT',
|
||||
passwordVerified: shareSession.passwordVerified,
|
||||
})
|
||||
: {
|
||||
hasAccess: false,
|
||||
canComment: false,
|
||||
canDownload: false,
|
||||
allowGuests: false,
|
||||
requiresPassword: false,
|
||||
};
|
||||
hasGuestAccess = shareAccess.canComment && shareAccess.allowGuests;
|
||||
}
|
||||
}
|
||||
|
||||
const tags = await db.commentTag.findMany({
|
||||
where: { projectId },
|
||||
orderBy: { position: 'asc' },
|
||||
});
|
||||
|
||||
const response = successResponse(tags);
|
||||
const cacheControl = session?.user?.id
|
||||
? 'private, max-age=120, stale-while-revalidate=300'
|
||||
: 'private, no-cache';
|
||||
return withCacheControl(response, cacheControl);
|
||||
} catch (error) {
|
||||
logError('Error fetching tags:', error);
|
||||
return apiErrors.internalError('Failed to fetch tags');
|
||||
if (!hasGuestAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
}
|
||||
|
||||
const tags = await db.commentTag.findMany({
|
||||
where: { projectId },
|
||||
orderBy: { position: 'asc' },
|
||||
});
|
||||
|
||||
const response = successResponse(tags);
|
||||
const cacheControl = session?.user?.id
|
||||
? 'private, max-age=120, stale-while-revalidate=300'
|
||||
: 'private, no-cache';
|
||||
return withCacheControl(response, cacheControl);
|
||||
} catch (error) {
|
||||
logError('Error fetching tags:', error);
|
||||
return apiErrors.internalError('Failed to fetch tags');
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/projects/[projectId]/tags - Create a new tag
|
||||
export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, color } = body;
|
||||
|
||||
if (!name?.trim() || !color?.trim()) {
|
||||
return apiErrors.badRequest('Name and color are required');
|
||||
}
|
||||
|
||||
// Hex color validation
|
||||
if (!/^#[0-9A-Fa-f]{6}$/.test(color)) {
|
||||
return apiErrors.badRequest('Invalid color format');
|
||||
}
|
||||
|
||||
// Get max position
|
||||
const maxPos = await db.commentTag.aggregate({
|
||||
where: { projectId },
|
||||
_max: { position: true },
|
||||
});
|
||||
|
||||
const tag = await db.commentTag.create({
|
||||
data: {
|
||||
name: name.trim(),
|
||||
color: color.toUpperCase(),
|
||||
position: (maxPos._max.position ?? -1) + 1,
|
||||
projectId,
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(tag, 201);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error creating tag:', error);
|
||||
if ((error as { code?: string }).code === 'P2002') {
|
||||
return apiErrors.conflict('Tag name already exists');
|
||||
}
|
||||
return apiErrors.internalError('Failed to create tag');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, color } = body;
|
||||
|
||||
if (!name?.trim() || !color?.trim()) {
|
||||
return apiErrors.badRequest('Name and color are required');
|
||||
}
|
||||
|
||||
// Hex color validation
|
||||
if (!/^#[0-9A-Fa-f]{6}$/.test(color)) {
|
||||
return apiErrors.badRequest('Invalid color format');
|
||||
}
|
||||
|
||||
// Get max position
|
||||
const maxPos = await db.commentTag.aggregate({
|
||||
where: { projectId },
|
||||
_max: { position: true },
|
||||
});
|
||||
|
||||
const tag = await db.commentTag.create({
|
||||
data: {
|
||||
name: name.trim(),
|
||||
color: color.toUpperCase(),
|
||||
position: (maxPos._max.position ?? -1) + 1,
|
||||
projectId,
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(tag, 201);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error creating tag:', error);
|
||||
if ((error as { code?: string }).code === 'P2002') {
|
||||
return apiErrors.conflict('Tag name already exists');
|
||||
}
|
||||
return apiErrors.internalError('Failed to create tag');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,272 +13,276 @@ type RouteParams = { params: Promise<{ projectId: string; videoId: string }> };
|
||||
|
||||
// GET /api/projects/[projectId]/videos/[videoId]
|
||||
export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const session = await auth();
|
||||
const { projectId, videoId } = await params;
|
||||
try {
|
||||
const session = await auth();
|
||||
const { projectId, videoId } = await params;
|
||||
|
||||
// Parse query params for pagination and options
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const includeComments = searchParams.get('includeComments') !== 'false';
|
||||
const commentLimit = Math.min(parseInt(searchParams.get('commentLimit') || '50'), 100);
|
||||
const commentOffset = Math.max(0, parseInt(searchParams.get('commentOffset') || '0'));
|
||||
const includeReplies = searchParams.get('includeReplies') === 'true';
|
||||
// Parse query params for pagination and options
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const includeComments = searchParams.get('includeComments') !== 'false';
|
||||
const commentLimit = Math.min(parseInt(searchParams.get('commentLimit') || '50'), 100);
|
||||
const commentOffset = Math.max(0, parseInt(searchParams.get('commentOffset') || '0'));
|
||||
const includeReplies = searchParams.get('includeReplies') === 'true';
|
||||
|
||||
const video = await db.video.findFirst({
|
||||
where: { id: videoId, projectId },
|
||||
include: {
|
||||
project: true,
|
||||
versions: {
|
||||
orderBy: { versionNumber: 'desc' },
|
||||
...(includeComments ? {
|
||||
include: {
|
||||
comments: {
|
||||
orderBy: { timestamp: 'asc' },
|
||||
skip: commentOffset,
|
||||
take: commentLimit,
|
||||
select: {
|
||||
id: true,
|
||||
content: true,
|
||||
timestamp: true,
|
||||
timestampEnd: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
isResolved: true,
|
||||
resolvedAt: true,
|
||||
voiceUrl: true,
|
||||
voiceDuration: true,
|
||||
imageUrl: true,
|
||||
annotationData: true,
|
||||
parentId: true,
|
||||
authorId: true,
|
||||
tagId: true,
|
||||
versionId: true,
|
||||
guestName: true,
|
||||
// guestEmail excluded for privacy
|
||||
author: { select: { id: true, name: true, image: true } },
|
||||
tag: { select: { id: true, name: true, color: true } },
|
||||
...(includeReplies ? {
|
||||
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,
|
||||
annotationData: true,
|
||||
parentId: true,
|
||||
authorId: true,
|
||||
tagId: true,
|
||||
versionId: true,
|
||||
guestName: true,
|
||||
// guestEmail excluded for privacy
|
||||
author: { select: { id: true, name: true, image: true } },
|
||||
tag: { select: { id: true, name: true, color: true } },
|
||||
},
|
||||
},
|
||||
} : {}),
|
||||
},
|
||||
where: { parentId: null },
|
||||
const video = await db.video.findFirst({
|
||||
where: { id: videoId, projectId },
|
||||
include: {
|
||||
project: true,
|
||||
versions: {
|
||||
orderBy: { versionNumber: 'desc' },
|
||||
...(includeComments
|
||||
? {
|
||||
include: {
|
||||
comments: {
|
||||
orderBy: { timestamp: 'asc' },
|
||||
skip: commentOffset,
|
||||
take: commentLimit,
|
||||
select: {
|
||||
id: true,
|
||||
content: true,
|
||||
timestamp: true,
|
||||
timestampEnd: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
isResolved: true,
|
||||
resolvedAt: true,
|
||||
voiceUrl: true,
|
||||
voiceDuration: true,
|
||||
imageUrl: true,
|
||||
annotationData: true,
|
||||
parentId: true,
|
||||
authorId: true,
|
||||
tagId: true,
|
||||
versionId: true,
|
||||
guestName: true,
|
||||
// guestEmail excluded for privacy
|
||||
author: { select: { id: true, name: true, image: true } },
|
||||
tag: { select: { id: true, name: true, color: true } },
|
||||
...(includeReplies
|
||||
? {
|
||||
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,
|
||||
annotationData: true,
|
||||
parentId: true,
|
||||
authorId: true,
|
||||
tagId: true,
|
||||
versionId: true,
|
||||
guestName: true,
|
||||
// guestEmail excluded for privacy
|
||||
author: { select: { id: true, name: true, image: true } },
|
||||
tag: { select: { id: true, name: true, color: true } },
|
||||
},
|
||||
},
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
} : {
|
||||
select: {
|
||||
id: true,
|
||||
thumbnailUrl: true,
|
||||
duration: true,
|
||||
versionNumber: true,
|
||||
versionLabel: true,
|
||||
providerId: true,
|
||||
videoId: true,
|
||||
originalUrl: true,
|
||||
title: true,
|
||||
isActive: true,
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
where: { parentId: null },
|
||||
},
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
: {
|
||||
select: {
|
||||
id: true,
|
||||
thumbnailUrl: true,
|
||||
duration: true,
|
||||
versionNumber: true,
|
||||
versionLabel: true,
|
||||
providerId: true,
|
||||
videoId: true,
|
||||
originalUrl: true,
|
||||
title: true,
|
||||
isActive: true,
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
// Check access including workspace membership
|
||||
const access = await checkProjectAccess(video.project, session?.user?.id);
|
||||
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const response = successResponse({
|
||||
...video,
|
||||
isAuthenticated: !!session?.user?.id,
|
||||
currentUserId: session?.user?.id || null,
|
||||
currentUserName: session?.user?.name || null,
|
||||
canDownload: access.hasAccess,
|
||||
canManageTags: access.canEdit,
|
||||
canResolveComments: access.canEdit,
|
||||
canRequestApproval: access.canEdit,
|
||||
canShareVideo: access.canEdit,
|
||||
canUploadAssets: access.hasAccess,
|
||||
canDownloadAssets: !!session?.user?.id && access.hasAccess,
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, no-cache');
|
||||
} catch (error) {
|
||||
logError('Error fetching video:', error);
|
||||
return apiErrors.internalError('Failed to fetch video');
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
// Check access including workspace membership
|
||||
const access = await checkProjectAccess(video.project, session?.user?.id);
|
||||
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const response = successResponse({
|
||||
...video,
|
||||
isAuthenticated: !!session?.user?.id,
|
||||
currentUserId: session?.user?.id || null,
|
||||
currentUserName: session?.user?.name || null,
|
||||
canDownload: access.hasAccess,
|
||||
canManageTags: access.canEdit,
|
||||
canResolveComments: access.canEdit,
|
||||
canRequestApproval: access.canEdit,
|
||||
canShareVideo: access.canEdit,
|
||||
canUploadAssets: access.hasAccess,
|
||||
canDownloadAssets: !!session?.user?.id && access.hasAccess,
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, no-cache');
|
||||
} catch (error) {
|
||||
logError('Error fetching video:', error);
|
||||
return apiErrors.internalError('Failed to fetch video');
|
||||
}
|
||||
}
|
||||
|
||||
// PATCH /api/projects/[projectId]/videos/[videoId]
|
||||
export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId, videoId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId, videoId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const video = await db.video.findFirst({
|
||||
where: { id: videoId, projectId },
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(video.project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { title, description, position } = body;
|
||||
|
||||
// Validate types before using string methods to prevent type confusion attacks
|
||||
if (
|
||||
position !== undefined &&
|
||||
(typeof position !== 'number' || !Number.isInteger(position) || position < 0)
|
||||
) {
|
||||
return apiErrors.badRequest('position must be a non-negative integer');
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (typeof title === 'string') updateData.title = title.trim();
|
||||
if (typeof description === 'string') updateData.description = description.trim() || null;
|
||||
if (position !== undefined) updateData.position = position;
|
||||
|
||||
const updatedVideo = await db.video.update({
|
||||
where: { id: videoId },
|
||||
data: updateData,
|
||||
include: {
|
||||
versions: { orderBy: { versionNumber: 'desc' } },
|
||||
_count: { select: { versions: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(updatedVideo);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating video:', error);
|
||||
return apiErrors.internalError('Failed to update video');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const video = await db.video.findFirst({
|
||||
where: { id: videoId, projectId },
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(video.project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { title, description, position } = body;
|
||||
|
||||
// Validate types before using string methods to prevent type confusion attacks
|
||||
if (
|
||||
position !== undefined &&
|
||||
(typeof position !== 'number' || !Number.isInteger(position) || position < 0)
|
||||
) {
|
||||
return apiErrors.badRequest('position must be a non-negative integer');
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (typeof title === 'string') updateData.title = title.trim();
|
||||
if (typeof description === 'string') updateData.description = description.trim() || null;
|
||||
if (position !== undefined) updateData.position = position;
|
||||
|
||||
const updatedVideo = await db.video.update({
|
||||
where: { id: videoId },
|
||||
data: updateData,
|
||||
include: {
|
||||
versions: { orderBy: { versionNumber: 'desc' } },
|
||||
_count: { select: { versions: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(updatedVideo);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating video:', error);
|
||||
return apiErrors.internalError('Failed to update video');
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/projects/[projectId]/videos/[videoId]
|
||||
export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId, videoId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId, videoId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const video = await db.video.findFirst({
|
||||
where: { id: videoId, projectId },
|
||||
include: {
|
||||
versions: {
|
||||
select: {
|
||||
providerId: true,
|
||||
videoId: true,
|
||||
},
|
||||
},
|
||||
assets: {
|
||||
select: {
|
||||
provider: true,
|
||||
providerVideoId: true,
|
||||
},
|
||||
},
|
||||
project: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(video.project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Only project owner or admin can delete videos');
|
||||
}
|
||||
|
||||
const bunnyRefs = [
|
||||
...video.versions,
|
||||
...video.assets
|
||||
.filter((asset) => asset.provider === 'BUNNY' && !!asset.providerVideoId)
|
||||
.map((asset) => ({
|
||||
providerId: 'bunny',
|
||||
videoId: asset.providerVideoId as string,
|
||||
})),
|
||||
];
|
||||
|
||||
const mediaUrls = await collectVideoMediaUrls(videoId);
|
||||
|
||||
await db.video.delete({ where: { id: videoId } });
|
||||
|
||||
revalidatePath(`/projects/${projectId}`);
|
||||
|
||||
const [bunnyCleanupResult, r2CleanupResult] = await Promise.all([
|
||||
cleanupBunnyStreamVideosBestEffort(bunnyRefs),
|
||||
deleteMediaFilesBestEffort(mediaUrls),
|
||||
]);
|
||||
const cleanupInput = {
|
||||
bunny: bunnyCleanupResult,
|
||||
r2: r2CleanupResult,
|
||||
};
|
||||
const cleanupWarnings = buildCleanupWarnings(cleanupInput);
|
||||
if (cleanupWarnings) {
|
||||
logCleanupWarnings({ entityType: 'video', entityId: videoId }, cleanupInput);
|
||||
}
|
||||
|
||||
const response = successResponse({
|
||||
message: 'Video deleted',
|
||||
...(cleanupWarnings ? { cleanupWarnings } : {}),
|
||||
});
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error deleting video:', error);
|
||||
return apiErrors.internalError('Failed to delete video');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const video = await db.video.findFirst({
|
||||
where: { id: videoId, projectId },
|
||||
include: {
|
||||
versions: {
|
||||
select: {
|
||||
providerId: true,
|
||||
videoId: true,
|
||||
},
|
||||
},
|
||||
assets: {
|
||||
select: {
|
||||
provider: true,
|
||||
providerVideoId: true,
|
||||
},
|
||||
},
|
||||
project: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(video.project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Only project owner or admin can delete videos');
|
||||
}
|
||||
|
||||
const bunnyRefs = [
|
||||
...video.versions,
|
||||
...video.assets
|
||||
.filter((asset) => asset.provider === 'BUNNY' && !!asset.providerVideoId)
|
||||
.map((asset) => ({
|
||||
providerId: 'bunny',
|
||||
videoId: asset.providerVideoId as string,
|
||||
})),
|
||||
];
|
||||
|
||||
const mediaUrls = await collectVideoMediaUrls(videoId);
|
||||
|
||||
await db.video.delete({ where: { id: videoId } });
|
||||
|
||||
revalidatePath(`/projects/${projectId}`);
|
||||
|
||||
const [bunnyCleanupResult, r2CleanupResult] = await Promise.all([
|
||||
cleanupBunnyStreamVideosBestEffort(bunnyRefs),
|
||||
deleteMediaFilesBestEffort(mediaUrls),
|
||||
]);
|
||||
const cleanupInput = {
|
||||
bunny: bunnyCleanupResult,
|
||||
r2: r2CleanupResult,
|
||||
};
|
||||
const cleanupWarnings = buildCleanupWarnings(cleanupInput);
|
||||
if (cleanupWarnings) {
|
||||
logCleanupWarnings({ entityType: 'video', entityId: videoId }, cleanupInput);
|
||||
}
|
||||
|
||||
const response = successResponse({
|
||||
message: 'Video deleted',
|
||||
...(cleanupWarnings ? { cleanupWarnings } : {}),
|
||||
});
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error deleting video:', error);
|
||||
return apiErrors.internalError('Failed to delete video');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,7 +149,9 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
const allowDownloads = typeof body?.allowDownloads === 'boolean' ? body.allowDownloads : false;
|
||||
const password = typeof body?.password === 'string' ? body.password.trim() : '';
|
||||
if (password.length > MAX_SHARE_PASSWORD_LENGTH) {
|
||||
return apiErrors.badRequest(`Password must be ${MAX_SHARE_PASSWORD_LENGTH} characters or fewer`);
|
||||
return apiErrors.badRequest(
|
||||
`Password must be ${MAX_SHARE_PASSWORD_LENGTH} characters or fewer`
|
||||
);
|
||||
}
|
||||
const passwordHash = password ? await bcrypt.hash(password, 12) : null;
|
||||
const token = randomBytes(24).toString('base64url');
|
||||
@@ -166,26 +168,50 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
} | null = null;
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
try {
|
||||
link = await db.$transaction(async (tx) => {
|
||||
const existing = await tx.shareLink.findFirst({
|
||||
where: {
|
||||
projectId,
|
||||
videoId,
|
||||
permission: 'COMMENT',
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
select: { id: true },
|
||||
});
|
||||
link = await db.$transaction(
|
||||
async (tx) => {
|
||||
const existing = await tx.shareLink.findFirst({
|
||||
where: {
|
||||
projectId,
|
||||
videoId,
|
||||
permission: 'COMMENT',
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
return tx.shareLink.update({
|
||||
where: { id: existing.id },
|
||||
if (existing) {
|
||||
return tx.shareLink.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
token,
|
||||
allowGuests,
|
||||
allowDownloads,
|
||||
passwordHash,
|
||||
expiresAt: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
token: true,
|
||||
permission: true,
|
||||
allowGuests: true,
|
||||
allowDownloads: true,
|
||||
expiresAt: true,
|
||||
createdAt: true,
|
||||
passwordHash: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return tx.shareLink.create({
|
||||
data: {
|
||||
token,
|
||||
projectId,
|
||||
videoId,
|
||||
permission: 'COMMENT',
|
||||
allowGuests,
|
||||
allowDownloads,
|
||||
passwordHash,
|
||||
expiresAt: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
@@ -198,33 +224,16 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
passwordHash: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return tx.shareLink.create({
|
||||
data: {
|
||||
token,
|
||||
projectId,
|
||||
videoId,
|
||||
permission: 'COMMENT',
|
||||
allowGuests,
|
||||
allowDownloads,
|
||||
passwordHash,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
token: true,
|
||||
permission: true,
|
||||
allowGuests: true,
|
||||
allowDownloads: true,
|
||||
expiresAt: true,
|
||||
createdAt: true,
|
||||
passwordHash: true,
|
||||
},
|
||||
});
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable });
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable }
|
||||
);
|
||||
break;
|
||||
} catch (error) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2034' && attempt < 2) {
|
||||
if (
|
||||
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||
error.code === 'P2034' &&
|
||||
attempt < 2
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
@@ -261,11 +270,14 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const allowGuests = typeof body?.allowGuests === 'boolean' ? body.allowGuests : undefined;
|
||||
const allowDownloads = typeof body?.allowDownloads === 'boolean' ? body.allowDownloads : undefined;
|
||||
const allowDownloads =
|
||||
typeof body?.allowDownloads === 'boolean' ? body.allowDownloads : undefined;
|
||||
const rawPassword = typeof body?.password === 'string' ? body.password : undefined;
|
||||
const clearPassword = body?.clearPassword === true;
|
||||
if (rawPassword !== undefined && rawPassword.length > MAX_SHARE_PASSWORD_LENGTH) {
|
||||
return apiErrors.badRequest(`Password must be ${MAX_SHARE_PASSWORD_LENGTH} characters or fewer`);
|
||||
return apiErrors.badRequest(
|
||||
`Password must be ${MAX_SHARE_PASSWORD_LENGTH} characters or fewer`
|
||||
);
|
||||
}
|
||||
|
||||
const existing = await db.shareLink.findFirst({
|
||||
|
||||
@@ -9,151 +9,159 @@ import { logError } from '@/lib/logger';
|
||||
|
||||
type RouteParams = { params: Promise<{ projectId: string; videoId: string; versionId: string }> };
|
||||
|
||||
async function getVersionWithAccess(projectId: string, videoId: string, versionId: string, userId: string) {
|
||||
const version = await db.videoVersion.findFirst({
|
||||
where: { id: versionId, videoParentId: videoId },
|
||||
async function getVersionWithAccess(
|
||||
projectId: string,
|
||||
videoId: string,
|
||||
versionId: string,
|
||||
userId: string
|
||||
) {
|
||||
const version = await db.videoVersion.findFirst({
|
||||
where: { id: versionId, videoParentId: videoId },
|
||||
include: {
|
||||
video: {
|
||||
include: {
|
||||
video: {
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
},
|
||||
project: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!version || version.video.projectId !== projectId) {
|
||||
return null;
|
||||
}
|
||||
if (!version || version.video.projectId !== projectId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const project = version.video.project;
|
||||
const access = await checkProjectAccess(project, userId, { intent: 'manage' });
|
||||
const project = version.video.project;
|
||||
const access = await checkProjectAccess(project, userId, { intent: 'manage' });
|
||||
|
||||
return { version, canEdit: access.canEdit, isOwner: access.isOwner };
|
||||
return { version, canEdit: access.canEdit, isOwner: access.isOwner };
|
||||
}
|
||||
|
||||
// PATCH /api/projects/[projectId]/videos/[videoId]/versions/[versionId]
|
||||
export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId, videoId, versionId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId, videoId, versionId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const result = await getVersionWithAccess(projectId, videoId, versionId, session.user.id);
|
||||
if (!result) {
|
||||
return apiErrors.notFound('Version');
|
||||
}
|
||||
if (!result.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { duration, versionLabel, isActive } = body;
|
||||
|
||||
if (duration !== undefined && (typeof duration !== 'number' || !isFinite(duration) || duration < 0)) {
|
||||
return apiErrors.badRequest('Invalid duration value');
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (duration !== undefined) updateData.duration = duration;
|
||||
if (versionLabel !== undefined) updateData.versionLabel = versionLabel?.trim() || null;
|
||||
|
||||
if (isActive === true) {
|
||||
// Deactivate all other versions, then activate this one
|
||||
await db.videoVersion.updateMany({
|
||||
where: { videoParentId: videoId },
|
||||
data: { isActive: false },
|
||||
});
|
||||
updateData.isActive = true;
|
||||
}
|
||||
|
||||
const updated = await db.videoVersion.update({
|
||||
where: { id: versionId },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
const response = successResponse(updated);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating version:', error);
|
||||
return apiErrors.internalError('Failed to update version');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const result = await getVersionWithAccess(projectId, videoId, versionId, session.user.id);
|
||||
if (!result) {
|
||||
return apiErrors.notFound('Version');
|
||||
}
|
||||
if (!result.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { duration, versionLabel, isActive } = body;
|
||||
|
||||
if (
|
||||
duration !== undefined &&
|
||||
(typeof duration !== 'number' || !isFinite(duration) || duration < 0)
|
||||
) {
|
||||
return apiErrors.badRequest('Invalid duration value');
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (duration !== undefined) updateData.duration = duration;
|
||||
if (versionLabel !== undefined) updateData.versionLabel = versionLabel?.trim() || null;
|
||||
|
||||
if (isActive === true) {
|
||||
// Deactivate all other versions, then activate this one
|
||||
await db.videoVersion.updateMany({
|
||||
where: { videoParentId: videoId },
|
||||
data: { isActive: false },
|
||||
});
|
||||
updateData.isActive = true;
|
||||
}
|
||||
|
||||
const updated = await db.videoVersion.update({
|
||||
where: { id: versionId },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
const response = successResponse(updated);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating version:', error);
|
||||
return apiErrors.internalError('Failed to update version');
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/projects/[projectId]/videos/[videoId]/versions/[versionId]
|
||||
export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId, videoId, versionId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId, videoId, versionId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const result = await getVersionWithAccess(projectId, videoId, versionId, session.user.id);
|
||||
if (!result) {
|
||||
return apiErrors.notFound('Version');
|
||||
}
|
||||
if (!result.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
// Check there's more than one version — can't delete the last one
|
||||
const versionCount = await db.videoVersion.count({
|
||||
where: { videoParentId: videoId },
|
||||
});
|
||||
|
||||
if (versionCount <= 1) {
|
||||
return apiErrors.badRequest('Cannot delete the only version. Delete the video instead.');
|
||||
}
|
||||
|
||||
const wasActive = result.version.isActive;
|
||||
const bunnyRef = {
|
||||
providerId: result.version.providerId,
|
||||
videoId: result.version.videoId,
|
||||
};
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
// Delete the version (cascades to comments).
|
||||
await tx.videoVersion.delete({ where: { id: versionId } });
|
||||
|
||||
// If the deleted version was active, activate the latest remaining one.
|
||||
if (wasActive) {
|
||||
const latestVersion = await tx.videoVersion.findFirst({
|
||||
where: { videoParentId: videoId },
|
||||
orderBy: { versionNumber: 'desc' },
|
||||
});
|
||||
if (latestVersion) {
|
||||
await tx.videoVersion.update({
|
||||
where: { id: latestVersion.id },
|
||||
data: { isActive: true },
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const bunnyCleanupResult = await cleanupBunnyStreamVideosBestEffort([bunnyRef]);
|
||||
const cleanupInput = { bunny: bunnyCleanupResult };
|
||||
const cleanupWarnings = buildCleanupWarnings(cleanupInput);
|
||||
if (cleanupWarnings) {
|
||||
logCleanupWarnings({ entityType: 'video-version', entityId: versionId }, cleanupInput);
|
||||
}
|
||||
|
||||
const response = successResponse({
|
||||
message: 'Version deleted',
|
||||
...(cleanupWarnings ? { cleanupWarnings } : {}),
|
||||
});
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error deleting version:', error);
|
||||
return apiErrors.internalError('Failed to delete version');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const result = await getVersionWithAccess(projectId, videoId, versionId, session.user.id);
|
||||
if (!result) {
|
||||
return apiErrors.notFound('Version');
|
||||
}
|
||||
if (!result.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
// Check there's more than one version — can't delete the last one
|
||||
const versionCount = await db.videoVersion.count({
|
||||
where: { videoParentId: videoId },
|
||||
});
|
||||
|
||||
if (versionCount <= 1) {
|
||||
return apiErrors.badRequest('Cannot delete the only version. Delete the video instead.');
|
||||
}
|
||||
|
||||
const wasActive = result.version.isActive;
|
||||
const bunnyRef = {
|
||||
providerId: result.version.providerId,
|
||||
videoId: result.version.videoId,
|
||||
};
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
// Delete the version (cascades to comments).
|
||||
await tx.videoVersion.delete({ where: { id: versionId } });
|
||||
|
||||
// If the deleted version was active, activate the latest remaining one.
|
||||
if (wasActive) {
|
||||
const latestVersion = await tx.videoVersion.findFirst({
|
||||
where: { videoParentId: videoId },
|
||||
orderBy: { versionNumber: 'desc' },
|
||||
});
|
||||
if (latestVersion) {
|
||||
await tx.videoVersion.update({
|
||||
where: { id: latestVersion.id },
|
||||
data: { isActive: true },
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const bunnyCleanupResult = await cleanupBunnyStreamVideosBestEffort([bunnyRef]);
|
||||
const cleanupInput = { bunny: bunnyCleanupResult };
|
||||
const cleanupWarnings = buildCleanupWarnings(cleanupInput);
|
||||
if (cleanupWarnings) {
|
||||
logCleanupWarnings({ entityType: 'video-version', entityId: versionId }, cleanupInput);
|
||||
}
|
||||
|
||||
const response = successResponse({
|
||||
message: 'Version deleted',
|
||||
...(cleanupWarnings ? { cleanupWarnings } : {}),
|
||||
});
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error deleting version:', error);
|
||||
return apiErrors.internalError('Failed to delete version');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,177 +12,181 @@ type RouteParams = { params: Promise<{ projectId: string; videoId: string }> };
|
||||
|
||||
// GET /api/projects/[projectId]/videos/[videoId]/versions
|
||||
export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const session = await auth();
|
||||
const { projectId, videoId } = await params;
|
||||
try {
|
||||
const session = await auth();
|
||||
const { projectId, videoId } = await params;
|
||||
|
||||
const video = await db.video.findFirst({
|
||||
where: { id: videoId, projectId },
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
});
|
||||
const video = await db.video.findFirst({
|
||||
where: { id: videoId, projectId },
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(video.project, session?.user?.id);
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const versions = await db.videoVersion.findMany({
|
||||
where: { videoParentId: videoId },
|
||||
orderBy: { versionNumber: 'desc' },
|
||||
include: {
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse({ versions });
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error fetching versions:', error);
|
||||
return apiErrors.internalError('Failed to fetch versions');
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(video.project, session?.user?.id);
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const versions = await db.videoVersion.findMany({
|
||||
where: { videoParentId: videoId },
|
||||
orderBy: { versionNumber: 'desc' },
|
||||
include: {
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse({ versions });
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error fetching versions:', error);
|
||||
return apiErrors.internalError('Failed to fetch versions');
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/projects/[projectId]/videos/[videoId]/versions - Add a new version
|
||||
export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'create-version');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'create-version');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId, videoId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId, videoId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const video = await db.video.findFirst({
|
||||
where: { id: videoId, projectId },
|
||||
include: {
|
||||
project: true,
|
||||
versions: { orderBy: { versionNumber: 'desc' }, take: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(video.project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const {
|
||||
videoUrl,
|
||||
providerId,
|
||||
providerVideoId,
|
||||
versionLabel,
|
||||
thumbnailUrl,
|
||||
duration,
|
||||
setActive,
|
||||
uploadToken
|
||||
} = body;
|
||||
|
||||
if (!videoUrl) {
|
||||
return apiErrors.badRequest('Video URL is required');
|
||||
}
|
||||
|
||||
if (versionLabel !== undefined && versionLabel !== null) {
|
||||
if (typeof versionLabel !== 'string') {
|
||||
return apiErrors.badRequest('Version label must be a string');
|
||||
}
|
||||
if (versionLabel.trim().length > 100) {
|
||||
return apiErrors.badRequest('Version label must be 100 characters or fewer');
|
||||
}
|
||||
}
|
||||
|
||||
// Validate URLs use safe schemes (http/https only)
|
||||
const videoUrlError = validateUrl(videoUrl, 'Video URL');
|
||||
if (videoUrlError) {
|
||||
return apiErrors.badRequest(videoUrlError);
|
||||
}
|
||||
|
||||
const thumbnailUrlError = validateOptionalUrl(thumbnailUrl, 'Thumbnail URL');
|
||||
if (thumbnailUrlError) {
|
||||
return apiErrors.badRequest(thumbnailUrlError);
|
||||
}
|
||||
|
||||
const normalizedProviderId = typeof providerId === 'string' && providerId.trim()
|
||||
? providerId.trim().toLowerCase()
|
||||
: 'youtube';
|
||||
const normalizedProviderVideoId = typeof providerVideoId === 'string' ? providerVideoId.trim() : '';
|
||||
const normalizedUploadToken = typeof uploadToken === 'string' ? uploadToken.trim() : '';
|
||||
|
||||
if (normalizedProviderId === 'bunny') {
|
||||
if (!normalizedProviderVideoId || !normalizedUploadToken) {
|
||||
return apiErrors.badRequest('Bunny uploads must include providerVideoId and uploadToken');
|
||||
}
|
||||
|
||||
const isValidUploadToken = verifyBunnyUploadToken(normalizedUploadToken, {
|
||||
userId: session.user.id,
|
||||
projectId,
|
||||
videoId: normalizedProviderVideoId,
|
||||
});
|
||||
if (!isValidUploadToken) {
|
||||
return apiErrors.forbidden('Invalid Bunny upload token');
|
||||
}
|
||||
}
|
||||
|
||||
const nextVersionNumber = (video.versions[0]?.versionNumber || 0) + 1;
|
||||
|
||||
// Use transaction to handle active flag
|
||||
const version = await db.$transaction(async (tx: Parameters<Parameters<typeof db.$transaction>[0]>[0]) => {
|
||||
// If setActive, deactivate all other versions
|
||||
if (setActive) {
|
||||
await tx.videoVersion.updateMany({
|
||||
where: { videoParentId: videoId },
|
||||
data: { isActive: false },
|
||||
});
|
||||
}
|
||||
|
||||
return tx.videoVersion.create({
|
||||
data: {
|
||||
versionNumber: nextVersionNumber,
|
||||
versionLabel: versionLabel?.trim() || null,
|
||||
providerId: normalizedProviderId,
|
||||
videoId: normalizedProviderVideoId,
|
||||
originalUrl: videoUrl,
|
||||
title: versionLabel?.trim() || `Version ${nextVersionNumber}`,
|
||||
thumbnailUrl: thumbnailUrl || null,
|
||||
duration: duration || null,
|
||||
isActive: setActive ?? false,
|
||||
videoParentId: videoId,
|
||||
},
|
||||
include: {
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// Notify project owner (fire-and-forget, skip if they added it themselves)
|
||||
if (video.project.ownerId !== session.user.id) {
|
||||
const baseUrl = process.env.NEXTAUTH_URL || '';
|
||||
notifyProjectOwner(video.project.ownerId, {
|
||||
type: 'new_version',
|
||||
projectName: video.project.name,
|
||||
videoTitle: video.title,
|
||||
versionLabel: version.versionLabel || `Version ${version.versionNumber}`,
|
||||
addedBy: session.user.name || 'A team member',
|
||||
url: `${baseUrl}/watch/${video.id}`,
|
||||
}).catch((err) => logError('Notification failed:', err));
|
||||
}
|
||||
|
||||
const response = successResponse(version, 201);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error creating version:', error);
|
||||
return apiErrors.internalError('Failed to create version');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const video = await db.video.findFirst({
|
||||
where: { id: videoId, projectId },
|
||||
include: {
|
||||
project: true,
|
||||
versions: { orderBy: { versionNumber: 'desc' }, take: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(video.project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const {
|
||||
videoUrl,
|
||||
providerId,
|
||||
providerVideoId,
|
||||
versionLabel,
|
||||
thumbnailUrl,
|
||||
duration,
|
||||
setActive,
|
||||
uploadToken,
|
||||
} = body;
|
||||
|
||||
if (!videoUrl) {
|
||||
return apiErrors.badRequest('Video URL is required');
|
||||
}
|
||||
|
||||
if (versionLabel !== undefined && versionLabel !== null) {
|
||||
if (typeof versionLabel !== 'string') {
|
||||
return apiErrors.badRequest('Version label must be a string');
|
||||
}
|
||||
if (versionLabel.trim().length > 100) {
|
||||
return apiErrors.badRequest('Version label must be 100 characters or fewer');
|
||||
}
|
||||
}
|
||||
|
||||
// Validate URLs use safe schemes (http/https only)
|
||||
const videoUrlError = validateUrl(videoUrl, 'Video URL');
|
||||
if (videoUrlError) {
|
||||
return apiErrors.badRequest(videoUrlError);
|
||||
}
|
||||
|
||||
const thumbnailUrlError = validateOptionalUrl(thumbnailUrl, 'Thumbnail URL');
|
||||
if (thumbnailUrlError) {
|
||||
return apiErrors.badRequest(thumbnailUrlError);
|
||||
}
|
||||
|
||||
const normalizedProviderId =
|
||||
typeof providerId === 'string' && providerId.trim()
|
||||
? providerId.trim().toLowerCase()
|
||||
: 'youtube';
|
||||
const normalizedProviderVideoId =
|
||||
typeof providerVideoId === 'string' ? providerVideoId.trim() : '';
|
||||
const normalizedUploadToken = typeof uploadToken === 'string' ? uploadToken.trim() : '';
|
||||
|
||||
if (normalizedProviderId === 'bunny') {
|
||||
if (!normalizedProviderVideoId || !normalizedUploadToken) {
|
||||
return apiErrors.badRequest('Bunny uploads must include providerVideoId and uploadToken');
|
||||
}
|
||||
|
||||
const isValidUploadToken = verifyBunnyUploadToken(normalizedUploadToken, {
|
||||
userId: session.user.id,
|
||||
projectId,
|
||||
videoId: normalizedProviderVideoId,
|
||||
});
|
||||
if (!isValidUploadToken) {
|
||||
return apiErrors.forbidden('Invalid Bunny upload token');
|
||||
}
|
||||
}
|
||||
|
||||
const nextVersionNumber = (video.versions[0]?.versionNumber || 0) + 1;
|
||||
|
||||
// Use transaction to handle active flag
|
||||
const version = await db.$transaction(
|
||||
async (tx: Parameters<Parameters<typeof db.$transaction>[0]>[0]) => {
|
||||
// If setActive, deactivate all other versions
|
||||
if (setActive) {
|
||||
await tx.videoVersion.updateMany({
|
||||
where: { videoParentId: videoId },
|
||||
data: { isActive: false },
|
||||
});
|
||||
}
|
||||
|
||||
return tx.videoVersion.create({
|
||||
data: {
|
||||
versionNumber: nextVersionNumber,
|
||||
versionLabel: versionLabel?.trim() || null,
|
||||
providerId: normalizedProviderId,
|
||||
videoId: normalizedProviderVideoId,
|
||||
originalUrl: videoUrl,
|
||||
title: versionLabel?.trim() || `Version ${nextVersionNumber}`,
|
||||
thumbnailUrl: thumbnailUrl || null,
|
||||
duration: duration || null,
|
||||
isActive: setActive ?? false,
|
||||
videoParentId: videoId,
|
||||
},
|
||||
include: {
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
// Notify project owner (fire-and-forget, skip if they added it themselves)
|
||||
if (video.project.ownerId !== session.user.id) {
|
||||
const baseUrl = process.env.NEXTAUTH_URL || '';
|
||||
notifyProjectOwner(video.project.ownerId, {
|
||||
type: 'new_version',
|
||||
projectName: video.project.name,
|
||||
videoTitle: video.title,
|
||||
versionLabel: version.versionLabel || `Version ${version.versionNumber}`,
|
||||
addedBy: session.user.name || 'A team member',
|
||||
url: `${baseUrl}/watch/${video.id}`,
|
||||
}).catch((err) => logError('Notification failed:', err));
|
||||
}
|
||||
|
||||
const response = successResponse(version, 201);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error creating version:', error);
|
||||
return apiErrors.internalError('Failed to create version');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,152 +13,163 @@ import { enforceStorageQuota } from '@/lib/storage-quota';
|
||||
type RouteParams = { params: Promise<{ projectId: string }> };
|
||||
|
||||
async function getProjectWithEditAccess(projectId: string, userId: string) {
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, name: true, ownerId: true, workspaceId: true, visibility: true, workspace: { select: { ownerId: true } } },
|
||||
});
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
ownerId: true,
|
||||
workspaceId: true,
|
||||
visibility: true,
|
||||
workspace: { select: { ownerId: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!project) return null;
|
||||
if (!project) return null;
|
||||
|
||||
const access = await checkProjectAccess(project, userId, { intent: 'manage' });
|
||||
const canEdit = access.canEdit;
|
||||
const access = await checkProjectAccess(project, userId, { intent: 'manage' });
|
||||
const canEdit = access.canEdit;
|
||||
|
||||
if (!canEdit) return null;
|
||||
if (!canEdit) return null;
|
||||
|
||||
return project;
|
||||
return project;
|
||||
}
|
||||
|
||||
// POST /api/projects/[projectId]/videos/bunny-init
|
||||
export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await getProjectWithEditAccess(projectId, session.user.id);
|
||||
if (!project) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const title = typeof body?.title === 'string' ? body.title.trim() : '';
|
||||
|
||||
if (!title) {
|
||||
return apiErrors.badRequest('Title is required');
|
||||
}
|
||||
|
||||
if (!isBunnyUploadsFeatureEnabled()) {
|
||||
return apiErrors.badRequest('Direct uploads are disabled by this host');
|
||||
}
|
||||
|
||||
const quotaError = await enforceStorageQuota(project.workspace.ownerId, BigInt(0));
|
||||
if (quotaError) return quotaError;
|
||||
|
||||
const apiKey = process.env.BUNNY_STREAM_API_KEY;
|
||||
const libraryId = process.env.BUNNY_STREAM_LIBRARY_ID || process.env.NEXT_PUBLIC_BUNNY_STREAM_LIBRARY_ID;
|
||||
|
||||
if (!apiKey || !libraryId) {
|
||||
return apiErrors.internalError('Bunny Stream is not configured correctly');
|
||||
}
|
||||
|
||||
// 1. Create video object in Bunny Stream
|
||||
const bunnyRes = await fetch(`https://video.bunnycdn.com/library/${libraryId}/videos`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'AccessKey': apiKey,
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ title })
|
||||
});
|
||||
|
||||
if (!bunnyRes.ok) {
|
||||
logError('Failed to create Bunny Stream video', await bunnyRes.text());
|
||||
return apiErrors.internalError('Failed to initialize video upload with provider');
|
||||
}
|
||||
|
||||
const bunnyVideo = await bunnyRes.json();
|
||||
const videoId = bunnyVideo.guid;
|
||||
if (typeof videoId !== 'string' || videoId.length === 0) {
|
||||
return apiErrors.internalError('Upload provider did not return a valid video identifier');
|
||||
}
|
||||
|
||||
// 2. Generate TUS upload signature
|
||||
const expirationTime = Math.floor(Date.now() / 1000) + 3600; // 1 hour validity
|
||||
|
||||
// SHA256(library_id + api_key + expiration_time + video_id)
|
||||
const hash = crypto.createHash('sha256');
|
||||
hash.update(libraryId + apiKey + expirationTime + videoId);
|
||||
const signature = hash.digest('hex');
|
||||
const uploadToken = createBunnyUploadToken({
|
||||
userId: session.user.id,
|
||||
projectId,
|
||||
videoId,
|
||||
}, 3600);
|
||||
|
||||
const response = successResponse({
|
||||
videoId,
|
||||
libraryId,
|
||||
signature,
|
||||
expirationTime,
|
||||
uploadToken,
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error initializing Bunny upload:', error);
|
||||
return apiErrors.internalError('Failed to initialize upload');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await getProjectWithEditAccess(projectId, session.user.id);
|
||||
if (!project) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const title = typeof body?.title === 'string' ? body.title.trim() : '';
|
||||
|
||||
if (!title) {
|
||||
return apiErrors.badRequest('Title is required');
|
||||
}
|
||||
|
||||
if (!isBunnyUploadsFeatureEnabled()) {
|
||||
return apiErrors.badRequest('Direct uploads are disabled by this host');
|
||||
}
|
||||
|
||||
const quotaError = await enforceStorageQuota(project.workspace.ownerId, BigInt(0));
|
||||
if (quotaError) return quotaError;
|
||||
|
||||
const apiKey = process.env.BUNNY_STREAM_API_KEY;
|
||||
const libraryId =
|
||||
process.env.BUNNY_STREAM_LIBRARY_ID || process.env.NEXT_PUBLIC_BUNNY_STREAM_LIBRARY_ID;
|
||||
|
||||
if (!apiKey || !libraryId) {
|
||||
return apiErrors.internalError('Bunny Stream is not configured correctly');
|
||||
}
|
||||
|
||||
// 1. Create video object in Bunny Stream
|
||||
const bunnyRes = await fetch(`https://video.bunnycdn.com/library/${libraryId}/videos`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
AccessKey: apiKey,
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ title }),
|
||||
});
|
||||
|
||||
if (!bunnyRes.ok) {
|
||||
logError('Failed to create Bunny Stream video', await bunnyRes.text());
|
||||
return apiErrors.internalError('Failed to initialize video upload with provider');
|
||||
}
|
||||
|
||||
const bunnyVideo = await bunnyRes.json();
|
||||
const videoId = bunnyVideo.guid;
|
||||
if (typeof videoId !== 'string' || videoId.length === 0) {
|
||||
return apiErrors.internalError('Upload provider did not return a valid video identifier');
|
||||
}
|
||||
|
||||
// 2. Generate TUS upload signature
|
||||
const expirationTime = Math.floor(Date.now() / 1000) + 3600; // 1 hour validity
|
||||
|
||||
// SHA256(library_id + api_key + expiration_time + video_id)
|
||||
const hash = crypto.createHash('sha256');
|
||||
hash.update(libraryId + apiKey + expirationTime + videoId);
|
||||
const signature = hash.digest('hex');
|
||||
const uploadToken = createBunnyUploadToken(
|
||||
{
|
||||
userId: session.user.id,
|
||||
projectId,
|
||||
videoId,
|
||||
},
|
||||
3600
|
||||
);
|
||||
|
||||
const response = successResponse({
|
||||
videoId,
|
||||
libraryId,
|
||||
signature,
|
||||
expirationTime,
|
||||
uploadToken,
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error initializing Bunny upload:', error);
|
||||
return apiErrors.internalError('Failed to initialize upload');
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/projects/[projectId]/videos/bunny-init
|
||||
// Best-effort cleanup for interrupted uploads before a DB row is created.
|
||||
export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await getProjectWithEditAccess(projectId, session.user.id);
|
||||
if (!project) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const videoId = typeof body?.videoId === 'string' ? body.videoId.trim() : '';
|
||||
const uploadToken = typeof body?.uploadToken === 'string' ? body.uploadToken.trim() : '';
|
||||
|
||||
if (!videoId || !uploadToken) {
|
||||
return apiErrors.badRequest('videoId and uploadToken are required');
|
||||
}
|
||||
|
||||
const isValidUploadToken = verifyBunnyUploadToken(uploadToken, {
|
||||
userId: session.user.id,
|
||||
projectId,
|
||||
videoId,
|
||||
});
|
||||
if (!isValidUploadToken) {
|
||||
return apiErrors.forbidden('Invalid Bunny upload token');
|
||||
}
|
||||
|
||||
await cleanupBunnyStreamVideos([{ providerId: 'bunny', videoId }]);
|
||||
|
||||
const response = successResponse({ message: 'Pending upload cleaned up' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error cleaning up pending Bunny upload:', error);
|
||||
return apiErrors.internalError('Failed to cleanup pending upload');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const project = await getProjectWithEditAccess(projectId, session.user.id);
|
||||
if (!project) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const videoId = typeof body?.videoId === 'string' ? body.videoId.trim() : '';
|
||||
const uploadToken = typeof body?.uploadToken === 'string' ? body.uploadToken.trim() : '';
|
||||
|
||||
if (!videoId || !uploadToken) {
|
||||
return apiErrors.badRequest('videoId and uploadToken are required');
|
||||
}
|
||||
|
||||
const isValidUploadToken = verifyBunnyUploadToken(uploadToken, {
|
||||
userId: session.user.id,
|
||||
projectId,
|
||||
videoId,
|
||||
});
|
||||
if (!isValidUploadToken) {
|
||||
return apiErrors.forbidden('Invalid Bunny upload token');
|
||||
}
|
||||
|
||||
await cleanupBunnyStreamVideos([{ providerId: 'bunny', videoId }]);
|
||||
|
||||
const response = successResponse({ message: 'Pending upload cleaned up' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error cleaning up pending Bunny upload:', error);
|
||||
return apiErrors.internalError('Failed to cleanup pending upload');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,169 +12,179 @@ type RouteParams = { params: Promise<{ projectId: string }> };
|
||||
|
||||
// GET /api/projects/[projectId]/videos - List all videos in a project
|
||||
export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
try {
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
|
||||
// Check project exists and user has access
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
// Check project exists and user has access
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session?.user?.id);
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const videos = await db.video.findMany({
|
||||
where: { projectId },
|
||||
orderBy: { position: 'asc' },
|
||||
include: {
|
||||
versions: {
|
||||
where: { isActive: true },
|
||||
orderBy: { versionNumber: 'desc' },
|
||||
take: 1,
|
||||
select: {
|
||||
id: true,
|
||||
thumbnailUrl: true,
|
||||
duration: true,
|
||||
versionNumber: true,
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
},
|
||||
_count: { select: { versions: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse({ videos });
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error fetching videos:', error);
|
||||
return apiErrors.internalError('Failed to fetch videos');
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session?.user?.id);
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const videos = await db.video.findMany({
|
||||
where: { projectId },
|
||||
orderBy: { position: 'asc' },
|
||||
include: {
|
||||
versions: {
|
||||
where: { isActive: true },
|
||||
orderBy: { versionNumber: 'desc' },
|
||||
take: 1,
|
||||
select: {
|
||||
id: true,
|
||||
thumbnailUrl: true,
|
||||
duration: true,
|
||||
versionNumber: true,
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
},
|
||||
_count: { select: { versions: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse({ videos });
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error fetching videos:', error);
|
||||
return apiErrors.internalError('Failed to fetch videos');
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/projects/[projectId]/videos - Add a new video to the project
|
||||
export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'create-video');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'create-video');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
const session = await auth();
|
||||
const { projectId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
// Check project access (must be owner, project admin, or workspace admin)
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, name: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { title, description, videoUrl, providerId, videoId, thumbnailUrl, duration, uploadToken } = body;
|
||||
|
||||
if (!title || !videoUrl) {
|
||||
return apiErrors.badRequest('Title and video URL are required');
|
||||
}
|
||||
|
||||
// Validate URLs use safe schemes (http/https only)
|
||||
const videoUrlError = validateUrl(videoUrl, 'Video URL');
|
||||
if (videoUrlError) {
|
||||
return apiErrors.badRequest(videoUrlError);
|
||||
}
|
||||
|
||||
const thumbnailUrlError = validateOptionalUrl(thumbnailUrl, 'Thumbnail URL');
|
||||
if (thumbnailUrlError) {
|
||||
return apiErrors.badRequest(thumbnailUrlError);
|
||||
}
|
||||
|
||||
const normalizedProviderId = typeof providerId === 'string' && providerId.trim()
|
||||
? providerId.trim().toLowerCase()
|
||||
: 'youtube';
|
||||
const normalizedVideoId = typeof videoId === 'string' ? videoId.trim() : '';
|
||||
const normalizedUploadToken = typeof uploadToken === 'string' ? uploadToken.trim() : '';
|
||||
|
||||
if (normalizedProviderId === 'bunny') {
|
||||
if (!normalizedVideoId || !normalizedUploadToken) {
|
||||
return apiErrors.badRequest('Bunny uploads must include videoId and uploadToken');
|
||||
}
|
||||
|
||||
const isValidUploadToken = verifyBunnyUploadToken(normalizedUploadToken, {
|
||||
userId: session.user.id,
|
||||
projectId,
|
||||
videoId: normalizedVideoId,
|
||||
});
|
||||
if (!isValidUploadToken) {
|
||||
return apiErrors.forbidden('Invalid Bunny upload token');
|
||||
}
|
||||
}
|
||||
|
||||
// Get the next position
|
||||
const lastVideo = await db.video.findFirst({
|
||||
where: { projectId },
|
||||
orderBy: { position: 'desc' },
|
||||
});
|
||||
const nextPosition = (lastVideo?.position ?? -1) + 1;
|
||||
|
||||
// Create video with initial version
|
||||
const video = await db.video.create({
|
||||
data: {
|
||||
title: title.trim(),
|
||||
description: description?.trim() || null,
|
||||
position: nextPosition,
|
||||
projectId,
|
||||
versions: {
|
||||
create: {
|
||||
versionNumber: 1,
|
||||
providerId: normalizedProviderId,
|
||||
videoId: normalizedVideoId,
|
||||
originalUrl: videoUrl,
|
||||
title: title.trim(),
|
||||
thumbnailUrl: thumbnailUrl || null,
|
||||
duration: duration || null,
|
||||
isActive: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: {
|
||||
versions: true,
|
||||
_count: { select: { versions: true } },
|
||||
},
|
||||
});
|
||||
|
||||
// Notify project owner (fire-and-forget, skip if they added it themselves)
|
||||
if (project.ownerId !== session.user.id) {
|
||||
const baseUrl = process.env.NEXTAUTH_URL || '';
|
||||
notifyProjectOwner(project.ownerId, {
|
||||
type: 'new_video',
|
||||
projectName: project.name,
|
||||
videoTitle: title.trim(),
|
||||
addedBy: session.user.name || 'A team member',
|
||||
url: `${baseUrl}/watch/${video.id}`,
|
||||
}).catch((err) => logError('Notification failed:', err));
|
||||
}
|
||||
|
||||
const response = successResponse(video, 201);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error creating video:', error);
|
||||
return apiErrors.internalError('Failed to create video');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
// Check project access (must be owner, project admin, or workspace admin)
|
||||
const project = await db.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { id: true, name: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const {
|
||||
title,
|
||||
description,
|
||||
videoUrl,
|
||||
providerId,
|
||||
videoId,
|
||||
thumbnailUrl,
|
||||
duration,
|
||||
uploadToken,
|
||||
} = body;
|
||||
|
||||
if (!title || !videoUrl) {
|
||||
return apiErrors.badRequest('Title and video URL are required');
|
||||
}
|
||||
|
||||
// Validate URLs use safe schemes (http/https only)
|
||||
const videoUrlError = validateUrl(videoUrl, 'Video URL');
|
||||
if (videoUrlError) {
|
||||
return apiErrors.badRequest(videoUrlError);
|
||||
}
|
||||
|
||||
const thumbnailUrlError = validateOptionalUrl(thumbnailUrl, 'Thumbnail URL');
|
||||
if (thumbnailUrlError) {
|
||||
return apiErrors.badRequest(thumbnailUrlError);
|
||||
}
|
||||
|
||||
const normalizedProviderId =
|
||||
typeof providerId === 'string' && providerId.trim()
|
||||
? providerId.trim().toLowerCase()
|
||||
: 'youtube';
|
||||
const normalizedVideoId = typeof videoId === 'string' ? videoId.trim() : '';
|
||||
const normalizedUploadToken = typeof uploadToken === 'string' ? uploadToken.trim() : '';
|
||||
|
||||
if (normalizedProviderId === 'bunny') {
|
||||
if (!normalizedVideoId || !normalizedUploadToken) {
|
||||
return apiErrors.badRequest('Bunny uploads must include videoId and uploadToken');
|
||||
}
|
||||
|
||||
const isValidUploadToken = verifyBunnyUploadToken(normalizedUploadToken, {
|
||||
userId: session.user.id,
|
||||
projectId,
|
||||
videoId: normalizedVideoId,
|
||||
});
|
||||
if (!isValidUploadToken) {
|
||||
return apiErrors.forbidden('Invalid Bunny upload token');
|
||||
}
|
||||
}
|
||||
|
||||
// Get the next position
|
||||
const lastVideo = await db.video.findFirst({
|
||||
where: { projectId },
|
||||
orderBy: { position: 'desc' },
|
||||
});
|
||||
const nextPosition = (lastVideo?.position ?? -1) + 1;
|
||||
|
||||
// Create video with initial version
|
||||
const video = await db.video.create({
|
||||
data: {
|
||||
title: title.trim(),
|
||||
description: description?.trim() || null,
|
||||
position: nextPosition,
|
||||
projectId,
|
||||
versions: {
|
||||
create: {
|
||||
versionNumber: 1,
|
||||
providerId: normalizedProviderId,
|
||||
videoId: normalizedVideoId,
|
||||
originalUrl: videoUrl,
|
||||
title: title.trim(),
|
||||
thumbnailUrl: thumbnailUrl || null,
|
||||
duration: duration || null,
|
||||
isActive: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: {
|
||||
versions: true,
|
||||
_count: { select: { versions: true } },
|
||||
},
|
||||
});
|
||||
|
||||
// Notify project owner (fire-and-forget, skip if they added it themselves)
|
||||
if (project.ownerId !== session.user.id) {
|
||||
const baseUrl = process.env.NEXTAUTH_URL || '';
|
||||
notifyProjectOwner(project.ownerId, {
|
||||
type: 'new_video',
|
||||
projectName: project.name,
|
||||
videoTitle: title.trim(),
|
||||
addedBy: session.user.name || 'A team member',
|
||||
url: `${baseUrl}/watch/${video.id}`,
|
||||
}).catch((err) => logError('Notification failed:', err));
|
||||
}
|
||||
|
||||
const response = successResponse(video, 201);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error creating video:', error);
|
||||
return apiErrors.internalError('Failed to create video');
|
||||
}
|
||||
}
|
||||
|
||||
+181
-179
@@ -10,192 +10,194 @@ import { logError } from '@/lib/logger';
|
||||
|
||||
// GET /api/projects - List all projects for the authenticated user
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await auth();
|
||||
const MAX_LIMIT = 100;
|
||||
const MAX_PAGE = 1000;
|
||||
const MAX_OFFSET = 10000;
|
||||
try {
|
||||
const session = await auth();
|
||||
const MAX_LIMIT = 100;
|
||||
const MAX_PAGE = 1000;
|
||||
const MAX_OFFSET = 10000;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const pageParam = searchParams.get('page');
|
||||
const limitParam = searchParams.get('limit');
|
||||
const workspaceId = searchParams.get('workspaceId');
|
||||
|
||||
const pageRaw = pageParam === null ? 1 : Number(pageParam);
|
||||
if (!Number.isSafeInteger(pageRaw) || pageRaw < 1 || pageRaw > MAX_PAGE) {
|
||||
return apiErrors.badRequest('Invalid page. Must be a positive integer.');
|
||||
}
|
||||
|
||||
const limitRaw = limitParam === null ? 10 : Number(limitParam);
|
||||
if (!Number.isSafeInteger(limitRaw) || limitRaw < 1 || limitRaw > MAX_LIMIT) {
|
||||
return apiErrors.badRequest('Invalid limit. Must be a positive integer between 1 and 100.');
|
||||
}
|
||||
|
||||
const page = pageRaw;
|
||||
const limit = limitRaw;
|
||||
const skip = (page - 1) * limit;
|
||||
if (!Number.isSafeInteger(skip) || skip > MAX_OFFSET) {
|
||||
return apiErrors.badRequest('Invalid page range. Offset must be 10000 or less.');
|
||||
}
|
||||
|
||||
// Build base filter: user is owner OR a member
|
||||
const baseFilter: Record<string, unknown> = {
|
||||
OR: [
|
||||
{ ownerId: session.user.id },
|
||||
{ members: { some: { userId: session.user.id } } },
|
||||
// Also include projects in workspaces where the user is a workspace member
|
||||
...(workspaceId ? [] : [{
|
||||
workspace: {
|
||||
owner: buildBillingAccessWhereInput(),
|
||||
members: { some: { userId: session.user.id } },
|
||||
},
|
||||
}]),
|
||||
],
|
||||
workspace: {
|
||||
owner: buildBillingAccessWhereInput(),
|
||||
},
|
||||
};
|
||||
|
||||
// Filter by workspace if provided
|
||||
if (workspaceId) {
|
||||
baseFilter.workspaceId = workspaceId;
|
||||
}
|
||||
|
||||
// Get projects where user is owner OR a member
|
||||
const [projects, total] = await Promise.all([
|
||||
db.project.findMany({
|
||||
where: baseFilter,
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
_count: { select: { videos: true, members: true } },
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
skip,
|
||||
take: limit,
|
||||
}),
|
||||
db.project.count({
|
||||
where: baseFilter,
|
||||
}),
|
||||
]);
|
||||
|
||||
const response = successResponse(
|
||||
{ projects },
|
||||
200,
|
||||
{
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
}
|
||||
);
|
||||
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error fetching projects:', error);
|
||||
return apiErrors.internalError('Failed to fetch projects');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const pageParam = searchParams.get('page');
|
||||
const limitParam = searchParams.get('limit');
|
||||
const workspaceId = searchParams.get('workspaceId');
|
||||
|
||||
const pageRaw = pageParam === null ? 1 : Number(pageParam);
|
||||
if (!Number.isSafeInteger(pageRaw) || pageRaw < 1 || pageRaw > MAX_PAGE) {
|
||||
return apiErrors.badRequest('Invalid page. Must be a positive integer.');
|
||||
}
|
||||
|
||||
const limitRaw = limitParam === null ? 10 : Number(limitParam);
|
||||
if (!Number.isSafeInteger(limitRaw) || limitRaw < 1 || limitRaw > MAX_LIMIT) {
|
||||
return apiErrors.badRequest('Invalid limit. Must be a positive integer between 1 and 100.');
|
||||
}
|
||||
|
||||
const page = pageRaw;
|
||||
const limit = limitRaw;
|
||||
const skip = (page - 1) * limit;
|
||||
if (!Number.isSafeInteger(skip) || skip > MAX_OFFSET) {
|
||||
return apiErrors.badRequest('Invalid page range. Offset must be 10000 or less.');
|
||||
}
|
||||
|
||||
// Build base filter: user is owner OR a member
|
||||
const baseFilter: Record<string, unknown> = {
|
||||
OR: [
|
||||
{ ownerId: session.user.id },
|
||||
{ members: { some: { userId: session.user.id } } },
|
||||
// Also include projects in workspaces where the user is a workspace member
|
||||
...(workspaceId
|
||||
? []
|
||||
: [
|
||||
{
|
||||
workspace: {
|
||||
owner: buildBillingAccessWhereInput(),
|
||||
members: { some: { userId: session.user.id } },
|
||||
},
|
||||
},
|
||||
]),
|
||||
],
|
||||
workspace: {
|
||||
owner: buildBillingAccessWhereInput(),
|
||||
},
|
||||
};
|
||||
|
||||
// Filter by workspace if provided
|
||||
if (workspaceId) {
|
||||
baseFilter.workspaceId = workspaceId;
|
||||
}
|
||||
|
||||
// Get projects where user is owner OR a member
|
||||
const [projects, total] = await Promise.all([
|
||||
db.project.findMany({
|
||||
where: baseFilter,
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
_count: { select: { videos: true, members: true } },
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
skip,
|
||||
take: limit,
|
||||
}),
|
||||
db.project.count({
|
||||
where: baseFilter,
|
||||
}),
|
||||
]);
|
||||
|
||||
const response = successResponse({ projects }, 200, {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error fetching projects:', error);
|
||||
return apiErrors.internalError('Failed to fetch projects');
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/projects - Create a new project
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'create-project');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'create-project');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, description, visibility, workspaceId } = body;
|
||||
|
||||
if (!name || typeof name !== 'string' || name.trim().length === 0) {
|
||||
return apiErrors.badRequest('Project name is required');
|
||||
}
|
||||
|
||||
if (!workspaceId || typeof workspaceId !== 'string') {
|
||||
return apiErrors.badRequest('A workspace is required. Every project must belong to a workspace.');
|
||||
}
|
||||
|
||||
// Generate URL-friendly slug
|
||||
const baseSlug = name
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^a-z0-9\s-]/g, '')
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/-+/g, '-');
|
||||
|
||||
// Find all existing slugs with the same prefix in a single query
|
||||
const existingProjects = await db.project.findMany({
|
||||
where: { slug: { startsWith: baseSlug } },
|
||||
select: { slug: true },
|
||||
});
|
||||
|
||||
// Generate unique slug from the results
|
||||
const usedSlugs = new Set(existingProjects.map(p => p.slug));
|
||||
let slug = baseSlug;
|
||||
let counter = 1;
|
||||
while (usedSlugs.has(slug)) {
|
||||
slug = `${baseSlug}-${counter}`;
|
||||
counter++;
|
||||
}
|
||||
|
||||
// Verify user has access to the workspace
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Only workspace owners and admins can create projects');
|
||||
}
|
||||
|
||||
const project = await db.$transaction(async (tx) => {
|
||||
const createdProject = await tx.project.create({
|
||||
data: {
|
||||
name: name.trim(),
|
||||
description: description?.trim() || null,
|
||||
slug,
|
||||
visibility: visibility || ProjectVisibility.PRIVATE,
|
||||
ownerId: workspace.ownerId,
|
||||
workspaceId,
|
||||
},
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
_count: { select: { videos: true, members: true } },
|
||||
},
|
||||
});
|
||||
|
||||
await tx.commentTag.createMany({
|
||||
data: DEFAULT_COMMENT_TAGS.map((tag) => ({
|
||||
...tag,
|
||||
projectId: createdProject.id,
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
|
||||
return createdProject;
|
||||
});
|
||||
|
||||
const response = successResponse(project, 201);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error creating project:', error);
|
||||
return apiErrors.internalError('Failed to create project');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, description, visibility, workspaceId } = body;
|
||||
|
||||
if (!name || typeof name !== 'string' || name.trim().length === 0) {
|
||||
return apiErrors.badRequest('Project name is required');
|
||||
}
|
||||
|
||||
if (!workspaceId || typeof workspaceId !== 'string') {
|
||||
return apiErrors.badRequest(
|
||||
'A workspace is required. Every project must belong to a workspace.'
|
||||
);
|
||||
}
|
||||
|
||||
// Generate URL-friendly slug
|
||||
const baseSlug = name
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^a-z0-9\s-]/g, '')
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/-+/g, '-');
|
||||
|
||||
// Find all existing slugs with the same prefix in a single query
|
||||
const existingProjects = await db.project.findMany({
|
||||
where: { slug: { startsWith: baseSlug } },
|
||||
select: { slug: true },
|
||||
});
|
||||
|
||||
// Generate unique slug from the results
|
||||
const usedSlugs = new Set(existingProjects.map((p) => p.slug));
|
||||
let slug = baseSlug;
|
||||
let counter = 1;
|
||||
while (usedSlugs.has(slug)) {
|
||||
slug = `${baseSlug}-${counter}`;
|
||||
counter++;
|
||||
}
|
||||
|
||||
// Verify user has access to the workspace
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Only workspace owners and admins can create projects');
|
||||
}
|
||||
|
||||
const project = await db.$transaction(async (tx) => {
|
||||
const createdProject = await tx.project.create({
|
||||
data: {
|
||||
name: name.trim(),
|
||||
description: description?.trim() || null,
|
||||
slug,
|
||||
visibility: visibility || ProjectVisibility.PRIVATE,
|
||||
ownerId: workspace.ownerId,
|
||||
workspaceId,
|
||||
},
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
_count: { select: { videos: true, members: true } },
|
||||
},
|
||||
});
|
||||
|
||||
await tx.commentTag.createMany({
|
||||
data: DEFAULT_COMMENT_TAGS.map((tag) => ({
|
||||
...tag,
|
||||
projectId: createdProject.id,
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
|
||||
return createdProject;
|
||||
});
|
||||
|
||||
const response = successResponse(project, 201);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error creating project:', error);
|
||||
return apiErrors.internalError('Failed to create project');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,10 +21,10 @@ export async function GET(request: NextRequest) {
|
||||
const cfg = RATE_LIMIT_CONFIGS['search'];
|
||||
const rl = await checkRateLimit(userId, 'search', cfg);
|
||||
if (!rl.allowed) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Too many requests. Please try again later.' }),
|
||||
{ status: 429, headers: { 'Content-Type': 'application/json', ...rateLimitHeaders(rl, cfg.maxRequests) } }
|
||||
);
|
||||
return new Response(JSON.stringify({ error: 'Too many requests. Please try again later.' }), {
|
||||
status: 429,
|
||||
headers: { 'Content-Type': 'application/json', ...rateLimitHeaders(rl, cfg.maxRequests) },
|
||||
});
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
@@ -48,10 +48,7 @@ export async function GET(request: NextRequest) {
|
||||
};
|
||||
|
||||
const workspaceAccessFilter = {
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{ members: { some: { userId } } },
|
||||
],
|
||||
OR: [{ ownerId: userId }, { members: { some: { userId } } }],
|
||||
};
|
||||
|
||||
const [projects, workspaces, videos] = await Promise.all([
|
||||
|
||||
@@ -9,206 +9,211 @@ import { logError } from '@/lib/logger';
|
||||
|
||||
// GET /api/settings/notifications — Fetch current notification preferences
|
||||
export async function GET() {
|
||||
try {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const settings = await db.notificationSetting.findUnique({
|
||||
where: { userId: session.user.id },
|
||||
});
|
||||
|
||||
// Return defaults if no settings exist yet
|
||||
const response = successResponse(
|
||||
settings ?? {
|
||||
telegramChatId: null,
|
||||
telegramEnabled: false,
|
||||
emailEnabled: false,
|
||||
onNewVideo: true,
|
||||
onNewVersion: true,
|
||||
onNewComment: true,
|
||||
onNewReply: true,
|
||||
onApprovalEvents: true,
|
||||
timezone: 'UTC',
|
||||
}
|
||||
);
|
||||
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error fetching notification settings:', error);
|
||||
return apiErrors.internalError('Failed to fetch settings');
|
||||
try {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const settings = await db.notificationSetting.findUnique({
|
||||
where: { userId: session.user.id },
|
||||
});
|
||||
|
||||
// Return defaults if no settings exist yet
|
||||
const response = successResponse(
|
||||
settings ?? {
|
||||
telegramChatId: null,
|
||||
telegramEnabled: false,
|
||||
emailEnabled: false,
|
||||
onNewVideo: true,
|
||||
onNewVersion: true,
|
||||
onNewComment: true,
|
||||
onNewReply: true,
|
||||
onApprovalEvents: true,
|
||||
timezone: 'UTC',
|
||||
}
|
||||
);
|
||||
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error fetching notification settings:', error);
|
||||
return apiErrors.internalError('Failed to fetch settings');
|
||||
}
|
||||
}
|
||||
|
||||
// PUT /api/settings/notifications — Update notification preferences
|
||||
export async function PUT(request: NextRequest) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const {
|
||||
telegramChatId,
|
||||
telegramEnabled,
|
||||
emailEnabled,
|
||||
onNewVideo,
|
||||
onNewVersion,
|
||||
onNewComment,
|
||||
onNewReply,
|
||||
onApprovalEvents,
|
||||
timezone,
|
||||
} = body;
|
||||
|
||||
// Validate: if enabling Telegram, chatId is required and must be a valid Telegram ID
|
||||
if (telegramChatId && !/^-?\d{1,20}$/.test(telegramChatId)) {
|
||||
return apiErrors.badRequest('Invalid Chat ID format');
|
||||
}
|
||||
if (telegramEnabled && !telegramChatId) {
|
||||
return apiErrors.badRequest('Chat ID is required to enable Telegram notifications');
|
||||
}
|
||||
|
||||
const settings = await db.notificationSetting.upsert({
|
||||
where: { userId: session.user.id },
|
||||
create: {
|
||||
userId: session.user.id,
|
||||
telegramChatId: telegramChatId || null,
|
||||
telegramEnabled: !!telegramEnabled,
|
||||
emailEnabled: !!emailEnabled,
|
||||
onNewVideo: onNewVideo ?? true,
|
||||
onNewVersion: onNewVersion ?? true,
|
||||
onNewComment: onNewComment ?? true,
|
||||
onNewReply: onNewReply ?? true,
|
||||
onApprovalEvents: onApprovalEvents ?? true,
|
||||
timezone: timezone || 'UTC',
|
||||
},
|
||||
update: {
|
||||
telegramChatId: telegramChatId || null,
|
||||
telegramEnabled: !!telegramEnabled,
|
||||
emailEnabled: !!emailEnabled,
|
||||
onNewVideo: onNewVideo ?? true,
|
||||
onNewVersion: onNewVersion ?? true,
|
||||
onNewComment: onNewComment ?? true,
|
||||
onNewReply: onNewReply ?? true,
|
||||
onApprovalEvents: onApprovalEvents ?? true,
|
||||
timezone: timezone || 'UTC',
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(settings);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating notification settings:', error);
|
||||
return apiErrors.internalError('Failed to update settings');
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const {
|
||||
telegramChatId,
|
||||
telegramEnabled,
|
||||
emailEnabled,
|
||||
onNewVideo,
|
||||
onNewVersion,
|
||||
onNewComment,
|
||||
onNewReply,
|
||||
onApprovalEvents,
|
||||
timezone,
|
||||
} = body;
|
||||
|
||||
// Validate: if enabling Telegram, chatId is required and must be a valid Telegram ID
|
||||
if (telegramChatId && !/^-?\d{1,20}$/.test(telegramChatId)) {
|
||||
return apiErrors.badRequest('Invalid Chat ID format');
|
||||
}
|
||||
if (telegramEnabled && !telegramChatId) {
|
||||
return apiErrors.badRequest('Chat ID is required to enable Telegram notifications');
|
||||
}
|
||||
|
||||
const settings = await db.notificationSetting.upsert({
|
||||
where: { userId: session.user.id },
|
||||
create: {
|
||||
userId: session.user.id,
|
||||
telegramChatId: telegramChatId || null,
|
||||
telegramEnabled: !!telegramEnabled,
|
||||
emailEnabled: !!emailEnabled,
|
||||
onNewVideo: onNewVideo ?? true,
|
||||
onNewVersion: onNewVersion ?? true,
|
||||
onNewComment: onNewComment ?? true,
|
||||
onNewReply: onNewReply ?? true,
|
||||
onApprovalEvents: onApprovalEvents ?? true,
|
||||
timezone: timezone || 'UTC',
|
||||
},
|
||||
update: {
|
||||
telegramChatId: telegramChatId || null,
|
||||
telegramEnabled: !!telegramEnabled,
|
||||
emailEnabled: !!emailEnabled,
|
||||
onNewVideo: onNewVideo ?? true,
|
||||
onNewVersion: onNewVersion ?? true,
|
||||
onNewComment: onNewComment ?? true,
|
||||
onNewReply: onNewReply ?? true,
|
||||
onApprovalEvents: onApprovalEvents ?? true,
|
||||
timezone: timezone || 'UTC',
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(settings);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating notification settings:', error);
|
||||
return apiErrors.internalError('Failed to update settings');
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/settings/notifications — Test a notification channel
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { channel, telegramChatId } = body;
|
||||
|
||||
if (channel === 'telegram') {
|
||||
const telegramBotToken = process.env.TELEGRAM_BOT_TOKEN;
|
||||
if (!telegramBotToken) {
|
||||
return apiErrors.internalError('Telegram bot not configured (TELEGRAM_BOT_TOKEN missing)');
|
||||
}
|
||||
if (!telegramChatId) {
|
||||
return apiErrors.badRequest('Chat ID is required');
|
||||
}
|
||||
if (!/^-?\d{1,20}$/.test(telegramChatId)) {
|
||||
return apiErrors.badRequest('Invalid Chat ID format');
|
||||
}
|
||||
|
||||
const settingsUrl = `${process.env.NEXTAUTH_URL || ''}/settings`;
|
||||
const telegramPayload: Record<string, unknown> = {
|
||||
chat_id: telegramChatId,
|
||||
text: '✅ OpenFrame notifications connected successfully!\n\nYou will receive notifications here when activity happens on your projects.',
|
||||
link_preview_options: { is_disabled: true },
|
||||
};
|
||||
// Telegram inline keyboard buttons require HTTPS URLs
|
||||
if (settingsUrl.startsWith('https://')) {
|
||||
telegramPayload.reply_markup = {
|
||||
inline_keyboard: [[{ text: 'Open Settings', url: settingsUrl }]],
|
||||
};
|
||||
}
|
||||
const res = await fetch(`https://api.telegram.org/bot${telegramBotToken}/sendMessage`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(telegramPayload),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
logError('Telegram test failed:', (data as { description?: string }).description);
|
||||
return apiErrors.badRequest('Telegram test failed: check that the Chat ID is correct and the bot has been started');
|
||||
}
|
||||
|
||||
const response = successResponse({ message: 'Test message sent to Telegram' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
}
|
||||
|
||||
if (channel === 'email') {
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { email: true },
|
||||
});
|
||||
|
||||
if (!user?.email) {
|
||||
return apiErrors.badRequest('No email address on your account');
|
||||
}
|
||||
|
||||
const smtpHost = process.env.SMTP_HOST;
|
||||
const smtpPort = Number(process.env.SMTP_PORT || '587');
|
||||
const smtpUser = process.env.SMTP_USER;
|
||||
const smtpPass = process.env.SMTP_PASSWORD;
|
||||
|
||||
if (!smtpHost || !smtpUser || !smtpPass) {
|
||||
return apiErrors.internalError('Email service not configured (SMTP settings missing)');
|
||||
}
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: smtpHost,
|
||||
port: smtpPort,
|
||||
secure: smtpPort === 465,
|
||||
auth: { user: smtpUser, pass: smtpPass },
|
||||
});
|
||||
|
||||
const fromAddress = process.env.SMTP_FROM || process.env.EMAIL_FROM || 'OpenFrame <[email protected]>';
|
||||
|
||||
try {
|
||||
await transporter.sendMail({
|
||||
from: fromAddress,
|
||||
to: user.email,
|
||||
subject: '[OpenFrame] Test notification',
|
||||
html: testEmailHtml(),
|
||||
});
|
||||
} catch (emailErr) {
|
||||
logError('SMTP test email failed:', emailErr);
|
||||
return apiErrors.internalError('Failed to send test email — check SMTP settings');
|
||||
}
|
||||
|
||||
const response = successResponse({ message: `Test email sent to ${user.email}` });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
}
|
||||
|
||||
return apiErrors.badRequest('Unknown channel');
|
||||
} catch (error) {
|
||||
logError('Error testing notification:', error);
|
||||
return apiErrors.internalError('Failed to test notification');
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { channel, telegramChatId } = body;
|
||||
|
||||
if (channel === 'telegram') {
|
||||
const telegramBotToken = process.env.TELEGRAM_BOT_TOKEN;
|
||||
if (!telegramBotToken) {
|
||||
return apiErrors.internalError('Telegram bot not configured (TELEGRAM_BOT_TOKEN missing)');
|
||||
}
|
||||
if (!telegramChatId) {
|
||||
return apiErrors.badRequest('Chat ID is required');
|
||||
}
|
||||
if (!/^-?\d{1,20}$/.test(telegramChatId)) {
|
||||
return apiErrors.badRequest('Invalid Chat ID format');
|
||||
}
|
||||
|
||||
const settingsUrl = `${process.env.NEXTAUTH_URL || ''}/settings`;
|
||||
const telegramPayload: Record<string, unknown> = {
|
||||
chat_id: telegramChatId,
|
||||
text: '✅ OpenFrame notifications connected successfully!\n\nYou will receive notifications here when activity happens on your projects.',
|
||||
link_preview_options: { is_disabled: true },
|
||||
};
|
||||
// Telegram inline keyboard buttons require HTTPS URLs
|
||||
if (settingsUrl.startsWith('https://')) {
|
||||
telegramPayload.reply_markup = {
|
||||
inline_keyboard: [[{ text: 'Open Settings', url: settingsUrl }]],
|
||||
};
|
||||
}
|
||||
const res = await fetch(`https://api.telegram.org/bot${telegramBotToken}/sendMessage`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(telegramPayload),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
logError('Telegram test failed:', (data as { description?: string }).description);
|
||||
return apiErrors.badRequest(
|
||||
'Telegram test failed: check that the Chat ID is correct and the bot has been started'
|
||||
);
|
||||
}
|
||||
|
||||
const response = successResponse({ message: 'Test message sent to Telegram' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
}
|
||||
|
||||
if (channel === 'email') {
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { email: true },
|
||||
});
|
||||
|
||||
if (!user?.email) {
|
||||
return apiErrors.badRequest('No email address on your account');
|
||||
}
|
||||
|
||||
const smtpHost = process.env.SMTP_HOST;
|
||||
const smtpPort = Number(process.env.SMTP_PORT || '587');
|
||||
const smtpUser = process.env.SMTP_USER;
|
||||
const smtpPass = process.env.SMTP_PASSWORD;
|
||||
|
||||
if (!smtpHost || !smtpUser || !smtpPass) {
|
||||
return apiErrors.internalError('Email service not configured (SMTP settings missing)');
|
||||
}
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: smtpHost,
|
||||
port: smtpPort,
|
||||
secure: smtpPort === 465,
|
||||
auth: { user: smtpUser, pass: smtpPass },
|
||||
});
|
||||
|
||||
const fromAddress =
|
||||
process.env.SMTP_FROM ||
|
||||
process.env.EMAIL_FROM ||
|
||||
'OpenFrame <[email protected]>';
|
||||
|
||||
try {
|
||||
await transporter.sendMail({
|
||||
from: fromAddress,
|
||||
to: user.email,
|
||||
subject: '[OpenFrame] Test notification',
|
||||
html: testEmailHtml(),
|
||||
});
|
||||
} catch (emailErr) {
|
||||
logError('SMTP test email failed:', emailErr);
|
||||
return apiErrors.internalError('Failed to send test email — check SMTP settings');
|
||||
}
|
||||
|
||||
const response = successResponse({ message: `Test email sent to ${user.email}` });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
}
|
||||
|
||||
return apiErrors.badRequest('Unknown channel');
|
||||
} catch (error) {
|
||||
logError('Error testing notification:', error);
|
||||
return apiErrors.internalError('Failed to test notification');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import type Stripe from 'stripe';
|
||||
import {
|
||||
markSubscriptionCanceledByCustomerId,
|
||||
syncStripeSubscriptionToUser,
|
||||
} from '@/lib/billing';
|
||||
import { markSubscriptionCanceledByCustomerId, syncStripeSubscriptionToUser } from '@/lib/billing';
|
||||
import { getStripe, getStripeWebhookSecret } from '@/lib/stripe';
|
||||
import { logError } from '@/lib/logger';
|
||||
|
||||
@@ -11,9 +8,7 @@ export const runtime = 'nodejs';
|
||||
|
||||
async function handleSubscriptionDeleted(subscription: Stripe.Subscription) {
|
||||
const customerId =
|
||||
typeof subscription.customer === 'string'
|
||||
? subscription.customer
|
||||
: subscription.customer.id;
|
||||
typeof subscription.customer === 'string' ? subscription.customer : subscription.customer.id;
|
||||
|
||||
const currentPeriodEnd =
|
||||
'current_period_end' in subscription && typeof subscription.current_period_end === 'number'
|
||||
|
||||
@@ -77,12 +77,12 @@ export async function GET(
|
||||
const shareSession = getShareSessionFromRequest(request, video.id);
|
||||
const shareAccess = shareSession
|
||||
? await validateShareLinkAccess({
|
||||
token: shareSession.token,
|
||||
projectId: video.projectId,
|
||||
videoId: video.id,
|
||||
requiredPermission: 'VIEW',
|
||||
passwordVerified: shareSession.passwordVerified,
|
||||
})
|
||||
token: shareSession.token,
|
||||
projectId: video.projectId,
|
||||
videoId: video.id,
|
||||
requiredPermission: 'VIEW',
|
||||
passwordVerified: shareSession.passwordVerified,
|
||||
})
|
||||
: null;
|
||||
|
||||
if (!shareAccess?.hasAccess) {
|
||||
|
||||
@@ -17,10 +17,17 @@ import { reserveStorageQuota, releaseStorageReservation } from '@/lib/storage-qu
|
||||
import { logError } from '@/lib/logger';
|
||||
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
|
||||
const MAX_MULTIPART_BODY_SIZE = MAX_FILE_SIZE + (512 * 1024); // file + multipart overhead
|
||||
const MAX_MULTIPART_BODY_SIZE = MAX_FILE_SIZE + 512 * 1024; // file + multipart overhead
|
||||
|
||||
// Canonical MIME types accepted
|
||||
const ALLOWED_TYPES = new Set(['audio/webm', 'audio/ogg', 'audio/opus', 'audio/mp4', 'audio/mpeg', 'audio/wav']);
|
||||
const ALLOWED_TYPES = new Set([
|
||||
'audio/webm',
|
||||
'audio/ogg',
|
||||
'audio/opus',
|
||||
'audio/mp4',
|
||||
'audio/mpeg',
|
||||
'audio/wav',
|
||||
]);
|
||||
|
||||
// Normalize known MIME aliases to canonical values
|
||||
const MIME_ALIASES: Record<string, string> = {
|
||||
@@ -49,7 +56,11 @@ const SAFE_AUDIO_EXTENSIONS = new Set(['webm', 'ogg', 'opus', 'mp3', 'm4a', 'mp4
|
||||
|
||||
// Reject content that looks like HTML/XML/script regardless of the declared MIME type.
|
||||
function isHtmlContent(bytes: Buffer): boolean {
|
||||
const snippet = bytes.toString('latin1', 0, Math.min(bytes.length, 512)).trimStart().slice(0, 50).toLowerCase();
|
||||
const snippet = bytes
|
||||
.toString('latin1', 0, Math.min(bytes.length, 512))
|
||||
.trimStart()
|
||||
.slice(0, 50)
|
||||
.toLowerCase();
|
||||
return (
|
||||
snippet.startsWith('<!doctype') ||
|
||||
snippet.startsWith('<html') ||
|
||||
@@ -133,15 +144,22 @@ export async function POST(request: NextRequest) {
|
||||
const shareSession = getShareSessionFromRequest(request, safeVideoId);
|
||||
const shareAccess = shareSession
|
||||
? await validateShareLinkAccess({
|
||||
token: shareSession.token,
|
||||
projectId: video.projectId,
|
||||
videoId: safeVideoId,
|
||||
requiredPermission: 'COMMENT',
|
||||
passwordVerified: shareSession.passwordVerified,
|
||||
})
|
||||
: { hasAccess: false, canComment: false, canDownload: false, allowGuests: false, requiresPassword: false };
|
||||
token: shareSession.token,
|
||||
projectId: video.projectId,
|
||||
videoId: safeVideoId,
|
||||
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 && (session?.user?.id ? true : shareAccess.allowGuests);
|
||||
const canCommentWithShareLink =
|
||||
shareAccess.canComment && (session?.user?.id ? true : shareAccess.allowGuests);
|
||||
if (!canCommentWithMembership && !canCommentWithShareLink) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
@@ -166,7 +184,12 @@ export async function POST(request: NextRequest) {
|
||||
return apiErrors.forbidden('Invalid upload token');
|
||||
}
|
||||
|
||||
const quotaError = await enforceGuestUploadQuota(request, safeVideoId, 'audio', shareSession?.token ?? null);
|
||||
const quotaError = await enforceGuestUploadQuota(
|
||||
request,
|
||||
safeVideoId,
|
||||
'audio',
|
||||
shareSession?.token ?? null
|
||||
);
|
||||
if (quotaError) return quotaError;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,97 +11,97 @@ import { logError } from '@/lib/logger';
|
||||
const SAFE_FILENAME = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[a-z0-9]+$/i;
|
||||
|
||||
const CONTENT_TYPE_MAP: Record<string, string> = {
|
||||
jpeg: 'image/jpeg',
|
||||
jpg: 'image/jpeg',
|
||||
png: 'image/png',
|
||||
webp: 'image/webp',
|
||||
gif: 'image/gif',
|
||||
jpeg: 'image/jpeg',
|
||||
jpg: 'image/jpeg',
|
||||
png: 'image/png',
|
||||
webp: 'image/webp',
|
||||
gif: 'image/gif',
|
||||
};
|
||||
function getContentType(filename: string): string {
|
||||
const ext = filename.split('.').pop()?.toLowerCase() || '';
|
||||
return CONTENT_TYPE_MAP[ext] || 'application/octet-stream';
|
||||
const ext = filename.split('.').pop()?.toLowerCase() || '';
|
||||
return CONTENT_TYPE_MAP[ext] || 'application/octet-stream';
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ filename: string }> }
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ filename: string }> }
|
||||
) {
|
||||
try {
|
||||
const { filename } = await params;
|
||||
try {
|
||||
const { filename } = await params;
|
||||
|
||||
// Validate filename to prevent path traversal
|
||||
if (!SAFE_FILENAME.test(filename)) {
|
||||
return apiErrors.badRequest('Invalid filename');
|
||||
}
|
||||
|
||||
// Parallelize the DB lookup and session check to narrow the timing delta
|
||||
// between "asset not found" and "asset found, access denied" responses.
|
||||
const imageUrl = `/api/upload/image/${filename}`;
|
||||
const projectSelect = {
|
||||
id: true,
|
||||
ownerId: true,
|
||||
workspaceId: true,
|
||||
visibility: true,
|
||||
} as const;
|
||||
const videoSelect = {
|
||||
id: true,
|
||||
projectId: true,
|
||||
project: { select: projectSelect },
|
||||
} as const;
|
||||
const [comment, videoAsset, session] = await Promise.all([
|
||||
db.comment.findFirst({
|
||||
where: { imageUrl },
|
||||
select: {
|
||||
version: {
|
||||
select: { video: { select: videoSelect } },
|
||||
},
|
||||
},
|
||||
}),
|
||||
db.videoAsset.findFirst({
|
||||
where: { sourceUrl: imageUrl },
|
||||
select: { video: { select: videoSelect } },
|
||||
}),
|
||||
auth(),
|
||||
]);
|
||||
|
||||
const video = comment?.version?.video ?? videoAsset?.video ?? null;
|
||||
if (!video) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(video.project, session?.user?.id);
|
||||
|
||||
if (!access.hasAccess) {
|
||||
const shareSession = getShareSessionFromRequest(request, video.id);
|
||||
const shareAccess = shareSession
|
||||
? await validateShareLinkAccess({
|
||||
token: shareSession.token,
|
||||
projectId: video.projectId,
|
||||
videoId: video.id,
|
||||
requiredPermission: 'VIEW',
|
||||
passwordVerified: shareSession.passwordVerified,
|
||||
})
|
||||
: null;
|
||||
|
||||
if (!shareAccess?.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
}
|
||||
|
||||
const key = `images/${filename}`;
|
||||
return proxyR2MediaObject({
|
||||
request,
|
||||
key,
|
||||
fallbackContentType: getContentType(filename),
|
||||
cacheControl: 'private, no-store',
|
||||
extraHeaders: {
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Content-Security-Policy': "default-src 'none'; sandbox",
|
||||
},
|
||||
internalErrorMessage: 'Failed to retrieve image',
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
logError('Error serving image:', error);
|
||||
return apiErrors.internalError('Failed to retrieve image');
|
||||
// Validate filename to prevent path traversal
|
||||
if (!SAFE_FILENAME.test(filename)) {
|
||||
return apiErrors.badRequest('Invalid filename');
|
||||
}
|
||||
|
||||
// Parallelize the DB lookup and session check to narrow the timing delta
|
||||
// between "asset not found" and "asset found, access denied" responses.
|
||||
const imageUrl = `/api/upload/image/${filename}`;
|
||||
const projectSelect = {
|
||||
id: true,
|
||||
ownerId: true,
|
||||
workspaceId: true,
|
||||
visibility: true,
|
||||
} as const;
|
||||
const videoSelect = {
|
||||
id: true,
|
||||
projectId: true,
|
||||
project: { select: projectSelect },
|
||||
} as const;
|
||||
const [comment, videoAsset, session] = await Promise.all([
|
||||
db.comment.findFirst({
|
||||
where: { imageUrl },
|
||||
select: {
|
||||
version: {
|
||||
select: { video: { select: videoSelect } },
|
||||
},
|
||||
},
|
||||
}),
|
||||
db.videoAsset.findFirst({
|
||||
where: { sourceUrl: imageUrl },
|
||||
select: { video: { select: videoSelect } },
|
||||
}),
|
||||
auth(),
|
||||
]);
|
||||
|
||||
const video = comment?.version?.video ?? videoAsset?.video ?? null;
|
||||
if (!video) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(video.project, session?.user?.id);
|
||||
|
||||
if (!access.hasAccess) {
|
||||
const shareSession = getShareSessionFromRequest(request, video.id);
|
||||
const shareAccess = shareSession
|
||||
? await validateShareLinkAccess({
|
||||
token: shareSession.token,
|
||||
projectId: video.projectId,
|
||||
videoId: video.id,
|
||||
requiredPermission: 'VIEW',
|
||||
passwordVerified: shareSession.passwordVerified,
|
||||
})
|
||||
: null;
|
||||
|
||||
if (!shareAccess?.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
}
|
||||
|
||||
const key = `images/${filename}`;
|
||||
return proxyR2MediaObject({
|
||||
request,
|
||||
key,
|
||||
fallbackContentType: getContentType(filename),
|
||||
cacheControl: 'private, no-store',
|
||||
extraHeaders: {
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Content-Security-Policy': "default-src 'none'; sandbox",
|
||||
},
|
||||
internalErrorMessage: 'Failed to retrieve image',
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
logError('Error serving image:', error);
|
||||
return apiErrors.internalError('Failed to retrieve image');
|
||||
}
|
||||
}
|
||||
|
||||
+167
-155
@@ -9,169 +9,181 @@ import { validateShareLinkAccess } from '@/lib/share-links';
|
||||
import { getShareSessionFromRequest } from '@/lib/share-session';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import {
|
||||
detectImageMime,
|
||||
getImageExtension,
|
||||
isAllowedImageType,
|
||||
normalizeImageMime,
|
||||
detectImageMime,
|
||||
getImageExtension,
|
||||
isAllowedImageType,
|
||||
normalizeImageMime,
|
||||
} from '@/lib/image-upload-validation';
|
||||
import {
|
||||
deriveGuestUploadContext,
|
||||
enforceGuestUploadQuota,
|
||||
verifyGuestUploadToken,
|
||||
deriveGuestUploadContext,
|
||||
enforceGuestUploadQuota,
|
||||
verifyGuestUploadToken,
|
||||
} from '@/lib/guest-upload-token';
|
||||
import { logError } from '@/lib/logger';
|
||||
import { reserveStorageQuota, releaseStorageReservation } from '@/lib/storage-quota';
|
||||
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
|
||||
const MAX_MULTIPART_BODY_SIZE = MAX_FILE_SIZE + (512 * 1024); // file + multipart overhead
|
||||
const MAX_MULTIPART_BODY_SIZE = MAX_FILE_SIZE + 512 * 1024; // file + multipart overhead
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
// Check Content-Length header BEFORE loading the file
|
||||
const contentLength = request.headers.get('content-length');
|
||||
if (!contentLength) {
|
||||
return apiErrors.badRequest('Missing Content-Length header');
|
||||
}
|
||||
const bodySize = parseInt(contentLength, 10);
|
||||
if (isNaN(bodySize) || bodySize <= 0) {
|
||||
return apiErrors.badRequest('Invalid Content-Length header');
|
||||
}
|
||||
if (bodySize > MAX_MULTIPART_BODY_SIZE) {
|
||||
return apiErrors.badRequest('File too large. Maximum size is 10MB.');
|
||||
}
|
||||
|
||||
// Rate limit
|
||||
const limited = await rateLimit(request, 'image-upload');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
|
||||
const formData = await request.formData();
|
||||
const files = formData.getAll('image');
|
||||
if (files.length !== 1) {
|
||||
return apiErrors.badRequest('No image file provided');
|
||||
}
|
||||
const file = files[0];
|
||||
const videoId = formData.get('videoId');
|
||||
const uploadToken = formData.get('uploadToken');
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
return apiErrors.badRequest('No image file provided');
|
||||
}
|
||||
if (typeof videoId !== 'string' || !videoId.trim()) {
|
||||
return apiErrors.badRequest('videoId is required');
|
||||
}
|
||||
|
||||
const safeVideoId = videoId.trim();
|
||||
const video = await db.video.findUnique({
|
||||
where: { id: safeVideoId },
|
||||
include: {
|
||||
project: {
|
||||
include: { workspace: { select: { ownerId: true } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(video.project, session?.user?.id);
|
||||
const shareSession = getShareSessionFromRequest(request, safeVideoId);
|
||||
const shareAccess = shareSession
|
||||
? await validateShareLinkAccess({
|
||||
token: shareSession.token,
|
||||
projectId: video.projectId,
|
||||
videoId: safeVideoId,
|
||||
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 && (session?.user?.id ? true : shareAccess.allowGuests);
|
||||
if (!canCommentWithMembership && !canCommentWithShareLink) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
if (!session?.user?.id) {
|
||||
if (typeof uploadToken !== 'string' || !uploadToken.trim()) {
|
||||
return apiErrors.badRequest('uploadToken is required for guest uploads');
|
||||
}
|
||||
|
||||
const expectedContext = deriveGuestUploadContext(request, shareSession?.token ?? null);
|
||||
if (!expectedContext) {
|
||||
return apiErrors.forbidden('Missing trusted client IP header');
|
||||
}
|
||||
|
||||
const isValidUploadToken = verifyGuestUploadToken(uploadToken.trim(), {
|
||||
projectId: video.projectId,
|
||||
videoId: safeVideoId,
|
||||
intent: 'image',
|
||||
context: expectedContext,
|
||||
});
|
||||
if (!isValidUploadToken) {
|
||||
return apiErrors.forbidden('Invalid upload token');
|
||||
}
|
||||
|
||||
const quotaError = await enforceGuestUploadQuota(request, safeVideoId, 'image', shareSession?.token ?? null);
|
||||
if (quotaError) return quotaError;
|
||||
}
|
||||
|
||||
// Double-check file size (defense in depth - Content-Length can be spoofed)
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
return apiErrors.badRequest('File too large. Maximum size is 10MB.');
|
||||
}
|
||||
|
||||
// Enforce per-user storage quota before uploading.
|
||||
// All paths use the advisory-locked reservation so concurrent uploads always
|
||||
// see each other's in-flight sizes, eliminating the TOCTOU race.
|
||||
const workspaceOwnerId = video.project.workspace.ownerId;
|
||||
const reserveResult = await reserveStorageQuota(workspaceOwnerId, BigInt(file.size));
|
||||
if ('error' in reserveResult) return reserveResult.error;
|
||||
const reservationId = reserveResult.reservationId;
|
||||
|
||||
// Check content type
|
||||
const normalizedMime = normalizeImageMime(file.type);
|
||||
if (normalizedMime && !isAllowedImageType(normalizedMime)) {
|
||||
await releaseStorageReservation(reservationId);
|
||||
return apiErrors.badRequest(`Unsupported image format: ${file.type}`);
|
||||
}
|
||||
|
||||
// Convert to buffer
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
const detectedMime = detectImageMime(buffer);
|
||||
if (!detectedMime) {
|
||||
await releaseStorageReservation(reservationId);
|
||||
return apiErrors.badRequest('Uploaded file content does not match an allowed image type');
|
||||
}
|
||||
|
||||
// Generate unique filename
|
||||
const ext = getImageExtension(detectedMime);
|
||||
const filename = `${randomUUID()}.${ext}`;
|
||||
const key = `images/${filename}`;
|
||||
|
||||
try {
|
||||
// Upload to R2
|
||||
await r2Client.send(
|
||||
new PutObjectCommand({
|
||||
Bucket: R2_BUCKET_NAME,
|
||||
Key: key,
|
||||
Body: buffer,
|
||||
ContentType: detectedMime,
|
||||
})
|
||||
);
|
||||
} catch (uploadError) {
|
||||
await releaseStorageReservation(reservationId);
|
||||
throw uploadError;
|
||||
}
|
||||
|
||||
// Return the URL through our proxy endpoint
|
||||
const imageUrl = `/api/upload/image/${filename}`;
|
||||
|
||||
const response = successResponse({ url: imageUrl, reservationId }, 201);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error uploading image:', error);
|
||||
return apiErrors.internalError('Failed to upload image');
|
||||
try {
|
||||
// Check Content-Length header BEFORE loading the file
|
||||
const contentLength = request.headers.get('content-length');
|
||||
if (!contentLength) {
|
||||
return apiErrors.badRequest('Missing Content-Length header');
|
||||
}
|
||||
const bodySize = parseInt(contentLength, 10);
|
||||
if (isNaN(bodySize) || bodySize <= 0) {
|
||||
return apiErrors.badRequest('Invalid Content-Length header');
|
||||
}
|
||||
if (bodySize > MAX_MULTIPART_BODY_SIZE) {
|
||||
return apiErrors.badRequest('File too large. Maximum size is 10MB.');
|
||||
}
|
||||
|
||||
// Rate limit
|
||||
const limited = await rateLimit(request, 'image-upload');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
|
||||
const formData = await request.formData();
|
||||
const files = formData.getAll('image');
|
||||
if (files.length !== 1) {
|
||||
return apiErrors.badRequest('No image file provided');
|
||||
}
|
||||
const file = files[0];
|
||||
const videoId = formData.get('videoId');
|
||||
const uploadToken = formData.get('uploadToken');
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
return apiErrors.badRequest('No image file provided');
|
||||
}
|
||||
if (typeof videoId !== 'string' || !videoId.trim()) {
|
||||
return apiErrors.badRequest('videoId is required');
|
||||
}
|
||||
|
||||
const safeVideoId = videoId.trim();
|
||||
const video = await db.video.findUnique({
|
||||
where: { id: safeVideoId },
|
||||
include: {
|
||||
project: {
|
||||
include: { workspace: { select: { ownerId: true } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(video.project, session?.user?.id);
|
||||
const shareSession = getShareSessionFromRequest(request, safeVideoId);
|
||||
const shareAccess = shareSession
|
||||
? await validateShareLinkAccess({
|
||||
token: shareSession.token,
|
||||
projectId: video.projectId,
|
||||
videoId: safeVideoId,
|
||||
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 && (session?.user?.id ? true : shareAccess.allowGuests);
|
||||
if (!canCommentWithMembership && !canCommentWithShareLink) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
if (!session?.user?.id) {
|
||||
if (typeof uploadToken !== 'string' || !uploadToken.trim()) {
|
||||
return apiErrors.badRequest('uploadToken is required for guest uploads');
|
||||
}
|
||||
|
||||
const expectedContext = deriveGuestUploadContext(request, shareSession?.token ?? null);
|
||||
if (!expectedContext) {
|
||||
return apiErrors.forbidden('Missing trusted client IP header');
|
||||
}
|
||||
|
||||
const isValidUploadToken = verifyGuestUploadToken(uploadToken.trim(), {
|
||||
projectId: video.projectId,
|
||||
videoId: safeVideoId,
|
||||
intent: 'image',
|
||||
context: expectedContext,
|
||||
});
|
||||
if (!isValidUploadToken) {
|
||||
return apiErrors.forbidden('Invalid upload token');
|
||||
}
|
||||
|
||||
const quotaError = await enforceGuestUploadQuota(
|
||||
request,
|
||||
safeVideoId,
|
||||
'image',
|
||||
shareSession?.token ?? null
|
||||
);
|
||||
if (quotaError) return quotaError;
|
||||
}
|
||||
|
||||
// Double-check file size (defense in depth - Content-Length can be spoofed)
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
return apiErrors.badRequest('File too large. Maximum size is 10MB.');
|
||||
}
|
||||
|
||||
// Enforce per-user storage quota before uploading.
|
||||
// All paths use the advisory-locked reservation so concurrent uploads always
|
||||
// see each other's in-flight sizes, eliminating the TOCTOU race.
|
||||
const workspaceOwnerId = video.project.workspace.ownerId;
|
||||
const reserveResult = await reserveStorageQuota(workspaceOwnerId, BigInt(file.size));
|
||||
if ('error' in reserveResult) return reserveResult.error;
|
||||
const reservationId = reserveResult.reservationId;
|
||||
|
||||
// Check content type
|
||||
const normalizedMime = normalizeImageMime(file.type);
|
||||
if (normalizedMime && !isAllowedImageType(normalizedMime)) {
|
||||
await releaseStorageReservation(reservationId);
|
||||
return apiErrors.badRequest(`Unsupported image format: ${file.type}`);
|
||||
}
|
||||
|
||||
// Convert to buffer
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
const detectedMime = detectImageMime(buffer);
|
||||
if (!detectedMime) {
|
||||
await releaseStorageReservation(reservationId);
|
||||
return apiErrors.badRequest('Uploaded file content does not match an allowed image type');
|
||||
}
|
||||
|
||||
// Generate unique filename
|
||||
const ext = getImageExtension(detectedMime);
|
||||
const filename = `${randomUUID()}.${ext}`;
|
||||
const key = `images/${filename}`;
|
||||
|
||||
try {
|
||||
// Upload to R2
|
||||
await r2Client.send(
|
||||
new PutObjectCommand({
|
||||
Bucket: R2_BUCKET_NAME,
|
||||
Key: key,
|
||||
Body: buffer,
|
||||
ContentType: detectedMime,
|
||||
})
|
||||
);
|
||||
} catch (uploadError) {
|
||||
await releaseStorageReservation(reservationId);
|
||||
throw uploadError;
|
||||
}
|
||||
|
||||
// Return the URL through our proxy endpoint
|
||||
const imageUrl = `/api/upload/image/${filename}`;
|
||||
|
||||
const response = successResponse({ url: imageUrl, reservationId }, 201);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error uploading image:', error);
|
||||
return apiErrors.internalError('Failed to upload image');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,28 +75,40 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
include: {
|
||||
video: {
|
||||
include: {
|
||||
project: { select: { id: true, name: true, ownerId: true, workspaceId: true, visibility: true } },
|
||||
project: {
|
||||
select: { id: true, name: true, ownerId: true, workspaceId: true, visibility: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!version) return apiErrors.notFound('Version');
|
||||
|
||||
const access = await checkProjectAccess(version.video.project, session.user.id, { intent: 'manage' });
|
||||
const access = await checkProjectAccess(version.video.project, session.user.id, {
|
||||
intent: 'manage',
|
||||
});
|
||||
if (!access.canEdit) return apiErrors.forbidden('Access denied');
|
||||
|
||||
const body = await request.json().catch(() => ({})) as { approverIds?: unknown; message?: unknown };
|
||||
const body = (await request.json().catch(() => ({}))) as {
|
||||
approverIds?: unknown;
|
||||
message?: unknown;
|
||||
};
|
||||
const message = typeof body.message === 'string' ? body.message.trim() : '';
|
||||
if (message.length > 2000) {
|
||||
return apiErrors.badRequest('Message must be 2000 characters or fewer');
|
||||
}
|
||||
|
||||
const rawApproverIds = Array.isArray(body.approverIds) ? body.approverIds : [];
|
||||
const approverIds = Array.from(new Set(
|
||||
rawApproverIds
|
||||
.filter((approverId): approverId is string => typeof approverId === 'string' && approverId.trim().length > 0)
|
||||
.map((approverId) => approverId.trim())
|
||||
));
|
||||
const approverIds = Array.from(
|
||||
new Set(
|
||||
rawApproverIds
|
||||
.filter(
|
||||
(approverId): approverId is string =>
|
||||
typeof approverId === 'string' && approverId.trim().length > 0
|
||||
)
|
||||
.map((approverId) => approverId.trim())
|
||||
)
|
||||
);
|
||||
|
||||
if (approverIds.length === 0) {
|
||||
return apiErrors.badRequest('At least one approver is required');
|
||||
@@ -114,43 +126,46 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.badRequest('One or more approvers are not eligible for this project');
|
||||
}
|
||||
|
||||
const created = await db.$transaction(async (tx) => {
|
||||
const existingPending = await tx.approvalRequest.findFirst({
|
||||
where: { versionId, status: 'PENDING' },
|
||||
select: { id: true },
|
||||
});
|
||||
if (existingPending) {
|
||||
throw new Error('__PENDING_REQUEST_EXISTS__');
|
||||
}
|
||||
const created = await db.$transaction(
|
||||
async (tx) => {
|
||||
const existingPending = await tx.approvalRequest.findFirst({
|
||||
where: { versionId, status: 'PENDING' },
|
||||
select: { id: true },
|
||||
});
|
||||
if (existingPending) {
|
||||
throw new Error('__PENDING_REQUEST_EXISTS__');
|
||||
}
|
||||
|
||||
return tx.approvalRequest.create({
|
||||
data: {
|
||||
versionId,
|
||||
requestedById: session.user.id,
|
||||
message: message || null,
|
||||
decisions: {
|
||||
createMany: {
|
||||
data: approverIds.map((approverId) => ({
|
||||
approverId,
|
||||
status: 'PENDING',
|
||||
})),
|
||||
return tx.approvalRequest.create({
|
||||
data: {
|
||||
versionId,
|
||||
requestedById: session.user.id,
|
||||
message: message || null,
|
||||
decisions: {
|
||||
createMany: {
|
||||
data: approverIds.map((approverId) => ({
|
||||
approverId,
|
||||
status: 'PENDING',
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
include: {
|
||||
requestedBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
canceledBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
decisions: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
include: {
|
||||
approver: { select: { id: true, name: true, email: true, image: true } },
|
||||
include: {
|
||||
requestedBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
canceledBy: { select: { id: true, name: true, email: true, image: true } },
|
||||
decisions: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
include: {
|
||||
approver: { select: { id: true, name: true, email: true, image: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}, {
|
||||
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
|
||||
});
|
||||
});
|
||||
},
|
||||
{
|
||||
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
|
||||
}
|
||||
);
|
||||
|
||||
const requesterName = session.user.name || 'A team member';
|
||||
const versionLabel = version.versionLabel || `Version ${version.versionNumber}`;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -48,7 +48,10 @@ function buildBunnySourceCacheKey(
|
||||
return `${videoId}:${requestedQuality ?? 'none'}:${sourcePreference}`;
|
||||
}
|
||||
|
||||
function getCachedBunnyDownloadSource(cacheKey: string, now: number): BunnyDownloadSource | null | undefined {
|
||||
function getCachedBunnyDownloadSource(
|
||||
cacheKey: string,
|
||||
now: number
|
||||
): BunnyDownloadSource | null | undefined {
|
||||
const cached = bunnyDownloadSourceCache.get(cacheKey);
|
||||
if (!cached) return undefined;
|
||||
|
||||
@@ -60,7 +63,11 @@ function getCachedBunnyDownloadSource(cacheKey: string, now: number): BunnyDownl
|
||||
return cached.source;
|
||||
}
|
||||
|
||||
function setCachedBunnyDownloadSource(cacheKey: string, source: BunnyDownloadSource | null, now: number): void {
|
||||
function setCachedBunnyDownloadSource(
|
||||
cacheKey: string,
|
||||
source: BunnyDownloadSource | null,
|
||||
now: number
|
||||
): void {
|
||||
if (bunnyDownloadSourceCache.size >= BUNNY_SOURCE_CACHE_MAX_ENTRIES) {
|
||||
// Evict the oldest entry (Maps preserve insertion order)
|
||||
const firstKey = bunnyDownloadSourceCache.keys().next().value;
|
||||
@@ -146,7 +153,10 @@ async function resolveBunnyOriginalSource(videoId: string): Promise<BunnyDownloa
|
||||
return null;
|
||||
}
|
||||
|
||||
async function resolveBunnyCompressedSource(videoId: string, requestedQuality: number | null): Promise<BunnyDownloadSource> {
|
||||
async function resolveBunnyCompressedSource(
|
||||
videoId: string,
|
||||
requestedQuality: number | null
|
||||
): Promise<BunnyDownloadSource> {
|
||||
const hostname = resolveBunnyCdnHostname();
|
||||
if (!hostname) {
|
||||
return {
|
||||
@@ -156,7 +166,11 @@ async function resolveBunnyCompressedSource(videoId: string, requestedQuality: n
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof requestedQuality === 'number' && Number.isFinite(requestedQuality) && requestedQuality > 0) {
|
||||
if (
|
||||
typeof requestedQuality === 'number' &&
|
||||
Number.isFinite(requestedQuality) &&
|
||||
requestedQuality > 0
|
||||
) {
|
||||
const requestedUrl = `https://${hostname}/${videoId}/play_${requestedQuality}p.mp4`;
|
||||
if (await isRemoteFileAvailable(requestedUrl)) {
|
||||
return {
|
||||
@@ -243,9 +257,11 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
const rawQuality = searchParams.get('quality');
|
||||
const sourceParam = searchParams.get('source');
|
||||
const sourcePreference: BunnyDownloadSourcePreference =
|
||||
sourceParam === null ? 'auto' : sourceParam === 'original' || sourceParam === 'compressed'
|
||||
? sourceParam
|
||||
: 'auto';
|
||||
sourceParam === null
|
||||
? 'auto'
|
||||
: sourceParam === 'original' || sourceParam === 'compressed'
|
||||
? sourceParam
|
||||
: 'auto';
|
||||
|
||||
const version = await db.videoVersion.findUnique({
|
||||
where: { id: versionId },
|
||||
@@ -275,13 +291,19 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
const shareSession = getShareSessionFromRequest(request, version.video.id);
|
||||
const shareAccess = shareSession
|
||||
? await validateShareLinkAccess({
|
||||
token: shareSession.token,
|
||||
projectId: version.video.projectId,
|
||||
videoId: version.video.id,
|
||||
requiredPermission: 'VIEW',
|
||||
passwordVerified: shareSession.passwordVerified,
|
||||
})
|
||||
: { hasAccess: false, canComment: false, canDownload: false, allowGuests: false, requiresPassword: false };
|
||||
token: shareSession.token,
|
||||
projectId: version.video.projectId,
|
||||
videoId: version.video.id,
|
||||
requiredPermission: 'VIEW',
|
||||
passwordVerified: shareSession.passwordVerified,
|
||||
})
|
||||
: {
|
||||
hasAccess: false,
|
||||
canComment: false,
|
||||
canDownload: false,
|
||||
allowGuests: false,
|
||||
requiresPassword: false,
|
||||
};
|
||||
const canDownloadViaShareLink = shareAccess.hasAccess && shareAccess.canDownload;
|
||||
if (!access.hasAccess && !canDownloadViaShareLink) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
@@ -299,7 +321,9 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
rawQuality !== null &&
|
||||
(!Number.isFinite(requestedQuality) || !BUNNY_ALLOWED_QUALITIES.has(requestedQuality))
|
||||
) {
|
||||
return apiErrors.badRequest('Invalid quality. Allowed values: 2160, 1440, 1080, 720, 480, 360, 240');
|
||||
return apiErrors.badRequest(
|
||||
'Invalid quality. Allowed values: 2160, 1440, 1080, 720, 480, 360, 240'
|
||||
);
|
||||
}
|
||||
|
||||
if (rawQuality !== null && sourcePreference === 'original') {
|
||||
@@ -349,7 +373,10 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
workspaceId: version.video.project.workspace.id,
|
||||
billedUserId: version.video.project.workspace.ownerId,
|
||||
downloaderUserId: session?.user?.id ?? null,
|
||||
source: source.sourceType === 'original' ? DownloadEgressSource.ORIGINAL : DownloadEgressSource.COMPRESSED,
|
||||
source:
|
||||
source.sourceType === 'original'
|
||||
? DownloadEgressSource.ORIGINAL
|
||||
: DownloadEgressSource.COMPRESSED,
|
||||
quality: source.quality,
|
||||
estimatedBytes,
|
||||
},
|
||||
|
||||
@@ -152,10 +152,12 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.badRequest('Invalid source. Allowed values: original, compressed');
|
||||
}
|
||||
if (
|
||||
rawQuality !== null
|
||||
&& (!Number.isFinite(requestedQuality) || !BUNNY_ALLOWED_QUALITIES.has(requestedQuality))
|
||||
rawQuality !== null &&
|
||||
(!Number.isFinite(requestedQuality) || !BUNNY_ALLOWED_QUALITIES.has(requestedQuality))
|
||||
) {
|
||||
return apiErrors.badRequest('Invalid quality. Allowed values: 2160, 1440, 1080, 720, 480, 360, 240');
|
||||
return apiErrors.badRequest(
|
||||
'Invalid quality. Allowed values: 2160, 1440, 1080, 720, 480, 360, 240'
|
||||
);
|
||||
}
|
||||
if (rawQuality !== null && sourcePreference === 'original') {
|
||||
return apiErrors.badRequest('Quality cannot be used when source=original');
|
||||
|
||||
@@ -6,10 +6,7 @@ import { db } from '@/lib/db';
|
||||
import { cleanupBunnyStreamVideosBestEffort } from '@/lib/bunny-stream-cleanup';
|
||||
import { deleteMediaFilesBestEffort } from '@/lib/r2-cleanup';
|
||||
import { buildCleanupWarnings, logCleanupWarnings } from '@/lib/cleanup-warnings';
|
||||
import {
|
||||
canDeleteAssetForViewer,
|
||||
getVideoAssetAccessContext,
|
||||
} from '@/lib/video-assets';
|
||||
import { canDeleteAssetForViewer, getVideoAssetAccessContext } from '@/lib/video-assets';
|
||||
import { logError } from '@/lib/logger';
|
||||
|
||||
type RouteParams = { params: Promise<{ videoId: string; assetId: string }> };
|
||||
@@ -72,12 +69,16 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
r2CleanupResult = await deleteMediaFilesBestEffort([asset.sourceUrl]);
|
||||
}
|
||||
|
||||
let bunnyCleanupResult: Awaited<ReturnType<typeof cleanupBunnyStreamVideosBestEffort>> | undefined;
|
||||
let bunnyCleanupResult:
|
||||
| Awaited<ReturnType<typeof cleanupBunnyStreamVideosBestEffort>>
|
||||
| undefined;
|
||||
if (asset.provider === VideoAssetProvider.BUNNY && asset.providerVideoId) {
|
||||
bunnyCleanupResult = await cleanupBunnyStreamVideosBestEffort([{
|
||||
providerId: 'bunny',
|
||||
videoId: asset.providerVideoId,
|
||||
}]);
|
||||
bunnyCleanupResult = await cleanupBunnyStreamVideosBestEffort([
|
||||
{
|
||||
providerId: 'bunny',
|
||||
videoId: asset.providerVideoId,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
const cleanupInput = {
|
||||
|
||||
@@ -43,12 +43,18 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
|
||||
const shareSession = getShareSessionFromRequest(request, context.video.id);
|
||||
if (!context.viewerUserId) {
|
||||
const quotaError = await enforceGuestUploadQuota(request, context.video.id, 'bunny', shareSession?.token ?? null);
|
||||
const quotaError = await enforceGuestUploadQuota(
|
||||
request,
|
||||
context.video.id,
|
||||
'bunny',
|
||||
shareSession?.token ?? null
|
||||
);
|
||||
if (quotaError) return quotaError;
|
||||
}
|
||||
|
||||
const apiKey = process.env.BUNNY_STREAM_API_KEY;
|
||||
const libraryId = process.env.BUNNY_STREAM_LIBRARY_ID || process.env.NEXT_PUBLIC_BUNNY_STREAM_LIBRARY_ID;
|
||||
const libraryId =
|
||||
process.env.BUNNY_STREAM_LIBRARY_ID || process.env.NEXT_PUBLIC_BUNNY_STREAM_LIBRARY_ID;
|
||||
if (!apiKey || !libraryId) {
|
||||
return apiErrors.internalError('Bunny Stream is not configured correctly');
|
||||
}
|
||||
@@ -81,23 +87,29 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
|
||||
let uploadToken = '';
|
||||
if (context.viewerUserId) {
|
||||
uploadToken = createBunnyUploadToken({
|
||||
userId: context.viewerUserId,
|
||||
projectId: context.video.projectId,
|
||||
videoId: bunnyVideoId,
|
||||
}, 3600);
|
||||
uploadToken = createBunnyUploadToken(
|
||||
{
|
||||
userId: context.viewerUserId,
|
||||
projectId: context.video.projectId,
|
||||
videoId: bunnyVideoId,
|
||||
},
|
||||
3600
|
||||
);
|
||||
} else {
|
||||
const expectedContext = deriveGuestUploadContext(request, shareSession?.token ?? null);
|
||||
if (!expectedContext) {
|
||||
return apiErrors.forbidden('Missing trusted client IP header');
|
||||
}
|
||||
|
||||
uploadToken = createGuestUploadToken({
|
||||
projectId: context.video.projectId,
|
||||
videoId: context.video.id,
|
||||
intent: 'bunny',
|
||||
context: expectedContext,
|
||||
}, 3600);
|
||||
uploadToken = createGuestUploadToken(
|
||||
{
|
||||
projectId: context.video.projectId,
|
||||
videoId: context.video.id,
|
||||
intent: 'bunny',
|
||||
context: expectedContext,
|
||||
},
|
||||
3600
|
||||
);
|
||||
}
|
||||
|
||||
const response = successResponse({
|
||||
|
||||
@@ -25,7 +25,12 @@ import {
|
||||
sanitizeAssetDisplayName,
|
||||
} from '@/lib/video-assets';
|
||||
import { logError } from '@/lib/logger';
|
||||
import { enforceStorageQuota, reserveStorageQuota, releaseStorageReservation, PLAN_STORAGE_LIMIT_BYTES } from '@/lib/storage-quota';
|
||||
import {
|
||||
enforceStorageQuota,
|
||||
reserveStorageQuota,
|
||||
releaseStorageReservation,
|
||||
PLAN_STORAGE_LIMIT_BYTES,
|
||||
} from '@/lib/storage-quota';
|
||||
import { getCachedUserBunnyStorage } from '@/lib/admin-stats';
|
||||
import { isStripeFeatureEnabled } from '@/lib/feature-flags';
|
||||
|
||||
@@ -69,10 +74,7 @@ type YouTubeTitleCacheRecord = {
|
||||
const youtubeTitleCache = new Map<string, YouTubeTitleCacheRecord>();
|
||||
|
||||
function isAllowedBunnyMediaUrl(url: string): boolean {
|
||||
const allowedHosts = new Set<string>([
|
||||
'iframe.mediadelivery.net',
|
||||
'video.bunnycdn.com',
|
||||
]);
|
||||
const allowedHosts = new Set<string>(['iframe.mediadelivery.net', 'video.bunnycdn.com']);
|
||||
const bunnyCdnHostname = resolveServerBunnyCdnHostname();
|
||||
if (bunnyCdnHostname) {
|
||||
allowedHosts.add(bunnyCdnHostname);
|
||||
@@ -87,7 +89,11 @@ function isAllowedBunnyMediaUrl(url: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function shapeAssetForViewer(asset: AssetWithViewerFields, canExposeSource: boolean, canDelete: boolean) {
|
||||
function shapeAssetForViewer(
|
||||
asset: AssetWithViewerFields,
|
||||
canExposeSource: boolean,
|
||||
canDelete: boolean
|
||||
) {
|
||||
return {
|
||||
id: asset.id,
|
||||
videoId: asset.videoId,
|
||||
@@ -161,10 +167,12 @@ async function isFreshImageAttachment(url: string): Promise<AttachmentCheck> {
|
||||
if (!key) return { isFresh: false, sizeBytes: BigInt(0) };
|
||||
|
||||
try {
|
||||
const head = await r2Client.send(new HeadObjectCommand({
|
||||
Bucket: R2_BUCKET_NAME,
|
||||
Key: key,
|
||||
}));
|
||||
const head = await r2Client.send(
|
||||
new HeadObjectCommand({
|
||||
Bucket: R2_BUCKET_NAME,
|
||||
Key: key,
|
||||
})
|
||||
);
|
||||
if (!head.LastModified) return { isFresh: false, sizeBytes: BigInt(0) };
|
||||
const isFresh = Date.now() - head.LastModified.getTime() <= UNATTACHED_UPLOAD_TTL_MS;
|
||||
return { isFresh, sizeBytes: BigInt(head.ContentLength ?? 0) };
|
||||
@@ -178,10 +186,12 @@ async function isFreshAudioAttachment(url: string): Promise<AttachmentCheck> {
|
||||
if (!key) return { isFresh: false, sizeBytes: BigInt(0) };
|
||||
|
||||
try {
|
||||
const head = await r2Client.send(new HeadObjectCommand({
|
||||
Bucket: R2_BUCKET_NAME,
|
||||
Key: key,
|
||||
}));
|
||||
const head = await r2Client.send(
|
||||
new HeadObjectCommand({
|
||||
Bucket: R2_BUCKET_NAME,
|
||||
Key: key,
|
||||
})
|
||||
);
|
||||
if (!head.LastModified) return { isFresh: false, sizeBytes: BigInt(0) };
|
||||
const isFresh = Date.now() - head.LastModified.getTime() <= UNATTACHED_UPLOAD_TTL_MS;
|
||||
return { isFresh, sizeBytes: BigInt(head.ContentLength ?? 0) };
|
||||
@@ -201,7 +211,10 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
if (!context) return apiErrors.notFound('Video');
|
||||
if (!context.hasViewAccess) return apiErrors.forbidden('Access denied');
|
||||
|
||||
const requestedLimit = parsePaginationParam(request.nextUrl.searchParams.get('limit'), ASSET_LIST_DEFAULT_LIMIT);
|
||||
const requestedLimit = parsePaginationParam(
|
||||
request.nextUrl.searchParams.get('limit'),
|
||||
ASSET_LIST_DEFAULT_LIMIT
|
||||
);
|
||||
const requestedOffset = parsePaginationParam(request.nextUrl.searchParams.get('offset'), 0);
|
||||
const limit = Math.min(ASSET_LIST_MAX_LIMIT, Math.max(1, requestedLimit));
|
||||
const offset = requestedOffset;
|
||||
@@ -215,10 +228,7 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
const etag = `"assets:${videoId}:${limit}:${offset}:${includeDeleteMetadata ? 1 : 0}:${context.canDownloadAssets ? 1 : 0}:${assetsRevision._count.id}:${assetsRevision._max.updatedAt?.getTime() ?? 0}"`;
|
||||
const ifNoneMatch = request.headers.get('if-none-match');
|
||||
if (ifNoneMatch) {
|
||||
const matches = ifNoneMatch
|
||||
.split(',')
|
||||
.map(normalizeEtag)
|
||||
.includes(normalizeEtag(etag));
|
||||
const matches = ifNoneMatch.split(',').map(normalizeEtag).includes(normalizeEtag(etag));
|
||||
if (matches) {
|
||||
const notModified = new NextResponse(null, { status: 304 });
|
||||
notModified.headers.set('ETag', etag);
|
||||
@@ -254,12 +264,15 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
const pagedAssets = hasMore ? assets.slice(0, limit) : assets;
|
||||
|
||||
const response = successResponse({
|
||||
assets: pagedAssets.map((asset) => shapeAssetForViewer(
|
||||
asset,
|
||||
// R2_AUDIO proxy URLs have no auth gate — expose them to any viewer so guests can preview audio
|
||||
context.canDownloadAssets || (asset.provider === VideoAssetProvider.R2_AUDIO && context.hasViewAccess),
|
||||
includeDeleteMetadata ? canDeleteAssetForViewer(asset, context) : false
|
||||
)),
|
||||
assets: pagedAssets.map((asset) =>
|
||||
shapeAssetForViewer(
|
||||
asset,
|
||||
// R2_AUDIO proxy URLs have no auth gate — expose them to any viewer so guests can preview audio
|
||||
context.canDownloadAssets ||
|
||||
(asset.provider === VideoAssetProvider.R2_AUDIO && context.hasViewAccess),
|
||||
includeDeleteMetadata ? canDeleteAssetForViewer(asset, context) : false
|
||||
)
|
||||
),
|
||||
pagination: {
|
||||
limit,
|
||||
offset,
|
||||
@@ -378,7 +391,10 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
|
||||
providerVideoId = parsedSource.videoId;
|
||||
const youtubeTitle = await fetchYouTubeTitle(providerVideoId);
|
||||
displayName = sanitizeAssetDisplayName(requestedDisplayName, youtubeTitle || `YouTube ${providerVideoId}`);
|
||||
displayName = sanitizeAssetDisplayName(
|
||||
requestedDisplayName,
|
||||
youtubeTitle || `YouTube ${providerVideoId}`
|
||||
);
|
||||
sourceUrl = parsedSource.originalUrl;
|
||||
thumbnailUrl = getThumbnailUrl(parsedSource, 'large');
|
||||
kind = 'VIDEO';
|
||||
@@ -386,7 +402,8 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
|
||||
if (provider === VideoAssetProvider.BUNNY) {
|
||||
sourceUrl = typeof body?.sourceUrl === 'string' ? body.sourceUrl.trim() : '';
|
||||
providerVideoId = typeof body?.providerVideoId === 'string' ? body.providerVideoId.trim() : '';
|
||||
providerVideoId =
|
||||
typeof body?.providerVideoId === 'string' ? body.providerVideoId.trim() : '';
|
||||
const uploadToken = typeof body?.uploadToken === 'string' ? body.uploadToken.trim() : '';
|
||||
thumbnailUrl = typeof body?.thumbnailUrl === 'string' ? body.thumbnailUrl.trim() : null;
|
||||
|
||||
@@ -515,10 +532,15 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
thumbnailUrl,
|
||||
sizeBytes: assetSizeBytes,
|
||||
uploadedByUserId: context.viewerUserId,
|
||||
uploadedByGuestIdentityId: context.viewerUserId ? null : guestIdentity?.identityId ?? null,
|
||||
uploadedByGuestIdentityId: context.viewerUserId
|
||||
? null
|
||||
: (guestIdentity?.identityId ?? null),
|
||||
uploadedByGuestName: context.viewerUserId
|
||||
? null
|
||||
: sanitizeAssetDisplayName(typeof body?.guestName === 'string' ? body.guestName : null, 'Guest'),
|
||||
: sanitizeAssetDisplayName(
|
||||
typeof body?.guestName === 'string' ? body.guestName : null,
|
||||
'Guest'
|
||||
),
|
||||
billedUserId,
|
||||
},
|
||||
select: {
|
||||
@@ -540,11 +562,10 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
});
|
||||
});
|
||||
|
||||
const response = successResponse(shapeAssetForViewer(
|
||||
created,
|
||||
context.canDownloadAssets,
|
||||
true
|
||||
), 201);
|
||||
const response = successResponse(
|
||||
shapeAssetForViewer(created, context.canDownloadAssets, true),
|
||||
201
|
||||
);
|
||||
if (isGuest && guestIdentity?.shouldSetCookie) {
|
||||
setGuestIdentityCookie(response, guestIdentity.identityId);
|
||||
}
|
||||
|
||||
@@ -9,158 +9,169 @@ type RouteParams = { params: Promise<{ videoId: string }> };
|
||||
|
||||
// GET /api/watch/[videoId]/progress - Get watch progress for the current user
|
||||
export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized('Authentication required');
|
||||
}
|
||||
try {
|
||||
const session = await auth();
|
||||
|
||||
const { videoId } = await params;
|
||||
|
||||
// Get the video and its active version (project access data pre-fetched in same query)
|
||||
const userId = session.user.id;
|
||||
const video = await db.video.findUnique({
|
||||
where: { id: videoId },
|
||||
include: {
|
||||
project: { include: projectAccessInclude(userId) },
|
||||
versions: {
|
||||
where: { isActive: true },
|
||||
take: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = computeProjectAccess(video.project, userId);
|
||||
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const activeVersion = video.versions[0];
|
||||
if (!activeVersion) {
|
||||
return apiErrors.notFound('Video version');
|
||||
}
|
||||
|
||||
// Get watch progress for this user and version
|
||||
const progress = await db.watchProgress.findUnique({
|
||||
where: {
|
||||
userId_versionId: {
|
||||
userId: session.user.id,
|
||||
versionId: activeVersion.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return successResponse({
|
||||
progress: progress ? progress.progress : 0,
|
||||
duration: progress?.duration || activeVersion.duration || 0,
|
||||
percentage: progress?.percentage || 0,
|
||||
updatedAt: progress?.updatedAt || null,
|
||||
});
|
||||
} catch (error) {
|
||||
logError('Error fetching watch progress:', error);
|
||||
return apiErrors.internalError('Failed to fetch watch progress');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized('Authentication required');
|
||||
}
|
||||
|
||||
const { videoId } = await params;
|
||||
|
||||
// Get the video and its active version (project access data pre-fetched in same query)
|
||||
const userId = session.user.id;
|
||||
const video = await db.video.findUnique({
|
||||
where: { id: videoId },
|
||||
include: {
|
||||
project: { include: projectAccessInclude(userId) },
|
||||
versions: {
|
||||
where: { isActive: true },
|
||||
take: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = computeProjectAccess(video.project, userId);
|
||||
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const activeVersion = video.versions[0];
|
||||
if (!activeVersion) {
|
||||
return apiErrors.notFound('Video version');
|
||||
}
|
||||
|
||||
// Get watch progress for this user and version
|
||||
const progress = await db.watchProgress.findUnique({
|
||||
where: {
|
||||
userId_versionId: {
|
||||
userId: session.user.id,
|
||||
versionId: activeVersion.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return successResponse({
|
||||
progress: progress ? progress.progress : 0,
|
||||
duration: progress?.duration || activeVersion.duration || 0,
|
||||
percentage: progress?.percentage || 0,
|
||||
updatedAt: progress?.updatedAt || null,
|
||||
});
|
||||
} catch (error) {
|
||||
logError('Error fetching watch progress:', error);
|
||||
return apiErrors.internalError('Failed to fetch watch progress');
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/watch/[videoId]/progress - Save watch progress for the current user
|
||||
export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
// Rate limit watch progress updates (30 per minute to allow pause + periodic + visibility changes)
|
||||
const limited = await rateLimit(request, 'watch-progress');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized('Authentication required');
|
||||
}
|
||||
try {
|
||||
// Rate limit watch progress updates (30 per minute to allow pause + periodic + visibility changes)
|
||||
const limited = await rateLimit(request, 'watch-progress');
|
||||
if (limited) return limited;
|
||||
|
||||
const { videoId } = await params;
|
||||
const body = await request.json();
|
||||
const { progress, duration, versionId } = body;
|
||||
const session = await auth();
|
||||
|
||||
const MAX_VIDEO_SECONDS = 86_400; // 24 hours — reasonable upper bound for any video
|
||||
|
||||
if (typeof progress !== 'number' || !isFinite(progress) || progress < 0 || progress > MAX_VIDEO_SECONDS) {
|
||||
return apiErrors.badRequest('Invalid progress value');
|
||||
}
|
||||
|
||||
if (duration !== undefined && (typeof duration !== 'number' || !isFinite(duration) || duration < 0 || duration > MAX_VIDEO_SECONDS)) {
|
||||
return apiErrors.badRequest('Invalid duration value');
|
||||
}
|
||||
|
||||
if (versionId !== undefined && typeof versionId !== 'string') {
|
||||
return apiErrors.badRequest('Invalid versionId');
|
||||
}
|
||||
|
||||
// Always load the requested video and validate access before writing progress.
|
||||
// If versionId is provided, verify it belongs to this video; otherwise resolve active version.
|
||||
// Project access data is pre-fetched in the same query — no extra round-trips.
|
||||
const userId = session.user.id;
|
||||
const video = await db.video.findUnique({
|
||||
where: { id: videoId },
|
||||
include: {
|
||||
project: { include: projectAccessInclude(userId) },
|
||||
versions: {
|
||||
where: versionId ? { id: versionId } : { isActive: true },
|
||||
take: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = computeProjectAccess(video.project, userId);
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const targetVersion = video.versions[0];
|
||||
if (!targetVersion) {
|
||||
return apiErrors.notFound('Video version');
|
||||
}
|
||||
|
||||
// Calculate percentage
|
||||
const safeDuration = duration || 0;
|
||||
const percentage = safeDuration > 0 ? Math.min(100, (progress / safeDuration) * 100) : 0;
|
||||
|
||||
// Client already filters tiny deltas (<2s) before sending — safe to upsert directly.
|
||||
const watchProgress = await db.watchProgress.upsert({
|
||||
where: {
|
||||
userId_versionId: {
|
||||
userId: session.user.id,
|
||||
versionId: targetVersion.id,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
progress,
|
||||
duration: safeDuration,
|
||||
percentage,
|
||||
},
|
||||
create: {
|
||||
userId: session.user.id,
|
||||
versionId: targetVersion.id,
|
||||
progress,
|
||||
duration: safeDuration,
|
||||
percentage,
|
||||
},
|
||||
});
|
||||
|
||||
return successResponse({
|
||||
success: true,
|
||||
progress: watchProgress.progress,
|
||||
percentage: watchProgress.percentage,
|
||||
});
|
||||
} catch (error) {
|
||||
logError('Error saving watch progress:', error);
|
||||
return apiErrors.internalError('Failed to save watch progress');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized('Authentication required');
|
||||
}
|
||||
|
||||
const { videoId } = await params;
|
||||
const body = await request.json();
|
||||
const { progress, duration, versionId } = body;
|
||||
|
||||
const MAX_VIDEO_SECONDS = 86_400; // 24 hours — reasonable upper bound for any video
|
||||
|
||||
if (
|
||||
typeof progress !== 'number' ||
|
||||
!isFinite(progress) ||
|
||||
progress < 0 ||
|
||||
progress > MAX_VIDEO_SECONDS
|
||||
) {
|
||||
return apiErrors.badRequest('Invalid progress value');
|
||||
}
|
||||
|
||||
if (
|
||||
duration !== undefined &&
|
||||
(typeof duration !== 'number' ||
|
||||
!isFinite(duration) ||
|
||||
duration < 0 ||
|
||||
duration > MAX_VIDEO_SECONDS)
|
||||
) {
|
||||
return apiErrors.badRequest('Invalid duration value');
|
||||
}
|
||||
|
||||
if (versionId !== undefined && typeof versionId !== 'string') {
|
||||
return apiErrors.badRequest('Invalid versionId');
|
||||
}
|
||||
|
||||
// Always load the requested video and validate access before writing progress.
|
||||
// If versionId is provided, verify it belongs to this video; otherwise resolve active version.
|
||||
// Project access data is pre-fetched in the same query — no extra round-trips.
|
||||
const userId = session.user.id;
|
||||
const video = await db.video.findUnique({
|
||||
where: { id: videoId },
|
||||
include: {
|
||||
project: { include: projectAccessInclude(userId) },
|
||||
versions: {
|
||||
where: versionId ? { id: versionId } : { isActive: true },
|
||||
take: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
const access = computeProjectAccess(video.project, userId);
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const targetVersion = video.versions[0];
|
||||
if (!targetVersion) {
|
||||
return apiErrors.notFound('Video version');
|
||||
}
|
||||
|
||||
// Calculate percentage
|
||||
const safeDuration = duration || 0;
|
||||
const percentage = safeDuration > 0 ? Math.min(100, (progress / safeDuration) * 100) : 0;
|
||||
|
||||
// Client already filters tiny deltas (<2s) before sending — safe to upsert directly.
|
||||
const watchProgress = await db.watchProgress.upsert({
|
||||
where: {
|
||||
userId_versionId: {
|
||||
userId: session.user.id,
|
||||
versionId: targetVersion.id,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
progress,
|
||||
duration: safeDuration,
|
||||
percentage,
|
||||
},
|
||||
create: {
|
||||
userId: session.user.id,
|
||||
versionId: targetVersion.id,
|
||||
progress,
|
||||
duration: safeDuration,
|
||||
percentage,
|
||||
},
|
||||
});
|
||||
|
||||
return successResponse({
|
||||
success: true,
|
||||
progress: watchProgress.progress,
|
||||
percentage: watchProgress.percentage,
|
||||
});
|
||||
} catch (error) {
|
||||
logError('Error saving watch progress:', error);
|
||||
return apiErrors.internalError('Failed to save watch progress');
|
||||
}
|
||||
}
|
||||
|
||||
+200
-191
@@ -12,203 +12,212 @@ type RouteParams = { params: Promise<{ videoId: string }> };
|
||||
|
||||
// GET /api/watch/[videoId] - Public watch endpoint (no projectId needed)
|
||||
export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
// Rate limit: 60 requests per minute per IP for public watch endpoint
|
||||
const limited = await rateLimit(request, 'watch', { windowMs: 60 * 1000, maxRequests: 60 });
|
||||
if (limited) return limited;
|
||||
try {
|
||||
// Rate limit: 60 requests per minute per IP for public watch endpoint
|
||||
const limited = await rateLimit(request, 'watch', { windowMs: 60 * 1000, maxRequests: 60 });
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { videoId } = await params;
|
||||
const session = await auth();
|
||||
const { videoId } = await params;
|
||||
|
||||
// Parse query params
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const includeComments = searchParams.get('includeComments') === 'true';
|
||||
// Parse query params
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const includeComments = searchParams.get('includeComments') === 'true';
|
||||
|
||||
const video = await db.video.findUnique({
|
||||
where: { id: videoId },
|
||||
include: {
|
||||
project: true,
|
||||
versions: {
|
||||
orderBy: { versionNumber: 'desc' },
|
||||
...(includeComments ? {
|
||||
include: {
|
||||
comments: {
|
||||
orderBy: { timestamp: 'asc' },
|
||||
where: { parentId: null },
|
||||
select: {
|
||||
id: true,
|
||||
content: true,
|
||||
timestamp: true,
|
||||
timestampEnd: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
isResolved: true,
|
||||
resolvedAt: true,
|
||||
voiceUrl: true,
|
||||
voiceDuration: true,
|
||||
imageUrl: true,
|
||||
annotationData: true,
|
||||
parentId: true,
|
||||
authorId: true,
|
||||
guestIdentityId: 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,
|
||||
annotationData: true,
|
||||
parentId: true,
|
||||
authorId: true,
|
||||
guestIdentityId: true,
|
||||
tagId: true,
|
||||
versionId: true,
|
||||
guestName: true,
|
||||
author: { select: { id: true, name: true, image: true } },
|
||||
tag: { select: { id: true, name: true, color: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
} : {
|
||||
const video = await db.video.findUnique({
|
||||
where: { id: videoId },
|
||||
include: {
|
||||
project: true,
|
||||
versions: {
|
||||
orderBy: { versionNumber: 'desc' },
|
||||
...(includeComments
|
||||
? {
|
||||
include: {
|
||||
comments: {
|
||||
orderBy: { timestamp: 'asc' },
|
||||
where: { parentId: null },
|
||||
select: {
|
||||
id: true,
|
||||
content: true,
|
||||
timestamp: true,
|
||||
timestampEnd: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
isResolved: true,
|
||||
resolvedAt: true,
|
||||
voiceUrl: true,
|
||||
voiceDuration: true,
|
||||
imageUrl: true,
|
||||
annotationData: true,
|
||||
parentId: true,
|
||||
authorId: true,
|
||||
guestIdentityId: 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,
|
||||
thumbnailUrl: true,
|
||||
duration: true,
|
||||
versionNumber: true,
|
||||
versionLabel: true,
|
||||
providerId: true,
|
||||
videoId: true,
|
||||
originalUrl: true,
|
||||
title: true,
|
||||
isActive: true,
|
||||
_count: { select: { comments: true } },
|
||||
id: true,
|
||||
content: true,
|
||||
timestamp: true,
|
||||
timestampEnd: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
isResolved: true,
|
||||
resolvedAt: true,
|
||||
voiceUrl: true,
|
||||
voiceDuration: true,
|
||||
imageUrl: true,
|
||||
annotationData: true,
|
||||
parentId: true,
|
||||
authorId: true,
|
||||
guestIdentityId: true,
|
||||
tagId: true,
|
||||
versionId: true,
|
||||
guestName: true,
|
||||
author: { select: { id: true, name: true, image: true } },
|
||||
tag: { select: { id: true, name: true, color: true } },
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
: {
|
||||
select: {
|
||||
id: true,
|
||||
thumbnailUrl: true,
|
||||
duration: true,
|
||||
versionNumber: true,
|
||||
versionLabel: true,
|
||||
providerId: true,
|
||||
videoId: true,
|
||||
originalUrl: true,
|
||||
title: true,
|
||||
isActive: true,
|
||||
_count: { select: { comments: true } },
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
// Check access including workspace membership
|
||||
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: 'VIEW',
|
||||
passwordVerified: shareSession.passwordVerified,
|
||||
})
|
||||
: { hasAccess: false, canComment: false, canDownload: false, allowGuests: false, requiresPassword: false };
|
||||
|
||||
if (!access.hasAccess && !shareAccess.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
// 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 replies = comment.replies;
|
||||
const commentData = Object.fromEntries(
|
||||
Object.entries(comment).filter(
|
||||
([key]) => key !== 'authorId' && key !== 'guestIdentityId' && key !== 'replies'
|
||||
)
|
||||
);
|
||||
|
||||
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 replyData = Object.fromEntries(
|
||||
Object.entries(reply).filter(
|
||||
([key]) => key !== 'authorId' && key !== 'guestIdentityId'
|
||||
)
|
||||
);
|
||||
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 canUploadAssets = canCommentWithMembership || canCommentWithShareLink;
|
||||
const canDownloadAssets = !!session?.user?.id && (access.hasAccess || shareAccess.hasAccess);
|
||||
const response = successResponse({
|
||||
...videoData,
|
||||
versions,
|
||||
projectId: video.projectId,
|
||||
project: {
|
||||
name: project.name,
|
||||
ownerId: project.ownerId,
|
||||
visibility: project.visibility,
|
||||
},
|
||||
isAuthenticated: !!session?.user?.id,
|
||||
currentUserId: session?.user?.id || null,
|
||||
currentUserName: session?.user?.name || null,
|
||||
canComment: canCommentWithMembership || canCommentWithShareLink,
|
||||
canDownload: canDownloadWithMembership || canDownloadWithShareLink,
|
||||
canManageTags: access.canEdit,
|
||||
canResolveComments: access.canEdit,
|
||||
canShareVideo: access.canEdit,
|
||||
canUploadAssets,
|
||||
canDownloadAssets,
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, no-cache');
|
||||
} catch (error) {
|
||||
logError('Error fetching video:', error);
|
||||
return apiErrors.internalError('Failed to fetch video');
|
||||
if (!video) {
|
||||
return apiErrors.notFound('Video');
|
||||
}
|
||||
|
||||
// Check access including workspace membership
|
||||
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: 'VIEW',
|
||||
passwordVerified: shareSession.passwordVerified,
|
||||
})
|
||||
: {
|
||||
hasAccess: false,
|
||||
canComment: false,
|
||||
canDownload: false,
|
||||
allowGuests: false,
|
||||
requiresPassword: false,
|
||||
};
|
||||
|
||||
if (!access.hasAccess && !shareAccess.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
// 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 replies = comment.replies;
|
||||
const commentData = Object.fromEntries(
|
||||
Object.entries(comment).filter(
|
||||
([key]) => key !== 'authorId' && key !== 'guestIdentityId' && key !== 'replies'
|
||||
)
|
||||
);
|
||||
|
||||
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 replyData = Object.fromEntries(
|
||||
Object.entries(reply).filter(
|
||||
([key]) => key !== 'authorId' && key !== 'guestIdentityId'
|
||||
)
|
||||
);
|
||||
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 canUploadAssets = canCommentWithMembership || canCommentWithShareLink;
|
||||
const canDownloadAssets = !!session?.user?.id && (access.hasAccess || shareAccess.hasAccess);
|
||||
const response = successResponse({
|
||||
...videoData,
|
||||
versions,
|
||||
projectId: video.projectId,
|
||||
project: {
|
||||
name: project.name,
|
||||
ownerId: project.ownerId,
|
||||
visibility: project.visibility,
|
||||
},
|
||||
isAuthenticated: !!session?.user?.id,
|
||||
currentUserId: session?.user?.id || null,
|
||||
currentUserName: session?.user?.name || null,
|
||||
canComment: canCommentWithMembership || canCommentWithShareLink,
|
||||
canDownload: canDownloadWithMembership || canDownloadWithShareLink,
|
||||
canManageTags: access.canEdit,
|
||||
canResolveComments: access.canEdit,
|
||||
canShareVideo: access.canEdit,
|
||||
canUploadAssets,
|
||||
canDownloadAssets,
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, no-cache');
|
||||
} catch (error) {
|
||||
logError('Error fetching video:', error);
|
||||
return apiErrors.internalError('Failed to fetch video');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,13 +64,19 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
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 };
|
||||
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;
|
||||
|
||||
@@ -10,143 +10,143 @@ type RouteParams = { params: Promise<{ workspaceId: string; memberId: string }>
|
||||
|
||||
// PATCH /api/workspaces/[workspaceId]/members/[memberId] - Update member role
|
||||
export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'manage-member');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'manage-member');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { workspaceId, memberId } = await params;
|
||||
const session = await auth();
|
||||
const { workspaceId, memberId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
// Check if user is owner or admin
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { role } = body;
|
||||
|
||||
const validRoles = ['ADMIN', 'COMMENTATOR'];
|
||||
if (!validRoles.includes(role)) {
|
||||
return apiErrors.badRequest('Invalid role. Must be ADMIN or COMMENTATOR.');
|
||||
}
|
||||
|
||||
const member = await db.workspaceMember.findFirst({
|
||||
where: { id: memberId, workspaceId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!member) {
|
||||
return apiErrors.notFound('Member');
|
||||
}
|
||||
|
||||
const updatedMember = await db.workspaceMember.update({
|
||||
where: { id: member.id },
|
||||
data: { role: role as WorkspaceMemberRole },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, image: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(updatedMember);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating member role:', error);
|
||||
return apiErrors.internalError('Failed to update member role');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
// Check if user is owner or admin
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { role } = body;
|
||||
|
||||
const validRoles = ['ADMIN', 'COMMENTATOR'];
|
||||
if (!validRoles.includes(role)) {
|
||||
return apiErrors.badRequest('Invalid role. Must be ADMIN or COMMENTATOR.');
|
||||
}
|
||||
|
||||
const member = await db.workspaceMember.findFirst({
|
||||
where: { id: memberId, workspaceId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!member) {
|
||||
return apiErrors.notFound('Member');
|
||||
}
|
||||
|
||||
const updatedMember = await db.workspaceMember.update({
|
||||
where: { id: member.id },
|
||||
data: { role: role as WorkspaceMemberRole },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, image: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(updatedMember);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error updating member role:', error);
|
||||
return apiErrors.internalError('Failed to update member role');
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/workspaces/[workspaceId]/members/[memberId] - Remove member
|
||||
export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'manage-member');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'manage-member');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { workspaceId, memberId } = await params;
|
||||
const session = await auth();
|
||||
const { workspaceId, memberId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
// Users can remove themselves, admins/owners can remove anyone
|
||||
const memberToRemove = await db.workspaceMember.findFirst({
|
||||
where: { id: memberId, workspaceId },
|
||||
select: { id: true, userId: true },
|
||||
});
|
||||
|
||||
if (!memberToRemove) {
|
||||
return apiErrors.notFound('Member');
|
||||
}
|
||||
|
||||
const isSelf = memberToRemove.userId === session.user.id;
|
||||
|
||||
if ((!access.canEdit || (!isOwner && !isAdmin)) && !isSelf) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.projectMember.deleteMany({
|
||||
where: {
|
||||
userId: memberToRemove.userId,
|
||||
project: {
|
||||
workspaceId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await tx.project.updateMany({
|
||||
where: {
|
||||
workspaceId,
|
||||
ownerId: memberToRemove.userId,
|
||||
},
|
||||
data: {
|
||||
ownerId: workspace.ownerId,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workspaceMember.delete({ where: { id: memberToRemove.id } });
|
||||
});
|
||||
|
||||
const response = successResponse({ message: 'Member removed' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error removing member:', error);
|
||||
return apiErrors.internalError('Failed to remove member');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
// Users can remove themselves, admins/owners can remove anyone
|
||||
const memberToRemove = await db.workspaceMember.findFirst({
|
||||
where: { id: memberId, workspaceId },
|
||||
select: { id: true, userId: true },
|
||||
});
|
||||
|
||||
if (!memberToRemove) {
|
||||
return apiErrors.notFound('Member');
|
||||
}
|
||||
|
||||
const isSelf = memberToRemove.userId === session.user.id;
|
||||
|
||||
if ((!access.canEdit || (!isOwner && !isAdmin)) && !isSelf) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.projectMember.deleteMany({
|
||||
where: {
|
||||
userId: memberToRemove.userId,
|
||||
project: {
|
||||
workspaceId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await tx.project.updateMany({
|
||||
where: {
|
||||
workspaceId,
|
||||
ownerId: memberToRemove.userId,
|
||||
},
|
||||
data: {
|
||||
ownerId: workspace.ownerId,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workspaceMember.delete({ where: { id: memberToRemove.id } });
|
||||
});
|
||||
|
||||
const response = successResponse({ message: 'Member removed' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error removing member:', error);
|
||||
return apiErrors.internalError('Failed to remove member');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,11 @@ import { db } from '@/lib/db';
|
||||
import { auth, checkWorkspaceAccess } from '@/lib/auth';
|
||||
import { InvitationRole, WorkspaceMemberRole } from '@prisma/client';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { buildInvitationUrl, createOrRefreshInvitation, sendInvitationEmail } from '@/lib/invitations';
|
||||
import {
|
||||
buildInvitationUrl,
|
||||
createOrRefreshInvitation,
|
||||
sendInvitationEmail,
|
||||
} from '@/lib/invitations';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { logError } from '@/lib/logger';
|
||||
|
||||
@@ -11,215 +15,211 @@ type RouteParams = { params: Promise<{ workspaceId: string }> };
|
||||
|
||||
// GET /api/workspaces/[workspaceId]/members - List members
|
||||
export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const session = await auth();
|
||||
const { workspaceId } = await params;
|
||||
const MAX_LIMIT = 100;
|
||||
const MAX_PAGE = 1000;
|
||||
const MAX_OFFSET = 10000;
|
||||
try {
|
||||
const session = await auth();
|
||||
const { workspaceId } = await params;
|
||||
const MAX_LIMIT = 100;
|
||||
const MAX_PAGE = 1000;
|
||||
const MAX_OFFSET = 10000;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const pageParam = searchParams.get('page');
|
||||
const limitParam = searchParams.get('limit');
|
||||
|
||||
const pageRaw = pageParam === null ? 1 : Number(pageParam);
|
||||
if (!Number.isSafeInteger(pageRaw) || pageRaw < 1 || pageRaw > MAX_PAGE) {
|
||||
return apiErrors.badRequest('Invalid page. Must be a positive integer.');
|
||||
}
|
||||
|
||||
const limitRaw = limitParam === null ? 20 : Number(limitParam);
|
||||
if (!Number.isSafeInteger(limitRaw) || limitRaw < 1 || limitRaw > MAX_LIMIT) {
|
||||
return apiErrors.badRequest('Invalid limit. Must be a positive integer between 1 and 100.');
|
||||
}
|
||||
|
||||
const page = pageRaw;
|
||||
const limit = limitRaw;
|
||||
const skip = (page - 1) * limit;
|
||||
if (!Number.isSafeInteger(skip) || skip > MAX_OFFSET) {
|
||||
return apiErrors.badRequest('Invalid page range. Offset must be 10000 or less.');
|
||||
}
|
||||
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
include: {
|
||||
members: { where: { userId: session.user.id } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isMember = workspace.members.length > 0;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!access.hasAccess || (!isOwner && !isMember)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const canViewPendingInvitations = isOwner || isAdmin;
|
||||
const [members, total, pendingInvitations] = await Promise.all([
|
||||
db.workspaceMember.findMany({
|
||||
where: { workspaceId },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true, image: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
skip,
|
||||
take: limit,
|
||||
}),
|
||||
db.workspaceMember.count({
|
||||
where: { workspaceId },
|
||||
}),
|
||||
canViewPendingInvitations
|
||||
? db.invitation.findMany({
|
||||
where: {
|
||||
workspaceId,
|
||||
scope: 'WORKSPACE',
|
||||
status: 'PENDING',
|
||||
expiresAt: { gt: now },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
expiresAt: true,
|
||||
invitedBy: {
|
||||
select: { id: true, name: true, email: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
|
||||
// Include the owner as well
|
||||
const owner = await db.user.findUnique({
|
||||
where: { id: workspace.ownerId },
|
||||
select: { id: true, name: true, email: true, image: true },
|
||||
});
|
||||
|
||||
const response = successResponse(
|
||||
{ members, owner, pendingInvitations },
|
||||
200,
|
||||
{
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
}
|
||||
);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error fetching workspace members:', error);
|
||||
return apiErrors.internalError('Failed to fetch members');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const pageParam = searchParams.get('page');
|
||||
const limitParam = searchParams.get('limit');
|
||||
|
||||
const pageRaw = pageParam === null ? 1 : Number(pageParam);
|
||||
if (!Number.isSafeInteger(pageRaw) || pageRaw < 1 || pageRaw > MAX_PAGE) {
|
||||
return apiErrors.badRequest('Invalid page. Must be a positive integer.');
|
||||
}
|
||||
|
||||
const limitRaw = limitParam === null ? 20 : Number(limitParam);
|
||||
if (!Number.isSafeInteger(limitRaw) || limitRaw < 1 || limitRaw > MAX_LIMIT) {
|
||||
return apiErrors.badRequest('Invalid limit. Must be a positive integer between 1 and 100.');
|
||||
}
|
||||
|
||||
const page = pageRaw;
|
||||
const limit = limitRaw;
|
||||
const skip = (page - 1) * limit;
|
||||
if (!Number.isSafeInteger(skip) || skip > MAX_OFFSET) {
|
||||
return apiErrors.badRequest('Invalid page range. Offset must be 10000 or less.');
|
||||
}
|
||||
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
include: {
|
||||
members: { where: { userId: session.user.id } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isMember = workspace.members.length > 0;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!access.hasAccess || (!isOwner && !isMember)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const canViewPendingInvitations = isOwner || isAdmin;
|
||||
const [members, total, pendingInvitations] = await Promise.all([
|
||||
db.workspaceMember.findMany({
|
||||
where: { workspaceId },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true, image: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
skip,
|
||||
take: limit,
|
||||
}),
|
||||
db.workspaceMember.count({
|
||||
where: { workspaceId },
|
||||
}),
|
||||
canViewPendingInvitations
|
||||
? db.invitation.findMany({
|
||||
where: {
|
||||
workspaceId,
|
||||
scope: 'WORKSPACE',
|
||||
status: 'PENDING',
|
||||
expiresAt: { gt: now },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
expiresAt: true,
|
||||
invitedBy: {
|
||||
select: { id: true, name: true, email: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
|
||||
// Include the owner as well
|
||||
const owner = await db.user.findUnique({
|
||||
where: { id: workspace.ownerId },
|
||||
select: { id: true, name: true, email: true, image: true },
|
||||
});
|
||||
|
||||
const response = successResponse({ members, owner, pendingInvitations }, 200, {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
});
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error fetching workspace members:', error);
|
||||
return apiErrors.internalError('Failed to fetch members');
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/workspaces/[workspaceId]/members - Invite a member
|
||||
export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'invite-member');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'invite-member');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { workspaceId } = await params;
|
||||
const session = await auth();
|
||||
const { workspaceId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
// Check if user is owner or admin
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Only workspace owners and admins can invite members');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { email, role } = body;
|
||||
|
||||
if (!email || typeof email !== 'string') {
|
||||
return apiErrors.badRequest('Email is required');
|
||||
}
|
||||
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.validationError('Invalid email format');
|
||||
}
|
||||
|
||||
// Validate role
|
||||
const validRoles = ['ADMIN', 'COMMENTATOR'];
|
||||
const memberRole = validRoles.includes(role) ? role : 'COMMENTATOR';
|
||||
|
||||
// If this email belongs to an existing user, validate owner/member conflicts.
|
||||
const userToInvite = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (userToInvite?.id === workspace.ownerId) {
|
||||
return apiErrors.badRequest('Cannot invite the workspace owner as a member');
|
||||
}
|
||||
|
||||
if (userToInvite) {
|
||||
const existingMember = await db.workspaceMember.findUnique({
|
||||
where: { workspaceId_userId: { workspaceId, userId: userToInvite.id } },
|
||||
});
|
||||
|
||||
if (existingMember) {
|
||||
return apiErrors.conflict('User is already a member of this workspace');
|
||||
}
|
||||
}
|
||||
|
||||
const invitation = await createOrRefreshInvitation({
|
||||
email: normalizedEmail,
|
||||
scope: 'WORKSPACE',
|
||||
role: memberRole as InvitationRole,
|
||||
invitedById: session.user.id,
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
const invitationUrl = buildInvitationUrl(invitation.token);
|
||||
void sendInvitationEmail({
|
||||
to: normalizedEmail,
|
||||
inviterName: session.user.name || 'A team member',
|
||||
role: invitation.role,
|
||||
scope: invitation.scope,
|
||||
targetName: workspace.name,
|
||||
invitationUrl,
|
||||
});
|
||||
|
||||
const response = successResponse({ message: 'Invitation email sent.' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error inviting workspace member:', error);
|
||||
return apiErrors.internalError('Failed to invite member');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
// Check if user is owner or admin
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Only workspace owners and admins can invite members');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { email, role } = body;
|
||||
|
||||
if (!email || typeof email !== 'string') {
|
||||
return apiErrors.badRequest('Email is required');
|
||||
}
|
||||
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.validationError('Invalid email format');
|
||||
}
|
||||
|
||||
// Validate role
|
||||
const validRoles = ['ADMIN', 'COMMENTATOR'];
|
||||
const memberRole = validRoles.includes(role) ? role : 'COMMENTATOR';
|
||||
|
||||
// If this email belongs to an existing user, validate owner/member conflicts.
|
||||
const userToInvite = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (userToInvite?.id === workspace.ownerId) {
|
||||
return apiErrors.badRequest('Cannot invite the workspace owner as a member');
|
||||
}
|
||||
|
||||
if (userToInvite) {
|
||||
const existingMember = await db.workspaceMember.findUnique({
|
||||
where: { workspaceId_userId: { workspaceId, userId: userToInvite.id } },
|
||||
});
|
||||
|
||||
if (existingMember) {
|
||||
return apiErrors.conflict('User is already a member of this workspace');
|
||||
}
|
||||
}
|
||||
|
||||
const invitation = await createOrRefreshInvitation({
|
||||
email: normalizedEmail,
|
||||
scope: 'WORKSPACE',
|
||||
role: memberRole as InvitationRole,
|
||||
invitedById: session.user.id,
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
const invitationUrl = buildInvitationUrl(invitation.token);
|
||||
void sendInvitationEmail({
|
||||
to: normalizedEmail,
|
||||
inviterName: session.user.name || 'A team member',
|
||||
role: invitation.role,
|
||||
scope: invitation.scope,
|
||||
targetName: workspace.name,
|
||||
invitationUrl,
|
||||
});
|
||||
|
||||
const response = successResponse({ message: 'Invitation email sent.' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error inviting workspace member:', error);
|
||||
return apiErrors.internalError('Failed to invite member');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,228 +12,228 @@ type RouteParams = { params: Promise<{ workspaceId: string }> };
|
||||
|
||||
// GET /api/workspaces/[workspaceId] - Get a single workspace
|
||||
export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const session = await auth();
|
||||
const { workspaceId } = await params;
|
||||
const MAX_LIMIT = 100;
|
||||
const MAX_OFFSET = 10000;
|
||||
try {
|
||||
const session = await auth();
|
||||
const { workspaceId } = await params;
|
||||
const MAX_LIMIT = 100;
|
||||
const MAX_OFFSET = 10000;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const limitParam = searchParams.get('limit');
|
||||
const offsetParam = searchParams.get('offset');
|
||||
|
||||
const limitRaw = limitParam === null ? 20 : Number(limitParam);
|
||||
if (!Number.isSafeInteger(limitRaw) || limitRaw < 1 || limitRaw > MAX_LIMIT) {
|
||||
return apiErrors.badRequest('Invalid limit. Must be a positive integer between 1 and 100.');
|
||||
}
|
||||
|
||||
const offset = offsetParam === null ? 0 : Number(offsetParam);
|
||||
if (!Number.isSafeInteger(offset) || offset < 0 || offset > MAX_OFFSET) {
|
||||
return apiErrors.badRequest('Invalid offset. Must be a non-negative integer up to 10000.');
|
||||
}
|
||||
|
||||
const limit = limitRaw;
|
||||
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
members: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true, image: true } },
|
||||
},
|
||||
},
|
||||
projects: {
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
skip: offset,
|
||||
take: limit,
|
||||
include: {
|
||||
_count: { select: { videos: true, members: true } },
|
||||
},
|
||||
},
|
||||
_count: { select: { projects: true, members: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const response = successResponse(workspace);
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error fetching workspace:', error);
|
||||
return apiErrors.internalError('Failed to fetch workspace');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const limitParam = searchParams.get('limit');
|
||||
const offsetParam = searchParams.get('offset');
|
||||
|
||||
const limitRaw = limitParam === null ? 20 : Number(limitParam);
|
||||
if (!Number.isSafeInteger(limitRaw) || limitRaw < 1 || limitRaw > MAX_LIMIT) {
|
||||
return apiErrors.badRequest('Invalid limit. Must be a positive integer between 1 and 100.');
|
||||
}
|
||||
|
||||
const offset = offsetParam === null ? 0 : Number(offsetParam);
|
||||
if (!Number.isSafeInteger(offset) || offset < 0 || offset > MAX_OFFSET) {
|
||||
return apiErrors.badRequest('Invalid offset. Must be a non-negative integer up to 10000.');
|
||||
}
|
||||
|
||||
const limit = limitRaw;
|
||||
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
members: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true, image: true } },
|
||||
},
|
||||
},
|
||||
projects: {
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
skip: offset,
|
||||
take: limit,
|
||||
include: {
|
||||
_count: { select: { videos: true, members: true } },
|
||||
},
|
||||
},
|
||||
_count: { select: { projects: true, members: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
if (!access.hasAccess) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const response = successResponse(workspace);
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error fetching workspace:', error);
|
||||
return apiErrors.internalError('Failed to fetch workspace');
|
||||
}
|
||||
}
|
||||
|
||||
// PATCH /api/workspaces/[workspaceId] - Update a workspace
|
||||
export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { workspaceId } = await params;
|
||||
const session = await auth();
|
||||
const { workspaceId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const workspaceAccessTarget = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
select: { id: true, ownerId: true },
|
||||
});
|
||||
if (!workspaceAccessTarget) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(workspaceAccessTarget, session.user.id);
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, description } = body;
|
||||
|
||||
if (name !== undefined) {
|
||||
if (typeof name !== 'string' || name.trim().length === 0) {
|
||||
return apiErrors.badRequest('Name must be a non-empty string');
|
||||
}
|
||||
if (name.trim().length > 100) {
|
||||
return apiErrors.badRequest('Name must be 100 characters or fewer');
|
||||
}
|
||||
}
|
||||
if (description !== undefined && description !== null) {
|
||||
if (typeof description !== 'string') {
|
||||
return apiErrors.badRequest('Description must be a string');
|
||||
}
|
||||
if (description.trim().length > 1000) {
|
||||
return apiErrors.badRequest('Description must be 1000 characters or fewer');
|
||||
}
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (name !== undefined) updateData.name = name.trim();
|
||||
if (description !== undefined) updateData.description = description?.trim() || null;
|
||||
|
||||
const workspace = await db.workspace.update({
|
||||
where: { id: workspaceId },
|
||||
data: updateData,
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
_count: { select: { projects: true, members: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(workspace);
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error updating workspace:', error);
|
||||
return apiErrors.internalError('Failed to update workspace');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const workspaceAccessTarget = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
select: { id: true, ownerId: true },
|
||||
});
|
||||
if (!workspaceAccessTarget) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(workspaceAccessTarget, session.user.id);
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, description } = body;
|
||||
|
||||
if (name !== undefined) {
|
||||
if (typeof name !== 'string' || name.trim().length === 0) {
|
||||
return apiErrors.badRequest('Name must be a non-empty string');
|
||||
}
|
||||
if (name.trim().length > 100) {
|
||||
return apiErrors.badRequest('Name must be 100 characters or fewer');
|
||||
}
|
||||
}
|
||||
if (description !== undefined && description !== null) {
|
||||
if (typeof description !== 'string') {
|
||||
return apiErrors.badRequest('Description must be a string');
|
||||
}
|
||||
if (description.trim().length > 1000) {
|
||||
return apiErrors.badRequest('Description must be 1000 characters or fewer');
|
||||
}
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (name !== undefined) updateData.name = name.trim();
|
||||
if (description !== undefined) updateData.description = description?.trim() || null;
|
||||
|
||||
const workspace = await db.workspace.update({
|
||||
where: { id: workspaceId },
|
||||
data: updateData,
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
_count: { select: { projects: true, members: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(workspace);
|
||||
return withCacheControl(response, 'private, max-age=30, stale-while-revalidate=60');
|
||||
} catch (error) {
|
||||
logError('Error updating workspace:', error);
|
||||
return apiErrors.internalError('Failed to update workspace');
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/workspaces/[workspaceId] - Delete a workspace
|
||||
export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { workspaceId } = await params;
|
||||
const session = await auth();
|
||||
const { workspaceId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
select: { id: true, ownerId: true },
|
||||
});
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(workspace, session.user.id);
|
||||
if (!access.canDelete) {
|
||||
return apiErrors.forbidden('Only the workspace owner can delete it');
|
||||
}
|
||||
|
||||
const [workspaceVersionRefs, workspaceAssetRefs, mediaUrls] = await Promise.all([
|
||||
db.videoVersion.findMany({
|
||||
where: {
|
||||
video: {
|
||||
project: {
|
||||
workspaceId,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
providerId: true,
|
||||
videoId: true,
|
||||
},
|
||||
}),
|
||||
db.videoAsset.findMany({
|
||||
where: {
|
||||
provider: 'BUNNY',
|
||||
providerVideoId: { not: null },
|
||||
video: {
|
||||
project: {
|
||||
workspaceId,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
providerVideoId: true,
|
||||
},
|
||||
}),
|
||||
collectWorkspaceMediaUrls(workspaceId),
|
||||
]);
|
||||
|
||||
const bunnyRefs = [
|
||||
...workspaceVersionRefs,
|
||||
...workspaceAssetRefs.map((asset) => ({
|
||||
providerId: 'bunny',
|
||||
videoId: asset.providerVideoId as string,
|
||||
})),
|
||||
];
|
||||
|
||||
await db.workspace.delete({ where: { id: workspaceId } });
|
||||
|
||||
const [bunnyCleanupResult, r2CleanupResult] = await Promise.all([
|
||||
cleanupBunnyStreamVideosBestEffort(bunnyRefs),
|
||||
deleteMediaFilesBestEffort(mediaUrls),
|
||||
]);
|
||||
|
||||
const cleanupInput = {
|
||||
bunny: bunnyCleanupResult,
|
||||
r2: r2CleanupResult,
|
||||
};
|
||||
const cleanupWarnings = buildCleanupWarnings(cleanupInput);
|
||||
if (cleanupWarnings) {
|
||||
logCleanupWarnings({ entityType: 'workspace', entityId: workspaceId }, cleanupInput);
|
||||
}
|
||||
|
||||
const response = successResponse({
|
||||
message: 'Workspace deleted',
|
||||
...(cleanupWarnings ? { cleanupWarnings } : {}),
|
||||
});
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error deleting workspace:', error);
|
||||
return apiErrors.internalError('Failed to delete workspace');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
select: { id: true, ownerId: true },
|
||||
});
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(workspace, session.user.id);
|
||||
if (!access.canDelete) {
|
||||
return apiErrors.forbidden('Only the workspace owner can delete it');
|
||||
}
|
||||
|
||||
const [workspaceVersionRefs, workspaceAssetRefs, mediaUrls] = await Promise.all([
|
||||
db.videoVersion.findMany({
|
||||
where: {
|
||||
video: {
|
||||
project: {
|
||||
workspaceId,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
providerId: true,
|
||||
videoId: true,
|
||||
},
|
||||
}),
|
||||
db.videoAsset.findMany({
|
||||
where: {
|
||||
provider: 'BUNNY',
|
||||
providerVideoId: { not: null },
|
||||
video: {
|
||||
project: {
|
||||
workspaceId,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
providerVideoId: true,
|
||||
},
|
||||
}),
|
||||
collectWorkspaceMediaUrls(workspaceId),
|
||||
]);
|
||||
|
||||
const bunnyRefs = [
|
||||
...workspaceVersionRefs,
|
||||
...workspaceAssetRefs.map((asset) => ({
|
||||
providerId: 'bunny',
|
||||
videoId: asset.providerVideoId as string,
|
||||
})),
|
||||
];
|
||||
|
||||
await db.workspace.delete({ where: { id: workspaceId } });
|
||||
|
||||
const [bunnyCleanupResult, r2CleanupResult] = await Promise.all([
|
||||
cleanupBunnyStreamVideosBestEffort(bunnyRefs),
|
||||
deleteMediaFilesBestEffort(mediaUrls),
|
||||
]);
|
||||
|
||||
const cleanupInput = {
|
||||
bunny: bunnyCleanupResult,
|
||||
r2: r2CleanupResult,
|
||||
};
|
||||
const cleanupWarnings = buildCleanupWarnings(cleanupInput);
|
||||
if (cleanupWarnings) {
|
||||
logCleanupWarnings({ entityType: 'workspace', entityId: workspaceId }, cleanupInput);
|
||||
}
|
||||
|
||||
const response = successResponse({
|
||||
message: 'Workspace deleted',
|
||||
...(cleanupWarnings ? { cleanupWarnings } : {}),
|
||||
});
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error deleting workspace:', error);
|
||||
return apiErrors.internalError('Failed to delete workspace');
|
||||
}
|
||||
}
|
||||
|
||||
+125
-129
@@ -8,142 +8,138 @@ import { logError } from '@/lib/logger';
|
||||
|
||||
// GET /api/workspaces - List all workspaces for the authenticated user
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await auth();
|
||||
const MAX_LIMIT = 100;
|
||||
const MAX_PAGE = 1000;
|
||||
const MAX_OFFSET = 10000;
|
||||
try {
|
||||
const session = await auth();
|
||||
const MAX_LIMIT = 100;
|
||||
const MAX_PAGE = 1000;
|
||||
const MAX_OFFSET = 10000;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const pageParam = searchParams.get('page');
|
||||
const limitParam = searchParams.get('limit');
|
||||
|
||||
const pageRaw = pageParam === null ? 1 : Number(pageParam);
|
||||
if (!Number.isSafeInteger(pageRaw) || pageRaw < 1 || pageRaw > MAX_PAGE) {
|
||||
return apiErrors.badRequest('Invalid page. Must be a positive integer.');
|
||||
}
|
||||
|
||||
const limitRaw = limitParam === null ? 20 : Number(limitParam);
|
||||
if (!Number.isSafeInteger(limitRaw) || limitRaw < 1 || limitRaw > MAX_LIMIT) {
|
||||
return apiErrors.badRequest('Invalid limit. Must be a positive integer between 1 and 100.');
|
||||
}
|
||||
|
||||
const page = pageRaw;
|
||||
const limit = limitRaw;
|
||||
const skip = (page - 1) * limit;
|
||||
if (!Number.isSafeInteger(skip) || skip > MAX_OFFSET) {
|
||||
return apiErrors.badRequest('Invalid page range. Offset must be 10000 or less.');
|
||||
}
|
||||
|
||||
const where = {
|
||||
OR: [
|
||||
{ ownerId: session.user.id, owner: buildBillingAccessWhereInput() },
|
||||
{ members: { some: { userId: session.user.id } }, owner: buildBillingAccessWhereInput() },
|
||||
],
|
||||
};
|
||||
|
||||
// Get workspaces where user is owner OR a member
|
||||
const [workspaces, total] = await Promise.all([
|
||||
db.workspace.findMany({
|
||||
where,
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
_count: { select: { projects: true, members: true } },
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
skip,
|
||||
take: limit,
|
||||
}),
|
||||
db.workspace.count({ where }),
|
||||
]);
|
||||
|
||||
const response = successResponse(
|
||||
{ workspaces },
|
||||
200,
|
||||
{
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
}
|
||||
);
|
||||
return withCacheControl(response, 'private, max-age=60, stale-while-revalidate=120');
|
||||
} catch (error) {
|
||||
logError('Error fetching workspaces:', error);
|
||||
return apiErrors.internalError('Failed to fetch workspaces');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const pageParam = searchParams.get('page');
|
||||
const limitParam = searchParams.get('limit');
|
||||
|
||||
const pageRaw = pageParam === null ? 1 : Number(pageParam);
|
||||
if (!Number.isSafeInteger(pageRaw) || pageRaw < 1 || pageRaw > MAX_PAGE) {
|
||||
return apiErrors.badRequest('Invalid page. Must be a positive integer.');
|
||||
}
|
||||
|
||||
const limitRaw = limitParam === null ? 20 : Number(limitParam);
|
||||
if (!Number.isSafeInteger(limitRaw) || limitRaw < 1 || limitRaw > MAX_LIMIT) {
|
||||
return apiErrors.badRequest('Invalid limit. Must be a positive integer between 1 and 100.');
|
||||
}
|
||||
|
||||
const page = pageRaw;
|
||||
const limit = limitRaw;
|
||||
const skip = (page - 1) * limit;
|
||||
if (!Number.isSafeInteger(skip) || skip > MAX_OFFSET) {
|
||||
return apiErrors.badRequest('Invalid page range. Offset must be 10000 or less.');
|
||||
}
|
||||
|
||||
const where = {
|
||||
OR: [
|
||||
{ ownerId: session.user.id, owner: buildBillingAccessWhereInput() },
|
||||
{ members: { some: { userId: session.user.id } }, owner: buildBillingAccessWhereInput() },
|
||||
],
|
||||
};
|
||||
|
||||
// Get workspaces where user is owner OR a member
|
||||
const [workspaces, total] = await Promise.all([
|
||||
db.workspace.findMany({
|
||||
where,
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
_count: { select: { projects: true, members: true } },
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
skip,
|
||||
take: limit,
|
||||
}),
|
||||
db.workspace.count({ where }),
|
||||
]);
|
||||
|
||||
const response = successResponse({ workspaces }, 200, {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
});
|
||||
return withCacheControl(response, 'private, max-age=60, stale-while-revalidate=120');
|
||||
} catch (error) {
|
||||
logError('Error fetching workspaces:', error);
|
||||
return apiErrors.internalError('Failed to fetch workspaces');
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/workspaces - Create a new workspace
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'create-workspace');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
const limited = await rateLimit(request, 'create-workspace');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const billing = await getWorkspaceCreationEligibility(session.user.id);
|
||||
if (!billing.canCreateWorkspace) {
|
||||
return apiErrors.forbidden(
|
||||
billing.reason || 'Upgrade your account to create another workspace'
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, description } = body;
|
||||
|
||||
if (!name || typeof name !== 'string' || name.trim().length === 0) {
|
||||
return apiErrors.badRequest('Workspace name is required');
|
||||
}
|
||||
|
||||
// Generate slug
|
||||
const baseSlug = name
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^a-z0-9\s-]/g, '')
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/-+/g, '-');
|
||||
|
||||
// Find all existing slugs with the same prefix in a single query
|
||||
const existingWorkspaces = await db.workspace.findMany({
|
||||
where: { slug: { startsWith: baseSlug } },
|
||||
select: { slug: true },
|
||||
});
|
||||
|
||||
// Generate unique slug from the results
|
||||
const usedSlugs = new Set(existingWorkspaces.map(w => w.slug));
|
||||
let slug = baseSlug;
|
||||
let counter = 1;
|
||||
while (usedSlugs.has(slug)) {
|
||||
slug = `${baseSlug}-${counter}`;
|
||||
counter++;
|
||||
}
|
||||
|
||||
const workspace = await db.workspace.create({
|
||||
data: {
|
||||
name: name.trim(),
|
||||
description: description?.trim() || null,
|
||||
slug,
|
||||
ownerId: session.user.id,
|
||||
},
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
_count: { select: { projects: true, members: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(workspace, 201);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error creating workspace:', error);
|
||||
return apiErrors.internalError('Failed to create workspace');
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const billing = await getWorkspaceCreationEligibility(session.user.id);
|
||||
if (!billing.canCreateWorkspace) {
|
||||
return apiErrors.forbidden(
|
||||
billing.reason || 'Upgrade your account to create another workspace'
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, description } = body;
|
||||
|
||||
if (!name || typeof name !== 'string' || name.trim().length === 0) {
|
||||
return apiErrors.badRequest('Workspace name is required');
|
||||
}
|
||||
|
||||
// Generate slug
|
||||
const baseSlug = name
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^a-z0-9\s-]/g, '')
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/-+/g, '-');
|
||||
|
||||
// Find all existing slugs with the same prefix in a single query
|
||||
const existingWorkspaces = await db.workspace.findMany({
|
||||
where: { slug: { startsWith: baseSlug } },
|
||||
select: { slug: true },
|
||||
});
|
||||
|
||||
// Generate unique slug from the results
|
||||
const usedSlugs = new Set(existingWorkspaces.map((w) => w.slug));
|
||||
let slug = baseSlug;
|
||||
let counter = 1;
|
||||
while (usedSlugs.has(slug)) {
|
||||
slug = `${baseSlug}-${counter}`;
|
||||
counter++;
|
||||
}
|
||||
|
||||
const workspace = await db.workspace.create({
|
||||
data: {
|
||||
name: name.trim(),
|
||||
description: description?.trim() || null,
|
||||
slug,
|
||||
ownerId: session.user.id,
|
||||
},
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, image: true } },
|
||||
_count: { select: { projects: true, members: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(workspace, 201);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Error creating workspace:', error);
|
||||
return apiErrors.internalError('Failed to create workspace');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user