Cotton code
165 lines · 8.6 KB · TypeScriptRaw
#!/usr/bin/env tsx/** * PURPOSE STRINGS AGAINST THE BUILT BINARY (ITMS-90683, Words build 21, 22 Nov 2026). * * App Store processing scans the binary, not the source: an app that references a privacy-sensitive API must carry * that API's purpose string in its Info.plist even if it never calls it, or the build is rejected after upload. * Words was rejected for NSContactsUsageDescription because shared code named the Contacts API. * * This reads what a built `.app` links (`otool -L`) and the Objective-C classes it references (`nm -u`), in the main * binary, the debug dylib a Debug build splits off, and every embedded framework, and fails when one is referenced * without its string. Run on the archived app before every upload (fastlane `archive_export!`), and by hand: * *   tsx scripts/ios-purpose-strings.ts path/to/CottonNotes.app [more.app …] */import { execFileSync } from "node:child_process";import { existsSync, readdirSync } from "node:fs";import { basename, join } from "node:path";/** One privacy-sensitive API: what in a binary names it, and the Info.plist keys of which one must be present. */export interface PrivacyApi {  name: string;  /** Objective-C classes whose reference App Store processing reads as use. */  classes: string[];  /** Any one of these keys satisfies it. */  keys: string[];  /** false: reported but not failed (Apple does not refuse an upload for it; the prompt is still worded by the OS). */  refusedAtUpload?: false;}export const PRIVACY_APIS: PrivacyApi[] = [  { name: "Contacts", classes: ["CNContactStore", "CNContactFetchRequest", "CNContactFormatter"], keys: ["NSContactsUsageDescription"] },  { name: "Camera", classes: ["AVCaptureDevice", "AVCaptureSession"], keys: ["NSCameraUsageDescription"] },  { name: "Microphone", classes: ["AVAudioRecorder", "AVAudioApplication"], keys: ["NSMicrophoneUsageDescription"] },  { name: "Speech recognition", classes: ["SFSpeechRecognizer"], keys: ["NSSpeechRecognitionUsageDescription"] },  { name: "Photos", classes: ["PHPhotoLibrary", "PHAssetCreationRequest"], keys: ["NSPhotoLibraryUsageDescription", "NSPhotoLibraryAddUsageDescription"] },  { name: "Calendars and reminders", classes: ["EKEventStore"], keys: ["NSCalendarsFullAccessUsageDescription", "NSCalendarsWriteOnlyAccessUsageDescription", "NSCalendarsUsageDescription", "NSRemindersFullAccessUsageDescription", "NSRemindersUsageDescription"] },  { name: "Location", classes: ["CLLocationManager"], keys: ["NSLocationWhenInUseUsageDescription", "NSLocationAlwaysAndWhenInUseUsageDescription"] },  { name: "Bluetooth", classes: ["CBCentralManager", "CBPeripheralManager"], keys: ["NSBluetoothAlwaysUsageDescription"] },  { name: "Motion", classes: ["CMMotionActivityManager", "CMPedometer", "CMAltimeter"], keys: ["NSMotionUsageDescription"] },  { name: "Health", classes: ["HKHealthStore"], keys: ["NSHealthShareUsageDescription", "NSHealthUpdateUsageDescription"] },  { name: "Apple Music library", classes: ["MPMediaLibrary", "MPMediaQuery"], keys: ["NSAppleMusicUsageDescription"] },  { name: "Face ID", classes: ["LAContext"], keys: ["NSFaceIDUsageDescription"] },  { name: "Tracking", classes: ["ATTrackingManager"], keys: ["NSUserTrackingUsageDescription"] },  { name: "Siri", classes: ["INPreferences"], keys: ["NSSiriUsageDescription"] },  { name: "NFC", classes: ["NFCNDEFReaderSession", "NFCTagReaderSession"], keys: ["NFCReaderUsageDescription"] },  { name: "HomeKit", classes: ["HMHomeManager"], keys: ["NSHomeKitUsageDescription"] },];/** Frameworks whose mere linking names the API (an app that links Contacts is read as using it). */export const PRIVACY_FRAMEWORKS: Record<string, string> = {  Contacts: "Contacts",  ContactsUI: "Contacts",  EventKit: "Calendars and reminders",  EventKitUI: "Calendars and reminders",  CoreLocation: "Location",  CoreBluetooth: "Bluetooth",  CoreMotion: "Motion",  HealthKit: "Health",  AppTrackingTransparency: "Tracking",  CoreNFC: "NFC",  HomeKit: "HomeKit",};export interface Referenced {  /** Objective-C class names referenced (undefined symbols, without the `_OBJC_CLASS_$_` prefix). */  classes: Set<string>;  /** System framework names linked. */  frameworks: Set<string>;}export interface Missing {  api: string;  keys: string[];  because: string;}/** Every API the binary references without any of its keys in the plist. */export function missingPurposeStrings(referenced: Referenced, plist: Record<string, unknown>): Missing[] {  const has = (key: string) => typeof plist[key] === "string" && String(plist[key]).trim() !== "";  const out: Missing[] = [];  for (const api of PRIVACY_APIS) {    if (api.refusedAtUpload === false) continue;    const classes = api.classes.filter((one) => referenced.classes.has(one));    const frameworks = Object.entries(PRIVACY_FRAMEWORKS).filter(([framework, name]) => name === api.name && referenced.frameworks.has(framework)).map(([framework]) => framework);    if (classes.length === 0 && frameworks.length === 0) continue;    if (api.keys.some(has)) continue;    out.push({ api: api.name, keys: api.keys, because: [...frameworks.map((one) => `links ${one}`), ...classes.map((one) => `references ${one}`)].join(", ") });  }  return out;}/** Undefined Objective-C classes and linked system frameworks of one Mach-O file. */export function readBinary(path: string): Referenced {  const symbols = execFileSync("nm", ["-u", path], { encoding: "utf8", maxBuffer: 1 << 28, stdio: ["ignore", "pipe", "ignore"] });  const classes = new Set<string>();  for (const line of symbols.split("\n")) {    const found = /_OBJC_CLASS_\$_(\w+)/.exec(line);    if (found) classes.add(found[1]);  }  const linked = execFileSync("otool", ["-L", path], { encoding: "utf8", maxBuffer: 1 << 26 });  const frameworks = new Set<string>();  for (const line of linked.split("\n")) {    const found = /\/System\/Library\/Frameworks\/(\w+)\.framework\//.exec(line);    if (found) frameworks.add(found[1]);  }  return { classes, frameworks };}/** The app's executable, its Debug dylib when split off, and each embedded framework's binary. */export function binariesOf(app: string): string[] {  const plist = readPlist(app);  const executable = String(plist.CFBundleExecutable ?? basename(app, ".app"));  const out = [join(app, executable)];  const debug = join(app, `${executable}.debug.dylib`);  if (existsSync(debug)) out.push(debug);  const frameworks = join(app, "Frameworks");  if (existsSync(frameworks)) {    for (const one of readdirSync(frameworks)) {      if (one.endsWith(".framework")) {        const binary = join(frameworks, one, one.replace(/\.framework$/, ""));        if (existsSync(binary)) out.push(binary);      } else if (one.endsWith(".dylib")) out.push(join(frameworks, one));    }  }  return out.filter(existsSync);}export function readPlist(app: string): Record<string, unknown> {  return JSON.parse(execFileSync("plutil", ["-convert", "json", "-o", "-", join(app, "Info.plist")], { encoding: "utf8" }));}/** What one built app references and declares: the lines for a person, and what is missing. */export function checkApp(app: string): { missing: Missing[]; declared: string[]; referenced: string[] } {  const referenced: Referenced = { classes: new Set(), frameworks: new Set() };  for (const binary of binariesOf(app)) {    const one = readBinary(binary);    one.classes.forEach((name) => referenced.classes.add(name));    one.frameworks.forEach((name) => referenced.frameworks.add(name));  }  const plist = readPlist(app);  const apis = PRIVACY_APIS.filter((api) => api.classes.some((one) => referenced.classes.has(one)) || Object.entries(PRIVACY_FRAMEWORKS).some(([framework, name]) => name === api.name && referenced.frameworks.has(framework)));  return {    missing: missingPurposeStrings(referenced, plist),    declared: Object.keys(plist).filter((key) => key.endsWith("UsageDescription")).sort(),    referenced: apis.map((api) => api.name),  };}if (process.argv[1] && process.argv[1].endsWith("ios-purpose-strings.ts")) {  const apps = process.argv.slice(2);  if (apps.length === 0) {    console.error("usage: tsx scripts/ios-purpose-strings.ts <App.app> […]");    process.exit(2);  }  let failed = false;  for (const app of apps) {    const { missing, declared, referenced } = checkApp(app);    console.log(`${basename(app)}: references ${referenced.join(", ") || "nothing privacy-sensitive"}; declares ${declared.join(", ") || "no purpose string"}`);    for (const one of missing) {      failed = true;      console.error(`  MISSING ${one.api}: ${one.because}, but the Info.plist has none of ${one.keys.join(", ")} (App Store processing rejects this, ITMS-90683)`);    }  }  process.exit(failed ? 1 : 0);}