// HTTP handlers for ship on push (PY3.1), framework-free: the route files // under app/api/v1/github/** only pass the request through. import type { Repo } from "../repo.ts"; import { readCookie, sameOrigin } from "../http.ts"; import { SESSION_COOKIE } from "../session.ts"; import { orgForBearer } from "../tokens.ts"; import { CloudflareError } from "./cloudflare.ts"; import { GithubError } from "./github.ts"; import type { Jwk } from "./jwt.ts"; import { addAppDomain, appDomains, recordAppDomain, removeAppDomain } from "./domains.ts"; import { ciReport, ciSession, cloudflareCallback, githubSetup, githubUserCallback, go, linkStatus, ShipError, startLink, webhook, type ShipDeps } from "./service.ts"; export const NOT_CONFIGURED = "Ship on push is not switched on for this console yet."; const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } }); const escapeHtml = (s: string) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] as string); /** A plain page for the browser steps; the message never holds a token. */ export function page(title: string, message: string, status = 200): Response { // Escape first, then turn GitHub pull request links into anchors (their characters survive escaping). const text = escapeHtml(message).replace(/https:\/\/github\.com\/[\w./-]+[\w/]/g, (u) => `${u}`); const body = `${escapeHtml(title)}

${escapeHtml(title)}

${text}

You can close this tab; the terminal shows the same.

`; return new Response(body, { status, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "referrer-policy": "no-referrer" } }); } function failure(e: unknown, html: boolean): Response { const known = e instanceof ShipError || e instanceof GithubError || e instanceof CloudflareError; if (!known) console.error(`ship on push: ${(e as Error)?.message ?? e}`); const status = known ? (e as { status: number }).status : 500; const message = known ? (e as Error).message : "Railyard could not finish. Try again in a minute."; return html ? page("Not linked", message, status) : json({ error: message }, status); } async function browserSession(deps: ShipDeps, req: Request): Promise<{ cookie: string | null; ready: boolean }> { // A query flag is not enough: a forwarded link could carry it. Continuing is a same-origin POST of the form that named the org. const posted = req.method === "POST" && sameOrigin(req, deps.consoleUrl); const body = posted ? await req.clone().text() : ""; return { cookie: readCookie(req, SESSION_COOKIE), ready: posted && new URLSearchParams(body).get("confirm") === "1" }; } /** Names the org. Continuing is a same-origin POST, so a copied link cannot skip this page. */ function confirmPage(message: string, req: Request): Response { const url = new URL(req.url); const fields = [...url.searchParams.entries()].map(([k, v]) => ``).join(""); const body = `Confirm

Confirm this link

${escapeHtml(message)}

${fields}
`; return new Response(body, { status: 200, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "referrer-policy": "no-referrer" } }); } const redirectOrPage = (r: { redirect: string } | { done: string } | { confirm: string }, req: Request) => "redirect" in r ? Response.redirect(r.redirect, 302) : "confirm" in r ? confirmPage(r.confirm, req) : page("Linked", r.done); export async function linkStartH(deps: ShipDeps | null, repo: Repo, req: Request, now: Date): Promise { const who = await orgForBearer(repo, req.headers.get("authorization")); if (!who) return json({ error: "unauthorized" }, 401); if (!deps) return json({ error: NOT_CONFIGURED }, 503); try { return json(await startLink(deps, who.orgId, await req.json().catch(() => null), now), 201); } catch (e) { return failure(e, false); } } export async function linkStatusH(deps: ShipDeps | null, repo: Repo, req: Request): Promise { const who = await orgForBearer(repo, req.headers.get("authorization")); if (!who) return json({ error: "unauthorized" }, 401); if (!deps) return json({ error: NOT_CONFIGURED }, 503); try { return json(await linkStatus(deps, who.orgId, new URL(req.url).searchParams.get("id"))); } catch (e) { return failure(e, false); } } export async function goH(deps: ShipDeps | null, req: Request, now: Date): Promise { if (!deps) return page("Not available", NOT_CONFIGURED, 503); try { return redirectOrPage(await go(deps, new URL(req.url).searchParams.get("s"), now, await browserSession(deps, req)), req); } catch (e) { return failure(e, true); } } export async function setupH(deps: ShipDeps | null, req: Request, now: Date): Promise { if (!deps) return page("Not available", NOT_CONFIGURED, 503); try { return redirectOrPage(await githubSetup(deps, new URL(req.url).searchParams, now), req); } catch (e) { return failure(e, true); } } export async function githubUserCallbackH(deps: ShipDeps | null, req: Request, now: Date): Promise { if (!deps) return page("Not available", NOT_CONFIGURED, 503); try { return redirectOrPage(await githubUserCallback(deps, new URL(req.url).searchParams, now), req); } catch (e) { return failure(e, true); } } export async function cloudflareCallbackH(deps: ShipDeps | null, req: Request, now: Date): Promise { if (!deps) return page("Not available", NOT_CONFIGURED, 503); try { const url = new URL(req.url); if (req.method === "POST") { const posted = new URLSearchParams(await req.clone().text()); for (const [k, v] of posted) if (!url.searchParams.has(k)) url.searchParams.set(k, v); } return redirectOrPage(await cloudflareCallback(deps, url.searchParams, now, await browserSession(deps, req)), req); } catch (e) { return failure(e, true); } } export async function ciSessionH(deps: ShipDeps | null, req: Request, now: Date): Promise { if (!deps) return json({ error: NOT_CONFIGURED }, 503); try { return json(await ciSession(deps, req.headers.get("authorization"), now)); } catch (e) { return failure(e, false); } } export async function ciReportH(deps: ShipDeps | null, req: Request, now: Date): Promise { if (!deps) return json({ error: NOT_CONFIGURED }, 503); try { return json(await ciReport(deps, req.headers.get("authorization"), await req.json().catch(() => null), now)); } catch (e) { return failure(e, false); } } export async function webhookH(deps: ShipDeps | null, secret: string | null, req: Request): Promise { if (!deps || !secret) return json({ error: NOT_CONFIGURED }, 503); const raw = await req.text(); try { return json(await webhook(deps, secret, req.headers.get("x-github-event"), req.headers.get("x-hub-signature-256"), raw)); } catch (e) { if (e instanceof SyntaxError) return json({ error: "body is not JSON" }, 400); return failure(e, false); } } /** GitHub's Actions OIDC keys, cached for an hour (they rotate rarely; a miss refetches once). */ export function githubOidcKeys(fetchImpl: typeof fetch = fetch, ttlMs = 3_600_000): () => Promise { let cache: { at: number; keys: Jwk[] } | null = null; return async () => { if (cache && Date.now() - cache.at < ttlMs) return cache.keys; const res = await fetchImpl("https://token.actions.githubusercontent.com/.well-known/jwks"); const body = (await res.json().catch(() => ({}))) as { keys?: Jwk[] }; if (!res.ok || !Array.isArray(body.keys)) throw new ShipError("GitHub's signing keys could not be read; try again.", 503); cache = { at: Date.now(), keys: body.keys }; return body.keys; }; } /** * Custom domains (QY1.5), CLI bearer: * GET /api/v1/domains?app= the org's domains with their certificate state * POST /api/v1/domains {app, hostname} attach with the org's Cloudflare grant * DELETE /api/v1/domains {app, hostname} detach (idempotent) * 409 {code: "no_cloudflare_grant"} tells the CLI to use the local login. */ export async function domainsH(deps: ShipDeps | null, repo: Repo, req: Request, now: Date): Promise { const who = await orgForBearer(repo, req.headers.get("authorization")); if (!who) return json({ error: "unauthorized" }, 401); if (!deps) return json({ error: NOT_CONFIGURED }, 503); try { if (req.method === "GET") { const app = new URL(req.url).searchParams.get("app"); return json({ domains: await appDomains(deps, who.orgId, app && /^[a-z0-9][a-z0-9-]{0,39}$/.test(app) ? app : null, now) }); } const body = await req.json().catch(() => null); if (req.method === "POST") return json({ domain: await addAppDomain(deps, who.orgId, body, now) }, 201); if (req.method === "DELETE") return json(await removeAppDomain(deps, who.orgId, body, now)); return json({ error: "method not allowed" }, 405); } catch (e) { const code = (e as { code?: string }).code; if (code) return json({ error: (e as Error).message, code }, (e as { status: number }).status); return failure(e, false); } } /** POST /api/v1/domains/record: what the CLI did with the local Cloudflare login. */ export async function domainsRecordH(deps: ShipDeps | null, repo: Repo, req: Request, now: Date): Promise { const who = await orgForBearer(repo, req.headers.get("authorization")); if (!who) return json({ error: "unauthorized" }, 401); if (!deps) return json({ error: NOT_CONFIGURED }, 503); try { return json(await recordAppDomain(deps, who.orgId, await req.json().catch(() => null), now)); } catch (e) { return failure(e, false); } }