// Live runner terminal (PEP-9): GET — SSE stream of the pane, POST — keyboard input / paste. import { TerminalError, terminalInput, terminalSse } from "@peppa/runner"; import { currentUser } from "@/lib/auth"; import { db } from "@/lib/db"; export const dynamic = "force-dynamic"; type Ctx = { params: Promise<{ id: string }> }; const fail = (status: number, error: string) => Response.json({ error }, { status, headers: { "Cache-Control": "no-store" } }); function asResponse(e: unknown): Response { if (e instanceof TerminalError) return fail(e.status, e.message); console.error("terminal:", e); return fail(500, "Ошибка терминала"); } export async function GET(req: Request, { params }: Ctx) { const user = await currentUser(); if (!user) return fail(401, "Нужен вход"); try { return await terminalSse(db, user, Number((await params).id), req.signal); } catch (e) { return asResponse(e); } } /** Same-origin only: the session cookie is lax, and JSON bodies need a CORS preflight anyway. */ function sameOrigin(req: Request): boolean { const origin = req.headers.get("origin"); if (!origin) return true; const host = req.headers.get("x-forwarded-host") ?? req.headers.get("host"); try { return new URL(origin).host === host; } catch { return false; } } export async function POST(req: Request, { params }: Ctx) { const user = await currentUser(); if (!user) return fail(401, "Нужен вход"); if (!sameOrigin(req)) return fail(403, "Чужой источник"); if (!req.headers.get("content-type")?.startsWith("application/json")) return fail(415, "Нужен JSON"); // Paste limit is 64 KB; refuse oversized bodies before parsing. if (Number(req.headers.get("content-length") ?? 0) > 300_000) return fail(413, "Слишком длинный ввод"); let body: { keys?: unknown; paste?: unknown }; try { body = await req.json(); } catch { return fail(400, "Неверный JSON"); } try { await terminalInput(db, user, Number((await params).id), { keys: typeof body.keys === "string" ? body.keys : undefined, paste: typeof body.paste === "string" ? body.paste : undefined, }); return new Response(null, { status: 204 }); } catch (e) { return asResponse(e); } }