eas-cli 24.10.0 → 24.11.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.
@@ -76,6 +76,10 @@ export declare function setAnalyticsEnabledAsync(enabled: boolean): Promise<void
76
76
  * Returns the user's analytics enabled preference.
77
77
  */
78
78
  export declare function getAnalyticsEnabledAsync(): Promise<boolean>;
79
+ /**
80
+ * Returns true when the user opted out of analytics with DISABLE_EAS_ANALYTICS or `eas analytics off`.
81
+ */
82
+ export declare function isAnalyticsOptedOutAsync(): Promise<boolean>;
79
83
  /**
80
84
  * Create an instance of Analytics based on the user's analytics enabled preferences.
81
85
  */
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MetadataEvent = exports.BuildEvent = exports.SubmissionEvent = exports.BillingEvent = exports.CommandEvent = void 0;
4
4
  exports.setAnalyticsEnabledAsync = setAnalyticsEnabledAsync;
5
5
  exports.getAnalyticsEnabledAsync = getAnalyticsEnabledAsync;
6
+ exports.isAnalyticsOptedOutAsync = isAnalyticsOptedOutAsync;
6
7
  exports.createAnalyticsAsync = createAnalyticsAsync;
7
8
  const tslib_1 = require("tslib");
8
9
  const rudder_sdk_node_1 = tslib_1.__importDefault(require("@expo/rudder-sdk-node"));
@@ -94,6 +95,15 @@ async function getAnalyticsEnabledAsync() {
94
95
  const analyticsEnabled = await UserSettings_1.default.getAsync(USER_SETTINGS_KEY_ANALYTICS_ENABLED, null);
95
96
  return !!analyticsEnabled;
96
97
  }
98
+ /**
99
+ * Returns true when the user opted out of analytics with DISABLE_EAS_ANALYTICS or `eas analytics off`.
100
+ */
101
+ async function isAnalyticsOptedOutAsync() {
102
+ if (process.env.DISABLE_EAS_ANALYTICS) {
103
+ return true;
104
+ }
105
+ return (await UserSettings_1.default.getAsync(USER_SETTINGS_KEY_ANALYTICS_ENABLED, true)) === false;
106
+ }
97
107
  /**
98
108
  * Create an instance of Analytics based on the user's analytics enabled preferences.
99
109
  */
@@ -2,13 +2,19 @@ import EasCommand from '../../commandUtils/EasCommand';
2
2
  export default class AccountLogin extends EasCommand {
3
3
  static description: string;
4
4
  static aliases: string[];
5
+ static examples: string[];
5
6
  static flags: {
7
+ resume: import("@oclif/core/lib/interfaces").OptionFlag<string | undefined, import("@oclif/core/lib/interfaces").CustomOptions>;
8
+ match: import("@oclif/core/lib/interfaces").OptionFlag<string | undefined, import("@oclif/core/lib/interfaces").CustomOptions>;
6
9
  sso: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
7
10
  browser: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
11
+ 'non-interactive': import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
12
+ device: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
8
13
  };
9
14
  static contextDefinition: {
10
15
  sessionManager: import("../../commandUtils/context/SessionManagementContextField").default;
11
16
  maybeLoggedIn: import("../../commandUtils/context/MaybeLoggedInContextField").default;
12
17
  };
13
18
  runAsync(): Promise<void>;
19
+ private runDeviceLoginAsync;
14
20
  }
@@ -4,13 +4,33 @@ const tslib_1 = require("tslib");
4
4
  const core_1 = require("@oclif/core");
5
5
  const chalk_1 = tslib_1.__importDefault(require("chalk"));
6
6
  const EasCommand_1 = tslib_1.__importDefault(require("../../commandUtils/EasCommand"));
7
+ const flags_1 = require("../../commandUtils/flags");
7
8
  const log_1 = tslib_1.__importDefault(require("../../log"));
8
9
  const prompts_1 = require("../../prompts");
9
10
  const User_1 = require("../../user/User");
11
+ const deviceLogin_1 = require("../../user/deviceLogin");
10
12
  class AccountLogin extends EasCommand_1.default {
11
13
  static description = 'log in with your Expo account';
12
14
  static aliases = ['login'];
15
+ static examples = [
16
+ '<%= config.bin %> login --device',
17
+ '<%= config.bin %> login --device --non-interactive',
18
+ '<%= config.bin %> login --device --non-interactive --resume REQUEST_ID --match NUMBER_FROM_USER',
19
+ ];
13
20
  static flags = {
21
+ device: core_1.Flags.boolean({
22
+ description: 'Log in using a code in a browser on any device',
23
+ exclusive: ['sso'],
24
+ }),
25
+ ...flags_1.EASNonInteractiveFlag,
26
+ resume: core_1.Flags.string({
27
+ description: 'Resume a saved device login using its request ID (one command at a time)',
28
+ dependsOn: ['device'],
29
+ }),
30
+ match: core_1.Flags.string({
31
+ description: 'Submit the number the user sees in their browser',
32
+ dependsOn: ['device', 'resume'],
33
+ }),
14
34
  // can pass either --sso or -s
15
35
  sso: core_1.Flags.boolean({
16
36
  description: 'Log in with SSO',
@@ -29,22 +49,84 @@ class AccountLogin extends EasCommand_1.default {
29
49
  ...this.ContextOptions.SessionManagment,
30
50
  };
31
51
  async runAsync() {
32
- const { flags: { sso, browser }, } = await this.parse(AccountLogin);
33
- const { sessionManager, maybeLoggedIn: { actor }, } = await this.getContextAsync(AccountLogin, { nonInteractive: false });
52
+ const { flags: { sso, browser, device, 'non-interactive': nonInteractive, resume, match }, } = await this.parse(AccountLogin);
53
+ if (nonInteractive && !device) {
54
+ throw new Error('Use eas login --device --non-interactive to log in without prompts.');
55
+ }
56
+ const { sessionManager, maybeLoggedIn: { actor }, } = await this.getContextAsync(AccountLogin, { nonInteractive });
34
57
  if (sessionManager.getAccessToken()) {
35
- throw new Error('EXPO_TOKEN is set in your environment, and is being used for all EAS authentication. To use username/password authentication, unset EXPO_TOKEN in your environment and re-run the command.');
58
+ throw new Error('EXPO_TOKEN is set in your environment, and is being used for all EAS authentication. Unset EXPO_TOKEN to log in with an Expo account.');
36
59
  }
37
- if (actor) {
60
+ if (actor && !resume) {
38
61
  log_1.default.warn(`You are already logged in as ${chalk_1.default.bold((0, User_1.getActorDisplayName)(actor))}.`);
39
- const shouldContinue = await (0, prompts_1.confirmAsync)({
40
- message: 'Do you want to continue?',
41
- });
62
+ const shouldContinue = nonInteractive ||
63
+ (await (0, prompts_1.confirmAsync)({
64
+ message: 'Do you want to continue?',
65
+ }));
42
66
  if (!shouldContinue) {
43
67
  core_1.Errors.error('Aborted', { exit: 1 });
44
68
  }
45
69
  }
70
+ if (device) {
71
+ await this.runDeviceLoginAsync(sessionManager, { nonInteractive, resume, match });
72
+ return;
73
+ }
46
74
  await sessionManager.showLoginPromptAsync({ sso, browser });
47
75
  log_1.default.log('Logged in');
48
76
  }
77
+ async runDeviceLoginAsync(sessionManager, options) {
78
+ let result = options.resume
79
+ ? await (0, deviceLogin_1.resumeDeviceLoginAsync)(options.resume, sessionManager, options.match)
80
+ : await (0, deviceLogin_1.startDeviceLoginAsync)();
81
+ if (options.nonInteractive) {
82
+ if ((0, deviceLogin_1.isDeviceLoginFailure)(result)) {
83
+ throw new Error(`Device login failed (${result.status}). Start again with eas login --device.`);
84
+ }
85
+ if (result.status === 'authenticated') {
86
+ log_1.default.log(`Logged in as ${result.username}`);
87
+ return;
88
+ }
89
+ const resumeCommand = `eas login --device --non-interactive --resume ${result.request_id}`;
90
+ if (!options.resume) {
91
+ log_1.default.log(`Open ${result.verification_uri_complete}`);
92
+ log_1.default.log(`Code: ${result.user_code}`);
93
+ log_1.default.log('Ask the user to approve the login in their browser and send you any number shown.');
94
+ log_1.default.log(`Then run ${resumeCommand}, adding --match NUMBER_FROM_USER if they saw a number.`);
95
+ }
96
+ else if (result.status === 'matching_required') {
97
+ log_1.default.log('Ask the user for the number shown in their browser, then run:');
98
+ log_1.default.log(`${resumeCommand} --match NUMBER_FROM_USER`);
99
+ }
100
+ else {
101
+ log_1.default.log(`Approval pending. Retry after ${result.retry_after} seconds:`);
102
+ log_1.default.log(`${resumeCommand}${options.match ? ` --match ${options.match}` : ''}`);
103
+ }
104
+ return;
105
+ }
106
+ if ('verification_uri_complete' in result) {
107
+ log_1.default.log(`Open ${result.verification_uri_complete}`);
108
+ log_1.default.log(`Code: ${result.user_code}`);
109
+ log_1.default.log(`You can resume with eas login --device --resume ${result.request_id}`);
110
+ }
111
+ let match = options.match;
112
+ while (result.status !== 'authenticated') {
113
+ if ((0, deviceLogin_1.isDeviceLoginFailure)(result)) {
114
+ throw new Error(`Device login failed (${result.status}). Start again with eas login --device.`);
115
+ }
116
+ if (result.status === 'matching_required') {
117
+ const answer = await (0, prompts_1.promptAsync)({
118
+ type: 'select',
119
+ name: 'match',
120
+ message: 'Select the number shown in your browser',
121
+ choices: result.match_options.map(value => ({ title: value, value })),
122
+ });
123
+ match = answer.match;
124
+ }
125
+ const delayMs = result.retry_after * 1000;
126
+ await new Promise(resolve => setTimeout(resolve, delayMs));
127
+ result = await (0, deviceLogin_1.resumeDeviceLoginAsync)(result.request_id, sessionManager, match);
128
+ }
129
+ log_1.default.log(`Logged in as ${result.username}`);
130
+ }
49
131
  }
50
132
  exports.default = AccountLogin;
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
4
  const core_1 = require("@oclif/core");
5
5
  const nullthrows_1 = tslib_1.__importDefault(require("nullthrows"));
6
+ const AnalyticsManager_1 = require("../../analytics/AnalyticsManager");
7
+ const agent_1 = require("../../analytics/agent");
6
8
  const url_1 = require("../../build/utils/url");
7
9
  const EasCommand_1 = tslib_1.__importDefault(require("../../commandUtils/EasCommand"));
8
10
  const errors_1 = require("../../commandUtils/errors");
@@ -219,6 +221,7 @@ class Simulator extends EasCommand_1.default {
219
221
  let deviceRunSessionUrl;
220
222
  let sessionInterrupt;
221
223
  try {
224
+ const agentIdentity = await agentIdentityInputAsync();
222
225
  const session = await DeviceRunSessionMutation_1.DeviceRunSessionMutation.createDeviceRunSessionAsync(graphqlClient, {
223
226
  appId: projectId,
224
227
  name,
@@ -243,6 +246,8 @@ class Simulator extends EasCommand_1.default {
243
246
  ...(openUrl ? { openUrl } : {}),
244
247
  ...(resourceClass ? { resourceClass } : {}),
245
248
  ...(egress ? { egress } : {}),
249
+ requestOrigin: generated_1.DeviceRunSessionRequestOrigin.EasCli,
250
+ ...agentIdentity,
246
251
  maxRunTimeMinutes: flags['max-duration-minutes'],
247
252
  maxIdleTimeMinutes: flags['max-idle-time-minutes'],
248
253
  });
@@ -551,3 +556,13 @@ async function ensureDeviceRunSessionStoppedSafelyAsync(graphqlClient, deviceRun
551
556
  return false;
552
557
  }
553
558
  }
559
+ async function agentIdentityInputAsync() {
560
+ if (await (0, AnalyticsManager_1.isAnalyticsOptedOutAsync)()) {
561
+ return {};
562
+ }
563
+ const agent = (0, agent_1.getAgentTelemetryContext)();
564
+ if (!agent) {
565
+ return {};
566
+ }
567
+ return { agentId: agent.id, ...(agent.sessionId ? { agentSessionId: agent.sessionId } : {}) };
568
+ }
@@ -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
+ }