Compare commits

...
54 Commits
Author SHA1 Message Date
Brent Vatne 1d45941f5d v0.14.0 2021-05-10 11:28:46 -07:00
Quinlan Jung 5e5badf11f [eas-cli] credentials manager DX nits (#383) 2021-05-03 19:16:14 -07:00
jkh 840c65946b [eas-cli] remove --force to fix eas publish (#381) 2021-05-03 15:35:52 -07:00
Quinlan Jung fdbd786126 [eas-cli] move from deprecated iosAppCredentialsArray to iosAppCredentialsList (#380) 2021-05-03 13:16:33 -07:00
Quinlan Jung d5365275e0 [eas-cli] beta android credentials manager (#378) 2021-04-29 12:07:20 -07:00
Quinlan Jung 886e48d3ee [eas-cli] android graphql types (#377) 2021-04-29 11:17:18 -07:00
Wojciech Kozyra 342c78a4f6 [eas-cli] disable pending build check (#373)
* [eas-cli] disable pending builds check

* update CHANGELOG.md
2021-04-28 15:13:51 +02:00
Axel Delafosse a483d94e26 [eas-cli] assert (#372) 2021-04-28 11:54:33 +02:00
Axel DelafosseandDominik Sokal b40412a7a1 [eas-cli] add QR code to install internal distribution build on device (#371)
* [website] add qr code to install internal distribution build on device

* [eas-cli] update changelog

* [eas-cli] sort imports

* [eas-cli] sort imports

* [eas-cli] improve getInstallUrl typing

Co-authored-by: Dominik Sokal <[email protected]>

* [eas-cli] fix typing

* [eas-cli] clean code

Co-authored-by: Dominik Sokal <[email protected]>
2021-04-28 11:43:21 +02:00
Quinlan Jung d652e04f7b [eas-cli] getAppAsync not used anywhere outside (#369) 2021-04-27 13:09:10 -07:00
Quinlan Jung 85326d1104 [eas-cli] merge beta and main cred utils (#368) 2021-04-27 13:08:51 -07:00
Quinlan Jung 28c087138b [eas-cli] replace printCredentials with printCredentialsBeta (#367) 2021-04-27 13:08:30 -07:00
jkh 8badf14ec3 [eas-cli] create asset keys without an extension (#366)
* Clients must be using expo-asset >= 8.3.2 in order to handle this new update format.
2021-04-27 06:02:12 -07:00
Wojciech Kozyra 4f1db29ef8 [eas-cli] increase build wait timeout (#370)
* [eas-cli] increase build wait timeout

* Update CHANGELOG.md
2021-04-27 14:19:23 +02:00
Quinlan Jung 2354dc1b71 update changelog 2021-04-26 12:16:21 -07:00
Quinlan Jung f106bfa6d7 [eas-cli] replace ctx.ios with ctx.newIos (#365)
remove old ctx.ios

ctx.newIos -> ctx.ios

fix lint

unused fixtures

remove unused fixtures

merge fixtures

fix lint
2021-04-26 12:11:36 -07:00
Quinlan Jung 1a7edbea06 [eas-cli] merge everything from actions/new to actions (#364)
delete unused actions

delete old inner class

remove uneeded dist cert utils

merge dist cert utils

remove unused functions of pprofile utils

pop out new directory
2021-04-26 12:10:27 -07:00
Quinlan Jung 5bfaee9e4d [eas-cli] swap beta credentials manager with current (#363) 2021-04-26 12:07:35 -07:00
Quinlan Jung 0cb2309d7d [eas-cli] add additionalTypenames to delete mutations to clear urql cache 2021-04-23 13:43:50 -07:00
Quinlan Jung 0415a1d97f changelog stuff 2021-04-23 12:47:59 -07:00
Quinlan Jung 249c60f4d1 [eas-cli] add remove provisioning profile to beta manager (#361) 2021-04-23 12:33:48 -07:00
Quinlan Jung c357cc378c [eas-cli] add high level actions to beta manager (#360) 2021-04-23 12:29:14 -07:00
Quinlan Jung f7c0d731b6 changelog stuff" 2021-04-22 22:48:38 -07:00
Quinlan Jung e852e3edac [eas-cli] add CreateDistCert and UseExistingDistCert to beta manager (#357)
* [eas-cli] add create and add existing dist cert options

* nits:

* fix dx
2021-04-22 17:27:17 -07:00
Quinlan Jung 2a283b74a3 [eas-cli][eas-json] add getBuildProfileNamesAsync helper (#351)
* [eas-cli][eas-json] getProfileNames helper

* tweak name

* pr feedback

* pr feedback
2021-04-22 13:47:18 -07:00
Quinlan Jung c749bc2372 [eas-cli] refactor UpdateCredentialsJson (#352)
* [eas-cli] refactor UpdateCredentialsJson

* fix broken tests from switching b64 pprofile test fixture

* fix lint

* add to beta manager
2021-04-22 12:02:45 -07:00
Brent Vatne 9c60f7190e Update CHANGELOG 2021-04-22 10:49:49 -07:00
Brent Vatne 8126b2276e v0.13.0 2021-04-22 10:16:06 -07:00
Dominik Sokal e1de21015f implement SetupInternalProvisioningProfile (#344) 2021-04-22 10:01:35 -07:00
Dominik Sokal 61e505f1f8 fix typo 2021-04-22 16:00:39 +02:00
Wojciech KozyraandDominik Sokal 2e3611161e fix api deprecation error (#359)
* fix api deprecation error

* update CHANGELOG.md

* Update packages/eas-cli/src/build/build.ts

Co-authored-by: Dominik Sokal <[email protected]>

Co-authored-by: Dominik Sokal <[email protected]>
2021-04-22 14:08:25 +02:00
Dominik Sokal 95f5eaaacf update changelog 2021-04-22 11:40:42 +02:00
Dominik Sokal 87a3ea99e2 v0.12.0 2021-04-22 10:32:28 +02:00
Quinlan Jung ddab65a55d [eas-cli] adhoc opposite name (#358) 2021-04-22 10:29:37 +02:00
Wojciech Kozyra 0cf8f8ce0d [eas-cli] support --clear-cache (#355)
* [eas-cli] support --clear-cache

* update CHANGELOG.md

* fix param description
2021-04-22 10:17:09 +02:00
Dominik Sokal 2b531ec70c update contributing doc (#353) 2021-04-22 10:04:44 +02:00
Dominik Sokal 6cd7966904 send username as build metadata property (#354)
* send username as build metadata property

* update changelog

* upgrade @expo/eas-build-job to 0.2.27
2021-04-21 14:38:25 +02:00
Dominik Sokal ad72ab990f Update CHANGELOG.md 2021-04-21 09:20:08 +02:00
Brent Vatne b53412fc00 Update CHANGELOG 2021-04-20 15:29:06 -07:00
Brent Vatne cbb2de9e11 v0.11.1 2021-04-20 15:00:15 -07:00
Brent Vatne 593c42f601 [eas-cli] Bump @expo/apple-utils to fix initial iOS app capabilities sync 2021-04-20 14:59:27 -07:00
Quinlan Jung 84b10b9dad [eas-cli] fix lint 2021-04-20 14:14:40 -07:00
Quinlan Jung 0f286061e4 [eas-cli] tests for SelectIosDistributionTypeGraphqlFromBuildProfile 2021-04-20 14:13:44 -07:00
Quinlan Jung c8aad01480 [eas-cli] non interactive support, aesthetic nits 2021-04-20 14:12:12 -07:00
Quinlan Jung d70a6bee69 [eas-cli] resolve ios distribution types (#348)
* [eas-cli] resolve ios distribution types

* pr feedback

* pr feedback
2021-04-20 12:46:55 -07:00
Dominik Sokal 67799b5c54 update changelog 2021-04-20 15:36:23 +02:00
Dominik Sokal 05b8eef622 v0.11.0 2021-04-20 15:08:57 +02:00
Dominik Sokal 50e56b5bc4 fix building APKs for Android managed projects (#349)
* fix building APKs for Android managed projects

* update CHANGELOG
2021-04-20 14:39:58 +02:00
Dominik Sokal 30ab4e62ec simplify credentials providers - remove auto option (#345)
* simplify credentials providers - remove auto option

* update changelog

* address PR feedback
2021-04-20 10:39:37 +02:00
Dominik Sokal a1d901294b allow for registering devices when building app for internal distribution (#340)
* allow for registering devices when building app for internal distribution

* update CHANGELOG
2021-04-19 12:39:20 +02:00
Dominik Sokal eed818cfe5 refactor setting up adhoc provisioning profile (#338)
* refactor appstore provisioning profile validation

* refactor SetupAdhocProvisioningProfile

* update CHANGELOG

* address PR feedback
2021-04-19 12:29:37 +02:00
Dominik Sokal db0b6bfcf5 remove redundant finally block 2021-04-16 15:54:44 +02:00
Dominik Sokal da81c1c6df remove incorrect usage example from secret:list command 2021-04-16 14:16:41 +02:00
Dominik Sokal 42d3296f07 update CHANGELOG 2021-04-16 14:13:09 +02:00
120 changed files with 3374 additions and 4167 deletions

No files matched your search

+70 -1
View File
@@ -6,6 +6,76 @@ This is the log of notable changes to EAS CLI and related packages.
### 🛠 Breaking changes
- Make eas branch:publish work with expo-cli >= 4.4.3 ([#366](https://github.com/expo/eas-cli/pull/366) by [@jkhales](https://github.com/jkhales))
- Create asset keys without an extension. ([#366](https://github.com/expo/eas-cli/pull/366) by [@jkhales](https://github.com/jkhales))
### 🎉 New features
- Release new credentials manager. ([#363](https://github.com/expo/eas-cli/pull/363) by [@quinlanj](https://github.com/quinlanj))
- Add QR code to install internal distribution build on device. ([#371](https://github.com/expo/eas-cli/pull/371) by [@axeldelafosse](https://github.com/axeldelafosse))
### 🐛 Bug fixes
### 🧹 Chores
- Cleanup unused code. ([#364](https://github.com/expo/eas-cli/pull/364), [#365](https://github.com/expo/eas-cli/pull/365) by [@quinlanj](https://github.com/quinlanj))
- Redesign UX in beta credentials manager. ([#360](https://github.com/expo/eas-cli/pull/360) by [@quinlanj](https://github.com/quinlanj))
- Port more options to the beta credentials manager. ([#352](https://github.com/expo/eas-cli/pull/352), [357](https://github.com/expo/eas-cli/pull/357), [361](https://github.com/expo/eas-cli/pull/361) by [@quinlanj](https://github.com/quinlanj))
- Add getBuildProfileNamesAsync helper to EasJsonReader. ([#351](https://github.com/expo/eas-cli/pull/351) by [@quinlanj](https://github.com/quinlanj))
- Increase build timeout to 1 hour. ([#370](https://github.com/expo/eas-cli/pull/370) by [@wkozyra95](https://github.com/wkozyra95))
- Remove check for pending builds. ([#373](https://github.com/expo/eas-cli/pull/373) by [@wkozyra95](https://github.com/wkozyra95))
## [0.13.0](https://github.com/expo/eas-cli/releases/tag/v0.13.0) - 2021-04-22
### 🎉 New features
- Implement offline distribution certificate validation when running a build in non-interactive mode. ([#344](https://github.com/expo/eas-cli/pull/344) by [@dsokal](https://github.com/dsokal))
- Add support for building internal distribution apps for Apple Enterprise Teams. ([#344](https://github.com/expo/eas-cli/pull/344) by [@dsokal](https://github.com/dsokal))
### 🐛 Bug fixes
- Display descriptive error message when API for EAS Build changes. ([#359](https://github.com/expo/eas-cli/pull/359) by [@wkozyra95](https://github.com/wkozyra95))
## [0.12.0](https://github.com/expo/eas-cli/releases/tag/v0.12.0) - 2021-04-22
### 🎉 New features
- Add the initiating user's username to the build metadata. ([#354](https://github.com/expo/eas-cli/pull/354) by [@dsokal](https://github.com/dsokal))
- Add `--clear-cache` flag for `eas build`. ([#355](https://github.com/expo/eas-cli/pull/355) by [@wkozyra95](https://github.com/wkozyra95))
### 🐛 Bug fixes
- Fix the bug where the account name was used as the username. ([#354](https://github.com/expo/eas-cli/pull/354) by [@dsokal](https://github.com/dsokal))
## [0.11.1](https://github.com/expo/eas-cli/releases/tag/v0.11.1) - 2021-04-20
### 🎉 New features
- Resolve ios distribution types. ([#348](https://github.com/expo/eas-cli/pull/348) by [@quinlanj](https://github.com/quinlanj))
### 🐛 Bug fixes
- Bump version of `@expo/apple-utils` to fix capabilities sync immediately after initial identifier registration. ([593c4](https://github.com/expo/eas-cli/commit/593c42f601396deba1751489343ec07b0a8876da) by [@brentvatne](https://github.com/brentvatne))
## [0.11.0](https://github.com/expo/eas-cli/releases/tag/v0.11.0) - 2021-04-20
### 🛠 Breaking changes
- `"credentialsSource": "auto"` is now deprecated. The option will use `"remote"` as the default value. ([#345](https://github.com/expo/eas-cli/pull/345) by [@dsokal](https://github.com/dsokal))
### 🎉 New features
- Add validation when setting up ad-hoc provisioning profile in non-interactive mode. ([#338](https://github.com/expo/eas-cli/pull/338) by [@dsokal](https://github.com/dsokal))
- Allow for registering devices when running an ad-hoc build for the first time. ([#340](https://github.com/expo/eas-cli/pull/340) by [@dsokal](https://github.com/dsokal))
### 🐛 Bug fixes
- Fix the bug where all Android managed builds produced AAB archives. The `buildType` property from `eas.json` is not ignored now. ([#349](https://github.com/expo/eas-cli/pull/349) by [@dsokal](https://github.com/dsokal))
## [0.10.0](https://github.com/expo/eas-cli/releases/tag/v0.10.0) - 2021-04-16
### 🛠 Breaking changes
- `secrets:<COMMAND>` is renamed to `secret:<COMMAND>` ([#315](https://github.com/expo/eas-cli/pull/315) by [@fiberjw](https://github.com/fiberjw))
- `secret:delete` now accepts `id` through a flag rather than an argument ([#315](https://github.com/expo/eas-cli/pull/315) by [@fiberjw](https://github.com/fiberjw))
@@ -44,7 +114,6 @@ This is the log of notable changes to EAS CLI and related packages.
- Fix the issue where the first iOS build fails for a project without `ios.bundleIdentifier` set in `app.json`. ([#319](https://github.com/expo/eas-cli/pull/319) by [@dsokal](https://github.com/dsokal))
- Bump @expo/config-plugins to fix `eas build:configure` on Windows. ([d0f3e](https://github.com/expo/eas-cli/commit/d0f3e387e7f31dbce4c3b93b8d083c7d20d9e30d) by [@brentvatne](https://github.com/brentvatne))
- Replace REST API calls with GraphQL counterparts. ([#333](https://github.com/expo/eas-cli/pull/333) by [@barthap](https://github.com/barthap))
## [0.8.1](https://github.com/expo/eas-cli/releases/tag/v0.8.1) - 2021-04-06
+20
View File
@@ -5,6 +5,26 @@
1. Once the release is ready to go, you can go to https://github.com/expo/eas-cli/releases and mark it as not draft.
- Remember to copy the changelog entries from `CHANGELOG.md`.
1. Run `yarn lerna publish from-git` in the repository root folder. This will publish the packages to npm.
- This command works only if `HEAD` is on the release commit, e.g. when `git log -1` prints:
```
commit cbb2de9e118bfbcb5a597b261d2dbef0bb5d4b0b (tag: v0.11.1)
Author: Brent Vatne <[email protected]>
Date: Tue Apr 20 15:00:15 2021 -0700
v0.11.1
```
- If you run `yarn lerna publish from-git` on any other commit, it'll print something like:
```
lerna notice from-git No tagged release found
lerna success No changed packages to publish
```
- If you ever run into the above issue, use `git checkout RELEASE_COMMIT_HASH` to checkout to the release commit. Later, when you've published the packages to npm, run `git checkout main` to go back to the latest commit.
1. Update `CHANGELOG.md`.
- Add the new section with the release version in the title.
- Leave the `main` section empty (without any changelog entries).
+1 -1
View File
@@ -1,5 +1,5 @@
{
"npmClient": "yarn",
"useWorkspaces": true,
"version": "0.10.0"
"version": "0.14.0"
}
+27 -27
View File
@@ -49,7 +49,7 @@ eas --help COMMAND
* [`eas help [COMMAND]`](#eas-help-command)
* [`eas secret:create`](#eas-secretcreate)
* [`eas secret:delete`](#eas-secretdelete)
* [`eas secrets:list`](#eas-secretslist)
* [`eas secret:list`](#eas-secretlist)
* [`eas submit --platform=(android|ios)`](#eas-submit---platformandroidios)
* [`eas webhook:create`](#eas-webhookcreate)
* [`eas webhook:delete [ID]`](#eas-webhookdelete-id)
@@ -69,7 +69,7 @@ ALIASES
$ eas login
```
_See code: [build/commands/account/login.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/account/login.ts)_
_See code: [build/commands/account/login.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/account/login.ts)_
## `eas account:logout`
@@ -83,7 +83,7 @@ ALIASES
$ eas logout
```
_See code: [build/commands/account/logout.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/account/logout.ts)_
_See code: [build/commands/account/logout.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/account/logout.ts)_
## `eas account:view`
@@ -97,7 +97,7 @@ ALIASES
$ eas whoami
```
_See code: [build/commands/account/view.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/account/view.ts)_
_See code: [build/commands/account/view.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/account/view.ts)_
## `eas analytics [STATUS]`
@@ -108,7 +108,7 @@ USAGE
$ eas analytics [STATUS]
```
_See code: [build/commands/analytics.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/analytics.ts)_
_See code: [build/commands/analytics.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/analytics.ts)_
## `eas build`
@@ -120,6 +120,7 @@ USAGE
OPTIONS
-p, --platform=(android|ios|all)
--clear-cache Clear cache before the build
--local Run build locally [experimental]
--non-interactive Run command in --non-interactive mode
--profile=profile [default: release] Name of the build profile from eas.json
@@ -128,7 +129,7 @@ OPTIONS
--[no-]wait Wait for build(s) to complete
```
_See code: [build/commands/build/index.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/build/index.ts)_
_See code: [build/commands/build/index.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/build/index.ts)_
## `eas build:cancel [BUILD_ID]`
@@ -139,7 +140,7 @@ USAGE
$ eas build:cancel [BUILD_ID]
```
_See code: [build/commands/build/cancel.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/build/cancel.ts)_
_See code: [build/commands/build/cancel.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/build/cancel.ts)_
## `eas build:configure`
@@ -154,7 +155,7 @@ OPTIONS
--allow-experimental Enable experimental configuration steps.
```
_See code: [build/commands/build/configure.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/build/configure.ts)_
_See code: [build/commands/build/configure.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/build/configure.ts)_
## `eas build:list`
@@ -170,7 +171,7 @@ OPTIONS
--status=(in-queue|in-progress|errored|finished|canceled)
```
_See code: [build/commands/build/list.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/build/list.ts)_
_See code: [build/commands/build/list.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/build/list.ts)_
## `eas build:view [BUILD_ID]`
@@ -181,7 +182,7 @@ USAGE
$ eas build:view [BUILD_ID]
```
_See code: [build/commands/build/view.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/build/view.ts)_
_See code: [build/commands/build/view.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/build/view.ts)_
## `eas credentials`
@@ -192,7 +193,7 @@ USAGE
$ eas credentials
```
_See code: [build/commands/credentials.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/credentials.ts)_
_See code: [build/commands/credentials.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/credentials.ts)_
## `eas device:create`
@@ -203,7 +204,7 @@ USAGE
$ eas device:create
```
_See code: [build/commands/device/create.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/device/create.ts)_
_See code: [build/commands/device/create.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/device/create.ts)_
## `eas device:list`
@@ -217,7 +218,7 @@ OPTIONS
--apple-team-id=apple-team-id
```
_See code: [build/commands/device/list.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/device/list.ts)_
_See code: [build/commands/device/list.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/device/list.ts)_
## `eas device:view [UDID]`
@@ -228,7 +229,7 @@ USAGE
$ eas device:view [UDID]
```
_See code: [build/commands/device/view.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/device/view.ts)_
_See code: [build/commands/device/view.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/device/view.ts)_
## `eas help [COMMAND]`
@@ -261,7 +262,7 @@ OPTIONS
--value=value Value of the secret
```
_See code: [build/commands/secret/create.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/secret/create.ts)_
_See code: [build/commands/secret/create.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/secret/create.ts)_
## `eas secret:delete`
@@ -278,18 +279,18 @@ DESCRIPTION
Unsure where to find the secret's ID? Run eas secrets:list
```
_See code: [build/commands/secret/delete.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/secret/delete.ts)_
_See code: [build/commands/secret/delete.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/secret/delete.ts)_
## `eas secrets:list`
## `eas secret:list`
Lists environment secrets available for your current app
```
USAGE
$ eas secrets:list
$ eas secret:list
```
_See code: [build/commands/secret/list.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/secret/list.ts)_
_See code: [build/commands/secret/list.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/secret/list.ts)_
## `eas submit --platform=(android|ios)`
@@ -315,8 +316,7 @@ OPTIONS
iOS specific options=asc-app-id App Store Connect unique application Apple ID
number. Providing this param results in skipping
app creation step. Learn more:
https://expo.fyi/asc-app-id
app creation step. Learn more.
iOS specific options=bundle-identifier Your iOS Bundle Identifier (default:
expo.ios.bundleIdentifier from app config)
@@ -369,7 +369,7 @@ EXAMPLES
and provide its App ID
```
_See code: [build/commands/submit.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/submit.ts)_
_See code: [build/commands/submit.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/submit.ts)_
## `eas webhook:create`
@@ -388,7 +388,7 @@ OPTIONS
--url=url Webhook URL
```
_See code: [build/commands/webhook/create.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/webhook/create.ts)_
_See code: [build/commands/webhook/create.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/webhook/create.ts)_
## `eas webhook:delete [ID]`
@@ -402,7 +402,7 @@ ARGUMENTS
ID ID of the webhook to delete
```
_See code: [build/commands/webhook/delete.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/webhook/delete.ts)_
_See code: [build/commands/webhook/delete.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/webhook/delete.ts)_
## `eas webhook:list`
@@ -416,7 +416,7 @@ OPTIONS
--event=(BUILD) Event type that triggers the webhook
```
_See code: [build/commands/webhook/list.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/webhook/list.ts)_
_See code: [build/commands/webhook/list.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/webhook/list.ts)_
## `eas webhook:update`
@@ -436,7 +436,7 @@ OPTIONS
--url=url Webhook URL
```
_See code: [build/commands/webhook/update.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/webhook/update.ts)_
_See code: [build/commands/webhook/update.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/webhook/update.ts)_
## `eas webhook:view ID`
@@ -450,5 +450,5 @@ ARGUMENTS
ID ID of the webhook to view
```
_See code: [build/commands/webhook/view.ts](https://github.com/expo/eas-cli/blob/v0.10.0/build/commands/webhook/view.ts)_
_See code: [build/commands/webhook/view.ts](https://github.com/expo/eas-cli/blob/v0.14.0/build/commands/webhook/view.ts)_
<!-- commandsstop -->
+1
View File
@@ -3,6 +3,7 @@ schema: 'https://staging.exp.host/--/graphql'
documents:
- 'src/graphql/**/!(*.d).{ts,tsx}'
- 'src/credentials/ios/api/graphql/**/!(*.d).{ts,tsx}'
- 'src/credentials/android/api/graphql/**/!(*.d).{ts,tsx}'
- 'src/commands/**/*.ts'
generates:
src/graphql/generated.ts:
+244 -335
View File
@@ -1559,6 +1559,55 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "buildOrBuildJobs",
"description": "Coalesced Build (EAS) or BuildJob (Classic) items for this account. Use \"createdBefore\" to offset a query.",
"args": [
{
"name": "limit",
"description": "",
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"defaultValue": null
},
{
"name": "createdBefore",
"description": " Use a Date to offset queries ",
"type": {
"kind": "SCALAR",
"name": "DateTime",
"ofType": null
},
"defaultValue": null
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "BuildOrBuildJob",
"ofType": null
}
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "owner",
"description": "Owning User of this account if personal account",
@@ -1977,6 +2026,22 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "stripeId",
"description": "",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "price",
"description": "",
@@ -2861,6 +2926,55 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "buildOrBuildJobs",
"description": "Coalesced Build (EAS) or BuildJob (Classic) items for this app. Use \"createdBefore\" to offset a query.",
"args": [
{
"name": "limit",
"description": "",
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"defaultValue": null
},
{
"name": "createdBefore",
"description": " Use a Date to offset queries ",
"type": {
"kind": "SCALAR",
"name": "DateTime",
"ofType": null
},
"defaultValue": null
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "BuildOrBuildJob",
"ofType": null
}
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "submissions",
"description": "EAS Submissions associated with this app",
@@ -4061,11 +4175,54 @@
"kind": "INTERFACE",
"name": "ActivityTimelineProjectActivity",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "BuildOrBuildJob",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "INTERFACE",
"name": "BuildOrBuildJob",
"description": "",
"fields": [
{
"name": "id",
"description": "",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": [
{
"kind": "OBJECT",
"name": "Build",
"ofType": null
},
{
"kind": "OBJECT",
"name": "BuildJob",
"ofType": null
}
]
},
{
"kind": "OBJECT",
"name": "User",
@@ -4275,22 +4432,6 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "isEmailUnsubscribed",
"description": "",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "isExpoAdmin",
"description": "",
@@ -4586,6 +4727,22 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "isEmailUnsubscribed",
"description": "",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": true,
"deprecationReason": "No longer supported"
},
{
"name": "lastPasswordReset",
"description": "",
@@ -5599,6 +5756,11 @@
"kind": "INTERFACE",
"name": "ActivityTimelineProjectActivity",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "BuildOrBuildJob",
"ofType": null
}
],
"enumValues": null,
@@ -6145,280 +6307,6 @@
"enumValues": null,
"possibleTypes": null
},
{
"kind": "INPUT_OBJECT",
"name": "SubmissionFilter",
"description": "",
"fields": null,
"inputFields": [
{
"name": "platform",
"description": "",
"type": {
"kind": "ENUM",
"name": "AppPlatform",
"ofType": null
},
"defaultValue": null
},
{
"name": "status",
"description": "",
"type": {
"kind": "ENUM",
"name": "SubmissionStatus",
"ofType": null
},
"defaultValue": null
}
],
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "ENUM",
"name": "SubmissionStatus",
"description": "",
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": [
{
"name": "IN_QUEUE",
"description": "",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "IN_PROGRESS",
"description": "",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "FINISHED",
"description": "",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "ERRORED",
"description": "",
"isDeprecated": false,
"deprecationReason": null
}
],
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "Submission",
"description": "Represents an EAS Submission",
"fields": [
{
"name": "id",
"description": "",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "actor",
"description": "",
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Actor",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "activityTimestamp",
"description": "",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "DateTime",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "app",
"description": "",
"args": [],
"type": {
"kind": "OBJECT",
"name": "App",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "initiatingActor",
"description": "",
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Actor",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "platform",
"description": "",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "ENUM",
"name": "AppPlatform",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "status",
"description": "",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "ENUM",
"name": "SubmissionStatus",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "logsUrl",
"description": "",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "error",
"description": "",
"args": [],
"type": {
"kind": "OBJECT",
"name": "SubmissionError",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "createdAt",
"description": "",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "DateTime",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "updatedAt",
"description": "",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "DateTime",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "ActivityTimelineProjectActivity",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "SubmissionError",
"description": "",
"fields": [
{
"name": "errorCode",
"description": "",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "message",
"description": "",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "INPUT_OBJECT",
"name": "IosAppCredentialsFilter",
@@ -8196,9 +8084,13 @@
"description": "",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
@@ -11135,48 +11027,6 @@
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "SubmissionQuery",
"description": "",
"fields": [
{
"name": "byId",
"description": "Look up EAS Submission by submission ID",
"args": [
{
"name": "submissionId",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"defaultValue": null
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "Submission",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "UserInvitationPublicDataQuery",
@@ -15473,6 +15323,16 @@
},
"defaultValue": null
},
{
"name": "clear",
"description": "",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": null
},
{
"name": "key",
"description": "",
@@ -15637,6 +15497,16 @@
"ofType": null
},
"defaultValue": null
},
{
"name": "username",
"description": "",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": null
}
],
"interfaces": null,
@@ -15868,6 +15738,16 @@
},
"defaultValue": null
},
{
"name": "buildType",
"description": "",
"type": {
"kind": "ENUM",
"name": "AndroidManagedBuildType",
"ofType": null
},
"defaultValue": null
},
{
"name": "username",
"description": "",
@@ -15883,6 +15763,35 @@
"enumValues": null,
"possibleTypes": null
},
{
"kind": "ENUM",
"name": "AndroidManagedBuildType",
"description": "",
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": [
{
"name": "APK",
"description": "",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "APP_BUNDLE",
"description": "",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "DEVELOPMENT_CLIENT",
"description": "",
"isDeprecated": false,
"deprecationReason": null
}
],
"possibleTypes": null
},
{
"kind": "INPUT_OBJECT",
"name": "IosGenericJobInput",
+4 -4
View File
@@ -1,7 +1,7 @@
{
"name": "eas-cli",
"description": "EAS command line tool",
"version": "0.10.0",
"version": "0.14.0",
"author": "Expo <[email protected]>",
"bin": {
"eas": "./bin/run"
@@ -10,11 +10,11 @@
"dependencies": {
"@amplitude/identify": "^1.5.0",
"@amplitude/node": "^1.5.0",
"@expo/apple-utils": "0.0.0-alpha.17",
"@expo/apple-utils": "0.0.0-alpha.18",
"@expo/config": "~3.3.19",
"@expo/config-plugins": "1.0.24",
"@expo/eas-build-job": "0.2.22",
"@expo/eas-json": "^0.10.0",
"@expo/eas-build-job": "0.2.28",
"@expo/eas-json": "^0.14.0",
"@expo/json-file": "^8.2.24",
"@expo/plist": "^0.0.11",
"@expo/plugin-warn-if-update-available": "^1.7.0",
@@ -1,294 +0,0 @@
import { Workflow } from '@expo/eas-build-job';
import { CredentialsSource } from '@expo/eas-json';
import prompts from 'prompts';
import { asMock } from '../../__tests__/utils';
import { CredentialsProvider } from '../../credentials/CredentialsProvider';
import { ensureCredentialsAsync } from '../credentials';
jest.mock('prompts');
function createMockCredentialsProvider({
hasRemote,
hasLocal,
isLocalSynced,
}: any): CredentialsProvider {
return {
platform: 'android',
hasRemoteAsync: jest.fn().mockImplementation(() => hasRemote || false),
hasLocalAsync: jest.fn().mockImplementation(() => hasLocal || false),
isLocalSyncedAsync: jest.fn().mockImplementation(() => isLocalSynced || false),
} as CredentialsProvider;
}
const originalConsoleLog = console.log;
const originalConsoleWarn = console.warn;
beforeAll(() => {
console.log = jest.fn();
console.warn = jest.fn();
});
afterAll(() => {
console.log = originalConsoleLog;
console.warn = originalConsoleWarn;
});
beforeEach(() => {
asMock(prompts).mockReset();
asMock(prompts).mockImplementation(() => {
throw new Error(`unhandled prompts call - this shouldn't happen - fix tests!`);
});
});
describe(ensureCredentialsAsync, () => {
describe('for generic builds', () => {
it("should use credentials.json if it's the only available credentials", async () => {
const provider = createMockCredentialsProvider({
hasRemote: false,
hasLocal: true,
});
const src = await ensureCredentialsAsync(
provider,
Workflow.GENERIC,
CredentialsSource.AUTO,
false
);
expect(src).toBe('local');
});
it("should use credentials from server if it's the only available credentials", async () => {
const provider = createMockCredentialsProvider({
hasRemote: true,
hasLocal: false,
});
const src = await ensureCredentialsAsync(
provider,
Workflow.GENERIC,
CredentialsSource.AUTO,
false
);
expect(src).toBe('remote');
});
it('should use credentials.json if credentials are the same in credentials.json and on server', async () => {
const provider = createMockCredentialsProvider({
hasRemote: true,
hasLocal: true,
isLocalSynced: true,
});
const src = await ensureCredentialsAsync(
provider,
Workflow.GENERIC,
CredentialsSource.AUTO,
false
);
expect(prompts).toHaveBeenCalledTimes(0);
expect(src).toBe('local');
});
it('should ask which credentials to use when local and remote crednitals have different values', async () => {
const provider = createMockCredentialsProvider({
hasRemote: true,
hasLocal: true,
isLocalSynced: false,
});
asMock(prompts).mockImplementationOnce(() => {
return { select: 'local' };
});
const src = await ensureCredentialsAsync(
provider,
Workflow.GENERIC,
CredentialsSource.AUTO,
false
);
expect(prompts).toHaveBeenCalledTimes(1);
expect(src).toBe('local');
});
it('should ask when local and remote are not the same (select remote)', async () => {
const provider = createMockCredentialsProvider({
hasRemote: true,
hasLocal: true,
isLocalSynced: false,
});
asMock(prompts).mockImplementationOnce(() => {
return { select: 'remote' };
});
const src = await ensureCredentialsAsync(
provider,
Workflow.GENERIC,
CredentialsSource.AUTO,
false
);
expect(prompts).toHaveBeenCalledTimes(1);
expect(src).toBe('remote');
});
it('should should throw an error when local and remote are not the same (in non interactive mode)', async () => {
const provider = createMockCredentialsProvider({
hasRemote: true,
hasLocal: true,
isLocalSynced: false,
});
try {
await ensureCredentialsAsync(provider, Workflow.GENERIC, CredentialsSource.AUTO, true);
throw new Error('ensureCredentialsAsync should throw an Error');
} catch (e) {
expect(e.message).toMatch(
'Contents of your local credentials.json for Android are not the same as credentials on EAS servers'
);
}
expect(prompts).toHaveBeenCalledTimes(0);
});
it('should ask when no credentials are present and return remote if confirm=true', async () => {
const provider = createMockCredentialsProvider({
hasRemote: false,
hasLocal: false,
isLocalSynced: false,
});
asMock(prompts).mockImplementationOnce(() => {
return { value: true }; //confirm
});
const src = await ensureCredentialsAsync(
provider,
Workflow.GENERIC,
CredentialsSource.AUTO,
false
);
expect(prompts).toHaveBeenCalledTimes(1);
expect(src).toBe('remote');
});
it('should ask when no credentials are present and abort if confimr=false', async () => {
const provider = createMockCredentialsProvider({
hasRemote: false,
hasLocal: false,
isLocalSynced: false,
});
asMock(prompts).mockImplementationOnce(() => {
return { value: false }; //confirm
});
try {
await ensureCredentialsAsync(provider, Workflow.GENERIC, CredentialsSource.AUTO, false);
throw new Error('ensureCredentialsAsync should throw an Error');
} catch (e) {
expect(e.message).toMatch(
'Aborting build process, credentials are not configured for Android'
);
}
expect(prompts).toHaveBeenCalledTimes(1);
});
it('should throw an error when no credentials are present in non interactive mode', async () => {
const provider = createMockCredentialsProvider({
hasRemote: false,
hasLocal: false,
isLocalSynced: false,
});
asMock(prompts).mockImplementation(() => {
return { value: true }; // confirm
});
try {
await ensureCredentialsAsync(provider, Workflow.GENERIC, CredentialsSource.AUTO, true);
throw new Error('ensureCredentialsAsync should throw an Error');
} catch (e) {
expect(e.message).toMatch('Credentials for this app are not configured');
}
expect(prompts).toHaveBeenCalledTimes(0);
});
});
describe('for managed builds', () => {
it("should use credentials.json if it's the only available credentials", async () => {
const provider = createMockCredentialsProvider({
hasRemote: false,
hasLocal: true,
});
const src = await ensureCredentialsAsync(
provider,
Workflow.MANAGED,
CredentialsSource.AUTO,
false
);
expect(src).toBe('local');
});
it("should use credentials from server if it's the only available credentials", async () => {
const provider = createMockCredentialsProvider({
hasRemote: true,
hasLocal: false,
});
const src = await ensureCredentialsAsync(
provider,
Workflow.MANAGED,
CredentialsSource.AUTO,
false
);
expect(src).toBe('remote');
});
it('should use credentials.json if credentials are the same in credentials.json and on server', async () => {
const provider = createMockCredentialsProvider({
hasRemote: true,
hasLocal: true,
isLocalSynced: true,
});
const src = await ensureCredentialsAsync(
provider,
Workflow.MANAGED,
CredentialsSource.AUTO,
false
);
expect(prompts).toHaveBeenCalledTimes(0);
expect(src).toBe('local');
});
it('should use credentials.json even if credentials on server are different', async () => {
const provider = createMockCredentialsProvider({
hasRemote: true,
hasLocal: true,
isLocalSynced: false,
});
const src = await ensureCredentialsAsync(
provider,
Workflow.MANAGED,
CredentialsSource.AUTO,
false
);
expect(prompts).toHaveBeenCalledTimes(0);
expect(src).toBe('local');
});
});
describe('generic builds with credentialsSource set to local', () => {
it('should use credentials.json without asking even if credentials on server are different', async () => {
const provider = createMockCredentialsProvider({
hasRemote: true,
hasLocal: true,
isLocalSynced: false,
});
const src = await ensureCredentialsAsync(
provider,
Workflow.GENERIC,
CredentialsSource.LOCAL,
false
);
expect(prompts).toHaveBeenCalledTimes(0);
expect(src).toBe('local');
});
});
describe('generic builds with credentialsSource set to remote', () => {
it('should use credentials from server even if credentials.json exists and have different values', async () => {
const provider = createMockCredentialsProvider({
hasRemote: true,
hasLocal: true,
isLocalSynced: false,
});
const src = await ensureCredentialsAsync(
provider,
Workflow.GENERIC,
CredentialsSource.REMOTE,
false
);
expect(prompts).toHaveBeenCalledTimes(0);
expect(src).toBe('remote');
});
});
});
+3 -7
View File
@@ -13,9 +13,9 @@ import Log from '../../log';
import { toggleConfirmAsync } from '../../prompts';
import { CredentialsResult, prepareBuildRequestForPlatformAsync } from '../build';
import { BuildContext, CommandContext, createBuildContext } from '../context';
import { ensureCredentialsAsync } from '../credentials';
import { transformMetadata } from '../graphql';
import { Platform } from '../types';
import { logCredentialsSource } from '../utils/credentials';
import { ensureApplicationIdIsValidAsync } from './applicationId';
import { validateAndSyncProjectConfigurationAsync } from './configure';
import { transformGenericJob, transformManagedJob } from './graphql';
@@ -125,12 +125,8 @@ async function ensureAndroidCredentialsAsync(
skipCredentialsCheck: ctx.commandCtx.skipCredentialsCheck,
}
);
const credentialsSource = await ensureCredentialsAsync(
provider,
ctx.buildProfile.workflow,
ctx.buildProfile.credentialsSource,
ctx.commandCtx.nonInteractive
);
const { credentialsSource } = ctx.buildProfile;
logCredentialsSource(credentialsSource, Platform.ANDROID);
return {
credentials: await provider.getCredentialsAsync(credentialsSource),
source: credentialsSource,
+16 -1
View File
@@ -1,6 +1,10 @@
import { Android } from '@expo/eas-build-job';
import { AndroidGenericJobInput, AndroidManagedJobInput } from '../../graphql/generated';
import {
AndroidGenericJobInput,
AndroidManagedBuildType,
AndroidManagedJobInput,
} from '../../graphql/generated';
import { transformProjectArchive } from '../graphql';
export function transformGenericJob(job: Android.GenericJob): AndroidGenericJobInput {
@@ -25,5 +29,16 @@ export function transformManagedJob(job: Android.ManagedJob): AndroidManagedJobI
builderEnvironment: job.builderEnvironment,
cache: job.cache,
username: job.username,
buildType: transformBuildType(job.buildType),
};
}
function transformBuildType(buildType: Android.ManagedBuildType): AndroidManagedBuildType {
if (buildType === Android.ManagedBuildType.APK) {
return AndroidManagedBuildType.Apk;
} else if (buildType === Android.ManagedBuildType.APP_BUNDLE) {
return AndroidManagedBuildType.AppBundle;
} else {
return AndroidManagedBuildType.DevelopmentClient;
}
}
@@ -4,7 +4,8 @@ import path from 'path';
import { AndroidCredentials } from '../../credentials/android/AndroidCredentialsProvider';
import { readEnvironmentSecretsAsync } from '../../credentials/credentialsJson/read';
import { getProjectAccountNameAsync } from '../../project/projectUtils';
import { getUsername } from '../../project/projectUtils';
import { ensureLoggedInAsync } from '../../user/actions';
import { gitRootDirectoryAsync } from '../../utils/git';
import { BuildContext } from '../context';
import { Platform } from '../types';
@@ -71,7 +72,10 @@ async function prepareJobCommonAsync(
ndk: ctx.buildProfile.ndk,
env: ctx.buildProfile.env,
},
cache: ctx.buildProfile.cache,
cache: {
...ctx.buildProfile.cache,
clear: ctx.commandCtx.clearCache,
},
secrets: {
...(environmentSecrets ? { environmentSecrets } : {}),
...buildCredentials,
@@ -103,11 +107,11 @@ async function prepareManagedJobAsync(
): Promise<Partial<Android.ManagedJob>> {
const projectRootDirectory =
path.relative(await gitRootDirectoryAsync(), ctx.commandCtx.projectDir) || '.';
const accountName = await getProjectAccountNameAsync(ctx.commandCtx.exp);
const username = getUsername(ctx.commandCtx.exp, await ensureLoggedInAsync());
return {
...(await prepareJobCommonAsync(ctx, jobData)),
type: Workflow.MANAGED,
username: accountName,
username,
buildType: buildProfile.buildType,
releaseChannel: buildProfile.releaseChannel,
projectRootDirectory,
+17 -3
View File
@@ -109,10 +109,24 @@ export async function prepareBuildRequestForPlatformAsync<
return undefined;
} else {
try {
return sendBuildRequestAsync(builder, job, metadata);
return await sendBuildRequestAsync(builder, job, metadata);
} catch (error) {
if (error?.expoApiV2ErrorCode === 'TURTLE_DEPRECATED_JOB_FORMAT') {
Log.error('EAS Build API has changed, please upgrade to the latest eas-cli');
if (error?.graphQLErrors?.[0]?.extensions?.errorCode === 'TURTLE_DEPRECATED_JOB_FORMAT') {
Log.error('EAS Build API has changed, please upgrade to the latest eas-cli version.');
throw new Error('Build request failed.');
} else if (
error?.graphQLErrors?.[0]?.extensions?.errorCode === 'EAS_BUILD_TOO_MANY_PENDING_BUILDS'
) {
Log.error(
`You have already reached the maximum number of pending ${
requestedPlatformDisplayNames[job.platform]
} builds for your account. Try again later.`
);
throw new Error('Build request failed.');
} else if (error?.graphQLErrors) {
Log.error(
'Build request failed. Make sure you are using the latest eas-cli version. If the problem persists, please report the issue.'
);
}
throw error;
}
+4
View File
@@ -20,6 +20,7 @@ export interface CommandContext {
exp: ExpoConfig;
nonInteractive: boolean;
local: boolean;
clearCache: boolean;
skipCredentialsCheck: boolean;
skipProjectConfiguration: boolean;
waitForBuildEnd: boolean;
@@ -33,6 +34,7 @@ export async function createCommandContextAsync({
projectId,
nonInteractive = false,
local,
clearCache = false,
skipCredentialsCheck = false,
skipProjectConfiguration = false,
waitForBuildEnd,
@@ -44,6 +46,7 @@ export async function createCommandContextAsync({
projectDir: string;
nonInteractive: boolean;
local: boolean;
clearCache: boolean;
skipCredentialsCheck: boolean;
skipProjectConfiguration: boolean;
waitForBuildEnd: boolean;
@@ -63,6 +66,7 @@ export async function createCommandContextAsync({
exp,
nonInteractive,
local,
clearCache,
skipCredentialsCheck,
skipProjectConfiguration,
waitForBuildEnd,
+1 -1
View File
@@ -71,7 +71,7 @@ async function startBuildsAsync(
async function waitForBuildEndAsync(
buildIds: string[],
{ timeoutSec = 1800, intervalSec = 30 } = {}
{ timeoutSec = 3600, intervalSec = 30 } = {}
): Promise<(BuildFragment | null)[]> {
Log.log('Waiting for build to complete. You can press Ctrl+C to exit.');
const spinner = ora().start();
-104
View File
@@ -1,104 +0,0 @@
import { Platform, Workflow } from '@expo/eas-build-job';
import { CredentialsSource } from '@expo/eas-json';
import chalk from 'chalk';
import { CredentialsProvider } from '../credentials/CredentialsProvider';
import Log from '../log';
import { confirmAsync, promptAsync } from '../prompts';
import { requestedPlatformDisplayNames } from './constants';
function logCredentials(target: 'local' | 'remote', platform: Platform) {
let message = `Using ${target} ${requestedPlatformDisplayNames[platform]} credentials`;
if (target === 'local') message += ` ${chalk.dim('(credentials.json)')}`;
if (target === 'remote') message += ` ${chalk.dim('(Expo server)')}`;
Log.succeed(message);
}
async function ensureCredentialsAutoAsync(
provider: CredentialsProvider,
workflow: Workflow,
nonInteractive: boolean
): Promise<CredentialsSource.LOCAL | CredentialsSource.REMOTE> {
const platform = requestedPlatformDisplayNames[provider.platform];
switch (workflow) {
case Workflow.MANAGED:
if (await provider.hasLocalAsync()) {
return CredentialsSource.LOCAL;
} else {
return CredentialsSource.REMOTE;
}
case Workflow.GENERIC: {
const hasLocal = await provider.hasLocalAsync();
const hasRemote = await provider.hasRemoteAsync();
if (hasRemote && hasLocal) {
if (!(await provider.isLocalSyncedAsync())) {
if (nonInteractive) {
throw new Error(
`Contents of your local credentials.json for ${platform} are not the same as credentials on EAS servers. To use the desired credentials, set the "builds.${platform}.{profile}.credentialsSource" field in the credentials.json file to one of the following: "local", "remote".`
);
} else {
Log.log(
`Contents of your local credentials.json for ${platform} are not the same as credentials on EAS servers`
);
}
const { select } = await promptAsync({
type: 'select',
name: 'select',
message: 'Which credentials do you want to use for this build?',
choices: [
{ title: 'Local credentials.json', value: CredentialsSource.LOCAL },
{ title: 'Credentials stored on EAS servers.', value: CredentialsSource.REMOTE },
],
});
return select;
} else {
return CredentialsSource.LOCAL;
}
} else if (hasLocal) {
logCredentials('local', provider.platform);
return CredentialsSource.LOCAL;
} else if (hasRemote) {
logCredentials('remote', provider.platform);
return CredentialsSource.REMOTE;
} else {
if (nonInteractive) {
throw new Error(
`Credentials for this app are not configured and there is no entry in credentials.json for ${platform}. Either configure credentials.json, or launch the build without "--non-interactive" flag to get a prompt to generate credentials automatically.`
);
} else if (Log.isDebug) {
Log.warn(
`Credentials for this app are not configured and there is no entry in credentials.json for ${platform}`
);
}
const confirm = await confirmAsync({
message: `${platform} credentials not found, generate now?`,
});
if (confirm) {
return CredentialsSource.REMOTE;
} else {
throw new Error(`Aborting build process, credentials are not configured for ${platform}`);
}
}
}
}
}
export async function ensureCredentialsAsync(
provider: CredentialsProvider,
workflow: Workflow,
src: CredentialsSource,
nonInteractive: boolean
): Promise<CredentialsSource.LOCAL | CredentialsSource.REMOTE> {
switch (src) {
case CredentialsSource.LOCAL:
logCredentials('local', provider.platform);
return CredentialsSource.LOCAL;
case CredentialsSource.REMOTE:
logCredentials('remote', provider.platform);
return CredentialsSource.REMOTE;
case CredentialsSource.AUTO:
return await ensureCredentialsAutoAsync(provider, workflow, nonInteractive);
}
}
@@ -6,12 +6,12 @@ import { createCredentialsContextAsync } from '../../credentials/context';
import IosCredentialsProvider, {
IosCredentials,
} from '../../credentials/ios/IosCredentialsProvider';
import { getAppLookupParamsFromContext } from '../../credentials/ios/actions/new/BuildCredentialsUtils';
import { getAppLookupParamsFromContext } from '../../credentials/ios/actions/BuildCredentialsUtils';
import { AppLookupParams } from '../../credentials/ios/credentials';
import { CredentialsResult } from '../build';
import { BuildContext } from '../context';
import { ensureCredentialsAsync } from '../credentials';
import { Platform } from '../types';
import { logCredentialsSource } from '../utils/credentials';
export async function ensureIosCredentialsAsync(
ctx: BuildContext<Platform.IOS>
@@ -59,12 +59,8 @@ export async function resolveIosCredentialsAsync(
enterpriseProvisioning: params.enterpriseProvisioning,
skipCredentialsCheck: params.skipCredentialsCheck,
});
const credentialsSource = await ensureCredentialsAsync(
provider,
params.workflow,
params.credentialsSource,
params.nonInteractive
);
const { credentialsSource } = params;
logCredentialsSource(credentialsSource, Platform.IOS);
return {
credentials: await provider.getCredentialsAsync(credentialsSource),
source: credentialsSource,
+8 -4
View File
@@ -9,7 +9,8 @@ import {
isCredentialsMap,
readEnvironmentSecretsAsync,
} from '../../credentials/credentialsJson/read';
import { getProjectAccountNameAsync } from '../../project/projectUtils';
import { getUsername } from '../../project/projectUtils';
import { ensureLoggedInAsync } from '../../user/actions';
import { gitRootDirectoryAsync } from '../../utils/git';
import { BuildContext } from '../context';
import { Platform } from '../types';
@@ -90,7 +91,10 @@ async function prepareJobCommonAsync(
fastlane: ctx.buildProfile.fastlane,
env: ctx.buildProfile.env,
},
cache: ctx.buildProfile.cache,
cache: {
...ctx.buildProfile.cache,
clear: ctx.commandCtx.clearCache,
},
secrets: {
...(environmentSecrets ? { environmentSecrets } : {}),
buildCredentials,
@@ -140,7 +144,7 @@ async function prepareManagedJobAsync(
): Promise<Partial<Ios.ManagedJob>> {
const projectRootDirectory =
path.relative(await gitRootDirectoryAsync(), ctx.commandCtx.projectDir) || '.';
const accountName = await getProjectAccountNameAsync(ctx.commandCtx.exp);
const username = getUsername(ctx.commandCtx.exp, await ensureLoggedInAsync());
return {
...(await prepareJobCommonAsync(ctx, {
credentials: jobData.credentials,
@@ -149,7 +153,7 @@ async function prepareManagedJobAsync(
})),
type: Workflow.MANAGED,
buildType: buildProfile.buildType,
username: accountName,
username,
releaseChannel: buildProfile.releaseChannel,
projectRootDirectory,
};
+3 -1
View File
@@ -1,7 +1,8 @@
import { Metadata } from '@expo/eas-build-job';
import { CredentialsSource } from '@expo/eas-json';
import { getAppIdentifierAsync } from '../project/projectUtils';
import { getAppIdentifierAsync, getUsername } from '../project/projectUtils';
import { ensureLoggedInAsync } from '../user/actions';
import { gitCommitHashAsync } from '../utils/git';
import { readReleaseChannelSafelyAsync as readAndroidReleaseChannelSafelyAsync } from './android/UpdatesModule';
import { BuildContext } from './context';
@@ -42,6 +43,7 @@ export async function collectMetadata<T extends Platform>(
})) ?? undefined,
buildProfile: ctx.commandCtx.profile,
gitCommitHash: await gitCommitHashAsync(),
username: getUsername(ctx.commandCtx.exp, await ensureLoggedInAsync()),
};
}
@@ -0,0 +1,15 @@
import { Platform } from '@expo/eas-build-job';
import { CredentialsSource } from '@expo/eas-json';
import chalk from 'chalk';
import Log from '../../log';
import { requestedPlatformDisplayNames } from '../constants';
export function logCredentialsSource(credentialsSource: CredentialsSource, platform: Platform) {
let message = `Using ${credentialsSource} ${requestedPlatformDisplayNames[platform]} credentials`;
if (credentialsSource === CredentialsSource.LOCAL)
message += ` ${chalk.dim('(credentials.json)')}`;
else if (credentialsSource === CredentialsSource.REMOTE)
message += ` ${chalk.dim('(Expo server)')}`;
Log.succeed(message);
}
@@ -1,5 +1,7 @@
import assert from 'assert';
import chalk from 'chalk';
import indentString from 'indent-string';
import qrcodeTerminal from 'qrcode-terminal';
import {
BuildError,
@@ -15,7 +17,7 @@ import {
appPlatformEmojis,
requestedPlatformDisplayNames,
} from '../constants';
import { getBuildLogsUrl } from './url';
import { getBuildLogsUrl, getInternalDistributionInstallUrl } from './url';
export function printLogsUrls(
accountName: string,
@@ -82,10 +84,12 @@ function printBuildResult(accountName: string, build: BuildFragment): void {
buildId: build.id,
account: accountName,
});
const installUrl = getInternalDistributionInstallUrl(build);
qrcodeTerminal.generate(installUrl, code => console.log(`${indentString(code, 2)}\n`));
Log.log(
`${appPlatformEmojis[build.platform]} Open this link on your ${
appPlatformDisplayNames[build.platform]
} devices to install the app:`
} devices (or scan the QR code) to install the app:`
);
Log.log(`${chalk.underline(logsUrl)}`);
} else {
+16 -1
View File
@@ -1,4 +1,7 @@
import { getExpoWebsiteBaseUrl } from '../../api';
import assert from 'assert';
import { getExpoApiBaseUrl, getExpoWebsiteBaseUrl } from '../../api';
import { AppPlatform, BuildFragment } from '../../graphql/generated';
export function getBuildLogsUrl({
buildId,
@@ -13,3 +16,15 @@ export function getBuildLogsUrl({
export function getArtifactUrl(artifactId: string): string {
return `${getExpoWebsiteBaseUrl()}/artifacts/${artifactId}`;
}
export function getInternalDistributionInstallUrl(build: BuildFragment): string {
if (build.platform === AppPlatform.Ios) {
return `itms-services://?action=download-manifest;url=${getExpoApiBaseUrl()}/--/api/v2/projects/${
build.project.id
}/builds/${build.id}/manifest.plist`;
}
assert(build.artifacts?.buildUrl, 'buildUrl is missing');
return build.artifacts.buildUrl;
}
+7 -75
View File
@@ -2,7 +2,6 @@ import { ExpoConfig, getConfig } from '@expo/config';
import { Command, flags } from '@oclif/command';
import chalk from 'chalk';
import fs from 'fs-extra';
import nullthrows from 'nullthrows';
import path from 'path';
import {
@@ -13,22 +12,14 @@ import { configureAsync } from '../../build/configure';
import { createCommandContextAsync } from '../../build/context';
import { buildAsync } from '../../build/create';
import { RequestedPlatform } from '../../build/types';
import { formatGraphQLBuild } from '../../build/utils/formatBuild';
import { isGitStatusCleanAsync } from '../../build/utils/repository';
import { AppPlatform } from '../../graphql/generated';
import { BuildQuery } from '../../graphql/queries/BuildQuery';
import Log, { learnMore } from '../../log';
import {
isEasEnabledForProjectAsync,
warnEasUnavailable,
} from '../../project/isEasEnabledForProject';
import {
findProjectRootAsync,
getProjectAccountNameAsync,
getProjectIdAsync,
} from '../../project/projectUtils';
import { findProjectRootAsync, getProjectIdAsync } from '../../project/projectUtils';
import { confirmAsync, promptAsync } from '../../prompts';
import { Actor } from '../../user/User';
import { ensureLoggedInAsync } from '../../user/actions';
export default class Build extends Command {
@@ -61,13 +52,17 @@ export default class Build extends Command {
allowNo: true,
description: 'Wait for build(s) to complete',
}),
'clear-cache': flags.boolean({
default: false,
description: 'Clear cache before the build',
}),
};
async run(): Promise<void> {
const { flags } = this.parse(Build);
await initAnalyticsAsync(); // TODO: run in oclif hook for every command
try {
const user = await ensureLoggedInAsync();
await ensureLoggedInAsync();
const nonInteractive = flags['non-interactive'];
if (!flags.platform && nonInteractive) {
@@ -91,17 +86,6 @@ export default class Build extends Command {
return;
}
const accountName = await getProjectAccountNameAsync(exp);
const accountHasPendingBuilds = await ensureNoPendingBuildsExistAsync({
accountName,
platform,
projectId,
user,
});
if (accountHasPendingBuilds) {
return;
}
exp = (await ensureProjectConfiguredAsync(projectDir)) ?? exp;
const commandCtx = await createCommandContextAsync({
@@ -111,6 +95,7 @@ export default class Build extends Command {
projectDir,
projectId,
nonInteractive,
clearCache: flags['clear-cache'],
skipCredentialsCheck: flags['skip-credentials-check'],
local: flags.local,
skipProjectConfiguration: flags['skip-project-configuration'],
@@ -123,49 +108,6 @@ export default class Build extends Command {
}
}
async function ensureNoPendingBuildsExistAsync({
user,
platform,
accountName,
projectId,
}: {
user: Actor;
platform: RequestedPlatform;
accountName: string;
projectId: string;
}): Promise<boolean> {
// allow expo admins to run as many builds as they wish
if (user.isExpoAdmin) {
return false;
}
const appPlatforms = toAppPlatforms(platform);
const maybePendingBuilds = await Promise.all(
appPlatforms.map(appPlatform => BuildQuery.getPendingBuildIdAsync(accountName, appPlatform))
);
const pendingBuilds = maybePendingBuilds.filter(i => i !== null);
if (pendingBuilds.length > 0) {
Log.newLine();
Log.error(
'Your other builds are still pending. Wait for them to complete before running this command again.'
);
Log.newLine();
const results = await Promise.all(
pendingBuilds.map(pendingBuild => {
return BuildQuery.byIdAsync(nullthrows(pendingBuild).id);
})
);
for (const result of results) {
Log.log(formatGraphQLBuild(result));
}
process.exitCode = 1;
return true;
}
return false;
}
function verifyOptionsForLocalBuilds(platform: RequestedPlatform): boolean {
if (platform === RequestedPlatform.All) {
Log.error('Builds for multiple platforms are not supported with flag --local');
@@ -178,16 +120,6 @@ function verifyOptionsForLocalBuilds(platform: RequestedPlatform): boolean {
}
}
function toAppPlatforms(requestedPlatform: RequestedPlatform): AppPlatform[] {
if (requestedPlatform === RequestedPlatform.All) {
return [AppPlatform.Android, AppPlatform.Ios];
} else if (requestedPlatform === RequestedPlatform.Android) {
return [AppPlatform.Android];
} else {
return [AppPlatform.Ios];
}
}
async function promptForPlatformAsync(): Promise<RequestedPlatform> {
const { platform } = await promptAsync({
type: 'select',
@@ -20,7 +20,6 @@ import { ensureLoggedInAsync } from '../../user/actions';
export default class EnvironmentSecretList extends Command {
static description = 'Lists environment secrets available for your current app';
static usage = 'secrets:list';
async run(): Promise<void> {
await ensureLoggedInAsync();
@@ -1,8 +0,0 @@
import { Platform } from '@expo/eas-build-job';
export interface CredentialsProvider {
platform: Platform;
hasRemoteAsync(): Promise<boolean>;
hasLocalAsync(): Promise<boolean>;
isLocalSyncedAsync(): Promise<boolean>;
}
@@ -0,0 +1,61 @@
import {
AndroidAppBuildCredentialsFragment,
AndroidKeystoreFragment,
AndroidKeystoreType,
AppFragment,
CommonAndroidAppCredentialsFragment,
} from '../../graphql/generated';
import { testKeystore } from './fixtures-android';
import { testKeystoreBase64 } from './fixtures-base64-data';
export const testAppFragment: AppFragment = {
id: 'test-app-id',
fullName: '@testuser/testapp',
slug: 'testapp',
};
export const testJksAndroidKeystoreFragment: AndroidKeystoreFragment = {
id: 'test-id',
type: AndroidKeystoreType.Jks,
keystore: testKeystoreBase64,
keystorePassword: testKeystore.keystorePassword,
keyAlias: testKeystore.keyAlias,
keyPassword: testKeystore.keyPassword,
md5CertificateFingerprint: 'test-md5',
sha1CertificateFingerprint: 'test-sha1',
sha256CertificateFingerprint: 'test-sha256',
createdAt: new Date(),
updatedAt: new Date(),
};
export const testLegacyAndroidBuildCredentialsFragment: AndroidAppBuildCredentialsFragment = {
id: 'test-id',
isDefault: true,
isLegacy: true,
name: 'legacy',
androidKeystore: testJksAndroidKeystoreFragment,
};
export const testLegacyAndroidAppCredentialsFragment: CommonAndroidAppCredentialsFragment = {
id: 'test-id',
applicationIdentifier: null,
isLegacy: true,
app: testAppFragment,
androidAppBuildCredentialsList: [testLegacyAndroidBuildCredentialsFragment],
};
export const testAndroidBuildCredentialsFragment: AndroidAppBuildCredentialsFragment = {
id: 'test-id',
isDefault: true,
isLegacy: false,
name: 'Google App Store Build Credentials',
androidKeystore: testJksAndroidKeystoreFragment,
};
export const testAndroidAppCredentialsFragment: CommonAndroidAppCredentialsFragment = {
id: 'test-id',
applicationIdentifier: null,
isLegacy: false,
app: testAppFragment,
androidAppBuildCredentialsList: [testLegacyAndroidBuildCredentialsFragment],
};
@@ -34,6 +34,7 @@ export const testAppJson = {
slug: testSlug,
sdkVersion: '38.0.0',
ios: { bundleIdentifier: testBundleIdentifier },
android: { package: testPackageName },
};
export const testAppJsonWithDifferentOwner = {
@@ -5,15 +5,14 @@ import { Context } from '../context';
import { getAndroidApiMockWithoutCredentials } from './fixtures-android';
import { getAppstoreMock } from './fixtures-appstore';
import { testAppJson, testUsername } from './fixtures-constants';
import { getIosApiMockWithoutCredentials } from './fixtures-ios';
import { getNewIosApiMockWithoutCredentials } from './fixtures-new-ios';
import { getNewIosApiMockWithoutCredentials } from './fixtures-ios';
export function createCtxMock(mockOverride: Record<string, any> = {}): Context {
const defaultMock = {
ios: getIosApiMockWithoutCredentials(),
newIos: getNewIosApiMockWithoutCredentials(),
ios: getNewIosApiMockWithoutCredentials(),
android: getAndroidApiMockWithoutCredentials(),
appStore: getAppstoreMock(),
bestEffortAppStoreAuthenticateAsync: jest.fn(),
ensureAppleCtx: jest.fn(),
ensureProjectContext: jest.fn(),
user: {
@@ -4,45 +4,25 @@ import {
AppleDistributionCertificateFragment,
AppleProvisioningProfileFragment,
AppleTeamFragment,
CommonIosAppCredentialsFragment,
IosAppBuildCredentialsFragment,
IosDistributionType,
} from '../../graphql/generated';
import { IosAppCredentialsWithBuildCredentialsQueryResult } from '../ios/api/graphql/queries/IosAppCredentialsQuery';
import {
DistributionCertificate,
DistributionCertificateStoreInfo,
ProvisioningProfile,
ProvisioningProfileStoreInfo,
PushKey,
PushKeyStoreInfo,
} from '../ios/appstore/Credentials.types';
import { IosDistCredentials, IosPushCredentials } from '../ios/credentials';
import { testProvisioningProfileBase64 } from './fixtures-base64-data';
import { testBundleIdentifier, testExperienceName } from './fixtures-constants';
const today = new Date();
const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
export const testAppleTeam = {
id: 'test-team-id',
};
export const testProvisioningProfile: ProvisioningProfile = {
provisioningProfileId: 'test-id',
provisioningProfile: testProvisioningProfileBase64,
teamId: 'id',
};
export const testProvisioningProfiles = [testProvisioningProfile];
export const testProvisioningProfileFromApple: ProvisioningProfileStoreInfo = {
name: 'test-name',
status: 'Active',
expires: tomorrow.getTime(),
distributionMethod: 'test',
certificates: [],
provisioningProfileId: testProvisioningProfile.provisioningProfileId,
provisioningProfile: testProvisioningProfile.provisioningProfile,
teamId: 'id',
};
export const testProvisioningProfilesFromApple = [testProvisioningProfileFromApple];
export const testAppleTeamFragment: AppleTeamFragment = {
id: 'test-apple-team-id-1',
@@ -64,7 +44,7 @@ export const testProvisioningProfileFragment: AppleProvisioningProfileFragment =
id: 'test-prov-prof-id-1',
expiration: new Date(),
developerPortalIdentifier: 'test-developer-identifier',
provisioningProfile: 'test-provisioning-profile',
provisioningProfile: testProvisioningProfileBase64,
updatedAt: new Date(),
status: 'Active',
appleTeam: { ...testAppleTeamFragment },
@@ -117,11 +97,61 @@ export const testIosAppBuildCredentialsFragment: IosAppBuildCredentialsFragment
provisioningProfile: testProvisioningProfileFragment,
};
export const testCommonIosAppCredentialsFragment: CommonIosAppCredentialsFragment = {
id: 'test-common-ios-app-credentials-id',
app: testAppFragment,
appleTeam: testAppleTeamFragment,
appleAppIdentifier: testAppleAppIdentifierFragment,
iosAppBuildCredentialsList: [testIosAppBuildCredentialsFragment],
};
export const testIosAppCredentialsWithBuildCredentialsQueryResult: IosAppCredentialsWithBuildCredentialsQueryResult = {
id: 'test-app-credential-id',
iosAppBuildCredentialsArray: [testIosAppBuildCredentialsFragment],
iosAppBuildCredentialsList: [testIosAppBuildCredentialsFragment],
};
export const testAppleTeam = {
id: 'test-team-id',
};
export function getNewIosApiMockWithoutCredentials() {
return {
createOrUpdateIosAppBuildCredentialsAsync: jest.fn(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(),
createOrGetExistingIosAppCredentialsWithBuildCredentialsAsync: jest.fn(),
createOrGetExistingAppleTeamAsync: () => testAppleTeam,
createOrGetExistingAppleAppIdentifierAsync: jest.fn(),
getDevicesForAppleTeamAsync: jest.fn(),
createProvisioningProfileAsync: jest.fn(),
getProvisioningProfileAsync: jest.fn(),
updateProvisioningProfileAsync: jest.fn(),
deleteProvisioningProfilesAsync: jest.fn(),
getDistributionCertificateForAppAsync: jest.fn(),
getDistributionCertificatesForAccountAsync: jest.fn(),
createDistributionCertificateAsync: jest.fn(),
deleteDistributionCertificateAsync: jest.fn(),
};
}
export function getNewIosApiMockWithCredentials() {
return {
createOrUpdateIosAppBuildCredentialsAsync: jest.fn(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(),
createOrGetExistingIosAppCredentialsWithBuildCredentialsAsync: jest.fn(),
createOrGetExistingAppleTeamAsync: jest.fn(),
createOrGetExistingAppleAppIdentifierAsync: jest.fn(),
getDevicesForAppleTeamAsync: jest.fn(),
createProvisioningProfileAsync: jest.fn(),
getProvisioningProfileAsync: jest.fn(),
updateProvisioningProfileAsync: jest.fn(),
deleteProvisioningProfilesAsync: jest.fn(),
getDistributionCertificateForAppAsync: jest.fn(),
getDistributionCertificatesForAccountAsync: jest.fn(),
createDistributionCertificateAsync: jest.fn(),
deleteDistributionCertificateAsync: jest.fn(),
};
}
export const testDistCert: DistributionCertificate = {
certP12: 'Y2VydHAxMg==',
certPassword: 'test-password',
@@ -133,18 +163,6 @@ export const testIosDistCredential: IosDistCredentials = {
type: 'dist-cert',
...testDistCert,
};
export const testIosDistCredentials = [testIosDistCredential];
export const testDistCertFromApple: DistributionCertificateStoreInfo = {
id: 'test-id',
name: 'test-name',
status: 'Active',
created: today.getTime(),
expires: tomorrow.getTime(),
ownerName: 'test-owner',
ownerId: 'test-id',
serialNumber: testIosDistCredential.distCertSerialNumber as string,
};
export const testDistCertsFromApple = [testDistCertFromApple];
export const testPushKey: PushKey = {
apnsKeyP8: 'test-p8',
@@ -152,22 +170,16 @@ export const testPushKey: PushKey = {
teamId: 'test-team-id',
};
/**
* Legacy format fixtures
*/
export const testIosPushCredential: IosPushCredentials = {
id: 2,
type: 'push-key',
...testPushKey,
};
export const testIosPushCredentials = [testIosPushCredential];
export const testPushKeyFromApple: PushKeyStoreInfo = {
id: testIosPushCredential.apnsKeyId,
name: 'test-name',
};
export const testPushKeysFromApple = [testPushKeyFromApple];
export const testLegacyPushCert = {
pushId: 'test-push-id',
pushP12: 'test-push-p12',
pushPassword: 'test-push-password',
};
export const testAppCredential = {
experienceName: testExperienceName,
bundleIdentifier: testBundleIdentifier,
@@ -182,62 +194,3 @@ export const testAllCredentialsForApp = {
pushCredentials: testPushKey,
distCredentials: testDistCert,
};
export const testAppCredentials = [testAppCredential];
export const testAllCredentials = {
userCredentials: [...testIosDistCredentials, ...testIosPushCredentials],
appCredentials: testAppCredentials,
};
export function getIosApiMock() {
return {
getAllCredentials: jest.fn(() => testAllCredentials),
getDistributionCertificateAsync: jest.fn(() => testIosDistCredential),
getDistributionCertificateByIdAsync: jest.fn(id =>
id === testIosDistCredential.id ? testIosDistCredential : null
),
createDistributionCertificateAsync: jest.fn((owner, cert) => ({
id: 123,
type: 'dist-cert',
...cert,
})),
updateDistributionCertificateAsync: jest.fn(),
deleteDistributionCertificateAsync: jest.fn(),
useDistributionCertificateAsync: jest.fn(),
getPushKey: jest.fn(() => testIosPushCredential),
createPushKeyAsync: jest.fn((owner, key) => ({ id: 124, type: 'push-key', ...key })),
updatePushKeyAsync: jest.fn(),
deletePushKeyAsync: jest.fn(),
usePushKeyAsync: jest.fn(),
getAppCredentialsAsync: jest.fn(() => testAppCredentials),
getProvisioningProfileAsync: jest.fn(() => testProvisioningProfile),
updateProvisioningProfileAsync: jest.fn(),
deleteProvisioningProfileAsync: jest.fn(),
};
}
export function getIosApiMockWithoutCredentials() {
return {
getAllCredentials: jest.fn(() => ({ appCredentials: [], userCredentials: [] })),
getDistributionCertificateAsync: jest.fn(() => null),
getDistributionCertificateByIdAsync: jest.fn(() => {
throw new Error('not found');
}),
createDistributionCertificateAsync: jest.fn(),
updateDistributionCertificateAsync: jest.fn(),
deleteDistributionCertificateAsync: jest.fn(),
useDistributionCertificateAsync: jest.fn(),
getPushKeyAsync: jest.fn(() => null),
createPushKeyAsync: jest.fn(),
updatePushKeyAsync: jest.fn(),
deletePushKeyAsync: jest.fn(),
usePushKeyAsync: jest.fn(),
getAppCredentialsAsync: jest.fn(app => ({
experienceName: `${app.accountName}/${app.projectName}`,
bundleIdentifier: app.bundleIdentifier,
})),
getProvisioningProfileAsync: jest.fn(() => null),
updateProvisioningProfileAsync: jest.fn(),
deleteProvisioningProfileAsync: jest.fn(),
};
}
@@ -1,141 +0,0 @@
import {
DistributionCertificate,
DistributionCertificateStoreInfo,
ProvisioningProfile,
ProvisioningProfileStoreInfo,
PushKey,
PushKeyStoreInfo,
} from '../ios/appstore/Credentials.types';
import { IosDistCredentials, IosPushCredentials } from '../ios/credentials';
import { testProvisioningProfileBase64 } from './fixtures-base64-data';
import { testBundleIdentifier, testExperienceName } from './fixtures-constants';
const today = new Date();
const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
export const testAppleTeam = {
id: 'test-team-id',
};
export const testProvisioningProfile: ProvisioningProfile = {
provisioningProfileId: 'test-id',
provisioningProfile: testProvisioningProfileBase64,
teamId: 'id',
};
export const testProvisioningProfiles = [testProvisioningProfile];
export const testProvisioningProfileFromApple: ProvisioningProfileStoreInfo = {
name: 'test-name',
status: 'Active',
expires: tomorrow.getTime(),
distributionMethod: 'test',
certificates: [],
provisioningProfileId: testProvisioningProfile.provisioningProfileId,
provisioningProfile: testProvisioningProfile.provisioningProfile,
teamId: 'id',
};
export const testProvisioningProfilesFromApple = [testProvisioningProfileFromApple];
export const testDistCert: DistributionCertificate = {
certP12: 'Y2VydHAxMg==',
certPassword: 'test-password',
distCertSerialNumber: 'test-serial',
teamId: 'test-team-id',
};
export const testIosDistCredential: IosDistCredentials = {
id: 1,
type: 'dist-cert',
...testDistCert,
};
export const testIosDistCredentials = [testIosDistCredential];
export const testDistCertFromApple: DistributionCertificateStoreInfo = {
id: 'test-id',
name: 'test-name',
status: 'Active',
created: today.getTime(),
expires: tomorrow.getTime(),
ownerName: 'test-owner',
ownerId: 'test-id',
serialNumber: testIosDistCredential.distCertSerialNumber as string,
};
export const testDistCertsFromApple = [testDistCertFromApple];
export const testPushKey: PushKey = {
apnsKeyP8: 'test-p8',
apnsKeyId: 'test-key-id',
teamId: 'test-team-id',
};
export const testIosPushCredential: IosPushCredentials = {
id: 2,
type: 'push-key',
...testPushKey,
};
export const testIosPushCredentials = [testIosPushCredential];
export const testPushKeyFromApple: PushKeyStoreInfo = {
id: testIosPushCredential.apnsKeyId,
name: 'test-name',
};
export const testPushKeysFromApple = [testPushKeyFromApple];
export const testLegacyPushCert = {
pushId: 'test-push-id',
pushP12: 'test-push-p12',
pushPassword: 'test-push-password',
};
export const testAppCredential = {
experienceName: testExperienceName,
bundleIdentifier: testBundleIdentifier,
distCredentialsId: testIosDistCredential.id,
pushCredentialsId: testIosPushCredential.id,
credentials: {
...testProvisioningProfile,
},
};
export const testAllCredentialsForApp = {
...testAppCredential,
pushCredentials: testPushKey,
distCredentials: testDistCert,
};
export const testAppCredentials = [testAppCredential];
export const testAllCredentials = {
userCredentials: [...testIosDistCredentials, ...testIosPushCredentials],
appCredentials: testAppCredentials,
};
export function getNewIosApiMockWithoutCredentials() {
return {
getAppAsync: jest.fn(),
createOrUpdateIosAppBuildCredentialsAsync: jest.fn(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(),
createOrGetExistingIosAppCredentialsWithBuildCredentialsAsync: jest.fn(),
createOrGetExistingAppleTeamAsync: () => testAppleTeam,
createOrGetExistingAppleAppIdentifierAsync: jest.fn(),
getDevicesForAppleTeamAsync: jest.fn(),
createProvisioningProfileAsync: jest.fn(),
getProvisioningProfileAsync: jest.fn(),
updateProvisioningProfileAsync: jest.fn(),
deleteProvisioningProfilesAsync: jest.fn(),
getDistributionCertificateForAppAsync: jest.fn(),
getDistributionCertificatesForAccountAsync: jest.fn(),
createDistributionCertificateAsync: jest.fn(),
deleteDistributionCertificateAsync: jest.fn(),
};
}
export function getNewIosApiMockWithCredentials() {
return {
getAppAsync: jest.fn(),
createOrUpdateIosAppBuildCredentialsAsync: jest.fn(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(),
createOrGetExistingIosAppCredentialsWithBuildCredentialsAsync: jest.fn(),
createOrGetExistingAppleTeamAsync: jest.fn(),
createOrGetExistingAppleAppIdentifierAsync: jest.fn(),
getDevicesForAppleTeamAsync: jest.fn(),
createProvisioningProfileAsync: jest.fn(),
getProvisioningProfileAsync: jest.fn(),
updateProvisioningProfileAsync: jest.fn(),
deleteProvisioningProfilesAsync: jest.fn(),
getDistributionCertificateForAppAsync: jest.fn(),
getDistributionCertificatesForAccountAsync: jest.fn(),
createDistributionCertificateAsync: jest.fn(),
deleteDistributionCertificateAsync: jest.fn(),
};
}
@@ -1,9 +1,7 @@
import { Platform } from '@expo/eas-build-job';
import { CredentialsSource } from '@expo/eas-json';
import Log from '../../log';
import { CredentialsManager } from '../CredentialsManager';
import { CredentialsProvider } from '../CredentialsProvider';
import { Context } from '../context';
import * as credentialsJsonReader from '../credentialsJson/read';
import { SetupBuildCredentials } from './actions/SetupBuildCredentials';
@@ -23,7 +21,7 @@ interface Options {
skipCredentialsCheck?: boolean;
}
export default class AndroidCredentialsProvider implements CredentialsProvider {
export default class AndroidCredentialsProvider {
public readonly platform = Platform.ANDROID;
constructor(private ctx: Context, private options: Options) {}
@@ -33,45 +31,6 @@ export default class AndroidCredentialsProvider implements CredentialsProvider {
return `@${accountName}/${projectName}`;
}
public async hasRemoteAsync(): Promise<boolean> {
const keystore = await this.ctx.android.fetchKeystoreAsync(this.projectFullName);
return !!keystore;
}
public async hasLocalAsync(): Promise<boolean> {
if (!(await credentialsJsonReader.fileExistsAsync(this.ctx.projectDir))) {
return false;
}
try {
const rawCredentialsJson = await credentialsJsonReader.readRawAsync(this.ctx.projectDir);
return !!rawCredentialsJson?.android;
} catch (err) {
Log.error(err); // malformed json
return false;
}
}
public async isLocalSyncedAsync(): Promise<boolean> {
try {
const [remote, local] = await Promise.all([
this.ctx.android.fetchKeystoreAsync(this.projectFullName),
credentialsJsonReader.readAndroidCredentialsAsync(this.ctx.projectDir),
]);
const r = remote;
const l = local?.keystore;
return !!(
r &&
l &&
r.keystore === l.keystore &&
r.keystorePassword === l.keystorePassword &&
r.keyAlias === l.keyAlias &&
r.keyPassword === l.keyPassword
);
} catch (_) {
return false;
}
}
public async getCredentialsAsync(
src: CredentialsSource.LOCAL | CredentialsSource.REMOTE
): Promise<AndroidCredentials> {
@@ -81,7 +40,6 @@ export default class AndroidCredentialsProvider implements CredentialsProvider {
case CredentialsSource.REMOTE:
return await this.getRemoteAsync();
}
throw new Error('Unknown');
}
private async getRemoteAsync(): Promise<AndroidCredentials> {
@@ -0,0 +1,25 @@
import { getProjectAccountName, getProjectConfigDescription } from '../../../project/projectUtils';
import { findAccountByName } from '../../../user/Account';
import { Context } from '../../context';
import { AppLookupParams } from '../api/GraphqlClient';
export function getAppLookupParamsFromContext(ctx: Context): AppLookupParams {
ctx.ensureProjectContext();
const projectName = ctx.exp.slug;
const accountName = getProjectAccountName(ctx.exp, ctx.user);
const account = findAccountByName(ctx.user.accounts, accountName);
if (!account) {
throw new Error(`You do not have access to account: ${accountName}`);
}
const androidApplicationIdentifier = ctx.exp.android?.package;
if (!androidApplicationIdentifier) {
throw new Error(
`android.package needs to be defined in your ${getProjectConfigDescription(
ctx.projectDir
)} file`
);
}
return { account, projectName, androidApplicationIdentifier };
}
@@ -0,0 +1,40 @@
import { CommonAndroidAppCredentialsFragment } from '../../../graphql/generated';
import { Account } from '../../../user/Account';
import { AndroidAppCredentialsQuery } from './graphql/queries/AndroidAppCredentialsQuery';
export interface AppLookupParams {
account: Account;
projectName: string;
androidApplicationIdentifier: string; // 'android.package' field in app.json
}
export async function getAndroidAppCredentialsWithCommonFieldsAsync(
appLookupParams: AppLookupParams
): Promise<CommonAndroidAppCredentialsFragment | null> {
const { androidApplicationIdentifier } = appLookupParams;
const projectFullName = formatProjectFullName(appLookupParams);
return await AndroidAppCredentialsQuery.withCommonFieldsByApplicationIdentifierAsync(
projectFullName,
{
androidApplicationIdentifier,
legacyOnly: false,
}
);
}
/* There is at most one set of legacy android app credentials associated with an Expo App */
export async function getLegacyAndroidAppCredentialsWithCommonFieldsAsync(
appLookupParams: AppLookupParams
): Promise<CommonAndroidAppCredentialsFragment | null> {
const projectFullName = formatProjectFullName(appLookupParams);
return await AndroidAppCredentialsQuery.withCommonFieldsByApplicationIdentifierAsync(
projectFullName,
{
legacyOnly: true,
}
);
}
// TODO; refactor
const formatProjectFullName = ({ account, projectName }: AppLookupParams): string =>
`@${account.name}/${projectName}`;
@@ -0,0 +1,65 @@
import assert from 'assert';
import { print } from 'graphql';
import gql from 'graphql-tag';
import { graphqlClient, withErrorHandlingAsync } from '../../../../../graphql/client';
import {
CommonAndroidAppCredentialsFragment,
CommonAndroidAppCredentialsWithBuildCredentialsByApplicationIdentifierQuery,
} from '../../../../../graphql/generated';
import { CommonAndroidAppCredentialsFragmentNode } from '../../../../../graphql/types/credentials/AndroidAppCredentials';
const AndroidAppCredentialsQuery = {
async withCommonFieldsByApplicationIdentifierAsync(
projectFullName: string,
{
androidApplicationIdentifier,
legacyOnly,
}: {
androidApplicationIdentifier?: string;
legacyOnly?: boolean;
}
): Promise<CommonAndroidAppCredentialsFragment | null> {
const data = await withErrorHandlingAsync(
graphqlClient
.query<CommonAndroidAppCredentialsWithBuildCredentialsByApplicationIdentifierQuery>(
gql`
query CommonAndroidAppCredentialsWithBuildCredentialsByApplicationIdentifierQuery(
$projectFullName: String!
$applicationIdentifier: String
$legacyOnly: Boolean
) {
app {
byFullName(fullName: $projectFullName) {
id
androidAppCredentials(
filter: {
applicationIdentifier: $applicationIdentifier
legacyOnly: $legacyOnly
}
) {
id
...CommonAndroidAppCredentialsFragment
}
}
}
}
${print(CommonAndroidAppCredentialsFragmentNode)}
`,
{
projectFullName,
applicationIdentifier: androidApplicationIdentifier,
legacyOnly,
},
{
additionalTypenames: ['AndroidAppCredentials', 'AndroidAppBuildCredentials', 'App'],
}
)
.toPromise()
);
assert(data.app, 'GraphQL: `app` not defined in server response');
return data.app.byFullName.androidAppCredentials[0] ?? null;
},
};
export { AndroidAppCredentialsQuery };
@@ -0,0 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`print credentials prints the AndroidAppCredentials fragment 1`] = `"Android Credentials Project: testApp Application Identifier: test.com.app EAS Credentials: These will take precedence over Expo Classic credentials Configuration: legacy (Default) Keystore: Type: JKS Key Alias: QHdrb3p5cmEvY3JlZGVudGlhbHMtdGVzdA== MD5 Fingerprint: TE:ST:-M:D5 SHA1 Fingerprint: TE:ST:-S:HA:1 SHA256 Fingerprint: TE:ST:-S:HA:25:6 Updated 0 second ago Credentials ported from Expo Classic (expo-cli): Keystore: Type: JKS Key Alias: QHdrb3p5cmEvY3JlZGVudGlhbHMtdGVzdA== MD5 Fingerprint: TE:ST:-M:D5 SHA1 Fingerprint: TE:ST:-S:HA:1 SHA256 Fingerprint: TE:ST:-S:HA:25:6 Updated 0 second ago"`;
@@ -0,0 +1,31 @@
import mockdate from 'mockdate';
import Log from '../../../../log';
import {
testAndroidAppCredentialsFragment,
testLegacyAndroidAppCredentialsFragment,
} from '../../../__tests__/fixtures-android-new';
import { createCtxMock } from '../../../__tests__/fixtures-context';
import { getAppLookupParamsFromContext } from '../../actions/BuildCredentialsUtils';
import { displayAndroidAppCredentials } from '../printCredentialsBeta';
jest.mock('../../../../log');
jest.mock('chalk', () => ({ bold: jest.fn(log => log) }));
mockdate.set(new Date('4/20/2021'));
describe('print credentials', () => {
it('prints the AndroidAppCredentials fragment', async () => {
const ctx = createCtxMock();
const appLookupParams = getAppLookupParamsFromContext(ctx);
displayAndroidAppCredentials({
appLookupParams,
legacyAppCredentials: testLegacyAndroidAppCredentialsFragment,
appCredentials: testAndroidAppCredentialsFragment,
});
const loggedSoFar = (Log.log as jest.Mock).mock.calls.reduce(
(acc, mockValue) => acc + mockValue
);
expect(loggedSoFar).toMatchSnapshot();
});
});
@@ -0,0 +1,143 @@
import chalk from 'chalk';
import {
AndroidAppBuildCredentialsFragment,
CommonAndroidAppCredentialsFragment,
} from '../../../graphql/generated';
import Log from '../../../log';
import { fromNow } from '../../../utils/date';
import { AppLookupParams } from '../api/GraphqlClient';
export function displayEmptyAndroidCredentials(appLookupParams: AppLookupParams): void {
const { projectName, androidApplicationIdentifier } = appLookupParams;
Log.log(chalk.bold(`Android Credentials`));
Log.log(` Project: ${projectName}`);
Log.log(` Application Identifier: ${androidApplicationIdentifier}`);
Log.log(` No credentials set up yet!`);
}
/**
* sort a build credentials array in descending order of preference
* prefer default credentials, then prefer names that come first lexicographically
*/
function sortBuildCredentials(
androidAppBuildCredentialsList: AndroidAppBuildCredentialsFragment[]
): AndroidAppBuildCredentialsFragment[] {
return androidAppBuildCredentialsList.sort((buildCredentialsA, buildCredentialsB) => {
if (buildCredentialsA.isDefault) {
return -1;
} else if (buildCredentialsB.isDefault) {
return 1;
}
return buildCredentialsA.name.localeCompare(buildCredentialsB.name);
});
}
function displayLegacyAndroidAppCredentials(
legacyAppCredentials: CommonAndroidAppCredentialsFragment,
appCredentials: CommonAndroidAppCredentialsFragment | null
): void {
if (appCredentials) {
// differentiate between old and new if there's both
Log.log(chalk.bold(` Credentials ported from Expo Classic (expo-cli):`));
}
// There can only be one set of build credentials in legacy app credentials
const [legacyBuildCredentials] = legacyAppCredentials.androidAppBuildCredentialsList;
if (legacyBuildCredentials) {
displayAndroidBuildCredentials(
legacyBuildCredentials,
/* only one set to show, skip config display */ true
);
}
}
function displayEASAndroidAppCredentials(
legacyAppCredentials: CommonAndroidAppCredentialsFragment | null,
appCredentials: CommonAndroidAppCredentialsFragment
): void {
if (legacyAppCredentials) {
// differentiate between old and new if there's both
Log.log(chalk.bold(` EAS Credentials:`));
Log.log(` These will take precedence over Expo Classic credentials`);
}
const sortedBuildCredentialsList = sortBuildCredentials(
appCredentials.androidAppBuildCredentialsList
);
for (const buildCredentials of sortedBuildCredentialsList) {
displayAndroidBuildCredentials(buildCredentials);
}
}
function formatFingerprint(fingerprint: string | null): string {
if (!fingerprint) {
return 'unavailable';
}
const uppercaseFingerprint = fingerprint.toUpperCase();
const bytes = [];
for (let i = 0; i < uppercaseFingerprint.length; i++) {
const halfByte = uppercaseFingerprint.charAt(i);
if (i % 2 === 0) {
bytes.push(halfByte); // first half of the byte
} else {
bytes[bytes.length - 1] += halfByte; // second half of the byte
}
}
return bytes.join(':');
}
function displayAndroidBuildCredentials(
buildCredentials: AndroidAppBuildCredentialsFragment,
skipConfigurationDisplay?: boolean
): void {
if (!skipConfigurationDisplay) {
const { isDefault, name } = buildCredentials;
Log.log(chalk.bold(` Configuration: ${name}${isDefault ? ' (Default)' : ''}`));
Log.newLine();
}
const maybeKeystore = buildCredentials.androidKeystore;
Log.log(` Keystore:`);
if (maybeKeystore) {
const {
keyAlias,
type,
md5CertificateFingerprint,
sha1CertificateFingerprint,
sha256CertificateFingerprint,
updatedAt,
} = maybeKeystore;
Log.log(` Type: ${type}`);
Log.log(` Key Alias: ${keyAlias}`);
Log.log(` MD5 Fingerprint: ${formatFingerprint(md5CertificateFingerprint ?? null)}`);
Log.log(` SHA1 Fingerprint: ${formatFingerprint(sha1CertificateFingerprint ?? null)}`);
Log.log(` SHA256 Fingerprint: ${formatFingerprint(sha256CertificateFingerprint ?? null)}`);
Log.log(` Updated ${fromNow(new Date(updatedAt))} ago`);
} else {
Log.log(` None assigned yet`);
}
Log.newLine();
}
export function displayAndroidAppCredentials({
appLookupParams,
legacyAppCredentials,
appCredentials,
}: {
appLookupParams: AppLookupParams;
legacyAppCredentials: CommonAndroidAppCredentialsFragment | null;
appCredentials: CommonAndroidAppCredentialsFragment | null;
}): void {
const { projectName, androidApplicationIdentifier } = appLookupParams;
Log.log(chalk.bold(`Android Credentials`));
Log.log(` Project: ${projectName}`);
Log.log(` Application Identifier: ${androidApplicationIdentifier}`);
Log.newLine();
if (appCredentials) {
displayEASAndroidAppCredentials(legacyAppCredentials, appCredentials);
}
if (legacyAppCredentials) {
displayLegacyAndroidAppCredentials(legacyAppCredentials, appCredentials);
}
}
+5 -5
View File
@@ -8,7 +8,7 @@ import { confirmAsync } from '../prompts';
import { Actor, getActorDisplayName } from '../user/User';
import { ensureLoggedInAsync } from '../user/actions';
import AndroidApi from './android/api/Client';
import IosApi from './ios/api/Client';
import * as AndroidGraphqlClient from './android/api/GraphqlClient';
import * as IosGraphqlClient from './ios/api/GraphqlClient';
import AppStoreApi from './ios/appstore/AppStoreApi';
@@ -27,8 +27,8 @@ export interface Context {
readonly user: Actor;
readonly nonInteractive: boolean;
readonly android: AndroidApi;
readonly ios: IosApi;
readonly newIos: typeof IosGraphqlClient;
readonly newAndroid: typeof AndroidGraphqlClient;
readonly ios: typeof IosGraphqlClient;
readonly appStore: AppStoreApi;
readonly hasProjectContext: boolean;
readonly exp: ExpoConfig;
@@ -56,8 +56,8 @@ export async function createCredentialsContextAsync(
class CredentialsContext implements Context {
public readonly android = new AndroidApi();
public readonly ios = new IosApi();
public readonly newIos = IosGraphqlClient;
public readonly newAndroid = AndroidGraphqlClient;
public readonly ios = IosGraphqlClient;
public readonly appStore: AppStoreApi;
public readonly nonInteractive: boolean;
private shouldAskAuthenticateAppStore: boolean = true;
@@ -3,13 +3,15 @@ import { vol } from 'memfs';
import prompts from 'prompts';
import { asMock } from '../../../__tests__/utils';
import { IosDistributionType } from '../../../graphql/generated';
import { testKeystore } from '../../__tests__/fixtures-android';
import { createCtxMock } from '../../__tests__/fixtures-context';
import {
getNewIosApiMockWithoutCredentials,
testAllCredentialsForApp,
testIosDistCredential,
testProvisioningProfile,
testCommonIosAppCredentialsFragment,
} from '../../__tests__/fixtures-ios';
import { getAppLookupParamsFromContext } from '../../ios/actions/BuildCredentialsUtils';
import { updateAndroidCredentialsAsync, updateIosCredentialsAsync } from '../update';
jest.mock('fs');
@@ -195,9 +197,10 @@ describe('update credentials.json', () => {
it('should update ios credentials in credentials.json if www returns valid credentials', async () => {
const ctx = createCtxMock({
ios: {
getAppCredentialsAsync: jest.fn(() => testAllCredentialsForApp),
getDistributionCertificateAsync: jest.fn(() => testIosDistCredential),
getProvisioningProfileAsync: jest.fn(() => testProvisioningProfile),
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithCommonFieldsAsync: jest.fn(
() => testCommonIosAppCredentialsFragment
),
},
});
vol.fromJSON({
@@ -213,12 +216,19 @@ describe('update credentials.json', () => {
'./pprofile': 'somebinarycontent',
'./cert.p12': 'somebinarycontent2',
});
await updateIosCredentialsAsync(ctx, 'bundleIdentifier');
const appLookupParams = getAppLookupParamsFromContext(ctx);
await updateIosCredentialsAsync(ctx, appLookupParams, IosDistributionType.AppStore);
const certP12 = await fs.readFile('./cert.p12', 'base64');
const pprofile = await fs.readFile('./pprofile', 'base64');
const credJson = await fs.readJson('./credentials.json');
expect(certP12).toEqual(testAllCredentialsForApp.distCredentials.certP12);
expect(pprofile).toEqual(testAllCredentialsForApp.credentials.provisioningProfile);
expect(certP12).toEqual(
testCommonIosAppCredentialsFragment.iosAppBuildCredentialsList[0].distributionCertificate
?.certificateP12
);
expect(pprofile).toEqual(
testCommonIosAppCredentialsFragment.iosAppBuildCredentialsList[0].provisioningProfile
?.provisioningProfile
);
expect(credJson).toEqual({
ios: {
provisioningProfilePath: 'pprofile',
@@ -232,12 +242,14 @@ describe('update credentials.json', () => {
it('should create credentials.json provisioning profile and distribution certificate if credentials.json does not exist', async () => {
const ctx = createCtxMock({
ios: {
getAppCredentialsAsync: jest.fn(() => testAllCredentialsForApp),
getDistributionCertificateAsync: jest.fn(() => testIosDistCredential),
getProvisioningProfileAsync: jest.fn(() => testProvisioningProfile),
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithCommonFieldsAsync: jest.fn(
() => testCommonIosAppCredentialsFragment
),
},
});
await updateIosCredentialsAsync(ctx, 'bundleIdentifier');
const appLookupParams = getAppLookupParamsFromContext(ctx);
await updateIosCredentialsAsync(ctx, appLookupParams, IosDistributionType.AppStore);
const certP12 = await fs.readFile('./ios/certs/dist-cert.p12', 'base64');
const pprofile = await fs.readFile('./ios/certs/profile.mobileprovision', 'base64');
const credJson = await fs.readJson('./credentials.json');
@@ -256,9 +268,8 @@ describe('update credentials.json', () => {
it('should not do anything if no credentials are returned from www', async () => {
const ctx = createCtxMock({
ios: {
getAppCredentialsAsync: jest.fn(() => null),
getDistributionCertificateAsync: jest.fn(() => null),
getProvisioningProfileAsync: jest.fn(() => null),
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithCommonFieldsAsync: jest.fn(() => null),
},
});
const credJson = {
@@ -276,11 +287,12 @@ describe('update credentials.json', () => {
'./cert.p12': 'somebinarycontent2',
});
try {
await updateIosCredentialsAsync(ctx, 'bundleIdentifier');
const appLookupParams = getAppLookupParamsFromContext(ctx);
await updateIosCredentialsAsync(ctx, appLookupParams, IosDistributionType.AppStore);
throw new Error('updateIosCredentialsAsync should throw na error');
} catch (e) {
expect(e.message).toMatch(
'There are no credentials configured for this project on EAS servers'
'There are no credentials configured for the APP_STORE distribution of this project on EAS servers'
);
}
const certP12 = await fs.readFile('./cert.p12', 'base64');
@@ -291,15 +303,15 @@ describe('update credentials.json', () => {
expect(newCredJson).toEqual(credJson);
});
it('should display confirm prompt if some credentials are missing in www (confirm: true)', async () => {
// create deep clone the quick and dirty way
const testIosAppCredentialsNoDistCert = JSON.parse(
JSON.stringify(testCommonIosAppCredentialsFragment)
);
testIosAppCredentialsNoDistCert.iosAppBuildCredentialsList[0].distributionCertificate = null;
const ctx = createCtxMock({
ios: {
getAppCredentialsAsync: jest.fn(() => ({
...testAllCredentialsForApp,
distCredentialsId: undefined,
distCredentials: undefined,
})),
getDistributionCertificateAsync: jest.fn(() => null),
getProvisioningProfileAsync: jest.fn(() => testProvisioningProfile),
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithCommonFieldsAsync: jest.fn(() => testIosAppCredentialsNoDistCert),
},
});
@@ -322,7 +334,8 @@ describe('update credentials.json', () => {
'./pprofile': 'somebinarycontent',
'./cert.p12': 'somebinarycontent2',
});
await updateIosCredentialsAsync(ctx, 'bundleIdentifier');
const appLookupParams = getAppLookupParamsFromContext(ctx);
await updateIosCredentialsAsync(ctx, appLookupParams, IosDistributionType.AppStore);
const certP12Exists = await fs.pathExists('./cert.p12');
const pprofile = await fs.readFile('./pprofile', 'base64');
const credJson = await fs.readJson('./credentials.json');
@@ -337,9 +350,10 @@ describe('update credentials.json', () => {
it('should throw an error if credentials.json contains credentials for multi-target projects', async () => {
const ctx = createCtxMock({
ios: {
getAppCredentialsAsync: jest.fn(() => testAllCredentialsForApp),
getDistributionCertificateAsync: jest.fn(() => testIosDistCredential),
getProvisioningProfileAsync: jest.fn(() => testProvisioningProfile),
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithCommonFieldsAsync: jest.fn(
() => testCommonIosAppCredentialsFragment
),
},
});
vol.fromJSON({
@@ -366,16 +380,18 @@ describe('update credentials.json', () => {
'./dist-cert-1.p12': 'cert-1-somebinarycontent',
'./dist-cert-2.p12': 'cert-2-somebinarycontent',
});
await expect(() => updateIosCredentialsAsync(ctx, 'bundleIdentifier')).rejects.toThrow(
/Updating credentials.json failed/
);
const appLookupParams = getAppLookupParamsFromContext(ctx);
await expect(() =>
updateIosCredentialsAsync(ctx, appLookupParams, IosDistributionType.AppStore)
).rejects.toThrow(/Updating credentials.json failed/);
});
it(`should throw an error if there is a typo in credentials.json (because we can't tell if this is a target name or not)`, async () => {
const ctx = createCtxMock({
ios: {
getAppCredentialsAsync: jest.fn(() => testAllCredentialsForApp),
getDistributionCertificateAsync: jest.fn(() => testIosDistCredential),
getProvisioningProfileAsync: jest.fn(() => testProvisioningProfile),
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithCommonFieldsAsync: jest.fn(
() => testCommonIosAppCredentialsFragment
),
},
});
vol.fromJSON({
@@ -392,9 +408,10 @@ describe('update credentials.json', () => {
'./pprofile-1.mobileprovision': 'pprofile-1-somebinarycontent',
'./dist-cert-1.p12': 'cert-1-somebinarycontent',
});
await expect(() => updateIosCredentialsAsync(ctx, 'bundleIdentifier')).rejects.toThrow(
/Updating credentials.json failed/
);
const appLookupParams = getAppLookupParamsFromContext(ctx);
await expect(() =>
updateIosCredentialsAsync(ctx, appLookupParams, IosDistributionType.AppStore)
).rejects.toThrow(/Updating credentials.json failed/);
});
});
});
@@ -1,11 +1,13 @@
import fs from 'fs-extra';
import path from 'path';
import { IosDistributionType as IosDistributionTypeGraphql } from '../../graphql/generated';
import Log from '../../log';
import { getProjectAccountName } from '../../project/projectUtils';
import { confirmAsync } from '../../prompts';
import { gitStatusAsync } from '../../utils/git';
import { Context } from '../context';
import { AppLookupParams } from '../ios/api/GraphqlClient';
import { CredentialsJson } from './read';
/**
@@ -84,7 +86,8 @@ export async function updateAndroidCredentialsAsync(ctx: Context): Promise<void>
*/
export async function updateIosCredentialsAsync(
ctx: Context,
bundleIdentifier: string
appLookupParams: AppLookupParams,
iosDistributionTypeGraphql: IosDistributionTypeGraphql
): Promise<void> {
const credentialsJsonFilePath = path.join(ctx.projectDir, 'credentials.json');
let rawCredentialsJsonObject: any = {};
@@ -118,26 +121,27 @@ export async function updateIosCredentialsAsync(
}
}
const accountName = getProjectAccountName(ctx.exp, ctx.user);
const appLookupParams = {
accountName,
projectName: ctx.exp.slug,
bundleIdentifier,
};
const profilePath =
rawCredentialsJsonObject?.ios?.provisioningProfilePath ?? 'ios/certs/profile.mobileprovision';
const distCertPath =
rawCredentialsJsonObject?.ios?.distributionCertificate?.path ?? 'ios/certs/dist-cert.p12';
const appCredentials = await ctx.ios.getAppCredentialsAsync(appLookupParams);
const distCredentials = await ctx.ios.getDistributionCertificateAsync(appLookupParams);
if (!appCredentials?.credentials?.provisioningProfile && !distCredentials) {
throw new Error('There are no credentials configured for this project on EAS servers');
const iosAppCredentials = await ctx.ios.getIosAppCredentialsWithCommonFieldsAsync(
appLookupParams
);
const buildCredentials =
iosAppCredentials?.iosAppBuildCredentialsList.find(
buildCredentials => buildCredentials.iosDistributionType === iosDistributionTypeGraphql
) ?? null;
if (!buildCredentials) {
throw new Error(
`There are no credentials configured for the ${iosDistributionTypeGraphql} distribution of this project on EAS servers`
);
}
const areCredentialsComplete =
appCredentials?.credentials?.provisioningProfile &&
distCredentials?.certP12 &&
distCredentials?.certPassword;
buildCredentials.provisioningProfile?.provisioningProfile &&
buildCredentials.distributionCertificate?.certificateP12 &&
buildCredentials.distributionCertificate.certificatePassword;
if (!areCredentialsComplete) {
const confirm = await confirmAsync({
@@ -149,28 +153,27 @@ export async function updateIosCredentialsAsync(
return;
}
}
const provisioningProfile =
buildCredentials.provisioningProfile?.provisioningProfile ?? undefined;
const distributionCertificateP12 =
buildCredentials.distributionCertificate?.certificateP12 ?? undefined;
const distributionCertificatePassword =
buildCredentials.distributionCertificate?.certificatePassword ?? undefined;
Log.log(`Writing Provisioning Profile to ${profilePath}`);
await updateFileAsync(
ctx.projectDir,
profilePath,
appCredentials?.credentials?.provisioningProfile
);
await updateFileAsync(ctx.projectDir, profilePath, provisioningProfile);
const shouldWarnPProfile = await isFileUntrackedAsync(profilePath);
Log.log(`Writing Distribution Certificate to ${distCertPath}`);
await updateFileAsync(ctx.projectDir, distCertPath, distCredentials?.certP12);
await updateFileAsync(ctx.projectDir, distCertPath, distributionCertificateP12);
const shouldWarnDistCert = await isFileUntrackedAsync(distCertPath);
const iosCredentials: Partial<CredentialsJson['ios']> = {
...(appCredentials?.credentials?.provisioningProfile
? { provisioningProfilePath: profilePath }
: {}),
...(distCredentials?.certP12 && distCredentials?.certPassword
...(provisioningProfile ? { provisioningProfilePath: profilePath } : {}),
...(distributionCertificateP12 && distributionCertificatePassword
? {
distributionCertificate: {
path: distCertPath,
password: distCredentials?.certPassword,
password: distributionCertificatePassword,
},
}
: {}),
@@ -1,18 +1,11 @@
import { Platform } from '@expo/eas-build-job';
import { CredentialsSource, IosDistributionType, IosEnterpriseProvisioning } from '@expo/eas-json';
import { IosAppBuildCredentialsFragment } from '../../graphql/generated';
import Log from '../../log';
import { CredentialsManager } from '../CredentialsManager';
import { CredentialsProvider } from '../CredentialsProvider';
import { Context } from '../context';
import * as credentialsJsonReader from '../credentialsJson/read';
import type { IosCredentials } from '../credentialsJson/read';
import { SetupBuildCredentials } from './actions/SetupBuildCredentials';
import {
getBuildCredentialsAsync,
resolveDistributionType,
} from './actions/new/BuildCredentialsUtils';
import { AppLookupParams } from './api/GraphqlClient';
import { isAdHocProfile } from './utils/provisioningProfile';
@@ -25,72 +18,18 @@ interface Options {
skipCredentialsCheck?: boolean;
}
export default class IosCredentialsProvider implements CredentialsProvider {
export default class IosCredentialsProvider {
public readonly platform = Platform.IOS;
constructor(private ctx: Context, private options: Options) {}
public async hasRemoteAsync(): Promise<boolean> {
// TODO: this is temporary
// remove this check when we implement syncing local credentials for internal distribution
if (this.options.distribution === 'internal' && (await this.hasLocalAsync())) {
return false;
}
const buildCredentials = await this.fetchRemoteAsync();
return !!(
buildCredentials?.distributionCertificate?.certificateP12 ||
buildCredentials?.distributionCertificate?.certificatePassword ||
buildCredentials?.provisioningProfile?.provisioningProfile
);
}
public async hasLocalAsync(): Promise<boolean> {
if (!(await credentialsJsonReader.fileExistsAsync(this.ctx.projectDir))) {
return false;
}
try {
const rawCredentialsJson = await credentialsJsonReader.readRawAsync(this.ctx.projectDir);
return !!rawCredentialsJson?.ios;
} catch (err) {
Log.error(err); // malformed json
return false;
}
}
public async isLocalSyncedAsync(): Promise<boolean> {
try {
const [remote, local] = await Promise.all([this.fetchRemoteAsync(), this.getLocalAsync()]);
const r = remote;
const l = local;
// TODO
// For now, when credentials.json contains credentials for multi-target project
// assume they are synced with the Expo servers.
// Change this behavior when we figure out how to store multi-target project credentials in the db.
if (credentialsJsonReader.isCredentialsMap(l)) {
return true;
}
return !!(
r &&
l &&
r.provisioningProfile?.provisioningProfile === l.provisioningProfile &&
r.distributionCertificate?.certificateP12 === l.distributionCertificate.certP12 &&
r.distributionCertificate?.certificatePassword === l.distributionCertificate.certPassword
);
} catch (_) {
return false;
}
}
public async getCredentialsAsync(
src: CredentialsSource.LOCAL | CredentialsSource.REMOTE
): Promise<IosCredentials> {
switch (src) {
case CredentialsSource.LOCAL:
return await this.getLocalAsync();
case CredentialsSource.REMOTE:
return await this.getRemoteAsync();
if (src === CredentialsSource.LOCAL) {
return await this.getLocalAsync();
} else {
return await this.getRemoteAsync();
}
}
@@ -124,54 +63,18 @@ export default class IosCredentialsProvider implements CredentialsProvider {
}
private async getRemoteAsync(): Promise<IosCredentials> {
if (this.options.skipCredentialsCheck) {
Log.log('Skipping credentials check');
} else {
await new CredentialsManager(this.ctx).runActionAsync(
new SetupBuildCredentials({
app: this.options.app,
distribution: this.options.distribution,
enterpriseProvisioning: this.options.enterpriseProvisioning,
})
);
}
const buildCredentials = await this.fetchRemoteAsync();
if (
!buildCredentials?.distributionCertificate?.certificateP12 ||
!buildCredentials.distributionCertificate?.certificatePassword
) {
if (this.options.skipCredentialsCheck) {
throw new Error(
'Distribution certificate is missing and credentials check was skipped. Run without --skip-credentials-check to set it up.'
);
} else {
throw new Error('Distribution certificate is missing');
}
}
if (!buildCredentials.provisioningProfile?.provisioningProfile) {
if (this.options.skipCredentialsCheck) {
throw new Error(
'Provisioning profile is missing and credentials check was skipped. Run without --skip-credentials-check to set it up.'
);
} else {
throw new Error('Provisioning profile is missing');
}
}
const manager = new CredentialsManager(this.ctx);
const { provisioningProfile, distributionCertificate } = await new SetupBuildCredentials({
app: this.options.app,
distribution: this.options.distribution,
enterpriseProvisioning: this.options.enterpriseProvisioning,
}).runAsync(manager, this.ctx);
return {
provisioningProfile: buildCredentials.provisioningProfile.provisioningProfile,
provisioningProfile,
distributionCertificate: {
certP12: buildCredentials.distributionCertificate.certificateP12,
certPassword: buildCredentials.distributionCertificate.certificatePassword,
certP12: distributionCertificate.certificateP12,
certPassword: distributionCertificate.certificatePassword,
},
};
}
private async fetchRemoteAsync(): Promise<IosAppBuildCredentialsFragment | null> {
const distributionType = resolveDistributionType(
this.options.distribution,
this.options.enterpriseProvisioning
);
return await getBuildCredentialsAsync(this.ctx, this.options.app, distributionType);
}
}
@@ -1,21 +1,43 @@
import { CredentialsSource } from '@expo/eas-json';
import { vol } from 'memfs';
import { IosAppBuildCredentialsFragment } from '../../../graphql/generated';
import { getAppstoreMock } from '../../__tests__/fixtures-appstore';
import { createCtxMock } from '../../__tests__/fixtures-context';
import { testIosAppCredentialsWithBuildCredentialsQueryResult } from '../../__tests__/fixtures-ios';
import { getNewIosApiMockWithoutCredentials } from '../../__tests__/fixtures-new-ios';
import {
getNewIosApiMockWithoutCredentials,
testIosAppCredentialsWithBuildCredentialsQueryResult,
} from '../../__tests__/fixtures-ios';
import IosCredentialsProvider from '../IosCredentialsProvider';
import { getAppLookupParamsFromContext } from '../actions/new/BuildCredentialsUtils';
import { getAppLookupParamsFromContext } from '../actions/BuildCredentialsUtils';
jest.mock('fs');
jest.mock('../validators/validateProvisioningProfile', () => ({
validateProvisioningProfileAsync: async (
_ctx: any,
_app: any,
buildCredentials: Partial<IosAppBuildCredentialsFragment> | null
): Promise<boolean> => {
return !!(
buildCredentials &&
buildCredentials.distributionCertificate &&
buildCredentials.provisioningProfile
);
},
}));
const originalConsoleLog = console.log;
const originalConsoleError = console.error;
const originalConsoleWarn = console.warn;
beforeAll(() => {
console.log = jest.fn();
console.error = jest.fn();
console.warn = jest.fn();
});
afterAll(() => {
console.log = originalConsoleLog;
console.error = originalConsoleError;
console.warn = originalConsoleWarn;
});
beforeEach(() => {
@@ -23,79 +45,14 @@ beforeEach(() => {
});
describe(IosCredentialsProvider, () => {
describe('#hasRemoteAsync', () => {
it('returns false when distribution === internal and there are local credentials', async () => {
vol.fromJSON(
{
'./credentials.json': JSON.stringify({
ios: {
provisioningProfilePath: './ios/certs/profile.mobileprovision',
distributionCertificate: {
path: './ios/certs/cert.p12',
password: 'cert-password',
},
},
}),
},
'/app'
);
const ctx = createCtxMock({
nonInteractive: false,
appStore: getAppstoreMock(),
projectDir: '/app',
});
const appLookupParams = getAppLookupParamsFromContext(ctx);
const provider = new IosCredentialsProvider(ctx, {
app: {
account: {
id: `id-${appLookupParams.account.name}`,
name: appLookupParams.account.name,
},
bundleIdentifier: appLookupParams.bundleIdentifier,
projectName: appLookupParams.projectName,
},
distribution: 'internal',
});
await expect(provider.hasRemoteAsync()).resolves.toBe(false);
});
it('returns true when there are remote credentials', async () => {
const ctx = createCtxMock({
nonInteractive: false,
appStore: getAppstoreMock(),
projectDir: '/app',
newIos: {
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(
() => testIosAppCredentialsWithBuildCredentialsQueryResult
),
},
});
const appLookupParams = getAppLookupParamsFromContext(ctx);
const provider = new IosCredentialsProvider(ctx, {
app: {
account: {
id: `id-${appLookupParams.account.name}`,
name: appLookupParams.account.name,
},
bundleIdentifier: appLookupParams.bundleIdentifier,
projectName: appLookupParams.projectName,
},
distribution: 'store',
});
await expect(provider.hasRemoteAsync()).resolves.toBe(true);
});
});
describe('#getCredentialsAsync', () => {
describe('remote credentials', () => {
it('throws an error is credentials do not exist', async () => {
const ctx = createCtxMock({
nonInteractive: false,
nonInteractive: true,
appStore: getAppstoreMock(),
projectDir: '/app',
newIos: {
ios: {
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(() => null),
},
@@ -111,22 +68,28 @@ describe(IosCredentialsProvider, () => {
projectName: appLookupParams.projectName,
},
distribution: 'store',
skipCredentialsCheck: true,
});
await expect(provider.getCredentialsAsync(CredentialsSource.REMOTE)).rejects.toThrowError();
await expect(provider.getCredentialsAsync(CredentialsSource.REMOTE)).rejects.toThrowError(
/Credentials are not set up/
);
});
it('returns credentials if they exist', async () => {
const ctx = createCtxMock({
nonInteractive: false,
nonInteractive: true,
appStore: getAppstoreMock(),
projectDir: '/app',
newIos: {
ios: {
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(
() => testIosAppCredentialsWithBuildCredentialsQueryResult
),
getDistributionCertificateForAppAsync: jest.fn(
() =>
testIosAppCredentialsWithBuildCredentialsQueryResult.iosAppBuildCredentialsList[0]
.distributionCertificate
),
},
});
const appLookupParams = getAppLookupParamsFromContext(ctx);
@@ -140,11 +103,10 @@ describe(IosCredentialsProvider, () => {
projectName: appLookupParams.projectName,
},
distribution: 'store',
skipCredentialsCheck: true,
});
const buildCredentials =
testIosAppCredentialsWithBuildCredentialsQueryResult.iosAppBuildCredentialsArray[0];
testIosAppCredentialsWithBuildCredentialsQueryResult.iosAppBuildCredentialsList[0];
await expect(provider.getCredentialsAsync(CredentialsSource.REMOTE)).resolves.toMatchObject(
{
distributionCertificate: {
@@ -1,6 +1,6 @@
import { AppleTeamFragment } from '../../../../graphql/generated';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
import { AppleTeamFragment } from '../../../graphql/generated';
import { Context } from '../../context';
import { AppLookupParams } from '../api/GraphqlClient';
export async function resolveAppleTeamIfAuthenticatedAsync(
ctx: Context,
@@ -9,7 +9,7 @@ export async function resolveAppleTeamIfAuthenticatedAsync(
if (!ctx.appStore.authCtx) {
return null;
}
return await ctx.newIos.createOrGetExistingAppleTeamAsync(app, {
return await ctx.ios.createOrGetExistingAppleTeamAsync(app.account, {
appleTeamIdentifier: ctx.appStore.authCtx.team.id,
appleTeamName: ctx.appStore.authCtx.team.name,
});
@@ -1,4 +1,3 @@
import { IosDistributionType, IosEnterpriseProvisioning } from '@expo/eas-json';
import nullthrows from 'nullthrows';
import {
@@ -7,28 +6,36 @@ import {
AppleTeamFragment,
IosDistributionType as GraphQLIosDistributionType,
IosAppBuildCredentialsFragment,
} from '../../../../graphql/generated';
import {
getProjectAccountName,
getProjectConfigDescription,
} from '../../../../project/projectUtils';
import { findAccountByName } from '../../../../user/Account';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
} from '../../../graphql/generated';
import { getProjectAccountName, getProjectConfigDescription } from '../../../project/projectUtils';
import { findAccountByName } from '../../../user/Account';
import { Context } from '../../context';
import { AppLookupParams } from '../api/GraphqlClient';
import { resolveAppleTeamIfAuthenticatedAsync } from './AppleTeamUtils';
export async function getAllBuildCredentialsAsync(
ctx: Context,
app: AppLookupParams
): Promise<IosAppBuildCredentialsFragment[]> {
const appCredentials = await ctx.ios.getIosAppCredentialsWithBuildCredentialsAsync(app, {});
if (!appCredentials) {
return [];
}
return appCredentials.iosAppBuildCredentialsList;
}
export async function getBuildCredentialsAsync(
ctx: Context,
app: AppLookupParams,
iosDistributionType: GraphQLIosDistributionType
): Promise<IosAppBuildCredentialsFragment | null> {
const appCredentials = await ctx.newIos.getIosAppCredentialsWithBuildCredentialsAsync(app, {
const appCredentials = await ctx.ios.getIosAppCredentialsWithBuildCredentialsAsync(app, {
iosDistributionType,
});
if (!appCredentials || appCredentials.iosAppBuildCredentialsArray.length === 0) {
if (!appCredentials || appCredentials.iosAppBuildCredentialsList.length === 0) {
return null;
}
const [buildCredentials] = appCredentials.iosAppBuildCredentialsArray;
const [buildCredentials] = appCredentials.iosAppBuildCredentialsList;
return buildCredentials;
}
@@ -61,11 +68,11 @@ export async function assignBuildCredentialsAsync(
const resolvedAppleTeam = nullthrows(
appleTeam ?? (await resolveAppleTeamIfAuthenticatedAsync(ctx, app))
);
const appleAppIdentifier = await ctx.newIos.createOrGetExistingAppleAppIdentifierAsync(
const appleAppIdentifier = await ctx.ios.createOrGetExistingAppleAppIdentifierAsync(
app,
resolvedAppleTeam
);
return await ctx.newIos.createOrUpdateIosAppBuildCredentialsAsync(app, {
return await ctx.ios.createOrUpdateIosAppBuildCredentialsAsync(app, {
appleTeam: resolvedAppleTeam,
appleAppIdentifierId: appleAppIdentifier.id,
appleDistributionCertificateId: distCert.id,
@@ -94,20 +101,3 @@ export function getAppLookupParamsFromContext(ctx: Context): AppLookupParams {
return { account, projectName, bundleIdentifier };
}
export function resolveDistributionType(
distribution: IosDistributionType,
enterpriseProvisioning?: IosEnterpriseProvisioning
): GraphQLIosDistributionType {
if (distribution === 'internal') {
if (enterpriseProvisioning === 'adhoc') {
return GraphQLIosDistributionType.AdHoc;
} else if (enterpriseProvisioning === 'universal') {
return GraphQLIosDistributionType.Enterprise;
} else {
return GraphQLIosDistributionType.AdHoc;
}
} else {
return GraphQLIosDistributionType.AppStore;
}
}
@@ -2,91 +2,109 @@ import assert from 'assert';
import chalk from 'chalk';
import ora from 'ora';
import Log from '../../../log';
import { Action, CredentialsManager } from '../../CredentialsManager';
import { Context } from '../../context';
import {
DistributionCertificate,
ProvisioningProfileStoreInfo,
} from '../appstore/Credentials.types';
import { AppLookupParams } from '../credentials';
import { selectProvisioningProfileFromAppleAsync } from './ProvisioningProfileUtils';
AppleDistributionCertificateFragment,
AppleProvisioningProfileFragment,
} from '../../../graphql/generated';
import Log from '../../../log';
import { Context } from '../../context';
import { AppLookupParams } from '../api/GraphqlClient';
import { AppleProvisioningProfileMutationResult } from '../api/graphql/mutations/AppleProvisioningProfileMutation';
import { ProvisioningProfileStoreInfo } from '../appstore/Credentials.types';
import { AuthCtx } from '../appstore/authenticate';
import { MissingCredentialsNonInteractiveError } from '../errors';
export class UseExistingProvisioningProfile implements Action {
constructor(private app: AppLookupParams) {}
export class ConfigureProvisioningProfile {
constructor(
private app: AppLookupParams,
private distributionCertificate: AppleDistributionCertificateFragment,
private originalProvisioningProfile: AppleProvisioningProfileFragment
) {}
public async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
const selected = await selectProvisioningProfileFromAppleAsync(ctx, this.app.bundleIdentifier);
if (selected) {
const distCert = await ctx.ios.getDistributionCertificateAsync(this.app);
assert(distCert, 'missing distribution certificate');
await manager.runActionAsync(new ConfigureProvisioningProfile(this.app));
}
}
}
export class ConfigureProvisioningProfile implements Action {
constructor(private app: AppLookupParams) {}
public async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
const profile = await ctx.ios.getProvisioningProfileAsync(this.app);
if (!profile) {
throw new Error('No provisioning profile to configure');
}
if (!profile.provisioningProfileId) {
Log.warn("The provisioning profile we have on file cannot be validated on Apple's servers.");
return;
}
if (ctx.appStore.authCtx) {
const distCert = await ctx.ios.getDistributionCertificateAsync(this.app);
if (!distCert) {
Log.warn('There is no distribution certificate for this app.');
return;
}
const profilesFromApple = await ctx.appStore.listProvisioningProfilesAsync(
this.app.bundleIdentifier
public async runAsync(ctx: Context): Promise<AppleProvisioningProfileMutationResult | null> {
if (ctx.nonInteractive) {
throw new MissingCredentialsNonInteractiveError(
'Configuring Provisioning Profiles is only supported in interactive mode.'
);
const profilesWithMatchingId = profilesFromApple.filter(
appleInfo => appleInfo.provisioningProfileId === profile.provisioningProfileId
);
if (!profilesWithMatchingId || profilesWithMatchingId.length < 1) {
Log.warn('This profile is no longer valid on Apple Developer Portal.');
}
}
const { developerPortalIdentifier, provisioningProfile } = this.originalProvisioningProfile;
if (!developerPortalIdentifier && !provisioningProfile) {
Log.warn("The provisioning profile we have on file cannot be configured on Apple's servers.");
return null;
}
await this.configureAndUpdateAsync(ctx, this.app, distCert, profilesWithMatchingId[0]);
} else {
if (!ctx.appStore.authCtx) {
Log.warn(
"Without access to your Apple account we can't configure provisioning profiles for you."
);
Log.warn('Make sure to recreate the profile if you selected a new distribution certificate.');
return null;
}
const profilesFromApple = await ctx.appStore.listProvisioningProfilesAsync(
this.app.bundleIdentifier
);
const [matchingProfile] = profilesFromApple.filter(appleInfo =>
developerPortalIdentifier
? appleInfo.provisioningProfileId === developerPortalIdentifier
: appleInfo.provisioningProfile === provisioningProfile
);
if (!matchingProfile) {
Log.warn(
`Profile ${
developerPortalIdentifier ? `${developerPortalIdentifier} ` : ''
}not found on Apple Developer Portal.`
);
return null;
}
return await this.configureAndUpdateAsync(ctx, ctx.appStore.authCtx, this.app, matchingProfile);
}
private async configureAndUpdateAsync(
ctx: Context,
authCtx: AuthCtx,
app: AppLookupParams,
distCert: DistributionCertificate,
profileFromApple: ProvisioningProfileStoreInfo
) {
): Promise<AppleProvisioningProfileMutationResult> {
const {
developerPortalIdentifier,
certificateP12,
certificatePassword,
serialNumber,
} = this.distributionCertificate;
assert(
certificateP12 && certificatePassword,
'Distribution Certificate P12 and Password is required'
);
// configure profile on Apple's Server to use our distCert
const updatedProfile = await ctx.appStore.useExistingProvisioningProfileAsync(
app.bundleIdentifier,
profileFromApple,
distCert
{
certId: developerPortalIdentifier ?? undefined,
certP12: certificateP12,
certPassword: certificatePassword,
distCertSerialNumber: serialNumber,
teamId: authCtx.appleId,
}
);
const bundleIdTag = `(${app.bundleIdentifier})`;
const slugTag = `@${app.accountName}/${app.projectName}`;
const slugTag = `@${app.account.name}/${app.projectName}`;
const projectTag = `${chalk.bold(slugTag)} ${chalk.dim(bundleIdTag)}`;
const spinner = ora(`Updating Expo profile for ${projectTag}`).start();
try {
// Update profile on EAS servers
await ctx.ios.updateProvisioningProfileAsync(app, updatedProfile);
const configuredProvisioningProfile = await ctx.ios.updateProvisioningProfileAsync(
this.originalProvisioningProfile.id,
{
appleProvisioningProfile: updatedProfile.provisioningProfile,
developerPortalIdentifier: updatedProfile.provisioningProfileId,
}
);
spinner.succeed(`Updated Expo profile for ${projectTag}`);
return configuredProvisioningProfile;
} catch (error) {
spinner.fail();
throw error;
@@ -1,41 +1,16 @@
import assert from 'assert';
import Log from '../../../log';
import { Action, CredentialsManager } from '../../CredentialsManager';
import { Account } from '../../../user/Account';
import { Context } from '../../context';
import { IosDistCredentials } from '../credentials';
import { displayIosUserCredentials } from '../utils/printCredentials';
import { AppleDistributionCertificateMutationResult } from '../api/graphql/mutations/AppleDistributionCertificateMutation';
import { provideOrGenerateDistributionCertificateAsync } from './DistributionCertificateUtils';
export class CreateDistributionCertificateStandaloneManager implements Action {
constructor(private accountName: string) {}
export class CreateDistributionCertificate {
constructor(private account: Account) {}
public async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
const action = new CreateDistributionCertificate(this.accountName);
await manager.runActionAsync(action);
Log.newLine();
displayIosUserCredentials(action.distCredentials);
Log.newLine();
}
}
export class CreateDistributionCertificate implements Action {
private _distCredentials?: IosDistCredentials;
constructor(private accountName: string) {}
public get distCredentials(): IosDistCredentials {
assert(this._distCredentials, 'distCredentials can be accessed only after runAsync');
return this._distCredentials;
}
public async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
const distCert = await provideOrGenerateDistributionCertificateAsync(ctx, this.accountName);
this._distCredentials = await ctx.ios.createDistributionCertificateAsync(
this.accountName,
distCert
);
public async runAsync(ctx: Context): Promise<AppleDistributionCertificateMutationResult> {
const distCert = await provideOrGenerateDistributionCertificateAsync(ctx, this.account.name);
const result = await ctx.ios.createDistributionCertificateAsync(this.account, distCert);
Log.succeed('Created distribution certificate');
return result;
}
}
@@ -1,18 +1,18 @@
import assert from 'assert';
import nullthrows from 'nullthrows';
import { AppleDistributionCertificateFragment } from '../../../../graphql/generated';
import Log from '../../../../log';
import { Context } from '../../../context';
import { askForUserProvidedAsync } from '../../../utils/promptForCredentials';
import { AppLookupParams } from '../../api/GraphqlClient';
import { AppleProvisioningProfileMutationResult } from '../../api/graphql/mutations/AppleProvisioningProfileMutation';
import { ProvisioningProfile } from '../../appstore/Credentials.types';
import { AuthCtx } from '../../appstore/authenticate';
import { provisioningProfileSchema } from '../../credentials';
import { MissingCredentialsNonInteractiveError } from '../../errors';
import { generateProvisioningProfileAsync } from '../ProvisioningProfileUtils';
import { AppleDistributionCertificateFragment } from '../../../graphql/generated';
import Log from '../../../log';
import { Context } from '../../context';
import { askForUserProvidedAsync } from '../../utils/promptForCredentials';
import { AppLookupParams } from '../api/GraphqlClient';
import { AppleProvisioningProfileMutationResult } from '../api/graphql/mutations/AppleProvisioningProfileMutation';
import { ProvisioningProfile } from '../appstore/Credentials.types';
import { AuthCtx } from '../appstore/authenticate';
import { provisioningProfileSchema } from '../credentials';
import { MissingCredentialsNonInteractiveError } from '../errors';
import { resolveAppleTeamIfAuthenticatedAsync } from './AppleTeamUtils';
import { generateProvisioningProfileAsync } from './ProvisioningProfileUtils';
export class CreateProvisioningProfile {
constructor(
@@ -29,11 +29,11 @@ export class CreateProvisioningProfile {
const appleAuthCtx = await ctx.appStore.ensureAuthenticatedAsync();
const provisioningProfile = await this.provideOrGenerateAsync(ctx, appleAuthCtx);
const appleTeam = nullthrows(await resolveAppleTeamIfAuthenticatedAsync(ctx, this.app));
const appleAppIdentifier = await ctx.newIos.createOrGetExistingAppleAppIdentifierAsync(
const appleAppIdentifier = await ctx.ios.createOrGetExistingAppleAppIdentifierAsync(
this.app,
appleTeam
);
const provisioningProfileMutationResult = await ctx.newIos.createProvisioningProfileAsync(
const provisioningProfileMutationResult = await ctx.ios.createProvisioningProfileAsync(
this.app,
appleAppIdentifier,
{
@@ -1,14 +1,13 @@
import { AppleDevice } from '../../../../graphql/generated';
import { APPLE_DEVICE_CLASS_LABELS } from '../../../../graphql/types/credentials/AppleDevice';
import { promptAsync } from '../../.././../prompts';
import { AppleDeviceFragmentWithAppleTeam } from '../../api/graphql/queries/AppleDeviceQuery';
import { AppleDevice, AppleDeviceFragment } from '../../../graphql/generated';
import { APPLE_DEVICE_CLASS_LABELS } from '../../../graphql/types/credentials/AppleDevice';
import { promptAsync } from '../.././../prompts';
export async function chooseDevices(
allDevices: AppleDeviceFragmentWithAppleTeam[],
allDevices: AppleDeviceFragment[],
preselectedDeviceIdentifiers: string[] = []
): Promise<AppleDevice[]> {
const preselectedDeviceIdentifierSet = new Set(preselectedDeviceIdentifiers);
const isSelected = (device: AppleDeviceFragmentWithAppleTeam) =>
const isSelected = (device: AppleDeviceFragment) =>
preselectedDeviceIdentifierSet.size === 0 ||
preselectedDeviceIdentifierSet.has(device.identifier);
const { devices } = await promptAsync({
@@ -27,12 +26,12 @@ export async function chooseDevices(
return devices;
}
function formatDeviceLabel(device: AppleDeviceFragmentWithAppleTeam): string {
export function formatDeviceLabel(device: AppleDeviceFragment): string {
const deviceDetails = formatDeviceDetails(device);
return `${device.name ?? device.identifier}${deviceDetails !== '' ? ` ${deviceDetails}` : ''}`;
}
function formatDeviceDetails(device: AppleDeviceFragmentWithAppleTeam): string {
function formatDeviceDetails(device: AppleDeviceFragment): string {
let details = '';
if (device.deviceClass) {
details += APPLE_DEVICE_CLASS_LABELS[device.deviceClass];
@@ -1,26 +1,154 @@
import assert from 'assert';
import chalk from 'chalk';
import dateformat from 'dateformat';
import {
AppleDistributionCertificateFragment,
AppleTeamFragment,
} from '../../../graphql/generated';
import Log, { learnMore } from '../../../log';
import { promptAsync } from '../../../prompts';
import { Account } from '../../../user/Account';
import { fromNow } from '../../../utils/date';
import { Context } from '../../context';
import { askForUserProvidedAsync } from '../../utils/promptForCredentials';
import { AppLookupParams } from '../api/GraphqlClient';
import { AppleTooManyCertsError } from '../appstore/AppStoreApi';
import {
DistributionCertificate,
DistributionCertificateStoreInfo,
} from '../appstore/Credentials.types';
import {
filterRevokedDistributionCerts,
sortCertificatesByExpiryDesc,
} from '../appstore/CredentialsUtils';
import {
IosAppCredentials,
IosDistCredentials,
distributionCertificateSchema,
} from '../credentials';
import { findP12CertSerialNumber } from '../utils/p12Certificate';
import { filterRevokedDistributionCertsFromEasServers } from '../appstore/CredentialsUtils';
import { distributionCertificateSchema } from '../credentials';
import { validateDistributionCertificateAsync } from '../validators/validateDistributionCertificate';
export function formatDistributionCertificate(
distributionCertificate: AppleDistributionCertificateFragment,
validSerialNumbers?: string[]
): string {
const {
serialNumber,
developerPortalIdentifier,
appleTeam,
validityNotBefore,
validityNotAfter,
updatedAt,
} = distributionCertificate;
let line: string = '';
if (developerPortalIdentifier) {
line += `Cert ID: ${developerPortalIdentifier}`;
}
line += `${line === '' ? '' : ', '}Serial number: ${serialNumber}${
appleTeam ? `, ${formatAppleTeam(appleTeam)}` : ''
}`;
line += chalk.gray(
`\n Created: ${fromNow(new Date(validityNotBefore))} ago, Updated: ${fromNow(
new Date(updatedAt)
)} ago,`
);
line += chalk.gray(`\n Expires: ${dateformat(validityNotAfter, 'expiresHeaderFormat')}`);
const apps = distributionCertificate.iosAppBuildCredentialsList.map(
buildCredentials => buildCredentials.iosAppCredentials.app
);
if (apps.length) {
const appFullNames = apps.map(app => app.fullName).join(',');
line += chalk.gray(`\n 📲 Used by: ${appFullNames}`);
}
if (validSerialNumbers?.includes(serialNumber)) {
line += chalk.gray("\n ✅ Currently valid on Apple's servers.");
} else {
line += '';
}
return line;
}
function formatAppleTeam({ appleTeamIdentifier, appleTeamName }: AppleTeamFragment): string {
return `Team ID: ${appleTeamIdentifier}${appleTeamName ? `, Team name: ${appleTeamName}` : ''}`;
}
async function _selectDistributionCertificateAsync(
distCerts: AppleDistributionCertificateFragment[],
validDistributionCertificates?: AppleDistributionCertificateFragment[]
): Promise<AppleDistributionCertificateFragment | null> {
const validDistCertSerialNumbers = validDistributionCertificates?.map(
distCert => distCert.serialNumber
);
const { chosenDistCert } = await promptAsync({
type: 'select',
name: 'chosenDistCert',
message: 'Select certificate from the list.',
choices: distCerts.map(distCert => ({
title: formatDistributionCertificate(distCert, validDistCertSerialNumbers),
value: distCert,
})),
});
return chosenDistCert;
}
/**
* select a distribution certificate from an account (validity status shown on a best effort basis)
* */
export async function selectDistributionCertificateWithDependenciesAsync(
ctx: Context,
account: Account
): Promise<AppleDistributionCertificateFragment | null> {
const distCertsForAccount = await ctx.ios.getDistributionCertificatesForAccountAsync(account);
if (distCertsForAccount.length === 0) {
Log.warn(`There are no Distribution Certificates available in your EAS account.`);
return null;
}
if (!ctx.appStore.authCtx) {
return _selectDistributionCertificateAsync(distCertsForAccount);
}
// get valid certs on the developer portal
const certInfoFromApple = await ctx.appStore.listDistributionCertificatesAsync();
const validDistCerts = await filterRevokedDistributionCertsFromEasServers(
distCertsForAccount,
certInfoFromApple
);
return _selectDistributionCertificateAsync(distCertsForAccount, validDistCerts);
}
/**
* select a distribution certificate from a valid set (curated on a best effort basis)
* */
export async function selectValidDistributionCertificateAsync(
ctx: Context,
appLookupParams: AppLookupParams
): Promise<AppleDistributionCertificateFragment | null> {
const distCertsForAccount = await ctx.ios.getDistributionCertificatesForAccountAsync(
appLookupParams.account
);
if (distCertsForAccount.length === 0) {
Log.warn(`There are no Distribution Certificates available in your EAS account.`);
return null;
}
if (!ctx.appStore.authCtx) {
return _selectDistributionCertificateAsync(distCertsForAccount);
}
// filter by apple team
assert(ctx.appStore.authCtx, 'authentication to the Apple App Store is required');
const appleTeamIdentifier = ctx.appStore.authCtx.team.id;
const distCertsForAppleTeam = distCertsForAccount.filter(distCert => {
return !distCert.appleTeam || distCert.appleTeam.appleTeamIdentifier === appleTeamIdentifier;
});
// filter by valid certs on the developer portal
const certInfoFromApple = await ctx.appStore.listDistributionCertificatesAsync();
const validDistCerts = await filterRevokedDistributionCertsFromEasServers(
distCertsForAppleTeam,
certInfoFromApple
);
Log.log(
`${validDistCerts.length}/${distCertsForAccount.length} Distribution Certificates are currently valid for Apple Team ${ctx.appStore.authCtx?.team.id}.`
);
return _selectDistributionCertificateAsync(validDistCerts);
}
const APPLE_DIST_CERTS_TOO_MANY_GENERATED_ERROR = `
You can have only ${chalk.underline(
'three'
@@ -125,100 +253,6 @@ async function generateDistributionCertificateAsync(
return await generateDistributionCertificateAsync(ctx, accountName);
}
interface SelectOptions {
filterInvalid?: boolean;
}
type ValidityStatus = 'UNKNOWN' | 'VALID' | 'INVALID';
export async function selectDistributionCertificateAsync(
ctx: Context,
accountName: string,
options: SelectOptions = {}
): Promise<IosDistCredentials | null> {
const credentials = await ctx.ios.getAllCredentialsAsync(accountName);
let distCredentials = credentials.userCredentials.filter(
(cred): cred is IosDistCredentials => cred.type === 'dist-cert'
);
let validDistCredentials: IosDistCredentials[] | null = null;
if (ctx.appStore.authCtx) {
const certInfoFromApple = await ctx.appStore.listDistributionCertificatesAsync();
validDistCredentials = filterRevokedDistributionCerts(distCredentials, certInfoFromApple);
}
distCredentials =
options.filterInvalid && validDistCredentials ? validDistCredentials : distCredentials;
if (distCredentials.length === 0) {
Log.warn('There are no Distribution Certificates available in your Expo account.');
return null;
}
const format = (distCredentials: IosDistCredentials): string => {
const usedByApps = credentials.appCredentials.filter(
cred => cred.distCredentialsId === distCredentials.id
);
let validityStatus: ValidityStatus;
if (!validDistCredentials) {
validityStatus = 'UNKNOWN';
} else if (validDistCredentials.includes(distCredentials)) {
validityStatus = 'VALID';
} else {
validityStatus = 'INVALID';
}
return formatDistributionCertificate(distCredentials, usedByApps, validityStatus);
};
const { credentialsIndex } = await promptAsync({
type: 'select',
name: 'credentialsIndex',
message: 'Select certificate from the list.',
choices: distCredentials.map((entry, index) => ({
title: format(entry),
value: index,
})),
});
return distCredentials[credentialsIndex];
}
export function formatDistributionCertificate(
distributionCertificate: IosDistCredentials,
usedByApps: IosAppCredentials[],
validityStatus: ValidityStatus = 'UNKNOWN'
): string {
const joinApps = usedByApps.map(i => `${i.experienceName} (${i.bundleIdentifier})`).join(', ');
const usedByString = joinApps
? `\n ${chalk.gray(`used by ${joinApps}`)}`
: `\n ${chalk.gray(`not used by any apps`)}`;
let serialNumber = distributionCertificate.distCertSerialNumber;
try {
if (!serialNumber) {
serialNumber = findP12CertSerialNumber(
distributionCertificate.certP12,
distributionCertificate.certPassword
);
}
} catch (error) {
serialNumber = chalk.red('invalid serial number');
}
let validityText;
if (validityStatus === 'VALID') {
validityText = chalk.gray("\n ✅ Currently valid on Apple's servers.");
} else if (validityStatus === 'INVALID') {
validityText = chalk.gray("\n ❌ No longer valid on Apple's servers.");
} else {
validityText = chalk.gray(
"\n ❓ Validity of this certificate on Apple's servers is unknown."
);
}
return `Distribution Certificate (Cert ID: ${
distributionCertificate.certId || '-----'
}, Serial number: ${serialNumber}, Team ID: ${
distributionCertificate.teamId
})${usedByString}${validityText}`;
}
function formatDistributionCertificateFromApple(
appleInfo: DistributionCertificateStoreInfo
): string {
@@ -228,20 +262,3 @@ function formatDistributionCertificateFromApple(
return `${name} (${status}) - Cert ID: ${id}, Serial number: ${serialNumber}, Team ID: ${appleInfo.ownerId}, Team name: ${ownerName}
expires: ${expiresDate}, created: ${createdDate}`;
}
export async function getValidDistCertsAsync(
ctx: Context,
accountName: string
): Promise<IosDistCredentials[]> {
const credentials = await ctx.ios.getAllCredentialsAsync(accountName);
const distCredentials = credentials.userCredentials.filter(
(cred): cred is IosDistCredentials => cred.type === 'dist-cert'
);
if (!ctx.appStore.authCtx) {
Log.log(chalk.yellow(`Unable to determine validity of Distribution Certificates.`));
return distCredentials;
}
const certInfoFromApple = await ctx.appStore.listDistributionCertificatesAsync();
const validCerts = await filterRevokedDistributionCerts(distCredentials, certInfoFromApple);
return sortCertificatesByExpiryDesc(certInfoFromApple, validCerts);
}
@@ -1,38 +1,11 @@
import chalk from 'chalk';
import Log from '../../../log';
import { promptAsync } from '../../../prompts';
import { Context } from '../../context';
import {
DistributionCertificate,
ProvisioningProfile,
ProvisioningProfileStoreInfo,
} from '../appstore/Credentials.types';
import { IosAppCredentials } from '../credentials';
export async function selectProvisioningProfileFromAppleAsync(
ctx: Context,
bundleIdentifier: string
): Promise<ProvisioningProfileStoreInfo | null> {
const profiles = await ctx.appStore.listProvisioningProfilesAsync(bundleIdentifier);
if (profiles.length === 0) {
Log.warn(
`There are no provisioning profiles available on Apple Developer Portal for bundle identifier ${bundleIdentifier}.`
);
return null;
}
const { credentialsIndex } = await promptAsync({
type: 'select',
name: 'credentialsIndex',
message: 'Select provisioning profile from the list.',
choices: profiles.map((entry, index) => ({
title: formatProvisioningProfileFromApple(entry),
value: index,
})),
});
return profiles[credentialsIndex];
}
export function formatProvisioningProfileFromApple(
appleInfo: ProvisioningProfileStoreInfo
@@ -45,36 +18,6 @@ export function formatProvisioningProfileFromApple(
return `Provisioning Profile - ID: ${id}${details}`;
}
export async function selectProvisioningProfileFromExpoAsync(
ctx: Context,
accountName: string
): Promise<IosAppCredentials | null> {
const profiles = (await ctx.ios.getAllCredentialsAsync(accountName)).appCredentials.filter(
({ credentials }) => !!credentials.provisioningProfile && !!credentials.provisioningProfileId
);
if (profiles.length === 0) {
Log.warn('There are no provisioning profiles available in your Expo account.');
return null;
}
const format = (profile: IosAppCredentials) => {
const id = chalk.green(profile.credentials.provisioningProfileId || '-----');
const teamId = profile.credentials.teamId || '------';
return `Provisioning Profile (ID: ${id}, Team ID: ${teamId})`;
};
const { credentialsIndex } = await promptAsync({
type: 'select',
name: 'credentialsIndex',
message: 'Select provisioning profile from the list.',
choices: profiles.map((entry, index) => ({
title: format(entry),
value: index,
})),
});
return profiles[credentialsIndex];
}
export async function generateProvisioningProfileAsync(
ctx: Context,
bundleIdentifier: string,
@@ -1,57 +1,47 @@
import chalk from 'chalk';
import {
AppleDistributionCertificateFragment,
AppleProvisioningProfileIdentifiersFragment,
} from '../../../graphql/generated';
import Log from '../../../log';
import { confirmAsync } from '../../../prompts';
import { Action, CredentialsManager } from '../../CredentialsManager';
import { Account } from '../../../user/Account';
import { Context } from '../../context';
import { IosAppCredentials, getAppLookupParams } from '../credentials';
import { selectDistributionCertificateAsync } from './DistributionCertificateUtils';
import { RemoveSpecificProvisioningProfile } from './RemoveProvisioningProfile';
import { AppLookupParams } from '../api/GraphqlClient';
import { selectDistributionCertificateWithDependenciesAsync } from './DistributionCertificateUtils';
import { RemoveProvisioningProfiles } from './RemoveProvisioningProfile';
interface RemoveOptions {
shouldRevoke?: boolean;
}
export class SelectAndRemoveDistributionCertificate {
constructor(private account: Account) {}
export class RemoveDistributionCertificate implements Action {
constructor(private accountName: string, private options: RemoveOptions = {}) {}
async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
const selected = await selectDistributionCertificateAsync(ctx, this.accountName);
if (selected?.id) {
await manager.runActionAsync(
new RemoveSpecificDistributionCertificate(selected?.id, this.accountName, this.options)
);
async runAsync(ctx: Context): Promise<void> {
const selected = await selectDistributionCertificateWithDependenciesAsync(ctx, this.account);
if (selected) {
await new RemoveDistributionCertificate(this.account, selected).runAsync(ctx);
Log.succeed('Removed distribution certificate');
Log.newLine();
}
}
}
interface RemoveSpecificOptions {
shouldRevoke?: boolean;
}
export class RemoveSpecificDistributionCertificate implements Action {
export class RemoveDistributionCertificate {
constructor(
private userCredentialsId: number | string,
private accountName: string,
private options: RemoveSpecificOptions = {}
private account: Account,
private distributionCertificate: AppleDistributionCertificateFragment
) {}
public async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
const distributionCertificate = await ctx.ios.getDistributionCertificateByIdAsync(
this.userCredentialsId,
this.accountName
public async runAsync(ctx: Context): Promise<void> {
const apps = this.distributionCertificate.iosAppBuildCredentialsList.map(
buildCredentials => buildCredentials.iosAppCredentials.app
);
const credentials = await ctx.ios.getAllCredentialsAsync(this.accountName);
const apps = credentials.appCredentials.filter(
cred => cred.distCredentialsId === this.userCredentialsId
);
const appList = apps.map(appCred => chalk.green(appCred.experienceName)).join(', ');
if (appList && !ctx.nonInteractive) {
if (apps.length !== 0) {
const appFullNames = apps.map(app => app.fullName).join(',');
if (ctx.nonInteractive) {
throw new Error(
`Certificate is currently used by ${appFullNames} and cannot be deleted in non-interactive mode.`
);
}
const confirm = await confirmAsync({
message: `You are removing certificate used by ${appList}. Do you want to continue?`,
message: `You are removing certificate used by ${appFullNames}. Do you want to continue?`,
});
if (!confirm) {
Log.log('Aborting');
@@ -60,43 +50,41 @@ export class RemoveSpecificDistributionCertificate implements Action {
}
Log.log('Removing Distribution Certificate');
await ctx.ios.deleteDistributionCertificateAsync(this.userCredentialsId, this.accountName);
await ctx.ios.deleteDistributionCertificateAsync(this.distributionCertificate.id);
let shouldRevoke = this.options.shouldRevoke;
if (distributionCertificate.certId) {
if (!shouldRevoke && !ctx.nonInteractive) {
if (this.distributionCertificate.developerPortalIdentifier) {
let shouldRevoke = false;
if (!ctx.nonInteractive) {
shouldRevoke = await confirmAsync({
message: `Do you also want to revoke this Distribution Certificate on Apple Developer Portal?`,
});
} else if (ctx.nonInteractive) {
Log.log('Skipping certificate revocation on the Apple Developer Portal.');
}
if (shouldRevoke) {
await ctx.appStore.revokeDistributionCertificateAsync([distributionCertificate.certId]);
await ctx.appStore.revokeDistributionCertificateAsync([
this.distributionCertificate.developerPortalIdentifier,
]);
}
}
await this.removeInvalidProvisioningProfilesAsync(manager, ctx, apps, shouldRevoke);
await this.removeInvalidProvisioningProfilesAsync(ctx);
}
private async removeInvalidProvisioningProfilesAsync(
manager: CredentialsManager,
ctx: Context,
apps: IosAppCredentials[],
shouldRevoke?: boolean
) {
for (const appCredentials of apps) {
const appLookupParams = getAppLookupParams(
appCredentials.experienceName,
appCredentials.bundleIdentifier
);
if (!(await ctx.ios.getProvisioningProfileAsync(appLookupParams))) {
continue;
private async removeInvalidProvisioningProfilesAsync(ctx: Context): Promise<void> {
const buildCredentialsList = this.distributionCertificate.iosAppBuildCredentialsList;
const appsWithProfilesToRemove: AppLookupParams[] = [];
const profilesToRemove: AppleProvisioningProfileIdentifiersFragment[] = [];
for (const buildCredentials of buildCredentialsList) {
const projectName = buildCredentials.iosAppCredentials.app.slug;
const { bundleIdentifier } = buildCredentials.iosAppCredentials.appleAppIdentifier;
const appLookupParams = { account: this.account, projectName, bundleIdentifier };
const maybeProvisioningProfile = buildCredentials.provisioningProfile;
if (maybeProvisioningProfile) {
appsWithProfilesToRemove.push(appLookupParams);
profilesToRemove.push(maybeProvisioningProfile);
}
Log.log(
`Removing Provisioning Profile for ${appCredentials.experienceName} (${appCredentials.bundleIdentifier})`
);
await manager.runActionAsync(
new RemoveSpecificProvisioningProfile(appLookupParams, { shouldRevoke })
);
}
await new RemoveProvisioningProfiles(appsWithProfilesToRemove, profilesToRemove).runAsync(ctx);
}
}
@@ -1,48 +1,32 @@
import { assert } from '@expo/config';
import { AppleProvisioningProfileIdentifiersFragment } from '../../../graphql/generated';
import Log from '../../../log';
import { confirmAsync } from '../../../prompts';
import { Action, CredentialsManager } from '../../CredentialsManager';
import { Context } from '../../context';
import { AppLookupParams, getAppLookupParams } from '../credentials';
import { selectProvisioningProfileFromExpoAsync } from './ProvisioningProfileUtils';
import { AppLookupParams } from '../api/GraphqlClient';
interface RemoveOptions {
shouldRevoke?: boolean;
}
export class RemoveProvisioningProfile implements Action {
constructor(private accountName: string, private options: RemoveOptions = {}) {}
async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
const selected = await selectProvisioningProfileFromExpoAsync(ctx, this.accountName);
if (selected) {
const app = getAppLookupParams(selected.experienceName, selected.bundleIdentifier);
await manager.runActionAsync(new RemoveSpecificProvisioningProfile(app, this.options));
}
}
}
interface RemoveSpecificOptions {
shouldRevoke?: boolean;
}
export class RemoveSpecificProvisioningProfile implements Action {
constructor(private app: AppLookupParams, private options: RemoveSpecificOptions = {}) {}
async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
await ctx.ios.deleteProvisioningProfileAsync(this.app);
Log.succeed(
`Removed provisioning profile for @${this.app.accountName}/${this.app.projectName} (${this.app.bundleIdentifier})`
export class RemoveProvisioningProfiles {
constructor(
private apps: AppLookupParams[],
private provisioningProfiles: AppleProvisioningProfileIdentifiersFragment[]
) {
assert(
apps.length === provisioningProfiles.length,
'apps must correspond to the provisioning profiles being removed'
);
}
let { shouldRevoke } = this.options;
if (!shouldRevoke && !ctx.nonInteractive) {
shouldRevoke = await confirmAsync({
message: 'Do you also want to revoke this provisioning profile on Apple Developer Portal?',
});
}
if (shouldRevoke) {
await ctx.appStore.revokeProvisioningProfileAsync(this.app.bundleIdentifier);
async runAsync(ctx: Context): Promise<void> {
if (this.provisioningProfiles.length === 0) {
Log.log(`Skipping deletion of Provisioning Profiles`);
return;
}
await ctx.ios.deleteProvisioningProfilesAsync(
this.provisioningProfiles.map(profile => profile.id)
);
const appAndBundles = this.apps
.map(app => `@${app.account.name}/${app.projectName} (${app.bundleIdentifier})`)
.join(',');
Log.succeed(`Successfully removed provisioning profiles for ${appAndBundles}`);
}
}
@@ -0,0 +1,234 @@
import assert from 'assert';
import chalk from 'chalk';
import differenceBy from 'lodash/differenceBy';
import isEqual from 'lodash/isEqual';
import nullthrows from 'nullthrows';
import DeviceCreateAction, { RegistrationMethod } from '../../../devices/actions/create/action';
import {
AppleDeviceFragment,
AppleDistributionCertificateFragment,
AppleProvisioningProfileFragment,
AppleTeamFragment,
IosAppBuildCredentialsFragment,
IosDistributionType,
} from '../../../graphql/generated';
import Log from '../../../log';
import { confirmAsync, pressAnyKeyToContinueAsync } from '../../../prompts';
import { Context } from '../../context';
import { AppLookupParams } from '../api/GraphqlClient';
import { MissingCredentialsNonInteractiveError } from '../errors';
import { validateProvisioningProfileAsync } from '../validators/validateProvisioningProfile';
import { resolveAppleTeamIfAuthenticatedAsync } from './AppleTeamUtils';
import { assignBuildCredentialsAsync, getBuildCredentialsAsync } from './BuildCredentialsUtils';
import { chooseDevices, formatDeviceLabel } from './DeviceUtils';
import { SetupDistributionCertificate } from './SetupDistributionCertificate';
export class SetupAdhocProvisioningProfile {
constructor(private app: AppLookupParams) {}
async runAsync(ctx: Context): Promise<IosAppBuildCredentialsFragment> {
const distCert = await new SetupDistributionCertificate(
this.app,
IosDistributionType.AdHoc
).runAsync(ctx);
const areBuildCredentialsSetup = await this.areBuildCredentialsSetupAsync(ctx);
if (ctx.nonInteractive) {
if (areBuildCredentialsSetup) {
return nullthrows(await getBuildCredentialsAsync(ctx, this.app, IosDistributionType.AdHoc));
} else {
throw new MissingCredentialsNonInteractiveError(
'Provisioning profile is not configured correctly. Please run this command again in interactive mode.'
);
}
}
const currentBuildCredentials = await getBuildCredentialsAsync(
ctx,
this.app,
IosDistributionType.AdHoc
);
if (areBuildCredentialsSetup) {
const buildCredentials = nullthrows(currentBuildCredentials);
if (await this.shouldUseExistingProfileAsync(ctx, buildCredentials)) {
return buildCredentials;
}
}
return await this.runWithDistributionCertificateAsync(ctx, distCert);
}
async runWithDistributionCertificateAsync(
ctx: Context,
distCert: AppleDistributionCertificateFragment
): Promise<IosAppBuildCredentialsFragment> {
const currentBuildCredentials = await getBuildCredentialsAsync(
ctx,
this.app,
IosDistributionType.AdHoc
);
// 1. Resolve Apple Team
let appleTeam: AppleTeamFragment | null =
distCert.appleTeam ?? currentBuildCredentials?.provisioningProfile?.appleTeam ?? null;
if (!appleTeam) {
await ctx.appStore.ensureAuthenticatedAsync();
appleTeam = await resolveAppleTeamIfAuthenticatedAsync(ctx, this.app);
}
assert(appleTeam, 'Apple Team must be defined here');
// 2. Fetch devices registered on EAS servers
let registeredAppleDevices = await ctx.ios.getDevicesForAppleTeamAsync(this.app, appleTeam);
if (registeredAppleDevices.length === 0) {
const shouldRegisterDevices = await confirmAsync({
message: `You don't have any registered devices yet. Would you like to register them now?`,
initial: true,
});
if (shouldRegisterDevices) {
registeredAppleDevices = await this.registerDevicesAsync(ctx, appleTeam);
} else {
throw new Error(`Run 'eas device:create' to register your devices first`);
}
}
// 3. Choose devices for internal distribution
const provisionedDeviceIdentifiers = (
currentBuildCredentials?.provisioningProfile?.appleDevices ?? []
).map(i => i.identifier);
const chosenDevices = await chooseDevices(registeredAppleDevices, provisionedDeviceIdentifiers);
// 4. Reuse or create the profile on Apple Developer Portal
const provisioningProfileStoreInfo = await ctx.appStore.createOrReuseAdhocProvisioningProfileAsync(
chosenDevices.map(({ identifier }) => identifier),
this.app.bundleIdentifier,
distCert.serialNumber
);
// 5. Create or update the profile on servers
const appleAppIdentifier = await ctx.ios.createOrGetExistingAppleAppIdentifierAsync(
this.app,
appleTeam
);
let appleProvisioningProfile: AppleProvisioningProfileFragment | null = null;
if (currentBuildCredentials?.provisioningProfile) {
if (
currentBuildCredentials.provisioningProfile.developerPortalIdentifier !==
provisioningProfileStoreInfo.provisioningProfileId
) {
await ctx.ios.deleteProvisioningProfilesAsync([
currentBuildCredentials.provisioningProfile.id,
]);
appleProvisioningProfile = await ctx.ios.createProvisioningProfileAsync(
this.app,
appleAppIdentifier,
{
appleProvisioningProfile: provisioningProfileStoreInfo.provisioningProfile,
developerPortalIdentifier: provisioningProfileStoreInfo.provisioningProfileId,
}
);
} else {
appleProvisioningProfile = currentBuildCredentials.provisioningProfile;
}
} else {
appleProvisioningProfile = await ctx.ios.createProvisioningProfileAsync(
this.app,
appleAppIdentifier,
{
appleProvisioningProfile: provisioningProfileStoreInfo.provisioningProfile,
developerPortalIdentifier: provisioningProfileStoreInfo.provisioningProfileId,
}
);
}
// 6. Create (or update) app build credentials
assert(appleProvisioningProfile);
return await assignBuildCredentialsAsync(
ctx,
this.app,
IosDistributionType.AdHoc,
distCert,
appleProvisioningProfile,
appleTeam
);
}
private async areBuildCredentialsSetupAsync(ctx: Context): Promise<boolean> {
const buildCredentials = await getBuildCredentialsAsync(
ctx,
this.app,
IosDistributionType.AdHoc
);
return await validateProvisioningProfileAsync(ctx, this.app, buildCredentials);
}
private async shouldUseExistingProfileAsync(
ctx: Context,
buildCredentials: IosAppBuildCredentialsFragment
): Promise<boolean> {
const provisioningProfile = nullthrows(buildCredentials.provisioningProfile);
const appleTeam = nullthrows(provisioningProfile.appleTeam);
const registeredAppleDevices = await ctx.ios.getDevicesForAppleTeamAsync(this.app, appleTeam);
const provisionedDevices = provisioningProfile.appleDevices;
const allRegisteredDevicesAreProvisioned = doUDIDsMatch(
registeredAppleDevices.map(({ identifier }) => identifier),
provisionedDevices.map(({ identifier }) => identifier)
);
if (allRegisteredDevicesAreProvisioned) {
return await confirmAsync({
message: `All your registered devices are present in the Provisioning Profile. Would you like to reuse it?`,
initial: true,
});
} else {
const missingDevices = differenceBy(registeredAppleDevices, provisionedDevices, 'identifier');
Log.warn(`The provisioning profile is missing the following devices:`);
for (const missingDevice of missingDevices) {
Log.warn(`- ${formatDeviceLabel(missingDevice)}`);
}
return !(await confirmAsync({
message: `Would you like to choose the devices to provision again?`,
initial: true,
}));
}
}
private async registerDevicesAsync(
ctx: Context,
appleTeam: AppleTeamFragment
): Promise<AppleDeviceFragment[]> {
const action = new DeviceCreateAction(this.app.account, appleTeam);
const method = await action.runAsync();
while (true) {
if (method !== RegistrationMethod.INPUT) {
Log.newLine();
Log.log(chalk.bold("Press any key if you've already finished device registration."));
await pressAnyKeyToContinueAsync();
}
Log.newLine();
const devices = await ctx.ios.getDevicesForAppleTeamAsync(this.app, appleTeam, {
useCache: false,
});
if (devices.length === 0) {
Log.warn('There are still no registered devices.');
// if the user used the input method there should be some devices available
if (method === RegistrationMethod.INPUT) {
throw new Error('Input registration method has failed');
}
} else {
return devices;
}
}
}
}
function doUDIDsMatch(udidsA: string[], udidsB: string[]): boolean {
return isEqual(new Set(udidsA), new Set(udidsB));
}
@@ -1,23 +1,19 @@
import { IosDistributionType, IosEnterpriseProvisioning } from '@expo/eas-json';
import chalk from 'chalk';
import nullthrows from 'nullthrows';
import {
IosDistributionType as GraphQLIosDistributionType,
IosAppBuildCredentialsFragment,
} from '../../../graphql/generated';
import Log from '../../../log';
import { promptAsync } from '../../../prompts';
import { Action, CredentialsManager } from '../../CredentialsManager';
import { Context } from '../../context';
import { isCredentialsMap, readIosCredentialsAsync } from '../../credentialsJson/read';
import { AppLookupParams as GraphQLAppLookupParams } from '../api/GraphqlClient';
import { AppLookupParams, IosAppCredentials } from '../credentials';
import { displayProjectCredentials as legacyDisplayProjectCredentials } from '../utils/printCredentials';
import { displayProjectCredentials } from '../utils/printCredentialsBeta';
import { readAppleTeam } from '../utils/provisioningProfile';
import { SetupAdhocProvisioningProfile } from './new/SetupAdhocProvisioningProfile';
import { SetupInternalProvisioningProfile } from './new/SetupInternalProvisioningProfile';
import { SetupProvisioningProfile } from './new/SetupProvisioningProfile';
import { displayProjectCredentials } from '../utils/printCredentials';
import { SetupAdhocProvisioningProfile } from './SetupAdhocProvisioningProfile';
import { SetupInternalProvisioningProfile } from './SetupInternalProvisioningProfile';
import { SetupProvisioningProfile } from './SetupProvisioningProfile';
interface Options {
app: GraphQLAppLookupParams;
@@ -26,10 +22,19 @@ interface Options {
skipCredentialsCheck?: boolean;
}
export class SetupBuildCredentials implements Action {
interface IosAppBuildCredentials {
iosDistributionType: GraphQLIosDistributionType;
provisioningProfile: string;
distributionCertificate: {
certificateP12: string;
certificatePassword: string;
};
}
export class SetupBuildCredentials implements Action<IosAppBuildCredentials> {
constructor(private options: Options) {}
async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
async runAsync(manager: CredentialsManager, ctx: Context): Promise<IosAppBuildCredentials> {
const { app } = this.options;
await ctx.bestEffortAppStoreAuthenticateAsync();
@@ -46,12 +51,21 @@ export class SetupBuildCredentials implements Action {
}
try {
const buildCredentials = await this.setupBuildCredentials(ctx);
const appInfo = `@${app.account.name}/${app.projectName} (${app.bundleIdentifier})`;
displayProjectCredentials(app, buildCredentials);
Log.newLine();
Log.log(chalk.green(`All credentials are ready to build ${appInfo}`));
Log.newLine();
return {
iosDistributionType: buildCredentials.iosDistributionType,
provisioningProfile: nullthrows(buildCredentials.provisioningProfile?.provisioningProfile),
distributionCertificate: {
certificateP12: nullthrows(buildCredentials.distributionCertificate?.certificateP12),
certificatePassword: nullthrows(
buildCredentials.distributionCertificate?.certificatePassword
),
},
};
} catch (error) {
Log.error('Failed to setup credentials.');
throw error;
@@ -78,94 +92,3 @@ export class SetupBuildCredentials implements Action {
}
}
}
export class SetupBuildCredentialsFromCredentialsJson implements Action {
constructor(private app: AppLookupParams) {}
async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
let localCredentials;
try {
localCredentials = await readIosCredentialsAsync(ctx.projectDir);
} catch (error) {
Log.error(
'Reading credentials from credentials.json failed. Make sure this file is correct and all credentials are present there.'
);
throw error;
}
// TODO: implement storing multi-target credentials on EAS servers
if (isCredentialsMap(localCredentials)) {
throw new Error(
'Storing multi-target iOS credentials from credentials.json on EAS servers is not yet supported.'
);
}
const team = readAppleTeam(localCredentials.provisioningProfile);
await ctx.ios.updateProvisioningProfileAsync(this.app, {
...team,
provisioningProfile: localCredentials.provisioningProfile,
});
const credentials = await ctx.ios.getAllCredentialsAsync(this.app.accountName);
const distCert = await ctx.ios.getDistributionCertificateAsync(this.app);
const appsUsingCert = distCert?.id
? (credentials.appCredentials || []).filter(
(cred: IosAppCredentials) => cred.distCredentialsId === distCert.id
)
: [];
const appInfo = `@${this.app.accountName}/${this.app.projectName} (${this.app.bundleIdentifier})`;
const newDistCert = {
...team,
certP12: localCredentials.distributionCertificate.certP12,
certPassword: localCredentials.distributionCertificate.certPassword,
};
if (appsUsingCert.length > 1 && distCert?.id) {
const { update } = await promptAsync({
type: 'select',
name: 'update',
message:
'Current distribution certificate is used by multiple apps. Do you want to update all of them?',
choices: [
{ title: 'Update all apps', value: 'all' },
{ title: `Update only ${appInfo}`, value: 'app' },
],
});
if (update === 'all') {
await ctx.ios.updateDistributionCertificateAsync(
distCert.id,
this.app.accountName,
newDistCert
);
} else {
const createdDistCert = await ctx.ios.createDistributionCertificateAsync(
this.app.accountName,
newDistCert
);
await ctx.ios.useDistributionCertificateAsync(this.app, createdDistCert.id);
}
} else if (distCert?.id) {
await ctx.ios.updateDistributionCertificateAsync(
distCert.id,
this.app.accountName,
newDistCert
);
} else {
const createdDistCert = await ctx.ios.createDistributionCertificateAsync(
this.app.accountName,
newDistCert
);
await ctx.ios.useDistributionCertificateAsync(this.app, createdDistCert.id);
}
legacyDisplayProjectCredentials(
this.app,
await ctx.ios.getAppCredentialsAsync(this.app),
undefined,
await ctx.ios.getDistributionCertificateAsync(this.app)
);
Log.newLine();
Log.log(chalk.green(`All credentials are ready to build ${appInfo}`));
Log.newLine();
}
}
@@ -7,18 +7,18 @@ import {
AppleTeamFragment,
IosAppBuildCredentialsFragment,
IosDistributionType,
} from '../../../../graphql/generated';
import Log from '../../../../log';
import { confirmAsync } from '../../../../prompts';
import { Context } from '../../../context';
} from '../../../graphql/generated';
import Log from '../../../log';
import { confirmAsync } from '../../../prompts';
import { Context } from '../../context';
import {
IosTargetCredentials,
isCredentialsMap,
readIosCredentialsAsync,
} from '../../../credentialsJson/read';
import { AppLookupParams } from '../../api/GraphqlClient';
import { displayProjectCredentials } from '../../utils/printCredentialsBeta';
import { readAppleTeam } from '../../utils/provisioningProfile';
} from '../../credentialsJson/read';
import { AppLookupParams } from '../api/GraphqlClient';
import { displayProjectCredentials } from '../utils/printCredentials';
import { readAppleTeam } from '../utils/provisioningProfile';
import {
assignBuildCredentialsAsync,
getBuildCredentialsAsync,
@@ -39,7 +39,7 @@ export class SetupBuildCredentialsFromCredentialsJson {
const { certP12, certPassword } = distributionCertificate;
if (!currentDistributionCertificate) {
return await ctx.newIos.createDistributionCertificateAsync(this.app, {
return await ctx.ios.createDistributionCertificateAsync(this.app.account, {
certP12,
certPassword,
teamId: appleTeam.appleTeamIdentifier,
@@ -49,7 +49,7 @@ export class SetupBuildCredentialsFromCredentialsJson {
const isSameCertificate = currentDistributionCertificate.certificateP12 === certP12;
if (!isSameCertificate) {
return await ctx.newIos.createDistributionCertificateAsync(this.app, {
return await ctx.ios.createDistributionCertificateAsync(this.app.account, {
certP12,
certPassword,
teamId: appleTeam.appleTeamIdentifier,
@@ -68,11 +68,11 @@ export class SetupBuildCredentialsFromCredentialsJson {
): Promise<AppleProvisioningProfileFragment> {
const { provisioningProfile } = targetCredentials;
const appleAppIdentifier = await ctx.newIos.createOrGetExistingAppleAppIdentifierAsync(
const appleAppIdentifier = await ctx.ios.createOrGetExistingAppleAppIdentifierAsync(
this.app,
appleTeam
);
return await ctx.newIos.createProvisioningProfileAsync(this.app, appleAppIdentifier, {
return await ctx.ios.createProvisioningProfileAsync(this.app, appleAppIdentifier, {
appleProvisioningProfile: provisioningProfile,
});
}
@@ -128,7 +128,7 @@ export class SetupBuildCredentialsFromCredentialsJson {
// new credentials from local json
const appleTeamFromProvisioningProfile = readAppleTeam(localCredentials.provisioningProfile);
const appleTeam = await ctx.newIos.createOrGetExistingAppleTeamAsync(this.app, {
const appleTeam = await ctx.ios.createOrGetExistingAppleTeamAsync(this.app.account, {
appleTeamIdentifier: appleTeamFromProvisioningProfile.teamId,
appleTeamName: appleTeamFromProvisioningProfile.teamName,
});
@@ -5,14 +5,14 @@ import {
AppleDistributionCertificate,
AppleDistributionCertificateFragment,
IosDistributionType,
} from '../../../../graphql/generated';
import Log from '../../../../log';
import { confirmAsync, promptAsync } from '../../../../prompts';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
import { AppleDistributionCertificateMutationResult } from '../../api/graphql/mutations/AppleDistributionCertificateMutation';
import { getValidCertSerialNumbers } from '../../appstore/CredentialsUtils';
import { AppleTeamMissingError, MissingCredentialsNonInteractiveError } from '../../errors';
} from '../../../graphql/generated';
import Log from '../../../log';
import { confirmAsync, promptAsync } from '../../../prompts';
import { Context } from '../../context';
import { AppLookupParams } from '../api/GraphqlClient';
import { AppleDistributionCertificateMutationResult } from '../api/graphql/mutations/AppleDistributionCertificateMutation';
import { getValidCertSerialNumbers } from '../appstore/CredentialsUtils';
import { AppleTeamMissingError, MissingCredentialsNonInteractiveError } from '../errors';
import { resolveAppleTeamIfAuthenticatedAsync } from './AppleTeamUtils';
import { CreateDistributionCertificate } from './CreateDistributionCertificate';
import { formatDistributionCertificate } from './DistributionCertificateUtils';
@@ -26,7 +26,7 @@ export class SetupDistributionCertificate {
const appleTeam = await resolveAppleTeamIfAuthenticatedAsync(ctx, this.app);
try {
const currentCertificate = await ctx.newIos.getDistributionCertificateForAppAsync(
const currentCertificate = await ctx.ios.getDistributionCertificateForAppAsync(
this.app,
this.distributionType,
{ appleTeam }
@@ -80,6 +80,22 @@ export class SetupDistributionCertificate {
if (!currentCertificate) {
return false;
}
const now = new Date();
if (
now < new Date(currentCertificate.validityNotBefore) ||
now > new Date(currentCertificate.validityNotAfter)
) {
return false;
}
if (!ctx.appStore.authCtx) {
Log.warn(
"Skipping Distribution Certificate validation on Apple Servers because we aren't authenticated."
);
return true;
}
const validCertSerialNumbers = (await this.getValidDistCertsAsync(ctx)).map(
i => i.serialNumber
);
@@ -130,10 +146,10 @@ export class SetupDistributionCertificate {
private async createNewDistCertAsync(
ctx: Context
): Promise<AppleDistributionCertificateMutationResult> {
return new CreateDistributionCertificate(this.app).runAsync(ctx);
return new CreateDistributionCertificate(this.app.account).runAsync(ctx);
}
private async reuseDistCertAsync(ctx: Context): Promise<AppleDistributionCertificate> {
async reuseDistCertAsync(ctx: Context): Promise<AppleDistributionCertificate> {
const validDistCerts = await this.getValidDistCertsAsync(ctx);
const { distCert } = await promptAsync({
type: 'select',
@@ -159,7 +175,7 @@ export class SetupDistributionCertificate {
);
const validDistCertSerialNumberSet = new Set(validDistCertSerialNumbers);
const distCertsForAccount = await ctx.newIos.getDistributionCertificatesForAccountAsync(
const distCertsForAccount = await ctx.ios.getDistributionCertificatesForAccountAsync(
this.app.account
);
const distCertsForAppleTeam = distCertsForAccount.filter(distCert => {
@@ -0,0 +1,115 @@
import { IosAppBuildCredentialsFragment, IosDistributionType } from '../../../graphql/generated';
import Log from '../../../log';
import { promptAsync } from '../../../prompts';
import { Context } from '../../context';
import { AppLookupParams } from '../api/GraphqlClient';
import { getAllBuildCredentialsAsync } from './BuildCredentialsUtils';
import { SetupAdhocProvisioningProfile } from './SetupAdhocProvisioningProfile';
import { SetupProvisioningProfile } from './SetupProvisioningProfile';
/**
* It's used when setting up credentials for internal distribution but `enterpriseProvisioning` is not set.
*
* TLDR: If the user authenticates with an account with Apple Developer Enterprise Program membership we ask them
* to choose if they want to set up an adhoc or universal distribution provisioning profile. Otherwise, always
* set up an adhoc provisioning profile.
*/
export class SetupInternalProvisioningProfile {
constructor(private app: AppLookupParams) {}
async runAsync(ctx: Context): Promise<IosAppBuildCredentialsFragment> {
const buildCredentials = await getAllBuildCredentialsAsync(ctx, this.app);
const adhocBuildCredentialsExist =
buildCredentials.filter(
({ iosDistributionType }) => iosDistributionType === IosDistributionType.AdHoc
).length > 0;
const enterpriseBuildCredentialsExist =
buildCredentials.filter(
({ iosDistributionType }) => iosDistributionType === IosDistributionType.Enterprise
).length > 0;
if (!ctx.nonInteractive) {
if (ctx.appStore.authCtx) {
if (ctx.appStore.authCtx.team.inHouse) {
return await this.askForDistributionTypeAndSetupAsync(
ctx,
'Which credentials would you like to set up?'
);
} else {
return await this.setupAdhocProvisioningProfileAsync(ctx);
}
} else {
if (adhocBuildCredentialsExist && enterpriseBuildCredentialsExist) {
Log.log('You have set up both adhoc and universal distribution credentials.');
return await this.askForDistributionTypeAndSetupAsync(
ctx,
'Which credentials would you like to use?'
);
} else if (adhocBuildCredentialsExist) {
return await this.setupAdhocProvisioningProfileAsync(ctx);
} else if (enterpriseBuildCredentialsExist) {
return await this.setupUniversalProvisioningProfileAsync(ctx);
} else {
const { team } = await ctx.appStore.ensureAuthenticatedAsync();
if (team.inHouse) {
return await this.askForDistributionTypeAndSetupAsync(
ctx,
'Which credentials would you like to set up?'
);
} else {
return await this.setupAdhocProvisioningProfileAsync(ctx);
}
}
}
} else {
if (adhocBuildCredentialsExist && enterpriseBuildCredentialsExist) {
throw new Error(
`You're in non-interactive mode. You have set up both adhoc and universal distribution credentials. Please set the 'enterpriseProvisioning' property (to 'adhoc' or 'universal') in eas.json to choose the credentials to use.`
);
} else if (adhocBuildCredentialsExist) {
return await this.setupAdhocProvisioningProfileAsync(ctx);
} else if (enterpriseBuildCredentialsExist) {
return await this.setupUniversalProvisioningProfileAsync(ctx);
} else {
throw new Error(
`You're in non-interactive mode. EAS CLI couldn't find any credentials suitable for internal distribution. Please run again in interactive mode.`
);
}
}
}
private async setupAdhocProvisioningProfileAsync(
ctx: Context
): Promise<IosAppBuildCredentialsFragment> {
return await new SetupAdhocProvisioningProfile(this.app).runAsync(ctx);
}
private async setupUniversalProvisioningProfileAsync(
ctx: Context
): Promise<IosAppBuildCredentialsFragment> {
return await new SetupProvisioningProfile(this.app, IosDistributionType.Enterprise).runAsync(
ctx
);
}
private async askForDistributionTypeAndSetupAsync(
ctx: Context,
message: string
): Promise<IosAppBuildCredentialsFragment> {
const { distributionType } = await promptAsync({
type: 'select',
name: 'distributionType',
message,
choices: [
{ title: 'Universal Distribution', value: IosDistributionType.Enterprise },
{ title: 'Adhoc Distribution', value: IosDistributionType.AdHoc },
],
});
if (distributionType === IosDistributionType.Enterprise) {
return await this.setupUniversalProvisioningProfileAsync(ctx);
} else {
return await this.setupAdhocProvisioningProfileAsync(ctx);
}
}
}
@@ -5,15 +5,13 @@ import {
AppleProvisioningProfileFragment,
IosAppBuildCredentialsFragment,
IosDistributionType,
} from '../../../../graphql/generated';
import Log from '../../../../log';
import { confirmAsync } from '../../../../prompts';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
import { ProvisioningProfileStoreInfo } from '../../appstore/Credentials.types';
import { MissingCredentialsNonInteractiveError } from '../../errors';
import { validateProvisioningProfileAsync } from '../../validators/validateProvisioningProfile';
import { formatProvisioningProfileFromApple } from '../ProvisioningProfileUtils';
} from '../../../graphql/generated';
import { confirmAsync } from '../../../prompts';
import { Context } from '../../context';
import { AppLookupParams } from '../api/GraphqlClient';
import { ProvisioningProfileStoreInfo } from '../appstore/Credentials.types';
import { MissingCredentialsNonInteractiveError } from '../errors';
import { validateProvisioningProfileAsync } from '../validators/validateProvisioningProfile';
import {
assignBuildCredentialsAsync,
getBuildCredentialsAsync,
@@ -21,21 +19,18 @@ import {
} from './BuildCredentialsUtils';
import { ConfigureProvisioningProfile } from './ConfigureProvisioningProfile';
import { CreateProvisioningProfile } from './CreateProvisioningProfile';
import { formatProvisioningProfileFromApple } from './ProvisioningProfileUtils';
import { SetupDistributionCertificate } from './SetupDistributionCertificate';
/**
* Sets up either APP_STORE or ENTERPRISE provisioning profiles
*/
export class SetupProvisioningProfile {
constructor(private app: AppLookupParams, private distributionType: IosDistributionType) {}
async areBuildCredentialsSetupAsync(ctx: Context): Promise<boolean> {
const buildCredentials = await getBuildCredentialsAsync(ctx, this.app, this.distributionType);
if (!buildCredentials) {
return false;
}
const { distributionCertificate, provisioningProfile } = buildCredentials;
if (!distributionCertificate || !provisioningProfile) {
return false;
}
return await this.isCurrentProfileValidAsync(ctx, provisioningProfile, distributionCertificate);
return await validateProvisioningProfileAsync(ctx, this.app, buildCredentials);
}
async assignNewAndDeleteOldProfileAsync(
@@ -45,7 +40,7 @@ export class SetupProvisioningProfile {
): Promise<IosAppBuildCredentialsFragment> {
const buildCredentials = await this.createAndAssignProfileAsync(ctx, distCert);
// delete 'currentProfile' since its no longer valid
await ctx.newIos.deleteProvisioningProfilesAsync([currentProfile.id]);
await ctx.ios.deleteProvisioningProfilesAsync([currentProfile.id]);
return buildCredentials;
}
@@ -89,6 +84,11 @@ export class SetupProvisioningProfile {
}
async runAsync(ctx: Context): Promise<IosAppBuildCredentialsFragment> {
const distCert = await new SetupDistributionCertificate(
this.app,
this.distributionType
).runAsync(ctx);
const areBuildCredentialsSetup = await this.areBuildCredentialsSetupAsync(ctx);
if (areBuildCredentialsSetup) {
return nullthrows(await getBuildCredentialsAsync(ctx, this.app, this.distributionType));
@@ -99,11 +99,6 @@ export class SetupProvisioningProfile {
);
}
const distCert = await new SetupDistributionCertificate(
this.app,
this.distributionType
).runAsync(ctx);
const currentProfile = await getProvisioningProfileAsync(ctx, this.app, this.distributionType);
if (!currentProfile) {
return await this.createAndAssignProfileAsync(ctx, distCert);
@@ -140,37 +135,6 @@ export class SetupProvisioningProfile {
return updatedProfile;
}
private async isCurrentProfileValidAsync(
ctx: Context,
currentProfile: AppleProvisioningProfileFragment,
currentCertificate: AppleDistributionCertificateFragment
): Promise<boolean> {
const { provisioningProfile, developerPortalIdentifier } = currentProfile;
const { certificateP12, certificatePassword } = currentCertificate;
if (!provisioningProfile || !certificateP12 || !certificatePassword) {
return false;
}
const validationResult = await validateProvisioningProfileAsync(
ctx,
{
provisioningProfile,
...(developerPortalIdentifier
? { provisioningProfileId: developerPortalIdentifier }
: null),
},
{
certP12: certificateP12,
certPassword: certificatePassword,
},
this.app.bundleIdentifier
);
if (!validationResult.ok) {
Log.warn(validationResult.error);
return false;
}
return true;
}
private getCurrentProfileStoreInfo(
profiles: ProvisioningProfileStoreInfo[],
currentProfile: AppleProvisioningProfileFragment
@@ -1,23 +1,18 @@
import { Platform } from '@expo/eas-build-job';
import { IosDistributionType as IosDistributionTypeGraphql } from '../../../graphql/generated';
import Log from '../../../log';
import { ensureAppIdentifierIsDefinedAsync } from '../../../project/projectUtils';
import { Action, CredentialsManager } from '../../CredentialsManager';
import { Context } from '../../context';
import { updateIosCredentialsAsync } from '../../credentialsJson/update';
import { AppLookupParams } from '../credentials';
import { AppLookupParams } from '../api/GraphqlClient';
export class UpdateCredentialsJson implements Action {
constructor(private app: AppLookupParams) {}
export class UpdateCredentialsJson {
constructor(
private app: AppLookupParams,
private iosDistributionTypeGraphql: IosDistributionTypeGraphql
) {}
async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
const bundleIdentifer = await ensureAppIdentifierIsDefinedAsync({
projectDir: ctx.projectDir,
platform: Platform.IOS,
exp: ctx.exp,
});
async runAsync(ctx: Context): Promise<void> {
Log.log('Updating iOS credentials in credentials.json');
await updateIosCredentialsAsync(ctx, bundleIdentifer);
await updateIosCredentialsAsync(ctx, this.app, this.iosDistributionTypeGraphql);
Log.succeed(
'iOS part of your local credentials.json is synced with values stored on EAS servers.'
);
@@ -1,87 +0,0 @@
import chalk from 'chalk';
import Log from '../../../log';
import { confirmAsync } from '../../../prompts';
import { Action, CredentialsManager } from '../../CredentialsManager';
import { Context } from '../../context';
import { getAppLookupParams } from '../credentials';
import { displayIosUserCredentials } from '../utils/printCredentials';
import {
provideOrGenerateDistributionCertificateAsync,
selectDistributionCertificateAsync,
} from './DistributionCertificateUtils';
import { RemoveSpecificProvisioningProfile } from './RemoveProvisioningProfile';
export class UpdateDistributionCertificate implements Action {
constructor(private accountName: string) {}
public async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
const selected = await selectDistributionCertificateAsync(ctx, this.accountName);
if (!selected) {
return;
}
const credentials = await ctx.ios.getAllCredentialsAsync(this.accountName);
const apps = credentials.appCredentials.filter(cred => cred.distCredentialsId === selected.id);
const appList = apps.map(appCred => chalk.green(appCred.experienceName)).join(', ');
if (apps.length > 1) {
if (ctx.nonInteractive) {
throw new Error(
`Start the CLI without the '--non-interactive' flag to update the certificate used by ${appList}.`
);
}
const confirm = await confirmAsync({
message: `You are updating certificate used by ${appList}. Do you want to continue?`,
});
if (!confirm) {
Log.log('Aborting update process');
return;
}
}
await manager.runActionAsync(
new UpdateSpecificDistributionCertificate(selected.id, this.accountName)
);
const newDistCert = await ctx.ios.getDistributionCertificateByIdAsync(
selected.id,
this.accountName
);
displayIosUserCredentials(newDistCert);
Log.newLine();
}
}
export class UpdateSpecificDistributionCertificate implements Action {
constructor(private userCredentialsId: number | string, private accountName: string) {}
async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
const credentials = await ctx.ios.getAllCredentialsAsync(this.accountName);
const apps = credentials.appCredentials.filter(
cred => cred.distCredentialsId === this.userCredentialsId
);
const newDistCert = await provideOrGenerateDistributionCertificateAsync(ctx, this.accountName);
await ctx.ios.updateDistributionCertificateAsync(
this.userCredentialsId,
this.accountName,
newDistCert
);
Log.succeed('Updated distribution certificate');
Log.newLine();
for (const appCredentials of apps) {
Log.log(
`Removing provisioning profile for ${appCredentials.experienceName} (${appCredentials.bundleIdentifier})`
);
const appLookupParams = getAppLookupParams(
appCredentials.experienceName,
appCredentials.bundleIdentifier
);
await manager.runActionAsync(
new RemoveSpecificProvisioningProfile(appLookupParams, { shouldRevoke: true })
);
}
}
}
@@ -1,34 +0,0 @@
import Log from '../../../log';
import { Action, CredentialsManager } from '../../CredentialsManager';
import { Context } from '../../context';
import { AppLookupParams } from '../credentials';
import { ConfigureProvisioningProfile } from './ConfigureProvisioningProfile';
import { selectDistributionCertificateAsync } from './DistributionCertificateUtils';
export class UseExistingDistributionCertificate implements Action {
constructor(private app: AppLookupParams) {}
public async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
const selected = await selectDistributionCertificateAsync(ctx, this.app.accountName, {
filterInvalid: true,
});
if (selected) {
await manager.runActionAsync(new UseSpecificDistributionCertificate(this.app, selected.id));
}
const profile = await ctx.ios.getProvisioningProfileAsync(this.app);
if (profile) {
await manager.runActionAsync(new ConfigureProvisioningProfile(this.app));
}
}
}
export class UseSpecificDistributionCertificate implements Action {
constructor(private app: AppLookupParams, private userCredentialsId: number | string) {}
public async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
await ctx.ios.useDistributionCertificateAsync(this.app, this.userCredentialsId);
Log.succeed(
`Assigned distribution certificate to @${this.app.accountName}/${this.app.projectName} (${this.app.bundleIdentifier})`
);
}
}
@@ -1,11 +1,11 @@
import {
AppleDistributionCertificateFragment,
AppleProvisioningProfileFragment,
} from '../../../../../graphql/generated';
import { testProvisioningProfileFragment } from '../../../../__tests__/fixtures-ios';
import { Context } from '../../../../context';
import { AppLookupParams } from '../../../api/GraphqlClient';
import { AppleProvisioningProfileMutationResult } from '../../../api/graphql/mutations/AppleProvisioningProfileMutation';
} from '../../../../graphql/generated';
import { testProvisioningProfileFragment } from '../../../__tests__/fixtures-ios';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
import { AppleProvisioningProfileMutationResult } from '../../api/graphql/mutations/AppleProvisioningProfileMutation';
export class ConfigureProvisioningProfile {
constructor(
@@ -1,8 +1,8 @@
import { AppleDistributionCertificateFragment } from '../../../../../graphql/generated';
import { testProvisioningProfileFragment } from '../../../../__tests__/fixtures-ios';
import { Context } from '../../../../context';
import { AppLookupParams } from '../../../api/GraphqlClient';
import { AppleProvisioningProfileMutationResult } from '../../../api/graphql/mutations/AppleProvisioningProfileMutation';
import { AppleDistributionCertificateFragment } from '../../../../graphql/generated';
import { testProvisioningProfileFragment } from '../../../__tests__/fixtures-ios';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
import { AppleProvisioningProfileMutationResult } from '../../api/graphql/mutations/AppleProvisioningProfileMutation';
export class CreateProvisioningProfile {
constructor(
@@ -1,10 +1,10 @@
import {
AppleDistributionCertificateFragment,
IosDistributionType,
} from '../../../../../graphql/generated';
import { testDistCertFragmentOneDependency } from '../../../../__tests__/fixtures-ios';
import { Context } from '../../../../context';
import { AppLookupParams } from '../../../api/GraphqlClient';
} from '../../../../graphql/generated';
import { testDistCertFragmentOneDependency } from '../../../__tests__/fixtures-ios';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
export class SetupDistributionCertificate {
constructor(private app: AppLookupParams, private distributionType: IosDistributionType) {}
@@ -1,15 +1,15 @@
import { confirmAsync } from '../../../../../prompts';
import { getAppstoreMock, testAuthCtx } from '../../../../__tests__/fixtures-appstore';
import { createCtxMock } from '../../../../__tests__/fixtures-context';
import { confirmAsync } from '../../../../prompts';
import { getAppstoreMock, testAuthCtx } from '../../../__tests__/fixtures-appstore';
import { createCtxMock } from '../../../__tests__/fixtures-context';
import {
testDistCertFragmentNoDependencies,
testProvisioningProfile,
testProvisioningProfileFragment,
} from '../../../../__tests__/fixtures-ios';
import { MissingCredentialsNonInteractiveError } from '../../../errors';
} from '../../../__tests__/fixtures-ios';
import { MissingCredentialsNonInteractiveError } from '../../errors';
import { getAppLookupParamsFromContext } from '../BuildCredentialsUtils';
import { ConfigureProvisioningProfile } from '../ConfigureProvisioningProfile';
jest.mock('../../../../../prompts');
jest.mock('../../../../prompts');
(confirmAsync as jest.Mock).mockImplementation(() => true);
describe('ConfigureProvisioningProfile', () => {
@@ -38,7 +38,7 @@ describe('ConfigureProvisioningProfile', () => {
await provProfConfigurator.runAsync(ctx);
// expect provisioning profile not to be updated on expo servers
expect((ctx.newIos.updateProvisioningProfileAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.updateProvisioningProfileAsync as any).mock.calls.length).toBe(1);
// expect provisioning profile not to be updated on apple portal
expect((ctx.appStore.useExistingProvisioningProfileAsync as any).mock.calls.length).toBe(1);
});
@@ -57,7 +57,7 @@ describe('ConfigureProvisioningProfile', () => {
);
// expect provisioning profile not to be updated on expo servers
expect((ctx.newIos.updateProvisioningProfileAsync as any).mock.calls.length).toBe(0);
expect((ctx.ios.updateProvisioningProfileAsync as any).mock.calls.length).toBe(0);
// expect provisioning profile not to be updated on apple portal
expect((ctx.appStore.useExistingProvisioningProfileAsync as any).mock.calls.length).toBe(0);
});
@@ -1,14 +1,14 @@
import { confirmAsync } from '../../../../../prompts';
import { getAppstoreMock, testAuthCtx } from '../../../../__tests__/fixtures-appstore';
import { createCtxMock } from '../../../../__tests__/fixtures-context';
import { confirmAsync } from '../../../../prompts';
import { getAppstoreMock, testAuthCtx } from '../../../__tests__/fixtures-appstore';
import { createCtxMock } from '../../../__tests__/fixtures-context';
import {
testDistCertFragmentNoDependencies,
testProvisioningProfile,
} from '../../../../__tests__/fixtures-ios';
import { MissingCredentialsNonInteractiveError } from '../../../errors';
} from '../../../__tests__/fixtures-ios';
import { MissingCredentialsNonInteractiveError } from '../../errors';
import { getAppLookupParamsFromContext } from '../BuildCredentialsUtils';
import { CreateProvisioningProfile } from '../CreateProvisioningProfile';
jest.mock('../../../../../prompts');
jest.mock('../../../../prompts');
(confirmAsync as jest.Mock).mockImplementation(() => true);
describe('CreateProvisioningProfile', () => {
@@ -30,7 +30,7 @@ describe('CreateProvisioningProfile', () => {
await createProvProfAction.runAsync(ctx);
// expect provisioning profile to be created on expo servers
expect((ctx.newIos.createProvisioningProfileAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.createProvisioningProfileAsync as any).mock.calls.length).toBe(1);
// expect provisioning profile to be created on apple portal
expect((ctx.appStore.createProvisioningProfileAsync as any).mock.calls.length).toBe(1);
});
@@ -48,7 +48,7 @@ describe('CreateProvisioningProfile', () => {
);
// expect provisioning profile not to be created on expo servers
expect((ctx.newIos.createProvisioningProfileAsync as any).mock.calls.length).toBe(0);
expect((ctx.ios.createProvisioningProfileAsync as any).mock.calls.length).toBe(0);
// expect provisioning profile not to be created on apple portal
expect((ctx.appStore.createProvisioningProfileAsync as any).mock.calls.length).toBe(0);
});
@@ -1,12 +1,12 @@
import mockdate from 'mockdate';
import { AppleDistributionCertificateQuery } from '../../../api/graphql/queries/AppleDistributionCertificateQuery';
import { AppleDistributionCertificateQuery } from '../../api/graphql/queries/AppleDistributionCertificateQuery';
import { formatDistributionCertificate } from '../DistributionCertificateUtils';
jest.mock('../../../api/graphql/queries/AppleDistributionCertificateQuery');
jest.mock('../../api/graphql/queries/AppleDistributionCertificateQuery');
jest.mock('chalk', () => {
return {
__esModule: true, // this property makes it work
default: { gray: jest.fn(log => log) },
default: { gray: jest.fn(log => log), underline: jest.fn(log => log) },
};
});
@@ -1,13 +1,13 @@
import { confirmAsync } from '../../../../../prompts';
import { createCtxMock } from '../../../../__tests__/fixtures-context';
import { confirmAsync } from '../../../../prompts';
import { createCtxMock } from '../../../__tests__/fixtures-context';
import {
testDistCertFragmentNoDependencies,
testDistCertFragmentOneDependency,
} from '../../../../__tests__/fixtures-ios';
} from '../../../__tests__/fixtures-ios';
import { getAppLookupParamsFromContext } from '../BuildCredentialsUtils';
import { RemoveDistributionCertificate } from '../RemoveDistributionCertificate';
jest.mock('../../../../../prompts');
jest.mock('../../../../prompts');
(confirmAsync as jest.Mock).mockImplementation(() => true);
describe('RemoveDistributionCertificate', () => {
@@ -21,11 +21,11 @@ describe('RemoveDistributionCertificate', () => {
await removeDistCertAction.runAsync(ctx);
// expect dist cert to be deleted on expo servers
expect((ctx.newIos.deleteDistributionCertificateAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.deleteDistributionCertificateAsync as any).mock.calls.length).toBe(1);
// expect dist cert to be deleted on apple portal
expect((ctx.appStore.revokeDistributionCertificateAsync as any).mock.calls.length).toBe(1);
// expect provisioning profile deletion to be skipped because there arent any associated with the dist cert
expect((ctx.newIos.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(0);
expect((ctx.ios.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(0);
});
it('deletes the distribution certificate on Expo servers when there are no App Dependencies in Non-Interactive Mode', async () => {
const ctx = createCtxMock({ nonInteractive: true });
@@ -37,11 +37,11 @@ describe('RemoveDistributionCertificate', () => {
await removeDistCertAction.runAsync(ctx);
// expect dist cert to be deleted on expo servers
expect((ctx.newIos.deleteDistributionCertificateAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.deleteDistributionCertificateAsync as any).mock.calls.length).toBe(1);
// not supported in non-interactive mode
expect((ctx.appStore.revokeDistributionCertificateAsync as any).mock.calls.length).toBe(0);
// expect provisioning profile deletion to be skipped because there arent any associated with the dist cert
expect((ctx.newIos.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(0);
expect((ctx.ios.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(0);
});
it('deletes the distribution certificate and its provisioning profile on Expo and Apple servers when there are App Dependencies in Interactive Mode', async () => {
const ctx = createCtxMock({ nonInteractive: false });
@@ -53,11 +53,11 @@ describe('RemoveDistributionCertificate', () => {
await removeDistCertAction.runAsync(ctx);
// expect dist cert to be deleted on expo servers
expect((ctx.newIos.deleteDistributionCertificateAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.deleteDistributionCertificateAsync as any).mock.calls.length).toBe(1);
// expect dist cert to be deleted on apple portal
expect((ctx.appStore.revokeDistributionCertificateAsync as any).mock.calls.length).toBe(1);
// expect provisioning profile deletion to be invoked on expo servers
expect((ctx.newIos.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(1);
});
it('errors when the distribution certificate has App Dependencies in Non-Interactive Mode', async () => {
const ctx = createCtxMock({ nonInteractive: true });
@@ -1,4 +1,4 @@
import { createCtxMock } from '../../../../__tests__/fixtures-context';
import { createCtxMock } from '../../../__tests__/fixtures-context';
import { getAppLookupParamsFromContext } from '../BuildCredentialsUtils';
import { RemoveProvisioningProfiles } from '../RemoveProvisioningProfile';
@@ -17,6 +17,6 @@ describe('RemoveProvisioningProfile', () => {
await removeProfilesAction.runAsync(ctx);
// expect provisioning profile to be deleted from servers
expect((ctx.newIos.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(1);
});
});
@@ -1,21 +1,21 @@
import { asMock } from '../../../../../__tests__/utils';
import { IosDistributionType } from '../../../../../graphql/generated';
import { confirmAsync } from '../../../../../prompts';
import { createCtxMock } from '../../../../__tests__/fixtures-context';
import { asMock } from '../../../../__tests__/utils';
import { IosDistributionType } from '../../../../graphql/generated';
import { confirmAsync } from '../../../../prompts';
import { createCtxMock } from '../../../__tests__/fixtures-context';
import {
getNewIosApiMockWithoutCredentials,
testAppleAppIdentifierFragment,
testDistCert,
testDistCertFragmentNoDependencies,
testIosAppCredentialsWithBuildCredentialsQueryResult,
testProvisioningProfile,
testProvisioningProfileFragment,
} from '../../../../__tests__/fixtures-ios';
import { getNewIosApiMockWithoutCredentials } from '../../../../__tests__/fixtures-new-ios';
import { readIosCredentialsAsync } from '../../../../credentialsJson/read';
} from '../../../__tests__/fixtures-ios';
import { readIosCredentialsAsync } from '../../../credentialsJson/read';
import { getAppLookupParamsFromContext } from '../BuildCredentialsUtils';
import { SetupBuildCredentialsFromCredentialsJson } from '../SetupBuildCredentialsFromCredentialsJson';
jest.mock('../../../../../prompts');
jest.mock('../../../../credentialsJson/read');
jest.mock('../../../../prompts');
jest.mock('../../../credentialsJson/read');
const originalConsoleLog = console.log;
const originalConsoleWarn = console.warn;
@@ -48,12 +48,12 @@ describe('SetupBuildCredentialsFromCredentialsJson', () => {
const testBuildCreds = JSON.parse(
JSON.stringify(testIosAppCredentialsWithBuildCredentialsQueryResult)
);
testBuildCreds.iosAppBuildCredentialsArray[0].distributionCertificate.certificateP12 =
testBuildCreds.iosAppBuildCredentialsList[0].distributionCertificate.certificateP12 =
testDistCert.certP12;
testBuildCreds.iosAppBuildCredentialsArray[0].provisioningProfile.provisioningProfile =
testBuildCreds.iosAppBuildCredentialsList[0].provisioningProfile.provisioningProfile =
testProvisioningProfile.provisioningProfile;
const ctx = createCtxMock({
newIos: {
ios: {
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(() => testBuildCreds),
createOrGetExistingAppleAppIdentifierAsync: jest.fn(() => testAppleAppIdentifierFragment),
@@ -70,15 +70,15 @@ describe('SetupBuildCredentialsFromCredentialsJson', () => {
await setupBuildCredentialsFromCredentialsJsonAction.runAsync(ctx);
// expect build credentials not to be created or updated on expo servers
expect((ctx.newIos.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(0);
expect((ctx.ios.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(0);
// expect distribution certificate not to be uploaded on expo servers
expect((ctx.newIos.createDistributionCertificateAsync as any).mock.calls.length).toBe(0);
expect((ctx.ios.createDistributionCertificateAsync as any).mock.calls.length).toBe(0);
// expect provisioning profile not to be uploaded on expo servers
expect((ctx.newIos.createProvisioningProfileAsync as any).mock.calls.length).toBe(0);
expect((ctx.ios.createProvisioningProfileAsync as any).mock.calls.length).toBe(0);
});
it('sets up build credentials with no prior configuration in Interactive Mode', async () => {
const ctx = createCtxMock({
newIos: {
ios: {
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(() => null),
createOrGetExistingAppleAppIdentifierAsync: jest.fn(() => testAppleAppIdentifierFragment),
@@ -97,21 +97,23 @@ describe('SetupBuildCredentialsFromCredentialsJson', () => {
await setupBuildCredentialsFromCredentialsJsonAction.runAsync(ctx);
// expect build credentials to be created or updated on expo servers
expect((ctx.newIos.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(1);
// expect distribution certificate to be uploaded on expo servers
expect((ctx.newIos.createDistributionCertificateAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.createDistributionCertificateAsync as any).mock.calls.length).toBe(1);
// expect provisioning profile to be uploaded on expo servers
expect((ctx.newIos.createProvisioningProfileAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.createProvisioningProfileAsync as any).mock.calls.length).toBe(1);
});
it('sets up build credentials with different prior configuration in Interactive Mode', async () => {
// create deep clone the quick and dirty way
const testBuildCreds = JSON.parse(
JSON.stringify(testIosAppCredentialsWithBuildCredentialsQueryResult)
);
testBuildCreds.iosAppBuildCredentialsArray[0].distributionCertificate.certificateP12 =
testBuildCreds.iosAppBuildCredentialsList[0].distributionCertificate.certificateP12 =
'something different so SetupBuildCredentialsFromCredentialsJson doesnt think we want to exact the same cert and skip upload to expo servers';
testBuildCreds.iosAppBuildCredentialsList[0].provisioningProfile.provisioningProfile =
'something different so SetupBuildCredentialsFromCredentialsJson doesnt think we want to exact the same cert and skip upload to expo servers';
const ctx = createCtxMock({
newIos: {
ios: {
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(() => testBuildCreds),
createOrGetExistingAppleAppIdentifierAsync: jest.fn(() => testAppleAppIdentifierFragment),
@@ -128,22 +130,24 @@ describe('SetupBuildCredentialsFromCredentialsJson', () => {
await setupBuildCredentialsFromCredentialsJsonAction.runAsync(ctx);
// expect build credentials to be created or updated on expo servers
expect((ctx.newIos.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(1);
// expect distribution certificate to be uploaded on expo servers
expect((ctx.newIos.createDistributionCertificateAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.createDistributionCertificateAsync as any).mock.calls.length).toBe(1);
// expect provisioning profile to be uploaded on expo servers
expect((ctx.newIos.createProvisioningProfileAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.createProvisioningProfileAsync as any).mock.calls.length).toBe(1);
});
it('works in Non Interactive Mode - sets up build credentials with different prior configuration', async () => {
// create deep clone the quick and dirty way
const testBuildCreds = JSON.parse(
JSON.stringify(testIosAppCredentialsWithBuildCredentialsQueryResult)
);
testBuildCreds.iosAppBuildCredentialsArray[0].distributionCertificate.certificateP12 =
testBuildCreds.iosAppBuildCredentialsList[0].distributionCertificate.certificateP12 =
'something different so SetupBuildCredentialsFromCredentialsJson doesnt think we want to exact the same cert and skip upload to expo servers';
testBuildCreds.iosAppBuildCredentialsList[0].provisioningProfile.provisioningProfile =
'something different so SetupBuildCredentialsFromCredentialsJson doesnt think we want to exact the same cert and skip upload to expo servers';
const ctx = createCtxMock({
nonInteractive: true,
newIos: {
ios: {
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(() => testBuildCreds),
createOrGetExistingAppleAppIdentifierAsync: jest.fn(() => testAppleAppIdentifierFragment),
@@ -162,10 +166,10 @@ describe('SetupBuildCredentialsFromCredentialsJson', () => {
// expect no prompts to be called
expect((confirmAsync as any).mock.calls.length).toBe(0);
// expect build credentials to be created or updated on expo servers
expect((ctx.newIos.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(1);
// expect distribution certificate to be uploaded on expo servers
expect((ctx.newIos.createDistributionCertificateAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.createDistributionCertificateAsync as any).mock.calls.length).toBe(1);
// expect provisioning profile to be uploaded on expo servers
expect((ctx.newIos.createProvisioningProfileAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.createProvisioningProfileAsync as any).mock.calls.length).toBe(1);
});
});
@@ -0,0 +1,311 @@
import { asMock } from '../../../../__tests__/utils';
import { IosAppBuildCredentialsFragment, IosDistributionType } from '../../../../graphql/generated';
import { promptAsync } from '../../../../prompts';
import { getAppstoreMock, testAuthCtx } from '../../../__tests__/fixtures-appstore';
import { createCtxMock } from '../../../__tests__/fixtures-context';
import { getAllBuildCredentialsAsync } from '../BuildCredentialsUtils';
import { SetupAdhocProvisioningProfile } from '../SetupAdhocProvisioningProfile';
import { SetupInternalProvisioningProfile } from '../SetupInternalProvisioningProfile';
import { SetupProvisioningProfile } from '../SetupProvisioningProfile';
jest.mock('../../../../prompts');
jest.mock('../SetupAdhocProvisioningProfile');
jest.mock('../SetupProvisioningProfile');
jest.mock('../BuildCredentialsUtils', () => ({ getAllBuildCredentialsAsync: jest.fn() }));
beforeEach(() => {
asMock(promptAsync).mockReset();
asMock(getAllBuildCredentialsAsync).mockReset();
asMock(getAllBuildCredentialsAsync).mockImplementation(() => {
throw new Error(
`unhandled getAllBuildCredentialsAsync call - this shouldn't happen - fix tests!`
);
});
});
const testAdhocBuildCredentials: IosAppBuildCredentialsFragment = {
id: 'test-app-build-credentials-id-1',
iosDistributionType: IosDistributionType.AdHoc,
};
const testEnterpriseBuildCredentials: IosAppBuildCredentialsFragment = {
id: 'test-app-build-credentials-id-2',
iosDistributionType: IosDistributionType.Enterprise,
};
describe(SetupInternalProvisioningProfile, () => {
describe('interactive mode', () => {
describe('when authenticated with apple', () => {
it('runs the SetupAdhocProvisioningProfile action for non-enterprise team', async () => {
asMock(getAllBuildCredentialsAsync).mockImplementationOnce(() => {
const buildCredentials: IosAppBuildCredentialsFragment[] = [];
return buildCredentials;
});
const action = new SetupInternalProvisioningProfile({
account: { id: 'account-id', name: 'account-name' },
bundleIdentifier: 'com.expo.test',
projectName: 'testproject',
});
const ctx = createCtxMock({
nonInteractive: false,
appStore: {
...getAppstoreMock(),
ensureAuthenticatedAsync: jest.fn(() => testAuthCtx),
authCtx: testAuthCtx,
},
});
const runAsync = jest.fn();
SetupAdhocProvisioningProfile.prototype.runAsync = runAsync;
await action.runAsync(ctx);
expect(runAsync).toHaveBeenCalled();
});
it('asks the user for an action to run when they have access to an enterprise team', async () => {
asMock(promptAsync).mockImplementationOnce(() => ({
distributionType: IosDistributionType.Enterprise,
}));
asMock(getAllBuildCredentialsAsync).mockImplementationOnce(() => {
const buildCredentials: IosAppBuildCredentialsFragment[] = [];
return buildCredentials;
});
const action = new SetupInternalProvisioningProfile({
account: { id: 'account-id', name: 'account-name' },
bundleIdentifier: 'com.expo.test',
projectName: 'testproject',
});
const ctx = createCtxMock({
nonInteractive: false,
appStore: {
...getAppstoreMock(),
ensureAuthenticatedAsync: jest.fn(() => ({
...testAuthCtx,
team: { ...testAuthCtx.team, inHouse: true },
})),
authCtx: { ...testAuthCtx, team: { ...testAuthCtx.team, inHouse: true } },
},
});
const runAsync = jest.fn();
SetupProvisioningProfile.prototype.runAsync = runAsync;
await action.runAsync(ctx);
expect(runAsync).toHaveBeenCalled();
});
});
describe('when not authenticated with apple', () => {
it('asks the user for an action to run when both adhoc and universal distribution credentials exist', async () => {
asMock(promptAsync).mockImplementationOnce(() => ({
distributionType: IosDistributionType.Enterprise,
}));
asMock(getAllBuildCredentialsAsync).mockImplementationOnce(() => {
const buildCredentials: IosAppBuildCredentialsFragment[] = [
testAdhocBuildCredentials,
testEnterpriseBuildCredentials,
];
return buildCredentials;
});
const action = new SetupInternalProvisioningProfile({
account: { id: 'account-id', name: 'account-name' },
bundleIdentifier: 'com.expo.test',
projectName: 'testproject',
});
const ctx = createCtxMock({
nonInteractive: false,
appStore: {
...getAppstoreMock(),
ensureAuthenticatedAsync: jest.fn(() => null),
authCtx: null,
},
});
const runAsync = jest.fn();
SetupProvisioningProfile.prototype.runAsync = runAsync;
await action.runAsync(ctx);
expect(runAsync).toHaveBeenCalled();
});
it('runs the SetupAdhocProvisioningProfile action when adhoc credentials exist', async () => {
asMock(promptAsync).mockImplementationOnce(() => ({
distributionType: IosDistributionType.Enterprise,
}));
asMock(getAllBuildCredentialsAsync).mockImplementationOnce(() => {
const buildCredentials: IosAppBuildCredentialsFragment[] = [testAdhocBuildCredentials];
return buildCredentials;
});
const action = new SetupInternalProvisioningProfile({
account: { id: 'account-id', name: 'account-name' },
bundleIdentifier: 'com.expo.test',
projectName: 'testproject',
});
const ctx = createCtxMock({
nonInteractive: false,
appStore: {
...getAppstoreMock(),
ensureAuthenticatedAsync: jest.fn(() => null),
authCtx: null,
},
});
const runAsync = jest.fn();
SetupAdhocProvisioningProfile.prototype.runAsync = runAsync;
await action.runAsync(ctx);
expect(runAsync).toHaveBeenCalled();
});
it('runs the SetupProvisioningProfile action when enterprise credentials exist', async () => {
asMock(promptAsync).mockImplementationOnce(() => ({
distributionType: IosDistributionType.Enterprise,
}));
asMock(getAllBuildCredentialsAsync).mockImplementationOnce(() => {
const buildCredentials: IosAppBuildCredentialsFragment[] = [
testEnterpriseBuildCredentials,
];
return buildCredentials;
});
const action = new SetupInternalProvisioningProfile({
account: { id: 'account-id', name: 'account-name' },
bundleIdentifier: 'com.expo.test',
projectName: 'testproject',
});
const ctx = createCtxMock({
nonInteractive: false,
appStore: {
...getAppstoreMock(),
ensureAuthenticatedAsync: jest.fn(() => null),
authCtx: null,
},
});
const runAsync = jest.fn();
SetupProvisioningProfile.prototype.runAsync = runAsync;
await action.runAsync(ctx);
expect(runAsync).toHaveBeenCalled();
});
it('forces the apple authentication when neither adhoc nor enterprise credentials exist', async () => {
asMock(promptAsync).mockImplementationOnce(() => ({
distributionType: IosDistributionType.Enterprise,
}));
asMock(getAllBuildCredentialsAsync).mockImplementationOnce(() => {
const buildCredentials: IosAppBuildCredentialsFragment[] = [];
return buildCredentials;
});
const action = new SetupInternalProvisioningProfile({
account: { id: 'account-id', name: 'account-name' },
bundleIdentifier: 'com.expo.test',
projectName: 'testproject',
});
const ctx = createCtxMock({
nonInteractive: false,
appStore: {
...getAppstoreMock(),
ensureAuthenticatedAsync: jest.fn(() => testAuthCtx),
authCtx: null,
},
});
await action.runAsync(ctx);
expect(ctx.appStore.ensureAuthenticatedAsync).toHaveBeenCalled();
});
});
});
describe('non-interactive mode', () => {
it('throws an error when both adhoc and enterprise credentials are set up', async () => {
asMock(getAllBuildCredentialsAsync).mockImplementationOnce(() => {
const buildCredentials: IosAppBuildCredentialsFragment[] = [
testAdhocBuildCredentials,
testEnterpriseBuildCredentials,
];
return buildCredentials;
});
const action = new SetupInternalProvisioningProfile({
account: { id: 'account-id', name: 'account-name' },
bundleIdentifier: 'com.expo.test',
projectName: 'testproject',
});
const ctx = createCtxMock({
nonInteractive: true,
});
await expect(action.runAsync(ctx)).rejects.toThrow(
/You have set up both adhoc and universal distribution credentials/
);
});
it('throws an error when neither adhoc nor enterprise credentials are set up', async () => {
asMock(getAllBuildCredentialsAsync).mockImplementationOnce(() => {
const buildCredentials: IosAppBuildCredentialsFragment[] = [];
return buildCredentials;
});
const action = new SetupInternalProvisioningProfile({
account: { id: 'account-id', name: 'account-name' },
bundleIdentifier: 'com.expo.test',
projectName: 'testproject',
});
const ctx = createCtxMock({
nonInteractive: true,
});
await expect(action.runAsync(ctx)).rejects.toThrow(/couldn't find any credentials/);
});
it('runs the SetupAdhocProvisioningProfile action when adhoc credentials exist', async () => {
asMock(getAllBuildCredentialsAsync).mockImplementationOnce(() => {
const buildCredentials: IosAppBuildCredentialsFragment[] = [testAdhocBuildCredentials];
return buildCredentials;
});
const action = new SetupInternalProvisioningProfile({
account: { id: 'account-id', name: 'account-name' },
bundleIdentifier: 'com.expo.test',
projectName: 'testproject',
});
const ctx = createCtxMock({
nonInteractive: true,
});
const runAsync = jest.fn();
SetupAdhocProvisioningProfile.prototype.runAsync = runAsync;
await action.runAsync(ctx);
expect(runAsync).toHaveBeenCalled();
});
it('runs the SetupProvisioningProfile action when enterprise credentials exist', async () => {
asMock(getAllBuildCredentialsAsync).mockImplementationOnce(() => {
const buildCredentials: IosAppBuildCredentialsFragment[] = [testEnterpriseBuildCredentials];
return buildCredentials;
});
const action = new SetupInternalProvisioningProfile({
account: { id: 'account-id', name: 'account-name' },
bundleIdentifier: 'com.expo.test',
projectName: 'testproject',
});
const ctx = createCtxMock({
nonInteractive: true,
});
const runAsync = jest.fn();
SetupProvisioningProfile.prototype.runAsync = runAsync;
await action.runAsync(ctx);
expect(runAsync).toHaveBeenCalled();
});
});
});
@@ -1,32 +1,29 @@
import nullthrows from 'nullthrows';
import { IosDistributionType } from '../../../../../graphql/generated';
import { confirmAsync } from '../../../../../prompts';
import { getAppstoreMock, testAuthCtx } from '../../../../__tests__/fixtures-appstore';
import { createCtxMock } from '../../../../__tests__/fixtures-context';
import { IosDistributionType } from '../../../../graphql/generated';
import { confirmAsync } from '../../../../prompts';
import { getAppstoreMock, testAuthCtx } from '../../../__tests__/fixtures-appstore';
import { createCtxMock } from '../../../__tests__/fixtures-context';
import {
getNewIosApiMockWithoutCredentials,
testAppleAppIdentifierFragment,
testIosAppBuildCredentialsFragment,
testIosAppCredentialsWithBuildCredentialsQueryResult,
} from '../../../../__tests__/fixtures-ios';
import { getNewIosApiMockWithoutCredentials } from '../../../../__tests__/fixtures-new-ios';
import { MissingCredentialsNonInteractiveError } from '../../../errors';
import { validateProvisioningProfileAsync } from '../../../validators/validateProvisioningProfile';
} from '../../../__tests__/fixtures-ios';
import { MissingCredentialsNonInteractiveError } from '../../errors';
import { validateProvisioningProfileAsync } from '../../validators/validateProvisioningProfile';
import { getAppLookupParamsFromContext } from '../BuildCredentialsUtils';
import { SetupProvisioningProfile } from '../SetupProvisioningProfile';
jest.mock('../../../../../prompts');
jest.mock('../../../../prompts');
(confirmAsync as jest.Mock).mockImplementation(() => true);
jest.mock('../SetupDistributionCertificate');
jest.mock('../ConfigureProvisioningProfile');
jest.mock('../CreateProvisioningProfile');
jest.mock('../../../validators/validateProvisioningProfile');
jest.mock('../../validators/validateProvisioningProfile');
describe('SetupProvisioningProfile', () => {
it('repairs existing Provisioning Profile with bad build credentials in Interactive Mode', async () => {
(validateProvisioningProfileAsync as jest.Mock).mockImplementation(() => ({
error: 'testing: everything is fine, ignore this',
ok: false,
}));
(validateProvisioningProfileAsync as jest.Mock).mockImplementation(() => false);
const ctx = createCtxMock({
nonInteractive: false,
appStore: {
@@ -36,13 +33,13 @@ describe('SetupProvisioningProfile', () => {
listProvisioningProfilesAsync: jest.fn(() => [
{
provisioningProfileId: nullthrows(
testIosAppCredentialsWithBuildCredentialsQueryResult.iosAppBuildCredentialsArray[0]
testIosAppCredentialsWithBuildCredentialsQueryResult.iosAppBuildCredentialsList[0]
.provisioningProfile
).developerPortalIdentifier,
},
]),
},
newIos: {
ios: {
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(
() => testIosAppCredentialsWithBuildCredentialsQueryResult
@@ -61,15 +58,12 @@ describe('SetupProvisioningProfile', () => {
await setupProvisioningProfileAction.runAsync(ctx);
// expect build credentials to be created or updated on expo servers
expect((ctx.newIos.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(1);
// expect provisioning profile not to be deleted on expo servers
expect((ctx.newIos.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(0);
expect((ctx.ios.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(0);
});
it('sets up a new Provisioning Profile with bad build credentials in Interactive Mode', async () => {
(validateProvisioningProfileAsync as jest.Mock).mockImplementation(() => ({
error: 'testing: everything is fine, ignore this',
ok: false,
}));
(validateProvisioningProfileAsync as jest.Mock).mockImplementation(() => false);
const ctx = createCtxMock({
nonInteractive: false,
appStore: {
@@ -78,7 +72,7 @@ describe('SetupProvisioningProfile', () => {
authCtx: testAuthCtx,
listProvisioningProfilesAsync: jest.fn(() => []),
},
newIos: {
ios: {
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(
() => testIosAppCredentialsWithBuildCredentialsQueryResult
@@ -94,14 +88,12 @@ describe('SetupProvisioningProfile', () => {
await setupProvisioningProfileAction.runAsync(ctx);
// expect build credentials to be created or updated on expo servers
expect((ctx.newIos.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(1);
// expect provisioning profile to be deleted on expo servers
expect((ctx.newIos.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(1);
});
it('skips setting up a Provisioning Profile with prior build credentials configured properly in Interactive Mode', async () => {
(validateProvisioningProfileAsync as jest.Mock).mockImplementation(() => ({
ok: true,
}));
(validateProvisioningProfileAsync as jest.Mock).mockImplementation(() => true);
const ctx = createCtxMock({
nonInteractive: false,
appStore: {
@@ -110,7 +102,7 @@ describe('SetupProvisioningProfile', () => {
authCtx: testAuthCtx,
//listProvisioningProfilesAsync: jest.fn(() => []),
},
newIos: {
ios: {
...getNewIosApiMockWithoutCredentials(),
getIosAppCredentialsWithBuildCredentialsAsync: jest.fn(
() => testIosAppCredentialsWithBuildCredentialsQueryResult
@@ -126,11 +118,12 @@ describe('SetupProvisioningProfile', () => {
await setupProvisioningProfileAction.runAsync(ctx);
// expect build credentials not to be created or updated on expo servers
expect((ctx.newIos.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(0);
expect((ctx.ios.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(0);
// expect provisioning profile not to be deleted on expo servers
expect((ctx.newIos.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(0);
expect((ctx.ios.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(0);
});
it('sets up a Provisioning Profile with no prior build credentials configured in Interactive Mode', async () => {
(validateProvisioningProfileAsync as jest.Mock).mockImplementation(() => false);
const ctx = createCtxMock({
nonInteractive: false,
appStore: {
@@ -138,7 +131,7 @@ describe('SetupProvisioningProfile', () => {
ensureAuthenticatedAsync: jest.fn(() => testAuthCtx),
authCtx: testAuthCtx,
},
newIos: {
ios: {
...getNewIosApiMockWithoutCredentials(),
createOrGetExistingAppleAppIdentifierAsync: jest.fn(() => testAppleAppIdentifierFragment),
},
@@ -151,11 +144,12 @@ describe('SetupProvisioningProfile', () => {
await setupProvisioningProfileAction.runAsync(ctx);
// expect build credentials to be created or updated on expo servers
expect((ctx.newIos.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(1);
expect((ctx.ios.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(1);
// expect provisioning profile not to be deleted on expo servers
expect((ctx.newIos.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(0);
expect((ctx.ios.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(0);
});
it('errors in Non Interactive Mode', async () => {
(validateProvisioningProfileAsync as jest.Mock).mockImplementation(() => false);
const ctx = createCtxMock({
nonInteractive: true,
});
@@ -169,8 +163,8 @@ describe('SetupProvisioningProfile', () => {
);
// expect build credentials not to be created or updated on expo servers
expect((ctx.newIos.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(0);
expect((ctx.ios.createOrUpdateIosAppBuildCredentialsAsync as any).mock.calls.length).toBe(0);
// expect provisioning profile not to be deleted on expo servers
expect((ctx.newIos.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(0);
expect((ctx.ios.deleteProvisioningProfilesAsync as any).mock.calls.length).toBe(0);
});
});
@@ -1,113 +0,0 @@
import assert from 'assert';
import chalk from 'chalk';
import ora from 'ora';
import {
AppleDistributionCertificateFragment,
AppleProvisioningProfileFragment,
} from '../../../../graphql/generated';
import Log from '../../../../log';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
import { AppleProvisioningProfileMutationResult } from '../../api/graphql/mutations/AppleProvisioningProfileMutation';
import { ProvisioningProfileStoreInfo } from '../../appstore/Credentials.types';
import { AuthCtx } from '../../appstore/authenticate';
import { MissingCredentialsNonInteractiveError } from '../../errors';
export class ConfigureProvisioningProfile {
constructor(
private app: AppLookupParams,
private distributionCertificate: AppleDistributionCertificateFragment,
private originalProvisioningProfile: AppleProvisioningProfileFragment
) {}
public async runAsync(ctx: Context): Promise<AppleProvisioningProfileMutationResult | null> {
if (ctx.nonInteractive) {
throw new MissingCredentialsNonInteractiveError(
'Configuring Provisioning Profiles is only supported in interactive mode.'
);
}
const { developerPortalIdentifier, provisioningProfile } = this.originalProvisioningProfile;
if (!developerPortalIdentifier && !provisioningProfile) {
Log.warn("The provisioning profile we have on file cannot be configured on Apple's servers.");
return null;
}
if (!ctx.appStore.authCtx) {
Log.warn(
"Without access to your Apple account we can't configure provisioning profiles for you."
);
Log.warn('Make sure to recreate the profile if you selected a new distribution certificate.');
return null;
}
const profilesFromApple = await ctx.appStore.listProvisioningProfilesAsync(
this.app.bundleIdentifier
);
const [matchingProfile] = profilesFromApple.filter(appleInfo =>
developerPortalIdentifier
? appleInfo.provisioningProfileId === developerPortalIdentifier
: appleInfo.provisioningProfile === provisioningProfile
);
if (!matchingProfile) {
Log.warn(
`Profile ${
developerPortalIdentifier ? `${developerPortalIdentifier} ` : ''
}not found on Apple Developer Portal.`
);
return null;
}
return await this.configureAndUpdateAsync(ctx, ctx.appStore.authCtx, this.app, matchingProfile);
}
private async configureAndUpdateAsync(
ctx: Context,
authCtx: AuthCtx,
app: AppLookupParams,
profileFromApple: ProvisioningProfileStoreInfo
): Promise<AppleProvisioningProfileMutationResult> {
const {
developerPortalIdentifier,
certificateP12,
certificatePassword,
serialNumber,
} = this.distributionCertificate;
assert(
certificateP12 && certificatePassword,
'Distribution Certificate P12 and Password is required'
);
// configure profile on Apple's Server to use our distCert
const updatedProfile = await ctx.appStore.useExistingProvisioningProfileAsync(
app.bundleIdentifier,
profileFromApple,
{
certId: developerPortalIdentifier ?? undefined,
certP12: certificateP12,
certPassword: certificatePassword,
distCertSerialNumber: serialNumber,
teamId: authCtx.appleId,
}
);
const bundleIdTag = `(${app.bundleIdentifier})`;
const slugTag = `@${app.account.name}/${app.projectName}`;
const projectTag = `${chalk.bold(slugTag)} ${chalk.dim(bundleIdTag)}`;
const spinner = ora(`Updating Expo profile for ${projectTag}`).start();
try {
const configuredProvisioningProfile = await ctx.newIos.updateProvisioningProfileAsync(
this.originalProvisioningProfile.id,
{
appleProvisioningProfile: updatedProfile.provisioningProfile,
developerPortalIdentifier: updatedProfile.provisioningProfileId,
}
);
spinner.succeed(`Updated Expo profile for ${projectTag}`);
return configuredProvisioningProfile;
} catch (error) {
spinner.fail();
throw error;
}
}
}
@@ -1,19 +0,0 @@
import Log from '../../../../log';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
import { AppleDistributionCertificateMutationResult } from '../../api/graphql/mutations/AppleDistributionCertificateMutation';
import { provideOrGenerateDistributionCertificateAsync } from '../DistributionCertificateUtils';
export class CreateDistributionCertificate {
constructor(private app: AppLookupParams) {}
public async runAsync(ctx: Context): Promise<AppleDistributionCertificateMutationResult> {
const distCert = await provideOrGenerateDistributionCertificateAsync(
ctx,
this.app.account.name
);
const result = await ctx.newIos.createDistributionCertificateAsync(this.app, distCert);
Log.succeed('Created distribution certificate');
return result;
}
}
@@ -1,142 +0,0 @@
import assert from 'assert';
import chalk from 'chalk';
import dateformat from 'dateformat';
import {
AppleDistributionCertificateFragment,
AppleTeamFragment,
} from '../../../../graphql/generated';
import Log from '../../../../log';
import { promptAsync } from '../../../../prompts';
import { Account } from '../../../../user/Account';
import { fromNow } from '../../../../utils/date';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
import { filterRevokedDistributionCerts } from '../../appstore/CredentialsUtilsBeta';
export function formatDistributionCertificate(
distributionCertificate: AppleDistributionCertificateFragment,
validSerialNumbers?: string[]
): string {
const {
serialNumber,
developerPortalIdentifier,
appleTeam,
validityNotBefore,
validityNotAfter,
updatedAt,
} = distributionCertificate;
let line: string = '';
if (developerPortalIdentifier) {
line += `Cert ID: ${developerPortalIdentifier}`;
}
line += `${line === '' ? '' : ', '}Serial number: ${serialNumber}${
appleTeam ? `, ${formatAppleTeam(appleTeam)}` : ''
}`;
line += chalk.gray(
`\n Created: ${fromNow(new Date(validityNotBefore))} ago, Updated: ${fromNow(
new Date(updatedAt)
)} ago,`
);
line += chalk.gray(`\n Expires: ${dateformat(validityNotAfter, 'expiresHeaderFormat')}`);
const apps = distributionCertificate.iosAppBuildCredentialsList.map(
buildCredentials => buildCredentials.iosAppCredentials.app
);
if (apps.length) {
const appFullNames = apps.map(app => app.fullName).join(',');
line += chalk.gray(`\n 📲 Used by: ${appFullNames}`);
}
if (validSerialNumbers?.includes(serialNumber)) {
line += chalk.gray("\n ✅ Currently valid on Apple's servers.");
} else {
line += '';
}
return line;
}
function formatAppleTeam({ appleTeamIdentifier, appleTeamName }: AppleTeamFragment): string {
return `Team ID: ${appleTeamIdentifier}${appleTeamName ? `, Team name: ${appleTeamName}` : ''}`;
}
async function _selectDistributionCertificateAsync(
distCerts: AppleDistributionCertificateFragment[],
validDistributionCertificates?: AppleDistributionCertificateFragment[]
): Promise<AppleDistributionCertificateFragment | null> {
const validDistCertSerialNumbers = validDistributionCertificates?.map(
distCert => distCert.serialNumber
);
const { chosenDistCert } = await promptAsync({
type: 'select',
name: 'chosenDistCert',
message: 'Select certificate from the list.',
choices: distCerts.map(distCert => ({
title: formatDistributionCertificate(distCert, validDistCertSerialNumbers),
value: distCert,
})),
});
return chosenDistCert;
}
/**
* select a distribution certificate from an account (validity status shown on a best effort basis)
* */
export async function selectDistributionCertificateWithDependenciesAsync(
ctx: Context,
account: Account
): Promise<AppleDistributionCertificateFragment | null> {
const distCertsForAccount = await ctx.newIos.getDistributionCertificatesForAccountAsync(account);
if (distCertsForAccount.length === 0) {
Log.warn(`There are no Distribution Certificates available in your EAS account.`);
return null;
}
if (!ctx.appStore.authCtx) {
return _selectDistributionCertificateAsync(distCertsForAccount);
}
// get valid certs on the developer portal
const certInfoFromApple = await ctx.appStore.listDistributionCertificatesAsync();
const validDistCerts = await filterRevokedDistributionCerts(
distCertsForAccount,
certInfoFromApple
);
return _selectDistributionCertificateAsync(distCertsForAccount, validDistCerts);
}
/**
* select a distribution certificate from a valid set (curated on a best effort basis)
* */
export async function selectValidDistributionCertificateAsync(
ctx: Context,
appLookupParams: AppLookupParams
): Promise<AppleDistributionCertificateFragment | null> {
const distCertsForAccount = await ctx.newIos.getDistributionCertificatesForAccountAsync(
appLookupParams.account
);
if (distCertsForAccount.length === 0) {
Log.warn(`There are no Distribution Certificates available in your EAS account.`);
return null;
}
if (!ctx.appStore.authCtx) {
return _selectDistributionCertificateAsync(distCertsForAccount);
}
// filter by apple team
assert(ctx.appStore.authCtx, 'authentication to the Apple App Store is required');
const appleTeamIdentifier = ctx.appStore.authCtx.team.id;
const distCertsForAppleTeam = distCertsForAccount.filter(distCert => {
return !distCert.appleTeam || distCert.appleTeam.appleTeamIdentifier === appleTeamIdentifier;
});
// filter by valid certs on the developer portal
const certInfoFromApple = await ctx.appStore.listDistributionCertificatesAsync();
const validDistCerts = await filterRevokedDistributionCerts(
distCertsForAppleTeam,
certInfoFromApple
);
Log.log(
`${validDistCerts.length}/${distCertsForAccount.length} Distribution Certificates are currently valid for Apple Team ${ctx.appStore.authCtx?.team.id}.`
);
return _selectDistributionCertificateAsync(validDistCerts);
}
@@ -1,45 +0,0 @@
import isEqual from 'lodash/isEqual';
import { AppleDistributionCertificateFragment } from '../../../../graphql/generated';
import Log from '../../../../log';
import { AppleDeviceFragmentWithAppleTeam } from '../../api/graphql/queries/AppleDeviceQuery';
import { ProvisioningProfileStoreInfo } from '../../appstore/Credentials.types';
export function isDevPortalAdhocProfileValid(
profileFromDevPortal: ProvisioningProfileStoreInfo | null,
distCert: AppleDistributionCertificateFragment,
expectedDevices: AppleDeviceFragmentWithAppleTeam[]
): boolean {
if (!profileFromDevPortal) {
return false;
}
if (profileFromDevPortal.status === 'Invalid' || profileFromDevPortal.certificates.length === 0) {
Log.log('Provisioning Profile is invalid');
return false;
}
const currentDistCertId = profileFromDevPortal.certificates[0].id;
if (
distCert.developerPortalIdentifier &&
distCert.developerPortalIdentifier !== currentDistCertId
) {
Log.log(
`Provisioning Profile was generated for Distribution Certificate with ID "${currentDistCertId}", expected ID "${distCert.developerPortalIdentifier}"`
);
return false;
}
const profileDeviceUdids = (profileFromDevPortal.devices ?? []).map(({ udid }) => udid);
const expectedDeviceUdids = expectedDevices.map(({ identifier }) => identifier);
if (!doUDIDsMatch(profileDeviceUdids, expectedDeviceUdids)) {
Log.log('Provisioning Profile was generated for another set of devices');
return false;
}
return true;
}
export function doUDIDsMatch(udidsA: string[], udidsB: string[]): boolean {
return isEqual(new Set(udidsA), new Set(udidsB));
}
@@ -1,90 +0,0 @@
import {
AppleDistributionCertificateFragment,
AppleProvisioningProfileIdentifiersFragment,
} from '../../../../graphql/generated';
import Log from '../../../../log';
import { confirmAsync } from '../../../../prompts';
import { Account } from '../../../../user/Account';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
import { selectDistributionCertificateWithDependenciesAsync } from './DistributionCertificateUtils';
import { RemoveProvisioningProfiles } from './RemoveProvisioningProfile';
export class SelectAndRemoveDistributionCertificate {
constructor(private account: Account) {}
async runAsync(ctx: Context): Promise<void> {
const selected = await selectDistributionCertificateWithDependenciesAsync(ctx, this.account);
if (selected) {
await new RemoveDistributionCertificate(this.account, selected).runAsync(ctx);
Log.succeed('Removed distribution certificate');
Log.newLine();
}
}
}
export class RemoveDistributionCertificate {
constructor(
private account: Account,
private distributionCertificate: AppleDistributionCertificateFragment
) {}
public async runAsync(ctx: Context): Promise<void> {
const apps = this.distributionCertificate.iosAppBuildCredentialsList.map(
buildCredentials => buildCredentials.iosAppCredentials.app
);
if (apps.length !== 0) {
const appFullNames = apps.map(app => app.fullName).join(',');
if (ctx.nonInteractive) {
throw new Error(
`Certificate is currently used by ${appFullNames} and cannot be deleted in non-interactive mode.`
);
}
const confirm = await confirmAsync({
message: `You are removing certificate used by ${appFullNames}. Do you want to continue?`,
});
if (!confirm) {
Log.log('Aborting');
return;
}
}
Log.log('Removing Distribution Certificate');
await ctx.newIos.deleteDistributionCertificateAsync(this.distributionCertificate.id);
if (this.distributionCertificate.developerPortalIdentifier) {
let shouldRevoke = false;
if (!ctx.nonInteractive) {
shouldRevoke = await confirmAsync({
message: `Do you also want to revoke this Distribution Certificate on Apple Developer Portal?`,
});
} else if (ctx.nonInteractive) {
Log.log('Skipping certificate revocation on the Apple Developer Portal.');
}
if (shouldRevoke) {
await ctx.appStore.revokeDistributionCertificateAsync([
this.distributionCertificate.developerPortalIdentifier,
]);
}
}
await this.removeInvalidProvisioningProfilesAsync(ctx);
}
private async removeInvalidProvisioningProfilesAsync(ctx: Context): Promise<void> {
const buildCredentialsList = this.distributionCertificate.iosAppBuildCredentialsList;
const appsWithProfilesToRemove: AppLookupParams[] = [];
const profilesToRemove: AppleProvisioningProfileIdentifiersFragment[] = [];
for (const buildCredentials of buildCredentialsList) {
const projectName = buildCredentials.iosAppCredentials.app.slug;
const { bundleIdentifier } = buildCredentials.iosAppCredentials.appleAppIdentifier;
const appLookupParams = { account: this.account, projectName, bundleIdentifier };
const maybeProvisioningProfile = buildCredentials.provisioningProfile;
if (maybeProvisioningProfile) {
appsWithProfilesToRemove.push(appLookupParams);
profilesToRemove.push(maybeProvisioningProfile);
}
}
await new RemoveProvisioningProfiles(appsWithProfilesToRemove, profilesToRemove).runAsync(ctx);
}
}
@@ -1,32 +0,0 @@
import { assert } from '@expo/config';
import { AppleProvisioningProfileIdentifiersFragment } from '../../../../graphql/generated';
import Log from '../../../../log';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
export class RemoveProvisioningProfiles {
constructor(
private apps: AppLookupParams[],
private provisioningProfiles: AppleProvisioningProfileIdentifiersFragment[]
) {
assert(
apps.length === provisioningProfiles.length,
'apps must correspond to the provisioning profiles being removed'
);
}
async runAsync(ctx: Context): Promise<void> {
if (this.provisioningProfiles.length === 0) {
Log.log(`Skipping deletion of Provisioning Profiles`);
return;
}
await ctx.newIos.deleteProvisioningProfilesAsync(
this.provisioningProfiles.map(profile => profile.id)
);
const appAndBundles = this.apps
.map(app => `@${app.account.name}/${app.projectName} (${app.bundleIdentifier})`)
.join(',');
Log.succeed(`Successfully removed provisioning profiles for ${appAndBundles}`);
}
}
@@ -1,184 +0,0 @@
import nullthrows from 'nullthrows';
import {
AppleDevice,
IosAppBuildCredentialsFragment,
IosDistributionType,
} from '../../../../graphql/generated';
import Log from '../../../../log';
import { confirmAsync } from '../../../../prompts';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
import { AppleProvisioningProfileMutationResult } from '../../api/graphql/mutations/AppleProvisioningProfileMutation';
import { AppleDeviceFragmentWithAppleTeam } from '../../api/graphql/queries/AppleDeviceQuery';
import { AppleProvisioningProfileQueryResult } from '../../api/graphql/queries/AppleProvisioningProfileQuery';
import { ProvisioningProfileStoreInfo } from '../../appstore/Credentials.types';
import { ProfileClass } from '../../appstore/provisioningProfile';
import { AppleTeamMissingError, MissingCredentialsNonInteractiveError } from '../../errors';
import { resolveAppleTeamIfAuthenticatedAsync } from './AppleTeamUtils';
import { chooseDevices } from './DeviceUtils';
import { doUDIDsMatch, isDevPortalAdhocProfileValid } from './ProvisioningProfileUtils';
import { SetupDistributionCertificate } from './SetupDistributionCertificate';
export class SetupAdhocProvisioningProfile {
constructor(private app: AppLookupParams) {}
async runAsync(ctx: Context): Promise<IosAppBuildCredentialsFragment> {
if (ctx.nonInteractive) {
try {
return await this.runNonInteractiveAsync(ctx);
} catch (err) {
if (err instanceof AppleTeamMissingError) {
throw new MissingCredentialsNonInteractiveError();
}
throw err;
}
} else {
return await this.runInteractiveAsync(ctx);
}
}
private async runNonInteractiveAsync(ctx: Context): Promise<IosAppBuildCredentialsFragment> {
// 1. Setup Distribution Certificate
await new SetupDistributionCertificate(this.app, IosDistributionType.AdHoc).runAsync(ctx);
// 2. Fetch profile from EAS servers
const currentProfile = await ctx.newIos.getProvisioningProfileAsync(
this.app,
IosDistributionType.AdHoc
);
if (!currentProfile) {
throw new MissingCredentialsNonInteractiveError();
}
// TODO: implement validation
Log.warn(
'Provisioning Profile is not validated for non-interactive internal distribution builds.'
);
// app credentials should exist here because the profile exists
const appCredentials = nullthrows(
await ctx.newIos.getIosAppCredentialsWithBuildCredentialsAsync(this.app, {
iosDistributionType: IosDistributionType.AdHoc,
})
);
return appCredentials.iosAppBuildCredentialsArray[0];
}
private async runInteractiveAsync(ctx: Context): Promise<IosAppBuildCredentialsFragment> {
// 0. Ensure the user is authenticated with Apple and resolve the Apple team object
await ctx.appStore.ensureAuthenticatedAsync();
const appleTeam = nullthrows(await resolveAppleTeamIfAuthenticatedAsync(ctx, this.app));
// 1. Fetch devices registered on EAS servers
const registeredAppleDevices = await ctx.newIos.getDevicesForAppleTeamAsync(
this.app,
appleTeam
);
const registeredAppleDeviceIdentifiers = registeredAppleDevices.map(
({ identifier }) => identifier
);
if (registeredAppleDeviceIdentifiers.length === 0) {
throw new Error(`Run 'eas device:create' to register your devices first`);
}
// 2. Setup Distribution Certificate
const distCert = await new SetupDistributionCertificate(
this.app,
IosDistributionType.AdHoc
).runAsync(ctx);
let profileFromExpoServersToUse:
| AppleProvisioningProfileQueryResult
| AppleProvisioningProfileMutationResult
| null = await ctx.newIos.getProvisioningProfileAsync(this.app, IosDistributionType.AdHoc, {
appleTeam,
});
// 4. Choose devices for internal distribution
let chosenDevices: AppleDeviceFragmentWithAppleTeam[];
if (profileFromExpoServersToUse) {
const appleDeviceIdentifiersFromProfile = ((profileFromExpoServersToUse.appleDevices ??
[]) as AppleDevice[]).map(({ identifier }) => identifier);
let shouldAskToChooseDevices = true;
if (doUDIDsMatch(appleDeviceIdentifiersFromProfile, registeredAppleDeviceIdentifiers)) {
shouldAskToChooseDevices = await confirmAsync({
message: `All your registered devices are present in the Provisioning Profile. Would you like to exclude some devices?`,
initial: false,
});
}
chosenDevices = shouldAskToChooseDevices
? await chooseDevices(registeredAppleDevices, appleDeviceIdentifiersFromProfile)
: registeredAppleDevices;
} else {
chosenDevices = await chooseDevices(registeredAppleDevices);
}
// 5. Try to find the profile on Apple Developer Portal
const currentProfileFromDevPortal = await this.getProfileFromDevPortalAsync(ctx);
// 6. Validate the profile and possibly recreate it
let profileToUse: ProvisioningProfileStoreInfo;
let profileWasRecreated = false;
if (isDevPortalAdhocProfileValid(currentProfileFromDevPortal, distCert, chosenDevices)) {
profileToUse = nullthrows(currentProfileFromDevPortal);
} else {
const chosenDeviceUDIDs = chosenDevices.map(({ identifier }) => identifier);
await ctx.appStore.createOrReuseAdhocProvisioningProfileAsync(
chosenDeviceUDIDs,
this.app.bundleIdentifier,
distCert.serialNumber
);
profileToUse = nullthrows(await this.getProfileFromDevPortalAsync(ctx));
profileWasRecreated = true;
}
// 7. Send profile to www if new has been created
const appleAppIdentifier = await ctx.newIos.createOrGetExistingAppleAppIdentifierAsync(
this.app,
appleTeam
);
if (profileFromExpoServersToUse) {
if (profileWasRecreated) {
profileFromExpoServersToUse = await ctx.newIos.updateProvisioningProfileAsync(
profileFromExpoServersToUse.id,
{
appleProvisioningProfile: profileToUse.provisioningProfile,
developerPortalIdentifier: profileToUse.provisioningProfileId,
}
);
}
} else {
profileFromExpoServersToUse = await ctx.newIos.createProvisioningProfileAsync(
this.app,
appleAppIdentifier,
{
appleProvisioningProfile: profileToUse.provisioningProfile,
developerPortalIdentifier: profileToUse.provisioningProfileId,
}
);
}
// 8. Create (or update) app build credentials
return await ctx.newIos.createOrUpdateIosAppBuildCredentialsAsync(this.app, {
appleTeam,
appleAppIdentifierId: appleAppIdentifier.id,
appleDistributionCertificateId: distCert.id,
appleProvisioningProfileId: profileFromExpoServersToUse.id,
iosDistributionType: IosDistributionType.AdHoc,
});
}
private async getProfileFromDevPortalAsync(
ctx: Context
): Promise<ProvisioningProfileStoreInfo | null> {
const profilesFromDevPortal = await ctx.appStore.listProvisioningProfilesAsync(
this.app.bundleIdentifier,
ProfileClass.Adhoc
);
return profilesFromDevPortal.length >= 1 ? profilesFromDevPortal[0] : null;
}
}
@@ -1,12 +0,0 @@
import { IosAppBuildCredentialsFragment } from '../../../../graphql/generated';
import { Context } from '../../../context';
import { AppLookupParams } from '../../api/GraphqlClient';
import { SetupAdhocProvisioningProfile } from './SetupAdhocProvisioningProfile';
export class SetupInternalProvisioningProfile {
constructor(private app: AppLookupParams) {}
async runAsync(ctx: Context): Promise<IosAppBuildCredentialsFragment> {
return await new SetupAdhocProvisioningProfile(this.app).runAsync(ctx);
}
}
@@ -1,382 +0,0 @@
import assert from 'assert';
import keyBy from 'lodash/keyBy';
import omit from 'lodash/omit';
import pick from 'lodash/pick';
import {
DistributionCertificate,
ProvisioningProfile,
PushKey,
} from '../appstore/Credentials.types';
import {
AppLookupParams,
IosAppCredentials,
IosCredentials,
IosDistCredentials,
IosPushCredentials,
} from '../credentials';
import ApiClient from './ClientWrapper';
type CredentialFields = {
credentials: { [key: string]: any };
};
// appCredentials are identified by `${projectFullName} ${bundleIdentifier}` (see getAppCredentialsCacheIndex method)
// userCredentials are identified by id (string or numeric depending on API)
//
// Expected behavior of cache (internals)
//
// - when isPrefetched[accountName] true assume everything is synced for that account
// - when credentials[accountName].appCredentials[experienceNameBundleIdentifier] is truthy assume that user and app credentials for that app are synced
// - when accessing user or app credentials identified by AppLookupParams fetch all credentials for that app (user and app credentials)
// - when updating userCredentials refetch only userCredentials
// - when deleting userCredentials modify prefetched appCredentials without calling api
// - when updating provisioningProfile refetch all credentials for that app (user and app credentials)
// - when deleting provisioningProfile modify appCredentials in cache
// - when deleting pushCert refetch all credentials for app (app + user)
//
//
interface CredentialsCache {
[accountName: string]: {
appCredentials: {
[experienceNameBundleIdentifier: string]: IosAppCredentials;
};
userCredentials: {
[id: string]: IosDistCredentials | IosPushCredentials;
};
};
}
export default class IosApi {
client = new ApiClient();
credentials: CredentialsCache = {};
isPrefetched: { [accountName: string]: boolean } = {};
public async getAllCredentialsAsync(accountName: string): Promise<IosCredentials> {
if (!this.isPrefetched[accountName]) {
const credentials = await this.client.getAllCredentialsApi(accountName);
this.credentials[accountName] = {
appCredentials: keyBy(
credentials.appCredentials,
cred => `${cred.experienceName} ${cred.bundleIdentifier}`
),
userCredentials: keyBy(credentials.userCredentials, cred => String(cred.id)),
};
this.isPrefetched[accountName] = true;
}
return {
appCredentials: Object.values(this.credentials[accountName]?.appCredentials ?? {}),
userCredentials: Object.values(this.credentials[accountName]?.userCredentials ?? {}),
};
}
public async getDistributionCertificateAsync(
appLookupParams: AppLookupParams
): Promise<IosDistCredentials | null> {
await this.ensureAppCredentialsAsync(appLookupParams);
const appCredentialsIndex = this.getAppCredentialsCacheIndex(appLookupParams);
const { accountName } = appLookupParams;
const appCredentials = this.credentials[accountName]?.appCredentials?.[appCredentialsIndex];
if (!appCredentials || !appCredentials.distCredentialsId) {
return null;
}
const distCert = this.credentials[accountName]?.userCredentials?.[
appCredentials.distCredentialsId
] as IosDistCredentials | null;
return distCert ?? null;
}
public async getDistributionCertificateByIdAsync(
id: string | number,
accountName: string
): Promise<IosDistCredentials> {
if (!this.credentials[accountName]?.userCredentials?.[String(id)]) {
await this.refetchUserCredentialsAsync(id, accountName);
}
const distCert = this.credentials[accountName]?.userCredentials?.[String(id)];
assert(id && distCert, 'distribution certificate does not exists');
assert(distCert.type === 'dist-cert', 'wrong type of user credential');
return distCert as IosDistCredentials;
}
public async createDistributionCertificateAsync(
accountName: string,
credentials: DistributionCertificate
): Promise<IosDistCredentials> {
const id = await this.client.createDistributionCertificateApi(accountName, credentials);
// refetching because www might add some fields (e.g. certSerialNumber)
await this.refetchUserCredentialsAsync(id, accountName);
const distCert = this.credentials[accountName]?.userCredentials?.[String(id)];
assert(id && distCert, 'distribution certificate does not exists');
assert(distCert.type === 'dist-cert', 'wrong type of user credential');
return distCert as IosDistCredentials;
}
public async updateDistributionCertificateAsync(
id: number | string,
accountName: string,
credentials: DistributionCertificate
): Promise<IosDistCredentials> {
await this.client.updateDistributionCertificateApi(id, accountName, credentials);
// refetching because www might add some fields (e.g. certSerialNumber)
await this.refetchUserCredentialsAsync(id, accountName);
const distCert = this.credentials[accountName]?.userCredentials[String(id)];
assert(distCert, 'distribution certificate does not exists');
assert(distCert.type === 'dist-cert', 'wrong type of user credential');
return distCert as IosDistCredentials;
}
public async deleteDistributionCertificateAsync(
id: number | string,
accountName: string
): Promise<void> {
await this.client.deleteDistributionCertificateApi(id, accountName);
await this.removeUserCredentialFromCache(id, accountName);
}
public async useDistributionCertificateAsync(
appLookupParams: AppLookupParams,
userCredentialsId: number | string
): Promise<void> {
await this.client.useDistributionCertificateApi(appLookupParams, userCredentialsId);
await this.refetchAppCredentialsAsync(appLookupParams);
}
public async createPushKeyAsync(
accountName: string,
credentials: PushKey
): Promise<IosPushCredentials> {
const id = await this.client.createPushKeyApi(accountName, credentials);
await this.refetchUserCredentialsAsync(id, accountName);
const pushKey = this.credentials[accountName]?.userCredentials?.[String(id)];
assert(id && pushKey, 'push key does not exists');
assert(pushKey.type === 'push-key', 'wrong type of user credentials');
return pushKey;
}
public async updatePushKeyAsync(
id: number | string,
accountName: string,
credentials: PushKey
): Promise<IosPushCredentials> {
await this.client.updatePushKeyApi(id, accountName, credentials);
await this.refetchUserCredentialsAsync(id, accountName);
const pushKey = this.credentials[accountName]?.userCredentials?.[String(id)];
assert(id && pushKey, 'push key does not exists');
assert(pushKey.type === 'push-key', 'wrong type of user credentials');
return pushKey;
}
public async deletePushKeyAsync(id: number | string, accountName: string) {
await this.client.deletePushKeyApi(id, accountName);
await this.removeUserCredentialFromCache(id, accountName);
}
public async getPushKeyAsync(
appLookupParams: AppLookupParams
): Promise<IosPushCredentials | null> {
await this.ensureAppCredentialsAsync(appLookupParams);
const appCredentialsIndex = this.getAppCredentialsCacheIndex(appLookupParams);
const { accountName } = appLookupParams;
const appCredentials = this.credentials[accountName]?.appCredentials?.[appCredentialsIndex];
if (!appCredentials || !appCredentials.pushCredentialsId) {
return null;
}
const pushKey = this.credentials[accountName]?.userCredentials?.[
appCredentials.pushCredentialsId
] as IosPushCredentials | null;
return pushKey ?? null;
}
public async usePushKeyAsync(
appLookupParams: AppLookupParams,
userCredentialsId: number | string
): Promise<void> {
await this.client.usePushKeyApi(appLookupParams, userCredentialsId);
await this.refetchAppCredentialsAsync(appLookupParams);
}
public async getPushCertAsync(
appLookupParams: AppLookupParams
): Promise<{ pushId: string; pushP12: string; pushPassword: string } | null> {
const appCredentials = await this.getAppCredentialsAsync(appLookupParams);
const pushId = appCredentials?.credentials?.pushId;
const pushP12 = appCredentials?.credentials?.pushP12;
const pushPassword = appCredentials?.credentials?.pushPassword;
if (!pushId || !pushP12 || !pushPassword) {
return null;
}
return { pushId, pushP12, pushPassword };
}
public async deletePushCertAsync(appLookupParams: AppLookupParams): Promise<void> {
await this.client.deletePushCertApi(appLookupParams);
await this.refetchAppCredentialsAsync(appLookupParams);
}
public async getAppCredentialsAsync(
appLookupParams: AppLookupParams
): Promise<IosAppCredentials> {
const appCredentialsIndex = this.getAppCredentialsCacheIndex(appLookupParams);
const { accountName } = appLookupParams;
await this.ensureAppCredentialsAsync(appLookupParams);
return this.credentials[accountName]?.appCredentials?.[appCredentialsIndex];
}
public async getProvisioningProfileAsync(
appLookupParams: AppLookupParams
): Promise<ProvisioningProfile | null> {
const appCredentials = await this.getAppCredentialsAsync(appLookupParams);
const provisioningProfile = appCredentials?.credentials?.provisioningProfile;
if (!provisioningProfile) {
return null;
}
return pick(appCredentials.credentials, [
'provisioningProfile',
'provisioningProfileId',
'teamId',
'teamName',
]) as ProvisioningProfile;
}
public async updateProvisioningProfileAsync(
appLookupParams: AppLookupParams,
provisioningProfile: ProvisioningProfile
): Promise<ProvisioningProfile> {
const appCredentialsIndex = this.getAppCredentialsCacheIndex(appLookupParams);
const { accountName } = appLookupParams;
await this.client.updateProvisioningProfileApi(appLookupParams, provisioningProfile);
await this.refetchAppCredentialsAsync(appLookupParams);
return pick(this.credentials[accountName]?.appCredentials?.[appCredentialsIndex]?.credentials, [
'provisioningProfile',
'provisioningProfileId',
'teamId',
'teamName',
]) as ProvisioningProfile;
}
public async deleteProvisioningProfileAsync(appLookupParams: AppLookupParams): Promise<void> {
const appCredentialsIndex = this.getAppCredentialsCacheIndex(appLookupParams);
const { accountName } = appLookupParams;
await this.client.deleteProvisioningProfileApi(appLookupParams);
const appCredentials = this.credentials?.[accountName]?.appCredentials?.[appCredentialsIndex];
if (appCredentials?.credentials) {
// teamId should still be there because it might be part of push cert definition
appCredentials.credentials = omit(appCredentials.credentials, [
'provisioningProfile',
'provisioningProfileId',
]);
}
}
private getAppCredentialsCacheIndex(appLookupParams: AppLookupParams): string {
const { accountName, projectName, bundleIdentifier } = appLookupParams;
const projectFullName = `@${accountName}/${projectName}`;
return `${projectFullName} ${bundleIdentifier}`;
}
private removeUserCredentialFromCache(id: number | string, accountName: string): void {
if (this.credentials[accountName]?.userCredentials?.[String(id)]) {
delete this.credentials[accountName].userCredentials[String(id)];
}
const appCredentials = this.credentials[accountName]?.appCredentials;
if (appCredentials) {
for (const cred of Object.values(appCredentials)) {
if (cred.distCredentialsId === id) {
delete cred.distCredentialsId;
}
if (cred.pushCredentialsId === id) {
delete cred.pushCredentialsId;
}
}
}
}
// ensures that credentials are fetched from the server if they exist
// if there are no credentials on server for specific app this function should still succeed
private async ensureAppCredentialsAsync(appLookupParams: AppLookupParams): Promise<void> {
const appCredentialsIndex = this.getAppCredentialsCacheIndex(appLookupParams);
const { accountName } = appLookupParams;
if (
this.isPrefetched[accountName] ||
this.credentials?.[accountName]?.appCredentials?.[appCredentialsIndex]
) {
return;
}
await this.refetchAppCredentialsAsync(appLookupParams);
}
private async refetchUserCredentialsAsync(
id: number | string,
accountName: string
): Promise<void> {
const userCredentials = await this.client.getUserCredentialsByIdApi(id, accountName);
if (!userCredentials || !userCredentials.id) {
return;
}
this.credentials[accountName] = {
...this.credentials[accountName],
userCredentials: {
...this.credentials[accountName]?.userCredentials,
[String(id)]: userCredentials,
},
};
}
private async refetchAppCredentialsAsync(app: AppLookupParams): Promise<void> {
const { accountName } = app;
const appCredentialsIndex = this.getAppCredentialsCacheIndex(app);
const data = await this.client.getAllCredentialsForAppApi(app);
if (!data) {
return;
}
this.credentials[accountName] = {
appCredentials: {
...this.credentials[accountName]?.appCredentials,
[appCredentialsIndex]: omit(data, [
'pushCredentials',
'distCredentials',
]) as IosAppCredentials,
},
userCredentials: {
...this.credentials[accountName]?.userCredentials,
...(data.pushCredentialsId
? {
[String(data.pushCredentialsId)]: {
...data.pushCredentials,
id: data.pushCredentialsId,
type: 'push-key',
},
}
: {}),
...(data.distCredentialsId
? {
[String(data.distCredentialsId)]: {
...data.distCredentials,
id: data.distCredentialsId,
type: 'dist-cert',
},
}
: {}),
},
};
}
}
@@ -1,188 +0,0 @@
import { apiClient } from '../../../api';
import {
DistributionCertificate,
ProvisioningProfile,
PushKey,
} from '../appstore/Credentials.types';
import { IosAppCredentials, IosDistCredentials, IosPushCredentials } from '../credentials';
export interface AppLookupParams {
accountName: string;
projectName: string;
bundleIdentifier: string;
}
interface IosAllCredentialsForApp extends IosAppCredentials {
pushCredentials: Omit<IosPushCredentials, 'id' | 'type'>;
distCredentials: Omit<IosDistCredentials, 'id' | 'type'>;
}
interface AllCredentialsApiResponse {
appCredentials: IosAppCredentials[];
userCredentials: (IosDistCredentials | IosPushCredentials)[];
}
// This class should not be used directly, use only as part of cached api client from ./Client.ts
// or mock it in tests (it's easier to mock this class than got directly)
export default class ApiClient {
public async getAllCredentialsApi(accountName: string): Promise<AllCredentialsApiResponse> {
const response: any = await apiClient
.get('credentials/ios', { searchParams: { owner: accountName } })
.json();
return response.data;
}
public async getAllCredentialsForAppApi({
accountName,
projectName,
bundleIdentifier,
}: AppLookupParams): Promise<IosAllCredentialsForApp> {
const response: any = await apiClient
.get(`credentials/ios/@${accountName}/${projectName}/${bundleIdentifier}`)
.json();
return response.data;
}
public async getUserCredentialsByIdApi(
id: number | string,
accountName: string
): Promise<IosDistCredentials | IosPushCredentials> {
const response: any = await apiClient
.get(`credentials/ios/userCredentials/${id}`, { searchParams: { owner: accountName } })
.json();
return response.data;
}
public async createDistributionCertificateApi(
accountName: string,
credentials: DistributionCertificate
): Promise<number | string> {
const response: any = await apiClient
.post('credentials/ios/dist', {
json: {
owner: accountName,
credentials,
},
})
.json();
return response.data?.id;
}
public async updateDistributionCertificateApi(
id: number | string,
accountName: string,
credentials: DistributionCertificate
): Promise<void> {
await apiClient.put(`credentials/ios/dist/${id}`, {
json: { credentials, owner: accountName },
});
}
public async deleteDistributionCertificateApi(
id: number | string,
accountName: string
): Promise<void> {
await apiClient.delete(`credentials/ios/dist/${id}`, { searchParams: { owner: accountName } });
}
public async useDistributionCertificateApi(
{ accountName, projectName, bundleIdentifier }: AppLookupParams,
userCredentialsId: number | string
): Promise<void> {
await apiClient.post('credentials/ios/use/dist', {
json: {
experienceName: `@${accountName}/${projectName}`,
owner: accountName,
bundleIdentifier,
userCredentialsId,
},
});
}
public async createPushKeyApi(
accountName: string,
credentials: PushKey
): Promise<number | string> {
const response: any = await apiClient
.post('credentials/ios/push', {
json: {
owner: accountName,
credentials,
},
})
.json();
return response.data?.id;
}
public async updatePushKeyApi(
id: number | string,
accountName: string,
credentials: PushKey
): Promise<IosPushCredentials> {
const response: any = await apiClient
.put(`credentials/ios/push/${id}`, {
json: { owner: accountName },
})
.json();
return response.data;
}
public async deletePushKeyApi(id: number | string, accountName: string): Promise<void> {
await apiClient.delete(`credentials/ios/push/${id}`, { searchParams: { owner: accountName } });
}
public async usePushKeyApi(
{ accountName, projectName, bundleIdentifier }: AppLookupParams,
userCredentialsId: number | string
): Promise<void> {
await apiClient.post('credentials/ios/use/push', {
json: {
experienceName: `@${accountName}/${projectName}`,
owner: accountName,
bundleIdentifier,
userCredentialsId,
},
});
}
public async deletePushCertApi({
accountName,
projectName,
bundleIdentifier,
}: AppLookupParams): Promise<void> {
await apiClient.post(`credentials/ios/pushCert/delete`, {
json: {
experienceName: `@${accountName}/${projectName}`,
owner: accountName,
bundleIdentifier,
},
});
}
public async updateProvisioningProfileApi(
{ accountName, projectName, bundleIdentifier }: AppLookupParams,
credentials: ProvisioningProfile
): Promise<void> {
await apiClient.post(`credentials/ios/provisioningProfile/update`, {
json: {
experienceName: `@${accountName}/${projectName}`,
owner: accountName,
bundleIdentifier,
credentials,
},
});
}
public async deleteProvisioningProfileApi({
accountName,
projectName,
bundleIdentifier,
}: AppLookupParams): Promise<void> {
await apiClient.post(`credentials/ios/provisioningProfile/delete`, {
json: {
experienceName: `@${accountName}/${projectName}`,
owner: accountName,
bundleIdentifier,
},
});
}
}
@@ -3,6 +3,7 @@ import nullthrows from 'nullthrows';
import {
AppFragment,
AppleAppIdentifierFragment,
AppleDeviceFragment,
AppleDistributionCertificateFragment,
AppleTeamFragment,
CommonIosAppCredentialsFragment,
@@ -26,10 +27,7 @@ import { IosAppBuildCredentialsMutation } from './graphql/mutations/IosAppBuildC
import { IosAppCredentialsMutation } from './graphql/mutations/IosAppCredentialsMutation';
import { AppQuery } from './graphql/queries/AppQuery';
import { AppleAppIdentifierQuery } from './graphql/queries/AppleAppIdentifierQuery';
import {
AppleDeviceFragmentWithAppleTeam,
AppleDeviceQuery,
} from './graphql/queries/AppleDeviceQuery';
import { AppleDeviceQuery } from './graphql/queries/AppleDeviceQuery';
import { AppleDistributionCertificateQuery } from './graphql/queries/AppleDistributionCertificateQuery';
import {
AppleProvisioningProfileQuery,
@@ -47,7 +45,7 @@ export interface AppLookupParams {
bundleIdentifier: string;
}
export async function getAppAsync(appLookupParams: AppLookupParams): Promise<AppFragment> {
async function getAppAsync(appLookupParams: AppLookupParams): Promise<AppFragment> {
const projectFullName = formatProjectFullName(appLookupParams);
return await AppQuery.byFullNameAsync(projectFullName);
}
@@ -76,7 +74,7 @@ export async function createOrUpdateIosAppBuildCredentialsAsync(
iosDistributionType,
}
);
const iosAppBuildCredentials = iosAppCredentials.iosAppBuildCredentialsArray?.[0];
const iosAppBuildCredentials = iosAppCredentials.iosAppBuildCredentialsList?.[0];
if (!iosAppBuildCredentials) {
return await IosAppBuildCredentialsMutation.createIosAppBuildCredentialsAsync(
{
@@ -100,7 +98,7 @@ export async function createOrUpdateIosAppBuildCredentialsAsync(
export async function getIosAppCredentialsWithBuildCredentialsAsync(
appLookupParams: AppLookupParams,
{ iosDistributionType }: { iosDistributionType: IosDistributionType }
{ iosDistributionType }: { iosDistributionType?: IosDistributionType }
): Promise<IosAppCredentialsWithBuildCredentialsQueryResult | null> {
const { account, bundleIdentifier } = appLookupParams;
const appleAppIdentifier = await AppleAppIdentifierQuery.byBundleIdentifierAsync(
@@ -175,7 +173,7 @@ export async function createOrGetExistingIosAppCredentialsWithBuildCredentialsAs
}
export async function createOrGetExistingAppleTeamAsync(
{ account }: AppLookupParams,
account: Account,
{ appleTeamIdentifier, appleTeamName }: { appleTeamIdentifier: string; appleTeamName?: string }
): Promise<AppleTeamFragment> {
const appleTeam = await AppleTeamQuery.getByAppleTeamIdentifierAsync(
@@ -215,9 +213,12 @@ export async function createOrGetExistingAppleAppIdentifierAsync(
export async function getDevicesForAppleTeamAsync(
{ account }: AppLookupParams,
{ appleTeamIdentifier }: AppleTeamFragment
): Promise<AppleDeviceFragmentWithAppleTeam[]> {
return await AppleDeviceQuery.getAllByAppleTeamIdentifierAsync(account.id, appleTeamIdentifier);
{ appleTeamIdentifier }: AppleTeamFragment,
{ useCache = true }: { useCache?: boolean } = {}
): Promise<AppleDeviceFragment[]> {
return await AppleDeviceQuery.getAllByAppleTeamIdentifierAsync(account.id, appleTeamIdentifier, {
useCache,
});
}
export async function createProvisioningProfileAsync(
@@ -295,14 +296,13 @@ export async function getDistributionCertificatesForAccountAsync(
}
export async function createDistributionCertificateAsync(
appLookupParams: AppLookupParams,
account: Account,
distCert: DistributionCertificate
): Promise<AppleDistributionCertificateMutationResult> {
const appleTeam = await createOrGetExistingAppleTeamAsync(appLookupParams, {
const appleTeam = await createOrGetExistingAppleTeamAsync(account, {
appleTeamIdentifier: distCert.teamId,
appleTeamName: distCert.teamName,
});
const { account } = appLookupParams;
return await AppleDistributionCertificateMutation.createAppleDistributionCertificate(
{
certP12: distCert.certP12,
@@ -82,6 +82,9 @@ const AppleDistributionCertificateMutation = {
`,
{
appleDistributionCertificateId,
},
{
additionalTypenames: ['AppleDistributionCertificate'],
}
)
.toPromise()
@@ -117,6 +117,9 @@ const AppleProvisioningProfileMutation = {
`,
{
appleProvisioningProfileIds,
},
{
additionalTypenames: ['AppleProvisioningProfile'],
}
)
.toPromise()
@@ -34,7 +34,8 @@ export type AppleDevicesByIdentifierQueryResult = AppleDeviceQueryResult & {
const AppleDeviceQuery = {
async getAllByAppleTeamIdentifierAsync(
accountId: string,
appleTeamIdentifier: string
appleTeamIdentifier: string,
{ useCache = true }: { useCache?: boolean } = {}
): Promise<AppleDeviceFragmentWithAppleTeam[]> {
const data = await withErrorHandlingAsync(
graphqlClient
@@ -63,7 +64,10 @@ const AppleDeviceQuery = {
accountId,
appleTeamIdentifier,
},
{ additionalTypenames: ['AppleDevice'] }
{
additionalTypenames: ['AppleDevice'],
requestPolicy: useCache ? 'cache-first' : 'network-only',
}
)
.toPromise()
);
@@ -34,7 +34,7 @@ const AppleDistributionCertificateQuery = {
id
iosAppCredentials(filter: { appleAppIdentifierId: $appleAppIdentifierId }) {
id
iosAppBuildCredentialsArray(
iosAppBuildCredentialsList(
filter: { iosDistributionType: $iosDistributionType }
) {
id
@@ -67,7 +67,7 @@ const AppleDistributionCertificateQuery = {
);
assert(data.app, 'GraphQL: `app` not defined in server response');
return (
data.app.byFullName.iosAppCredentials[0]?.iosAppBuildCredentialsArray[0]
data.app.byFullName.iosAppCredentials[0]?.iosAppBuildCredentialsList[0]
?.distributionCertificate ?? null
);
},
@@ -41,7 +41,7 @@ const AppleProvisioningProfileQuery = {
id
iosAppCredentials(filter: { appleAppIdentifierId: $appleAppIdentifierId }) {
id
iosAppBuildCredentialsArray(
iosAppBuildCredentialsList(
filter: { iosDistributionType: $iosDistributionType }
) {
id
@@ -84,7 +84,7 @@ const AppleProvisioningProfileQuery = {
);
assert(data.app, 'GraphQL: `app` not defined in server response');
return (
data.app.byFullName.iosAppCredentials[0]?.iosAppBuildCredentialsArray[0]
data.app.byFullName.iosAppCredentials[0]?.iosAppBuildCredentialsList[0]
?.provisioningProfile ?? null
);
},
@@ -32,7 +32,7 @@ const IosAppBuildCredentialsQuery = {
id
iosAppCredentials(filter: { appleAppIdentifierId: $appleAppIdentifierId }) {
id
iosAppBuildCredentialsArray(
iosAppBuildCredentialsList(
filter: { iosDistributionType: $iosDistributionType }
) {
id
@@ -56,7 +56,7 @@ const IosAppBuildCredentialsQuery = {
.toPromise()
);
assert(data.app, 'GraphQL: `app` not defined in server response');
return data.app.byFullName.iosAppCredentials[0]?.iosAppBuildCredentialsArray[0] ?? null;
return data.app.byFullName.iosAppCredentials[0]?.iosAppBuildCredentialsList[0] ?? null;
},
};
@@ -19,7 +19,7 @@ import {
} from '../../../../../graphql/types/credentials/IosAppCredentials';
export type IosAppCredentialsWithBuildCredentialsQueryResult = IosAppCredentialsFragment & {
iosAppBuildCredentialsArray: IosAppBuildCredentialsFragment[];
iosAppBuildCredentialsList: IosAppBuildCredentialsFragment[];
};
const IosAppCredentialsQuery = {
async byAppIdentifierIdAsync(
@@ -66,7 +66,7 @@ const IosAppCredentialsQuery = {
iosDistributionType,
}: {
appleAppIdentifierId: string;
iosDistributionType: IosDistributionType;
iosDistributionType?: IosDistributionType;
}
): Promise<IosAppCredentialsWithBuildCredentialsQueryResult | null> {
const data = await withErrorHandlingAsync(
@@ -76,7 +76,7 @@ const IosAppCredentialsQuery = {
query IosAppCredentialsWithBuildCredentialsByAppIdentifierIdQuery(
$projectFullName: String!
$appleAppIdentifierId: String!
$iosDistributionType: IosDistributionType!
$iosDistributionType: IosDistributionType
) {
app {
byFullName(fullName: $projectFullName) {
@@ -84,7 +84,7 @@ const IosAppCredentialsQuery = {
iosAppCredentials(filter: { appleAppIdentifierId: $appleAppIdentifierId }) {
id
...IosAppCredentialsFragment
iosAppBuildCredentialsArray(
iosAppBuildCredentialsList(
filter: { iosDistributionType: $iosDistributionType }
) {
id
@@ -18,7 +18,7 @@ const IosAppCredentialsQuery = {
bundleIdentifier: 'com.quinlanj.test52',
__typename: 'AppleAppIdentifier',
},
iosAppBuildCredentialsArray: [
iosAppBuildCredentialsList: [
{
id: '6f8d0175-0caf-4922-b09b-eae757b83144',
iosDistributionType: 'APP_STORE',
@@ -1,5 +1,26 @@
import { AppleDistributionCertificateFragment } from '../../../graphql/generated';
import { DistributionCertificate, DistributionCertificateStoreInfo } from './Credentials.types';
export function filterRevokedDistributionCertsFromEasServers(
distributionCerts: AppleDistributionCertificateFragment[],
certInfoFromApple: DistributionCertificateStoreInfo[]
): AppleDistributionCertificateFragment[] {
if (distributionCerts.length === 0) {
return [];
}
// if the cert is valid, check it against apple to make sure it hasnt been revoked
const validCertSerialsOnAppleServer = certInfoFromApple
.filter(
// remove expired certs
cert => cert.expires > Math.floor(Date.now() / 1000)
)
.map(cert => cert.serialNumber);
return distributionCerts.filter(cert =>
validCertSerialsOnAppleServer.includes(cert.serialNumber)
);
}
export function filterRevokedDistributionCerts<T extends DistributionCertificate>(
distributionCerts: T[],
certInfoFromApple: DistributionCertificateStoreInfo[]
@@ -1,22 +0,0 @@
import { AppleDistributionCertificateFragment } from '../../../graphql/generated';
import { DistributionCertificateStoreInfo } from './Credentials.types';
export function filterRevokedDistributionCerts(
distributionCerts: AppleDistributionCertificateFragment[],
certInfoFromApple: DistributionCertificateStoreInfo[]
): AppleDistributionCertificateFragment[] {
if (distributionCerts.length === 0) {
return [];
}
// if the cert is valid, check it against apple to make sure it hasnt been revoked
const validCertSerialsOnAppleServer = certInfoFromApple
.filter(
// remove expired certs
cert => cert.expires > Math.floor(Date.now() / 1000)
)
.map(cert => cert.serialNumber);
return distributionCerts.filter(cert =>
validCertSerialsOnAppleServer.includes(cert.serialNumber)
);
}
@@ -3,7 +3,7 @@ import nullthrows from 'nullthrows';
import Log from '../../../../log';
import { IosAppCredentialsQuery } from '../../api/graphql/queries/IosAppCredentialsQuery';
import { displayIosAppCredentials } from '../printCredentialsBeta';
import { displayIosAppCredentials } from '../printCredentials';
jest.mock('../../../../log');
jest.mock('chalk', () => ({ bold: jest.fn(log => log) }));
@@ -1,104 +1,159 @@
import chalk from 'chalk';
import dateformat from 'dateformat';
import { AppleDevice } from '../../../graphql/generated';
import {
AppleDeviceFragment,
CommonIosAppCredentialsFragment,
IosAppBuildCredentialsFragment,
IosDistributionType,
} from '../../../graphql/generated';
import { APPLE_DEVICE_CLASS_LABELS } from '../../../graphql/types/credentials/AppleDevice';
import Log from '../../../log';
import {
AppLookupParams,
IosAppCredentials,
IosCredentials,
IosDistCredentials,
IosPushCredentials,
} from '../credentials';
import { fromNow } from '../../../utils/date';
import { AppLookupParams } from '../api/GraphqlClient';
function prettyIosDistributionType(distributionType: IosDistributionType): string {
switch (distributionType) {
case IosDistributionType.AppStore:
return 'App Store';
case IosDistributionType.AdHoc:
return 'Ad Hoc';
case IosDistributionType.Development:
return 'Development';
case IosDistributionType.Enterprise:
return 'Enterprise';
default:
return 'Unknown';
}
}
export function displayEmptyIosCredentials(appLookupParams: AppLookupParams): void {
const { projectName, bundleIdentifier } = appLookupParams;
Log.log(chalk.bold(`iOS Credentials`));
Log.log(` Project: ${projectName}`);
Log.log(` Bundle Identifier: ${bundleIdentifier}`);
Log.log(` No credentials set up yet!`);
}
/**
* sort a build credentials array in descending order of preference
*/
function sortBuildCredentialsByDistributionType(
iosAppBuildCredentialsList: IosAppBuildCredentialsFragment[]
): IosAppBuildCredentialsFragment[] {
// The order in which we choose the distribution type from least to most preferred
const typePriority = [
IosDistributionType.Development,
IosDistributionType.AdHoc,
IosDistributionType.Enterprise,
IosDistributionType.AppStore,
];
return iosAppBuildCredentialsList
.sort(
(buildCredentialsA, buildCredentialsB) =>
typePriority.indexOf(buildCredentialsA.iosDistributionType) -
typePriority.indexOf(buildCredentialsB.iosDistributionType)
)
.reverse();
}
export function displayIosAppCredentials(credentials: CommonIosAppCredentialsFragment): void {
Log.log(chalk.bold(`iOS Credentials`));
Log.log(` Project: ${credentials.app.fullName}`);
Log.log(` Bundle Identifier: ${credentials.appleAppIdentifier.bundleIdentifier}`);
const appleTeam = credentials.appleTeam;
if (appleTeam) {
const { appleTeamIdentifier, appleTeamName } = appleTeam;
Log.log(` Apple Team: ${appleTeamIdentifier} ${appleTeamName ? `(${appleTeamName})` : ''}`);
}
Log.newLine();
if (credentials.iosAppBuildCredentialsList.length === 0) {
Log.log(` Configuration: None setup yet`);
Log.newLine();
return;
}
const sortedIosAppBuildCredentialsList = sortBuildCredentialsByDistributionType(
credentials.iosAppBuildCredentialsList
);
for (const iosAppBuildCredentials of sortedIosAppBuildCredentialsList) {
displayIosAppBuildCredentials(iosAppBuildCredentials);
}
}
export function displayProjectCredentials(
appLookupParams: AppLookupParams,
appCredentials?: IosAppCredentials | null,
pushKey?: IosPushCredentials | null,
distCert?: IosDistCredentials | null
buildCredentials: IosAppBuildCredentialsFragment
): void {
const experienceName = `@${appLookupParams.accountName}/${appLookupParams.projectName}`;
const bundleIdentifier = appLookupParams.bundleIdentifier;
if (!appCredentials) {
Log.log(
chalk.bold(
`No credentials configured for app ${experienceName} with bundle identifier ${bundleIdentifier}\n`
)
);
return;
}
Log.log();
const experienceName = `@${appLookupParams.account.name}/${appLookupParams.projectName}`;
Log.addNewLineIfNone();
Log.log(chalk.bold('Project Credentials Configuration:'));
displayIosAppCredentials(appCredentials);
Log.log();
if (distCert) {
displayIosUserCredentials(distCert);
}
if (pushKey) {
displayIosUserCredentials(pushKey);
}
Log.log(` Project: ${chalk.bold(experienceName)}`);
Log.log(` Bundle Identifier: ${appLookupParams.bundleIdentifier}`);
displayIosAppBuildCredentials(buildCredentials);
}
export async function displayAllIosCredentials(credentials: IosCredentials) {
Log.log(chalk.bold('Available credentials for iOS apps'));
Log.newLine();
Log.log(chalk.bold('Application credentials'));
Log.newLine();
for (const cred of credentials.appCredentials) {
displayIosAppCredentials(cred);
Log.log();
}
Log.log(chalk.bold('User credentials\n'));
for (const cred of credentials.userCredentials) {
displayIosUserCredentials(cred, credentials);
Log.newLine();
}
Log.newLine();
}
export function displayIosAppCredentials(appCredentials: IosAppCredentials) {
function displayIosAppBuildCredentials(buildCredentials: IosAppBuildCredentialsFragment): void {
Log.log(
` Project: ${chalk.bold(appCredentials.experienceName)}, bundle identifier: ${
appCredentials.bundleIdentifier
}`
chalk.bold(
` Configuration: ${prettyIosDistributionType(buildCredentials.iosDistributionType)}`
)
);
if (appCredentials.credentials.provisioningProfile) {
Log.log(
` Provisioning profile (ID: ${chalk.green(
appCredentials.credentials.provisioningProfileId || '---------'
)})`
);
} else {
Log.log(' Provisioning profile is missing. It will be generated during the next build');
}
if (appCredentials.credentials.devices && appCredentials.credentials.devices.length > 0) {
Log.log(` Provisioned devices:`);
for (const device of appCredentials.credentials.devices) {
Log.log(` - ${formatDevice(device)}`);
Log.newLine();
const maybeDistCert = buildCredentials.distributionCertificate;
Log.log(` Distribution Certificate:`);
if (maybeDistCert) {
const { serialNumber, updatedAt, validityNotAfter, appleTeam } = maybeDistCert;
Log.log(` Serial Number: ${serialNumber}`);
Log.log(` Expiration Date: ${dateformat(validityNotAfter, 'expiresHeaderFormat')}`);
if (appleTeam) {
const { appleTeamIdentifier, appleTeamName } = appleTeam;
Log.log(
` Apple Team: ${appleTeamIdentifier} ${appleTeamName ? `(${appleTeamName})` : ''}`
);
}
Log.log(` Updated ${fromNow(new Date(updatedAt))} ago`);
} else {
Log.log(` None assigned yet`);
}
if (appCredentials.credentials.teamId || appCredentials.credentials.teamName) {
Log.log(
` Apple Team ID: ${chalk.green(
appCredentials.credentials.teamId || '---------'
)}, Apple Team Name: ${chalk.green(appCredentials.credentials.teamName || '---------')}`
);
}
if (appCredentials.credentials.pushP12 && appCredentials.credentials.pushPassword) {
Log.log(
` (deprecated) Push Certificate (Push ID: ${chalk.green(
appCredentials.credentials.pushId || '-----'
)})`
);
Log.newLine();
const maybeProvProf = buildCredentials.provisioningProfile;
Log.log(` Provisioning Profile:`);
if (maybeProvProf) {
const {
expiration,
updatedAt,
status,
developerPortalIdentifier,
appleTeam,
appleDevices,
} = maybeProvProf;
if (developerPortalIdentifier) {
Log.log(` Developer Portal ID: ${developerPortalIdentifier}`);
}
Log.log(` Status: ${status}`);
Log.log(` Expiration Date: ${dateformat(expiration, 'expiresHeaderFormat')}`);
if (appleTeam) {
const { appleTeamIdentifier, appleTeamName } = appleTeam;
Log.log(
` Apple Team: ${appleTeamIdentifier} ${appleTeamName ? `(${appleTeamName})` : ''}`
);
}
if (appleDevices && appleDevices.length > 0) {
Log.log(` Provisioned devices:`);
for (const appleDevice of appleDevices) {
Log.log(` - ${formatAppleDevice(appleDevice)}`);
}
}
Log.log(` Updated ${fromNow(new Date(updatedAt))} ago`);
} else {
Log.log(` None assigned yet`);
}
Log.newLine();
}
function formatDevice(device: AppleDevice): string {
function formatAppleDevice(device: AppleDeviceFragment): string {
let deviceString = '';
if (device.name) {
deviceString += device.name;
@@ -124,38 +179,3 @@ function formatDevice(device: AppleDevice): string {
}
return deviceString;
}
export function displayIosUserCredentials(
userCredentials: IosPushCredentials | IosDistCredentials,
credentials?: IosCredentials
) {
if (userCredentials.type === 'push-key') {
Log.log(` Push Notifications Key - Key ID: ${chalk.green(userCredentials.apnsKeyId)}`);
} else if (userCredentials.type === 'dist-cert') {
Log.log(
` Distribution Certificate - Certificate ID: ${chalk.green(
userCredentials.certId || '-----'
)}`
);
} else {
Log.warn(` Unknown key type ${(userCredentials as any).type}`);
}
Log.log(
` Apple Team ID: ${chalk.green(
userCredentials.teamId || '---------'
)}, Apple Team Name: ${chalk.green(userCredentials.teamName || '---------')}`
);
if (credentials) {
const field = userCredentials.type === 'push-key' ? 'pushCredentialsId' : 'distCredentialsId';
const usedByApps = [
...new Set(
credentials.appCredentials
.filter(c => c[field] === userCredentials.id)
.map(c => `${c.experienceName} (${c.bundleIdentifier})`)
),
].join(',\n ');
const usedByAppsText = usedByApps ? `used by\n ${usedByApps}` : 'not used by any apps';
Log.log(` ${chalk.gray(usedByAppsText)}`);
}
}
@@ -1,181 +0,0 @@
import chalk from 'chalk';
import dateformat from 'dateformat';
import {
AppleDeviceFragment,
CommonIosAppCredentialsFragment,
IosAppBuildCredentialsFragment,
IosDistributionType,
} from '../../../graphql/generated';
import { APPLE_DEVICE_CLASS_LABELS } from '../../../graphql/types/credentials/AppleDevice';
import Log from '../../../log';
import { fromNow } from '../../../utils/date';
import { AppLookupParams } from '../api/GraphqlClient';
function prettyIosDistributionType(distributionType: IosDistributionType): string {
switch (distributionType) {
case IosDistributionType.AppStore:
return 'App Store';
case IosDistributionType.AdHoc:
return 'Ad Hoc';
case IosDistributionType.Development:
return 'Development';
case IosDistributionType.Enterprise:
return 'Enterprise';
default:
return 'Unknown';
}
}
export function displayEmptyIosCredentials(appLookupParams: AppLookupParams): void {
const { projectName, bundleIdentifier } = appLookupParams;
Log.log(chalk.bold(`iOS Credentials`));
Log.log(` Project: ${projectName}`);
Log.log(` Bundle Identifier: ${bundleIdentifier}`);
Log.log(` No credentials set up yet!`);
}
/**
* sort a build credentials array in descending order of preference
*/
function sortBuildCredentialsByDistributionType(
iosAppBuildCredentialsArray: IosAppBuildCredentialsFragment[]
): IosAppBuildCredentialsFragment[] {
// The order in which we choose the distribution type from least to most preferred
const typePriority = [
IosDistributionType.Development,
IosDistributionType.AdHoc,
IosDistributionType.Enterprise,
IosDistributionType.AppStore,
];
return iosAppBuildCredentialsArray
.sort(
(buildCredentialsA, buildCredentialsB) =>
typePriority.indexOf(buildCredentialsA.iosDistributionType) -
typePriority.indexOf(buildCredentialsB.iosDistributionType)
)
.reverse();
}
export function displayIosAppCredentials(credentials: CommonIosAppCredentialsFragment): void {
Log.log(chalk.bold(`iOS Credentials`));
Log.log(` Project: ${credentials.app.fullName}`);
Log.log(` Bundle Identifier: ${credentials.appleAppIdentifier.bundleIdentifier}`);
const appleTeam = credentials.appleTeam;
if (appleTeam) {
const { appleTeamIdentifier, appleTeamName } = appleTeam;
Log.log(` Apple Team: ${appleTeamIdentifier} ${appleTeamName ? `(${appleTeamName})` : ''}`);
}
Log.newLine();
if (credentials.iosAppBuildCredentialsArray.length === 0) {
Log.log(` Configuration: None setup yet`);
Log.newLine();
return;
}
const sortedIosAppBuildCredentialsArray = sortBuildCredentialsByDistributionType(
credentials.iosAppBuildCredentialsArray
);
for (const iosAppBuildCredentials of sortedIosAppBuildCredentialsArray) {
displayIosAppBuildCredentials(iosAppBuildCredentials);
}
}
export function displayProjectCredentials(
appLookupParams: AppLookupParams,
buildCredentials: IosAppBuildCredentialsFragment
): void {
const experienceName = `@${appLookupParams.account.name}/${appLookupParams.projectName}`;
Log.addNewLineIfNone();
Log.log(chalk.bold('Project Credentials Configuration:'));
Log.log(` Project: ${chalk.bold(experienceName)}`);
Log.log(` Bundle Identifier: ${appLookupParams.bundleIdentifier}`);
displayIosAppBuildCredentials(buildCredentials);
}
function displayIosAppBuildCredentials(buildCredentials: IosAppBuildCredentialsFragment): void {
Log.log(
chalk.bold(
` Configuration: ${prettyIosDistributionType(buildCredentials.iosDistributionType)}`
)
);
Log.newLine();
const maybeDistCert = buildCredentials.distributionCertificate;
Log.log(` Distribution Certificate:`);
if (maybeDistCert) {
const { serialNumber, updatedAt, validityNotAfter, appleTeam } = maybeDistCert;
Log.log(` Serial Number: ${serialNumber}`);
Log.log(` Expiration Date: ${dateformat(validityNotAfter, 'expiresHeaderFormat')}`);
if (appleTeam) {
const { appleTeamIdentifier, appleTeamName } = appleTeam;
Log.log(
` Apple Team: ${appleTeamIdentifier} ${appleTeamName ? `(${appleTeamName})` : ''}`
);
}
Log.log(` Updated ${fromNow(new Date(updatedAt))} ago`);
} else {
Log.log(` None assigned yet`);
}
Log.newLine();
const maybeProvProf = buildCredentials.provisioningProfile;
Log.log(` Provisioning Profile:`);
if (maybeProvProf) {
const {
expiration,
updatedAt,
status,
developerPortalIdentifier,
appleTeam,
appleDevices,
} = maybeProvProf;
if (developerPortalIdentifier) {
Log.log(` Developer Portal ID: ${developerPortalIdentifier}`);
}
Log.log(` Status: ${status}`);
Log.log(` Expiration Date: ${dateformat(expiration, 'expiresHeaderFormat')}`);
if (appleTeam) {
const { appleTeamIdentifier, appleTeamName } = appleTeam;
Log.log(
` Apple Team: ${appleTeamIdentifier} ${appleTeamName ? `(${appleTeamName})` : ''}`
);
}
if (appleDevices && appleDevices.length > 0) {
Log.log(` Provisioned devices:`);
for (const appleDevice of appleDevices) {
Log.log(` - ${formatAppleDevice(appleDevice)}`);
}
}
Log.log(` Updated ${fromNow(new Date(updatedAt))} ago`);
} else {
Log.log(` None assigned yet`);
}
Log.newLine();
}
function formatAppleDevice(device: AppleDeviceFragment): string {
let deviceString = '';
if (device.name) {
deviceString += device.name;
}
if (device.deviceClass || device.model) {
const deviceDetails = [
device.deviceClass && APPLE_DEVICE_CLASS_LABELS[device.deviceClass],
device.model,
]
.filter(i => i)
.join(' ');
if (deviceString === '') {
deviceString += deviceDetails;
} else {
deviceString += ` - ${deviceDetails}`;
}
}
if (deviceString === '') {
deviceString += device.identifier;
} else {
deviceString += ` (UDID: ${device.identifier})`;
}
return deviceString;
}
@@ -1,127 +1,128 @@
import { PlistArray, PlistObject } from '@expo/plist';
import assert from 'assert';
import crypto from 'crypto';
import minimatch from 'minimatch';
import nullthrows from 'nullthrows';
import { IosAppBuildCredentialsFragment, IosDistributionType } from '../../../graphql/generated';
import Log from '../../../log';
import { Context } from '../../context';
import { DistributionCertificate, ProvisioningProfile } from '../appstore/Credentials.types';
import { AppLookupParams } from '../api/GraphqlClient';
import { ProfileClass } from '../appstore/provisioningProfile';
import { getP12CertFingerprint } from '../utils/p12Certificate';
import { parse as parseProvisioningProfile } from '../utils/provisioningProfile';
interface ValidationResult {
error?: string;
ok: boolean;
}
export async function validateProvisioningProfileAsync(
ctx: Context,
profile: Pick<ProvisioningProfile, 'provisioningProfile' | 'provisioningProfileId'>,
distCert: Pick<DistributionCertificate, 'certP12' | 'certPassword'>,
bundleIdentifier: string
): Promise<ValidationResult> {
const resultWithoutApple = validateProvisioningProfileWithoutApple(
profile,
distCert,
bundleIdentifier
);
app: AppLookupParams,
buildCredentials: Partial<IosAppBuildCredentialsFragment> | null
): Promise<boolean> {
if (
!buildCredentials ||
!buildCredentials.distributionCertificate ||
!buildCredentials.provisioningProfile
) {
return false;
}
// already failed, return early
if (!resultWithoutApple.ok) {
return resultWithoutApple;
const resultWithoutApple = validateProvisioningProfileWithoutApple(app, buildCredentials);
if (!resultWithoutApple) {
return false;
}
if (!ctx.appStore.authCtx) {
Log.warn(
"Skipping Provisioning Profile validation on Apple Servers because we aren't authenticated."
);
return resultWithoutApple;
return true;
}
return await validateProvisioningProfileWithAppleAsync(ctx, profile, bundleIdentifier);
return await validateProvisioningProfileWithAppleAsync(ctx, app, buildCredentials);
}
async function validateProvisioningProfileWithAppleAsync(
ctx: Context,
profile: Pick<ProvisioningProfile, 'provisioningProfile' | 'provisioningProfileId'>,
bundleIdentifier: string
): Promise<ValidationResult> {
const profilesFromApple = await ctx.appStore.listProvisioningProfilesAsync(bundleIdentifier);
const configuredProfileFromApple = profilesFromApple.find(appleProfile =>
profile.provisioningProfileId
? appleProfile.provisioningProfileId === profile.provisioningProfileId
: appleProfile.provisioningProfile === profile.provisioningProfile
);
if (!configuredProfileFromApple) {
return {
error: `Provisioning profile (id: ${profile.provisioningProfileId}) does not exist in Apple Dev Portal`,
ok: false,
};
}
if (configuredProfileFromApple.status !== 'ACTIVE') {
return {
error: `Provisioning profile (id: ${profile.provisioningProfileId}) is no longer valid`,
ok: false,
};
}
return { ok: true };
}
export function validateProvisioningProfileWithoutApple(
provisioningProfile: Pick<ProvisioningProfile, 'provisioningProfile' | 'provisioningProfileId'>,
distCert: Pick<DistributionCertificate, 'certP12' | 'certPassword'>,
bundleIdentifier: string
): ValidationResult {
function validateProvisioningProfileWithoutApple(
app: AppLookupParams,
{ provisioningProfile, distributionCertificate }: Partial<IosAppBuildCredentialsFragment>
): boolean {
try {
const profilePlist = parseProvisioningProfile(provisioningProfile.provisioningProfile);
const profilePlist = parseProvisioningProfile(
nullthrows(provisioningProfile?.provisioningProfile)
);
let distCertFingerprint: string;
try {
distCertFingerprint = getP12CertFingerprint(distCert.certP12, distCert.certPassword);
distCertFingerprint = getP12CertFingerprint(
nullthrows(distributionCertificate?.certificateP12),
nullthrows(distributionCertificate?.certificatePassword)
);
} catch (e) {
return {
error: `Failed to calculate fingerprint for Distribution Certificate: ${e.toString()}`,
ok: false,
};
Log.warn(`Failed to calculate fingerprint for Distribution Certificate: ${e.toString()}`);
return false;
}
const devCertStatus = validateDeveloperCertificate(profilePlist, distCertFingerprint);
if (!devCertStatus.ok) {
return devCertStatus;
if (!devCertStatus) {
return false;
}
const bundleIdentifierStatus = validateBundleIdentifier(profilePlist, bundleIdentifier);
if (!bundleIdentifierStatus.ok) {
return bundleIdentifierStatus;
const bundleIdentifierStatus = validateBundleIdentifier(profilePlist, app.bundleIdentifier);
if (!bundleIdentifierStatus) {
return false;
}
const isExpired = new Date(profilePlist['ExpirationDate'] as string) <= new Date();
if (isExpired) {
return {
error: 'Provisioning Profile has expired.',
ok: false,
};
Log.warn('Provisioning Profile has expired.');
return false;
}
} catch (error) {
return {
error: 'Provisioning Profile is malformed.',
ok: false,
};
Log.warn('Provisioning Profile is malformed.');
return false;
}
return {
ok: true,
};
return true;
}
async function validateProvisioningProfileWithAppleAsync(
ctx: Context,
app: AppLookupParams,
buildCredentials: Partial<IosAppBuildCredentialsFragment>
): Promise<boolean> {
assert(buildCredentials.provisioningProfile, 'Provisioning Profile must be defined');
const { developerPortalIdentifier, provisioningProfile } = buildCredentials.provisioningProfile;
const profilesFromApple = await ctx.appStore.listProvisioningProfilesAsync(
app.bundleIdentifier,
buildCredentials.iosDistributionType === IosDistributionType.AdHoc
? ProfileClass.Adhoc
: ProfileClass.General
);
const configuredProfileFromApple = profilesFromApple.find(appleProfile =>
developerPortalIdentifier
? appleProfile.provisioningProfileId === developerPortalIdentifier
: appleProfile.provisioningProfile === provisioningProfile
);
if (!configuredProfileFromApple) {
Log.warn(
`Provisioning profile (id: ${developerPortalIdentifier}) does not exist in Apple Developer Portal`
);
return false;
}
if (configuredProfileFromApple.status !== 'ACTIVE') {
Log.warn(`Provisioning profile (id: ${developerPortalIdentifier}) is no longer valid`);
return false;
}
return true;
}
function validateDeveloperCertificate(
plistData: PlistObject,
distCertFingerprint: string
): ValidationResult {
): boolean {
const devCertBase64 = (plistData?.DeveloperCertificates as PlistArray)?.[0] as string;
if (!devCertBase64) {
return {
error: 'Missing certificate fingerprint in provisioning profile.',
ok: false,
};
Log.warn('Missing certificate fingerprint in provisioning profile.');
return false;
}
const devCertBuffer = Buffer.from(devCertBase64, 'base64');
const devCertFingerprint = crypto
@@ -131,40 +132,34 @@ function validateDeveloperCertificate(
.toUpperCase();
if (devCertFingerprint !== distCertFingerprint) {
return {
error: 'Provisioning profile is not associated with uploaded Distribution Certificate.',
ok: false,
};
Log.warn('Provisioning profile is not associated with uploaded Distribution Certificate.');
return false;
}
return { ok: true };
return true;
}
function validateBundleIdentifier(
plistData: PlistObject,
expectedBundleIdentifier: string
): ValidationResult {
): boolean {
const actualApplicationIdentifier = (plistData.Entitlements as PlistObject)?.[
'application-identifier'
] as string;
if (!actualApplicationIdentifier) {
return {
error: 'Missing application-identifier in provisioning profile entitlements',
ok: false,
};
Log.warn('Missing application-identifier in provisioning profile entitlements');
return false;
}
const actualBundleIdentifier = /\.(.+)/.exec(actualApplicationIdentifier)?.[1] as string;
if (!actualBundleIdentifier) {
return {
error: 'Malformed application-identifier field in provisioning profile',
ok: false,
};
Log.warn('Malformed application-identifier field in provisioning profile');
return false;
}
if (!minimatch(expectedBundleIdentifier, actualBundleIdentifier)) {
return {
error: `Wrong bundleIdentifier found in provisioning profile; expected: ${expectedBundleIdentifier}, found (in provisioning profile): ${actualBundleIdentifier}`,
ok: false,
};
Log.warn(
`Wrong bundleIdentifier found in provisioning profile; expected: ${expectedBundleIdentifier}, found (in provisioning profile): ${actualBundleIdentifier}`
);
return false;
}
return { ok: true };
return true;
}
@@ -0,0 +1,63 @@
import Log from '../../log';
import { getProjectAccountName } from '../../project/projectUtils';
import { findAccountByName } from '../../user/Account';
import { ensureActorHasUsername } from '../../user/actions';
import { Action, CredentialsManager } from '../CredentialsManager';
import { getAppLookupParamsFromContext } from '../android/actions/BuildCredentialsUtils';
import {
displayAndroidAppCredentials,
displayEmptyAndroidCredentials,
} from '../android/utils/printCredentialsBeta';
import { Context } from '../context';
import { PressAnyKeyToContinue } from './HelperActions';
enum ActionType {}
enum Scope {
Project,
Account,
Manager,
}
type ActionInfo = { value: ActionType; title: string; scope: Scope };
const highLevelActions: ActionInfo[] = [];
export class ManageAndroid implements Action {
async runAsync(
manager: CredentialsManager,
ctx: Context,
_currentActions: ActionInfo[] = highLevelActions
): Promise<void> {
while (true) {
try {
const accountName = ctx.hasProjectContext
? getProjectAccountName(ctx.exp, ctx.user)
: ensureActorHasUsername(ctx.user);
const account = findAccountByName(ctx.user.accounts, accountName);
if (!account) {
throw new Error(`You do not have access to account: ${accountName}`);
}
if (ctx.hasProjectContext) {
const appLookupParams = getAppLookupParamsFromContext(ctx);
const legacyAppCredentials = await ctx.newAndroid.getLegacyAndroidAppCredentialsWithCommonFieldsAsync(
appLookupParams
);
const appCredentials = await ctx.newAndroid.getAndroidAppCredentialsWithCommonFieldsAsync(
appLookupParams
);
if (!legacyAppCredentials && !appCredentials) {
displayEmptyAndroidCredentials(appLookupParams);
} else {
displayAndroidAppCredentials({ appLookupParams, legacyAppCredentials, appCredentials });
}
throw new Error('Not Implemented Yet');
}
} catch (err) {
Log.error(err);
await manager.runActionAsync(new PressAnyKeyToContinue());
}
}
}
}
@@ -1,37 +1,76 @@
import { EasConfig, EasJsonReader } from '@expo/eas-json';
import {
AppleDistributionCertificateFragment,
IosAppBuildCredentialsFragment,
IosDistributionType as IosDistributionTypeGraphql,
} from '../../graphql/generated';
import Log from '../../log';
import { getProjectAccountName } from '../../project/projectUtils';
import { promptAsync } from '../../prompts';
import { confirmAsync, promptAsync } from '../../prompts';
import { Account, findAccountByName } from '../../user/Account';
import { ensureActorHasUsername } from '../../user/actions';
import { Action, CredentialsManager } from '../CredentialsManager';
import { Context } from '../context';
import { CreateDistributionCertificateStandaloneManager } from '../ios/actions/CreateDistributionCertificate';
import { RemoveDistributionCertificate } from '../ios/actions/RemoveDistributionCertificate';
import { RemoveSpecificProvisioningProfile } from '../ios/actions/RemoveProvisioningProfile';
import {
SetupBuildCredentials,
SetupBuildCredentialsFromCredentialsJson,
} from '../ios/actions/SetupBuildCredentials';
import { getAppLookupParamsFromContext } from '../ios/actions/BuildCredentialsUtils';
import { CreateDistributionCertificate } from '../ios/actions/CreateDistributionCertificate';
import { selectValidDistributionCertificateAsync } from '../ios/actions/DistributionCertificateUtils';
import { SelectAndRemoveDistributionCertificate } from '../ios/actions/RemoveDistributionCertificate';
import { RemoveProvisioningProfiles } from '../ios/actions/RemoveProvisioningProfile';
import { SetupAdhocProvisioningProfile } from '../ios/actions/SetupAdhocProvisioningProfile';
import { SetupBuildCredentials } from '../ios/actions/SetupBuildCredentials';
import { SetupBuildCredentialsFromCredentialsJson } from '../ios/actions/SetupBuildCredentialsFromCredentialsJson';
import { SetupProvisioningProfile } from '../ios/actions/SetupProvisioningProfile';
import { UpdateCredentialsJson } from '../ios/actions/UpdateCredentialsJson';
import { UpdateDistributionCertificate } from '../ios/actions/UpdateDistributionCertificate';
import { UseExistingDistributionCertificate } from '../ios/actions/UseDistributionCertificate';
import { getAppLookupParamsFromContext } from '../ios/actions/new/BuildCredentialsUtils';
import { AppLookupParams } from '../ios/credentials';
import { displayAllIosCredentials } from '../ios/utils/printCredentials';
import { AppLookupParams } from '../ios/api/GraphqlClient';
import {
displayEmptyIosCredentials,
displayIosAppCredentials,
} from '../ios/utils/printCredentials';
import { PressAnyKeyToContinue } from './HelperActions';
import { SelectBuildProfileFromEasJson } from './SelectBuildProfileFromEasJson';
import { SelectIosDistributionTypeGraphqlFromBuildProfile } from './SelectIosDistributionTypeGraphqlFromBuildProfile';
enum ActionType {
ManageCredentialsJson,
ManageBuildCredentials,
GoBackToHighLevelActions,
SetupBuildCredentials,
SetupBuildCredentialsFromCredentialsJson,
UpdateCredentialsJson,
UseExistingDistributionCertificate,
RemoveSpecificProvisioningProfile,
RemoveProvisioningProfile,
CreateDistributionCertificate,
UpdateDistributionCertificate,
RemoveDistributionCertificate,
}
enum Scope {
Project,
Account,
Manager,
}
type ActionInfo = { value: ActionType; title: string; scope: Scope };
const highLevelActions: ActionInfo[] = [
{
value: ActionType.ManageBuildCredentials,
title: 'Build Credentials: Manage everything needed to build your project',
scope: Scope.Manager,
},
{
value: ActionType.ManageCredentialsJson,
title: 'Credentials.json: Upload/Download credentials between EAS servers and your local json ',
scope: Scope.Manager,
},
];
export class ManageIos implements Action {
async runAsync(manager: CredentialsManager, ctx: Context): Promise<void> {
async runAsync(
manager: CredentialsManager,
ctx: Context,
currentActions: ActionInfo[] = highLevelActions
): Promise<void> {
while (true) {
try {
await ctx.bestEffortAppStoreAuthenticateAsync();
@@ -39,60 +78,116 @@ export class ManageIos implements Action {
const accountName = ctx.hasProjectContext
? getProjectAccountName(ctx.exp, ctx.user)
: ensureActorHasUsername(ctx.user);
const iosCredentials = await ctx.ios.getAllCredentialsAsync(accountName);
await displayAllIosCredentials(iosCredentials);
const account = findAccountByName(ctx.user.accounts, accountName);
if (!account) {
throw new Error(`You do not have access to account: ${accountName}`);
}
if (ctx.hasProjectContext) {
const appLookupParams = getAppLookupParamsFromContext(ctx);
const iosAppCredentials = await ctx.ios.getIosAppCredentialsWithCommonFieldsAsync(
appLookupParams
);
if (!iosAppCredentials) {
displayEmptyIosCredentials(appLookupParams);
} else {
displayIosAppCredentials(iosAppCredentials);
}
}
const projectSpecificActions: { value: ActionType; title: string }[] = ctx.hasProjectContext
? [
{
// This command will be triggered during build to ensure all credentials are ready
// I'm leaving it here for now to simplify testing
value: ActionType.SetupBuildCredentials,
title: 'Ensure all credentials for project are valid',
},
{
value: ActionType.UpdateCredentialsJson,
title: 'Update credentials.json with values from EAS servers',
},
{
value: ActionType.SetupBuildCredentialsFromCredentialsJson,
title: 'Update credentials on EAS servers with values from credentials.json',
},
{
value: ActionType.UseExistingDistributionCertificate,
title: 'Use existing Distribution Certificate in current project',
},
{
value: ActionType.RemoveSpecificProvisioningProfile,
title: 'Remove Provisioning Profile from current project',
},
]
: [];
const { action } = await promptAsync({
const credentialsJsonActions: { value: ActionType; title: string; scope: Scope }[] = [
{
value: ActionType.UpdateCredentialsJson,
title: 'Download credentials from EAS to credentials.json',
scope: Scope.Project,
},
{
value: ActionType.SetupBuildCredentialsFromCredentialsJson,
title: 'Upload credentials from credentials.json to EAS',
scope: Scope.Project,
},
{
value: ActionType.GoBackToHighLevelActions,
title: 'Go back',
scope: Scope.Manager,
},
];
const buildCredentialsActions: { value: ActionType; title: string; scope: Scope }[] = [
{
// This command will be triggered during build to ensure all credentials are ready
// I'm leaving it here for now to simplify testing
value: ActionType.SetupBuildCredentials,
title: 'All: Set up all the required credentials to build your project',
scope: Scope.Project,
},
{
value: ActionType.UseExistingDistributionCertificate,
title: 'Distribution Certificate: Use an existing one for your project',
scope: Scope.Project,
},
{
value: ActionType.CreateDistributionCertificate,
title: `Distribution Certificate: Add a new one to your account`,
scope: ctx.hasProjectContext ? Scope.Project : Scope.Account,
},
{
value: ActionType.RemoveDistributionCertificate,
title: 'Distribution Certificate: Delete one from your account',
scope: Scope.Account,
},
{
value: ActionType.RemoveProvisioningProfile,
title: 'Provisioning Profile: Delete one from your project',
scope: Scope.Project,
},
{
value: ActionType.GoBackToHighLevelActions,
title: 'Go back',
scope: Scope.Manager,
},
];
const { action: chosenAction } = await promptAsync({
type: 'select',
name: 'action',
message: 'What do you want to do?',
choices: [
...projectSpecificActions,
{
value: ActionType.CreateDistributionCertificate,
title: 'Add new Distribution Certificate',
},
{
value: ActionType.RemoveDistributionCertificate,
title: 'Remove Distribution Certificate',
},
{
value: ActionType.UpdateDistributionCertificate,
title: 'Update Distribution Certificate',
},
],
choices: currentActions.map(action => ({
value: action.value,
title: action.title,
})),
});
try {
await manager.runActionAsync(this.getAction(manager, ctx, accountName, action));
const actionInfo = currentActions.find(action => action.value === chosenAction);
if (!actionInfo) {
throw new Error('Action not supported yet');
}
if (actionInfo.scope === Scope.Manager) {
if (chosenAction === ActionType.ManageBuildCredentials) {
currentActions = buildCredentialsActions;
continue;
} else if (chosenAction === ActionType.ManageCredentialsJson) {
currentActions = credentialsJsonActions;
continue;
} else if (chosenAction === ActionType.GoBackToHighLevelActions) {
currentActions = highLevelActions;
continue;
}
} else if (actionInfo.scope === Scope.Project) {
const appLookupParams = getAppLookupParamsFromContext(ctx);
const easJsonReader = await new EasJsonReader(ctx.projectDir, 'ios');
const easConfig = await new SelectBuildProfileFromEasJson(easJsonReader).runAsync(ctx);
await this.runProjectSpecificActionAsync(
manager,
ctx,
appLookupParams,
easConfig,
chosenAction
);
} else if (actionInfo.scope === Scope.Account) {
await this.runAccountSpecificActionAsync(ctx, account, chosenAction);
} else {
throw new Error('Unknown action selected');
}
} catch (err) {
Log.error(err);
}
@@ -104,52 +199,127 @@ export class ManageIos implements Action {
}
}
private getAppLookupParamsFromContext(ctx: Context): AppLookupParams {
const projectName = ctx.exp.slug;
const accountName = getProjectAccountName(ctx.exp, ctx.user);
const bundleIdentifier = ctx.exp.ios?.bundleIdentifier;
if (!bundleIdentifier) {
throw new Error(`ios.bundleIdentifier needs to be defined`);
private async runAccountSpecificActionAsync(
ctx: Context,
account: Account,
action: ActionType
): Promise<void> {
if (action === ActionType.RemoveDistributionCertificate) {
await new SelectAndRemoveDistributionCertificate(account).runAsync(ctx);
} else if (action === ActionType.CreateDistributionCertificate) {
await new CreateDistributionCertificate(account).runAsync(ctx);
}
return { accountName, projectName, bundleIdentifier };
}
private getAction(
private async runProjectSpecificActionAsync(
manager: CredentialsManager,
ctx: Context,
accountName: string,
appLookupParams: AppLookupParams,
easConfig: EasConfig,
action: ActionType
): Action {
): Promise<void> {
if (action === ActionType.SetupBuildCredentials) {
const iosDistributionTypeEasConfig = easConfig.builds.ios?.distribution;
if (!iosDistributionTypeEasConfig) {
throw new Error(`The distributionType field is required in your iOS build profile`);
}
await new SetupBuildCredentials({
app: appLookupParams,
distribution: iosDistributionTypeEasConfig,
}).runAsync(manager, ctx);
return;
}
const iosAppCredentials = await ctx.ios.getIosAppCredentialsWithCommonFieldsAsync(
appLookupParams
);
const iosDistributionTypeGraphql = await new SelectIosDistributionTypeGraphqlFromBuildProfile(
easConfig
).runAsync(ctx, iosAppCredentials);
switch (action) {
case ActionType.CreateDistributionCertificate:
return new CreateDistributionCertificateStandaloneManager(accountName);
case ActionType.UpdateDistributionCertificate:
return new UpdateDistributionCertificate(accountName);
case ActionType.RemoveDistributionCertificate:
return new RemoveDistributionCertificate(accountName);
case ActionType.UseExistingDistributionCertificate: {
const app = this.getAppLookupParamsFromContext(ctx);
return new UseExistingDistributionCertificate(app);
}
case ActionType.SetupBuildCredentials: {
const appLookupParams = getAppLookupParamsFromContext(ctx);
return new SetupBuildCredentials({ app: appLookupParams, distribution: 'store' });
}
case ActionType.RemoveSpecificProvisioningProfile: {
const app = this.getAppLookupParamsFromContext(ctx);
return new RemoveSpecificProvisioningProfile(app);
case ActionType.SetupBuildCredentialsFromCredentialsJson: {
await new SetupBuildCredentialsFromCredentialsJson(
appLookupParams,
iosDistributionTypeGraphql
).runAsync(ctx);
return;
}
case ActionType.UpdateCredentialsJson: {
const app = this.getAppLookupParamsFromContext(ctx);
return new UpdateCredentialsJson(app);
await new UpdateCredentialsJson(appLookupParams, iosDistributionTypeGraphql).runAsync(ctx);
return;
}
case ActionType.SetupBuildCredentialsFromCredentialsJson: {
const app = this.getAppLookupParamsFromContext(ctx);
return new SetupBuildCredentialsFromCredentialsJson(app);
case ActionType.UseExistingDistributionCertificate: {
const distCert = await selectValidDistributionCertificateAsync(ctx, appLookupParams);
if (!distCert) {
return;
}
await this.setupProvisioningProfileWithSpecificDistCertAsync(
ctx,
appLookupParams,
distCert,
iosDistributionTypeGraphql
);
return;
}
case ActionType.CreateDistributionCertificate: {
const distCert = await new CreateDistributionCertificate(appLookupParams.account).runAsync(
ctx
);
const confirm = await confirmAsync({
message: `Do you want ${appLookupParams.projectName} to use the new Distribution Certificate?`,
});
if (confirm) {
await this.setupProvisioningProfileWithSpecificDistCertAsync(
ctx,
appLookupParams,
distCert,
iosDistributionTypeGraphql
);
}
return;
}
case ActionType.RemoveProvisioningProfile: {
const provisioningProfile = iosAppCredentials?.iosAppBuildCredentialsList.find(
buildCredentials => buildCredentials.iosDistributionType === iosDistributionTypeGraphql
)?.provisioningProfile;
if (!provisioningProfile) {
Log.log(
`No provisioning profile associated with the ${iosDistributionTypeGraphql} configuration of ${appLookupParams.projectName}`
);
return;
}
const confirm = await confirmAsync({
message: `Delete the provisioning profile associated with the ${iosDistributionTypeGraphql} configuration of ${appLookupParams.projectName}?`,
});
if (confirm) {
await new RemoveProvisioningProfiles([appLookupParams], [provisioningProfile]).runAsync(
ctx
);
}
return;
}
default:
throw new Error('Unknown action selected');
}
}
private async setupProvisioningProfileWithSpecificDistCertAsync(
ctx: Context,
appLookupParams: AppLookupParams,
distCert: AppleDistributionCertificateFragment,
iosDistributionTypeGraphql: IosDistributionTypeGraphql
): Promise<IosAppBuildCredentialsFragment> {
Log.log(`Setting up ${appLookupParams.projectName} to use Distribution Certificate`);
Log.log(`Creating provisioning profile...`);
if (iosDistributionTypeGraphql === IosDistributionTypeGraphql.AdHoc) {
return await new SetupAdhocProvisioningProfile(
appLookupParams
).runWithDistributionCertificateAsync(ctx, distCert);
} else {
return await new SetupProvisioningProfile(
appLookupParams,
iosDistributionTypeGraphql
).createAndAssignProfileAsync(ctx, distCert);
}
}
}
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more