caelum0x 014f62b224 feat(ship): ship on push through the customer's own GitHub Actions and Cloudflare, with no token shown (PY3.1)
RYP-E3 in Wave P. ADR RY-0004 records the evidence that path A exists
(Cloudflare self-managed OAuth clients, changelog 2026-06-03, authorization
code flow only) and builds it; path B stays the written fallback; path C
stays rejected.

- railyard link: one URL; at most two consents in the browser (install the
  Railyard GitHub App on the repo, then Cloudflare's own consent screen with
  PKCE), each skipped when done before; then one pull request from the App on
  railyard/ship-on-push adding .github/workflows/railyard.yml. Nothing is
  pushed to a default branch. The installation id GitHub sends back is not
  trusted; the App's view of the repo decides.
- The workflow holds no key: it asks GitHub for an OIDC token (audience = the
  console) and runs `railyard ci`. The console checks issuer, audience,
  expiry and signature, the stable repository_id, the Railyard workflow ref
  only, push/workflow_dispatch on branches only, and a paused org; it answers
  with a short-lived Cloudflare access token (sealed refresh token rotated and
  resealed; a cached access token reused while 10 min are left).
- railyard ci masks the token first, deploys exactly like railyard deploy,
  never opens a login, and reports with a fresh OIDC token. The console
  records the deploy (branch and commit from the token) and writes one
  preview comment on the branch's pull request, edited on later pushes.
- Signed App webhooks drop links on uninstall or repo removal.
- GET /api/v1/github/manifest creates the App (owner item Y4); the done page
  shows one command that pipes the App key into wrangler secrets.
- Migration 0007_ship.sql (idempotent; scratch Postgres only): installations,
  links (one per repo), sealed Cloudflare grants, link sessions; RLS on, no
  anon/authenticated grants.
- Off until RAILYARD_SHIP_ON_PUSH_LIVE=1 and every name is set (routes 503;
  copy stays "arriving" under denylist rule railyard-slot-ship-on-push).

Env: RAILYARD_SHIP_ON_PUSH_LIVE, GITHUB_APP_ID, GITHUB_APP_SLUG,
GITHUB_APP_PRIVATE_KEY, GITHUB_APP_WEBHOOK_SECRET, CLOUDFLARE_OAUTH_CLIENT_ID,
CLOUDFLARE_OAUTH_CLIENT_SECRET, CLOUDFLARE_OAUTH_SCOPES (optional); reuses
RAILYARD_CREDENTIALS_KEY.

Tests: console 122/122 (ship 12, migration 0007 on a scratch cluster), tsc
clean; CLI 18/18 (link and ci 5, copy lint). The 5-minute push-to-live run on
a real repo and Cloudflare account is owner-run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 03:10:35 +03:00

98 lines
4.4 KiB
TypeScript

// RS256 JWTs with WebCrypto (Node and Workers alike), for ship on push (PY3.1):
// signing the GitHub App's own JWT and verifying GitHub Actions OIDC tokens.
// No dependency: the two operations are small and fully tested.
import { b64url } from "../crypto.ts";
const enc = new TextEncoder();
const dec = new TextDecoder();
export function fromB64url(s: string): Uint8Array {
const pad = s.replace(/-/g, "+").replace(/_/g, "/");
const bin = atob(pad + "===".slice((pad.length + 3) % 4));
return Uint8Array.from(bin, (c) => c.charCodeAt(0));
}
function pemBody(pem: string): Uint8Array {
const b64 = pem.replace(/-----(BEGIN|END) [A-Z ]+-----/g, "").replace(/\s+/g, "");
return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
}
function derLength(n: number): number[] {
if (n < 0x80) return [n];
const bytes: number[] = [];
for (let v = n; v > 0; v >>= 8) bytes.unshift(v & 0xff);
return [0x80 | bytes.length, ...bytes];
}
function der(tag: number, body: Uint8Array | number[]): Uint8Array {
const b = body instanceof Uint8Array ? [...body] : body;
return Uint8Array.from([tag, ...derLength(b.length), ...b]);
}
/**
* GitHub hands out App keys as PKCS#1 ("BEGIN RSA PRIVATE KEY"); WebCrypto
* imports PKCS#8 only. PKCS#8 = SEQUENCE { 0, SEQUENCE { rsaEncryption, NULL }, OCTET STRING pkcs1 }.
*/
export function pkcs1ToPkcs8(pkcs1: Uint8Array): Uint8Array {
const version = [0x02, 0x01, 0x00];
const algorithm = [...der(0x30, [...der(0x06, [0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01]), 0x05, 0x00])];
return der(0x30, [...version, ...algorithm, ...der(0x04, pkcs1)]);
}
export async function importRsaPrivateKey(pem: string): Promise<CryptoKey> {
const text = pem.replace(/\\n/g, "\n");
const raw = pemBody(text);
const pkcs8 = /BEGIN RSA PRIVATE KEY/.test(text) ? pkcs1ToPkcs8(raw) : raw;
return crypto.subtle.importKey("pkcs8", pkcs8, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["sign"]);
}
export async function signRs256(key: CryptoKey, payload: Record<string, unknown>, kid?: string): Promise<string> {
const header = b64url(enc.encode(JSON.stringify({ alg: "RS256", typ: "JWT", ...(kid ? { kid } : {}) })));
const body = b64url(enc.encode(JSON.stringify(payload)));
const sig = new Uint8Array(await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, enc.encode(`${header}.${body}`)));
return `${header}.${body}.${b64url(sig)}`;
}
export interface Jwk {
kty: string;
kid?: string;
n?: string;
e?: string;
alg?: string;
use?: string;
}
export type JwtCheck = { ok: true; claims: Record<string, unknown> } | { ok: false; error: string };
/**
* Verifies an RS256 JWT against a key set: signature, `iss`, `aud`, `exp` and
* `nbf` (60 s leeway). Any other algorithm, a missing kid match or a malformed
* token is refused.
*/
export async function verifyRs256(token: string, keys: Jwk[], opts: { issuer: string; audience: string; now: Date }): Promise<JwtCheck> {
const parts = token.split(".");
if (parts.length !== 3) return { ok: false, error: "malformed token" };
let header: { alg?: string; kid?: string };
let claims: Record<string, unknown>;
try {
header = JSON.parse(dec.decode(fromB64url(parts[0] as string)));
claims = JSON.parse(dec.decode(fromB64url(parts[1] as string)));
} catch {
return { ok: false, error: "malformed token" };
}
if (header.alg !== "RS256") return { ok: false, error: "unsupported algorithm" };
const jwk = keys.find((k) => k.kty === "RSA" && (!header.kid || k.kid === header.kid));
if (!jwk?.n || !jwk.e) return { ok: false, error: "unknown signing key" };
const key = await crypto.subtle.importKey("jwk", { kty: "RSA", n: jwk.n, e: jwk.e, ext: true }, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
const valid = await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, fromB64url(parts[2] as string), enc.encode(`${parts[0]}.${parts[1]}`));
if (!valid) return { ok: false, error: "bad signature" };
const nowS = Math.floor(opts.now.getTime() / 1000);
if (claims.iss !== opts.issuer) return { ok: false, error: "wrong issuer" };
const aud = claims.aud;
if (!(aud === opts.audience || (Array.isArray(aud) && aud.includes(opts.audience)))) return { ok: false, error: "wrong audience" };
if (typeof claims.exp !== "number" || claims.exp + 60 < nowS) return { ok: false, error: "expired" };
if (typeof claims.nbf === "number" && claims.nbf - 60 > nowS) return { ok: false, error: "not yet valid" };
return { ok: true, claims };
}