@contrail/cli 3.5.5-alpha.cb68c04 → 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-alpha.cb68c04 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
@@ -9,10 +9,10 @@ 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
18
  try {
@@ -78,7 +78,7 @@ async function getOrgSlug(config) {
78
78
  return orgSlug;
79
79
  }
80
80
  async function authenticateWithApiKey(config, apiKey, orgSlug) {
81
- const apiGateway = config?.apiGateway ?? CONFIGURATION.apiGateway;
81
+ const apiGateway = getApiGateway(config);
82
82
  sdk_1.Auth.config = {
83
83
  apiUserToken: apiKey,
84
84
  apiRefreshToken: null,
@@ -90,6 +90,12 @@ async function authenticateWithApiKey(config, apiKey, orgSlug) {
90
90
  return returnAndStoreConfig(sdk_1.Auth.config);
91
91
  }
92
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];
93
99
  const questions = [];
94
100
  if (!process.env.CONTRAIL_CLI_EMAIL) {
95
101
  questions.push({
@@ -112,14 +118,15 @@ async function authenticateWithUsernamePassword(config) {
112
118
  email: process.env.CONTRAIL_CLI_EMAIL || answers.email,
113
119
  password: process.env.CONTRAIL_CLI_PASSWORD || answers.password,
114
120
  orgSlug: await getOrgSlug(config),
115
- ...(config?.apiGateway && { apiGateway: config.apiGateway }),
121
+ apiGateway,
122
+ environment,
116
123
  };
117
124
  if (!params.email || !params.password) {
118
125
  throw new Error('Email and Password required');
119
126
  }
120
127
  const poolData = {
121
- UserPoolId: CONFIGURATION.userPoolId,
122
- ClientId: CONFIGURATION.clientId,
128
+ UserPoolId: cognitoConfig.userPoolId,
129
+ ClientId: cognitoConfig.clientId,
123
130
  };
124
131
  const userPool = new amazon_cognito_identity_js_1.CognitoUserPool(poolData);
125
132
  const authData = {
@@ -135,19 +142,26 @@ async function authenticateWithUsernamePassword(config) {
135
142
  return new Promise((resolve, reject) => {
136
143
  cognitoUser.authenticateUser(authDetails, {
137
144
  onSuccess: async (result) => {
138
- const user = result;
139
- const config = await setAuthContext(user, params);
140
- resolve(config);
145
+ try {
146
+ resolve(await setAuthContext(result, params));
147
+ }
148
+ catch (e) {
149
+ reject(e);
150
+ }
141
151
  },
142
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
+ }
143
157
  reject(err);
144
158
  },
145
159
  });
146
160
  });
147
161
  }
148
162
  async function setAuthContext(user, params) {
149
- const apiGateway = params?.apiGateway ?? CONFIGURATION.apiGateway;
150
- 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);
151
165
  // Set Auth Config
152
166
  sdk_1.Auth.config = {
153
167
  apiUserToken: vibeAccessToken,
@@ -183,7 +197,10 @@ async function refreshCurrentUserOrg() {
183
197
  // await checkTelemetry(current_Version);
184
198
  return returnAndStoreConfig(sdk_1.Auth.config);
185
199
  }
186
- async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiGateway) {
200
+ function getApiGateway(config) {
201
+ return config?.apiGateway ?? DEFAULT_API_GATEWAY;
202
+ }
203
+ async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiGateway, environment) {
187
204
  const url = `${apiGateway}/auth/cognito/`;
188
205
  const response = await fetch(url, {
189
206
  method: 'POST',
@@ -193,9 +210,11 @@ async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiG
193
210
  },
194
211
  body: JSON.stringify({ accessToken: cognitoAccessToken }),
195
212
  });
196
- return await response.json().then((data) => {
197
- return { vibeAccessToken: data.accessToken, vibeRefreshToken: data.refreshToken };
198
- });
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 };
199
218
  }
200
219
  async function requestRefreshedAccessToken(vibeRefreshToken, apiGateway) {
201
220
  const url = `${apiGateway}/auth/jwt_refresh/`;
@@ -1,6 +1,130 @@
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
+ });
4
128
  describe('parseNetworkFailureReason', () => {
5
129
  it('reports the cause behind a fetch failure', () => {
6
130
  const e = Object.assign(new TypeError('fetch failed'), {
@@ -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.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-alpha.cb68c04",
3
+ "version": "3.5.6-alpha.0001fc1",
4
4
  "description": "VibeIQ's Contrail Platform CLI.",
5
5
  "bin": {
6
6
  "contrail-cli": "./bin/run",