import type Limrun from '@limrun/api'; import { readFile } from 'node:fs/promises'; import { APP_STORE_CONNECT_API_KEY_TYPE, LimrunSigningSecretStore } from './limrun-signing-store'; import type { XcodeCloudSigningFlagValues } from './xcode-signing-options'; /** A key passed with explicit flags. The private key travels with the build request. */ export interface InlineAppleCredentials { kind: 'inline'; keyId: string; privateKeyP8Base64: string; issuerId?: string; teamID?: string; } /** A key in Limrun secret storage. The build reads it, so it never reaches this computer. */ export interface SecretAppleCredentials { kind: 'secret'; /** name/, as the build request and permission take it. */ target: string; teamID?: string; /** Whether the saved key is a team key; cloud signing needs one. */ hasIssuer: boolean; } export type AppleCredentials = InlineAppleCredentials | SecretAppleCredentials; const SECRET_SUFFIX = '/APP_STORE_CONNECT_API_KEY'; export async function resolveAppleCredentials( flags: XcodeCloudSigningFlagValues & { 'asc-key-secret'?: string }, client: Limrun, store = new LimrunSigningSecretStore(client), ): Promise { // Never combine part of an explicit credential with a different saved key. if ( flags['asc-key'] !== undefined || flags['asc-key-id'] !== undefined || flags['asc-issuer-id'] !== undefined ) { if (flags['asc-key-secret'] !== undefined) { throw new Error('Use either --asc-key-secret or the --asc-key flags, not both.'); } if (!flags['asc-key'] || !flags['asc-key-id']) { throw new Error('Explicit App Store Connect credentials require both --asc-key-id and --asc-key.'); } return { kind: 'inline', keyId: flags['asc-key-id'], privateKeyP8Base64: (await readFile(flags['asc-key'])).toString('base64'), issuerId: flags['asc-issuer-id'], teamID: flags['team-id'], }; } let secret; if (flags['asc-key-secret']) { secret = await store.find(flags['asc-key-secret']); if (!secret) throw new Error(`No secret named ${flags['asc-key-secret']} was found.`); } else if (flags['team-id']) { secret = await store.find(`${flags['team-id']}${SECRET_SUFFIX}`); } else { const keys = await store.listType(APP_STORE_CONNECT_API_KEY_TYPE); if (keys.length > 1) { throw new Error( 'Several App Store Connect keys are saved. Select one with --team-id or --asc-key-secret.', ); } secret = keys[0]; } if (secret && secret.state !== 'ready') secret = await store.ready(secret.name); if (!secret) return undefined; if (secret.type !== APP_STORE_CONNECT_API_KEY_TYPE) { throw new Error(`The secret ${secret.name} holds a ${secret.type}, not an App Store Connect key.`); } const details = secret.metadata ?? {}; const teamID = typeof details['teamID'] === 'string' ? details['teamID'] : secret.name.endsWith(SECRET_SUFFIX) ? secret.name.slice(0, -SECRET_SUFFIX.length) : undefined; return { kind: 'secret', target: `name/${secret.name}`, teamID, hasIssuer: typeof details['issuerId'] === 'string' && details['issuerId'] !== '', }; }