This repository has been archived by the owner on Jan 18, 2024. It is now read-only.
/
IOSBuilder.js
702 lines (645 loc) · 21.7 KB
/
IOSBuilder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
/**
* @flow
*/
import fs from 'fs-extra';
import path from 'path';
import untildify from 'untildify';
import { Exp, Credentials, XDLError, ErrorCode, IosCodeSigning } from 'xdl';
import ora from 'ora';
import _ from 'lodash';
import BaseBuilder from './BaseBuilder';
import prompt from '../../prompt';
import log from '../../log';
import * as authFuncs from './auth';
const nonEmptyInput = val => val !== '';
const expertPrompt = `
WARNING! In this mode, we won't be able to make sure your certificates,
or provisioning profile are valid. Please double check that you're
uploading valid files for your app otherwise you may encounter strange errors!
Make sure you've created your app ID on the developer portal, that your app ID
is in app.json as \`bundleIdentifier\`, and that the provisioning profile you
upload matches that team ID and app ID.
`;
const produceAbsolutePath = p12Path => {
p12Path = untildify(p12Path);
if (!path.isAbsolute(p12Path)) {
p12Path = path.resolve(p12Path);
}
return p12Path;
};
const runAsExpertQuestion = {
type: 'list',
name: 'isExpoManaged',
message: 'How would you like to upload your credentials?\n',
choices: [
{ name: 'Expo handles all credentials, you can still provide overrides', value: true },
{
name: 'I will provide all the credentials and files needed, Expo does limited validation',
value: false,
},
],
};
const OBLIGATORY_CREDS_KEYS = {
pushP12: 'pushCert',
pushPassword: 'pushCert',
provisioningProfile: 'provisioningProfile',
teamId: 'teamId',
};
const OBLIGATORY_DIST_CERT_CREDS_KEYS = {
certP12: 'distCert',
certPassword: 'distCert',
};
const LET_EXPO_HANDLE = 'Let Expo handle the process';
const I_PROVIDE_FILE = 'I want to upload my own file';
const OVERRIDE_CHOICES = [
{ name: LET_EXPO_HANDLE, value: true },
{ name: I_PROVIDE_FILE, value: false },
];
const whatToOverride = [
{
type: 'list',
name: 'distCert',
message: 'Will you provide your own Distribution Certificate?',
choices: OVERRIDE_CHOICES,
},
{
type: 'list',
name: 'pushCert',
message: 'Will you provide your own Push Certificate?',
choices: OVERRIDE_CHOICES,
},
];
const provisionProfilePath = {
type: 'input',
name: 'pathToProvisioningProfile',
message: 'Path to your .mobile provisioning Profile',
validate: authFuncs.doesFileProvidedExist.bind(null, true),
filter: produceAbsolutePath,
};
const sharedQuestions = [
{
type: 'input',
name: 'pathToP12',
message: 'Path to P12 file:',
validate: authFuncs.doesFileProvidedExist.bind(null, true),
filter: produceAbsolutePath,
},
{
type: 'password',
name: 'p12Password',
message: 'P12 password:',
validate: password => password.length > 0,
},
];
const appleCredsQuestions = [
{
type: 'input',
name: 'appleId',
message: `What's your Apple ID?`,
validate: nonEmptyInput,
},
{
type: 'password',
name: 'password',
message: `Password?`,
validate: nonEmptyInput,
},
];
const createChooseDistCertPrompt = choices => ({
type: 'list',
name: 'distCert',
message: 'Would you like to reuse Distribution Certificate from another app?',
choices,
});
export default class IOSBuilder extends BaseBuilder {
async run() {
const publicUrl = this.options.publicUrl;
const buildOptions = {
...(publicUrl ? { publicUrl } : {}),
};
// validate bundleIdentifier before hitting the network to check build status
const {
args: {
username,
remoteFullPackageName: experienceName,
bundleIdentifierIOS: bundleIdentifier,
sdkVersion,
},
} = publicUrl
? await Exp.getThirdPartyInfoAsync(publicUrl)
: await Exp.getPublishInfoAsync(this.projectDir);
await this.checkIfSdkIsSupported(sdkVersion, 'ios');
if (!bundleIdentifier) {
throw new XDLError(
ErrorCode.INVALID_OPTIONS,
`Your project must have a bundleIdentifier set in app.json.
See https://docs.expo.io/versions/latest/guides/building-standalone-apps.html`
);
}
// Check the status of any current builds
await this.checkStatus({ platform: 'ios', sdkVersion, ...buildOptions });
const credentialMetadata = { username, experienceName, bundleIdentifier, platform: 'ios' };
const clearOnly = {};
if (this.options.clearCredentials) {
clearOnly.distCert = true;
clearOnly.appCredentials = true;
} else {
if (this.options.clearAppCredentials) {
clearOnly.appCredentials = true;
}
if (this.options.clearDistCert) {
clearOnly.distCert = true;
}
}
// Clear credentials if they want to:
if (!_.isEmpty(clearOnly)) {
await Credentials.removeCredentialsForPlatform('ios', {
...credentialMetadata,
only: clearOnly,
});
log.warn('Removed existing credentials from expo servers');
}
if (this.options.type !== 'simulator') {
try {
await authFuncs.prepareLocalAuth();
await this.runLocalAuth(credentialMetadata);
} catch (e) {
log.error(`Error while gathering & validating credentials`);
if (authFuncs.DEBUG) {
if (e.stdout !== undefined) {
// sometimes WSL adds null characters
log.error(e.stdout.replace(/\0/g, ''));
} else {
log.error(e);
}
}
throw e;
}
}
// Publish the experience, if necessary
const publishedExpIds = this.options.publicUrl
? undefined
: await this.ensureReleaseExists('ios');
// Initiate the build with the published experience
await this.build(publishedExpIds, 'ios', { bundleIdentifier, ...buildOptions });
}
checkEnv() {
return (
this.options.teamId &&
this.options.distP12Path &&
process.env.EXPO_IOS_DIST_P12_PASSWORD &&
this.options.pushP12Path &&
process.env.EXPO_IOS_PUSH_P12_PASSWORD &&
this.options.provisioningProfilePath
);
}
async runningAsCI() {
const creds = {
teamId: this.options.teamId,
certP12: this.options.distP12Path,
certPassword: process.env.EXPO_IOS_DIST_P12_PASSWORD,
pushP12: this.options.pushP12Path,
pushPassword: process.env.EXPO_IOS_PUSH_P12_PASSWORD,
provisioningProfile: this.options.provisioningProfilePath,
};
return {
...creds,
...{
provisioningProfile: (await fs.readFile(creds.provisioningProfile)).toString('base64'),
certP12: (await fs.readFile(creds.certP12)).toString('base64'),
pushP12: (await fs.readFile(creds.pushP12)).toString('base64'),
},
};
}
async runningAsExpert(credentialsToAskFor = ['distCert', 'pushCert', 'provisioningProfile']) {
log(expertPrompt);
let newCredentials = {};
let newMetadata = {};
for (const choice of credentialsToAskFor) {
const { metadata, credentials } = await this.userProvidedOverride(choice);
newCredentials = { ...newCredentials, ...credentials };
newMetadata = { ...newMetadata, ...metadata };
}
return {
newCredentials,
newMetadata,
};
}
// End user wants to override these credentials, that is, they want
// to provide their own creds
async userProvidedOverride(choice) {
switch (choice) {
case 'distCert': {
log('Please provide your distribution certificate P12:');
const distCertValues = await prompt(sharedQuestions);
const certP12Buffer = await fs.readFile(distCertValues.pathToP12);
const certPassword = distCertValues.p12Password;
const distCertSerialNumber = IosCodeSigning.findP12CertSerialNumber(
certP12Buffer,
certPassword
);
return {
metadata: distCertSerialNumber,
credentials: this._ensureObjectsHasOnlyStrings({
certP12: certP12Buffer.toString('base64'),
certPassword,
}),
};
}
case 'pushCert': {
log('Please provide the path to your push notification cert P12');
const pushCertValues = await prompt(sharedQuestions);
return {
metadata: {},
credentials: this._ensureObjectsHasOnlyStrings({
pushP12: (await fs.readFile(pushCertValues.pathToP12)).toString('base64'),
pushPassword: pushCertValues.p12Password,
}),
};
}
case 'provisioningProfile': {
log('Please provide the path to your .mobile provisioning profile');
const { pathToProvisioningProfile } = await prompt(provisionProfilePath);
return {
metadata: {},
credentials: this._ensureObjectsHasOnlyStrings({
provisioningProfile: (await fs.readFile(pathToProvisioningProfile)).toString('base64'),
}),
};
}
default:
throw new Error(`Unknown choice to override: ${choice}`);
}
}
_ensureObjectsHasOnlyStrings(obj) {
const result = {};
Object.keys(obj).forEach(k => {
const isString = typeof obj[k] === 'string';
if (isString) {
result[k] = obj[k];
} else {
result[k] = JSON.stringify(obj[k]);
}
});
return result;
}
async _ensureAppExists(appleCreds, credsMetadata, teamId) {
let checkAppExistenceAttempt = await authFuncs.ensureAppIdLocally(
appleCreds,
credsMetadata,
teamId
);
if (
checkAppExistenceAttempt.result === 'failure' &&
checkAppExistenceAttempt.reason.startsWith(authFuncs.NO_BUNDLE_ID)
) {
checkAppExistenceAttempt = await authFuncs.createAppOnPortal(
appleCreds,
credsMetadata,
teamId
);
}
this._throwIfFailureWithReasonDump(checkAppExistenceAttempt);
const { result, ...other } = checkAppExistenceAttempt;
return this._ensureObjectsHasOnlyStrings(other);
}
async produceProvisionProfile(appleCreds, credsMetadata, teamId, isEnterprise) {
const produceProvisionProfileAttempt = await authFuncs.produceProvisionProfile(
appleCreds,
credsMetadata,
teamId,
isEnterprise
);
if (
produceProvisionProfileAttempt.result === 'failure' &&
produceProvisionProfileAttempt.reason.startsWith(authFuncs.MULTIPLE_PROFILES)
) {
log.warn(authFuncs.APPLE_ERRORS);
}
this._throwIfFailureWithReasonDump(produceProvisionProfileAttempt);
return this._ensureObjectsHasOnlyStrings(produceProvisionProfileAttempt);
}
async expoManagedResource(choice, appleCreds, teamId, credsMetadata, isEnterprise) {
switch (choice) {
case 'distCert': {
const produceCertAttempt = await authFuncs.produceCerts(appleCreds, teamId, isEnterprise);
this._throwIfFailureWithReasonDump(produceCertAttempt);
const distCertSerialNumber = IosCodeSigning.findP12CertSerialNumber(
produceCertAttempt.certP12,
produceCertAttempt.certPassword
);
return {
metadata: {
distCertSerialNumber,
},
credentials: this._ensureObjectsHasOnlyStrings(produceCertAttempt),
};
}
case 'pushCert': {
const producePushCertsAttempt = await authFuncs.producePushCerts(
appleCreds,
credsMetadata,
teamId,
isEnterprise
);
this._throwIfFailureWithReasonDump(producePushCertsAttempt);
return {
metadata: {},
credentials: this._ensureObjectsHasOnlyStrings(producePushCertsAttempt),
};
}
case 'provisioningProfile':
return {
metadata: {},
credentials: await this.produceProvisionProfile(
appleCreds,
credsMetadata,
teamId,
isEnterprise
),
};
default:
throw new Error(`Unknown manage resource choice requested: ${choice}`);
}
}
async _revokeHelper(appleCredentials, credsMetadata, teamId, isEnterprise, distOrPush) {
// Get back IDs that Spaceship knows how to revoke
const revokeWhat = await authFuncs.askWhichCertsToDump(
appleCredentials,
credsMetadata,
teamId,
distOrPush,
isEnterprise
);
if (revokeWhat.length !== 0) {
const revokeAttempt = await authFuncs.revokeCredentialsOnApple(
appleCredentials,
credsMetadata,
revokeWhat,
teamId
);
if (revokeAttempt.result === 'success') {
log(`Revoked ${revokeAttempt.revokeCount} existing certs on developer.apple.com`);
} else {
log.warn(`Could not revoke certs: ${revokeAttempt.reason}`);
}
}
}
async _handleRevokes(appleCredentials, credsMetadata, teamId, isEnterprise) {
const f = this._revokeHelper.bind(null, appleCredentials, credsMetadata, teamId, isEnterprise);
if (this.options.revokeAppleDistCerts) {
log.warn('ATTENTION: Revoking your Apple Distribution Certificates is permanent');
await f('distCert');
}
if (this.options.revokeApplePushCerts) {
log.warn('ATTENTION: Revoking your Apple Push Certificates is permanent');
await f('pushCert');
}
if (this.options.revokeAppleProvisioningProfile) {
await new Promise(r => setTimeout(() => r(), 400));
log.warn(
`ATTENTION: Revoking your Apple Provisioning Profile for ${
credsMetadata.bundleIdentifier
} is permanent`
);
const revokeAttempt = await authFuncs.revokeProvisioningProfile(
appleCredentials,
credsMetadata,
teamId
);
if (revokeAttempt.result === 'success') {
log.warn(revokeAttempt.msg);
} else {
log.warn(
`Could not revoke provisioning profile: ${revokeAttempt.reason} rawDump:${JSON.stringify(
revokeAttempt
)}`
);
}
}
}
async _validateCredsEnsureAppExists(credsMetadata, justTeamId, isEnterprise) {
const appleCredentials = await this.askForAppleCreds(justTeamId);
log('Validating Credentials...');
const checkCredsAttempt = await authFuncs.validateCredentialsProduceTeamId(appleCredentials);
this._throwIfFailureWithReasonDump(checkCredsAttempt);
await this._handleRevokes(
appleCredentials,
credsMetadata,
checkCredsAttempt.teamId,
isEnterprise
);
await this._ensureAppExists(appleCredentials, credsMetadata, checkCredsAttempt.teamId);
return {
appleCredentials,
team: {
teamId: checkCredsAttempt.teamId,
teamName: checkCredsAttempt.teamName,
},
};
}
async runningAsExpoManaged(
appleCredentials,
teamId,
credsMetadata,
isEnterprise,
credsMissing = ['distCert', 'pushCert', 'provisioningProfile']
) {
// (dsokal)
// This function and generally - IOSBuilder is unnecessarily overcomplicated.
// It would be good to refactor it some day, because changing anything here
// always takes me more time than I think it should.
//
// There are only two possible scenarios here:
// - all of credentials are missing
// - distribution certificate is missing (we have to regenerate provisioning profile)
if (_.includes(credsMissing, 'distCert') && !_.includes(credsMissing, 'provisioningProfile')) {
credsMissing.push('provisioningProfile');
}
const whatToOverrideFiltered = whatToOverride.filter(({ name }) =>
_.includes(credsMissing, name)
);
const whatToOverrideResult = await prompt(whatToOverrideFiltered);
const expoManages = { provisioningProfile: true };
const { userCredentialId, serialNumber } = whatToOverrideResult.distCert
? await this._chooseDistCert(credsMetadata.username, teamId)
: {};
const toCopy = userCredentialId
? _.omit(whatToOverrideResult, 'distCert')
: whatToOverrideResult;
Object.assign(expoManages, toCopy);
let newCredentials = {};
let newMetadata = {
...credsMetadata,
};
if (userCredentialId) {
newCredentials.userCredentialId = userCredentialId;
newMetadata.distCertSerialNumber = serialNumber;
}
const spinner = ora('Running local authentication and producing required credentials').start();
const choices = _.intersection(credsMissing, Object.keys(expoManages));
try {
for (const choice of choices) {
spinner.text = `Now producing files for ${choice}`;
if (expoManages[choice]) {
spinner.start();
const { metadata, credentials } = await this.expoManagedResource(
choice,
appleCredentials,
teamId,
newMetadata,
isEnterprise
);
newMetadata = { ...newMetadata, ...metadata };
newCredentials = { ...newCredentials, ...credentials };
} else {
spinner.stop();
const { metadata, credentials } = await this.userProvidedOverride(choice);
newMetadata = { ...newMetadata, ...metadata };
newCredentials = { ...newCredentials, ...credentials };
}
}
} catch (e) {
throw e;
} finally {
spinner.stop();
}
return {
newCredentials,
newMetadata,
};
}
async _chooseDistCert(username, teamId) {
const certs = await Credentials.getExistingDistCerts(username, teamId);
if (certs.length > 0) {
const choices = certs.map(({ userCredentialId, certId, serialNumber, usedByApps }) => {
let name = `Serial number: ${serialNumber || 'unknown'}`;
if (certId) {
name = `${name}, Certificate ID: ${certId}`;
}
if (usedByApps) {
name = `Used in apps: ${usedByApps.join(', ')} (${name})`;
}
return {
name,
value: {
userCredentialId,
serialNumber,
},
};
});
choices.push({
name: 'No, please create a new one',
value: null,
});
const { distCert } = await prompt(createChooseDistCertPrompt(choices));
return {
userCredentialId: distCert && String(distCert.userCredentialId),
serialNumber: distCert && distCert.serialNumber,
};
} else {
return {};
}
}
_areCredsMissing(creds, action) {
const clientHas = new Set(Object.keys(creds));
const credsMissing = [];
const obligatoryCreds = clientHas.has('userCredentialId')
? OBLIGATORY_CREDS_KEYS
: { ...OBLIGATORY_CREDS_KEYS, ...OBLIGATORY_DIST_CERT_CREDS_KEYS };
const obligatoryKeys = new Set(Object.keys(obligatoryCreds));
for (const k of obligatoryKeys.keys()) {
if (clientHas.has(k) === false) {
credsMissing.push(k);
action !== undefined && action();
}
}
if (credsMissing.length !== 0) {
log.warn(`We do not have some credentials for you, ${credsMissing}`);
return _.chain(credsMissing)
.map(k => obligatoryCreds[k])
.uniq()
.value();
}
}
async runLocalAuth(credsMetadata) {
let credsStarter = await Credentials.getEncryptedCredentialsForPlatformAsync(credsMetadata);
let clientHasAllNeededCreds = false;
let credsMissing;
if (credsStarter !== undefined) {
clientHasAllNeededCreds = true;
credsMissing = this._areCredsMissing(credsStarter, () => (clientHasAllNeededCreds = false));
} else {
credsStarter = {};
}
if (this.checkEnv()) {
const credentialsCI = await this.runningAsCI();
const creds = { ...credsStarter, ...credentialsCI };
this._areCredsMissing(creds);
await Credentials.updateCredentialsForPlatform('ios', creds, credsMetadata);
log.warn(
`Encrypted ${Object.keys(OBLIGATORY_CREDS_KEYS).join(', ')} and saved to expo servers`
);
} else if (clientHasAllNeededCreds === false) {
const strategy = await prompt(runAsExpertQuestion);
const isEnterprise = this.options.appleEnterpriseAccount !== undefined;
credsStarter.enterpriseAccount = isEnterprise ? 'true' : 'false';
const { appleCredentials, team } = await this._validateCredsEnsureAppExists(
credsMetadata,
!strategy.isExpoManaged,
isEnterprise
);
credsStarter = { ...credsStarter, ...team };
if (strategy.isExpoManaged) {
const { newCredentials, newMetadata } = await this.runningAsExpoManaged(
appleCredentials,
credsStarter.teamId,
credsMetadata,
isEnterprise,
credsMissing
);
credsStarter = { ...credsStarter, ...newCredentials };
credsMetadata = { ...credsMetadata, ...newMetadata };
} else {
const { newCredentials, newMetadata } = await this.runningAsExpert(credsMissing);
credsStarter = { ...credsStarter, ...newCredentials };
credsMetadata = { ...credsMetadata, ...newMetadata };
}
const { result, ...creds } = credsStarter;
this._areCredsMissing(creds);
const withoutEncrypted = _.pickBy(creds, v => v !== 'encrypted');
await Credentials.updateCredentialsForPlatform('ios', withoutEncrypted, credsMetadata);
} else {
log('Using existing credentials for this build');
}
}
_throwIfFailureWithReasonDump(replyAttempt) {
if (replyAttempt.result === 'failure') {
const { reason, rawDump } = replyAttempt;
throw new Error(`Reason: ${reason}, raw: ${JSON.stringify(rawDump, null, 2)}`);
}
}
async askForAppleCreds(justTeamId = false) {
const { appleId } = this.options;
const password = process.env.EXPO_APPLE_PASSWORD;
if (appleId && password) {
return {
appleId,
password,
};
}
if (justTeamId === false) {
console.log(`
We need your Apple ID/password to manage certificates and
provisioning profiles from your Apple Developer account.
Note: Expo does not keep your Apple ID or your Apple password.
`);
} else {
console.log(`
We need your Apple ID/password to ensure the correct teamID and appID
Note: Expo does not keep your Apple ID or your Apple password.
`);
}
return prompt(appleCredsQuestions);
}
}