// Code signing through the App Store Connect API (Certificates, Identifiers & Profiles), pure planning: // bundle id capabilities, which distribution certificate to use, which provisioning profile to (re)create, where // profiles are installed, and the ExportOptions.plist for `xcodebuild -exportArchive`. The command is // cli/apple/signing.ts; requests are JSON:API `Req`s (printed on --dry, sent otherwise). // API reference: https://developer.apple.com/documentation/appstoreconnectapi (Bundle IDs, Bundle ID Capabilities, // Certificates, Profiles). import { createHash, X509Certificate } from 'node:crypto'; import { join } from 'node:path'; import type { Req } from '../apple/jsonapi'; import { one, many } from '../apple/jsonapi'; import type { PlistValue } from './plist'; /** CapabilityType values of the App Store Connect API (BundleIdCapability.capabilityType). */ export const CAPABILITY_TYPES = ['ICLOUD', 'IN_APP_PURCHASE', 'GAME_CENTER', 'PUSH_NOTIFICATIONS', 'WALLET', 'INTER_APP_AUDIO', 'MAPS', 'ASSOCIATED_DOMAINS', 'PERSONAL_VPN', 'APP_GROUPS', 'HEALTHKIT', 'HOMEKIT', 'WIRELESS_ACCESSORY_CONFIGURATION', 'APPLE_PAY', 'DATA_PROTECTION', 'SIRIKIT', 'NETWORK_EXTENSIONS', 'MULTIPATH', 'HOT_SPOT', 'NFC_TAG_READING', 'CLASSKIT', 'AUTOFILL_CREDENTIAL_PROVIDER', 'ACCESS_WIFI_INFORMATION', 'NETWORK_CUSTOM_PROTOCOL', 'COREMEDIA_HLS_LOW_LATENCY', 'SYSTEM_EXTENSION_INSTALL', 'USER_MANAGEMENT', 'APPLE_ID_AUTH'] as const; export type CapabilityType = typeof CAPABILITY_TYPES[number]; /** Certificate types storebound creates: Apple Distribution (DISTRIBUTION, all platforms), the older iOS Distribution, * and Developer ID Application (Mac apps outside the App Store; Account Holder only). */ export const CERT_TYPES = ['DISTRIBUTION', 'IOS_DISTRIBUTION', 'DEVELOPER_ID_APPLICATION', 'DEVELOPER_ID_APPLICATION_G2'] as const; export type CertType = typeof CERT_TYPES[number]; /** Profile types for store builds (Profile.profileType). */ export const PROFILE_TYPES = ['IOS_APP_STORE', 'IOS_APP_ADHOC', 'TVOS_APP_STORE', 'MAC_APP_STORE', 'MAC_APP_DIRECT', 'MAC_CATALYST_APP_STORE'] as const; export type ProfileType = typeof PROFILE_TYPES[number]; export interface CapabilitySpec { type: CapabilityType; settings?: unknown[] } export interface AppleSigning { /** automatic (default): xcodebuild -allowProvisioningUpdates with the API key creates what it needs. * manual: the certificate and profiles from `storebound apple signing ensure`, named in ExportOptions.plist. */ style?: 'automatic' | 'manual'; /** Team ID (10 characters). Default: the bundle id's seedId from the API. */ teamId?: string; /** Default DISTRIBUTION (Apple Distribution). */ certificateType?: CertType; /** Default IOS_APP_STORE. */ profileType?: ProfileType; /** Capabilities the bundle id must have (Certificates, Identifiers & Profiles), e.g. ['IN_APP_PURCHASE', 'GAME_CENTER']. */ capabilities?: (CapabilityType | CapabilitySpec)[]; /** Bundle ids of app extensions / widgets / watch apps in the same archive: each gets its own profile. */ extraBundleIds?: string[]; } export function validateSigning(s: AppleSigning | undefined): string[] { if (!s) return []; const e: string[] = []; if (s.style && !['automatic', 'manual'].includes(s.style)) e.push('apple.signing.style: automatic | manual'); if (s.teamId && !/^[A-Z0-9]{10}$/.test(s.teamId)) e.push('apple.signing.teamId: the 10-character Team ID'); if (s.certificateType && !CERT_TYPES.includes(s.certificateType)) e.push(`apple.signing.certificateType: one of ${CERT_TYPES.join(', ')}`); if (s.profileType && !PROFILE_TYPES.includes(s.profileType)) e.push(`apple.signing.profileType: one of ${PROFILE_TYPES.join(', ')}`); for (const c of s.capabilities ?? []) { const t = typeof c === 'string' ? c : c?.type; if (!CAPABILITY_TYPES.includes(t as CapabilityType)) e.push(`apple.signing.capabilities: unknown capability "${String(t)}" (${CAPABILITY_TYPES.slice(0, 6).join(', ')}, ...)`); } for (const b of s.extraBundleIds ?? []) if (!/^[A-Za-z0-9.-]+$/.test(b)) e.push(`apple.signing.extraBundleIds: "${b}" is not a bundle id`); return e; } export const capabilitySpecs = (s: AppleSigning | undefined): CapabilitySpec[] => (s?.capabilities ?? []).map(c => (typeof c === 'string' ? { type: c } : c)); /** Capabilities to add (never removes one: removing can break a shipped feature; extra ones are reported). */ export function planCapabilities(bundleIdId: string, existing: string[], want: CapabilitySpec[]): { create: Req[]; present: string[]; extra: string[] } { const have = new Set(existing); const create = want.filter(w => !have.has(w.type)).map((w): Req => ({ method: 'POST', path: '/v1/bundleIdCapabilities', note: `capability ${w.type}`, body: { data: { type: 'bundleIdCapabilities', attributes: { capabilityType: w.type, ...(w.settings ? { settings: w.settings } : {}) }, relationships: { bundleId: one('bundleIds', bundleIdId) } } }, })); return { create, present: want.filter(w => have.has(w.type)).map(w => w.type), extra: existing.filter(t => !want.some(w => w.type === t)) }; } export interface ApiCert { id: string; attributes: { certificateType?: string; certificateContent?: string; expirationDate?: string; displayName?: string; name?: string; serialNumber?: string; activated?: boolean } } /** SHA-1 of the certificate DER, upper-case hex: what `security find-identity` prints. */ export const certSha1 = (contentB64: string): string => createHash('sha1').update(Buffer.from(contentB64, 'base64')).digest('hex').toUpperCase(); /** SPKI (DER, base64) of a certificate's public key, or null when it does not parse. */ export function certSpki(contentB64: string): string | null { try { return new X509Certificate(Buffer.from(contentB64, 'base64')).publicKey.export({ type: 'spki', format: 'der' }).toString('base64'); } catch { return null; } } export interface CertChoice { cert: ApiCert | null; why: string; usable: ApiCert[]; withoutKey: ApiCert[]; expiring: ApiCert[] } /** A certificate is usable when it is of the wanted type, active, valid for 30 more days and this machine holds its * private key (a key file in .storebound/signing or a code signing identity in the keychain). Newest first. */ export function pickCertificate(certs: ApiCert[], type: CertType, hasKey: (c: ApiCert) => boolean, now = Date.now()): CertChoice { const ofType = certs.filter(c => c.attributes.certificateType === type && c.attributes.activated !== false); const valid = ofType.filter(c => Date.parse(c.attributes.expirationDate ?? '') > now); const expiring = valid.filter(c => Date.parse(c.attributes.expirationDate!) - now < 30 * 86_400_000); const usable = valid.filter(c => hasKey(c) && !expiring.includes(c)).sort((a, b) => Date.parse(b.attributes.expirationDate!) - Date.parse(a.attributes.expirationDate!)); const withoutKey = valid.filter(c => !hasKey(c)); const cert = usable[0] ?? null; const why = cert ? `using ${cert.attributes.name ?? cert.attributes.displayName ?? type} (expires ${cert.attributes.expirationDate?.slice(0, 10)})` : withoutKey.length ? `${withoutKey.length} ${type} certificate(s) on the team, but this machine has none of their private keys: a new one is needed (or import the .p12 from the Mac that made it)` : `no valid ${type} certificate`; return { cert, why, usable, withoutKey, expiring }; } /** Apple caps distribution certificates per team (Apple Distribution: 3 per team). */ export const CERT_LIMIT: Partial> = { DISTRIBUTION: 3, IOS_DISTRIBUTION: 3, DEVELOPER_ID_APPLICATION: 5, DEVELOPER_ID_APPLICATION_G2: 5 }; export function certificateReq(type: CertType, csr: string): Req { return { method: 'POST', path: '/v1/certificates', note: `create ${type} certificate (key in .storebound/signing, never printed)`, body: { data: { type: 'certificates', attributes: { certificateType: type, csrContent: csr } } } }; } /** A 403 when creating a Developer ID certificate: only the Account Holder may create them. Explanation or null. */ export function explainCertError(err: unknown, type: CertType): string | null { const s = String(err); if (/DEVELOPER_ID/.test(type) && /-> 403/.test(s)) return 'Developer ID certificates can only be created by the Account Holder of the team. An API key (even Admin) gets 403 here. ' + 'The Account Holder creates it once in Xcode (Settings > Accounts > Manage Certificates > + > Developer ID Application) or at ' + 'developer.apple.com > Certificates, then exports the .p12 for this machine. App Store builds need DISTRIBUTION instead.'; if (/-> 409/.test(s) && /maximum|limit|already/i.test(s)) return 'The team has reached its limit of this certificate type. Revoke an unused one at developer.apple.com > Certificates (owner decision: ' + 'builds signed with it keep working, but its profiles become invalid), or use a certificate whose key is on another Mac (export a .p12 there).'; if (/-> 403/.test(s)) return 'The API key may not manage certificates: it needs the Admin role (Users and Access > Integrations).'; return null; } export interface ApiProfile { id: string; attributes: { name?: string; profileType?: string; profileState?: string; expirationDate?: string; uuid?: string; profileContent?: string }; certIds?: string[]; /** Xcode-managed profile (automatic signing, "iOS Team Store Provisioning Profile: ..."): listed under the bundle id, * but /v1/profiles/{id} answers 404 for it, so its certificates are unknown and storebound never reuses it. */ managed?: boolean; } /** The profiles of one bundle id of `type`, each with its certificate ids. A profile the profiles API does not serve * (404: Xcode-managed, seen live October 2026) is kept with `managed: true` instead of failing the whole read. */ export async function readProfiles(all: (path: string) => Promise<{ id: string; attributes?: Record }[]>, bundleIdId: string, type: ProfileType): Promise { const ps = await all(`/v1/bundleIds/${bundleIdId}/profiles?limit=200`); const out: ApiProfile[] = []; for (const p of ps.filter(p => p.attributes?.profileType === type)) { const attributes = p.attributes as ApiProfile['attributes']; try { const certs = await all(`/v1/profiles/${p.id}/relationships/certificates?limit=200`); out.push({ id: p.id, attributes, certIds: certs.map(x => x.id) }); } catch (e) { if (!/-> 404\b/.test((e as Error).message)) throw e; out.push({ id: p.id, attributes, managed: true }); } } return out; } export const profileName = (bundleId: string, type: ProfileType, date = new Date()): string => `storebound ${bundleId} ${type === 'IOS_APP_STORE' ? 'App Store' : type} ${date.toISOString().slice(0, 16).replace('T', ' ')}`; export interface ProfilePlan { reuse: ApiProfile | null; create: Req | null; why: string } /** Reuse an ACTIVE profile of the type that holds the certificate and is valid for 14 more days; else create one. */ export function planProfile(existing: ApiProfile[], o: { bundleId: string; bundleIdId: string; certId: string; type: ProfileType; now?: number }): ProfilePlan { const now = o.now ?? Date.now(); const ok = existing.filter(p => p.attributes.profileType === o.type && p.attributes.profileState === 'ACTIVE' && Date.parse(p.attributes.expirationDate ?? '') - now > 14 * 86_400_000 && (p.certIds ?? []).includes(o.certId)) .sort((a, b) => Date.parse(b.attributes.expirationDate!) - Date.parse(a.attributes.expirationDate!)); if (ok[0]) return { reuse: ok[0], create: null, why: `profile "${ok[0].attributes.name}" is active (expires ${ok[0].attributes.expirationDate?.slice(0, 10)})` }; const stale = existing.filter(p => p.attributes.profileType === o.type && !p.managed); const managed = existing.filter(p => p.attributes.profileType === o.type && p.managed); const why = [ stale.length ? `${stale.length} ${o.type} profile(s), none active with this certificate (states: ${[...new Set(stale.map(p => p.attributes.profileState))].join(', ')})` : '', managed.length ? `${managed.length} Xcode-managed (automatic signing; not readable through the API, not reused)` : '', ].filter(Boolean).join('; ') || `no ${o.type} profile`; return { reuse: null, why, create: { method: 'POST', path: '/v1/profiles', note: `create ${o.type} profile for ${o.bundleId}`, body: { data: { type: 'profiles', attributes: { name: profileName(o.bundleId, o.type, new Date(now)), profileType: o.type }, relationships: { bundleId: one('bundleIds', o.bundleIdId), certificates: many('certificates', [o.certId]) } } }, } }; } /** Where provisioning profiles are installed: Xcode 16 and later read ~/Library/Developer/Xcode/UserData/Provisioning * Profiles; older Xcode (and some tools) ~/Library/MobileDevice/Provisioning Profiles. storebound writes both. */ export const profileDirs = (home: string): string[] => [join(home, 'Library/Developer/Xcode/UserData/Provisioning Profiles'), join(home, 'Library/MobileDevice/Provisioning Profiles')]; /** Lines of `security find-identity -v -p codesigning` -> SHA-1 hashes of identities with a private key. */ export function parseIdentities(out: string): { sha1: string; name: string }[] { return [...out.matchAll(/^\s*\d+\)\s+([0-9A-F]{40})\s+"([^"]+)"/gm)].map(m => ({ sha1: m[1]!, name: m[2]! })); } export interface ExportOptionsInput { teamId: string; style: 'automatic' | 'manual'; profiles?: Record; method?: string; uploadSymbols?: boolean; certificate?: string } /** ExportOptions.plist for an App Store Connect export (`method` app-store-connect, Xcode 15.3+; "app-store" is the * deprecated name). destination export: storebound uploads the IPA itself (`apple upload`), with the build number it * chose, so Xcode must not change it (manageAppVersionAndBuildNumber false). */ export function exportOptions(i: ExportOptionsInput): Record { const o: Record = { method: i.method ?? 'app-store-connect', teamID: i.teamId, signingStyle: i.style, destination: 'export', uploadSymbols: i.uploadSymbols ?? true, manageAppVersionAndBuildNumber: false, }; if (i.style === 'manual') { if (!i.profiles || !Object.keys(i.profiles).length) throw new Error('manual signing needs a provisioning profile per bundle id (storebound apple signing ensure)'); o.provisioningProfiles = { ...i.profiles }; o.signingCertificate = i.certificate ?? 'Apple Distribution'; } return o; }