| 1 | import { getAgentEnv, validateSession } from "@/lib/community-agent"; |
| 2 | import { merchEnv } from "@/lib/merch/server"; |
| 3 | import { operatorAction } from "@/lib/merch/operator"; |
| 4 | import { MerchError, parseConfig } from "@/lib/merch/model"; |
| 5 | import { readBoundedBody, BodyReadError } from "@/lib/bounded-body"; |
| 6 | |
| 7 | export const dynamic = "force-dynamic"; |
| 8 | export async function POST(request: Request) { |
| 9 | try { |
| 10 | const authEnv = await getAgentEnv(); |
| 11 | const sid = request.headers.get("cookie")?.split(";").map(c => c.trim()).find(c => c.startsWith("mt_sid="))?.slice(7); |
| 12 | if (!authEnv.MAINTAINER_TOKEN || !await validateSession(authEnv.CURATED_KV, sid)) throw new MerchError(401, "unauthorized", "Maintainer sign-in is required."); |
| 13 | const env = await merchEnv(), config = parseConfig(env.MERCH_CONFIG_JSON); |
| 14 | if (!config || request.headers.get("origin") !== new URL(config.siteOrigin).origin || !request.headers.get("content-type")?.startsWith("application/json")) throw new MerchError(403, "request_blocked", "Use the approved store origin."); |
| 15 | const raw = await readBoundedBody(request, 8192); |
| 16 | let input: unknown; |
| 17 | try { input = JSON.parse(new TextDecoder().decode(raw)); } catch { throw new MerchError(422, "invalid_request", "Invalid operation data."); } |
| 18 | return Response.json(await operatorAction(env, input), { headers: { "Cache-Control": "no-store" } }); |
| 19 | } catch (error) { |
| 20 | const known = error instanceof MerchError || error instanceof BodyReadError; |
| 21 | return Response.json({ error: known ? error.message : "Operation unavailable; review the durable receipt before retrying.", code: error instanceof MerchError ? error.code : "operator_unavailable" }, { status: known ? error.status : 503, headers: { "Cache-Control": "no-store" } }); |
| 22 | } |
| 23 | } |
| 24 |