import { json } from "@sveltejs/kit"; import type { RequestHandler } from "./$types"; import { getConfig } from "#lib/server/config.ts"; import { claimedServiceAuthDid, noStore, sessionActor } from "#lib/server/github/index.ts"; const CREATE_TASK = "org.tangled.temp.migrator.createTask"; const object = (value: unknown): Record | null => value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record) : null; export const POST: RequestHandler = async ({ request, cookies, platform, fetch }) => { const authorization = request.headers.get("authorization"); if (!authorization) return json({ error: "Unauthorized" }, { status: 401, headers: noStore() }); const input = await request .json() .then(object) .catch(() => null); if (!input) return json( { error: "InvalidRequest", message: "expected a JSON object" }, { status: 400, headers: noStore() } ); const session = await sessionActor(cookies, platform); const hasPrivate = Array.isArray(input.jobs) && input.jobs.some((job) => object(job)?.private === true); const githubToken = session && hasPrivate && claimedServiceAuthDid(authorization) === session.did ? session.token : null; const body = { requestId: input.requestId, jobs: input.jobs, ...(githubToken ? { githubToken } : {}) }; try { const upstream = await fetch(`${getConfig(platform).migratorUrl}/xrpc/${CREATE_TASK}`, { method: "POST", redirect: "error", headers: { authorization, accept: "application/json", "content-type": "application/json" }, body: JSON.stringify(body), signal: request.signal }); const headers = new Headers(upstream.headers); headers.set("cache-control", "no-store"); return new Response(upstream.body, { status: upstream.status, statusText: upstream.statusText, headers }); } catch { return json( { error: "UpstreamFailure", message: "the migrator is unavailable" }, { status: 502, headers: noStore() } ); } };