Cotton code
193 lines · 10.4 KB · TypeScriptRaw
/** * The open host's two site-association files, made from the registry so they never drift * (19 Nov 2026). A Cotton account passkey is for the sign-in host, and a phone lets an * app use it only when the host names the app: * *   APPLE_APP_SITE_ASSOCIATION  `{"webcredentials":{"apps":["<team>.<bundle id>", …]}}`, every iPhone *                               app people sign in to (cut to phones, signsInOnIphone): the live bundle ids on the live Worker, the dev ones on the dev *                               Worker (each app's entitlement names its own Worker's host, scripts/ios-spec-gate.ts). *   ANDROID_ASSET_LINKS         Digital Asset Links, `delegate_permission/common.get_login_creds` for every *                               Android app cut to phones (signsInOnAndroid) whose registry row lists its signing certificates *                               (`android.signing`, SHA-256 colon hex, Play App Signing's for a store build). *   PASSKEY_ANDROID_ORIGINS     the same certificates as WebAuthn origins, `android:apk-key-hash:<b64url>`. * * They are vars in `apps/business/wrangler.jsonc`, written right after each Worker's OPEN_HOST, so a deploy * carries them; a var with nothing to list is left out (the route then answers as no route). * *   pnpm -s passkey:associations           print what each Worker serves *   pnpm -s passkey:associations --write   write them into wrangler.jsonc *   pnpm -s passkey:associations --check   exit 1 when wrangler.jsonc is not what the registry says * * The guard is the root suite's scripts/__tests__/site-associations.test.ts (guards-main runs it). */import { readFileSync, writeFileSync } from "node:fs";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";import { devHost } from "./dev-server";const HERE = dirname(fileURLToPath(import.meta.url));export const ROOT = join(HERE, "..", "..", "..");export const WRANGLER = join(ROOT, "apps", "business", "wrangler.jsonc");const REGISTRY = join(ROOT, "apps", "registry.json");const PROJECT = join(ROOT, "apps", "cotton", "project.yml");export type Side = "live" | "dev";export type Phase = "planned" | "provisioned" | "development" | "production" | "parked";/** * Cut to phones: development or production, never parked or planned. The same rule as scripts/lib/registry.ts's * isCut, signsInOnIphone and signsInOnAndroid (this package is ESM and the root's scripts are not, so it is said * twice); the root guard holds the two to the same apps. */const cut = (row: Pick<Row, "phase">): boolean => row.phase === "development" || row.phase === "production";export const signsInOnIphone = (row: Row): boolean => cut(row) && Boolean(row.ios?.live.flavour);export const signsInOnAndroid = (row: Row): boolean => cut(row) && Boolean(row.android);/** What this reads of a registry row. */export interface Row {  slug: string;  phase: Phase;  ios: { live: { flavour: string | null; bundleId: string }; dev: { bundleId: string } | null } | null;  android: { package: string; devPackage: string | null; signing?: { live: string[]; dev: string[] } } | null;}export function readRows(path = REGISTRY): Row[] {  return (JSON.parse(readFileSync(path, "utf8")) as { apps: Row[] }).apps;}/** The Apple team every Cotton iPhone app is signed by: project.yml's DEVELOPMENT_TEAM. */export function readTeam(path = PROJECT): string {  const team = /^\s+DEVELOPMENT_TEAM:\s*([A-Z0-9]{10})\s*$/m.exec(readFileSync(path, "utf8"))?.[1];  if (!team) throw new Error(`${path} names no DEVELOPMENT_TEAM`);  return team;}/** The iPhone apps one Worker's host must name: `<team>.<bundle id>`, every app people sign in to, that Worker's side. */export function appleApps(rows: Row[], team: string, side: Side): string[] {  // An app with no dev identity (one App Store record, as a business app is) has nothing on the dev Worker.  return rows.filter(signsInOnIphone).flatMap((row) => {    const variant = side === "live" ? row.ios!.live : row.ios!.dev;    return variant ? [`${team}.${variant.bundleId}`] : [];  });}/** * The apps that open a Circle invitation link (`<host>/c/<code>#<secret>`, cotton-ffi phone/circle.rs): Comms and * Contacts, once each is cut to phones. Each hands the whole link to `circle.invite.open`. */export const CIRCLE_LINK_APPS: ReadonlySet<string> = new Set(["messages", "contacts"]);/** The path an invitation link takes on the open host. */export const CIRCLE_LINK_PATH = "/c/*";export function appleSiteAssociation(rows: Row[], team: string, side: Side): string | null {  const apps = appleApps(rows, team, side);  if (apps.length === 0) return null;  const opening = appleApps(rows.filter((row) => CIRCLE_LINK_APPS.has(row.slug)), team, side);  return JSON.stringify({ webcredentials: { apps }, ...(opening.length ? { applinks: { details: [{ appIDs: opening, components: [{ "/": CIRCLE_LINK_PATH }] }] } } : {}) });}const FINGERPRINT = /^[0-9A-F]{2}(:[0-9A-F]{2}){31}$/;/** Every Android app cut to phones with a package on that side (a null devPackage is no dev app), and the certificates its row lists (none yet is an empty list). */export function androidApps(rows: Row[], side: Side): { slug: string; package: string; fingerprints: string[] }[] {  return rows.filter(signsInOnAndroid).flatMap((row) => {    const pkg = side === "live" ? row.android!.package : row.android!.devPackage;    if (!pkg) return [];    const fingerprints = row.android!.signing?.[side] ?? [];    for (const one of fingerprints) {      if (!FINGERPRINT.test(one)) throw new Error(`${row.slug}: android.signing.${side} has ${one}, not a SHA-256 in colon hex (AB:CD:…)`);    }    return [{ slug: row.slug, package: pkg, fingerprints }];  });}export function androidAssetLinks(rows: Row[], side: Side): string | null {  const statements = androidApps(rows, side)    .filter((app) => app.fingerprints.length > 0)    .map((app) => ({      relation: CIRCLE_LINK_APPS.has(app.slug) ? ["delegate_permission/common.get_login_creds", "delegate_permission/common.handle_all_urls"] : ["delegate_permission/common.get_login_creds"],      target: { namespace: "android_app", package_name: app.package, sha256_cert_fingerprints: app.fingerprints },    }));  return statements.length > 0 ? JSON.stringify(statements) : null;}/** A certificate's SHA-256 (colon hex) as the WebAuthn origin an Android app signs with. */export function apkKeyHash(fingerprint: string): string {  return `android:apk-key-hash:${Buffer.from(fingerprint.replaceAll(":", ""), "hex").toString("base64url")}`;}export function androidOrigins(rows: Row[], side: Side): string | null {  const origins = androidApps(rows, side).flatMap((app) => app.fingerprints.map(apkKeyHash));  return origins.length > 0 ? origins.join(",") : null;}/** The managed vars, in the order they are written, for one side. */export function managedVars(rows: Row[], team: string, side: Side): [string, string | null][] {  return [    ["APPLE_APP_SITE_ASSOCIATION", appleSiteAssociation(rows, team, side)],    ["ANDROID_ASSET_LINKS", androidAssetLinks(rows, side)],    ["PASSKEY_ANDROID_ORIGINS", androidOrigins(rows, side)],  ];}const MANAGED = /^\s*("(APPLE_APP_SITE_ASSOCIATION|ANDROID_ASSET_LINKS|PASSKEY_ANDROID_ORIGINS)": .*,|\/\/ Written by `pnpm -s passkey:associations`.*)$/;/** * wrangler.jsonc with one Worker's managed vars written right after its `"OPEN_HOST": "<host>",` line, the * managed lines already there replaced. The host names the block, so the live and dev Workers never mix. */export function withVars(text: string, host: string, vars: [string, string | null][]): string {  const lines = text.split("\n");  const at = lines.findIndex((line) => line.trim() === `"OPEN_HOST": ${JSON.stringify(host)},`);  if (at < 0) throw new Error(`wrangler.jsonc has no "OPEN_HOST": "${host}", line to write after`);  const indent = /^\s*/.exec(lines[at]!)![0];  // The managed lines are taken out wherever they stand in this Worker's vars, not only right after OPEN_HOST: a  // var written between them later (GOOGLE_BASE, 24 Nov 2026) left the old list below the new one, and a repeated  // key in wrangler.jsonc is read last-wins, so the Worker served the old list (the Post, Sites and Data cut, 26 Nov).  let close = at + 1;  while (close < lines.length && !lines[close]!.trim().startsWith("}")) close += 1;  const rest = lines.slice(at + 1, close).filter((line) => !MANAGED.test(line));  const written = vars.filter((pair): pair is [string, string] => pair[1] !== null);  const block = written.length > 0    ? [`${indent}// Written by \`pnpm -s passkey:associations\` from apps/registry.json; never by hand.`, ...written.map(([name, value]) => `${indent}${JSON.stringify(name)}: ${JSON.stringify(value)},`)]    : [];  return [...lines.slice(0, at + 1), ...block, ...rest, ...lines.slice(close)].join("\n");}export const HOSTS: Record<Side, string> = { live: "cottondb.com", dev: devHost() };/** wrangler.jsonc as the registry says it should be. */export function expectedWrangler(text: string, rows: Row[], team: string): string {  return (["live", "dev"] as const).reduce((out, side) => withVars(out, HOSTS[side], managedVars(rows, team, side)), text);}function main(): void {  const mode = process.argv[2];  const rows = readRows();  const team = readTeam();  const text = readFileSync(WRANGLER, "utf8");  const expected = expectedWrangler(text, rows, team);  if (mode === "--write") {    if (expected !== text) writeFileSync(WRANGLER, expected, "utf8");    console.log(expected === text ? "passkey:associations: wrangler.jsonc is current" : "passkey:associations: wrangler.jsonc written");    return;  }  if (mode === "--check") {    if (expected === text) return;    console.error("passkey:associations: apps/business/wrangler.jsonc is not what apps/registry.json says; run pnpm -s passkey:associations --write");    process.exit(1);  }  if (mode !== undefined) {    console.error("usage: pnpm -s passkey:associations [--write | --check]");    process.exit(2);  }  for (const side of ["live", "dev"] as const) {    console.log(`${side} (${HOSTS[side]})`);    for (const [name, value] of managedVars(rows, team, side)) console.log(`  ${name}: ${value ?? "(none: nothing to list)"}`);    for (const app of androidApps(rows, side).filter((one) => one.fingerprints.length === 0)) {      console.log(`  owed: ${app.slug} (${app.package}) lists no android.signing.${side} certificate`);    }  }}if (process.argv[1]?.endsWith("site-associations.ts")) main();