feat: implement R2 audio file management and rate limiting enhancements

- Add R2 client setup and audio upload functionality in lib/r2.ts.
- Create audio file cleanup functions in lib/r2-cleanup.ts to delete voice files associated with videos, projects, and workspaces.
- Enhance rate limiting in lib/rate-limit.ts with new action-specific limits and improved IP validation.
- Introduce a unified rate limit check function that returns a 429 response when limits are exceeded.
- Update package.json to include the AWS SDK for S3.
This commit is contained in:
Yusuf İpek
2026-02-07 12:27:40 +03:00
parent f240689e27
commit 296c5257a7
23 changed files with 1913 additions and 181 deletions
+10 -1
View File
@@ -1,3 +1,12 @@
import { handlers } from '@/lib/auth';
import { rateLimit } from '@/lib/rate-limit';
export const { GET, POST } = handlers;
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
return handlers.POST(request as any);
}
+37
View File
@@ -1,6 +1,9 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { r2Client, R2_BUCKET_NAME } from '@/lib/r2';
import { DeleteObjectCommand } from '@aws-sdk/client-s3';
import { rateLimit } from '@/lib/rate-limit';
type RouteParams = { params: Promise<{ commentId: string }> };
@@ -65,6 +68,9 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
// PATCH /api/comments/[commentId]
export async function PATCH(request: NextRequest, { params }: RouteParams) {
try {
const limited = await rateLimit(request, 'mutate');
if (limited) return limited;
const session = await auth();
const { commentId } = await params;
@@ -152,6 +158,9 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
// DELETE /api/comments/[commentId]
export async function DELETE(request: NextRequest, { params }: RouteParams) {
try {
const limited = await rateLimit(request, 'mutate');
if (limited) return limited;
const session = await auth();
const { commentId } = await params;
@@ -162,6 +171,7 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
const comment = await db.comment.findUnique({
where: { id: commentId },
include: {
replies: { select: { voiceUrl: true } },
version: {
include: {
video: { include: { project: true } },
@@ -184,8 +194,35 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
);
}
// Collect all voice URLs to delete from R2 (comment + its replies)
const voiceUrls: string[] = [];
if (comment.voiceUrl) voiceUrls.push(comment.voiceUrl);
for (const reply of comment.replies) {
if (reply.voiceUrl) voiceUrls.push(reply.voiceUrl);
}
await db.comment.delete({ where: { id: commentId } });
// Clean up audio files from R2 (best-effort, don't block on failure)
const AUDIO_PREFIX = '/api/upload/audio/';
for (const url of voiceUrls) {
try {
// Extract filename using string parsing (safe against ReDoS)
const idx = url.indexOf(AUDIO_PREFIX);
const filename = idx !== -1 ? url.slice(idx + AUDIO_PREFIX.length) : null;
if (filename) {
await r2Client.send(
new DeleteObjectCommand({
Bucket: R2_BUCKET_NAME,
Key: `voice/${filename}`,
})
);
}
} catch (err) {
console.error('Failed to delete audio from R2:', err);
}
}
return NextResponse.json({ success: true, message: 'Comment deleted' });
} catch (error) {
console.error('Error deleting comment:', error);
@@ -2,12 +2,16 @@ import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { ProjectMemberRole } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
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;
const session = await auth();
const { projectId, memberId } = await params;
@@ -63,6 +67,9 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
// 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;
const session = await auth();
const { projectId, memberId } = await params;
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { ProjectMemberRole } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
type RouteParams = { params: Promise<{ projectId: string }> };
@@ -59,6 +60,9 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
// 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;
const session = await auth();
const { projectId } = await params;
+11
View File
@@ -2,6 +2,8 @@ import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { ProjectMemberRole, ProjectVisibility } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
import { cleanupProjectVoiceFiles } from '@/lib/r2-cleanup';
type RouteParams = { params: Promise<{ projectId: string }> };
@@ -117,6 +119,9 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
// 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;
const session = await auth();
const { projectId } = await params;
@@ -159,6 +164,9 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
// 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;
const session = await auth();
const { projectId } = await params;
@@ -179,6 +187,9 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
);
}
// Clean up voice files from R2 before cascade delete removes comment rows
await cleanupProjectVoiceFiles(projectId);
await db.project.delete({ where: { id: projectId } });
return NextResponse.json({ success: true, message: 'Project deleted' });
@@ -2,6 +2,8 @@ import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { ProjectMemberRole } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
import { cleanupVideoVoiceFiles } from '@/lib/r2-cleanup';
type RouteParams = { params: Promise<{ projectId: string; videoId: string }> };
@@ -65,6 +67,9 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
// 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;
const session = await auth();
const { projectId, videoId } = await params;
@@ -122,6 +127,9 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
// 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;
const session = await auth();
const { projectId, videoId } = await params;
@@ -152,6 +160,9 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
);
}
// Clean up voice files from R2 before cascade delete removes comment rows
await cleanupVideoVoiceFiles(videoId);
await db.video.delete({ where: { id: videoId } });
return NextResponse.json({ success: true, message: 'Video deleted' });
@@ -3,6 +3,7 @@ import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { ProjectMemberRole } from '@prisma/client';
import { validateUrl, validateOptionalUrl } from '@/lib/validation';
import { rateLimit } from '@/lib/rate-limit';
type RouteParams = { params: Promise<{ projectId: string; videoId: string }> };
@@ -54,6 +55,9 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
// 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;
const session = await auth();
const { projectId, videoId } = await params;
@@ -3,6 +3,7 @@ import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { ProjectMemberRole } from '@prisma/client';
import { validateUrl, validateOptionalUrl } from '@/lib/validation';
import { rateLimit } from '@/lib/rate-limit';
type RouteParams = { params: Promise<{ projectId: string }> };
@@ -57,6 +58,9 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
// 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;
const session = await auth();
const { projectId } = await params;
+4
View File
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { ProjectVisibility } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
// GET /api/projects - List all projects for the authenticated user
export async function GET(request: NextRequest) {
@@ -75,6 +76,9 @@ export async function GET(request: NextRequest) {
// 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;
const session = await auth();
if (!session?.user?.id) {
+58
View File
@@ -0,0 +1,58 @@
import { NextResponse } from 'next/server';
import { r2Client, R2_BUCKET_NAME } from '@/lib/r2';
import { GetObjectCommand } from '@aws-sdk/client-s3';
// Only allow UUID filenames with safe extensions
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;
export async function GET(
_request: Request,
{ params }: { params: Promise<{ filename: string }> }
) {
try {
const { filename } = await params;
// Validate filename to prevent path traversal
if (!SAFE_FILENAME.test(filename)) {
return NextResponse.json({ error: 'Invalid filename' }, { status: 400 });
}
const key = `voice/${filename}`;
const response = await r2Client.send(
new GetObjectCommand({
Bucket: R2_BUCKET_NAME,
Key: key,
})
);
if (!response.Body) {
return NextResponse.json({ error: 'File not found' }, { status: 404 });
}
const contentType = response.ContentType || 'audio/webm';
const contentLength = response.ContentLength;
// Stream the response body directly instead of buffering in memory
const stream = response.Body.transformToWebStream();
return new NextResponse(stream, {
status: 200,
headers: {
'Content-Type': contentType,
...(contentLength ? { 'Content-Length': String(contentLength) } : {}),
'Cache-Control': 'public, max-age=31536000, immutable',
},
});
} catch (error: unknown) {
const errorName = error instanceof Error ? error.name : '';
if (errorName === 'NoSuchKey') {
return NextResponse.json({ error: 'File not found' }, { status: 404 });
}
console.error('Error serving audio:', error);
return NextResponse.json(
{ error: 'Failed to retrieve audio' },
{ status: 500 }
);
}
}
+76
View File
@@ -0,0 +1,76 @@
import { NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import { r2Client, R2_BUCKET_NAME } from '@/lib/r2';
import { PutObjectCommand } from '@aws-sdk/client-s3';
import { randomUUID } from 'crypto';
import { rateLimit } from '@/lib/rate-limit';
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
const ALLOWED_TYPES = ['audio/webm', 'audio/ogg', 'audio/mp4', 'audio/mpeg', 'audio/wav'];
export async function POST(request: Request) {
try {
// Rate limit
const limited = await rateLimit(request, 'voice-upload');
if (limited) return limited;
// Require authentication
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const formData = await request.formData();
const file = formData.get('audio') as File | null;
if (!file) {
return NextResponse.json({ error: 'No audio file provided' }, { status: 400 });
}
if (file.size > MAX_FILE_SIZE) {
return NextResponse.json(
{ error: 'File too large. Maximum size is 10MB.' },
{ status: 400 }
);
}
// Check content type
const contentType = file.type || 'audio/webm';
if (!ALLOWED_TYPES.includes(contentType)) {
return NextResponse.json(
{ error: `Unsupported audio format: ${contentType}` },
{ status: 400 }
);
}
// Generate unique filename
const ext = contentType.split('/')[1] || 'webm';
const filename = `${randomUUID()}.${ext}`;
const key = `voice/${filename}`;
// Convert to buffer
const arrayBuffer = await file.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
// Upload to R2
await r2Client.send(
new PutObjectCommand({
Bucket: R2_BUCKET_NAME,
Key: key,
Body: buffer,
ContentType: contentType,
})
);
// Return the URL through our proxy endpoint
const voiceUrl = `/api/upload/audio/${filename}`;
return NextResponse.json({ url: voiceUrl }, { status: 201 });
} catch (error) {
console.error('Error uploading audio:', error);
return NextResponse.json(
{ error: 'Failed to upload audio' },
{ status: 500 }
);
}
}
+10 -4
View File
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { validateOptionalUrl } from '@/lib/validation';
import { rateLimit } from '@/lib/rate-limit';
type RouteParams = { params: Promise<{ versionId: string }> };
@@ -74,6 +75,9 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
// POST /api/versions/[versionId]/comments
export async function POST(request: NextRequest, { params }: RouteParams) {
try {
const limited = await rateLimit(request, 'comment');
if (limited) return limited;
const session = await auth();
const { versionId } = await params;
@@ -149,10 +153,12 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
);
}
// Validate voice URL uses safe scheme
const voiceUrlError = validateOptionalUrl(voiceUrl, 'Voice URL');
if (voiceUrlError) {
return NextResponse.json({ error: voiceUrlError }, { status: 400 });
// Validate voice URL uses safe scheme (allow internal /api/ paths)
if (voiceUrl && !voiceUrl.startsWith('/api/')) {
const voiceUrlError = validateOptionalUrl(voiceUrl, 'Voice URL');
if (voiceUrlError) {
return NextResponse.json({ error: voiceUrlError }, { status: 400 });
}
}
const comment = await db.comment.create({
@@ -2,12 +2,16 @@ import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { WorkspaceMemberRole } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
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;
const session = await auth();
const { workspaceId, memberId } = await params;
@@ -64,6 +68,9 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
// 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;
const session = await auth();
const { workspaceId, memberId } = await params;
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { WorkspaceMemberRole } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
type RouteParams = { params: Promise<{ workspaceId: string }> };
@@ -60,6 +61,9 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
// 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;
const session = await auth();
const { workspaceId } = await params;
+11
View File
@@ -1,6 +1,8 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { rateLimit } from '@/lib/rate-limit';
import { cleanupWorkspaceVoiceFiles } from '@/lib/r2-cleanup';
type RouteParams = { params: Promise<{ workspaceId: string }> };
@@ -81,6 +83,9 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
// 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;
const session = await auth();
const { workspaceId } = await params;
@@ -122,6 +127,9 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
// 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;
const session = await auth();
const { workspaceId } = await params;
@@ -142,6 +150,9 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
);
}
// Clean up voice files from R2 before cascade delete removes comment rows
await cleanupWorkspaceVoiceFiles(workspaceId);
await db.workspace.delete({ where: { id: workspaceId } });
return NextResponse.json({ success: true, message: 'Workspace deleted' });
+4
View File
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { rateLimit } from '@/lib/rate-limit';
// GET /api/workspaces - List all workspaces for the authenticated user
export async function GET() {
@@ -39,6 +40,9 @@ export async function GET() {
// 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;
const session = await auth();
if (!session?.user?.id) {