@contrail/cli 3.5.5-alpha.cb68c04 → 3.5.6-alpha.b24b9cb

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.5.5-alpha.cb68c04 linux-x64 node-v24.21.0
20
+ @contrail/cli/3.5.6-alpha.b24b9cb linux-x64 node-v24.22.1
21
21
  $ contrail --help [COMMAND]
22
22
  USAGE
23
23
  $ contrail COMMAND
@@ -1,4 +1,3 @@
1
1
  import { AuthContext } from '@contrail/sdk';
2
2
  export declare function authUser(): Promise<AuthContext>;
3
3
  export declare function getVersionFromPackageJson(): string;
4
- export declare function parseNetworkFailureReason(e: any): string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseNetworkFailureReason = exports.getVersionFromPackageJson = exports.authUser = void 0;
3
+ exports.getVersionFromPackageJson = 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 inquirer_1 = tslib_1.__importDefault(require("inquirer"));
@@ -9,26 +9,12 @@ const config_1 = require("../helpers/config/config");
9
9
  const logger_1 = tslib_1.__importDefault(require("../logger"));
10
10
  const path_1 = tslib_1.__importDefault(require("path"));
11
11
  const fs_1 = tslib_1.__importDefault(require("fs"));
12
- const CONFIGURATION = {
13
- userPoolId: 'us-east-1_qIaNZdUfm',
14
- clientId: process.env.CONTRAIL_COGNITO_CLIENT_ID || '7knkt34gfacbgd0ghnuspefdfg',
15
- apiGateway: 'https://api.vibeiq.com/prod/api',
12
+ const DEFAULT_API_GATEWAY = config_1.ENVIRONMENTS.prod;
13
+ const COGNITO_CONFIGS = {
14
+ dev: { userPoolId: 'us-east-1_e2cA0nJWu', clientId: '209s9c62o165cqab0fu5ihjtu9' },
15
+ prod: { userPoolId: 'us-east-1_qIaNZdUfm', clientId: '7knkt34gfacbgd0ghnuspefdfg' },
16
16
  };
17
17
  async function authUser() {
18
- try {
19
- return await resolveAuthContext();
20
- }
21
- catch (e) {
22
- const reason = parseNetworkFailureReason(e);
23
- if (!reason) {
24
- throw e;
25
- }
26
- logger_1.default.error(`Could not reach the VibeIQ API: ${reason}`);
27
- process.exit(1);
28
- }
29
- }
30
- exports.authUser = authUser;
31
- async function resolveAuthContext() {
32
18
  logger_1.default.debug('authorizing user...');
33
19
  const config = await (0, config_1.getConfig)();
34
20
  if (process.env.CONTRAIL_CLI_API_KEY) {
@@ -54,14 +40,16 @@ async function resolveAuthContext() {
54
40
  return await refreshCurrentUserOrg();
55
41
  }
56
42
  catch (e) {
57
- if (parseNetworkFailureReason(e)) {
58
- throw e;
43
+ if (isNetworkConnectionError(e)) {
44
+ logger_1.default.error("Encountered a network connection issue. Please ensure you're connected to the internet and try again");
45
+ process.exit(1);
59
46
  }
60
47
  logger_1.default.info('Token expired. Requesting auth credentials...');
61
48
  }
62
49
  }
63
50
  return await authenticateWithUsernamePassword(config);
64
51
  }
52
+ exports.authUser = authUser;
65
53
  async function getOrgSlug(config) {
66
54
  const orgSlug = config?.orgSlug || process.env.CONTRAIL_CLI_ORG_SLUG;
67
55
  if (!orgSlug) {
@@ -78,7 +66,7 @@ async function getOrgSlug(config) {
78
66
  return orgSlug;
79
67
  }
80
68
  async function authenticateWithApiKey(config, apiKey, orgSlug) {
81
- const apiGateway = config?.apiGateway ?? CONFIGURATION.apiGateway;
69
+ const apiGateway = getApiGateway(config);
82
70
  sdk_1.Auth.config = {
83
71
  apiUserToken: apiKey,
84
72
  apiRefreshToken: null,
@@ -90,6 +78,12 @@ async function authenticateWithApiKey(config, apiKey, orgSlug) {
90
78
  return returnAndStoreConfig(sdk_1.Auth.config);
91
79
  }
92
80
  async function authenticateWithUsernamePassword(config) {
81
+ const apiGateway = getApiGateway(config);
82
+ const environment = (0, config_1.findEnvironmentName)(apiGateway);
83
+ if (!environment) {
84
+ 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.`);
85
+ }
86
+ const cognitoConfig = COGNITO_CONFIGS[environment];
93
87
  const questions = [];
94
88
  if (!process.env.CONTRAIL_CLI_EMAIL) {
95
89
  questions.push({
@@ -112,14 +106,15 @@ async function authenticateWithUsernamePassword(config) {
112
106
  email: process.env.CONTRAIL_CLI_EMAIL || answers.email,
113
107
  password: process.env.CONTRAIL_CLI_PASSWORD || answers.password,
114
108
  orgSlug: await getOrgSlug(config),
115
- ...(config?.apiGateway && { apiGateway: config.apiGateway }),
109
+ apiGateway,
110
+ environment,
116
111
  };
117
112
  if (!params.email || !params.password) {
118
113
  throw new Error('Email and Password required');
119
114
  }
120
115
  const poolData = {
121
- UserPoolId: CONFIGURATION.userPoolId,
122
- ClientId: CONFIGURATION.clientId,
116
+ UserPoolId: cognitoConfig.userPoolId,
117
+ ClientId: cognitoConfig.clientId,
123
118
  };
124
119
  const userPool = new amazon_cognito_identity_js_1.CognitoUserPool(poolData);
125
120
  const authData = {
@@ -135,19 +130,26 @@ async function authenticateWithUsernamePassword(config) {
135
130
  return new Promise((resolve, reject) => {
136
131
  cognitoUser.authenticateUser(authDetails, {
137
132
  onSuccess: async (result) => {
138
- const user = result;
139
- const config = await setAuthContext(user, params);
140
- resolve(config);
133
+ try {
134
+ resolve(await setAuthContext(result, params));
135
+ }
136
+ catch (e) {
137
+ reject(e);
138
+ }
141
139
  },
142
140
  onFailure: (err) => {
141
+ if (err?.code === 'ResourceNotFoundException') {
142
+ reject(new Error(`This version of the CLI has outdated ${environment} sign-in settings (${err.message}). Update the CLI: npm i -g @contrail/cli`));
143
+ return;
144
+ }
143
145
  reject(err);
144
146
  },
145
147
  });
146
148
  });
147
149
  }
148
150
  async function setAuthContext(user, params) {
149
- const apiGateway = params?.apiGateway ?? CONFIGURATION.apiGateway;
150
- const { vibeAccessToken, vibeRefreshToken } = await getVibeAccessTokenFromCognitoAccessToken(user.idToken.jwtToken, apiGateway);
151
+ const apiGateway = params.apiGateway;
152
+ const { vibeAccessToken, vibeRefreshToken } = await getVibeAccessTokenFromCognitoAccessToken(user.idToken.jwtToken, apiGateway, params.environment);
151
153
  // Set Auth Config
152
154
  sdk_1.Auth.config = {
153
155
  apiUserToken: vibeAccessToken,
@@ -183,7 +185,10 @@ async function refreshCurrentUserOrg() {
183
185
  // await checkTelemetry(current_Version);
184
186
  return returnAndStoreConfig(sdk_1.Auth.config);
185
187
  }
186
- async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiGateway) {
188
+ function getApiGateway(config) {
189
+ return config?.apiGateway ?? DEFAULT_API_GATEWAY;
190
+ }
191
+ async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiGateway, environment) {
187
192
  const url = `${apiGateway}/auth/cognito/`;
188
193
  const response = await fetch(url, {
189
194
  method: 'POST',
@@ -193,9 +198,11 @@ async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiG
193
198
  },
194
199
  body: JSON.stringify({ accessToken: cognitoAccessToken }),
195
200
  });
196
- return await response.json().then((data) => {
197
- return { vibeAccessToken: data.accessToken, vibeRefreshToken: data.refreshToken };
198
- });
201
+ if (!response.ok) {
202
+ throw new Error(`${environment} rejected the sign-in (${response.status}).`);
203
+ }
204
+ const data = await response.json();
205
+ return { vibeAccessToken: data.accessToken, vibeRefreshToken: data.refreshToken };
199
206
  }
200
207
  async function requestRefreshedAccessToken(vibeRefreshToken, apiGateway) {
201
208
  const url = `${apiGateway}/auth/jwt_refresh/`;
@@ -227,11 +234,7 @@ async function returnAndStoreConfig(config) {
227
234
  await (0, config_1.storeConfig)(configCopy);
228
235
  return configCopy;
229
236
  }
230
- function parseNetworkFailureReason(e) {
237
+ function isNetworkConnectionError(e) {
231
238
  const cause = e?.cause;
232
- if (!cause) {
233
- return null;
234
- }
235
- return cause.code ? `${cause.code}: ${cause.message}` : cause.message;
239
+ return cause?.code === 'ENOTFOUND' || cause?.code === 'ECONNREFUSED';
236
240
  }
237
- exports.parseNetworkFailureReason = parseNetworkFailureReason;
@@ -1,21 +1,128 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const amazon_cognito_identity_js_1 = require("amazon-cognito-identity-js");
4
+ const sdk_1 = require("@contrail/sdk");
5
+ const config_1 = require("../helpers/config/config");
3
6
  const login_1 = require("./login");
4
- describe('parseNetworkFailureReason', () => {
5
- it('reports the cause behind a fetch failure', () => {
6
- const e = Object.assign(new TypeError('fetch failed'), {
7
- cause: Object.assign(new Error('unable to get local issuer certificate'), {
8
- code: 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
9
- }),
7
+ const mockAuthenticateUser = jest.fn();
8
+ jest.mock('amazon-cognito-identity-js', () => ({
9
+ CognitoUserPool: jest.fn(),
10
+ AuthenticationDetails: jest.fn(),
11
+ CognitoUser: jest.fn().mockImplementation(() => ({
12
+ authenticateUser: (details, callbacks) => mockAuthenticateUser(details, callbacks),
13
+ })),
14
+ }));
15
+ jest.mock('@contrail/sdk', () => ({
16
+ Auth: { config: {} },
17
+ getCurrentUser: jest.fn(),
18
+ setConfig: jest.fn(),
19
+ }));
20
+ jest.mock('../helpers/config/config', () => ({
21
+ ...jest.requireActual('../helpers/config/config'),
22
+ getConfig: jest.fn(),
23
+ storeConfig: jest.fn(),
24
+ }));
25
+ jest.mock('../logger', () => ({
26
+ __esModule: true,
27
+ default: { debug: jest.fn(), info: jest.fn() },
28
+ }));
29
+ const DEV_GATEWAY = 'https://api.dev.vibeiq.com/dev/api';
30
+ function restoreEnv(name, value) {
31
+ if (value === undefined) {
32
+ delete process.env[name];
33
+ }
34
+ else {
35
+ process.env[name] = value;
36
+ }
37
+ }
38
+ function jsonResponse(status, body = {}) {
39
+ return new Response(JSON.stringify(body), { status });
40
+ }
41
+ describe('authUser with email and password', () => {
42
+ const originalFetch = global.fetch;
43
+ const originalEmail = process.env.CONTRAIL_CLI_EMAIL;
44
+ const originalPassword = process.env.CONTRAIL_CLI_PASSWORD;
45
+ let fetchMock;
46
+ beforeEach(() => {
47
+ jest.clearAllMocks();
48
+ process.env.CONTRAIL_CLI_EMAIL = 'dev@vibeiq.com';
49
+ process.env.CONTRAIL_CLI_PASSWORD = 'secret';
50
+ config_1.getConfig.mockResolvedValue({ apiGateway: DEV_GATEWAY, orgSlug: 'adam-zone-1' });
51
+ sdk_1.getCurrentUser.mockResolvedValue({ id: 'user-1' });
52
+ mockAuthenticateUser.mockImplementation((_details, callbacks) => callbacks.onSuccess({ idToken: { jwtToken: 'cognito-id-token' } }));
53
+ fetchMock = jest.fn();
54
+ global.fetch = fetchMock;
55
+ });
56
+ afterEach(() => {
57
+ global.fetch = originalFetch;
58
+ restoreEnv('CONTRAIL_CLI_EMAIL', originalEmail);
59
+ restoreEnv('CONTRAIL_CLI_PASSWORD', originalPassword);
60
+ });
61
+ it('should sign in through the dev pool when the config points at dev', async () => {
62
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
63
+ const context = await (0, login_1.authUser)();
64
+ expect(amazon_cognito_identity_js_1.CognitoUserPool).toHaveBeenCalledWith({
65
+ UserPoolId: 'us-east-1_e2cA0nJWu',
66
+ ClientId: '209s9c62o165cqab0fu5ihjtu9',
67
+ });
68
+ expect(context).toEqual({
69
+ apiUserToken: 'vibe-access',
70
+ apiRefreshToken: 'vibe-refresh',
71
+ apiGateway: DEV_GATEWAY,
72
+ orgSlug: 'adam-zone-1',
73
+ });
74
+ });
75
+ it('should sign in through the prod pool when the config points at prod', async () => {
76
+ config_1.getConfig.mockResolvedValue({
77
+ apiGateway: 'https://api.vibeiq.com/prod/api',
78
+ orgSlug: 'adam-zone-1',
79
+ });
80
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
81
+ await (0, login_1.authUser)();
82
+ expect(amazon_cognito_identity_js_1.CognitoUserPool).toHaveBeenCalledWith({
83
+ UserPoolId: 'us-east-1_qIaNZdUfm',
84
+ ClientId: '7knkt34gfacbgd0ghnuspefdfg',
85
+ });
86
+ });
87
+ it('should match the dev pool despite a trailing slash or different case in the gateway', async () => {
88
+ config_1.getConfig.mockResolvedValue({
89
+ apiGateway: 'https://API.dev.vibeiq.com/dev/api/',
90
+ orgSlug: 'adam-zone-1',
91
+ });
92
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
93
+ await (0, login_1.authUser)();
94
+ expect(amazon_cognito_identity_js_1.CognitoUserPool).toHaveBeenCalledWith({
95
+ UserPoolId: 'us-east-1_e2cA0nJWu',
96
+ ClientId: '209s9c62o165cqab0fu5ihjtu9',
97
+ });
98
+ });
99
+ it('should explain an unknown gateway even when it has no scheme', async () => {
100
+ config_1.getConfig.mockResolvedValue({
101
+ apiGateway: 'api.dev.vibeiq.com/dev/api',
102
+ orgSlug: 'adam-zone-1',
103
+ });
104
+ await expect((0, login_1.authUser)()).rejects.toThrow('No Cognito user pool is known for api.dev.vibeiq.com/dev/api.');
105
+ });
106
+ it('should fail without saving tokens when no pool is known for the environment', async () => {
107
+ config_1.getConfig.mockResolvedValue({
108
+ apiGateway: 'http://localhost:3000/api',
109
+ orgSlug: 'adam-zone-1',
10
110
  });
11
- expect((0, login_1.parseNetworkFailureReason)(e)).toBe('UNABLE_TO_GET_ISSUER_CERT_LOCALLY: unable to get local issuer certificate');
111
+ await expect((0, login_1.authUser)()).rejects.toThrow('No Cognito user pool is known for http://localhost:3000/api.');
112
+ expect(config_1.storeConfig).not.toHaveBeenCalled();
12
113
  });
13
- it('falls back to the message when the cause carries no code', () => {
14
- const e = Object.assign(new TypeError('fetch failed'), { cause: new Error('bad port') });
15
- expect((0, login_1.parseNetworkFailureReason)(e)).toBe('bad port');
114
+ it('should tell the user to update the CLI when its Cognito client or pool no longer exists', async () => {
115
+ mockAuthenticateUser.mockImplementation((_details, callbacks) => callbacks.onFailure({
116
+ code: 'ResourceNotFoundException',
117
+ message: 'User pool client 209s9c62o165cqab0fu5ihjtu9 does not exist.',
118
+ }));
119
+ await expect((0, login_1.authUser)()).rejects.toThrow('This version of the CLI has outdated dev sign-in settings (User pool client 209s9c62o165cqab0fu5ihjtu9 does not exist.). Update the CLI: npm i -g @contrail/cli');
120
+ expect(config_1.storeConfig).not.toHaveBeenCalled();
16
121
  });
17
- it('returns null for an API error so the caller still treats it as an expired token', () => {
18
- expect((0, login_1.parseNetworkFailureReason)(new Error('Token expired'))).toBeNull();
122
+ it('should fail without saving tokens when the environment rejects the sign-in', async () => {
123
+ fetchMock.mockResolvedValueOnce(jsonResponse(401, { message: 'Unauthorized' }));
124
+ await expect((0, login_1.authUser)()).rejects.toThrow('dev rejected the sign-in (401).');
125
+ expect(config_1.storeConfig).not.toHaveBeenCalled();
19
126
  });
20
127
  });
21
128
  describe('getVersionFromPackageJson', () => {
@@ -60,7 +60,7 @@ class BaseCommand extends core_1.Command {
60
60
  const data = (0, lodash_1.pick)(config, ['orgSlug', 'apiGateway']);
61
61
  let env = '';
62
62
  if (data.apiGateway) {
63
- env = Object.keys(config_1.ENVIRONMENTS).find((key) => config_1.ENVIRONMENTS[key] === data.apiGateway);
63
+ env = (0, config_1.findEnvironmentName)(data.apiGateway);
64
64
  }
65
65
  data.environment = env;
66
66
  delete data.apiGateway;
@@ -2,6 +2,8 @@ export declare const ENVIRONMENTS: {
2
2
  dev: string;
3
3
  prod: string;
4
4
  };
5
+ export type EnvironmentName = keyof typeof ENVIRONMENTS;
6
+ export declare function findEnvironmentName(apiGateway: string): EnvironmentName | undefined;
5
7
  export declare function initializeVibeIQConfig(): Promise<void>;
6
8
  export declare function readVibeIQConfig(): Promise<any>;
7
9
  export declare function writeVibeIQConfig(config: any): Promise<void>;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.checkTelemetry = exports.validateEnvironments = exports.getConfigContent = exports.getConfigFiles = exports.storeConfig = exports.getConfig = exports.writeConfig = exports.createConfig = exports.storeVibeIQConfig = exports.writeVibeIQConfig = exports.readVibeIQConfig = exports.initializeVibeIQConfig = exports.ENVIRONMENTS = void 0;
3
+ exports.checkTelemetry = exports.validateEnvironments = exports.getConfigContent = exports.getConfigFiles = exports.storeConfig = exports.getConfig = exports.writeConfig = exports.createConfig = exports.storeVibeIQConfig = exports.writeVibeIQConfig = exports.readVibeIQConfig = exports.initializeVibeIQConfig = exports.findEnvironmentName = exports.ENVIRONMENTS = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const node_fs_1 = require("node:fs");
6
6
  const node_path_1 = require("node:path");
@@ -16,6 +16,11 @@ exports.ENVIRONMENTS = {
16
16
  dev: 'https://api.dev.vibeiq.com/dev/api',
17
17
  prod: 'https://api.vibeiq.com/prod/api',
18
18
  };
19
+ function findEnvironmentName(apiGateway) {
20
+ const normalizedGateway = apiGateway?.trim().replace(/\/+$/, '').toLowerCase();
21
+ return Object.keys(exports.ENVIRONMENTS).find((name) => exports.ENVIRONMENTS[name] === normalizedGateway);
22
+ }
23
+ exports.findEnvironmentName = findEnvironmentName;
19
24
  async function initializeVibeIQConfig() {
20
25
  try {
21
26
  await node_fs_1.promises.mkdir(configDirectoryLocation, { recursive: true });
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "3.5.5-alpha.cb68c04",
2
+ "version": "3.5.6-alpha.b24b9cb",
3
3
  "commands": {
4
4
  "app:create": {
5
5
  "id": "app:create",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrail/cli",
3
- "version": "3.5.5-alpha.cb68c04",
3
+ "version": "3.5.6-alpha.b24b9cb",
4
4
  "description": "VibeIQ's Contrail Platform CLI.",
5
5
  "bin": {
6
6
  "contrail-cli": "./bin/run",