Files
Vault/app/api/admin/update-video/route.ts
T
twotalesanimation 08b6e58b8e
Deploy Vault CMS / deploy (push) Successful in 2m23s
Patch React2Shell RCE and harden auth, uploads and containers
- Upgrade next 16.0.3 -> 16.3.5 and react/react-dom 19.2.0 -> 19.3.0
  (CVE-2025-55182 / CVE-2025-66478 unauthenticated RCE), next-auth -> 4.24.15
- Require admin role on /api/users, /api/courses and /api/enrollments,
  which were unauthenticated
- Replace ALLOWED_ADMINS checks that allowed any signed-in user when the
  variable was empty with the role-based requireAdmin
- Sanitize upload filenames, restrict thumbnail extensions, store edited
  thumbnails in UPLOADS_DIR, tighten traversal checks in file routes
- Dockerfile: Node 22, pinned pnpm, non-root user, critical audit gate
- Compose: read-only rootfs, dropped caps, no-new-privileges, Postgres
  password from env
- Exclude .env from Docker build context; add security headers
- Deploy with git reset --hard instead of git pull
- Remove stale package-lock.json

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 11:52:33 +02:00

161 lines
5.0 KiB
TypeScript

// app/api/admin/update-video/route.ts
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth-options';
import { prisma } from '@/lib/prisma';
import { writeFile, mkdir } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
const UPLOADS_DIR = process.env.UPLOADS_DIR || '/uploads';
const THUMBNAIL_EXTS: Record<string, string> = {
'image/jpeg': '.jpg',
'image/png': '.png',
'image/webp': '.webp',
'image/gif': '.gif',
};
export async function PATCH(req: Request) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.email) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const role = (session as any)?.user?.role ?? null;
if (!(role === 'admin' || role === 'superadmin')) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const { videoId, title } = await req.json();
if (!videoId) {
return NextResponse.json(
{ error: 'videoId required' },
{ status: 400 }
);
}
if (!title || typeof title !== 'string' || title.trim().length === 0) {
return NextResponse.json(
{ error: 'title required and must be non-empty' },
{ status: 400 }
);
}
const updatedVideo = await prisma.video.update({
where: { id: videoId },
data: { title: title.trim() },
});
return NextResponse.json(updatedVideo, { status: 200 });
} catch (err: any) {
console.error('update video error', err);
return NextResponse.json(
{ error: err?.message ?? 'server error' },
{ status: 500 }
);
}
}
export async function POST(req: Request) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.email)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
const role = (session as any)?.user?.role ?? null;
if (!(role === 'admin' || role === 'superadmin')) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const formData = await req.formData().catch(() => null);
if (!formData) {
return NextResponse.json({ error: 'Invalid form data' }, { status: 400 });
}
const videoId = formData.get('videoId') as string;
const title = formData.get('title') as string;
const description = formData.get('description') as string | null;
const thumbnail = formData.get('thumbnail') as File | null;
const restricted = formData.get('restrictedCourseIds') as string | null;
if (!videoId)
return NextResponse.json({ error: 'videoId required' }, { status: 400 });
// Build update data
const updateData: any = {};
if (title) updateData.title = title;
if (description !== null) updateData.description = description;
let restrictedCourseIds: string[] | null = null;
if (restricted) {
try {
const parsed = JSON.parse(restricted);
if (Array.isArray(parsed)) {
restrictedCourseIds = parsed.filter((id) => typeof id === 'string' && id);
}
} catch (err) {
console.warn('Invalid restrictedCourseIds payload', err);
}
}
// Handle thumbnail upload if provided
if (thumbnail && thumbnail.size > 0) {
// extension comes from an allowlist, never from client-supplied strings
const ext = THUMBNAIL_EXTS[thumbnail.type];
if (!ext) {
return NextResponse.json(
{ error: 'Thumbnail must be a JPEG, PNG, WebP or GIF image' },
{ status: 400 }
);
}
const bytes = await thumbnail.arrayBuffer();
const buffer = Buffer.from(bytes);
// Save with the upload route's thumbnails; the app directory itself is
// read-only in production
const uploadDir = join(UPLOADS_DIR, 'thumbnails');
await mkdir(uploadDir, { recursive: true });
const filename = `${Date.now()}-${randomUUID()}${ext}`;
await writeFile(join(uploadDir, filename), buffer);
updateData.thumbnail = `/api/thumbnails/${filename}`;
}
if (Object.keys(updateData).length === 0 && !thumbnail && restrictedCourseIds === null) {
return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
}
const updated = await prisma.video.update({
where: { id: videoId },
data: updateData,
});
if (restrictedCourseIds !== null) {
await prisma.videoCourse.deleteMany({ where: { videoId } });
if (restrictedCourseIds.length > 0) {
await prisma.videoCourse.createMany({
data: restrictedCourseIds.map((courseId) => ({
videoId,
courseId,
exclusive: true,
})),
skipDuplicates: true,
});
}
}
return NextResponse.json({ success: true, video: updated });
} catch (err: any) {
console.error('update video error', err);
return NextResponse.json(
{ error: err?.message ?? 'server error' },
{ status: 500 }
);
}
}