// 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"; import { getT } from "@/lib/i18n"; import { m } from "@peppa/shared/i18n"; export const dynamic = "force-dynamic"; type Ctx = { params: Promise<{ id: string }> }; const fail = async (status: number, error: string) => Response.json({ error: (await getT()).text(error) }, { status, headers: { "Cache-Control": "no-store" } }); function asResponse(e: unknown): Promise { if (e instanceof TerminalError) return fail(e.status, e.message); console.error("terminal:", e); return fail(500, m("Ошибка терминала")); } export async function GET(req: Request, { params }: Ctx) { const user = await currentUser(); if (!user) return fail(401, m("Нужен вход")); 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, m("Нужен вход")); if (!sameOrigin(req)) return fail(403, m("Чужой источник")); if (!req.headers.get("content-type")?.startsWith("application/json")) return fail(415, m("Нужен JSON")); // Paste limit is 64 KB; refuse oversized bodies before parsing. if (Number(req.headers.get("content-length") ?? 0) > 300_000) return fail(413, m("Слишком длинный ввод")); let body: { keys?: unknown; paste?: unknown }; try { body = await req.json(); } catch { return fail(400, m("Неверный 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); } }