@contrail/cli 3.6.0-alpha-8-alpha.c321203 → 3.6.0-alpha-8-alpha.53e9604

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.6.0-alpha-8-alpha.c321203 linux-x64 node-v24.22.1
20
+ @contrail/cli/3.6.0-alpha-8-alpha.53e9604 linux-x64 node-v24.22.1
21
21
  $ contrail --help [COMMAND]
22
22
  USAGE
23
23
  $ contrail COMMAND
@@ -37,14 +37,15 @@ async function authUser() {
37
37
  };
38
38
  (0, sdk_1.setConfig)(sdk_1.Auth.config);
39
39
  try {
40
- return await refreshCurrentUserOrg();
40
+ return await signInWithStoredTokens();
41
41
  }
42
42
  catch (e) {
43
+ logger_1.default.debug(`stored tokens rejected: ${e?.message}`);
43
44
  if (isNetworkConnectionError(e)) {
44
45
  logger_1.default.error("Encountered a network connection issue. Please ensure you're connected to the internet and try again");
45
46
  process.exit(1);
46
47
  }
47
- logger_1.default.info(`Failed to refresh token: ${e}. Requesting auth credentials...`);
48
+ logger_1.default.info('Token expired. Requesting auth credentials...');
48
49
  }
49
50
  }
50
51
  return await authenticateWithUsernamePassword(config);
@@ -150,47 +151,43 @@ async function authenticateWithUsernamePassword(config) {
150
151
  async function setAuthContext(user, params) {
151
152
  const apiGateway = params.apiGateway;
152
153
  const { vibeAccessToken, vibeRefreshToken } = await getVibeAccessTokenFromCognitoAccessToken(user.idToken.jwtToken, apiGateway, params.environment);
154
+ // Set Auth Config
153
155
  sdk_1.Auth.config = {
154
156
  apiUserToken: vibeAccessToken,
155
157
  apiRefreshToken: vibeRefreshToken,
156
158
  apiGateway,
157
159
  orgSlug: params.orgSlug,
158
160
  };
161
+ // SET SDK CONFIG
159
162
  (0, sdk_1.setConfig)(sdk_1.Auth.config);
160
163
  return refreshCurrentUserOrg();
161
164
  }
162
- async function refreshCurrentUserOrg() {
163
- logger_1.default.debug('refreshing current user org...');
164
- const currentUser = await (0, sdk_1.getCurrentUser)().catch((e) => {
165
- if (isExpiredTokenError(e)) {
166
- logger_1.default.debug('access token expired; attempting refresh');
167
- return;
168
- }
169
- throw e;
170
- });
171
- if (!currentUser) {
172
- const config = await (0, config_1.getConfig)();
173
- try {
174
- const newVibeAccessToken = await requestRefreshedAccessToken(config.apiRefreshToken, config.apiGateway);
175
- sdk_1.Auth.config = {
176
- apiUserToken: newVibeAccessToken,
177
- apiRefreshToken: config.apiRefreshToken,
178
- apiGateway: config.apiGateway,
179
- orgSlug: config.orgSlug,
180
- };
181
- (0, sdk_1.setConfig)(sdk_1.Auth.config);
182
- }
183
- catch (e) {
184
- throw Error(`Could not get refresh token: ${e}`);
165
+ async function signInWithStoredTokens() {
166
+ try {
167
+ await (0, sdk_1.getCurrentUser)();
168
+ }
169
+ catch (e) {
170
+ if (isNetworkConnectionError(e)) {
171
+ throw e;
185
172
  }
173
+ logger_1.default.debug('access token rejected, refreshing it...');
174
+ await refreshAccessToken();
175
+ await (0, sdk_1.getCurrentUser)();
186
176
  }
177
+ return returnAndStoreConfig(sdk_1.Auth.config);
178
+ }
179
+ async function refreshCurrentUserOrg() {
180
+ logger_1.default.debug('refreshing current user org...');
181
+ await (0, sdk_1.getCurrentUser)();
187
182
  // TODO: To uncomment when telemetry backend is developed.
188
183
  // const current_Version = getVersionFromPackageJson();
189
184
  // await checkTelemetry(current_Version);
190
185
  return returnAndStoreConfig(sdk_1.Auth.config);
191
186
  }
192
- function isExpiredTokenError(e) {
193
- return e?.message?.includes('token is expired');
187
+ async function refreshAccessToken() {
188
+ const newVibeAccessToken = await requestRefreshedAccessToken(sdk_1.Auth.config.apiRefreshToken, sdk_1.Auth.config.apiGateway);
189
+ sdk_1.Auth.config = { ...sdk_1.Auth.config, apiUserToken: newVibeAccessToken };
190
+ (0, sdk_1.setConfig)(sdk_1.Auth.config);
194
191
  }
195
192
  function getApiGateway(config) {
196
193
  return config?.apiGateway ?? DEFAULT_API_GATEWAY;
@@ -221,9 +218,12 @@ async function requestRefreshedAccessToken(vibeRefreshToken, apiGateway) {
221
218
  },
222
219
  body: JSON.stringify({ refreshToken: vibeRefreshToken }),
223
220
  });
221
+ if (!response.ok) {
222
+ throw new Error(`Token refresh failed with status ${response.status}`);
223
+ }
224
224
  const data = await response.json();
225
- if (!response.ok || !data.accessToken) {
226
- throw new Error(`jwt_refresh returned ${response.status} with no access token`);
225
+ if (!data.accessToken) {
226
+ throw new Error('Token refresh response did not contain an access token');
227
227
  }
228
228
  return data.accessToken;
229
229
  }
@@ -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,90 @@ 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
+ let exitSpy;
141
+ function acceptOnlyTokensGivenToTheSdk() {
142
+ sdk_1.getCurrentUser.mockImplementation(async () => {
143
+ const token = sdk_1.setConfig.mock.calls.at(-1)?.[0]?.apiUserToken;
144
+ if (!acceptedTokens.includes(token)) {
145
+ throw new Error('Failed to fetch current user. Unauthorized');
146
+ }
147
+ return { id: 'user-1' };
148
+ });
149
+ }
150
+ beforeEach(() => {
151
+ jest.clearAllMocks();
152
+ process.env.CONTRAIL_CLI_EMAIL = 'dev@vibeiq.com';
153
+ process.env.CONTRAIL_CLI_PASSWORD = 'secret';
154
+ config_1.getConfig.mockResolvedValue(storedConfig);
155
+ acceptedTokens = ['refreshed-access', 'vibe-access'];
156
+ acceptOnlyTokensGivenToTheSdk();
157
+ mockAuthenticateUser.mockImplementation((_details, callbacks) => callbacks.onSuccess({ idToken: { jwtToken: 'cognito-id-token' } }));
158
+ fetchMock = jest.fn();
159
+ global.fetch = fetchMock;
160
+ });
161
+ afterEach(() => {
162
+ exitSpy?.mockRestore();
163
+ global.fetch = originalFetch;
164
+ restoreEnv('CONTRAIL_CLI_EMAIL', originalEmail);
165
+ restoreEnv('CONTRAIL_CLI_PASSWORD', originalPassword);
166
+ });
167
+ it('should refresh an expired access token without asking for a password', async () => {
168
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'refreshed-access' }));
169
+ const context = await (0, login_1.authUser)();
170
+ expect(fetchMock).toHaveBeenCalledWith(`${DEV_GATEWAY}/auth/jwt_refresh/`, expect.objectContaining({ body: JSON.stringify({ refreshToken: 'stored-refresh' }) }));
171
+ expect(context).toEqual({ ...storedConfig, apiUserToken: 'refreshed-access' });
172
+ expect(config_1.storeConfig).toHaveBeenCalledWith(context);
173
+ });
174
+ it('should keep a still-valid access token without refreshing it', async () => {
175
+ acceptedTokens = ['expired-access'];
176
+ const context = await (0, login_1.authUser)();
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(context).toEqual({
185
+ ...storedConfig,
186
+ apiUserToken: 'vibe-access',
187
+ apiRefreshToken: 'vibe-refresh',
188
+ });
189
+ });
190
+ it('should report a rejected password sign-in without refreshing the token it was just issued', async () => {
191
+ config_1.getConfig.mockResolvedValue({ apiGateway: DEV_GATEWAY, orgSlug: 'adam-zone-1' });
192
+ acceptedTokens = [];
193
+ fetchMock
194
+ .mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }))
195
+ .mockResolvedValueOnce(jsonResponse(400, { message: 'Bad Request' }));
196
+ await expect((0, login_1.authUser)()).rejects.toThrow('Failed to fetch current user. Unauthorized');
197
+ expect(config_1.storeConfig).not.toHaveBeenCalled();
198
+ });
199
+ it('should exit with a connection error instead of prompting when the network is down', async () => {
200
+ const networkError = Object.assign(new TypeError('fetch failed'), {
201
+ cause: { code: 'ENOTFOUND' },
202
+ });
203
+ sdk_1.getCurrentUser.mockRejectedValue(networkError);
204
+ exitSpy = jest.spyOn(process, 'exit').mockImplementation((code) => {
205
+ throw new Error(`exit ${code}`);
206
+ });
207
+ await expect((0, login_1.authUser)()).rejects.toThrow('exit 1');
208
+ expect(fetchMock).not.toHaveBeenCalled();
209
+ expect(mockAuthenticateUser).not.toHaveBeenCalled();
210
+ });
211
+ });
128
212
  describe('getVersionFromPackageJson', () => {
129
213
  it('should return the version value from package.json', () => {
130
214
  const version = (0, login_1.getVersionFromPackageJson)();
@@ -1,6 +1,5 @@
1
1
  import { Item } from '@contrail/entity-types';
2
2
  import { API_VERSION } from '@contrail/sdk';
3
- export declare function throwIfInvalidAssortmentId(assortmentId: string): Promise<void>;
4
3
  export declare function createAssortmentItem(assortmentItem: {
5
4
  assortmentId: string;
6
5
  itemId: string;
@@ -1,20 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.findItemsNotInAssortment = exports.createAssortmentItem = exports.throwIfInvalidAssortmentId = void 0;
3
+ exports.findItemsNotInAssortment = exports.createAssortmentItem = void 0;
4
4
  const sdk_1 = require("@contrail/sdk");
5
5
  const batchFetch_1 = require("./batchFetch");
6
6
  const items_1 = require("./items");
7
- async function throwIfInvalidAssortmentId(assortmentId) {
8
- if (!(await doesAssortmentExistById(assortmentId))) {
9
- throw new Error(`Assortment with ID ${assortmentId} does not exist`);
10
- }
11
- }
12
- exports.throwIfInvalidAssortmentId = throwIfInvalidAssortmentId;
13
- async function doesAssortmentExistById(id) {
14
- const client = new sdk_1.Entities();
15
- const assortment = await client.get({ entityName: 'assortment', id });
16
- return !!assortment;
17
- }
18
7
  async function createAssortmentItem(assortmentItem, options = {}) {
19
8
  const client = new sdk_1.Entities();
20
9
  const { assortmentId, itemId } = assortmentItem;
@@ -1,5 +1,4 @@
1
1
  import { Item } from '@contrail/entity-types';
2
- export declare function throwIfInvalidItemId(itemId: string): Promise<void>;
3
2
  export type SparseItem = Pick<Item, 'id' | 'itemFamilyId' | 'roles' | 'name'>;
4
3
  export declare function getAllItemsUsingCacheFallback(): Promise<SparseItem[]>;
5
4
  export declare function getManyItems(maxCount?: number): Promise<SparseItem[]>;
@@ -7,4 +6,3 @@ export declare function getItemFamilies(count: number): Promise<SparseItem[] | u
7
6
  export declare function getFamilyName(item: SparseItem): Promise<string[] | undefined>;
8
7
  export declare const Roles: readonly ["option", "family"];
9
8
  export type Role = (typeof Roles)[number];
10
- export declare function throwIfInvalidItemLevel(role: string): asserts role is Role;
@@ -1,18 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.throwIfInvalidItemLevel = exports.Roles = exports.getFamilyName = exports.getItemFamilies = exports.getManyItems = exports.getAllItemsUsingCacheFallback = exports.throwIfInvalidItemId = void 0;
3
+ exports.Roles = exports.getFamilyName = exports.getItemFamilies = exports.getManyItems = exports.getAllItemsUsingCacheFallback = void 0;
4
4
  const sdk_1 = require("@contrail/sdk");
5
- async function throwIfInvalidItemId(itemId) {
6
- if (!(await doesItemExistById(itemId))) {
7
- throw new Error(`Item with ID ${itemId} does not exist`);
8
- }
9
- }
10
- exports.throwIfInvalidItemId = throwIfInvalidItemId;
11
- async function doesItemExistById(id) {
12
- const client = new sdk_1.Entities();
13
- const item = await client.get({ entityName: 'item', id });
14
- return !!item;
15
- }
16
5
  const ITEMS_CACHE_BY_ID = new Map();
17
6
  async function getAllItemsUsingCacheFallback() {
18
7
  if (ITEMS_CACHE_BY_ID.size > 0) {
@@ -73,12 +62,6 @@ async function ensureItemCacheIsPopulated() {
73
62
  }
74
63
  }
75
64
  exports.Roles = ['option', 'family'];
76
- function throwIfInvalidItemLevel(role) {
77
- if (!exports.Roles.includes(role)) {
78
- throw new Error(`Invalid role: ${role}. Valid roles are: ${exports.Roles.join(', ')}`);
79
- }
80
- }
81
- exports.throwIfInvalidItemLevel = throwIfInvalidItemLevel;
82
65
  async function getItems(criteria, count = 100) {
83
66
  const client = new sdk_1.Entities();
84
67
  const items = [];
@@ -1,3 +1,2 @@
1
1
  import { Item } from '@contrail/entity-types';
2
- export declare function throwIfInvalidProjectId(projectId: string): Promise<void>;
3
2
  export declare function findItemsNotInProject(projectId: string): Promise<Item[]>;
@@ -1,31 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.findItemsNotInProject = exports.throwIfInvalidProjectId = void 0;
4
- const sdk_1 = require("@contrail/sdk");
3
+ exports.findItemsNotInProject = void 0;
5
4
  const batchFetch_1 = require("./batchFetch");
6
5
  const items_1 = require("./items");
7
6
  const PROJECT_ITEMS_CACHE_BY_PROJECT_ID = new Map();
8
7
  const PROJECT_ITEMS_CACHE_BY_ITEM_ID = new Map();
9
- async function throwIfInvalidProjectId(projectId) {
10
- if (!(await doesProjectExistById(projectId))) {
11
- throw new Error(`Project with ID ${projectId} does not exist`);
12
- }
13
- }
14
- exports.throwIfInvalidProjectId = throwIfInvalidProjectId;
15
- async function doesProjectExistById(id) {
16
- const client = new sdk_1.Entities();
17
- const project = await client
18
- .get({
19
- entityName: 'project',
20
- id,
21
- customParams: { propertySlugs: 'id' },
22
- })
23
- .catch((e) => {
24
- console.error(e);
25
- return null; // Return null if project does not exist
26
- });
27
- return !!project;
28
- }
29
8
  async function cacheProjectItemsByProjectId(projectId) {
30
9
  if (PROJECT_ITEMS_CACHE_BY_PROJECT_ID.has(projectId)) {
31
10
  return; // Already cached
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "3.6.0-alpha-8-alpha.c321203",
2
+ "version": "3.6.0-alpha-8-alpha.53e9604",
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.6.0-alpha-8-alpha.c321203",
3
+ "version": "3.6.0-alpha-8-alpha.53e9604",
4
4
  "description": "VibeIQ's Contrail Platform CLI.",
5
5
  "bin": {
6
6
  "contrail-cli": "./bin/run",