@contrail/cli 3.5.5 → 3.5.6-alpha.0001fc1

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 linux-x64 node-v24.21.0
20
+ @contrail/cli/3.5.6-alpha.0001fc1 linux-x64 node-v24.22.1
21
21
  $ contrail --help [COMMAND]
22
22
  USAGE
23
23
  $ contrail COMMAND
@@ -1,3 +1,4 @@
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.getVersionFromPackageJson = exports.authUser = void 0;
3
+ exports.parseNetworkFailureReason = 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,12 +9,26 @@ 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() {
18
32
  logger_1.default.debug('authorizing user...');
19
33
  const config = await (0, config_1.getConfig)();
20
34
  if (process.env.CONTRAIL_CLI_API_KEY) {
@@ -40,16 +54,14 @@ async function authUser() {
40
54
  return await refreshCurrentUserOrg();
41
55
  }
42
56
  catch (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);
57
+ if (parseNetworkFailureReason(e)) {
58
+ throw e;
46
59
  }
47
60
  logger_1.default.info('Token expired. Requesting auth credentials...');
48
61
  }
49
62
  }
50
63
  return await authenticateWithUsernamePassword(config);
51
64
  }
52
- exports.authUser = authUser;
53
65
  async function getOrgSlug(config) {
54
66
  const orgSlug = config?.orgSlug || process.env.CONTRAIL_CLI_ORG_SLUG;
55
67
  if (!orgSlug) {
@@ -66,7 +78,7 @@ async function getOrgSlug(config) {
66
78
  return orgSlug;
67
79
  }
68
80
  async function authenticateWithApiKey(config, apiKey, orgSlug) {
69
- const apiGateway = config?.apiGateway ?? CONFIGURATION.apiGateway;
81
+ const apiGateway = getApiGateway(config);
70
82
  sdk_1.Auth.config = {
71
83
  apiUserToken: apiKey,
72
84
  apiRefreshToken: null,
@@ -78,6 +90,12 @@ async function authenticateWithApiKey(config, apiKey, orgSlug) {
78
90
  return returnAndStoreConfig(sdk_1.Auth.config);
79
91
  }
80
92
  async function authenticateWithUsernamePassword(config) {
93
+ const apiGateway = getApiGateway(config);
94
+ const environment = (0, config_1.findEnvironmentName)(apiGateway);
95
+ if (!environment) {
96
+ 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.`);
97
+ }
98
+ const cognitoConfig = COGNITO_CONFIGS[environment];
81
99
  const questions = [];
82
100
  if (!process.env.CONTRAIL_CLI_EMAIL) {
83
101
  questions.push({
@@ -100,14 +118,15 @@ async function authenticateWithUsernamePassword(config) {
100
118
  email: process.env.CONTRAIL_CLI_EMAIL || answers.email,
101
119
  password: process.env.CONTRAIL_CLI_PASSWORD || answers.password,
102
120
  orgSlug: await getOrgSlug(config),
103
- ...(config?.apiGateway && { apiGateway: config.apiGateway }),
121
+ apiGateway,
122
+ environment,
104
123
  };
105
124
  if (!params.email || !params.password) {
106
125
  throw new Error('Email and Password required');
107
126
  }
108
127
  const poolData = {
109
- UserPoolId: CONFIGURATION.userPoolId,
110
- ClientId: CONFIGURATION.clientId,
128
+ UserPoolId: cognitoConfig.userPoolId,
129
+ ClientId: cognitoConfig.clientId,
111
130
  };
112
131
  const userPool = new amazon_cognito_identity_js_1.CognitoUserPool(poolData);
113
132
  const authData = {
@@ -123,19 +142,26 @@ async function authenticateWithUsernamePassword(config) {
123
142
  return new Promise((resolve, reject) => {
124
143
  cognitoUser.authenticateUser(authDetails, {
125
144
  onSuccess: async (result) => {
126
- const user = result;
127
- const config = await setAuthContext(user, params);
128
- resolve(config);
145
+ try {
146
+ resolve(await setAuthContext(result, params));
147
+ }
148
+ catch (e) {
149
+ reject(e);
150
+ }
129
151
  },
130
152
  onFailure: (err) => {
153
+ if (err?.code === 'ResourceNotFoundException') {
154
+ reject(new Error(`This version of the CLI has outdated ${environment} sign-in settings (${err.message}). Update the CLI: npm i -g @contrail/cli`));
155
+ return;
156
+ }
131
157
  reject(err);
132
158
  },
133
159
  });
134
160
  });
135
161
  }
136
162
  async function setAuthContext(user, params) {
137
- const apiGateway = params?.apiGateway ?? CONFIGURATION.apiGateway;
138
- const { vibeAccessToken, vibeRefreshToken } = await getVibeAccessTokenFromCognitoAccessToken(user.idToken.jwtToken, apiGateway);
163
+ const apiGateway = params.apiGateway;
164
+ const { vibeAccessToken, vibeRefreshToken } = await getVibeAccessTokenFromCognitoAccessToken(user.idToken.jwtToken, apiGateway, params.environment);
139
165
  // Set Auth Config
140
166
  sdk_1.Auth.config = {
141
167
  apiUserToken: vibeAccessToken,
@@ -171,7 +197,10 @@ async function refreshCurrentUserOrg() {
171
197
  // await checkTelemetry(current_Version);
172
198
  return returnAndStoreConfig(sdk_1.Auth.config);
173
199
  }
174
- async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiGateway) {
200
+ function getApiGateway(config) {
201
+ return config?.apiGateway ?? DEFAULT_API_GATEWAY;
202
+ }
203
+ async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiGateway, environment) {
175
204
  const url = `${apiGateway}/auth/cognito/`;
176
205
  const response = await fetch(url, {
177
206
  method: 'POST',
@@ -181,9 +210,11 @@ async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiG
181
210
  },
182
211
  body: JSON.stringify({ accessToken: cognitoAccessToken }),
183
212
  });
184
- return await response.json().then((data) => {
185
- return { vibeAccessToken: data.accessToken, vibeRefreshToken: data.refreshToken };
186
- });
213
+ if (!response.ok) {
214
+ throw new Error(`${environment} rejected the sign-in (${response.status}).`);
215
+ }
216
+ const data = await response.json();
217
+ return { vibeAccessToken: data.accessToken, vibeRefreshToken: data.refreshToken };
187
218
  }
188
219
  async function requestRefreshedAccessToken(vibeRefreshToken, apiGateway) {
189
220
  const url = `${apiGateway}/auth/jwt_refresh/`;
@@ -215,7 +246,11 @@ async function returnAndStoreConfig(config) {
215
246
  await (0, config_1.storeConfig)(configCopy);
216
247
  return configCopy;
217
248
  }
218
- function isNetworkConnectionError(e) {
249
+ function parseNetworkFailureReason(e) {
219
250
  const cause = e?.cause;
220
- return cause?.code === 'ENOTFOUND' || cause?.code === 'ECONNREFUSED';
251
+ if (!cause) {
252
+ return null;
253
+ }
254
+ return cause.code ? `${cause.code}: ${cause.message}` : cause.message;
221
255
  }
256
+ exports.parseNetworkFailureReason = parseNetworkFailureReason;
@@ -1,6 +1,147 @@
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");
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(), error: 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',
110
+ });
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();
113
+ });
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();
121
+ });
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();
126
+ });
127
+ });
128
+ describe('parseNetworkFailureReason', () => {
129
+ it('reports the cause behind a fetch failure', () => {
130
+ const e = Object.assign(new TypeError('fetch failed'), {
131
+ cause: Object.assign(new Error('unable to get local issuer certificate'), {
132
+ code: 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
133
+ }),
134
+ });
135
+ expect((0, login_1.parseNetworkFailureReason)(e)).toBe('UNABLE_TO_GET_ISSUER_CERT_LOCALLY: unable to get local issuer certificate');
136
+ });
137
+ it('falls back to the message when the cause carries no code', () => {
138
+ const e = Object.assign(new TypeError('fetch failed'), { cause: new Error('bad port') });
139
+ expect((0, login_1.parseNetworkFailureReason)(e)).toBe('bad port');
140
+ });
141
+ it('returns null for an API error so the caller still treats it as an expired token', () => {
142
+ expect((0, login_1.parseNetworkFailureReason)(new Error('Token expired'))).toBeNull();
143
+ });
144
+ });
4
145
  describe('getVersionFromPackageJson', () => {
5
146
  it('should return the version value from package.json', () => {
6
147
  const version = (0, login_1.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",
2
+ "version": "3.5.6-alpha.0001fc1",
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",
3
+ "version": "3.5.6-alpha.0001fc1",
4
4
  "description": "VibeIQ's Contrail Platform CLI.",
5
5
  "bin": {
6
6
  "contrail-cli": "./bin/run",