@contrail/cli 3.6.0 → 3.7.0-alpha.fef3ff4

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.fef3ff4 linux-x64 node-v24.22.2
21
21
  $ contrail --help [COMMAND]
22
22
  USAGE
23
23
  $ contrail COMMAND
@@ -67,6 +67,7 @@ To get instructions on how to set up autocomplete for your shell, run `contrail
67
67
  * [`contrail load custom-entity DATAFILE CONFIGFILE`](#contrail-load-custom-entity-datafile-configfile)
68
68
  * [`contrail load line-sheet DATAFILE CONFIGFILE`](#contrail-load-line-sheet-datafile-configfile)
69
69
  * [`contrail load upload-and-load INCOMINGFILE CONFIGFILENAME`](#contrail-load-upload-and-load-incomingfile-configfilename)
70
+ * [`contrail login`](#contrail-login)
70
71
  * [`contrail org-config export`](#contrail-org-config-export)
71
72
  * [`contrail org-config import`](#contrail-org-config-import)
72
73
  * [`contrail projects export PROJECTNAME`](#contrail-projects-export-projectname)
@@ -1009,6 +1010,30 @@ EXAMPLES
1009
1010
  $ contrail load-processor upload-and-load <File Path> <Config Path>
1010
1011
  ```
1011
1012
 
1013
+ ## `contrail login`
1014
+
1015
+ Sign in to VibeIQ with SSO or your email and password
1016
+
1017
+ ```
1018
+ USAGE
1019
+ $ contrail login [-l error|warn|info|debug] [-e true|false] [--browser]
1020
+
1021
+ FLAGS
1022
+ -e, --alwaysConfirmEnv=<option> [default: true] The Environment variables
1023
+ <options: true|false>
1024
+ -l, --logLevel=<option> The Log Level
1025
+ <options: error|warn|info|debug>
1026
+ --[no-]browser Open a browser for SSO. Use --no-browser to paste a sign-in code instead.
1027
+
1028
+ DESCRIPTION
1029
+ Sign in to VibeIQ with SSO or your email and password
1030
+
1031
+ EXAMPLES
1032
+ $ contrail login
1033
+
1034
+ $ contrail login --no-browser
1035
+ ```
1036
+
1012
1037
  ## `contrail org-config export`
1013
1038
 
1014
1039
  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>;
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.refreshSsoAccessToken = exports.exchangeCodeForTokens = exports.buildOpenBrowserCommand = exports.openBrowser = exports.canOpenBrowser = exports.listenForLoopbackCode = exports.parsePastedSignInCode = exports.buildAuthorizeUrl = exports.createSignInAttempt = exports.fetchSsoDomainCheck = exports.LOOPBACK_CALLBACK_URL = exports.LOOPBACK_PORT = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const node_http_1 = require("node:http");
6
+ const node_child_process_1 = require("node:child_process");
7
+ const sign_in_error_1 = require("./sign-in-error");
8
+ // Must match the CLI client's loopback callback URL in contrail-api resources/cognito.
9
+ exports.LOOPBACK_PORT = 7731;
10
+ exports.LOOPBACK_CALLBACK_URL = `http://localhost:${exports.LOOPBACK_PORT}/callback`;
11
+ const BROWSER_SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000;
12
+ const OAUTH_SCOPES = ['openid', 'email', 'api.vibeiq.default/read', 'api.vibeiq.default/write'];
13
+ async function fetchSsoDomainCheck(email, apiGateway) {
14
+ const domain = email.split('@').pop().toLowerCase();
15
+ const response = await fetch(`${apiGateway}/sso-login/domain-check/${encodeURIComponent(domain)}`);
16
+ if (!response.ok) {
17
+ throw new sign_in_error_1.SignInError('SSO_DOMAIN_CHECK_FAILED', 'Could not check whether your email domain signs in with SSO.', { domain, status: response.status });
18
+ }
19
+ const body = await response.text();
20
+ if (!body) {
21
+ return { kind: 'none' };
22
+ }
23
+ const { identityProvider } = JSON.parse(body);
24
+ return identityProvider ? { kind: 'cognito', identityProvider } : { kind: 'legacy' };
25
+ }
26
+ exports.fetchSsoDomainCheck = fetchSsoDomainCheck;
27
+ function createSignInAttempt() {
28
+ // RFC 7636 needs a 43-128 character verifier: 32 random bytes encode to 43.
29
+ const verifier = (0, node_crypto_1.randomBytes)(32).toString('base64url');
30
+ return {
31
+ verifier,
32
+ challenge: (0, node_crypto_1.createHash)('sha256').update(verifier).digest('base64url'),
33
+ // RFC 6749 section 10.10 asks for at most a 2^-128 chance of guessing state.
34
+ state: (0, node_crypto_1.randomBytes)(16).toString('base64url'),
35
+ };
36
+ }
37
+ exports.createSignInAttempt = createSignInAttempt;
38
+ function buildAuthorizeUrl(client, identityProvider, redirectUri, signInAttempt) {
39
+ const params = new URLSearchParams({
40
+ response_type: 'code',
41
+ client_id: client.clientId,
42
+ redirect_uri: redirectUri,
43
+ scope: OAUTH_SCOPES.join(' '),
44
+ identity_provider: identityProvider,
45
+ code_challenge: signInAttempt.challenge,
46
+ code_challenge_method: 'S256',
47
+ state: signInAttempt.state,
48
+ });
49
+ return `${client.domain}/oauth2/authorize?${params}`;
50
+ }
51
+ exports.buildAuthorizeUrl = buildAuthorizeUrl;
52
+ function parsePastedSignInCode(pasted, expectedState) {
53
+ const [code, state] = pasted.trim().split('#');
54
+ if (!code || state !== expectedState) {
55
+ throw new sign_in_error_1.SignInError('SSO_SIGN_IN_CODE_MISMATCH', 'That sign-in code is not from this login attempt. Run the command again.');
56
+ }
57
+ return code;
58
+ }
59
+ exports.parsePastedSignInCode = parsePastedSignInCode;
60
+ function listenForLoopbackCode(expectedState) {
61
+ let resolveCode;
62
+ let rejectCode;
63
+ const code = new Promise((resolve, reject) => {
64
+ resolveCode = resolve;
65
+ rejectCode = reject;
66
+ });
67
+ const server = (0, node_http_1.createServer)((request, response) => {
68
+ const url = new URL(request.url, exports.LOOPBACK_CALLBACK_URL);
69
+ if (url.pathname !== '/callback') {
70
+ response.writeHead(404).end();
71
+ return;
72
+ }
73
+ if (url.searchParams.get('state') !== expectedState) {
74
+ response.writeHead(400, { 'Content-Type': 'text/plain' }).end('Unknown sign-in attempt.');
75
+ return;
76
+ }
77
+ const error = url.searchParams.get('error_description') ?? url.searchParams.get('error');
78
+ const receivedCode = url.searchParams.get('code');
79
+ const signedIn = !error && Boolean(receivedCode);
80
+ const page = signedIn
81
+ ? 'Sign-in received. Return to your terminal.'
82
+ : 'Sign-in failed. Return to your terminal.';
83
+ response
84
+ .writeHead(signedIn ? 200 : 400, { 'Content-Type': 'text/plain', Connection: 'close' })
85
+ .end(page, () => stopListening(request.socket, () => {
86
+ if (error) {
87
+ rejectCode(new sign_in_error_1.SignInError('SSO_SIGN_IN_REJECTED', 'Your identity provider did not complete the sign-in. Run the command again.', { oauthError: error }));
88
+ }
89
+ else if (!signedIn) {
90
+ rejectCode(new sign_in_error_1.SignInError('SSO_UNEXPECTED_CALLBACK', 'SSO sign-in returned an unexpected response. Run the command again.'));
91
+ }
92
+ else {
93
+ resolveCode(receivedCode);
94
+ }
95
+ }));
96
+ });
97
+ const openSockets = new Set();
98
+ server.on('connection', (socket) => {
99
+ openSockets.add(socket);
100
+ socket.once('close', () => openSockets.delete(socket));
101
+ });
102
+ const timeout = setTimeout(() => stopListening(undefined, () => rejectCode(new sign_in_error_1.SignInError('SSO_SIGN_IN_TIMED_OUT', 'Timed out waiting for the browser sign-in.'))), BROWSER_SIGN_IN_TIMEOUT_MS);
103
+ function stopListening(respondingSocket, settle) {
104
+ clearTimeout(timeout);
105
+ server.close();
106
+ openSockets.forEach((socket) => socket !== respondingSocket && socket.destroy());
107
+ settle();
108
+ }
109
+ return new Promise((resolve, reject) => {
110
+ server.once('error', (error) => {
111
+ clearTimeout(timeout);
112
+ if (error.code !== 'EADDRINUSE') {
113
+ reject(error);
114
+ return;
115
+ }
116
+ reject(new sign_in_error_1.SignInError('SSO_LOOPBACK_PORT_IN_USE', 'The sign-in port is in use. Run contrail login --no-browser instead.', { port: exports.LOOPBACK_PORT }));
117
+ });
118
+ server.listen(exports.LOOPBACK_PORT, 'localhost', () => resolve({ code, stop: () => stopListening(undefined, () => undefined) }));
119
+ });
120
+ }
121
+ exports.listenForLoopbackCode = listenForLoopbackCode;
122
+ function canOpenBrowser(env = process.env, platform = process.platform) {
123
+ const isRemoteShell = Boolean(env.SSH_CONNECTION || env.SSH_TTY);
124
+ const hasLinuxDisplay = Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
125
+ return !isRemoteShell && (platform !== 'linux' || hasLinuxDisplay);
126
+ }
127
+ exports.canOpenBrowser = canOpenBrowser;
128
+ function openBrowser(url) {
129
+ const [command, args] = buildOpenBrowserCommand(url, process.platform);
130
+ return new Promise((resolve, reject) => {
131
+ const browserProcess = (0, node_child_process_1.spawn)(command, args, { stdio: 'ignore', detached: true });
132
+ browserProcess.once('spawn', () => {
133
+ browserProcess.unref();
134
+ resolve();
135
+ });
136
+ browserProcess.once('error', reject);
137
+ });
138
+ }
139
+ exports.openBrowser = openBrowser;
140
+ function buildOpenBrowserCommand(url, platform) {
141
+ if (platform === 'darwin') {
142
+ return ['open', [url]];
143
+ }
144
+ if (platform === 'win32') {
145
+ return ['rundll32', ['url.dll,FileProtocolHandler', url]];
146
+ }
147
+ return ['xdg-open', [url]];
148
+ }
149
+ exports.buildOpenBrowserCommand = buildOpenBrowserCommand;
150
+ async function exchangeCodeForTokens(client, code, redirectUri, verifier) {
151
+ const tokens = await postToTokenEndpoint(client, {
152
+ grant_type: 'authorization_code',
153
+ client_id: client.clientId,
154
+ code,
155
+ redirect_uri: redirectUri,
156
+ code_verifier: verifier,
157
+ });
158
+ return { accessToken: tokens.access_token, refreshToken: tokens.refresh_token };
159
+ }
160
+ exports.exchangeCodeForTokens = exchangeCodeForTokens;
161
+ async function refreshSsoAccessToken(client, refreshToken) {
162
+ const tokens = await postToTokenEndpoint(client, {
163
+ grant_type: 'refresh_token',
164
+ client_id: client.clientId,
165
+ refresh_token: refreshToken,
166
+ });
167
+ return tokens.access_token;
168
+ }
169
+ exports.refreshSsoAccessToken = refreshSsoAccessToken;
170
+ async function postToTokenEndpoint(client, form) {
171
+ const response = await fetch(`${client.domain}/oauth2/token`, {
172
+ method: 'POST',
173
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
174
+ body: new URLSearchParams(form),
175
+ });
176
+ const body = await response.json();
177
+ if (!response.ok) {
178
+ throw new sign_in_error_1.SignInError('SSO_TOKEN_REQUEST_FAILED', 'Cognito rejected the token request.', {
179
+ status: response.status,
180
+ oauthError: body.error,
181
+ });
182
+ }
183
+ return body;
184
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,191 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const node_crypto_1 = require("node:crypto");
4
+ const node_net_1 = require("node:net");
5
+ const sso_1 = require("./sso");
6
+ const ssoClient = {
7
+ domain: 'https://dev-vibeiq.auth.us-east-1.amazoncognito.com',
8
+ clientId: 'cli-client',
9
+ };
10
+ describe('createSignInAttempt', () => {
11
+ it('should derive the challenge as the base64url SHA-256 of the verifier', () => {
12
+ const signInAttempt = (0, sso_1.createSignInAttempt)();
13
+ expect(signInAttempt.challenge).toBe((0, node_crypto_1.createHash)('sha256').update(signInAttempt.verifier).digest('base64url'));
14
+ });
15
+ it('should make a verifier of at least the 43 characters PKCE requires', () => {
16
+ expect((0, sso_1.createSignInAttempt)().verifier.length).toBeGreaterThanOrEqual(43);
17
+ });
18
+ });
19
+ describe('buildAuthorizeUrl', () => {
20
+ it('should send the user straight to their identity provider with a PKCE challenge', () => {
21
+ const url = new URL((0, sso_1.buildAuthorizeUrl)(ssoClient, 'sso-vibeiq-com', sso_1.LOOPBACK_CALLBACK_URL, {
22
+ verifier: 'verifier',
23
+ challenge: 'challenge',
24
+ state: 'state',
25
+ }));
26
+ expect(url.origin + url.pathname).toBe(`${ssoClient.domain}/oauth2/authorize`);
27
+ expect(Object.fromEntries(url.searchParams)).toEqual({
28
+ response_type: 'code',
29
+ client_id: 'cli-client',
30
+ redirect_uri: 'http://localhost:7731/callback',
31
+ scope: 'openid email api.vibeiq.default/read api.vibeiq.default/write',
32
+ identity_provider: 'sso-vibeiq-com',
33
+ code_challenge: 'challenge',
34
+ code_challenge_method: 'S256',
35
+ state: 'state',
36
+ });
37
+ });
38
+ });
39
+ describe('parsePastedSignInCode', () => {
40
+ it('should return the code when the pasted state matches this attempt', () => {
41
+ expect((0, sso_1.parsePastedSignInCode)(' the-code#the-state \n', 'the-state')).toBe('the-code');
42
+ });
43
+ it('should reject a code from another attempt', () => {
44
+ expect(() => (0, sso_1.parsePastedSignInCode)('the-code#other-state', 'the-state')).toThrow(expect.objectContaining({ code: 'SSO_SIGN_IN_CODE_MISMATCH' }));
45
+ });
46
+ it('should reject a code pasted without its state', () => {
47
+ expect(() => (0, sso_1.parsePastedSignInCode)('the-code', 'the-state')).toThrow(expect.objectContaining({ code: 'SSO_SIGN_IN_CODE_MISMATCH' }));
48
+ });
49
+ });
50
+ describe('canOpenBrowser', () => {
51
+ it('should open a browser on a local Mac', () => {
52
+ expect((0, sso_1.canOpenBrowser)({}, 'darwin')).toBe(true);
53
+ });
54
+ it('should not open a browser over SSH', () => {
55
+ expect((0, sso_1.canOpenBrowser)({ SSH_CONNECTION: '10.0.0.1 22 10.0.0.2 22' }, 'darwin')).toBe(false);
56
+ });
57
+ it('should not open a browser on Linux without a display', () => {
58
+ expect((0, sso_1.canOpenBrowser)({}, 'linux')).toBe(false);
59
+ });
60
+ it('should open a browser on a Linux desktop', () => {
61
+ expect((0, sso_1.canOpenBrowser)({ WAYLAND_DISPLAY: 'wayland-0' }, 'linux')).toBe(true);
62
+ });
63
+ });
64
+ describe('fetchSsoDomainCheck', () => {
65
+ const originalFetch = global.fetch;
66
+ afterEach(() => {
67
+ global.fetch = originalFetch;
68
+ });
69
+ function stubDomainCheckFetch(body, status = 200) {
70
+ global.fetch = jest.fn().mockResolvedValue(new Response(body, { status }));
71
+ }
72
+ it('should name the Cognito identity provider for an SSO domain', async () => {
73
+ stubDomainCheckFetch(JSON.stringify({ identityProvider: 'sso-vibeiq-com' }));
74
+ await expect((0, sso_1.fetchSsoDomainCheck)('Dev@VibeIQ.com', 'https://api')).resolves.toEqual({
75
+ kind: 'cognito',
76
+ identityProvider: 'sso-vibeiq-com',
77
+ });
78
+ expect(global.fetch).toHaveBeenCalledWith('https://api/sso-login/domain-check/vibeiq.com');
79
+ });
80
+ it('should report a legacy SSO domain', async () => {
81
+ stubDomainCheckFetch(JSON.stringify({ identityProvider: '', url: 'https://api/sso-login/login/acme.com' }));
82
+ await expect((0, sso_1.fetchSsoDomainCheck)('dev@acme.com', 'https://api')).resolves.toEqual({
83
+ kind: 'legacy',
84
+ });
85
+ });
86
+ it('should report no SSO for an empty response', async () => {
87
+ stubDomainCheckFetch('');
88
+ await expect((0, sso_1.fetchSsoDomainCheck)('dev@example.com', 'https://api')).resolves.toEqual({
89
+ kind: 'none',
90
+ });
91
+ });
92
+ it('should fail when the lookup fails', async () => {
93
+ stubDomainCheckFetch('{}', 502);
94
+ await expect((0, sso_1.fetchSsoDomainCheck)('dev@example.com', 'https://api')).rejects.toMatchObject({
95
+ code: 'SSO_DOMAIN_CHECK_FAILED',
96
+ details: { domain: 'example.com', status: 502 },
97
+ });
98
+ });
99
+ });
100
+ describe('listenForLoopbackCode', () => {
101
+ it('should resolve with the code the browser redirects back with', async () => {
102
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
103
+ const response = await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
104
+ expect(response.status).toBe(200);
105
+ await expect(listener.code).resolves.toBe('the-code');
106
+ });
107
+ it('should keep waiting for this attempt after a redirect from another attempt', async () => {
108
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
109
+ const staleResponse = await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=old-code&state=old-state`);
110
+ await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
111
+ expect(staleResponse.status).toBe(400);
112
+ await expect(listener.code).resolves.toBe('the-code');
113
+ });
114
+ it('should reject a redirect for this attempt that carries no code', async () => {
115
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
116
+ const rejection = expect(listener.code).rejects.toMatchObject({
117
+ code: 'SSO_UNEXPECTED_CALLBACK',
118
+ });
119
+ const response = await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?state=the-state`);
120
+ expect(response.status).toBe(400);
121
+ await rejection;
122
+ });
123
+ it('should reject when the identity provider reports an error', async () => {
124
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
125
+ const rejection = expect(listener.code).rejects.toMatchObject({
126
+ code: 'SSO_SIGN_IN_REJECTED',
127
+ details: { oauthError: 'User cancelled' },
128
+ });
129
+ await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?error=access_denied&error_description=User%20cancelled&state=the-state`);
130
+ await rejection;
131
+ });
132
+ it('should close idle browser connections once the code arrives', async () => {
133
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
134
+ const idleConnection = (0, node_net_1.connect)(sso_1.LOOPBACK_PORT, 'localhost');
135
+ await new Promise((resolve) => idleConnection.once('connect', resolve));
136
+ const idleConnectionClosed = new Promise((resolve) => idleConnection.once('close', resolve));
137
+ await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
138
+ await expect(listener.code).resolves.toBe('the-code');
139
+ await expect(idleConnectionClosed).resolves.toBe(false);
140
+ });
141
+ it('should tell the user to paste a code instead when the port is taken', async () => {
142
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
143
+ await expect((0, sso_1.listenForLoopbackCode)('another-state')).rejects.toMatchObject({
144
+ code: 'SSO_LOOPBACK_PORT_IN_USE',
145
+ details: { port: sso_1.LOOPBACK_PORT },
146
+ });
147
+ await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
148
+ await listener.code;
149
+ });
150
+ it('should free the port when stopped', async () => {
151
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
152
+ listener.stop();
153
+ const nextListener = await (0, sso_1.listenForLoopbackCode)('next-state');
154
+ nextListener.stop();
155
+ });
156
+ });
157
+ describe('buildOpenBrowserCommand', () => {
158
+ it('should use open on a Mac', () => {
159
+ expect((0, sso_1.buildOpenBrowserCommand)('https://sign.in', 'darwin')).toEqual([
160
+ 'open',
161
+ ['https://sign.in'],
162
+ ]);
163
+ });
164
+ it('should pass the URL through rundll32 on Windows so the shell cannot split it', () => {
165
+ expect((0, sso_1.buildOpenBrowserCommand)('https://sign.in?a=1&b=2', 'win32')).toEqual([
166
+ 'rundll32',
167
+ ['url.dll,FileProtocolHandler', 'https://sign.in?a=1&b=2'],
168
+ ]);
169
+ });
170
+ it('should use xdg-open on Linux', () => {
171
+ expect((0, sso_1.buildOpenBrowserCommand)('https://sign.in', 'linux')).toEqual([
172
+ 'xdg-open',
173
+ ['https://sign.in'],
174
+ ]);
175
+ });
176
+ });
177
+ describe('exchangeCodeForTokens', () => {
178
+ const originalFetch = global.fetch;
179
+ afterEach(() => {
180
+ global.fetch = originalFetch;
181
+ });
182
+ it('should name the Cognito error when the exchange is refused', async () => {
183
+ global.fetch = jest
184
+ .fn()
185
+ .mockResolvedValue(new Response(JSON.stringify({ error: 'invalid_grant' }), { status: 400 }));
186
+ await expect((0, sso_1.exchangeCodeForTokens)(ssoClient, 'the-code', sso_1.LOOPBACK_CALLBACK_URL, 'verifier')).rejects.toMatchObject({
187
+ code: 'SSO_TOKEN_REQUEST_FAILED',
188
+ details: { status: 400, oauthError: 'invalid_grant' },
189
+ });
190
+ });
191
+ });
@@ -11,5 +11,8 @@ export declare abstract class BaseCommand extends Command {
11
11
  protected args: any;
12
12
  init(): Promise<void>;
13
13
  setLogLevel(logLevel: string, config?: any): void;
14
+ protected catch(error: Error & {
15
+ exitCode?: number;
16
+ }): Promise<unknown>;
14
17
  private confirmEnv;
15
18
  }
@@ -8,6 +8,7 @@ const logger_1 = tslib_1.__importDefault(require("./logger"));
8
8
  const config_1 = require("./helpers/config/config");
9
9
  const lodash_1 = require("lodash");
10
10
  const login_1 = require("./auth/login");
11
+ const sign_in_error_1 = require("./auth/sign-in-error");
11
12
  const baseFlags_1 = require("./baseFlags");
12
13
  class BaseCommand extends core_1.Command {
13
14
  static description = 'Global Flags';
@@ -48,11 +49,17 @@ class BaseCommand extends core_1.Command {
48
49
  logger_1.default.level = config.logLevel;
49
50
  }
50
51
  }
52
+ async catch(error) {
53
+ if (error instanceof sign_in_error_1.SignInError) {
54
+ this.error((0, sign_in_error_1.formatErrorForTerminal)(error), { exit: 1 });
55
+ }
56
+ return super.catch(error);
57
+ }
51
58
  async confirmEnv() {
52
59
  let config = await (0, config_1.getConfig)();
53
60
  if ((0, lodash_1.keys)(config).length === 0) {
54
61
  await (0, login_1.authUser)().catch((e) => {
55
- console.log(`Error: ${e.message}\n\nCheck if you are using the correct environment configuration and credentials.`);
62
+ console.log(`Error: ${(0, sign_in_error_1.formatErrorForTerminal)(e)}\n\nCheck if you are using the correct environment configuration and credentials.`);
56
63
  this.exit(1);
57
64
  });
58
65
  config = await (0, config_1.getConfig)();
@@ -0,0 +1,12 @@
1
+ import { BaseCommand } from '../basecommand';
2
+ export default class Login extends BaseCommand {
3
+ static description: string;
4
+ skipConfirmEnv: boolean;
5
+ static examples: string[];
6
+ static flags: {
7
+ browser: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
8
+ alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
9
+ logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
10
+ };
11
+ run(): Promise<void>;
12
+ }
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const core_1 = require("@oclif/core");
5
+ const basecommand_1 = require("../basecommand");
6
+ const login_1 = require("../auth/login");
7
+ const logger_1 = tslib_1.__importDefault(require("../logger"));
8
+ class Login extends basecommand_1.BaseCommand {
9
+ static description = 'Sign in to VibeIQ with SSO or your email and password';
10
+ skipConfirmEnv = true;
11
+ static examples = ['$ contrail login', '$ contrail login --no-browser'];
12
+ static flags = {
13
+ ...basecommand_1.BaseCommand.baseFlags,
14
+ browser: core_1.Flags.boolean({
15
+ description: 'Open a browser for SSO. Use --no-browser to paste a sign-in code instead.',
16
+ default: true,
17
+ allowNo: true,
18
+ }),
19
+ };
20
+ async run() {
21
+ const context = await (0, login_1.signIn)({ shouldOpenBrowser: this.flags.browser });
22
+ logger_1.default.info(`Signed in to ${context.orgSlug}.`);
23
+ }
24
+ }
25
+ exports.default = Login;
@@ -1,6 +1,55 @@
1
1
  {
2
- "version": "3.6.0",
2
+ "version": "3.7.0-alpha.fef3ff4",
3
3
  "commands": {
4
+ "login": {
5
+ "id": "login",
6
+ "description": "Sign in to VibeIQ with SSO or your email and password",
7
+ "strict": true,
8
+ "pluginName": "@contrail/cli",
9
+ "pluginAlias": "@contrail/cli",
10
+ "pluginType": "core",
11
+ "aliases": [],
12
+ "examples": [
13
+ "$ contrail login",
14
+ "$ contrail login --no-browser"
15
+ ],
16
+ "flags": {
17
+ "logLevel": {
18
+ "name": "logLevel",
19
+ "type": "option",
20
+ "char": "l",
21
+ "description": "The Log Level",
22
+ "required": false,
23
+ "multiple": false,
24
+ "options": [
25
+ "error",
26
+ "warn",
27
+ "info",
28
+ "debug"
29
+ ]
30
+ },
31
+ "alwaysConfirmEnv": {
32
+ "name": "alwaysConfirmEnv",
33
+ "type": "option",
34
+ "char": "e",
35
+ "description": "The Environment variables",
36
+ "required": false,
37
+ "multiple": false,
38
+ "options": [
39
+ "true",
40
+ "false"
41
+ ],
42
+ "default": "true"
43
+ },
44
+ "browser": {
45
+ "name": "browser",
46
+ "type": "boolean",
47
+ "description": "Open a browser for SSO. Use --no-browser to paste a sign-in code instead.",
48
+ "allowNo": true
49
+ }
50
+ },
51
+ "args": {}
52
+ },
4
53
  "app:create": {
5
54
  "id": "app:create",
6
55
  "description": "Create a new app. The current organization will be set as the owner of the app",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrail/cli",
3
- "version": "3.6.0",
3
+ "version": "3.7.0-alpha.fef3ff4",
4
4
  "description": "VibeIQ's Contrail Platform CLI.",
5
5
  "bin": {
6
6
  "contrail-cli": "./bin/run",