import { NextResponse } from 'next/server'; import path from 'node:path'; import fs from 'node:fs/promises'; const BASE_DIR = '/app/files'; export async function GET(req: Request) { try { const url = new URL(req.url); const raw = url.searchParams.get('path'); if (!raw) { return NextResponse.json({ error: 'Missing path' }, { status: 400 }); } const safe = path.normalize('/' + raw).replace(/^\/+/, '/'); const target = path.resolve(BASE_DIR, '.' + safe); if (!target.startsWith(BASE_DIR)) { return NextResponse.json({ error: 'Invalid path' }, { status: 400 }); } const st = await fs.stat(target).catch(() => null); if (!st || !st.isFile()) { return NextResponse.json({ error: 'Not a file' }, { status: 400 }); } const data = await fs.readFile(target); // naive content-type guess const ext = path.extname(target).toLowerCase(); const ctype = ext === '.pdf' ? 'application/pdf' : ext === '.png' ? 'image/png' : ext === '.jpg' || ext === '.jpeg' ? 'image/jpeg' : ext === '.webp' ? 'image/webp' : ext === '.txt' ? 'text/plain; charset=utf-8' : 'application/octet-stream'; return new Response(data, { headers: { 'Content-Type': ctype, 'Content-Length': String(data.byteLength), 'Content-Disposition': `inline; filename="${path.basename(target)}"`, 'Cache-Control': 'no-store', } }); } catch (e: any) { return NextResponse.json({ error: e?.message ?? 'Unknown error' }, { status: 500 }); } }