import { NextRequest, NextResponse } from "next/server"; import { exec } from "child_process"; import { auth } from "@/lib/auth"; import { parseTasks, buildCommand } from "../route"; export const dynamic = "force-dynamic"; export async function POST(req: NextRequest) { const session = await auth(); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 403 }); } const { id } = await req.json(); if (typeof id !== "string" || !/^[a-f0-9]{16}$/.test(id)) { return NextResponse.json({ error: "Invalid id" }, { status: 400 }); } const task = parseTasks().find((t) => t.id === id); if (!task) { return NextResponse.json({ error: "Task not found" }, { status: 404 }); } const cmd = buildCommand(task); return new Promise((resolve) => { const child = exec(cmd, { timeout: 60_000 }, (err, stdout, stderr) => { if (err) { resolve( NextResponse.json( { success: false, message: err.message, stderr: stderr?.toString().slice(-500), }, { status: 500 } ) ); return; } resolve( NextResponse.json({ success: true, message: "Task executed", stdout: stdout?.toString().slice(-500), }) ); }); req.signal.addEventListener("abort", () => { try { child.kill(); } catch {} }); }); }