eas-cli 24.10.0 → 24.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import { ExpoConfig } from '@expo/config';
2
2
  import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
3
- import { AppPlatform, PartnerActor, Robot, SsoUser, Update, UpdateBranchFragment, UpdateFragment, UpdatePublishMutation, User } from '../graphql/generated';
3
+ import { AppPlatform, PartnerActor, Robot, SsoUser, Update, UpdateBranchFragment, UpdateFragment, UpdatePublishMutation, UpdateWithFileUrlsFragment, User } from '../graphql/generated';
4
4
  import { RequestedPlatform } from '../platform';
5
5
  export type FormatUpdateParameter = Pick<Update, 'id' | 'createdAt' | 'message'> & {
6
6
  actor?: Pick<Robot, '__typename' | 'firstName'> | Pick<User, '__typename' | 'username'> | Pick<SsoUser, '__typename' | 'username'> | Pick<PartnerActor, '__typename' | 'username'> | null;
@@ -9,6 +9,7 @@ export type UpdateJsonInfo = {
9
9
  branch: string;
10
10
  runtimeVersion: string;
11
11
  } & Pick<UpdateFragment, 'id' | 'createdAt' | 'group' | 'message' | 'platform' | 'manifestPermalink' | 'gitCommitHash'>;
12
+ export type UpdateWithFileUrlsJsonInfo = UpdateJsonInfo & Pick<UpdateWithFileUrlsFragment, 'assetMapUrl' | 'sourceMapUrl'>;
12
13
  export type UpdateGroupDescription = FormatUpdateParameter & {
13
14
  branch: string;
14
15
  group: string;
@@ -52,6 +53,11 @@ export declare function formatUpdateMessage(update: FormatUpdateParameter): stri
52
53
  export declare function ensureValidVersions(exp: ExpoConfig, platform: RequestedPlatform): void;
53
54
  export declare function formatUpdateTitle(update: UpdateFragment): string;
54
55
  export declare function getUpdateJsonInfosForUpdates(updates: UpdateFragment[]): UpdateJsonInfo[];
56
+ /**
57
+ * Same as getUpdateJsonInfosForUpdates, with the stored file URLs. Only `eas update:view` queries
58
+ * those, because the server signs each one per request.
59
+ */
60
+ export declare function getUpdateWithFileUrlsJsonInfosForUpdates(updates: UpdateWithFileUrlsFragment[]): UpdateWithFileUrlsJsonInfo[];
55
61
  export declare function getUpdateGroupDescriptions(updateGroups: UpdateFragment[][]): FormattedUpdateGroupDescription[];
56
62
  export declare function getUpdateGroupDescriptionsWithBranch(updateGroups: UpdateFragment[][]): FormattedUpdateGroupDescriptionWithBranch[];
57
63
  export declare function getBranchDescription(branch: UpdateBranchFragment): FormattedBranchDescription;
@@ -10,6 +10,7 @@ exports.formatUpdateMessage = formatUpdateMessage;
10
10
  exports.ensureValidVersions = ensureValidVersions;
11
11
  exports.formatUpdateTitle = formatUpdateTitle;
12
12
  exports.getUpdateJsonInfosForUpdates = getUpdateJsonInfosForUpdates;
13
+ exports.getUpdateWithFileUrlsJsonInfosForUpdates = getUpdateWithFileUrlsJsonInfosForUpdates;
13
14
  exports.getUpdateGroupDescriptions = getUpdateGroupDescriptions;
14
15
  exports.getUpdateGroupDescriptionsWithBranch = getUpdateGroupDescriptionsWithBranch;
15
16
  exports.getBranchDescription = getBranchDescription;
@@ -140,6 +141,19 @@ function getUpdateJsonInfosForUpdates(updates) {
140
141
  gitCommitHash: update.gitCommitHash,
141
142
  }));
142
143
  }
144
+ /**
145
+ * Same as getUpdateJsonInfosForUpdates, with the stored file URLs. Only `eas update:view` queries
146
+ * those, because the server signs each one per request.
147
+ */
148
+ function getUpdateWithFileUrlsJsonInfosForUpdates(updates) {
149
+ return getUpdateJsonInfosForUpdates(updates).map((info, index) => ({
150
+ ...info,
151
+ // Null unless the update was published with an asset map. The URL is signed and expires.
152
+ assetMapUrl: updates[index].assetMapUrl ?? null,
153
+ // Null unless published with `--upload-source-maps`. The URL is signed and expires.
154
+ sourceMapUrl: updates[index].sourceMapUrl ?? null,
155
+ }));
156
+ }
143
157
  function getUpdateGroupDescriptions(updateGroups) {
144
158
  return updateGroups.map(updateGroup => ({
145
159
  message: formatUpdateMessage(updateGroup[0]),
@@ -42,6 +42,7 @@ export default class SessionManager {
42
42
  browser?: boolean | undefined;
43
43
  }): Promise<void>;
44
44
  private browserLoginAsync;
45
+ loginWithDeviceSessionAsync(sessionSecret: string): Promise<string>;
45
46
  private loginAsync;
46
47
  /**
47
48
  * Prompt for an OTP with the option to cancel the question by answering empty (pressing return key).
@@ -7,6 +7,7 @@ const chalk_1 = tslib_1.__importDefault(require("chalk"));
7
7
  const nullthrows_1 = tslib_1.__importDefault(require("nullthrows"));
8
8
  const fetchSessionSecretAndUser_1 = require("./fetchSessionSecretAndUser");
9
9
  const fetchSessionSecretAndUserFromBrowserAuthFlow_1 = require("./fetchSessionSecretAndUserFromBrowserAuthFlow");
10
+ const fetchUser_1 = require("./fetchUser");
10
11
  const ApiV2Error_1 = require("../ApiV2Error");
11
12
  const api_1 = require("../api");
12
13
  const createGraphqlClient_1 = require("../commandUtils/context/contextUtils/createGraphqlClient");
@@ -154,6 +155,17 @@ class SessionManager {
154
155
  currentConnection: 'Browser-Flow-Authentication',
155
156
  });
156
157
  }
158
+ async loginWithDeviceSessionAsync(sessionSecret) {
159
+ const { id, username } = await (0, fetchUser_1.fetchUserAsync)({ sessionSecret });
160
+ await this.setSessionAsync({
161
+ sessionSecret,
162
+ userId: id,
163
+ username,
164
+ currentConnection: 'Browser-Flow-Authentication',
165
+ });
166
+ this.currentActor = undefined;
167
+ return username;
168
+ }
157
169
  async loginAsync(input) {
158
170
  const { sessionSecret, id, username } = await (0, fetchSessionSecretAndUser_1.fetchSessionSecretAndUserAsync)(input);
159
171
  await this.setSessionAsync({
@@ -0,0 +1,38 @@
1
+ import { z } from 'zod';
2
+ import SessionManager from './SessionManager';
3
+ declare const terminalErrorSchema: z.ZodEnum<{
4
+ access_denied: "access_denied";
5
+ expired_token: "expired_token";
6
+ invalid_grant: "invalid_grant";
7
+ }>;
8
+ type PendingDeviceLogin = {
9
+ request_id: string;
10
+ verification_uri: string;
11
+ verification_uri_complete: string;
12
+ user_code: string;
13
+ expires_at: string;
14
+ retry_after: number;
15
+ };
16
+ export type DeviceLoginResult = {
17
+ request_id: string;
18
+ status: 'authenticated';
19
+ username: string;
20
+ } | {
21
+ request_id: string;
22
+ status: z.infer<typeof terminalErrorSchema>;
23
+ } | (PendingDeviceLogin & ({
24
+ status: 'authorization_pending' | 'slow_down';
25
+ } | {
26
+ status: 'matching_required';
27
+ match_options: string[];
28
+ }));
29
+ export declare function isDeviceLoginFailure(result: {
30
+ status: string;
31
+ }): result is {
32
+ status: z.infer<typeof terminalErrorSchema>;
33
+ };
34
+ export declare function startDeviceLoginAsync(): Promise<PendingDeviceLogin & {
35
+ status: 'authorization_pending';
36
+ }>;
37
+ export declare function resumeDeviceLoginAsync(requestId: string, sessionManager: SessionManager, match?: string): Promise<DeviceLoginResult>;
38
+ export {};
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isDeviceLoginFailure = isDeviceLoginFailure;
4
+ exports.startDeviceLoginAsync = startDeviceLoginAsync;
5
+ exports.resumeDeviceLoginAsync = resumeDeviceLoginAsync;
6
+ const tslib_1 = require("tslib");
7
+ const json_file_1 = tslib_1.__importDefault(require("@expo/json-file"));
8
+ const crypto_1 = require("crypto");
9
+ const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
10
+ const os_1 = tslib_1.__importDefault(require("os"));
11
+ const path_1 = tslib_1.__importDefault(require("path"));
12
+ const zod_1 = require("zod");
13
+ const api_1 = require("../api");
14
+ const fetch_1 = tslib_1.__importStar(require("../fetch"));
15
+ const paths_1 = require("../utils/paths");
16
+ const grantSchema = zod_1.z.object({
17
+ device_code: zod_1.z.string().min(1),
18
+ user_code: zod_1.z.string().min(1),
19
+ verification_uri: zod_1.z.url(),
20
+ expires_in: zod_1.z.number().positive(),
21
+ interval: zod_1.z.number().positive(),
22
+ });
23
+ const terminalErrorSchema = zod_1.z.enum(['access_denied', 'expired_token', 'invalid_grant']);
24
+ const tokenSchema = zod_1.z.union([
25
+ zod_1.z.object({ session_secret: zod_1.z.string().min(1), expires_at: zod_1.z.iso.datetime() }),
26
+ zod_1.z.object({ error: zod_1.z.literal('matching_required'), match_options: zod_1.z.array(zod_1.z.string()).min(1) }),
27
+ zod_1.z.object({ error: zod_1.z.enum(['authorization_pending', 'slow_down']).or(terminalErrorSchema) }),
28
+ ]);
29
+ const stateSchema = zod_1.z.object({
30
+ apiUrl: zod_1.z.string(),
31
+ deviceCode: zod_1.z.string(),
32
+ userCode: zod_1.z.string(),
33
+ verificationUri: zod_1.z.string(),
34
+ expiresAt: zod_1.z.number(),
35
+ interval: zod_1.z.number(),
36
+ nextPollAt: zod_1.z.number(),
37
+ sessionSecret: zod_1.z.string().optional(),
38
+ });
39
+ function isDeviceLoginFailure(result) {
40
+ return terminalErrorSchema.safeParse(result.status).success;
41
+ }
42
+ function getRequestPath(requestId) {
43
+ if (!zod_1.z.uuid().safeParse(requestId).success) {
44
+ throw new Error('Invalid device login request ID. Start again with eas login --device.');
45
+ }
46
+ return path_1.default.join(path_1.default.dirname((0, paths_1.getStateJsonPath)()), 'device-login', `${requestId}.json`);
47
+ }
48
+ async function postAsync(endpoint, body) {
49
+ const response = await (0, fetch_1.default)(`${(0, api_1.getExpoApiBaseUrl)()}/v2/auth/${endpoint}`, {
50
+ method: 'POST',
51
+ headers: { 'Content-Type': 'application/json' },
52
+ body: JSON.stringify({ client_id: 'eas-cli', ...body }),
53
+ timeout: 30_000,
54
+ });
55
+ return (await response.json()).data;
56
+ }
57
+ function publicResult(requestId, state) {
58
+ const verificationUrl = new URL(state.verificationUri);
59
+ verificationUrl.searchParams.set('user_code', state.userCode);
60
+ return {
61
+ request_id: requestId,
62
+ status: 'authorization_pending',
63
+ verification_uri: state.verificationUri,
64
+ verification_uri_complete: verificationUrl.toString(),
65
+ user_code: state.userCode,
66
+ expires_at: new Date(state.expiresAt).toISOString(),
67
+ retry_after: Math.max(0, Math.ceil((state.nextPollAt - Date.now()) / 1000)),
68
+ };
69
+ }
70
+ async function startDeviceLoginAsync() {
71
+ const result = grantSchema.safeParse(await postAsync('device_authorization', {
72
+ device_name: os_1.default.hostname().slice(0, 255),
73
+ device_platform: os_1.default.platform(),
74
+ device_os_version: os_1.default.release().slice(0, 64),
75
+ }));
76
+ if (!result.success) {
77
+ throw new Error('Unexpected device authorization response. Try again or update EAS CLI.');
78
+ }
79
+ const grant = result.data;
80
+ const requestId = (0, crypto_1.randomUUID)();
81
+ const requestPath = getRequestPath(requestId);
82
+ await fs_extra_1.default.mkdir(path_1.default.dirname(requestPath), { recursive: true, mode: 0o700 });
83
+ const state = {
84
+ apiUrl: (0, api_1.getExpoApiBaseUrl)(),
85
+ deviceCode: grant.device_code,
86
+ userCode: grant.user_code,
87
+ verificationUri: grant.verification_uri,
88
+ expiresAt: Date.now() + grant.expires_in * 1000,
89
+ interval: Math.max(5, grant.interval),
90
+ nextPollAt: Date.now() + Math.max(5, grant.interval) * 1000,
91
+ };
92
+ // JsonFile preserves this mode when atomically replacing the file on subsequent writes.
93
+ await fs_extra_1.default.writeFile(requestPath, '{}', { mode: 0o600, flag: 'wx' });
94
+ await json_file_1.default.writeAsync(requestPath, state);
95
+ return publicResult(requestId, state);
96
+ }
97
+ // Resume one request at a time, as with other CLI session updates. State survives between
98
+ // invocations; concurrent commands for the same request are not serialized.
99
+ async function resumeDeviceLoginAsync(requestId, sessionManager, match) {
100
+ if (match !== undefined && !/^\d{1,8}$/.test(match)) {
101
+ throw new Error('--match must be the number the user sees in their browser.');
102
+ }
103
+ const requestPath = getRequestPath(requestId);
104
+ if (!(await fs_extra_1.default.pathExists(requestPath))) {
105
+ throw new Error('Device login request not found. Start again with eas login --device.');
106
+ }
107
+ const parsed = stateSchema.safeParse(await json_file_1.default.readAsync(requestPath));
108
+ if (!parsed.success) {
109
+ throw new Error('Invalid saved device login. Start again with eas login --device.');
110
+ }
111
+ const state = parsed.data;
112
+ if (state.apiUrl !== (0, api_1.getExpoApiBaseUrl)()) {
113
+ throw new Error('Resume device login in the same Expo API environment where it was started.');
114
+ }
115
+ if (state.expiresAt <= Date.now()) {
116
+ await fs_extra_1.default.remove(requestPath);
117
+ return { request_id: requestId, status: 'expired_token' };
118
+ }
119
+ if (!state.sessionSecret) {
120
+ if (state.nextPollAt > Date.now()) {
121
+ return publicResult(requestId, state);
122
+ }
123
+ // Persist the deadline before polling so errors and process restarts respect the interval.
124
+ state.nextPollAt = Date.now() + state.interval * 1000;
125
+ await json_file_1.default.writeAsync(requestPath, state);
126
+ let data;
127
+ let retryAfter = 0;
128
+ try {
129
+ data = await postAsync('token', {
130
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
131
+ device_code: state.deviceCode,
132
+ ...(match !== undefined ? { match_value: match } : {}),
133
+ });
134
+ }
135
+ catch (error) {
136
+ if (!(error instanceof fetch_1.RequestError) || error.response.status !== 429) {
137
+ throw error;
138
+ }
139
+ const header = error.response.headers.get('retry-after');
140
+ const seconds = header ? Number(header) : NaN;
141
+ const delay = Number.isFinite(seconds)
142
+ ? seconds
143
+ : (Date.parse(header ?? '') - Date.now()) / 1000;
144
+ retryAfter = Number.isFinite(delay) ? delay : 60;
145
+ data = { error: 'slow_down' };
146
+ }
147
+ const result = tokenSchema.safeParse(data);
148
+ if (!result.success) {
149
+ throw new Error('Unexpected device token response. Resume this request to retry.');
150
+ }
151
+ if ('error' in result.data) {
152
+ const response = result.data;
153
+ const failure = { request_id: requestId, status: response.error };
154
+ if (isDeviceLoginFailure(failure)) {
155
+ await fs_extra_1.default.remove(requestPath);
156
+ return failure;
157
+ }
158
+ switch (response.error) {
159
+ case 'slow_down':
160
+ state.interval += 5;
161
+ state.nextPollAt = Date.now() + Math.max(state.interval, retryAfter) * 1000;
162
+ await json_file_1.default.writeAsync(requestPath, state);
163
+ return { ...publicResult(requestId, state), status: 'slow_down' };
164
+ case 'matching_required':
165
+ return {
166
+ ...publicResult(requestId, state),
167
+ status: response.error,
168
+ match_options: response.match_options,
169
+ };
170
+ }
171
+ return publicResult(requestId, state);
172
+ }
173
+ // The grant is single-use. Persist its secret before fetching the user/installing the
174
+ // session, so a later invocation can finish if those operations fail.
175
+ state.sessionSecret = result.data.session_secret;
176
+ state.expiresAt = Date.parse(result.data.expires_at);
177
+ await json_file_1.default.writeAsync(requestPath, state);
178
+ }
179
+ const username = await sessionManager.loginWithDeviceSessionAsync(state.sessionSecret);
180
+ await fs_extra_1.default.remove(requestPath);
181
+ return { request_id: requestId, status: 'authenticated', username };
182
+ }
@@ -118,8 +118,10 @@ async function getAppPathAsync(outputDir, applicationExtension) {
118
118
  if (appFilePaths.length === 0) {
119
119
  throw Error('Did not find any installable apps inside tarball.');
120
120
  }
121
- if (appFilePaths.length === 1) {
122
- return path_1.default.join(outputDir, appFilePaths[0]);
121
+ // App Clips are nested inside their containing iOS app and cannot be run independently.
122
+ const installableAppPaths = appFilePaths.filter(filePath => !appFilePaths.some(parentPath => filePath.startsWith(`${parentPath}/`)));
123
+ if (installableAppPaths.length === 1) {
124
+ return path_1.default.join(outputDir, installableAppPaths[0]);
123
125
  }
124
126
  log_1.default.newLine();
125
127
  log_1.default.log('Detected multiple apps in the tarball:');
@@ -129,7 +131,7 @@ async function getAppPathAsync(outputDir, applicationExtension) {
129
131
  message: 'Select the app to run:',
130
132
  name: 'selectedFile',
131
133
  choices: [
132
- ...appFilePaths.map(filePath => ({
134
+ ...installableAppPaths.map(filePath => ({
133
135
  title: filePath,
134
136
  value: filePath,
135
137
  })),