@contrail/cli 3.6.0 → 3.7.0-alpha.3c9e156

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.
package/README.md CHANGED
@@ -17,7 +17,7 @@ $ npm install -g @contrail/cli
17
17
  $ contrail COMMAND
18
18
  running command...
19
19
  $ contrail (--version)
20
- @contrail/cli/3.6.0 linux-x64 node-v24.22.2
20
+ @contrail/cli/3.7.0-alpha.3c9e156 linux-x64 node-v24.22.3
21
21
  $ contrail --help [COMMAND]
22
22
  USAGE
23
23
  $ contrail COMMAND
@@ -45,6 +45,7 @@ To get instructions on how to set up autocomplete for your shell, run `contrail
45
45
  * [`contrail app version major`](#contrail-app-version-major)
46
46
  * [`contrail app version minor`](#contrail-app-version-minor)
47
47
  * [`contrail app version patch`](#contrail-app-version-patch)
48
+ * [`contrail app version prerelease`](#contrail-app-version-prerelease)
48
49
  * [`contrail autocomplete [SHELL]`](#contrail-autocomplete-shell)
49
50
  * [`contrail config create`](#contrail-config-create)
50
51
  * [`contrail config describe [NAME]`](#contrail-config-describe-name)
@@ -67,6 +68,7 @@ To get instructions on how to set up autocomplete for your shell, run `contrail
67
68
  * [`contrail load custom-entity DATAFILE CONFIGFILE`](#contrail-load-custom-entity-datafile-configfile)
68
69
  * [`contrail load line-sheet DATAFILE CONFIGFILE`](#contrail-load-line-sheet-datafile-configfile)
69
70
  * [`contrail load upload-and-load INCOMINGFILE CONFIGFILENAME`](#contrail-load-upload-and-load-incomingfile-configfilename)
71
+ * [`contrail login`](#contrail-login)
70
72
  * [`contrail org-config export`](#contrail-org-config-export)
71
73
  * [`contrail org-config import`](#contrail-org-config-import)
72
74
  * [`contrail projects export PROJECTNAME`](#contrail-projects-export-projectname)
@@ -263,7 +265,7 @@ EXAMPLES
263
265
 
264
266
  ## `contrail app publish`
265
267
 
266
- Publish the app to the marketplace. This visibility of your app depends on the app.yml configuration ("visibility" property)
268
+ Publish the app to the marketplace. This visibility of your app depends on the app.yml configuration ("visibility" property). A pre-release version (e.g. "1.4.0-alpha.1") is published without becoming the latest version of the app.
267
269
 
268
270
  ```
269
271
  USAGE
@@ -281,7 +283,7 @@ FLAGS
281
283
 
282
284
  DESCRIPTION
283
285
  Publish the app to the marketplace. This visibility of your app depends on the app.yml configuration ("visibility"
284
- property)
286
+ property). A pre-release version (e.g. "1.4.0-alpha.1") is published without becoming the latest version of the app.
285
287
 
286
288
  EXAMPLES
287
289
  $ contrail app publish
@@ -396,6 +398,28 @@ EXAMPLES
396
398
  $ contrail app version patch
397
399
  ```
398
400
 
401
+ ## `contrail app version prerelease`
402
+
403
+ Upgrade the Pre-release app version. A stable version becomes the first alpha of the next patch (1.2.3 to 1.2.4-alpha.0). A pre-release version gets its number bumped (1.2.4-alpha.0 to 1.2.4-alpha.1).
404
+
405
+ ```
406
+ USAGE
407
+ $ contrail app version prerelease [-l error|warn|info|debug] [-e true|false]
408
+
409
+ FLAGS
410
+ -e, --alwaysConfirmEnv=<option> [default: true] The Environment variables
411
+ <options: true|false>
412
+ -l, --logLevel=<option> The Log Level
413
+ <options: error|warn|info|debug>
414
+
415
+ DESCRIPTION
416
+ Upgrade the Pre-release app version. A stable version becomes the first alpha of the next patch (1.2.3 to
417
+ 1.2.4-alpha.0). A pre-release version gets its number bumped (1.2.4-alpha.0 to 1.2.4-alpha.1).
418
+
419
+ EXAMPLES
420
+ $ contrail app version prerelease
421
+ ```
422
+
399
423
  ## `contrail autocomplete [SHELL]`
400
424
 
401
425
  display autocomplete installation instructions
@@ -1009,6 +1033,30 @@ EXAMPLES
1009
1033
  $ contrail load-processor upload-and-load <File Path> <Config Path>
1010
1034
  ```
1011
1035
 
1036
+ ## `contrail login`
1037
+
1038
+ Sign in to VibeIQ with SSO or your email and password
1039
+
1040
+ ```
1041
+ USAGE
1042
+ $ contrail login [-l error|warn|info|debug] [-e true|false] [--browser]
1043
+
1044
+ FLAGS
1045
+ -e, --alwaysConfirmEnv=<option> [default: true] The Environment variables
1046
+ <options: true|false>
1047
+ -l, --logLevel=<option> The Log Level
1048
+ <options: error|warn|info|debug>
1049
+ --[no-]browser Open a browser for SSO. Use --no-browser to paste a sign-in code instead.
1050
+
1051
+ DESCRIPTION
1052
+ Sign in to VibeIQ with SSO or your email and password
1053
+
1054
+ EXAMPLES
1055
+ $ contrail login
1056
+
1057
+ $ contrail login --no-browser
1058
+ ```
1059
+
1012
1060
  ## `contrail org-config export`
1013
1061
 
1014
1062
  Export the org config for your Org
@@ -1,3 +1,7 @@
1
1
  import { AuthContext } from '@contrail/sdk';
2
+ export interface SignInOptions {
3
+ shouldOpenBrowser: boolean;
4
+ }
2
5
  export declare function authUser(): Promise<AuthContext>;
6
+ export declare function signIn(options: SignInOptions): Promise<AuthContext>;
3
7
  export declare function getVersionFromPackageJson(): string;
@@ -1,18 +1,36 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getVersionFromPackageJson = exports.authUser = void 0;
3
+ exports.getVersionFromPackageJson = exports.signIn = exports.authUser = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const amazon_cognito_identity_js_1 = require("amazon-cognito-identity-js");
6
6
  const sdk_1 = require("@contrail/sdk");
7
7
  const config_1 = require("../helpers/config/config");
8
8
  const logger_1 = tslib_1.__importDefault(require("../logger"));
9
+ const sso_1 = require("./sso");
10
+ const sign_in_error_1 = require("./sign-in-error");
9
11
  const path_1 = tslib_1.__importDefault(require("path"));
10
12
  const fs_1 = tslib_1.__importDefault(require("fs"));
11
13
  const common_1 = require("../common");
12
14
  const DEFAULT_API_GATEWAY = config_1.ENVIRONMENTS.prod;
13
15
  const COGNITO_CONFIGS = {
14
- dev: { userPoolId: 'us-east-1_e2cA0nJWu', clientId: '209s9c62o165cqab0fu5ihjtu9' },
15
- prod: { userPoolId: 'us-east-1_qIaNZdUfm', clientId: '7knkt34gfacbgd0ghnuspefdfg' },
16
+ dev: {
17
+ userPoolId: 'us-east-1_e2cA0nJWu',
18
+ clientId: '209s9c62o165cqab0fu5ihjtu9',
19
+ sso: {
20
+ domain: 'https://dev-vibeiq.auth.us-east-1.amazoncognito.com',
21
+ clientId: '2d1cke4drm5rd1mcvpcq3d6sq6',
22
+ pastedCodeCallbackUrl: 'https://login.dev.vibeiq.com/cli',
23
+ },
24
+ },
25
+ prod: {
26
+ userPoolId: 'us-east-1_qIaNZdUfm',
27
+ clientId: '7knkt34gfacbgd0ghnuspefdfg',
28
+ sso: {
29
+ domain: 'https://prod-vibeiq.auth.us-east-1.amazoncognito.com',
30
+ clientId: '49dr6o3kv1ot88evq0cfblnb83',
31
+ pastedCodeCallbackUrl: 'https://login.vibeiq.com/cli',
32
+ },
33
+ },
16
34
  };
17
35
  async function authUser() {
18
36
  logger_1.default.debug('authorizing user...');
@@ -37,7 +55,7 @@ async function authUser() {
37
55
  };
38
56
  (0, sdk_1.setConfig)(sdk_1.Auth.config);
39
57
  try {
40
- return await signInWithStoredTokens();
58
+ return await signInWithStoredTokens(config.signInMethod ?? 'password');
41
59
  }
42
60
  catch (e) {
43
61
  logger_1.default.debug(`stored tokens rejected: ${e?.message}`);
@@ -48,9 +66,86 @@ async function authUser() {
48
66
  logger_1.default.info('Token expired. Requesting auth credentials...');
49
67
  }
50
68
  }
51
- return await authenticateWithUsernamePassword(config);
69
+ return await signIn({ shouldOpenBrowser: true });
52
70
  }
53
71
  exports.authUser = authUser;
72
+ async function signIn(options) {
73
+ const config = await (0, config_1.getConfig)();
74
+ const apiGateway = getApiGateway(config);
75
+ const environment = getSignInEnvironment(apiGateway);
76
+ const email = process.env.CONTRAIL_CLI_EMAIL || (await promptForEmail());
77
+ const params = {
78
+ email,
79
+ orgSlug: await getOrgSlug(config),
80
+ apiGateway,
81
+ environment,
82
+ };
83
+ if (process.env.CONTRAIL_CLI_PASSWORD) {
84
+ return authenticateWithUsernamePassword(params);
85
+ }
86
+ const domainCheck = await (0, sso_1.fetchSsoDomainCheck)(email, apiGateway);
87
+ if (domainCheck.kind === 'cognito') {
88
+ return signInWithSso(params, domainCheck.identityProvider, options);
89
+ }
90
+ if (domainCheck.kind === 'legacy') {
91
+ console.log('The CLI does not support your SSO provider yet. Sign in with your VibeIQ password, or set CONTRAIL_CLI_API_KEY.');
92
+ }
93
+ return authenticateWithUsernamePassword(params);
94
+ }
95
+ exports.signIn = signIn;
96
+ function getSignInEnvironment(apiGateway) {
97
+ const environment = (0, config_1.findEnvironmentName)(apiGateway);
98
+ if (!environment) {
99
+ throw new sign_in_error_1.SignInError('ENVIRONMENT_NOT_CONFIGURED', 'Sign-in works only for dev and prod. Use CONTRAIL_CLI_API_KEY for other environments.', { apiGateway });
100
+ }
101
+ return environment;
102
+ }
103
+ async function promptForEmail() {
104
+ const answers = await (0, common_1.promptOnStderr)([
105
+ { type: 'input', name: 'email', validate: (val) => !!val, message: 'Email' },
106
+ ]);
107
+ return answers.email;
108
+ }
109
+ async function signInWithSso(params, identityProvider, options) {
110
+ const ssoClient = COGNITO_CONFIGS[params.environment].sso;
111
+ const signInAttempt = (0, sso_1.createSignInAttempt)();
112
+ const usesLoopback = options.shouldOpenBrowser && (0, sso_1.canOpenBrowser)();
113
+ const redirectUri = usesLoopback ? sso_1.LOOPBACK_CALLBACK_URL : ssoClient.pastedCodeCallbackUrl;
114
+ const authorizeUrl = (0, sso_1.buildAuthorizeUrl)(ssoClient, identityProvider, redirectUri, signInAttempt);
115
+ let code;
116
+ if (usesLoopback) {
117
+ const loopbackListener = await (0, sso_1.listenForLoopbackCode)(signInAttempt.state);
118
+ console.log(`Opening your browser to sign in. If it does not open, visit:\n${authorizeUrl}`);
119
+ try {
120
+ await (0, sso_1.openBrowser)(authorizeUrl);
121
+ }
122
+ catch (error) {
123
+ if (error?.code !== 'ENOENT') {
124
+ loopbackListener.stop();
125
+ throw error;
126
+ }
127
+ console.log('Could not find a browser to open. Open the URL above to sign in.');
128
+ }
129
+ code = await loopbackListener.code;
130
+ }
131
+ else {
132
+ console.log(`Open this URL in any browser to sign in:\n${authorizeUrl}`);
133
+ const answers = await (0, common_1.promptOnStderr)([
134
+ { type: 'input', name: 'signInCode', validate: (val) => !!val, message: 'Sign-in code' },
135
+ ]);
136
+ code = (0, sso_1.parsePastedSignInCode)(answers.signInCode, signInAttempt.state);
137
+ }
138
+ const tokens = await (0, sso_1.exchangeCodeForTokens)(ssoClient, code, redirectUri, signInAttempt.verifier);
139
+ sdk_1.Auth.config = {
140
+ apiUserToken: tokens.accessToken,
141
+ apiRefreshToken: tokens.refreshToken,
142
+ apiGateway: params.apiGateway,
143
+ orgSlug: params.orgSlug,
144
+ };
145
+ (0, sdk_1.setConfig)(sdk_1.Auth.config);
146
+ await (0, sdk_1.getCurrentUser)();
147
+ return returnAndStoreConfig(sdk_1.Auth.config, 'sso');
148
+ }
54
149
  async function getOrgSlug(config) {
55
150
  const orgSlug = config?.orgSlug || process.env.CONTRAIL_CLI_ORG_SLUG;
56
151
  if (!orgSlug) {
@@ -76,43 +171,11 @@ async function authenticateWithApiKey(config, apiKey, orgSlug) {
76
171
  };
77
172
  (0, sdk_1.setConfig)(sdk_1.Auth.config);
78
173
  await (0, sdk_1.getCurrentUser)();
79
- return returnAndStoreConfig(sdk_1.Auth.config);
174
+ return returnAndStoreConfig(sdk_1.Auth.config, 'apiKey');
80
175
  }
81
- async function authenticateWithUsernamePassword(config) {
82
- const apiGateway = getApiGateway(config);
83
- const environment = (0, config_1.findEnvironmentName)(apiGateway);
84
- if (!environment) {
85
- throw new Error(`No Cognito user pool is known for ${apiGateway}. Email and password sign-in works for ${Object.keys(COGNITO_CONFIGS).join(' and ')}; use CONTRAIL_CLI_API_KEY for other environments.`);
86
- }
87
- const cognitoConfig = COGNITO_CONFIGS[environment];
88
- const questions = [];
89
- if (!process.env.CONTRAIL_CLI_EMAIL) {
90
- questions.push({
91
- type: 'input',
92
- name: 'email',
93
- validate: (val) => !!val,
94
- message: 'Email',
95
- });
96
- }
97
- if (!process.env.CONTRAIL_CLI_PASSWORD) {
98
- questions.push({
99
- type: 'password',
100
- name: 'password',
101
- validate: (val) => !!val,
102
- message: 'Password',
103
- });
104
- }
105
- const answers = await (0, common_1.promptOnStderr)(questions);
106
- const params = {
107
- email: process.env.CONTRAIL_CLI_EMAIL || answers.email,
108
- password: process.env.CONTRAIL_CLI_PASSWORD || answers.password,
109
- orgSlug: await getOrgSlug(config),
110
- apiGateway,
111
- environment,
112
- };
113
- if (!params.email || !params.password) {
114
- throw new Error('Email and Password required');
115
- }
176
+ async function authenticateWithUsernamePassword(params) {
177
+ const cognitoConfig = COGNITO_CONFIGS[params.environment];
178
+ const password = process.env.CONTRAIL_CLI_PASSWORD || (await promptForPassword());
116
179
  const poolData = {
117
180
  UserPoolId: cognitoConfig.userPoolId,
118
181
  ClientId: cognitoConfig.clientId,
@@ -120,7 +183,7 @@ async function authenticateWithUsernamePassword(config) {
120
183
  const userPool = new amazon_cognito_identity_js_1.CognitoUserPool(poolData);
121
184
  const authData = {
122
185
  Username: params.email,
123
- Password: params.password,
186
+ Password: password,
124
187
  };
125
188
  const authDetails = new amazon_cognito_identity_js_1.AuthenticationDetails(authData);
126
189
  const userData = {
@@ -140,7 +203,7 @@ async function authenticateWithUsernamePassword(config) {
140
203
  },
141
204
  onFailure: (err) => {
142
205
  if (err?.code === 'ResourceNotFoundException') {
143
- reject(new Error(`This version of the CLI has outdated ${environment} sign-in settings (${err.message}). Update the CLI: npm i -g @contrail/cli`));
206
+ reject(new Error(`This version of the CLI has outdated ${params.environment} sign-in settings (${err.message}). Update the CLI: npm i -g @contrail/cli`));
144
207
  return;
145
208
  }
146
209
  reject(err);
@@ -148,6 +211,12 @@ async function authenticateWithUsernamePassword(config) {
148
211
  });
149
212
  });
150
213
  }
214
+ async function promptForPassword() {
215
+ const answers = await (0, common_1.promptOnStderr)([
216
+ { type: 'password', name: 'password', validate: (val) => !!val, message: 'Password' },
217
+ ]);
218
+ return answers.password;
219
+ }
151
220
  async function setAuthContext(user, params) {
152
221
  const apiGateway = params.apiGateway;
153
222
  const { vibeAccessToken, vibeRefreshToken } = await getVibeAccessTokenFromCognitoAccessToken(user.idToken.jwtToken, apiGateway, params.environment);
@@ -160,9 +229,9 @@ async function setAuthContext(user, params) {
160
229
  };
161
230
  // SET SDK CONFIG
162
231
  (0, sdk_1.setConfig)(sdk_1.Auth.config);
163
- return refreshCurrentUserOrg();
232
+ return refreshCurrentUserOrg('password');
164
233
  }
165
- async function signInWithStoredTokens() {
234
+ async function signInWithStoredTokens(signInMethod) {
166
235
  try {
167
236
  await (0, sdk_1.getCurrentUser)();
168
237
  }
@@ -171,24 +240,35 @@ async function signInWithStoredTokens() {
171
240
  throw e;
172
241
  }
173
242
  logger_1.default.debug('access token rejected, refreshing it...');
174
- await refreshAccessToken();
243
+ await refreshAccessToken(signInMethod);
175
244
  await (0, sdk_1.getCurrentUser)();
176
245
  }
177
- return returnAndStoreConfig(sdk_1.Auth.config);
246
+ return returnAndStoreConfig(sdk_1.Auth.config, signInMethod);
178
247
  }
179
- async function refreshCurrentUserOrg() {
248
+ async function refreshCurrentUserOrg(signInMethod) {
180
249
  logger_1.default.debug('refreshing current user org...');
181
250
  await (0, sdk_1.getCurrentUser)();
182
251
  // TODO: To uncomment when telemetry backend is developed.
183
252
  // const current_Version = getVersionFromPackageJson();
184
253
  // await checkTelemetry(current_Version);
185
- return returnAndStoreConfig(sdk_1.Auth.config);
254
+ return returnAndStoreConfig(sdk_1.Auth.config, signInMethod);
186
255
  }
187
- async function refreshAccessToken() {
188
- const newVibeAccessToken = await requestRefreshedAccessToken(sdk_1.Auth.config.apiRefreshToken, sdk_1.Auth.config.apiGateway);
189
- sdk_1.Auth.config = { ...sdk_1.Auth.config, apiUserToken: newVibeAccessToken };
256
+ async function refreshAccessToken(signInMethod) {
257
+ const newAccessToken = await fetchRefreshedAccessTokenForSignInMethod(signInMethod);
258
+ sdk_1.Auth.config = { ...sdk_1.Auth.config, apiUserToken: newAccessToken };
190
259
  (0, sdk_1.setConfig)(sdk_1.Auth.config);
191
260
  }
261
+ async function fetchRefreshedAccessTokenForSignInMethod(signInMethod) {
262
+ const { apiRefreshToken, apiGateway } = sdk_1.Auth.config;
263
+ if (signInMethod === 'sso') {
264
+ const ssoClient = COGNITO_CONFIGS[getSignInEnvironment(apiGateway)].sso;
265
+ return (0, sso_1.refreshSsoAccessToken)(ssoClient, apiRefreshToken);
266
+ }
267
+ if (signInMethod === 'apiKey') {
268
+ throw new sign_in_error_1.SignInError('API_KEY_CANNOT_REFRESH', 'An API key cannot be refreshed. Set a new one.');
269
+ }
270
+ return requestRefreshedAccessToken(apiRefreshToken, apiGateway);
271
+ }
192
272
  function getApiGateway(config) {
193
273
  return config?.apiGateway ?? DEFAULT_API_GATEWAY;
194
274
  }
@@ -238,9 +318,9 @@ function getVersionFromPackageJson() {
238
318
  return packageJson.version;
239
319
  }
240
320
  exports.getVersionFromPackageJson = getVersionFromPackageJson;
241
- async function returnAndStoreConfig(config) {
321
+ async function returnAndStoreConfig(config, signInMethod) {
242
322
  const configCopy = Object.assign({}, config);
243
- await (0, config_1.storeConfig)(configCopy);
323
+ await (0, config_1.storeConfig)({ ...configCopy, signInMethod });
244
324
  return configCopy;
245
325
  }
246
326
  function isNetworkConnectionError(e) {
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
3
4
  const amazon_cognito_identity_js_1 = require("amazon-cognito-identity-js");
4
5
  const sdk_1 = require("@contrail/sdk");
6
+ const common = tslib_1.__importStar(require("../common"));
5
7
  const config_1 = require("../helpers/config/config");
6
8
  const login_1 = require("./login");
7
9
  const mockAuthenticateUser = jest.fn();
@@ -101,14 +103,17 @@ describe('authUser with email and password', () => {
101
103
  apiGateway: 'api.dev.vibeiq.com/dev/api',
102
104
  orgSlug: 'adam-zone-1',
103
105
  });
104
- await expect((0, login_1.authUser)()).rejects.toThrow('No Cognito user pool is known for api.dev.vibeiq.com/dev/api.');
106
+ await expect((0, login_1.authUser)()).rejects.toMatchObject({
107
+ code: 'ENVIRONMENT_NOT_CONFIGURED',
108
+ details: { apiGateway: 'api.dev.vibeiq.com/dev/api' },
109
+ });
105
110
  });
106
111
  it('should fail without saving tokens when no pool is known for the environment', async () => {
107
112
  config_1.getConfig.mockResolvedValue({
108
113
  apiGateway: 'http://localhost:3000/api',
109
114
  orgSlug: 'adam-zone-1',
110
115
  });
111
- await expect((0, login_1.authUser)()).rejects.toThrow('No Cognito user pool is known for http://localhost:3000/api.');
116
+ await expect((0, login_1.authUser)()).rejects.toMatchObject({ code: 'ENVIRONMENT_NOT_CONFIGURED' });
112
117
  expect(config_1.storeConfig).not.toHaveBeenCalled();
113
118
  });
114
119
  it('should tell the user to update the CLI when its Cognito client or pool no longer exists', async () => {
@@ -169,7 +174,7 @@ describe('authUser with stored tokens', () => {
169
174
  const context = await (0, login_1.authUser)();
170
175
  expect(fetchMock).toHaveBeenCalledWith(`${DEV_GATEWAY}/auth/jwt_refresh/`, expect.objectContaining({ body: JSON.stringify({ refreshToken: 'stored-refresh' }) }));
171
176
  expect(context).toEqual({ ...storedConfig, apiUserToken: 'refreshed-access' });
172
- expect(config_1.storeConfig).toHaveBeenCalledWith(context);
177
+ expect(config_1.storeConfig).toHaveBeenCalledWith({ ...context, signInMethod: 'password' });
173
178
  });
174
179
  it('should keep a still-valid access token without refreshing it', async () => {
175
180
  acceptedTokens = ['expired-access'];
@@ -209,6 +214,115 @@ describe('authUser with stored tokens', () => {
209
214
  expect(mockAuthenticateUser).not.toHaveBeenCalled();
210
215
  });
211
216
  });
217
+ describe('signIn with SSO', () => {
218
+ const originalFetch = global.fetch;
219
+ const originalEmail = process.env.CONTRAIL_CLI_EMAIL;
220
+ const originalPassword = process.env.CONTRAIL_CLI_PASSWORD;
221
+ const DEV_COGNITO_DOMAIN = 'https://dev-vibeiq.auth.us-east-1.amazoncognito.com';
222
+ let fetchMock;
223
+ let promptSpy;
224
+ let consoleLogSpy;
225
+ function pasteCodeFromPrintedSignInUrl() {
226
+ promptSpy.mockImplementation(async () => {
227
+ const printedOutput = consoleLogSpy.mock.calls.map(([message]) => message).join('\n');
228
+ const signInUrl = new URL(printedOutput.match(/https:\/\/\S+oauth2\/authorize\S+/)[0]);
229
+ return { signInCode: `pasted-code#${signInUrl.searchParams.get('state')}` };
230
+ });
231
+ }
232
+ beforeEach(() => {
233
+ jest.clearAllMocks();
234
+ process.env.CONTRAIL_CLI_EMAIL = 'dev@vibeiq.com';
235
+ delete process.env.CONTRAIL_CLI_PASSWORD;
236
+ config_1.getConfig.mockResolvedValue({ apiGateway: DEV_GATEWAY, orgSlug: 'adam-zone-1' });
237
+ sdk_1.getCurrentUser.mockResolvedValue({ id: 'user-1' });
238
+ mockAuthenticateUser.mockImplementation((_details, callbacks) => callbacks.onSuccess({ idToken: { jwtToken: 'cognito-id-token' } }));
239
+ consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined);
240
+ promptSpy = jest.spyOn(common, 'promptOnStderr');
241
+ pasteCodeFromPrintedSignInUrl();
242
+ fetchMock = jest.fn();
243
+ global.fetch = fetchMock;
244
+ });
245
+ afterEach(() => {
246
+ promptSpy.mockRestore();
247
+ consoleLogSpy.mockRestore();
248
+ global.fetch = originalFetch;
249
+ restoreEnv('CONTRAIL_CLI_EMAIL', originalEmail);
250
+ restoreEnv('CONTRAIL_CLI_PASSWORD', originalPassword);
251
+ });
252
+ it('should sign in through the domain identity provider with a pasted code', async () => {
253
+ fetchMock
254
+ .mockResolvedValueOnce(jsonResponse(200, { identityProvider: 'sso-vibeiq-com' }))
255
+ .mockResolvedValueOnce(jsonResponse(200, { access_token: 'cognito-access', refresh_token: 'cognito-refresh' }));
256
+ const context = await (0, login_1.signIn)({ shouldOpenBrowser: false });
257
+ const [tokenUrl, tokenRequest] = fetchMock.mock.calls[1];
258
+ const tokenForm = new URLSearchParams(tokenRequest.body);
259
+ expect(tokenUrl).toBe(`${DEV_COGNITO_DOMAIN}/oauth2/token`);
260
+ expect(tokenForm.get('code')).toBe('pasted-code');
261
+ expect(tokenForm.get('redirect_uri')).toBe('https://login.dev.vibeiq.com/cli');
262
+ expect(context).toEqual({
263
+ apiUserToken: 'cognito-access',
264
+ apiRefreshToken: 'cognito-refresh',
265
+ apiGateway: DEV_GATEWAY,
266
+ orgSlug: 'adam-zone-1',
267
+ });
268
+ expect(config_1.storeConfig).toHaveBeenCalledWith({ ...context, signInMethod: 'sso' });
269
+ });
270
+ it('should reject a pasted code from a different sign-in attempt without saving tokens', async () => {
271
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { identityProvider: 'sso-vibeiq-com' }));
272
+ promptSpy.mockResolvedValue({ signInCode: 'pasted-code#another-state' });
273
+ await expect((0, login_1.signIn)({ shouldOpenBrowser: false })).rejects.toMatchObject({
274
+ code: 'SSO_SIGN_IN_CODE_MISMATCH',
275
+ });
276
+ expect(config_1.storeConfig).not.toHaveBeenCalled();
277
+ });
278
+ it('should ask for a password when the email domain has no SSO', async () => {
279
+ fetchMock
280
+ .mockResolvedValueOnce(new Response('', { status: 200 }))
281
+ .mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
282
+ promptSpy.mockResolvedValue({ password: 'secret' });
283
+ const context = await (0, login_1.signIn)({ shouldOpenBrowser: false });
284
+ expect(context.apiUserToken).toBe('vibe-access');
285
+ expect(config_1.storeConfig).toHaveBeenCalledWith({ ...context, signInMethod: 'password' });
286
+ });
287
+ it('should ask for a password when the email domain uses SSO the CLI cannot open', async () => {
288
+ fetchMock
289
+ .mockResolvedValueOnce(jsonResponse(200, { identityProvider: '', url: 'legacy' }))
290
+ .mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
291
+ promptSpy.mockResolvedValue({ password: 'secret' });
292
+ const context = await (0, login_1.signIn)({ shouldOpenBrowser: false });
293
+ expect(context.apiUserToken).toBe('vibe-access');
294
+ expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('The CLI does not support your SSO provider yet.'));
295
+ });
296
+ it('should refresh a stored SSO token through Cognito instead of the VibeIQ refresh endpoint', async () => {
297
+ config_1.getConfig.mockResolvedValue({
298
+ apiUserToken: 'expired-access',
299
+ apiRefreshToken: 'cognito-refresh',
300
+ apiGateway: DEV_GATEWAY,
301
+ orgSlug: 'adam-zone-1',
302
+ signInMethod: 'sso',
303
+ });
304
+ sdk_1.getCurrentUser
305
+ .mockRejectedValueOnce(new Error('Failed to fetch current user. Unauthorized'))
306
+ .mockResolvedValueOnce({ id: 'user-1' });
307
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { access_token: 'refreshed-access' }));
308
+ const context = await (0, login_1.authUser)();
309
+ const [tokenUrl, tokenRequest] = fetchMock.mock.calls[0];
310
+ expect(tokenUrl).toBe(`${DEV_COGNITO_DOMAIN}/oauth2/token`);
311
+ expect(new URLSearchParams(tokenRequest.body).get('refresh_token')).toBe('cognito-refresh');
312
+ expect(context.apiUserToken).toBe('refreshed-access');
313
+ });
314
+ it('should name the misconfiguration when a stored SSO token points at an unknown environment', async () => {
315
+ config_1.getConfig.mockResolvedValue({
316
+ apiUserToken: 'expired-access',
317
+ apiRefreshToken: 'cognito-refresh',
318
+ apiGateway: 'http://localhost:3000/api',
319
+ orgSlug: 'adam-zone-1',
320
+ signInMethod: 'sso',
321
+ });
322
+ sdk_1.getCurrentUser.mockRejectedValueOnce(new Error('Failed to fetch current user. Unauthorized'));
323
+ await expect((0, login_1.authUser)()).rejects.toMatchObject({ code: 'ENVIRONMENT_NOT_CONFIGURED' });
324
+ });
325
+ });
212
326
  describe('getVersionFromPackageJson', () => {
213
327
  it('should return the version value from package.json', () => {
214
328
  const version = (0, login_1.getVersionFromPackageJson)();
@@ -0,0 +1,7 @@
1
+ export type SignInErrorCode = 'ENVIRONMENT_NOT_CONFIGURED' | 'SSO_DOMAIN_CHECK_FAILED' | 'SSO_SIGN_IN_CODE_MISMATCH' | 'SSO_SIGN_IN_REJECTED' | 'SSO_UNEXPECTED_CALLBACK' | 'SSO_SIGN_IN_TIMED_OUT' | 'SSO_LOOPBACK_PORT_IN_USE' | 'SSO_TOKEN_REQUEST_FAILED' | 'API_KEY_CANNOT_REFRESH';
2
+ export declare class SignInError extends Error {
3
+ readonly code: SignInErrorCode;
4
+ readonly details: Record<string, string | number | undefined>;
5
+ constructor(code: SignInErrorCode, message: string, details?: Record<string, string | number | undefined>);
6
+ }
7
+ export declare function formatErrorForTerminal(error: Error): string;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatErrorForTerminal = exports.SignInError = void 0;
4
+ class SignInError extends Error {
5
+ code;
6
+ details;
7
+ constructor(code, message, details = {}) {
8
+ super(message);
9
+ this.code = code;
10
+ this.details = details;
11
+ this.name = 'SignInError';
12
+ }
13
+ }
14
+ exports.SignInError = SignInError;
15
+ function formatErrorForTerminal(error) {
16
+ if (!(error instanceof SignInError)) {
17
+ return error.message;
18
+ }
19
+ const details = Object.entries(error.details)
20
+ .filter(([, value]) => value !== undefined)
21
+ .map(([name, value]) => `${name}: ${value}`);
22
+ return details.length ? `${error.message} (${details.join(', ')})` : error.message;
23
+ }
24
+ exports.formatErrorForTerminal = formatErrorForTerminal;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const sign_in_error_1 = require("./sign-in-error");
4
+ describe('formatErrorForTerminal', () => {
5
+ it('should follow a sign-in error message with its details', () => {
6
+ const error = new sign_in_error_1.SignInError('SSO_TOKEN_REQUEST_FAILED', 'Cognito rejected the token request.', {
7
+ status: 400,
8
+ oauthError: 'invalid_grant',
9
+ });
10
+ expect((0, sign_in_error_1.formatErrorForTerminal)(error)).toBe('Cognito rejected the token request. (status: 400, oauthError: invalid_grant)');
11
+ });
12
+ it('should leave out details that are not set', () => {
13
+ const error = new sign_in_error_1.SignInError('SSO_TOKEN_REQUEST_FAILED', 'Cognito rejected the token request.', {
14
+ status: 400,
15
+ oauthError: undefined,
16
+ });
17
+ expect((0, sign_in_error_1.formatErrorForTerminal)(error)).toBe('Cognito rejected the token request. (status: 400)');
18
+ });
19
+ it('should show only the message for other errors', () => {
20
+ expect((0, sign_in_error_1.formatErrorForTerminal)(new Error('Something else.'))).toBe('Something else.');
21
+ });
22
+ });
@@ -0,0 +1,38 @@
1
+ /// <reference types="node" />
2
+ export declare const LOOPBACK_PORT = 7731;
3
+ export declare const LOOPBACK_CALLBACK_URL: string;
4
+ export interface SsoClient {
5
+ domain: string;
6
+ clientId: string;
7
+ }
8
+ export interface SsoTokens {
9
+ accessToken: string;
10
+ refreshToken: string;
11
+ }
12
+ export interface SignInAttempt {
13
+ verifier: string;
14
+ challenge: string;
15
+ state: string;
16
+ }
17
+ export type SsoDomainCheck = {
18
+ kind: 'cognito';
19
+ identityProvider: string;
20
+ } | {
21
+ kind: 'legacy';
22
+ } | {
23
+ kind: 'none';
24
+ };
25
+ export declare function fetchSsoDomainCheck(email: string, apiGateway: string): Promise<SsoDomainCheck>;
26
+ export declare function createSignInAttempt(): SignInAttempt;
27
+ export declare function buildAuthorizeUrl(client: SsoClient, identityProvider: string, redirectUri: string, signInAttempt: SignInAttempt): string;
28
+ export declare function parsePastedSignInCode(pasted: string, expectedState: string): string;
29
+ export interface LoopbackListener {
30
+ code: Promise<string>;
31
+ stop: () => void;
32
+ }
33
+ export declare function listenForLoopbackCode(expectedState: string): Promise<LoopbackListener>;
34
+ export declare function canOpenBrowser(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): boolean;
35
+ export declare function openBrowser(url: string): Promise<void>;
36
+ export declare function buildOpenBrowserCommand(url: string, platform: NodeJS.Platform): [string, string[]];
37
+ export declare function exchangeCodeForTokens(client: SsoClient, code: string, redirectUri: string, verifier: string): Promise<SsoTokens>;
38
+ export declare function refreshSsoAccessToken(client: SsoClient, refreshToken: string): Promise<string>;