caelum0x 90f6ba3b78 feat(ship): custom domains for shipped apps on the customer's own Cloudflare account (QY1.5, I6)
- packages/cli/src/domains.mjs: a dependency-free client of Cloudflare's
  public Workers Custom Domains API (zones lookup, PUT/GET/DELETE
  /accounts/{id}/workers/domains, certificate pack state). Cloudflare
  issues the TLS certificate; a domain reads active once it is. The token
  goes in the Authorization header only and is scrubbed from every error.
  Byte copy at apps/console/lib/ship/cf-domains.mjs (drift test).
- railyard domains [add|remove HOSTNAME] [--app]: the console attaches the
  hostname to the app's production Worker with the org's Cloudflare grant
  (the QY1.1 OAuth step; the access token is opened and used inside the
  console only). Without a grant (409 no_cloudflare_grant) the CLI does the
  same with the local login (CLOUDFLARE_API_TOKEN or the wrangler login
  file after `wrangler whoami`) and the console records the outcome. Adding
  an attached hostname keeps it; one on another Worker is refused; remove
  is idempotent; a hostname outside the account's zones is refused plainly.
- Console: migration 0010 railyard.app_domains (one org per hostname,
  lower case, cascade, RLS, no anon); GET/POST/DELETE /api/v1/domains and
  POST /api/v1/domains/record (CLI bearer); states refreshed from
  Cloudflare when the org has a grant. Cloudflare OAuth default scopes add
  zone:read and ssl_certs:write (orgs linked before need to run
  railyard link once more for console-side domains).
- Scribase bridge: new signed route domains {scribase_org_id, app?} ->
  {available, domains:[{app, hostname, state, checked_at, created_at}],
  next} for the Deploy tab; contract fixture v2 adds it (additive).

Tests: CLI 23/23 (new domains.test.mjs 5: grant path with the real console
handlers and a fake Cloudflare, local-login path, wrangler config file,
refusals, idempotent remove, no token printed or sent to the console);
console 147/147 (new lib/ship/domains.test.ts 4: drift, worker naming
equal to the CLI's, attach/detach and cross-org refusal, record and
refresh, bridge listing; 0010 migration on a scratch PG); contract 6/6;
console tsc clean.

Owner-only: one real-domain proof (railyard domains add on a domain in the
owner's Cloudflare account) is not run here; record it at the deploy gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:45:57 +03:00

202 lines
11 KiB
TypeScript

// 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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[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) => `<a href="${u}">${u}</a>`);
const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(title)}</title>
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:36rem;margin:15vh auto;padding:0 1.5rem;color:#1d2330;background:#f6f7f9}h1{font-size:1.25rem}a{color:#2b5bd7}</style></head>
<body><h1>${escapeHtml(title)}</h1><p>${text}</p><p>You can close this tab; the terminal shows the same.</p></body></html>`;
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]) => `<input type="hidden" name="${escapeHtml(k)}" value="${escapeHtml(v)}">`).join("");
const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Confirm</title>
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:36rem;margin:15vh auto;padding:0 1.5rem;color:#1d2330;background:#f6f7f9}h1{font-size:1.25rem}button{font:inherit;background:#2b5bd7;color:#fff;border:0;border-radius:6px;padding:.5rem 1rem;cursor:pointer}</style></head>
<body><h1>Confirm this link</h1><p>${escapeHtml(message)}</p>
<form method="post" action="${escapeHtml(url.pathname)}">${fields}<input type="hidden" name="confirm" value="1"><button type="submit">Continue</button></form></body></html>`;
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<Response> {
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<Response> {
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<Response> {
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<Response> {
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<Response> {
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<Response> {
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<Response> {
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<Response> {
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<Response> {
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<Jwk[]> {
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<Response> {
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<Response> {
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);
}
}