Add guest upload tokens and share-session aware permissions

This commit is contained in:
Yusuf İpek
2026-02-23 18:17:22 +03:00
parent 9058317247
commit fe7235052e
21 changed files with 1117 additions and 150 deletions
+22 -3
View File
@@ -1,7 +1,8 @@
import { NextResponse } from 'next/server';
import { r2Client, R2_BUCKET_NAME } from '@/lib/r2';
import { GetObjectCommand, HeadObjectCommand } from '@aws-sdk/client-s3';
import { DeleteObjectCommand, GetObjectCommand, HeadObjectCommand } from '@aws-sdk/client-s3';
import { apiErrors } from '@/lib/api-response';
import { db } from '@/lib/db';
// 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;
@@ -14,6 +15,7 @@ const CONTENT_TYPE_MAP: Record<string, string> = {
gif: 'image/gif',
svg: 'image/svg+xml',
};
const UNATTACHED_UPLOAD_TTL_MS = 15 * 60 * 1000;
function getContentType(filename: string): string {
const ext = filename.split('.').pop()?.toLowerCase() || '';
@@ -33,6 +35,7 @@ export async function GET(
}
const key = `images/${filename}`;
const mediaUrl = `/api/upload/image/${filename}`;
// Get file metadata to determine content type
const headResponse = await r2Client.send(
@@ -42,6 +45,23 @@ export async function GET(
})
);
const lastModified = headResponse.LastModified;
if (lastModified && Date.now() - lastModified.getTime() > UNATTACHED_UPLOAD_TTL_MS) {
const referenced = await db.comment.findFirst({
where: { imageUrl: mediaUrl },
select: { id: true },
});
if (!referenced) {
await r2Client.send(
new DeleteObjectCommand({
Bucket: R2_BUCKET_NAME,
Key: key,
})
).catch(() => undefined);
return apiErrors.notFound('File');
}
}
const contentType = headResponse.ContentType || getContentType(filename);
const objectResponse = await r2Client.send(
@@ -72,7 +92,7 @@ export async function GET(
status: 200,
headers: {
'Content-Type': contentType,
'Cache-Control': 'public, max-age=31536000, immutable',
'Cache-Control': 'private, no-store',
'Accept-Ranges': 'bytes',
},
});
@@ -85,4 +105,3 @@ export async function GET(
return apiErrors.internalError('Failed to retrieve image');
}
}