@contrail/cli 3.5.6 → 3.5.7-alpha.a18b693

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.6 linux-x64 node-v24.22.1
20
+ @contrail/cli/3.5.7-alpha.a18b693 linux-x64 node-v24.22.1
21
21
  $ contrail --help [COMMAND]
22
22
  USAGE
23
23
  $ contrail COMMAND
@@ -163,28 +163,27 @@ async function setAuthContext(user, params) {
163
163
  }
164
164
  async function refreshCurrentUserOrg() {
165
165
  logger_1.default.debug('refreshing current user org...');
166
- const currentUser = await (0, sdk_1.getCurrentUser)();
167
- if (!currentUser) {
168
- const config = await (0, config_1.getConfig)();
169
- try {
170
- const newVibeAccessToken = await requestRefreshedAccessToken(config.apiRefreshToken, config.apiGateway);
171
- sdk_1.Auth.config = {
172
- apiUserToken: newVibeAccessToken,
173
- apiRefreshToken: config.apiRefreshToken,
174
- apiGateway: config.apiGateway,
175
- orgSlug: config.orgSlug,
176
- };
177
- console.log('fetched new access token from refresh token', newVibeAccessToken);
178
- }
179
- catch (e) {
180
- throw Error('Could not get refresh token');
166
+ try {
167
+ await (0, sdk_1.getCurrentUser)();
168
+ }
169
+ catch (e) {
170
+ if (isNetworkConnectionError(e)) {
171
+ throw e;
181
172
  }
173
+ logger_1.default.debug('access token rejected, refreshing it...');
174
+ await refreshAccessToken();
175
+ await (0, sdk_1.getCurrentUser)();
182
176
  }
183
177
  // TODO: To uncomment when telemetry backend is developed.
184
178
  // const current_Version = getVersionFromPackageJson();
185
179
  // await checkTelemetry(current_Version);
186
180
  return returnAndStoreConfig(sdk_1.Auth.config);
187
181
  }
182
+ async function refreshAccessToken() {
183
+ const newVibeAccessToken = await requestRefreshedAccessToken(sdk_1.Auth.config.apiRefreshToken, sdk_1.Auth.config.apiGateway);
184
+ sdk_1.Auth.config = { ...sdk_1.Auth.config, apiUserToken: newVibeAccessToken };
185
+ (0, sdk_1.setConfig)(sdk_1.Auth.config);
186
+ }
188
187
  function getApiGateway(config) {
189
188
  return config?.apiGateway ?? DEFAULT_API_GATEWAY;
190
189
  }
@@ -214,9 +213,14 @@ async function requestRefreshedAccessToken(vibeRefreshToken, apiGateway) {
214
213
  },
215
214
  body: JSON.stringify({ refreshToken: vibeRefreshToken }),
216
215
  });
217
- return await response.json().then((data) => {
218
- return data.accessToken;
219
- });
216
+ if (!response.ok) {
217
+ throw new Error(`Token refresh failed with status ${response.status}`);
218
+ }
219
+ const data = await response.json();
220
+ if (!data.accessToken) {
221
+ throw new Error('Token refresh response did not contain an access token');
222
+ }
223
+ return data.accessToken;
220
224
  }
221
225
  function getVersionFromPackageJson() {
222
226
  // Get the path to the package.json file
@@ -24,7 +24,7 @@ jest.mock('../helpers/config/config', () => ({
24
24
  }));
25
25
  jest.mock('../logger', () => ({
26
26
  __esModule: true,
27
- default: { debug: jest.fn(), info: jest.fn() },
27
+ default: { debug: jest.fn(), info: jest.fn(), error: jest.fn() },
28
28
  }));
29
29
  const DEV_GATEWAY = 'https://api.dev.vibeiq.com/dev/api';
30
30
  function restoreEnv(name, value) {
@@ -125,6 +125,83 @@ describe('authUser with email and password', () => {
125
125
  expect(config_1.storeConfig).not.toHaveBeenCalled();
126
126
  });
127
127
  });
128
+ describe('authUser with stored tokens', () => {
129
+ const originalFetch = global.fetch;
130
+ const originalEmail = process.env.CONTRAIL_CLI_EMAIL;
131
+ const originalPassword = process.env.CONTRAIL_CLI_PASSWORD;
132
+ const storedConfig = {
133
+ apiUserToken: 'expired-access',
134
+ apiRefreshToken: 'stored-refresh',
135
+ apiGateway: DEV_GATEWAY,
136
+ orgSlug: 'adam-zone-1',
137
+ };
138
+ let acceptedTokens;
139
+ let fetchMock;
140
+ function acceptOnlyTokensGivenToTheSdk() {
141
+ sdk_1.getCurrentUser.mockImplementation(async () => {
142
+ const token = sdk_1.setConfig.mock.calls.at(-1)?.[0]?.apiUserToken;
143
+ if (!acceptedTokens.includes(token)) {
144
+ throw new Error('Failed to fetch current user. Unauthorized');
145
+ }
146
+ return { id: 'user-1' };
147
+ });
148
+ }
149
+ beforeEach(() => {
150
+ jest.clearAllMocks();
151
+ process.env.CONTRAIL_CLI_EMAIL = 'dev@vibeiq.com';
152
+ process.env.CONTRAIL_CLI_PASSWORD = 'secret';
153
+ config_1.getConfig.mockResolvedValue(storedConfig);
154
+ acceptedTokens = ['refreshed-access', 'vibe-access'];
155
+ acceptOnlyTokensGivenToTheSdk();
156
+ mockAuthenticateUser.mockImplementation((_details, callbacks) => callbacks.onSuccess({ idToken: { jwtToken: 'cognito-id-token' } }));
157
+ fetchMock = jest.fn();
158
+ global.fetch = fetchMock;
159
+ });
160
+ afterEach(() => {
161
+ global.fetch = originalFetch;
162
+ restoreEnv('CONTRAIL_CLI_EMAIL', originalEmail);
163
+ restoreEnv('CONTRAIL_CLI_PASSWORD', originalPassword);
164
+ });
165
+ it('should refresh an expired access token without asking for a password', async () => {
166
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'refreshed-access' }));
167
+ const context = await (0, login_1.authUser)();
168
+ expect(fetchMock).toHaveBeenCalledWith(`${DEV_GATEWAY}/auth/jwt_refresh/`, expect.objectContaining({ body: JSON.stringify({ refreshToken: 'stored-refresh' }) }));
169
+ expect(mockAuthenticateUser).not.toHaveBeenCalled();
170
+ expect(context).toEqual({ ...storedConfig, apiUserToken: 'refreshed-access' });
171
+ expect(config_1.storeConfig).toHaveBeenCalledWith(context);
172
+ });
173
+ it('should keep a still-valid access token without refreshing it', async () => {
174
+ acceptedTokens = ['expired-access'];
175
+ const context = await (0, login_1.authUser)();
176
+ expect(fetchMock).not.toHaveBeenCalled();
177
+ expect(context).toEqual(storedConfig);
178
+ });
179
+ it('should fall back to the password sign-in when the refresh token is rejected', async () => {
180
+ fetchMock
181
+ .mockResolvedValueOnce(jsonResponse(401, { message: 'Unauthorized' }))
182
+ .mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
183
+ const context = await (0, login_1.authUser)();
184
+ expect(mockAuthenticateUser).toHaveBeenCalledTimes(1);
185
+ expect(context).toEqual({
186
+ ...storedConfig,
187
+ apiUserToken: 'vibe-access',
188
+ apiRefreshToken: 'vibe-refresh',
189
+ });
190
+ });
191
+ it('should exit with a connection error instead of prompting when the network is down', async () => {
192
+ const networkError = Object.assign(new TypeError('fetch failed'), {
193
+ cause: { code: 'ENOTFOUND' },
194
+ });
195
+ sdk_1.getCurrentUser.mockRejectedValue(networkError);
196
+ const exit = jest.spyOn(process, 'exit').mockImplementation((code) => {
197
+ throw new Error(`exit ${code}`);
198
+ });
199
+ await expect((0, login_1.authUser)()).rejects.toThrow('exit 1');
200
+ expect(fetchMock).not.toHaveBeenCalled();
201
+ expect(mockAuthenticateUser).not.toHaveBeenCalled();
202
+ exit.mockRestore();
203
+ });
204
+ });
128
205
  describe('getVersionFromPackageJson', () => {
129
206
  it('should return the version value from package.json', () => {
130
207
  const version = (0, login_1.getVersionFromPackageJson)();
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "3.5.6",
2
+ "version": "3.5.7-alpha.a18b693",
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.6",
3
+ "version": "3.5.7-alpha.a18b693",
4
4
  "description": "VibeIQ's Contrail Platform CLI.",
5
5
  "bin": {
6
6
  "contrail-cli": "./bin/run",