Patch React2Shell RCE and harden auth, uploads and containers
Deploy Vault CMS / deploy (push) Successful in 2m23s

- 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>
This commit is contained in:
twotalesanimation
2026-09-15 11:52:33 +02:00
parent a863a5cbf3
commit 08b6e58b8e
21 changed files with 974 additions and 10406 deletions
+5 -2
View File
@@ -2,8 +2,11 @@
.gitignore
node_modules
.next
.env.local
.env.*.local
# Never bake secrets into image layers; they are passed in at runtime
.env
.env.*
.gitea
*.tsbuildinfo
.DS_Store
*.log
npm-debug.log*
+2
View File
@@ -21,6 +21,8 @@ jobs:
cd /opt/owicms-src
# Force the checkout to match the remote exactly, discarding any
# local modifications (a plain pull can keep or merge tampered files)
git fetch origin
git reset --hard origin/master
+19 -8
View File
@@ -1,18 +1,23 @@
# Multi-stage Dockerfile for Next.js CMS
# Stage 1: Build
FROM node:20-alpine AS builder
FROM node:22-alpine AS builder
WORKDIR /app
# Copy package files
COPY package.json pnpm-lock.yaml ./
# Install dependencies
RUN npm install -g pnpm && pnpm install --frozen-lockfile
# Install dependencies (pnpm pinned so builds are reproducible)
RUN npm install -g pnpm@10.22.0 && pnpm install --frozen-lockfile
# Copy source code
COPY . .
# Refuse to build when a production dependency has a known critical
# vulnerability. Runs after COPY so it isn't skipped by the layer cache on
# deploys that only change source code.
RUN pnpm audit --prod --audit-level critical
ARG DATABASE_URL="postgresql://dummy:dummy@localhost:5432/dummy"
ENV DATABASE_URL=$DATABASE_URL
@@ -21,30 +26,36 @@ ENV DATABASE_URL=$DATABASE_URL
RUN pnpm exec prisma generate
# Build Next.js application
RUN npm run build
RUN pnpm run build
# Stage 2: Production Runtime
FROM node:20-alpine
FROM node:22-alpine
WORKDIR /app
# Install dumb-init for proper signal handling
RUN apk add --no-cache dumb-init
# Copy from builder: node_modules and .next build output
# Copy from builder: node_modules and .next build output.
# Files stay root-owned so the app user cannot rewrite its own code; only the
# Next.js cache directory is writable.
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json
RUN mkdir -p .next/cache && chown node:node .next/cache
# Set production environment
ENV NODE_ENV=production
# Run as the unprivileged "node" user (uid 1000) instead of root
USER node
# Expose port 3000
EXPOSE 3000
# Use dumb-init to handle signals properly
ENTRYPOINT ["dumb-init", "--"]
# Start Next.js production server
CMD ["npm", "run", "start"]
# Start Next.js production server (directly, so npm doesn't need a writable home)
CMD ["node", "node_modules/next/dist/bin/next", "start"]
+5 -2
View File
@@ -1,7 +1,7 @@
# ==============================
# Build stage
# ==============================
FROM node:20-alpine AS builder
FROM node:22-alpine AS builder
WORKDIR /app
@@ -25,7 +25,7 @@ RUN npm run build
# ==============================
# Runtime stage
# ==============================
FROM node:20-alpine
FROM node:22-alpine
# Install FFmpeg
RUN apk add --no-cache ffmpeg
@@ -48,5 +48,8 @@ COPY prisma ./prisma
ENV NODE_ENV=production
ENV UPLOADS_DIR=/uploads
# Run as the unprivileged "node" user (uid 1000) instead of root
USER node
# The container runs once and exits
CMD ["node", "dist/index.js"]
+2 -10
View File
@@ -1,19 +1,11 @@
// app/api/admin/create-course/route.ts
import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth-options';
async function checkAdmin() {
const session = await getServerSession(authOptions);
if (!session?.user?.email) throw { status: 401, message: 'Unauthorized' };
const allowed = (process.env.ALLOWED_ADMINS || '').split(',').map(s=>s.trim()).filter(Boolean);
if (allowed.length && !allowed.includes(session.user.email)) throw { status: 403, message: 'Forbidden' };
}
import { requireAdmin } from '@/lib/admin-check';
export async function POST(req: Request) {
try {
await checkAdmin();
await requireAdmin();
const body = await req.json();
const { title, code } = body;
if (!title) return NextResponse.json({ error: 'missing title' }, { status: 400 });
+2 -10
View File
@@ -1,19 +1,11 @@
// app/api/admin/create-playlist/route.ts
import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth-options';
async function checkAdmin() {
const session = await getServerSession(authOptions);
if (!session?.user?.email) throw { status: 401, message: 'Unauthorized' };
const allowed = (process.env.ALLOWED_ADMINS || '').split(',').map(s=>s.trim()).filter(Boolean);
if (allowed.length && !allowed.includes(session.user.email)) throw { status: 403, message: 'Forbidden' };
}
import { requireAdmin } from '@/lib/admin-check';
export async function POST(req: Request) {
try {
await checkAdmin();
await requireAdmin();
const { title, courseId, additionalCourseIds } = await req.json();
if (!title || !courseId) return NextResponse.json({ error: 'missing fields' }, { status: 400 });
+4 -12
View File
@@ -2,20 +2,12 @@
// Assign or remove a playlist from additional courses
import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth-options';
async function checkAdmin() {
const session = await getServerSession(authOptions);
if (!session?.user?.email) throw { status: 401, message: 'Unauthorized' };
const allowed = (process.env.ALLOWED_ADMINS || '').split(',').map(s=>s.trim()).filter(Boolean);
if (allowed.length && !allowed.includes(session.user.email)) throw { status: 403, message: 'Forbidden' };
}
import { requireAdmin } from '@/lib/admin-check';
// GET: Get all courses a playlist is assigned to
export async function GET(req: Request) {
try {
await checkAdmin();
await requireAdmin();
const { searchParams } = new URL(req.url);
const playlistId = searchParams.get('playlistId');
@@ -49,7 +41,7 @@ export async function GET(req: Request) {
// POST: Assign playlist to an additional course
export async function POST(req: Request) {
try {
await checkAdmin();
await requireAdmin();
const { playlistId, courseId } = await req.json();
if (!playlistId || !courseId) return NextResponse.json({ error: 'missing fields' }, { status: 400 });
@@ -76,7 +68,7 @@ export async function POST(req: Request) {
// DELETE: Remove playlist from a course
export async function DELETE(req: Request) {
try {
await checkAdmin();
await requireAdmin();
const { searchParams } = new URL(req.url);
const playlistId = searchParams.get('playlistId');
const courseId = searchParams.get('courseId');
+25 -6
View File
@@ -5,6 +5,16 @@ 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 {
@@ -93,18 +103,27 @@ export async function POST(req: Request) {
// 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 to public/thumbnails
const uploadDir = join(process.cwd(), 'public', 'thumbnails');
// 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 = `${videoId}-${Date.now()}.${thumbnail.type.split('/')[1] || 'jpg'}`;
const filepath = join(uploadDir, filename);
await writeFile(filepath, buffer);
const filename = `${Date.now()}-${randomUUID()}${ext}`;
await writeFile(join(uploadDir, filename), buffer);
updateData.thumbnail = `/thumbnails/${filename}`;
updateData.thumbnail = `/api/thumbnails/${filename}`;
}
if (Object.keys(updateData).length === 0 && !thumbnail && restrictedCourseIds === null) {
+2 -15
View File
@@ -4,8 +4,7 @@ import fs from "fs";
import path from "path";
import { spawn } from "child_process";
import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth-options";
import { requireAdmin } from "@/lib/admin-check";
const UPLOADS_DIR = process.env.UPLOADS_DIR || "/uploads";
@@ -56,23 +55,11 @@ async function getVideoDurationFromFile(filePath: string): Promise<number | null
});
}
async function checkAdmin() {
const session = await getServerSession(authOptions);
if (!session?.user?.email) throw { status: 401, message: "Unauthorized" };
const allowed = (process.env.ALLOWED_ADMINS || "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
if (allowed.length && !allowed.includes(session.user.email))
throw { status: 403, message: "Forbidden" };
return session;
}
export async function POST(req: Request) {
try {
console.log('[Upload/Finalize] Request received');
await checkAdmin();
await requireAdmin();
const body = await req.json();
const { videoId } = body;
+8 -18
View File
@@ -7,8 +7,7 @@ import { IncomingMessage } from "http";
import { spawn } from "child_process";
import formidable, { Fields, Files, File as FormidableFile } from "formidable";
import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth-options";
import { requireAdmin } from "@/lib/admin-check";
// For 2GB uploads over Tailscale (~10-50 Mbps), need 30-45 minutes
export const maxDuration = 2700; // 45 minutes for very large uploads over slow connections
@@ -20,6 +19,8 @@ const UPLOADS_DIR = process.env.UPLOADS_DIR || "/uploads";
// post-parse rename is a cheap atomic move instead of a multi-GB copy
const TMP_DIR = path.join(UPLOADS_DIR, "tmp");
const THUMBNAIL_EXTS = new Set([".jpg", ".jpeg", ".png", ".webp", ".gif"]);
// Helper to extract video duration using FFprobe
async function getVideoDurationFromFile(filePath: string): Promise<number | null> {
return new Promise((resolve) => {
@@ -134,18 +135,6 @@ async function moveFile(src: string, dest: string) {
await fs.promises.chmod(dest, 0o644);
}
async function checkAdmin() {
const session = await getServerSession(authOptions);
if (!session?.user?.email) throw { status: 401, message: "Unauthorized" };
const allowed = (process.env.ALLOWED_ADMINS || "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
if (allowed.length && !allowed.includes(session.user.email))
throw { status: 403, message: "Forbidden" };
return session;
}
export async function POST(req: Request) {
// track saved paths so we can cleanup on error
let savedVideoDest: string | undefined;
@@ -156,7 +145,7 @@ export async function POST(req: Request) {
try {
console.log('[Upload] Request received, content-type:', req.headers.get("content-type"));
const session = await checkAdmin();
const session = await requireAdmin();
console.log('[Upload] Admin check passed for:', session.user?.email);
@@ -184,8 +173,8 @@ export async function POST(req: Request) {
if (thumbFile) {
try {
const originalThumbName = thumbFile.originalFilename || path.basename(thumbFile.filepath);
const tExt = path.extname(originalThumbName) || ".jpg";
const thumbFilename = `${Date.now()}-thumb${tExt}`;
const tExt = path.extname(originalThumbName).toLowerCase();
const thumbFilename = `${Date.now()}-thumb${THUMBNAIL_EXTS.has(tExt) ? tExt : ".jpg"}`;
const thumbDest = path.join(UPLOADS_DIR, "thumbnails", thumbFilename);
await moveFile(thumbFile.filepath, thumbDest);
thumbnailUrl = `/api/thumbnails/${thumbFilename}`;
@@ -198,7 +187,8 @@ export async function POST(req: Request) {
if (!isManualCopy) {
if (!videoFile) return NextResponse.json({ error: "no file" }, { status: 400 });
const originalFilename = videoFile.originalFilename || path.basename(videoFile.filepath);
// basename: the client-supplied name must not be able to contain "../"
const originalFilename = path.basename(videoFile.originalFilename || videoFile.filepath);
const filename = `${Date.now()}-${originalFilename}`;
const dest = path.join(UPLOADS_DIR, "videos", filename);
+5 -1
View File
@@ -1,8 +1,12 @@
// app/api/users/route.ts
// app/api/courses/route.ts
import { NextResponse } from "next/server";
import { prisma } from "../../../lib/prisma";
import { adminGuard } from "@/lib/admin-check";
export async function GET() {
const denied = await adminGuard();
if (denied) return denied;
const courses = await prisma.course.findMany({ select: { id: true, title: true, code: true } });
return NextResponse.json(courses);
}
+11 -3
View File
@@ -1,13 +1,15 @@
// /app/api/enrollments/route.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
import { prisma } from '@/lib/prisma';
import { adminGuard } from '@/lib/admin-check';
// --- GET --------------------------------------------------------------------
export async function GET() {
const denied = await adminGuard();
if (denied) return denied;
try {
const enrollments = await prisma.enrollment.findMany({
include: {
@@ -26,6 +28,9 @@ export async function GET() {
// --- POST --------------------------------------------------------------------
export async function POST(req: NextRequest) {
const denied = await adminGuard();
if (denied) return denied;
try {
const body = await req.json();
@@ -74,6 +79,9 @@ export async function POST(req: NextRequest) {
// --- DELETE --------------------------------------------------------------------
export async function DELETE(req: NextRequest) {
const denied = await adminGuard();
if (denied) return denied;
try {
const body = await req.json();
const id = body?.id;
+2 -2
View File
@@ -27,7 +27,7 @@ export async function GET(
const requestedPath = path.join(THUMBNAILS_DIR, ...pathSegments);
// Security: prevent directory traversal attacks
if (!requestedPath.startsWith(THUMBNAILS_DIR)) {
if (!requestedPath.startsWith(THUMBNAILS_DIR + path.sep)) {
return NextResponse.json(
{ error: 'Invalid request' },
{ status: 403 }
@@ -93,7 +93,7 @@ export async function HEAD(
const requestedPath = path.join(THUMBNAILS_DIR, ...pathSegments);
// Security: prevent directory traversal attacks
if (!requestedPath.startsWith(THUMBNAILS_DIR)) {
if (!requestedPath.startsWith(THUMBNAILS_DIR + path.sep)) {
return new NextResponse(null, { status: 403 });
}
+4
View File
@@ -1,9 +1,13 @@
// app/api/users/route.ts
import { NextResponse } from "next/server";
import { prisma } from "../../../lib/prisma";
import { adminGuard } from "@/lib/admin-check";
export async function GET() {
const denied = await adminGuard();
if (denied) return denied;
const users = await prisma.user.findMany({ select: { id: true, name: true, email: true } });
return NextResponse.json(users);
}
+2 -2
View File
@@ -27,7 +27,7 @@ export async function GET(
const requestedPath = path.join(HLS_DIR, ...pathSegments);
// Security: prevent directory traversal attacks
if (!requestedPath.startsWith(HLS_DIR)) {
if (!requestedPath.startsWith(HLS_DIR + path.sep)) {
return NextResponse.json(
{ error: 'Invalid request' },
{ status: 403 }
@@ -92,7 +92,7 @@ export async function HEAD(
const requestedPath = path.join(HLS_DIR, ...pathSegments);
// Security: prevent directory traversal attacks
if (!requestedPath.startsWith(HLS_DIR)) {
if (!requestedPath.startsWith(HLS_DIR + path.sep)) {
return new NextResponse(null, { status: 403 });
}
+26 -3
View File
@@ -10,10 +10,21 @@ services:
ports:
- "3000:3000"
# Hardening: the app can't modify its own files, gain privileges, or use
# Linux capabilities. Only /tmp, the Next.js cache and /uploads are writable.
read_only: true
tmpfs:
- /tmp
- /app/.next/cache:uid=1000,gid=1000
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
# Environment variables required for production
environment:
# Database connection (must match PostgreSQL service)
DATABASE_URL: postgresql://cms_user:changeme@postgres:5432/cms_db
DATABASE_URL: postgresql://cms_user:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@postgres:5432/cms_db
# NextAuth configuration
NEXTAUTH_URL: http://localhost:3000 # Update to your production domain
@@ -26,12 +37,16 @@ services:
# Admin email whitelist (comma-separated)
ALLOWED_ADMINS: ${ALLOWED_ADMINS:-admin@university.edu}
# Shared secret for the remote transcoder API
TRANSCODER_SECRET: ${TRANSCODER_SECRET}
# Upload directory (external to Next.js public folder)
UPLOADS_DIR: /uploads
# Mounted volumes for persistent data
volumes:
# Mount uploads directory as bind mount for real-time file sync
# Must be writable by uid 1000: chown -R 1000:1000 /mnt/lab/configs/owicms/uploads
- /mnt/lab/configs/owicms/uploads:/uploads
# Wait for database to be ready before starting
@@ -51,10 +66,14 @@ services:
image: postgres:16-alpine
container_name: college-postgres
restart: unless-stopped
security_opt:
- no-new-privileges:true
environment:
POSTGRES_USER: cms_user
POSTGRES_PASSWORD: changeme # Change in production!
# Only applied when the data volume is first created. To change the
# password of an existing database, also run ALTER USER cms_user PASSWORD '...'
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
POSTGRES_DB: cms_db
# Mounted volume for database persistence
@@ -74,11 +93,15 @@ services:
dockerfile: Dockerfile.transcoder
container_name: college-transcoder
restart: on-failure
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
# Environment variables
environment:
# Database connection (must match PostgreSQL service)
DATABASE_URL: postgresql://cms_user:changeme@postgres:5432/cms_db
DATABASE_URL: postgresql://cms_user:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@postgres:5432/cms_db
# Transcoder configuration
UPLOADS_DIR: /uploads
+17
View File
@@ -1,4 +1,5 @@
// lib/admin-check.ts
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from './auth-options';
@@ -9,3 +10,19 @@ export async function requireAdmin() {
if (!(role === 'admin' || role === 'superadmin')) throw { status: 403, message: 'Forbidden' };
return session;
}
/**
* Route-handler variant: returns a JSON error response when the caller is not
* an admin, or null when they are.
*/
export async function adminGuard(): Promise<NextResponse | null> {
try {
await requireAdmin();
return null;
} catch (err: any) {
return NextResponse.json(
{ error: err?.message ?? 'Unauthorized' },
{ status: err?.status ?? 401 }
);
}
}
+17
View File
@@ -1,6 +1,20 @@
import type { NextConfig } from "next";
const securityHeaders = [
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "X-Frame-Options", value: "DENY" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
{ key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
// Limited to directives that don't conflict with Next.js inline scripts:
// blocks <base> tag hijacking, plugin content, and framing (clickjacking)
{
key: "Content-Security-Policy",
value: "base-uri 'self'; object-src 'none'; frame-ancestors 'none'",
},
];
const nextConfig: NextConfig = {
poweredByHeader: false,
images: {
remotePatterns: [
{
@@ -10,6 +24,9 @@ const nextConfig: NextConfig = {
},
],
},
async headers() {
return [{ source: "/:path*", headers: securityHeaders }];
},
};
export default nextConfig;
-9575
View File
File diff suppressed because it is too large Load Diff
+6 -6
View File
@@ -45,11 +45,11 @@
"formidable": "^3.5.4",
"hls.js": "^1.6.15",
"lucide-react": "^0.554.0",
"next": "16.0.3",
"next-auth": "^4.24.13",
"next": "16.3.5",
"next-auth": "^4.24.15",
"next-themes": "^0.4.6",
"react": "19.2.0",
"react-dom": "19.2.0",
"react": "19.3.0",
"react-dom": "19.3.0",
"recharts": "2.15.4",
"sonner": "^2.0.7",
"swr": "^2.3.6",
@@ -61,13 +61,13 @@
"devDependencies": {
"@tailwindcss/postcss": "^4.1.17",
"@types/formidable": "^3.4.6",
"@types/unzipper": "^0.10.10",
"@types/node": "^20.19.25",
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/unzipper": "^0.10.10",
"autoprefixer": "^10.4.22",
"eslint": "^9",
"eslint-config-next": "16.0.3",
"eslint-config-next": "16.3.5",
"postcss": "^8.5.6",
"prisma": "^6.19.0",
"tailwindcss": "^4.1.17",
+794 -715
View File
File diff suppressed because it is too large Load Diff