Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 08b6e58b8e | |||
| a863a5cbf3 |
+5
-2
@@ -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*
|
||||
|
||||
@@ -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
@@ -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"]
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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 });
|
||||
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// app/uploads/videos/[...path]/route.ts
|
||||
// Serves uploaded MP4s from UPLOADS_DIR/videos at the /uploads/videos/* URLs
|
||||
// stored in the database. Streams from disk with HTTP Range support — browsers
|
||||
// require range requests for <video> seeking, and multi-GB files must never be
|
||||
// buffered in memory.
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { Readable } from "stream";
|
||||
|
||||
const VIDEOS_DIR = path.join(process.env.UPLOADS_DIR || "/uploads", "videos");
|
||||
|
||||
const CONTENT_TYPES: Record<string, string> = {
|
||||
".mp4": "video/mp4",
|
||||
".m4v": "video/mp4",
|
||||
".webm": "video/webm",
|
||||
".mov": "video/quicktime",
|
||||
".mkv": "video/x-matroska",
|
||||
};
|
||||
|
||||
function resolveVideoPath(segments: string[]): string | null {
|
||||
if (segments.length === 0) return null;
|
||||
const requested = path.resolve(VIDEOS_DIR, ...segments);
|
||||
// Security: prevent directory traversal attacks
|
||||
if (!requested.startsWith(path.resolve(VIDEOS_DIR) + path.sep)) return null;
|
||||
return requested;
|
||||
}
|
||||
|
||||
async function statFile(filePath: string): Promise<fs.Stats | null> {
|
||||
try {
|
||||
const stats = await fs.promises.stat(filePath);
|
||||
return stats.isFile() ? stats : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Parses "bytes=start-end" | "bytes=start-" | "bytes=-suffix".
|
||||
// Returns null for absent/invalid headers (caller serves the full file) and
|
||||
// "unsatisfiable" when the range is outside the file (caller returns 416).
|
||||
function parseRange(
|
||||
header: string | null,
|
||||
size: number
|
||||
): { start: number; end: number } | "unsatisfiable" | null {
|
||||
if (!header) return null;
|
||||
const m = header.match(/^bytes=(\d*)-(\d*)$/);
|
||||
if (!m || (m[1] === "" && m[2] === "")) return null;
|
||||
|
||||
let start: number;
|
||||
let end: number;
|
||||
if (m[1] === "") {
|
||||
// suffix range: last N bytes
|
||||
const suffix = parseInt(m[2], 10);
|
||||
if (suffix === 0) return "unsatisfiable";
|
||||
start = Math.max(0, size - suffix);
|
||||
end = size - 1;
|
||||
} else {
|
||||
start = parseInt(m[1], 10);
|
||||
end = m[2] === "" ? size - 1 : Math.min(parseInt(m[2], 10), size - 1);
|
||||
}
|
||||
if (start >= size || start > end) return "unsatisfiable";
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
function baseHeaders(filePath: string, stats: fs.Stats): Record<string, string> {
|
||||
const ext = path.extname(filePath).toLowerCase();
|
||||
return {
|
||||
"Content-Type": CONTENT_TYPES[ext] ?? "application/octet-stream",
|
||||
"Accept-Ranges": "bytes",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
"Last-Modified": stats.mtime.toUTCString(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
context: { params: Promise<{ path?: string[] }> }
|
||||
) {
|
||||
try {
|
||||
const params = await context.params;
|
||||
const filePath = resolveVideoPath(params?.path || []);
|
||||
if (!filePath) {
|
||||
return NextResponse.json({ error: "Invalid request" }, { status: 400 });
|
||||
}
|
||||
|
||||
const stats = await statFile(filePath);
|
||||
if (!stats) {
|
||||
console.log(`[Videos] File not found: ${filePath}`);
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const headers = baseHeaders(filePath, stats);
|
||||
const range = parseRange(request.headers.get("range"), stats.size);
|
||||
|
||||
if (range === "unsatisfiable") {
|
||||
return new NextResponse(null, {
|
||||
status: 416,
|
||||
headers: { ...headers, "Content-Range": `bytes */${stats.size}` },
|
||||
});
|
||||
}
|
||||
|
||||
if (range) {
|
||||
const stream = fs.createReadStream(filePath, { start: range.start, end: range.end });
|
||||
return new NextResponse(Readable.toWeb(stream) as unknown as BodyInit, {
|
||||
status: 206,
|
||||
headers: {
|
||||
...headers,
|
||||
"Content-Range": `bytes ${range.start}-${range.end}/${stats.size}`,
|
||||
"Content-Length": String(range.end - range.start + 1),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const stream = fs.createReadStream(filePath);
|
||||
return new NextResponse(Readable.toWeb(stream) as unknown as BodyInit, {
|
||||
status: 200,
|
||||
headers: { ...headers, "Content-Length": String(stats.size) },
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[Videos] Error serving video file:", error);
|
||||
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function HEAD(
|
||||
request: Request,
|
||||
context: { params: Promise<{ path?: string[] }> }
|
||||
) {
|
||||
try {
|
||||
const params = await context.params;
|
||||
const filePath = resolveVideoPath(params?.path || []);
|
||||
if (!filePath) return new NextResponse(null, { status: 400 });
|
||||
|
||||
const stats = await statFile(filePath);
|
||||
if (!stats) return new NextResponse(null, { status: 404 });
|
||||
|
||||
return new NextResponse(null, {
|
||||
status: 200,
|
||||
headers: {
|
||||
...baseHeaders(filePath, stats),
|
||||
"Content-Length": String(stats.size),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[Videos] Error in HEAD request:", error);
|
||||
return new NextResponse(null, { status: 500 });
|
||||
}
|
||||
}
|
||||
+42
-19
@@ -9,36 +9,51 @@ services:
|
||||
restart: unless-stopped
|
||||
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
|
||||
NEXTAUTH_SECRET: ${NEXTAUTH_SECRET} # Set via .env file
|
||||
|
||||
|
||||
# Google OAuth (from .env)
|
||||
GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID}
|
||||
GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET}
|
||||
|
||||
|
||||
# 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
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
|
||||
# Health check
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:3000"]
|
||||
@@ -51,16 +66,20 @@ 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
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
|
||||
|
||||
# Health check
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U cms_user"]
|
||||
@@ -74,28 +93,32 @@ 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
|
||||
NODE_ENV: production
|
||||
|
||||
|
||||
# Mounted volumes for access to uploads
|
||||
volumes:
|
||||
# Mount uploads directory using bind mount for real-time file sync
|
||||
- /mnt/lab/configs/owicms/uploads:/uploads
|
||||
|
||||
|
||||
# Wait for database and CMS to be ready
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
cms:
|
||||
condition: service_healthy
|
||||
|
||||
|
||||
# Note: This transcoder runs as a batch job.
|
||||
# It processes all 'uploaded' videos and exits.
|
||||
# With restart: on-failure, it will restart and process new videos.
|
||||
|
||||
@@ -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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
Generated
-9575
File diff suppressed because it is too large
Load Diff
+6
-6
@@ -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",
|
||||
|
||||
Generated
+794
-715
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user