Cotton code
812 lines · 43.0 KB · TypeScriptRaw
/** * Apply the extension gate to the project spec, at GENERATION time. * * `apps/cotton/project.yml` declares `COTTON_SHARE_ENABLED` as a build * setting, `YES`. This reads that default, lets an environment variable of the * same name override it, and — when the gate is off — writes a spec with that * target and the app's dependency on it removed. * * WHY GENERATION TIME. A build setting cannot drop a target from the graph. An * extension deleted from the built `.app` afterwards has still been built and * signed, and Xcode's own `ValidateEmbeddedBinary` then fails on the hole — * measured, not assumed. * * It also writes out each BUSINESS FLAVOUR the spec declares * (`businessFlavours`): the app and its share extension cloned from * `Cotton`'s, under the flavour's identity, with a scheme of the same name. * A gated-off extension is gone from every family, because the clone is made * after the gate. * * Usage: `tsx scripts/ios-spec-gate.ts <spec-in> <spec-out>`. It prints the * gates it applied and exits 3 when every gate is on and no business flavour * is declared, which is the caller's signal to use the original spec and write * no file at all. */import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";import { parse, stringify } from "yaml";import { signsInOnIphone, type Registry } from "./lib/registry";/** Where `project.yml` and every path it names live. */const IOS_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "apps", "cotton");/** * THE DEV SERVER IS A SETTING. Every flavour.json names its dev side as * `https://{dev-host}`; the host is config/dev-server.json's (the one place * the Worker's dev deploy, the Android build and the scripts read it too). * The bundle carries a filled-in copy of each manifest, written under * `.manifests/<target>/flavour.json` beside the gated spec, so the app reads * its real dev address and the tree names none. */export const DEV_HOST_TOKEN = "{dev-host}";export const DEV_SERVER_CONFIG = join(IOS_DIR, "..", "..", "config", "dev-server.json");export const MANIFESTS_DIR = ".manifests";/** The dev Worker's host, from config/dev-server.json; refused when it is not one. */export function devHost(config = DEV_SERVER_CONFIG): string {  if (!existsSync(config)) throw new Error(`${config} is missing: it names the dev Worker every app's dev build signs in at ({"host": "<your dev Worker's host>"})`);  const host = (JSON.parse(readFileSync(config, "utf8")) as { host?: unknown }).host;  if (typeof host !== "string" || !/^[a-z0-9.-]+$/i.test(host)) throw new Error(`${config}: "host" is no host name`);  return host;}/** A manifest's text with the dev host filled in. */export function filledManifest(path: string, host = devHost()): string {  return readFileSync(join(IOS_DIR, path), "utf8").split(DEV_HOST_TOKEN).join(host);}/** The bundle's copy of a manifest: written for the caller, and its path from the project. */function bundledManifest(target: string, path: string, written: Written[]): string {  const at = `${MANIFESTS_DIR}/${target}/flavour.json`;  written.push({ path: at, text: filledManifest(path) });  return at;}/** * Each gate, and the target it decides. * * The phone's one extension, the share extension. The Mac ships none, so the * spec has no macOS target to gate. */export const EXTENSION_GATES: Record<string, string> = {  COTTON_SHARE_ENABLED: "CottonShareExtension",};/** Xcode's spelling of a boolean, which is not JavaScript's. */export function isOff(value: unknown): boolean {  const text = String(value).trim().toUpperCase();  return text === "NO" || text === "0" || text === "FALSE";}interface Target {  /** A target it builds and embeds, or a package product it links (CottonCalls for the Calling targets). */  dependencies?: ({ target?: string; embed?: boolean; codeSign?: boolean } | { package: string; product: string })[];  sources?: (string | { path: string; [key: string]: unknown })[];  settings?: { base?: Record<string, unknown>; [key: string]: unknown };  [key: string]: unknown;}interface Spec {  settings?: { base?: Record<string, unknown> };  targets: Record<string, Target>;  passkeyProvider?: Target;  chatNotifications?: Target;  meetingsWidgets?: Target;  schemes?: Record<string, Record<string, unknown>>;  businessFlavours?: Record<string, BusinessFlavour>;}/** One business, as `project.yml`'s `businessFlavours` declares it. */export interface BusinessFlavour {  target: string;  appId: string;  displayName: string;  urlScheme: string;  appIcon: string;  icons: string;  manifest: string;  /**   * Info.plist keys this flavour's APP carries beyond Cotton's, merged over   * the clone's own — what one flavour opens that the others do not (Rigby's   * `.cottonpkg` document type). Optional, and the app target's only: the   * extensions open no documents.   */  info?: Record<string, unknown>;  /**   * The flavour's second identity, for a family that is two apps by   * `COTTON_FLAVOR` as Cotton is (Cotton Books and Cotton Books Dev): the   * dev side's app id, label, URL scheme and icon. Absent, the family is one   * identity whatever `COTTON_FLAVOR` says (a business app is one App Store   * record).   */  dev?: Identity;  /**   * The share extension's activation rule, in place of Cotton's six: a   * predicate naming the types this flavour takes (Cotton Books: an EPUB, a   * PDF or a Goodreads CSV). Absent, the clone keeps Cotton's rule.   */  shareRule?: string;  /**   * `false` when the flavour takes no shares at all, so its family is the app   * alone: Cotton Money, whose rows an assistant writes over MCP and whose   * kit holds no table a shared file could become (6 Nov 2026). Absent, the   * family carries the share extension.   */  share?: false;  /**   * `true` for the passkey app (Cotton Keys): its family carries the passkey   * provider cloned from the spec's `passkeyProvider` template, embedded in   * the app. Absent, the family has none — Cotton never does.   */  provider?: true;  /**   * `true` for an app that carries Cotton chat (Cotton Messages): its family   * carries the notification service extension cloned from the spec's   * `chatNotifications` template, embedded in the app, which rewrites a chat   * push to its sender and words. Absent, the family has none.   */  notifications?: true;  /**   * `true` for Cotton Meetings: its family carries the widget extension   * cloned from the spec's `meetingsWidgets` template (the recording's Live   * Activity and the control that starts one), embedded in the app. Absent,   * the family has none.   */  widgets?: true;  /**   * Folders this flavour's APP alone carries as resources, copied whole by   * name into its bundle: what one app draws with and no other ships (Cotton   * Vault's faces, `App/Flavours/keys/VaultFonts`, with their licences).   */  resources?: string[];  /**   * The app's own entitlements in place of Cotton's: Cotton Keys' adds the   * AutoFill credential provider entitlement its identity store needs.   */  entitlements?: string;  /**   * Package products this flavour's APP links beyond Cotton's: what one app   * runs that no other carries (Cotton Calling's `CottonCalls`, which brings   * the WebRTC framework). The app target's only.   */  dependencies?: { package: string; product: string }[];  /**   * Build settings this flavour's APP sets beyond the clone's own (Cotton   * Calling's `SWIFT_ACTIVE_COMPILATION_CONDITIONS: $(inherited) COTTON_CALLING`,   * which lets the shared app source start its engine). The app target's only.   */  settings?: Record<string, string>;  /**   * Script phases this flavour's APP alone runs once its bundle is built: Cotton Albums' face model, put in the bundle   * from outside the repository by its pinned SHA-256, the build failing when it is absent or wrong. The app target's   * only, after the phases every clone carries.   */  scripts?: { name: string; script: string; inputFiles?: string[] }[];  /**   * `true` for an app that asks only for what it uses (Story, Days, Words for   * the App Store, 22 Nov 2026): every permission prompt, background mode,   * background task and Bonjour service inherited from Cotton's plist is   * dropped, so the app carries only what its own `info` gives (App Review   * 5.1.1(ii), 2.5.4). Absent, the clone keeps Cotton's whole set.   */  ownPermissions?: true;  /**   * `false` for an app that may read the photo library but must never change it (Cotton Albums' look-only build,   * owner 27 Nov 2026): built with `COTTON_NO_PHOTO_WRITES`, and refused here if its plist still asks to add photos.   */  photoWrites?: false;  /**   * Swift compilation conditions this flavour's APP target alone is built with: `COTTON_ALBUMS` puts Cotton Albums'   * PhotoKit library (`App/Cotton/AlbumsPhotos+Photos.swift`) into Albums and no other app (ITMS-90683).   */  conditions?: string[];  /**   * The app's privacy manifest (`PrivacyInfo.xcprivacy`), relative to   * `apps/cotton`, copied into the app's bundle: what it collects and why it   * reads the required-reason APIs. The app target's only.   */  privacyManifest?: string;}/** * The Info.plist keys an `ownPermissions` app drops from Cotton's before its * own `info` is merged: what a person is asked for and what runs in the * background. */export function permissionKey(key: string): boolean {  return key.endsWith("UsageDescription") || ["UIBackgroundModes", "BGTaskSchedulerPermittedIdentifiers", "NSBonjourServices"].includes(key);}/** * The export-compliance keys (App Store Connect, 22 Nov 2026). An `ownPermissions` app drops Cotton's `false`: * these apps seal with the core's own AES-256-GCM, X25519 and Ed25519, so "no non-exempt encryption" is not * theirs to say. With neither key, App Store Connect asks the export questions for each build. `true` alone is * refused at upload (altool 90592: "The export compliance key value [] … doesn't match … documentation"): it goes * only with the `ITSEncryptionExportComplianceCode` Apple issues once it has approved the app's documentation * (https://developer.apple.com/documentation/security/complying-with-encryption-export-regulations). */export const EXPORT_KEYS = ["ITSAppUsesNonExemptEncryption", "ITSEncryptionExportComplianceCode"] as const;/** Why an app's export keys would be refused at upload; null when they would not. */export function exportRefusal(properties: Record<string, unknown>): string | null {  if (properties.ITSAppUsesNonExemptEncryption === false) {    return "ITSAppUsesNonExemptEncryption is false in the plist: the four apps carry no export key, so each build is answered the one same way after its upload, by pnpm phone:cut (the export-compliance answer: standard encryption, not in France). Leave the key out.";  }  const code = properties.ITSEncryptionExportComplianceCode;  if (properties.ITSAppUsesNonExemptEncryption === true && (typeof code !== "string" || code.trim() === "")) {    return "ITSAppUsesNonExemptEncryption is true with no ITSEncryptionExportComplianceCode: App Store Connect refuses the upload (90592). Leave both out until Apple issues the code.";  }  return null;}/** * The Swift condition an app is built with when its plist carries no NSContactsUsageDescription: the address book * (`App/Cotton/AddressBook+Contacts.swift`, the one source that names Contacts) is left out, so the binary does not * reference the Contacts API and App Store processing asks for no purpose string (ITMS-90683, Words build 21, 22 Nov 2026). */export const NO_CONTACTS = "COTTON_NO_CONTACTS";export const NO_CAMERA = "COTTON_NO_CAMERA";export const NO_PHOTOS = "COTTON_NO_PHOTOS";/** * A flavour that may read photos but never change them (`photoWrites: false`): Cotton Albums' first build only looks * (owner, 27 Nov 2026). The app target's photo writers (`CameraRoll+Photos.swift`'s camera roll, * `AlbumsWrites+Photos.swift`) are compiled out, so its binary holds no call to `PHPhotoLibrary.performChanges`. */export const NO_PHOTO_WRITES = "COTTON_NO_PHOTO_WRITES";/** * Each privacy API the app target alone names (`App/Cotton/AddressBook+Contacts.swift`, `Camera+AVFoundation.swift`, * `CameraRoll+Photos.swift`), and the plist keys that keep it in: an own-permissions app with none of them is built * with the condition, without the code, and without the reference App Store processing would ask a string for. */export const COMPILED_OUT: { condition: string; keys: string[] }[] = [  { condition: NO_CONTACTS, keys: ["NSContactsUsageDescription"] },  { condition: NO_CAMERA, keys: ["NSCameraUsageDescription"] },  { condition: NO_PHOTOS, keys: ["NSPhotoLibraryUsageDescription", "NSPhotoLibraryAddUsageDescription"] },];/** * The privacy APIs the shared packages always link (CottonUI's dictation: AVAudioRecorder, AVAudioApplication, * SFSpeechRecognizer), so every app's binary references them and App Store processing asks for their strings whatever * the app shows. An own-permissions app without them is refused here, at generation, rather than at the archive * (the cuts of Post and Sites from 852b2d03fa, 26 Nov 2026: `phone:cut --dry-run` reads no binary and passed). */export const ALWAYS_LINKED: { api: string; key: string }[] = [  { api: "Microphone", key: "NSMicrophoneUsageDescription" },  { api: "Speech recognition", key: "NSSpeechRecognitionUsageDescription" },];/** What an own-permissions app's plist lacks of ALWAYS_LINKED, as a refusal; null when it has each. */export function linkedRefusal(properties: Record<string, unknown>): string | null {  const missing = ALWAYS_LINKED.filter((one) => typeof properties[one.key] !== "string" || String(properties[one.key]).trim() === "");  if (missing.length === 0) return null;  return `the shared code links ${missing.map((m) => m.api).join(" and ")}, so its info must carry ${missing.map((m) => m.key).join(" and ")} (App Store processing refuses the build, ITMS-90683)`;}/** One side of a two-app family: what `dev` names. */export interface Identity {  appId: string;  displayName: string;  urlScheme: string;  appIcon: string;}/** Cotton's own manifest, a source of the `Cotton` target that no clone carries. */export const COTTON_MANIFEST = "App/CottonManifest/flavour.json";/** The app every family is cloned from, and the scheme that builds it. */export const FAMILY_APP = "Cotton";export const FAMILY_SCHEME = "tinmen-cotton";/** * The phone extensions a family carries, by the suffix after the app's * target name. A business flavour is a phone app. */export const FAMILY_EXTENSIONS = ["ShareExtension"];/** The suffix of the passkey provider a `provider: true` family carries. */export const PROVIDER_SUFFIX = "Provider";/** The suffix of the chat notification extension a `notifications: true` family carries. */export const NOTIFICATIONS_SUFFIX = "Notifications";/** The suffix of the widget extension a `widgets: true` family carries. */export const WIDGETS_SUFFIX = "Widgets";/** The intents' words a `widgets: true` app carries beside its extension. */export const MEETINGS_INTENT_STRINGS = "App/MeetingsWidgets/Strings";const FLAVOUR_KEYS: (keyof BusinessFlavour)[] = [  "target",  "appId",  "displayName",  "urlScheme",  "appIcon",  "icons",  "manifest",];/** Which targets this environment turns off, given the spec's own defaults. */export function gatedOut(spec: Spec, env: Record<string, string | undefined>): string[] {  const base = spec.settings?.base ?? {};  return Object.entries(EXTENSION_GATES)    .filter(([gate]) => isOff(env[gate] ?? base[gate] ?? "YES"))    .map(([, target]) => target);}/** The spec without those targets, or the same object when none are gated. */export function withoutTargets(spec: Spec, targets: string[]): Spec {  for (const name of targets) {    delete spec.targets[name];    for (const target of Object.values(spec.targets)) {      if (!target.dependencies) continue;      target.dependencies = target.dependencies.filter((one) => !("target" in one) || one.target !== name);    }  }  return spec;}/** * One business flavour's two targets and its scheme, added to the spec. * * Each clone is Cotton's target with the family's names in place of * Cotton's, and the IDENTITY set at target level: `COTTON_APP_ID`, * `COTTON_DISPLAY_NAME`, `COTTON_URL_SCHEME` and `COTTON_APPICON_NAME` are the * four settings every bundle id, the app group, the label, the scheme and the * icon are derived from, so overriding them is the whole identity — and a * target setting beats the project's `$(X_$(COTTON_FLAVOR))` pair whatever * `COTTON_FLAVOR` says. The app also carries the manifest (as `flavour.json`) * and the flavour's icon catalogue. */export function withBusinessFlavour(spec: Spec, name: string, flavour: BusinessFlavour, written: Written[] = []): Spec {  for (const key of FLAVOUR_KEYS) {    if (typeof flavour[key] !== "string" || flavour[key].trim() === "") {      throw new Error(`business flavour ${name}: ${key} is required`);    }  }  if (flavour.share !== undefined && flavour.share !== false) throw new Error(`business flavour ${name}: share is false or absent`);  if (flavour.share === false && flavour.shareRule !== undefined) throw new Error(`business flavour ${name}: a flavour that takes no shares has no share rule`);  if (flavour.provider !== undefined && flavour.provider !== true) throw new Error(`business flavour ${name}: provider is true or absent`);  if (flavour.notifications !== undefined && flavour.notifications !== true) throw new Error(`business flavour ${name}: notifications is true or absent`);  if (flavour.widgets !== undefined && flavour.widgets !== true) throw new Error(`business flavour ${name}: widgets is true or absent`);  for (const folder of flavour.resources ?? []) {    if (typeof folder !== "string" || !existsSync(join(IOS_DIR, folder))) throw new Error(`business flavour ${name}: resources folder ${String(folder)} does not exist`);  }  const app = spec.targets[FAMILY_APP];  if (!app) throw new Error(`business flavour ${name}: the spec has no ${FAMILY_APP} target to clone`);  if (spec.targets[flavour.target]) throw new Error(`business flavour ${name}: target ${flavour.target} already exists`);  const identity = flavour.dev ? pairedIdentity(name, flavour, flavour.dev) : {    COTTON_APP_ID: flavour.appId,    COTTON_DISPLAY_NAME: flavour.displayName,    COTTON_URL_SCHEME: flavour.urlScheme,    COTTON_APPICON_NAME: flavour.appIcon,    // A business app (no dev pair) keeps a keychain group of its own: it    // shares no key with Cotton's family (e2e rulings R9). A two-app family    // inherits the project's one group per flavour.    COTTON_KEYCHAIN_GROUP: `${flavour.appId}.keys`,  };  const renamed = (target: string): string =>    target.startsWith(FAMILY_APP) ? flavour.target + target.slice(FAMILY_APP.length) : target;  const clone = (source: Target, extra: Record<string, unknown>): Target => {    const copy = structuredClone(source);    copy.dependencies = copy.dependencies?.map((one) => ("target" in one && one.target ? { ...one, target: renamed(one.target) } : one));    copy.settings = { ...copy.settings, base: { ...copy.settings?.base, ...identity, ...extra } };    return copy;  };  const appClone = clone(app, {    PRODUCT_NAME: flavour.target,    ...(flavour.entitlements ? { CODE_SIGN_ENTITLEMENTS: flavour.entitlements } : {}),    ...(flavour.settings ?? {}),  });  if (flavour.dependencies) {    appClone.dependencies = [...(appClone.dependencies ?? []), ...structuredClone(flavour.dependencies)];  }  if (flavour.scripts) {    const inherited = (appClone.postBuildScripts as unknown[] | undefined) ?? [];    appClone.postBuildScripts = [...inherited, ...flavour.scripts.map((one) => ({ ...structuredClone(one), basedOnDependencyAnalysis: false }))];  }  ownInfo(appClone, name, "", manifestName(flavour));  if (flavour.ownPermissions) {    const info = appClone.info as { properties?: Record<string, unknown> };    for (const key of Object.keys(info.properties ?? {})) {      if (permissionKey(key) || (EXPORT_KEYS as readonly string[]).includes(key)) delete info.properties![key];    }  }  if (flavour.info) {    const info = appClone.info as { properties?: Record<string, unknown> };    info.properties = { ...info.properties, ...structuredClone(flavour.info) };  }  {    const properties = (appClone.info as { properties?: Record<string, unknown> }).properties ?? {};    const refused = exportRefusal(properties);    if (refused) throw new Error(`${name}: ${refused}`);    const unlinked = flavour.ownPermissions ? linkedRefusal(properties) : null;    if (unlinked) throw new Error(`${name}: ${unlinked}`);    // An app that does not say why it would use contacts, the camera or photos carries no code that can (ITMS-90683).    if (flavour.photoWrites === false && properties.NSPhotoLibraryAddUsageDescription) {      throw new Error(`${name}: photoWrites is false but the plist still asks to add photos (NSPhotoLibraryAddUsageDescription)`);    }    if (flavour.ownPermissions || flavour.photoWrites === false || flavour.conditions) {      const left = flavour.ownPermissions ? COMPILED_OUT.filter((one) => !one.keys.some((key) => properties[key])).map((one) => one.condition) : [];      if (flavour.photoWrites === false) left.push(NO_PHOTO_WRITES);      left.push(...(flavour.conditions ?? []));      if (left.length > 0) {        const base = (appClone.settings as { base: Record<string, unknown> }).base;        const conditions = String(base.SWIFT_ACTIVE_COMPILATION_CONDITIONS ?? "$(inherited)");        base.SWIFT_ACTIVE_COMPILATION_CONDITIONS = [conditions, ...left].join(" ");      }    }  }  const storyboard = launchScreen(appClone, flavour);  appClone.sources = [    // Cotton's own manifest is Cotton's: a clone carries its flavour's instead.    ...(appClone.sources ?? []).filter((one) => (typeof one === "string" ? one : one.path) !== COTTON_MANIFEST),    { path: flavour.icons, buildPhase: "resources" },    { path: bundledManifest(flavour.target, flavour.manifest, written), buildPhase: "resources" },    ...(flavour.privacyManifest ? [{ path: flavour.privacyManifest, buildPhase: "resources" }] : []),    // A folder reference, copied whole under its own name (`Bundle.main`'s `VaultFonts/`).    ...(flavour.resources ?? []).map((folder) => ({ path: folder, type: "folder", buildPhase: "resources" })),    ...(storyboard ? [{ path: storyboard, buildPhase: "resources" }] : []),    // The intents' words (their titles and Siri phrases are keys in Swift),    // read from the app's bundle as from the extension's.    ...(flavour.widgets ? [{ path: MEETINGS_INTENT_STRINGS, buildPhase: "resources" }] : []),  ];  spec.targets[flavour.target] = appClone;  for (const suffix of FAMILY_EXTENSIONS) {    const source = spec.targets[FAMILY_APP + suffix];    // Gated off, so gone from Cotton's family too — and from the clone's    // dependencies, which named it; or a flavour that takes no shares.    if (!source || flavour.share === false) {      appClone.dependencies = appClone.dependencies?.filter((one) => !("target" in one) || one.target !== flavour.target + suffix);      continue;    }    const extension = clone(source, {});    ownInfo(extension, name, suffix, manifestName(flavour));    if (flavour.shareRule !== undefined) shareRule(extension, name, flavour.shareRule);    spec.targets[flavour.target + suffix] = extension;  }  if (flavour.provider) {    if (!spec.passkeyProvider) throw new Error(`business flavour ${name}: the spec has no passkeyProvider to clone`);    const provider = clone(spec.passkeyProvider, {});    ownInfo(provider, name, PROVIDER_SUFFIX, manifestName(flavour));    spec.targets[flavour.target + PROVIDER_SUFFIX] = provider;    appClone.dependencies = [...(appClone.dependencies ?? []), { target: flavour.target + PROVIDER_SUFFIX, embed: true, codeSign: true }];  }  if (flavour.notifications) {    if (!spec.chatNotifications) throw new Error(`business flavour ${name}: the spec has no chatNotifications to clone`);    const notifications = clone(spec.chatNotifications, {});    ownInfo(notifications, name, NOTIFICATIONS_SUFFIX, manifestName(flavour));    spec.targets[flavour.target + NOTIFICATIONS_SUFFIX] = notifications;    appClone.dependencies = [...(appClone.dependencies ?? []), { target: flavour.target + NOTIFICATIONS_SUFFIX, embed: true, codeSign: true }];  }  if (flavour.widgets) {    if (!spec.meetingsWidgets) throw new Error(`business flavour ${name}: the spec has no meetingsWidgets to clone`);    const widgets = clone(spec.meetingsWidgets, {});    ownInfo(widgets, name, WIDGETS_SUFFIX, manifestName(flavour));    spec.targets[flavour.target + WIDGETS_SUFFIX] = widgets;    appClone.dependencies = [...(appClone.dependencies ?? []), { target: flavour.target + WIDGETS_SUFFIX, embed: true, codeSign: true }];  }  const scheme = spec.schemes?.[FAMILY_SCHEME];  if (scheme) {    // Build, run and archive the flavour's app; the tests stay Cotton's.    const { test: _test, ...rest } = structuredClone(scheme);    spec.schemes![name] = { ...rest, build: { targets: { [flavour.target]: "all" } } };  }  return spec;}/** * A two-app family's identity: each of the four settings as a `_real`/`_dev` * pair switched by `COTTON_FLAVOR`, the way the project's own base settings * switch Cotton's — so Cotton Books Dev never resolves Cotton Books' ids. */function pairedIdentity(name: string, real: BusinessFlavour, dev: Identity): Record<string, string> {  const keys: [string, keyof Identity][] = [    ["COTTON_APP_ID", "appId"],    ["COTTON_DISPLAY_NAME", "displayName"],    ["COTTON_URL_SCHEME", "urlScheme"],    ["COTTON_APPICON_NAME", "appIcon"],  ];  const out: Record<string, string> = {};  for (const [setting, key] of keys) {    if (typeof dev[key] !== "string" || dev[key].trim() === "") throw new Error(`business flavour ${name}: dev.${key} is required`);    if (dev[key] === real[key]) throw new Error(`business flavour ${name}: dev.${key} is the real app's`);    out[`${setting}_real`] = real[key];    out[`${setting}_dev`] = dev[key];    out[setting] = `$(${setting}_$(COTTON_FLAVOR))`;  }  return out;}/** The share extension's activation rule replaced by the flavour's predicate. */function shareRule(target: Target, name: string, rule: string): void {  const attributes = (target.info as { properties?: { NSExtension?: { NSExtensionAttributes?: Record<string, unknown> } } } | undefined)    ?.properties?.NSExtension?.NSExtensionAttributes;  if (!attributes) throw new Error(`business flavour ${name}: the share extension has no activation rule to replace`);  if (rule.trim() === "") throw new Error(`business flavour ${name}: shareRule is empty`);  attributes.NSExtensionActivationRule = rule;}/** * Why a manifest's database cannot be built, or null when it can. Every app * is one app over one database, by data (owner's 62nd–64th rulings): Cotton's * names `"personal"` (the person's own object, signed in at the open host), * and every business names its object on the Worker — the https server and * its slug under `business` — the only object the phone opens (the Worker, * 24 Oct 2026; the relay database is gone, 25 Oct 2026). */export function manifestDatabaseRefusal(path: string, manifest: { database?: unknown; business?: unknown }): string | null {  if (manifest.database === "personal") return null;  if (manifest.database !== undefined) return `${path}: its database is "personal" or a business object, nothing else`;  const business = manifest.business;  if (typeof business !== "object" || business === null || Array.isArray(business)) {    return `${path}: names no database — "personal", or a business {"server", "slug"}`;  }  const { server, slug } = business as { server?: unknown; slug?: unknown };  if (typeof server !== "string" || !server.startsWith("https://")) return `${path}: its business names no https server`;  if (typeof slug !== "string" || !/^[a-z0-9-]+$/.test(slug)) return `${path}: its business names no slug`;  return null;}/** A manifest that does not say its database is a build that does not happen. */function refuseWithoutDatabase(path: string): void {  const refusal = manifestDatabaseRefusal(path, JSON.parse(readFileSync(join(IOS_DIR, path), "utf8")));  if (refusal) throw new Error(refusal);}/** The name the flavour's manifest says, which every sentence it shows is said in. */function manifestName(flavour: BusinessFlavour): string {  refuseWithoutDatabase(flavour.manifest);  const name = (JSON.parse(readFileSync(join(IOS_DIR, flavour.manifest), "utf8")) as { name?: unknown }).name;  if (typeof name !== "string" || name.trim() === "") throw new Error(`business flavour manifest ${flavour.manifest}: name is required`);  return name;}/** The launch storyboard an app on its own ground launches with, beside its manifest, and what it draws from its flavour's catalogue. */export const LAUNCH_STORYBOARD = "LaunchScreen";export const LAUNCH_GROUND = "LaunchGround";export const LAUNCH_SURFACE = "LaunchSurface";export const LAUNCH_LAMP = "LaunchLamp";export const LAUNCH_OBJECT = "LaunchObject";/** * The ground a flavour launches on (a `FaceGround` id), or undefined: Cotton's paper. It is the ground the app stands * on (`ground`), or, for an app that stands on the shell's paper and still launches on its icon's ground, the one its * manifest names for the launch alone (`launch`: Messages, whose chats lie on paper, 15 Nov 2026). */export function manifestGround(flavour: BusinessFlavour): string | undefined {  const manifest = JSON.parse(readFileSync(join(IOS_DIR, flavour.manifest), "utf8")) as { ground?: unknown; launch?: unknown };  for (const key of ["launch", "ground"] as const) {    const ground = manifest[key];    if (ground === undefined) continue;    if (typeof ground !== "string" || ground.trim() === "") throw new Error(`business flavour manifest ${flavour.manifest}: ${key} is a FaceGround id`);    return ground;  }  return undefined;}/** A flat flavour (`flat` in its manifest): a plain colour, light and dark, and no painted ground to launch on. */export function isFlat(flavour: BusinessFlavour): boolean {  const manifest = JSON.parse(readFileSync(join(IOS_DIR, flavour.manifest), "utf8")) as { flat?: unknown };  return manifest.flat !== undefined;}/** Where a flavour's launch storyboard is, relative to the app's directory: beside its manifest. */export function launchStoryboard(flavour: BusinessFlavour): string {  return join(dirname(flavour.manifest), `${LAUNCH_STORYBOARD}.storyboard`);}/** * An app that stands on a ground of its own launches on it (12 Nov 2026), the * ground as the app lays it, full bleed, its icon's object cut out in the * middle (13 Nov 2026): a launch storyboard beside the flavour's manifest, * drawing its catalogue's `LaunchGround` colour, `LaunchSurface` (the ground * laid from the screen's top left, never scaled), `LaunchLamp` where the ground has a lamp and * `LaunchObject` centred (`scripts/gen-launch-screens.py` writes them all); * the splash after it draws the same (`SplashOverlay`). Every picture the * storyboard names must be in the catalogue, or the launch screen would draw * a hole where it stands. A flavour that names no ground to launch on and is not flat keeps Cotton's * launch screen. Answers the storyboard's path, for the target's resources. */function launchScreen(target: Target, flavour: BusinessFlavour): string | undefined {  // A flat app launches on its own colour and mark (Comms names no ground: its chats lie on the shell's paper).  if (manifestGround(flavour) === undefined && !isFlat(flavour)) return undefined;  const storyboard = launchStoryboard(flavour);  const regenerate = "run scripts/gen-launch-screens.py";  if (!existsSync(join(IOS_DIR, storyboard))) {    throw new Error(`business flavour ${flavour.target}: its manifest names a ground and it has no ${storyboard}: ${regenerate}`);  }  const drawn = readFileSync(join(IOS_DIR, storyboard), "utf8");  const named = [...drawn.matchAll(/<image name="(\w+)"/g)].map((one) => one[1]);  // A flat app (Cotton Story, 17 Nov 2026) has no painted ground: its launch  // screen is its flat colour, light or dark, and its word mark, no surface.  const surfaced = isFlat(flavour) || named.includes(LAUNCH_SURFACE);  if (!surfaced || !drawn.includes(`<color key="backgroundColor" name="${LAUNCH_GROUND}"/>`)) {    throw new Error(`business flavour ${flavour.target}: ${storyboard} does not lay ${LAUNCH_GROUND} and ${LAUNCH_SURFACE}: ${regenerate}`);  }  const sets = [`${LAUNCH_GROUND}.colorset`, ...named.map((name) => `${name}.imageset`)];  for (const set of sets) {    if (!existsSync(join(IOS_DIR, flavour.icons, set, "Contents.json"))) {      throw new Error(`business flavour ${flavour.target}: ${storyboard} draws ${set} and ${flavour.icons} has none: ${regenerate}`);    }  }  for (const set of [`${LAUNCH_LAMP}.imageset`, `${LAUNCH_OBJECT}.imageset`]) {    if (existsSync(join(IOS_DIR, flavour.icons, set)) && !sets.includes(set)) {      throw new Error(`business flavour ${flavour.target}: ${flavour.icons} has ${set} and ${storyboard} does not draw it: ${regenerate}`);    }  }  const info = target.info as { properties?: Record<string, unknown> };  // Cotton's own launch screen (`UILaunchScreen`, its paper's colour) is not this app's.  const properties = { ...info.properties };  delete properties.UILaunchScreen;  info.properties = { ...properties, UILaunchStoryboardName: LAUNCH_STORYBOARD };  return storyboard;}/** * The clone's own Info.plist, its permission prompts said in the business's * name. Cotton's prompts read "Cotton uses your microphone…", and a clone * that kept them showed the word Cotton to a business's customer the first * time the app asked for the camera (lane phonewalk, 19 Oct 2026). Its own * path, because two targets writing one generated plist is last-writer-wins. */function ownInfo(target: Target, flavour: string, suffix: string, name: string): void {  const info = target.info as { path?: string; properties?: Record<string, unknown> } | undefined;  if (!info) return;  // Cotton's plist sits inside a source folder the clone keeps; xcodegen leaves  // a target's own plist out of its resources, so once the clone owns another  // plist, Cotton's is copied in too and two commands produce Info.plist.  const cottons = info.path;  if (cottons) {    target.sources = target.sources?.map((one) => {      const source = typeof one === "string" ? { path: one } : one;      if (!cottons.startsWith(`${source.path}/`)) return one;      return { ...source, excludes: [...((source.excludes as string[] | undefined) ?? []), cottons.slice(source.path.length + 1)] };    });  }  info.path = `App/Flavours/${flavour}/${suffix || "App"}/Info.plist`;  for (const [key, value] of Object.entries(info.properties ?? {})) {    if (key.endsWith("UsageDescription") && typeof value === "string") {      info.properties![key] = value.replace(/\bCotton\b/g, name);    }  }}/** * PASSKEYS ON EVERY APP PEOPLE SIGN IN TO (19 Nov 2026). A Cotton * account passkey is for the sign-in host, and iOS lets an app use one only * when the app carries `webcredentials:<host>` and the host's * apple-app-site-association names the app. Each app the registry marks * as signing in on an iPhone (`signsInOnIphone`: cut to phones, development or * production, with a flavour a lane cuts) gets, here, an entitlements file of its own: its base entitlements * (the flavour's, else Cotton's) plus that one associated domain, for the host * its manifest signs in at, `COTTON_SIGNIN_HOST` by `COTTON_FLAVOR` (the live * host for the live app, the dev host for the dev one). A parked or planned * app carries none, so its profile needs no Associated Domains until it is cut. * The Worker's list is `pnpm -s passkey:associations` (the same registry). */export const ASSOCIATED_DOMAINS = "com.apple.developer.associated-domains";/** Where the gate writes each sign-in app's entitlements, relative to `apps/cotton` (gitignored, as the gated spec is). */export const PASSKEY_ENTITLEMENTS_DIR = ".entitlements";/** The Info.plist key a sign-in app says its passkey host in (`CottonKit/PasskeyPlatform.swift` `hostKey`). */export const PASSKEY_HOST_KEY = "CottonPasskeyHost";/** A file the gate writes beside the gated spec: its path relative to `apps/cotton`, and its text. */export interface Written {  path: string;  text: string;}/** The iPhone apps people sign in to (the registry's, `signsInOnIphone`), by their app target. */export function signInTargets(registryPath = join(IOS_DIR, "..", "registry.json")): Set<string> {  const registry = JSON.parse(readFileSync(registryPath, "utf8")) as Registry;  return new Set(registry.apps.filter(signsInOnIphone).map((app) => app.ios!.target));}/** The sign-in host a manifest names, each side: `business.server` is one https URL, or a `{real, dev}` pair. */export function signInHosts(path: string): { real: string; dev: string } {  const server = (JSON.parse(filledManifest(path)) as { business?: { server?: unknown } }).business?.server;  const host = (url: unknown, side: string): string => {    if (typeof url !== "string" || !url.startsWith("https://")) throw new Error(`${path}: business.server${side} is no https URL, so no passkey host`);    return new URL(url).hostname;  };  if (typeof server === "string") return { real: host(server, ""), dev: host(server, "") };  const pair = (server ?? {}) as { real?: unknown; dev?: unknown };  return { real: host(pair.real, ".real"), dev: host(pair.dev, ".dev") };}/** * The app targets that open a Circle invitation link (`https://<sign-in host>/c/<code>#<secret>`, cotton-ffi * phone/circle.rs): Comms and Contacts. They also carry `applinks:<host>`, which the host's * apple-app-site-association answers for `/c/*` (apps/business/scripts/site-associations.ts CIRCLE_LINK_APPS). */export const CIRCLE_LINK_TARGETS: ReadonlySet<string> = new Set(["CottonMessages", "CottonContacts"]);/** An entitlements plist with the `webcredentials:$(COTTON_SIGNIN_HOST)` associated domain added before its closing dict (and `applinks:` for an app that opens Circle links). */export function withWebCredentials(text: string, path: string, applinks = false): string {  if (text.includes(ASSOCIATED_DOMAINS)) throw new Error(`${path} already names ${ASSOCIATED_DOMAINS}; the gate adds it to sign-in apps alone`);  const end = text.lastIndexOf("</dict>");  if (end < 0) throw new Error(`${path} has no closing </dict>`);  const domain = `\t<!-- Generated by scripts/ios-spec-gate.ts for a sign-in app: a Cotton\n\t     account passkey for the host it signs in at. -->\n\t<key>${ASSOCIATED_DOMAINS}</key>\n\t<array>\n\t\t<string>webcredentials:$(COTTON_SIGNIN_HOST)</string>\n${applinks ? "\t\t<string>applinks:$(COTTON_SIGNIN_HOST)</string>\n" : ""}\t</array>\n`;  return text.slice(0, end) + domain + text.slice(end);}/** The flavour's app target given its own entitlements with the passkey domain, and the file that holds them. */function withPasskeyDomain(spec: Spec, name: string, flavour: BusinessFlavour, written: Written[]): void {  const app = spec.targets[flavour.target];  const base = app.settings?.base ?? {};  const from = base.CODE_SIGN_ENTITLEMENTS;  if (typeof from !== "string") throw new Error(`business flavour ${name}: its app has no entitlements to add a passkey domain to`);  const hosts = signInHosts(flavour.manifest);  const path = `${PASSKEY_ENTITLEMENTS_DIR}/${flavour.target}.entitlements`;  const host = flavour.dev    ? { COTTON_SIGNIN_HOST_real: hosts.real, COTTON_SIGNIN_HOST_dev: hosts.dev, COTTON_SIGNIN_HOST: "$(COTTON_SIGNIN_HOST_$(COTTON_FLAVOR))" }    : { COTTON_SIGNIN_HOST: hosts.real };  app.settings = { ...app.settings, base: { ...base, ...host, CODE_SIGN_ENTITLEMENTS: path } };  // The app cannot read its own entitlements, so the host is said in its Info.plist too (CottonKit's PasskeyPlatform).  const info = app.info as { properties?: Record<string, unknown> } | undefined;  if (!info) throw new Error(`business flavour ${name}: its app has no Info.plist to say its passkey host in`);  info.properties = { ...info.properties, [PASSKEY_HOST_KEY]: "$(COTTON_SIGNIN_HOST)" };  written.push({ path, text: withWebCredentials(readFileSync(join(IOS_DIR, from), "utf8"), from, CIRCLE_LINK_TARGETS.has(flavour.target)) });}/** * Every declared business flavour written out, and the declaration gone. An * app target in `signIn` (the registry's, `signInTargets`) also gets the * passkey domain, its entitlements file pushed onto `written` for the caller * to write. */export function withBusinessFlavours(spec: Spec, signIn: ReadonlySet<string> = new Set(), written: Written[] = []): Spec {  const declared = spec.businessFlavours ?? {};  delete spec.businessFlavours;  refuseWithoutDatabase(COTTON_MANIFEST);  const targets = new Set(Object.values(declared).map((flavour) => flavour.target));  for (const target of signIn) {    if (!targets.has(target)) throw new Error(`the registry's sign-in app ${target} is no business flavour in project.yml, so it would ship without its passkey domain`);  }  for (const [name, flavour] of Object.entries(declared)) {    withBusinessFlavour(spec, name, flavour, written);    if (signIn.has(flavour.target)) withPasskeyDomain(spec, name, flavour, written);  }  // Cotton's own manifest, filled in like every clone's (the clones above dropped it by its source path).  const cotton = spec.targets[FAMILY_APP];  if (cotton?.sources) {    cotton.sources = cotton.sources.map((one) =>      (typeof one === "string" ? one : one.path) === COTTON_MANIFEST        ? { ...(typeof one === "string" ? {} : one), path: bundledManifest(FAMILY_APP, COTTON_MANIFEST, written), buildPhase: "resources" }        : one,    );  }  // Templates, never targets of their own: Cotton's family builds no provider  // and no chat notification extension.  delete spec.passkeyProvider;  delete spec.chatNotifications;  delete spec.meetingsWidgets;  return spec;}function main(): void {  const [input, output] = process.argv.slice(2);  if (!input || !output) {    console.error("usage: tsx scripts/ios-spec-gate.ts <spec-in> <spec-out>");    process.exit(2);  }  const spec = parse(readFileSync(input, "utf8")) as Spec;  const dropped = gatedOut(spec, process.env);  const flavours = Object.keys(spec.businessFlavours ?? {});  // Exit 3 is "nothing to do", not a failure: the caller then hands xcodegen  // the hand-written spec rather than a copy of it.  if (dropped.length === 0 && flavours.length === 0) process.exit(3);  const written: Written[] = [];  writeFileSync(output, stringify(withBusinessFlavours(withoutTargets(spec, dropped), signInTargets(), written)), "utf8");  for (const file of written) {    mkdirSync(join(dirname(output), dirname(file.path)), { recursive: true });    writeFileSync(join(dirname(output), file.path), file.text, "utf8");  }  if (written.length > 0) console.log(`ios-spec-gate: written (manifests with the dev host, passkey domains) — ${written.map((file) => file.path).join(", ")}`);  if (dropped.length > 0) console.log(`ios-spec-gate: off — ${dropped.join(", ")}`);  if (flavours.length > 0) console.log(`ios-spec-gate: business flavours — ${flavours.join(", ")}`);}if (process.argv[1]?.endsWith("ios-spec-gate.ts")) main();