@contrail/cli 3.5.5-alpha.68765d7 → 3.5.5-alpha.6b09743

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.68765d7 linux-x64 node-v24.21.0
20
+ @contrail/cli/3.5.5-alpha.6b09743 linux-x64 node-v24.21.0
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
  logger_1.default.debug('authorizing user...');
@@ -66,7 +66,7 @@ async function getOrgSlug(config) {
66
66
  return orgSlug;
67
67
  }
68
68
  async function authenticateWithApiKey(config, apiKey, orgSlug) {
69
- const apiGateway = config?.apiGateway ?? CONFIGURATION.apiGateway;
69
+ const apiGateway = getApiGateway(config);
70
70
  sdk_1.Auth.config = {
71
71
  apiUserToken: apiKey,
72
72
  apiRefreshToken: null,
@@ -78,6 +78,12 @@ async function authenticateWithApiKey(config, apiKey, orgSlug) {
78
78
  return returnAndStoreConfig(sdk_1.Auth.config);
79
79
  }
80
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];
81
87
  const questions = [];
82
88
  if (!process.env.CONTRAIL_CLI_EMAIL) {
83
89
  questions.push({
@@ -100,14 +106,15 @@ async function authenticateWithUsernamePassword(config) {
100
106
  email: process.env.CONTRAIL_CLI_EMAIL || answers.email,
101
107
  password: process.env.CONTRAIL_CLI_PASSWORD || answers.password,
102
108
  orgSlug: await getOrgSlug(config),
103
- ...(config?.apiGateway && { apiGateway: config.apiGateway }),
109
+ apiGateway,
110
+ environment,
104
111
  };
105
112
  if (!params.email || !params.password) {
106
113
  throw new Error('Email and Password required');
107
114
  }
108
115
  const poolData = {
109
- UserPoolId: CONFIGURATION.userPoolId,
110
- ClientId: CONFIGURATION.clientId,
116
+ UserPoolId: cognitoConfig.userPoolId,
117
+ ClientId: cognitoConfig.clientId,
111
118
  };
112
119
  const userPool = new amazon_cognito_identity_js_1.CognitoUserPool(poolData);
113
120
  const authData = {
@@ -123,19 +130,26 @@ async function authenticateWithUsernamePassword(config) {
123
130
  return new Promise((resolve, reject) => {
124
131
  cognitoUser.authenticateUser(authDetails, {
125
132
  onSuccess: async (result) => {
126
- const user = result;
127
- const config = await setAuthContext(user, params);
128
- resolve(config);
133
+ try {
134
+ resolve(await setAuthContext(result, params));
135
+ }
136
+ catch (e) {
137
+ reject(e);
138
+ }
129
139
  },
130
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
+ }
131
145
  reject(err);
132
146
  },
133
147
  });
134
148
  });
135
149
  }
136
150
  async function setAuthContext(user, params) {
137
- const apiGateway = params?.apiGateway ?? CONFIGURATION.apiGateway;
138
- 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);
139
153
  // Set Auth Config
140
154
  sdk_1.Auth.config = {
141
155
  apiUserToken: vibeAccessToken,
@@ -171,7 +185,10 @@ async function refreshCurrentUserOrg() {
171
185
  // await checkTelemetry(current_Version);
172
186
  return returnAndStoreConfig(sdk_1.Auth.config);
173
187
  }
174
- async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiGateway) {
188
+ function getApiGateway(config) {
189
+ return config?.apiGateway ?? DEFAULT_API_GATEWAY;
190
+ }
191
+ async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiGateway, environment) {
175
192
  const url = `${apiGateway}/auth/cognito/`;
176
193
  const response = await fetch(url, {
177
194
  method: 'POST',
@@ -181,9 +198,11 @@ async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiG
181
198
  },
182
199
  body: JSON.stringify({ accessToken: cognitoAccessToken }),
183
200
  });
184
- return await response.json().then((data) => {
185
- return { vibeAccessToken: data.accessToken, vibeRefreshToken: data.refreshToken };
186
- });
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 };
187
206
  }
188
207
  async function requestRefreshedAccessToken(vibeRefreshToken, apiGateway) {
189
208
  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() },
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('getVersionFromPackageJson', () => {
5
129
  it('should return the version value from package.json', () => {
6
130
  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-alpha.68765d7",
2
+ "version": "3.5.5-alpha.6b09743",
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.68765d7",
3
+ "version": "3.5.5-alpha.6b09743",
4
4
  "description": "VibeIQ's Contrail Platform CLI.",
5
5
  "bin": {
6
6
  "contrail-cli": "./bin/run",