@contrail/cli 3.6.0-alpha-8-alpha.85a73d5 → 3.6.0-alpha.a5acc88

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.
Files changed (84) hide show
  1. package/README.md +26 -181
  2. package/dist/api/types.d.ts +0 -35
  3. package/dist/api/types.js +1 -49
  4. package/dist/auth/login.d.ts +4 -0
  5. package/dist/auth/login.js +115 -52
  6. package/dist/auth/login.spec.js +100 -0
  7. package/dist/auth/sso.d.ts +36 -0
  8. package/dist/auth/sso.js +174 -0
  9. package/dist/auth/sso.spec.js +148 -0
  10. package/dist/basecommand.js +2 -2
  11. package/dist/commands/app/getApiKey.js +2 -2
  12. package/dist/commands/login.d.ts +12 -0
  13. package/dist/commands/login.js +25 -0
  14. package/dist/common.d.ts +1 -4
  15. package/dist/common.js +1 -18
  16. package/dist/helpers/config/config.d.ts +3 -3
  17. package/dist/helpers/config/config.js +3 -3
  18. package/dist/helpers/file-helpers.d.ts +0 -1
  19. package/dist/helpers/file-helpers.js +3 -20
  20. package/dist/logger.js +1 -4
  21. package/node_modules/@contrail/entity-compare/package.json +3 -6
  22. package/node_modules/@contrail/loader/lib/common/conditional-columns.js +1 -1
  23. package/node_modules/@contrail/loader/lib/constants.d.ts +8 -0
  24. package/node_modules/@contrail/loader/lib/constants.js +9 -1
  25. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.d.ts +4 -0
  26. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.js +57 -0
  27. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.spec.js +492 -34
  28. package/node_modules/@contrail/loader/lib/pipeline/validate.js +2 -52
  29. package/node_modules/@contrail/loader/lib/pipeline/validate.spec.js +0 -85
  30. package/node_modules/@contrail/loader/package.json +2 -2
  31. package/node_modules/@contrail/sdk/.github/workflows/publish-to-npm.yml +4 -1
  32. package/node_modules/@contrail/sdk/lib/auth/login.js +1 -1
  33. package/node_modules/@contrail/sdk/lib/config/config.d.ts +0 -3
  34. package/node_modules/@contrail/sdk/lib/config/config.js +7 -13
  35. package/node_modules/@contrail/sdk/lib/core/request.js +2 -6
  36. package/node_modules/@contrail/sdk/lib/entities/entities.client.d.ts +0 -2
  37. package/node_modules/@contrail/sdk/lib/entities/entities.client.js +1 -3
  38. package/node_modules/@contrail/sdk/lib/entities/entity.resource.registry.js +0 -1
  39. package/node_modules/@contrail/sdk/lib/index.d.ts +0 -1
  40. package/node_modules/@contrail/sdk/lib/index.js +0 -1
  41. package/node_modules/@contrail/sdk/package.json +1 -1
  42. package/oclif.manifest.json +50 -449
  43. package/package.json +12 -5
  44. package/dist/commands/entities/create.d.ts +0 -50
  45. package/dist/commands/entities/create.js +0 -633
  46. package/dist/commands/entities/create.spec.js +0 -583
  47. package/dist/commands/entities/delete.d.ts +0 -20
  48. package/dist/commands/entities/delete.js +0 -140
  49. package/dist/commands/entities/get.d.ts +0 -25
  50. package/dist/commands/entities/get.js +0 -269
  51. package/dist/commands/entities/grammar.spec.d.ts +0 -1
  52. package/dist/commands/entities/grammar.spec.js +0 -79
  53. package/dist/commands/entities/output.spec.d.ts +0 -1
  54. package/dist/commands/entities/output.spec.js +0 -72
  55. package/dist/commands/entities/update.d.ts +0 -32
  56. package/dist/commands/entities/update.js +0 -161
  57. package/dist/helpers/entities/assortment-items.d.ts +0 -11
  58. package/dist/helpers/entities/assortment-items.js +0 -76
  59. package/dist/helpers/entities/batchFetch.d.ts +0 -8
  60. package/dist/helpers/entities/batchFetch.js +0 -49
  61. package/dist/helpers/entities/index.d.ts +0 -3
  62. package/dist/helpers/entities/index.js +0 -6
  63. package/dist/helpers/entities/items.d.ts +0 -6
  64. package/dist/helpers/entities/items.js +0 -56
  65. package/dist/helpers/entities/items.spec.d.ts +0 -1
  66. package/dist/helpers/entities/items.spec.js +0 -19
  67. package/dist/helpers/entities/project-items.d.ts +0 -2
  68. package/dist/helpers/entities/project-items.js +0 -44
  69. package/dist/helpers/propertySpecifications/dateRanges.d.ts +0 -34
  70. package/dist/helpers/propertySpecifications/dateRanges.js +0 -83
  71. package/dist/helpers/propertySpecifications/dateRanges.spec.d.ts +0 -1
  72. package/dist/helpers/propertySpecifications/dateRanges.spec.js +0 -91
  73. package/dist/helpers/propertySpecifications/propertySpecifications.d.ts +0 -39
  74. package/dist/helpers/propertySpecifications/propertySpecifications.js +0 -102
  75. package/dist/helpers/propertySpecifications/propertySpecifications.spec.d.ts +0 -1
  76. package/dist/helpers/propertySpecifications/propertySpecifications.spec.js +0 -387
  77. package/dist/logger.spec.d.ts +0 -1
  78. package/dist/logger.spec.js +0 -12
  79. package/node_modules/@contrail/sdk/lib/image-search/image-search.d.ts +0 -34
  80. package/node_modules/@contrail/sdk/lib/image-search/image-search.js +0 -42
  81. package/node_modules/@contrail/sdk/lib/image-search/index.d.ts +0 -1
  82. package/node_modules/@contrail/sdk/lib/image-search/index.js +0 -17
  83. package/node_modules/@contrail/sdk/scripts/replicate-bug.js +0 -69
  84. /package/dist/{commands/entities/create.spec.d.ts → auth/sso.spec.d.ts} +0 -0
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
3
4
  const amazon_cognito_identity_js_1 = require("amazon-cognito-identity-js");
4
5
  const sdk_1 = require("@contrail/sdk");
6
+ const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
5
7
  const config_1 = require("../helpers/config/config");
6
8
  const login_1 = require("./login");
7
9
  const mockAuthenticateUser = jest.fn();
@@ -209,6 +211,104 @@ describe('authUser with stored tokens', () => {
209
211
  expect(mockAuthenticateUser).not.toHaveBeenCalled();
210
212
  });
211
213
  });
214
+ describe('signIn with SSO', () => {
215
+ const originalFetch = global.fetch;
216
+ const originalEmail = process.env.CONTRAIL_CLI_EMAIL;
217
+ const originalPassword = process.env.CONTRAIL_CLI_PASSWORD;
218
+ const DEV_COGNITO_DOMAIN = 'https://dev-vibeiq.auth.us-east-1.amazoncognito.com';
219
+ let fetchMock;
220
+ let promptSpy;
221
+ let consoleLogSpy;
222
+ function pasteCodeFromPrintedSignInUrl() {
223
+ promptSpy.mockImplementation(async () => {
224
+ const printed = consoleLogSpy.mock.calls.map(([message]) => message).join('\n');
225
+ const signInUrl = new URL(printed.match(/https:\/\/\S+oauth2\/authorize\S+/)[0]);
226
+ return { signInCode: `pasted-code#${signInUrl.searchParams.get('state')}` };
227
+ });
228
+ }
229
+ beforeEach(() => {
230
+ jest.clearAllMocks();
231
+ process.env.CONTRAIL_CLI_EMAIL = 'dev@vibeiq.com';
232
+ delete process.env.CONTRAIL_CLI_PASSWORD;
233
+ config_1.getConfig.mockResolvedValue({ apiGateway: DEV_GATEWAY, orgSlug: 'adam-zone-1' });
234
+ sdk_1.getCurrentUser.mockResolvedValue({ id: 'user-1' });
235
+ mockAuthenticateUser.mockImplementation((_details, callbacks) => callbacks.onSuccess({ idToken: { jwtToken: 'cognito-id-token' } }));
236
+ consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined);
237
+ promptSpy = jest.spyOn(inquirer_1.default, 'prompt');
238
+ pasteCodeFromPrintedSignInUrl();
239
+ fetchMock = jest.fn();
240
+ global.fetch = fetchMock;
241
+ });
242
+ afterEach(() => {
243
+ promptSpy.mockRestore();
244
+ consoleLogSpy.mockRestore();
245
+ global.fetch = originalFetch;
246
+ restoreEnv('CONTRAIL_CLI_EMAIL', originalEmail);
247
+ restoreEnv('CONTRAIL_CLI_PASSWORD', originalPassword);
248
+ });
249
+ it('should sign in through the domain identity provider with a pasted code', async () => {
250
+ fetchMock
251
+ .mockResolvedValueOnce(jsonResponse(200, { identityProvider: 'sso-vibeiq-com' }))
252
+ .mockResolvedValueOnce(jsonResponse(200, { access_token: 'cognito-access', refresh_token: 'cognito-refresh' }));
253
+ const context = await (0, login_1.signIn)({ openBrowser: false });
254
+ expect(fetchMock.mock.calls[0][0]).toBe(`${DEV_GATEWAY}/sso-login/domain-check/vibeiq.com`);
255
+ const [tokenUrl, tokenRequest] = fetchMock.mock.calls[1];
256
+ const tokenForm = new URLSearchParams(tokenRequest.body);
257
+ expect(tokenUrl).toBe(`${DEV_COGNITO_DOMAIN}/oauth2/token`);
258
+ expect(tokenForm.get('code')).toBe('pasted-code');
259
+ expect(tokenForm.get('redirect_uri')).toBe('https://login.dev.vibeiq.com/cli');
260
+ expect(context).toEqual({
261
+ apiUserToken: 'cognito-access',
262
+ apiRefreshToken: 'cognito-refresh',
263
+ apiGateway: DEV_GATEWAY,
264
+ orgSlug: 'adam-zone-1',
265
+ });
266
+ expect(config_1.storeConfig).toHaveBeenCalledWith({ ...context, signInMethod: 'sso' });
267
+ });
268
+ it('should reject a pasted code from a different sign-in attempt without saving tokens', async () => {
269
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { identityProvider: 'sso-vibeiq-com' }));
270
+ promptSpy.mockResolvedValue({ signInCode: 'pasted-code#another-state' });
271
+ await expect((0, login_1.signIn)({ openBrowser: false })).rejects.toThrow('That sign-in code is not from this login attempt.');
272
+ expect(config_1.storeConfig).not.toHaveBeenCalled();
273
+ });
274
+ it('should ask for a password when the email domain has no SSO', async () => {
275
+ fetchMock
276
+ .mockResolvedValueOnce(new Response('', { status: 200 }))
277
+ .mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
278
+ promptSpy.mockResolvedValue({ password: 'secret' });
279
+ const context = await (0, login_1.signIn)({ openBrowser: false });
280
+ expect(mockAuthenticateUser).toHaveBeenCalled();
281
+ expect(context.apiUserToken).toBe('vibe-access');
282
+ expect(config_1.storeConfig).toHaveBeenCalledWith({ ...context, signInMethod: 'password' });
283
+ });
284
+ it('should ask for a password when the email domain uses SSO the CLI cannot open', async () => {
285
+ fetchMock
286
+ .mockResolvedValueOnce(jsonResponse(200, { identityProvider: '', url: 'legacy' }))
287
+ .mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
288
+ promptSpy.mockResolvedValue({ password: 'secret' });
289
+ const context = await (0, login_1.signIn)({ openBrowser: false });
290
+ expect(context.apiUserToken).toBe('vibe-access');
291
+ expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('The CLI does not support your SSO provider yet.'));
292
+ });
293
+ it('should refresh a stored SSO token through Cognito instead of the VibeIQ refresh endpoint', async () => {
294
+ config_1.getConfig.mockResolvedValue({
295
+ apiUserToken: 'expired-access',
296
+ apiRefreshToken: 'cognito-refresh',
297
+ apiGateway: DEV_GATEWAY,
298
+ orgSlug: 'adam-zone-1',
299
+ signInMethod: 'sso',
300
+ });
301
+ sdk_1.getCurrentUser
302
+ .mockRejectedValueOnce(new Error('Failed to fetch current user. Unauthorized'))
303
+ .mockResolvedValueOnce({ id: 'user-1' });
304
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { access_token: 'refreshed-access' }));
305
+ const context = await (0, login_1.authUser)();
306
+ const [tokenUrl, tokenRequest] = fetchMock.mock.calls[0];
307
+ expect(tokenUrl).toBe(`${DEV_COGNITO_DOMAIN}/oauth2/token`);
308
+ expect(new URLSearchParams(tokenRequest.body).get('refresh_token')).toBe('cognito-refresh');
309
+ expect(context.apiUserToken).toBe('refreshed-access');
310
+ });
311
+ });
212
312
  describe('getVersionFromPackageJson', () => {
213
313
  it('should return the version value from package.json', () => {
214
314
  const version = (0, login_1.getVersionFromPackageJson)();
@@ -0,0 +1,36 @@
1
+ /// <reference types="node" />
2
+ export declare const LOOPBACK_PORT = 7731;
3
+ export declare const LOOPBACK_CALLBACK_URL: string;
4
+ export interface SsoClient {
5
+ domain: string;
6
+ clientId: string;
7
+ }
8
+ export interface SsoTokens {
9
+ accessToken: string;
10
+ refreshToken: string;
11
+ }
12
+ export interface PkceChallenge {
13
+ verifier: string;
14
+ challenge: string;
15
+ state: string;
16
+ }
17
+ export type SsoDomainCheck = {
18
+ kind: 'cognito';
19
+ identityProvider: string;
20
+ } | {
21
+ kind: 'legacy';
22
+ } | {
23
+ kind: 'none';
24
+ };
25
+ export declare function fetchSsoDomainCheck(email: string, apiGateway: string): Promise<SsoDomainCheck>;
26
+ export declare function createPkceChallenge(): PkceChallenge;
27
+ export declare function buildAuthorizeUrl(client: SsoClient, identityProvider: string, redirectUri: string, pkce: PkceChallenge): string;
28
+ export declare function parsePastedSignInCode(pasted: string, expectedState: string): string;
29
+ export interface LoopbackListener {
30
+ code: Promise<string>;
31
+ }
32
+ export declare function listenForLoopbackCode(expectedState: string): Promise<LoopbackListener>;
33
+ export declare function canOpenBrowser(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): boolean;
34
+ export declare function openBrowser(url: string): Promise<void>;
35
+ export declare function exchangeCodeForTokens(client: SsoClient, code: string, redirectUri: string, verifier: string): Promise<SsoTokens>;
36
+ export declare function refreshSsoAccessToken(client: SsoClient, refreshToken: string): Promise<string>;
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.refreshSsoAccessToken = exports.exchangeCodeForTokens = exports.openBrowser = exports.canOpenBrowser = exports.listenForLoopbackCode = exports.parsePastedSignInCode = exports.buildAuthorizeUrl = exports.createPkceChallenge = exports.fetchSsoDomainCheck = exports.LOOPBACK_CALLBACK_URL = exports.LOOPBACK_PORT = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const node_http_1 = require("node:http");
6
+ const node_child_process_1 = require("node:child_process");
7
+ exports.LOOPBACK_PORT = 7731;
8
+ exports.LOOPBACK_CALLBACK_URL = `http://localhost:${exports.LOOPBACK_PORT}/callback`;
9
+ const BROWSER_SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000;
10
+ const OAUTH_SCOPES = ['openid', 'email', 'api.vibeiq.default/read', 'api.vibeiq.default/write'];
11
+ async function fetchSsoDomainCheck(email, apiGateway) {
12
+ const domain = email.split('@').pop().toLowerCase();
13
+ const response = await fetch(`${apiGateway}/sso-login/domain-check/${encodeURIComponent(domain)}`);
14
+ if (!response.ok) {
15
+ throw new Error(`SSO lookup for ${domain} failed (${response.status}).`);
16
+ }
17
+ const body = await response.text();
18
+ if (!body) {
19
+ return { kind: 'none' };
20
+ }
21
+ const { identityProvider } = JSON.parse(body);
22
+ return identityProvider ? { kind: 'cognito', identityProvider } : { kind: 'legacy' };
23
+ }
24
+ exports.fetchSsoDomainCheck = fetchSsoDomainCheck;
25
+ function createPkceChallenge() {
26
+ const verifier = (0, node_crypto_1.randomBytes)(32).toString('base64url');
27
+ return {
28
+ verifier,
29
+ challenge: (0, node_crypto_1.createHash)('sha256').update(verifier).digest('base64url'),
30
+ state: (0, node_crypto_1.randomBytes)(16).toString('base64url'),
31
+ };
32
+ }
33
+ exports.createPkceChallenge = createPkceChallenge;
34
+ function buildAuthorizeUrl(client, identityProvider, redirectUri, pkce) {
35
+ const params = new URLSearchParams({
36
+ response_type: 'code',
37
+ client_id: client.clientId,
38
+ redirect_uri: redirectUri,
39
+ scope: OAUTH_SCOPES.join(' '),
40
+ identity_provider: identityProvider,
41
+ code_challenge: pkce.challenge,
42
+ code_challenge_method: 'S256',
43
+ state: pkce.state,
44
+ });
45
+ return `${client.domain}/oauth2/authorize?${params}`;
46
+ }
47
+ exports.buildAuthorizeUrl = buildAuthorizeUrl;
48
+ function parsePastedSignInCode(pasted, expectedState) {
49
+ const [code, state] = pasted.trim().split('#');
50
+ if (!code || state !== expectedState) {
51
+ throw new Error('That sign-in code is not from this login attempt. Run the command again.');
52
+ }
53
+ return code;
54
+ }
55
+ exports.parsePastedSignInCode = parsePastedSignInCode;
56
+ function listenForLoopbackCode(expectedState) {
57
+ let resolveCode;
58
+ let rejectCode;
59
+ const code = new Promise((resolve, reject) => {
60
+ resolveCode = resolve;
61
+ rejectCode = reject;
62
+ });
63
+ const server = (0, node_http_1.createServer)((request, response) => {
64
+ const url = new URL(request.url, exports.LOOPBACK_CALLBACK_URL);
65
+ if (url.pathname !== '/callback') {
66
+ response.writeHead(404).end();
67
+ return;
68
+ }
69
+ if (url.searchParams.get('state') !== expectedState) {
70
+ response.writeHead(400, { 'Content-Type': 'text/plain' }).end('Unknown sign-in attempt.');
71
+ return;
72
+ }
73
+ const error = url.searchParams.get('error_description') ?? url.searchParams.get('error');
74
+ const receivedCode = url.searchParams.get('code');
75
+ const signedIn = !error && Boolean(receivedCode);
76
+ const page = signedIn
77
+ ? 'Sign-in received. Return to your terminal.'
78
+ : 'Sign-in failed. Return to your terminal.';
79
+ response
80
+ .writeHead(signedIn ? 200 : 400, { 'Content-Type': 'text/plain', Connection: 'close' })
81
+ .end(page, () => stopListening(request.socket, () => {
82
+ if (error) {
83
+ rejectCode(new Error(`SSO sign-in failed: ${error}`));
84
+ }
85
+ else if (!signedIn) {
86
+ rejectCode(new Error('SSO sign-in returned an unexpected response. Run the command again.'));
87
+ }
88
+ else {
89
+ resolveCode(receivedCode);
90
+ }
91
+ }));
92
+ });
93
+ const openSockets = new Set();
94
+ server.on('connection', (socket) => {
95
+ openSockets.add(socket);
96
+ socket.once('close', () => openSockets.delete(socket));
97
+ });
98
+ const timeout = setTimeout(() => stopListening(undefined, () => rejectCode(new Error('Timed out waiting for the browser sign-in.'))), BROWSER_SIGN_IN_TIMEOUT_MS);
99
+ function stopListening(respondingSocket, settle) {
100
+ clearTimeout(timeout);
101
+ server.close();
102
+ openSockets.forEach((socket) => socket !== respondingSocket && socket.destroy());
103
+ settle();
104
+ }
105
+ return new Promise((resolve, reject) => {
106
+ server.once('error', (error) => {
107
+ clearTimeout(timeout);
108
+ reject(error.code === 'EADDRINUSE'
109
+ ? new Error(`Port ${exports.LOOPBACK_PORT} is in use. Run contrail login --no-browser instead.`)
110
+ : error);
111
+ });
112
+ server.listen(exports.LOOPBACK_PORT, 'localhost', () => resolve({ code }));
113
+ });
114
+ }
115
+ exports.listenForLoopbackCode = listenForLoopbackCode;
116
+ function canOpenBrowser(env = process.env, platform = process.platform) {
117
+ const isRemoteShell = Boolean(env.SSH_CONNECTION || env.SSH_TTY);
118
+ const hasLinuxDisplay = Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
119
+ return !isRemoteShell && (platform !== 'linux' || hasLinuxDisplay);
120
+ }
121
+ exports.canOpenBrowser = canOpenBrowser;
122
+ function openBrowser(url) {
123
+ const [command, args] = buildOpenBrowserCommand(url, process.platform);
124
+ return new Promise((resolve, reject) => {
125
+ const browserProcess = (0, node_child_process_1.spawn)(command, args, { stdio: 'ignore', detached: true });
126
+ browserProcess.once('spawn', () => {
127
+ browserProcess.unref();
128
+ resolve();
129
+ });
130
+ browserProcess.once('error', reject);
131
+ });
132
+ }
133
+ exports.openBrowser = openBrowser;
134
+ function buildOpenBrowserCommand(url, platform) {
135
+ if (platform === 'darwin') {
136
+ return ['open', [url]];
137
+ }
138
+ if (platform === 'win32') {
139
+ return ['rundll32', ['url.dll,FileProtocolHandler', url]];
140
+ }
141
+ return ['xdg-open', [url]];
142
+ }
143
+ async function exchangeCodeForTokens(client, code, redirectUri, verifier) {
144
+ const tokens = await postToTokenEndpoint(client, {
145
+ grant_type: 'authorization_code',
146
+ client_id: client.clientId,
147
+ code,
148
+ redirect_uri: redirectUri,
149
+ code_verifier: verifier,
150
+ });
151
+ return { accessToken: tokens.access_token, refreshToken: tokens.refresh_token };
152
+ }
153
+ exports.exchangeCodeForTokens = exchangeCodeForTokens;
154
+ async function refreshSsoAccessToken(client, refreshToken) {
155
+ const tokens = await postToTokenEndpoint(client, {
156
+ grant_type: 'refresh_token',
157
+ client_id: client.clientId,
158
+ refresh_token: refreshToken,
159
+ });
160
+ return tokens.access_token;
161
+ }
162
+ exports.refreshSsoAccessToken = refreshSsoAccessToken;
163
+ async function postToTokenEndpoint(client, form) {
164
+ const response = await fetch(`${client.domain}/oauth2/token`, {
165
+ method: 'POST',
166
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
167
+ body: new URLSearchParams(form),
168
+ });
169
+ const body = await response.json();
170
+ if (!response.ok) {
171
+ throw new Error(`SSO token request failed (${response.status} ${body.error}).`);
172
+ }
173
+ return body;
174
+ }
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const node_crypto_1 = require("node:crypto");
4
+ const node_net_1 = require("node:net");
5
+ const sso_1 = require("./sso");
6
+ const ssoClient = {
7
+ domain: 'https://dev-vibeiq.auth.us-east-1.amazoncognito.com',
8
+ clientId: 'cli-client',
9
+ };
10
+ describe('createPkceChallenge', () => {
11
+ it('should derive the challenge as the base64url SHA-256 of the verifier', () => {
12
+ const pkce = (0, sso_1.createPkceChallenge)();
13
+ expect(pkce.challenge).toBe((0, node_crypto_1.createHash)('sha256').update(pkce.verifier).digest('base64url'));
14
+ });
15
+ });
16
+ describe('buildAuthorizeUrl', () => {
17
+ it('should send the user straight to their identity provider with a PKCE challenge', () => {
18
+ const url = new URL((0, sso_1.buildAuthorizeUrl)(ssoClient, 'sso-vibeiq-com', sso_1.LOOPBACK_CALLBACK_URL, {
19
+ verifier: 'verifier',
20
+ challenge: 'challenge',
21
+ state: 'state',
22
+ }));
23
+ expect(url.origin + url.pathname).toBe(`${ssoClient.domain}/oauth2/authorize`);
24
+ expect(Object.fromEntries(url.searchParams)).toEqual({
25
+ response_type: 'code',
26
+ client_id: 'cli-client',
27
+ redirect_uri: 'http://localhost:7731/callback',
28
+ scope: 'openid email api.vibeiq.default/read api.vibeiq.default/write',
29
+ identity_provider: 'sso-vibeiq-com',
30
+ code_challenge: 'challenge',
31
+ code_challenge_method: 'S256',
32
+ state: 'state',
33
+ });
34
+ });
35
+ });
36
+ describe('parsePastedSignInCode', () => {
37
+ it('should return the code when the pasted state matches this attempt', () => {
38
+ expect((0, sso_1.parsePastedSignInCode)(' the-code#the-state \n', 'the-state')).toBe('the-code');
39
+ });
40
+ it('should reject a code from another attempt', () => {
41
+ expect(() => (0, sso_1.parsePastedSignInCode)('the-code#other-state', 'the-state')).toThrow('That sign-in code is not from this login attempt.');
42
+ });
43
+ it('should reject a code pasted without its state', () => {
44
+ expect(() => (0, sso_1.parsePastedSignInCode)('the-code', 'the-state')).toThrow('That sign-in code is not from this login attempt.');
45
+ });
46
+ });
47
+ describe('canOpenBrowser', () => {
48
+ it('should open a browser on a local Mac', () => {
49
+ expect((0, sso_1.canOpenBrowser)({}, 'darwin')).toBe(true);
50
+ });
51
+ it('should not open a browser over SSH', () => {
52
+ expect((0, sso_1.canOpenBrowser)({ SSH_CONNECTION: '10.0.0.1 22 10.0.0.2 22' }, 'darwin')).toBe(false);
53
+ });
54
+ it('should not open a browser on Linux without a display', () => {
55
+ expect((0, sso_1.canOpenBrowser)({}, 'linux')).toBe(false);
56
+ });
57
+ it('should open a browser on a Linux desktop', () => {
58
+ expect((0, sso_1.canOpenBrowser)({ WAYLAND_DISPLAY: 'wayland-0' }, 'linux')).toBe(true);
59
+ });
60
+ });
61
+ describe('fetchSsoDomainCheck', () => {
62
+ const originalFetch = global.fetch;
63
+ afterEach(() => {
64
+ global.fetch = originalFetch;
65
+ });
66
+ function stubDomainCheckFetch(body, status = 200) {
67
+ global.fetch = jest.fn().mockResolvedValue(new Response(body, { status }));
68
+ }
69
+ it('should name the Cognito identity provider for an SSO domain', async () => {
70
+ stubDomainCheckFetch(JSON.stringify({ identityProvider: 'sso-vibeiq-com' }));
71
+ await expect((0, sso_1.fetchSsoDomainCheck)('Dev@VibeIQ.com', 'https://api')).resolves.toEqual({
72
+ kind: 'cognito',
73
+ identityProvider: 'sso-vibeiq-com',
74
+ });
75
+ expect(global.fetch).toHaveBeenCalledWith('https://api/sso-login/domain-check/vibeiq.com');
76
+ });
77
+ it('should report a legacy SSO domain', async () => {
78
+ stubDomainCheckFetch(JSON.stringify({ identityProvider: '', url: 'https://api/sso-login/login/acme.com' }));
79
+ await expect((0, sso_1.fetchSsoDomainCheck)('dev@acme.com', 'https://api')).resolves.toEqual({
80
+ kind: 'legacy',
81
+ });
82
+ });
83
+ it('should report no SSO for an empty response', async () => {
84
+ stubDomainCheckFetch('');
85
+ await expect((0, sso_1.fetchSsoDomainCheck)('dev@example.com', 'https://api')).resolves.toEqual({
86
+ kind: 'none',
87
+ });
88
+ });
89
+ it('should fail when the lookup fails', async () => {
90
+ stubDomainCheckFetch('{}', 502);
91
+ await expect((0, sso_1.fetchSsoDomainCheck)('dev@example.com', 'https://api')).rejects.toThrow('SSO lookup for example.com failed (502).');
92
+ });
93
+ });
94
+ describe('listenForLoopbackCode', () => {
95
+ it('should resolve with the code the browser redirects back with', async () => {
96
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
97
+ const response = await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
98
+ expect(response.status).toBe(200);
99
+ await expect(listener.code).resolves.toBe('the-code');
100
+ });
101
+ it('should keep waiting for this attempt after a redirect from another attempt', async () => {
102
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
103
+ const staleResponse = await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=old-code&state=old-state`);
104
+ await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
105
+ expect(staleResponse.status).toBe(400);
106
+ await expect(listener.code).resolves.toBe('the-code');
107
+ });
108
+ it('should reject a redirect for this attempt that carries no code', async () => {
109
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
110
+ const rejection = expect(listener.code).rejects.toThrow('SSO sign-in returned an unexpected response.');
111
+ const response = await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?state=the-state`);
112
+ expect(response.status).toBe(400);
113
+ await rejection;
114
+ });
115
+ it('should reject when the identity provider reports an error', async () => {
116
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
117
+ const rejection = expect(listener.code).rejects.toThrow('SSO sign-in failed: User cancelled');
118
+ await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?error=access_denied&error_description=User%20cancelled&state=the-state`);
119
+ await rejection;
120
+ });
121
+ it('should close idle browser connections once the code arrives', async () => {
122
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
123
+ const idleConnection = (0, node_net_1.connect)(7731, 'localhost');
124
+ await new Promise((resolve) => idleConnection.once('connect', resolve));
125
+ const idleConnectionClosed = new Promise((resolve) => idleConnection.once('close', resolve));
126
+ await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
127
+ await expect(listener.code).resolves.toBe('the-code');
128
+ await expect(idleConnectionClosed).resolves.toBe(false);
129
+ });
130
+ it('should tell the user to paste a code instead when the port is taken', async () => {
131
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
132
+ await expect((0, sso_1.listenForLoopbackCode)('another-state')).rejects.toThrow('Port 7731 is in use. Run contrail login --no-browser instead.');
133
+ await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
134
+ await listener.code;
135
+ });
136
+ });
137
+ describe('exchangeCodeForTokens', () => {
138
+ const originalFetch = global.fetch;
139
+ afterEach(() => {
140
+ global.fetch = originalFetch;
141
+ });
142
+ it('should name the Cognito error when the exchange is refused', async () => {
143
+ global.fetch = jest
144
+ .fn()
145
+ .mockResolvedValue(new Response(JSON.stringify({ error: 'invalid_grant' }), { status: 400 }));
146
+ await expect((0, sso_1.exchangeCodeForTokens)(ssoClient, 'the-code', sso_1.LOOPBACK_CALLBACK_URL, 'verifier')).rejects.toThrow('SSO token request failed (400 invalid_grant).');
147
+ });
148
+ });
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BaseCommand = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const core_1 = require("@oclif/core");
6
- const common_1 = require("./common");
7
6
  const logger_1 = tslib_1.__importDefault(require("./logger"));
7
+ const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
8
8
  const config_1 = require("./helpers/config/config");
9
9
  const lodash_1 = require("lodash");
10
10
  const login_1 = require("./auth/login");
@@ -73,7 +73,7 @@ class BaseCommand extends core_1.Command {
73
73
  choices: ['yes', 'no'],
74
74
  default: 'no',
75
75
  });
76
- const { confirm } = await (0, common_1.promptOnStderr)(questions);
76
+ const { confirm } = await inquirer_1.default.prompt(questions);
77
77
  if (confirm === 'no') {
78
78
  logger_1.default.info('Please use `contrail config use` command to choose the configuration or `contrail config set --environment=prod` to set different environment.');
79
79
  this.exit(1);
@@ -35,7 +35,7 @@ class GetAPIKeyApp extends basecommand_1.BaseCommand {
35
35
  },
36
36
  ];
37
37
  const answers = await inquirer_1.default.prompt(questions);
38
- this.log(`App API key: (app:${answers.appApiKey})`);
38
+ logger_1.default.info(`App API key: (app:${answers.appApiKey})`);
39
39
  }
40
40
  else {
41
41
  const appFound = installedApps.find((x) => x.app.identifier === this.flags.appIdentifier);
@@ -43,7 +43,7 @@ class GetAPIKeyApp extends basecommand_1.BaseCommand {
43
43
  logger_1.default.info('You do not have such an app installed');
44
44
  return;
45
45
  }
46
- this.log(`App API key: (app:${appFound.apiKey.apiKey})`);
46
+ logger_1.default.info(`App API key: (app:${appFound.apiKey.apiKey})`);
47
47
  }
48
48
  }
49
49
  }
@@ -0,0 +1,12 @@
1
+ import { BaseCommand } from '../basecommand';
2
+ export default class Login extends BaseCommand {
3
+ static description: string;
4
+ skipConfirmEnv: boolean;
5
+ static examples: string[];
6
+ static flags: {
7
+ browser: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
8
+ alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
9
+ logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
10
+ };
11
+ run(): Promise<void>;
12
+ }
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const core_1 = require("@oclif/core");
5
+ const basecommand_1 = require("../basecommand");
6
+ const login_1 = require("../auth/login");
7
+ const logger_1 = tslib_1.__importDefault(require("../logger"));
8
+ class Login extends basecommand_1.BaseCommand {
9
+ static description = 'Sign in to VibeIQ with SSO or your email and password';
10
+ skipConfirmEnv = true;
11
+ static examples = ['$ contrail login', '$ contrail login --no-browser'];
12
+ static flags = {
13
+ ...basecommand_1.BaseCommand.baseFlags,
14
+ browser: core_1.Flags.boolean({
15
+ description: 'Open a browser for SSO. Use --no-browser to paste a sign-in code instead.',
16
+ default: true,
17
+ allowNo: true,
18
+ }),
19
+ };
20
+ async run() {
21
+ const context = await (0, login_1.signIn)({ openBrowser: this.flags.browser });
22
+ logger_1.default.info(`Signed in to ${context.orgSlug}.`);
23
+ }
24
+ }
25
+ exports.default = Login;
package/dist/common.d.ts CHANGED
@@ -1,7 +1,4 @@
1
1
  /// <reference types="node" />
2
2
  export declare function getSeparatorByPlatform(): string;
3
3
  export declare function delay(ms: number): Promise<NodeJS.Timeout>;
4
- export declare function removeSlash(string: string): string;
5
- export declare function routeConsoleLogToStderr(): void;
6
- export declare function sdkErrorMessage(reason: any): string;
7
- export declare const promptOnStderr: any;
4
+ export declare function removeSlash(string: any): string;
package/dist/common.js CHANGED
@@ -1,8 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.promptOnStderr = exports.sdkErrorMessage = exports.routeConsoleLogToStderr = exports.removeSlash = exports.delay = exports.getSeparatorByPlatform = void 0;
4
- const tslib_1 = require("tslib");
5
- const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
3
+ exports.removeSlash = exports.delay = exports.getSeparatorByPlatform = void 0;
6
4
  function getSeparatorByPlatform() {
7
5
  const isWin = process.platform === 'win32';
8
6
  const separator = isWin ? '\\' : '/';
@@ -18,18 +16,3 @@ function removeSlash(string) {
18
16
  return string.replace(re, '-');
19
17
  }
20
18
  exports.removeSlash = removeSlash;
21
- // The SDK and auth flow print request logs and token messages via bare
22
- // console.log. A command whose stdout is a data contract must route those to
23
- // stderr before any of that code runs.
24
- function routeConsoleLogToStderr() {
25
- console.log = (...args) => console.error(...args);
26
- }
27
- exports.routeConsoleLogToStderr = routeConsoleLogToStderr;
28
- // SDK errors can carry an empty message with the response body in details
29
- function sdkErrorMessage(reason) {
30
- return reason?.message || reason?.details || String(reason);
31
- }
32
- exports.sdkErrorMessage = sdkErrorMessage;
33
- // inquirer renders prompt UI to its output stream directly, bypassing the
34
- // console.log redirect; stdout must stay data-only
35
- exports.promptOnStderr = inquirer_1.default.createPromptModule({ output: process.stderr });
@@ -9,10 +9,10 @@ export declare function readVibeIQConfig(): Promise<any>;
9
9
  export declare function writeVibeIQConfig(config: any): Promise<void>;
10
10
  export declare function storeVibeIQConfig(incomingConfig: any): Promise<void>;
11
11
  export declare function createConfig(fileName: any): Promise<void>;
12
- export declare function writeConfig(config: any, configName?: string | null): Promise<void>;
12
+ export declare function writeConfig(config: any, configName?: string): Promise<void>;
13
13
  export declare function getConfig(): Promise<any>;
14
- export declare function storeConfig(incomingConfig: any, configName?: string | null, merge?: boolean): Promise<void>;
14
+ export declare function storeConfig(incomingConfig: any, configName?: string, merge?: boolean): Promise<void>;
15
15
  export declare function getConfigFiles(): Promise<any>;
16
16
  export declare function getConfigContent(fileName: string): Promise<any>;
17
- export declare function validateEnvironments(envName?: string | null): Promise<any>;
17
+ export declare function validateEnvironments(envName?: any): Promise<any>;
18
18
  export declare function checkTelemetry(cliVersion: string): Promise<void>;
@@ -46,13 +46,13 @@ exports.initializeVibeIQConfig = initializeVibeIQConfig;
46
46
  async function readVibeIQConfig() {
47
47
  let fileContent;
48
48
  try {
49
- fileContent = (await node_fs_1.promises.readFile(configFileLocation)).toString();
49
+ fileContent = await (await node_fs_1.promises.readFile(configFileLocation)).toString();
50
50
  }
51
51
  catch {
52
52
  logger_1.default.debug(`failed to open config file (${configFileLocation}) for reading.`);
53
53
  logger_1.default.debug('trying to initialize config file');
54
54
  await initializeVibeIQConfig();
55
- fileContent = (await node_fs_1.promises.readFile(configFileLocation)).toString();
55
+ fileContent = await (await node_fs_1.promises.readFile(configFileLocation)).toString();
56
56
  }
57
57
  try {
58
58
  return JSON.parse(fileContent);
@@ -165,7 +165,7 @@ async function getConfigContent(fileName) {
165
165
  return JSON.parse(fileContent);
166
166
  }
167
167
  catch (error) {
168
- logger_1.default.error(`Failed to open/parse config file (${fileName}) might be malformed or not found. Path: ${configFilePath}, error: ${error}`);
168
+ logger_1.default.error(`Failed to open/parse config file (${fileName}) might be malformed or not found.`);
169
169
  }
170
170
  }
171
171
  exports.getConfigContent = getConfigContent;
@@ -1,5 +1,4 @@
1
1
  export declare function safeFileOverwrite(fileLocation: string, overwrite: boolean): Promise<boolean>;
2
2
  export declare function parseCSVData(data: string): any;
3
- export declare function parseFileAsJsonArray(fileName: string): any[];
4
3
  export declare function saveData(data: any, fileLocation: string, overwrite: boolean): Promise<void>;
5
4
  export declare function loadData(fileLocation: string): any;