@contrail/cli 3.6.0-alpha-8-alpha.82b70ea → 3.6.0-alpha.5ecc188

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 (88) 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 +136 -56
  6. package/dist/auth/login.spec.js +117 -3
  7. package/dist/auth/sign-in-error.d.ts +7 -0
  8. package/dist/auth/sign-in-error.js +24 -0
  9. package/dist/auth/sign-in-error.spec.js +22 -0
  10. package/dist/auth/sso.d.ts +38 -0
  11. package/dist/auth/sso.js +184 -0
  12. package/dist/auth/sso.spec.js +191 -0
  13. package/dist/basecommand.d.ts +3 -0
  14. package/dist/basecommand.js +10 -3
  15. package/dist/commands/app/getApiKey.js +2 -2
  16. package/dist/commands/login.d.ts +12 -0
  17. package/dist/commands/login.js +25 -0
  18. package/dist/common.d.ts +1 -4
  19. package/dist/common.js +1 -18
  20. package/dist/helpers/config/config.d.ts +3 -3
  21. package/dist/helpers/config/config.js +3 -3
  22. package/dist/helpers/file-helpers.d.ts +0 -1
  23. package/dist/helpers/file-helpers.js +3 -20
  24. package/dist/logger.js +1 -4
  25. package/node_modules/@contrail/entity-compare/package.json +3 -6
  26. package/node_modules/@contrail/loader/lib/common/conditional-columns.js +1 -1
  27. package/node_modules/@contrail/loader/lib/constants.d.ts +8 -0
  28. package/node_modules/@contrail/loader/lib/constants.js +9 -1
  29. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.d.ts +4 -0
  30. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.js +57 -0
  31. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.spec.js +492 -34
  32. package/node_modules/@contrail/loader/lib/pipeline/validate.js +2 -52
  33. package/node_modules/@contrail/loader/lib/pipeline/validate.spec.js +0 -85
  34. package/node_modules/@contrail/loader/package.json +2 -2
  35. package/node_modules/@contrail/sdk/.github/workflows/publish-to-npm.yml +4 -1
  36. package/node_modules/@contrail/sdk/lib/auth/login.js +1 -1
  37. package/node_modules/@contrail/sdk/lib/config/config.d.ts +0 -3
  38. package/node_modules/@contrail/sdk/lib/config/config.js +7 -13
  39. package/node_modules/@contrail/sdk/lib/core/request.js +2 -6
  40. package/node_modules/@contrail/sdk/lib/entities/entities.client.d.ts +0 -2
  41. package/node_modules/@contrail/sdk/lib/entities/entities.client.js +1 -3
  42. package/node_modules/@contrail/sdk/lib/entities/entity.resource.registry.js +0 -1
  43. package/node_modules/@contrail/sdk/lib/index.d.ts +0 -1
  44. package/node_modules/@contrail/sdk/lib/index.js +0 -1
  45. package/node_modules/@contrail/sdk/package.json +1 -1
  46. package/oclif.manifest.json +50 -449
  47. package/package.json +12 -5
  48. package/dist/commands/entities/create.d.ts +0 -50
  49. package/dist/commands/entities/create.js +0 -640
  50. package/dist/commands/entities/create.spec.js +0 -583
  51. package/dist/commands/entities/delete.d.ts +0 -20
  52. package/dist/commands/entities/delete.js +0 -140
  53. package/dist/commands/entities/get.d.ts +0 -25
  54. package/dist/commands/entities/get.js +0 -276
  55. package/dist/commands/entities/grammar.spec.js +0 -79
  56. package/dist/commands/entities/output.spec.d.ts +0 -1
  57. package/dist/commands/entities/output.spec.js +0 -72
  58. package/dist/commands/entities/update.d.ts +0 -32
  59. package/dist/commands/entities/update.js +0 -161
  60. package/dist/helpers/entities/assortment-items.d.ts +0 -11
  61. package/dist/helpers/entities/assortment-items.js +0 -76
  62. package/dist/helpers/entities/batchFetch.d.ts +0 -8
  63. package/dist/helpers/entities/batchFetch.js +0 -49
  64. package/dist/helpers/entities/index.d.ts +0 -3
  65. package/dist/helpers/entities/index.js +0 -6
  66. package/dist/helpers/entities/items.d.ts +0 -8
  67. package/dist/helpers/entities/items.js +0 -88
  68. package/dist/helpers/entities/items.spec.d.ts +0 -1
  69. package/dist/helpers/entities/items.spec.js +0 -19
  70. package/dist/helpers/entities/project-items.d.ts +0 -2
  71. package/dist/helpers/entities/project-items.js +0 -44
  72. package/dist/helpers/propertySpecifications/dateRanges.d.ts +0 -34
  73. package/dist/helpers/propertySpecifications/dateRanges.js +0 -83
  74. package/dist/helpers/propertySpecifications/dateRanges.spec.d.ts +0 -1
  75. package/dist/helpers/propertySpecifications/dateRanges.spec.js +0 -91
  76. package/dist/helpers/propertySpecifications/propertySpecifications.d.ts +0 -40
  77. package/dist/helpers/propertySpecifications/propertySpecifications.js +0 -104
  78. package/dist/helpers/propertySpecifications/propertySpecifications.spec.d.ts +0 -1
  79. package/dist/helpers/propertySpecifications/propertySpecifications.spec.js +0 -387
  80. package/dist/logger.spec.d.ts +0 -1
  81. package/dist/logger.spec.js +0 -12
  82. package/node_modules/@contrail/sdk/lib/image-search/image-search.d.ts +0 -34
  83. package/node_modules/@contrail/sdk/lib/image-search/image-search.js +0 -42
  84. package/node_modules/@contrail/sdk/lib/image-search/index.d.ts +0 -1
  85. package/node_modules/@contrail/sdk/lib/image-search/index.js +0 -17
  86. package/node_modules/@contrail/sdk/scripts/replicate-bug.js +0 -69
  87. /package/dist/{commands/entities/create.spec.d.ts → auth/sign-in-error.spec.d.ts} +0 -0
  88. /package/dist/{commands/entities/grammar.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();
@@ -101,14 +103,17 @@ describe('authUser with email and password', () => {
101
103
  apiGateway: 'api.dev.vibeiq.com/dev/api',
102
104
  orgSlug: 'adam-zone-1',
103
105
  });
104
- await expect((0, login_1.authUser)()).rejects.toThrow('No Cognito user pool is known for api.dev.vibeiq.com/dev/api.');
106
+ await expect((0, login_1.authUser)()).rejects.toMatchObject({
107
+ code: 'ENVIRONMENT_NOT_CONFIGURED',
108
+ details: { apiGateway: 'api.dev.vibeiq.com/dev/api' },
109
+ });
105
110
  });
106
111
  it('should fail without saving tokens when no pool is known for the environment', async () => {
107
112
  config_1.getConfig.mockResolvedValue({
108
113
  apiGateway: 'http://localhost:3000/api',
109
114
  orgSlug: 'adam-zone-1',
110
115
  });
111
- await expect((0, login_1.authUser)()).rejects.toThrow('No Cognito user pool is known for http://localhost:3000/api.');
116
+ await expect((0, login_1.authUser)()).rejects.toMatchObject({ code: 'ENVIRONMENT_NOT_CONFIGURED' });
112
117
  expect(config_1.storeConfig).not.toHaveBeenCalled();
113
118
  });
114
119
  it('should tell the user to update the CLI when its Cognito client or pool no longer exists', async () => {
@@ -169,7 +174,7 @@ describe('authUser with stored tokens', () => {
169
174
  const context = await (0, login_1.authUser)();
170
175
  expect(fetchMock).toHaveBeenCalledWith(`${DEV_GATEWAY}/auth/jwt_refresh/`, expect.objectContaining({ body: JSON.stringify({ refreshToken: 'stored-refresh' }) }));
171
176
  expect(context).toEqual({ ...storedConfig, apiUserToken: 'refreshed-access' });
172
- expect(config_1.storeConfig).toHaveBeenCalledWith(context);
177
+ expect(config_1.storeConfig).toHaveBeenCalledWith({ ...context, signInMethod: 'password' });
173
178
  });
174
179
  it('should keep a still-valid access token without refreshing it', async () => {
175
180
  acceptedTokens = ['expired-access'];
@@ -209,6 +214,115 @@ describe('authUser with stored tokens', () => {
209
214
  expect(mockAuthenticateUser).not.toHaveBeenCalled();
210
215
  });
211
216
  });
217
+ describe('signIn with SSO', () => {
218
+ const originalFetch = global.fetch;
219
+ const originalEmail = process.env.CONTRAIL_CLI_EMAIL;
220
+ const originalPassword = process.env.CONTRAIL_CLI_PASSWORD;
221
+ const DEV_COGNITO_DOMAIN = 'https://dev-vibeiq.auth.us-east-1.amazoncognito.com';
222
+ let fetchMock;
223
+ let promptSpy;
224
+ let consoleLogSpy;
225
+ function pasteCodeFromPrintedSignInUrl() {
226
+ promptSpy.mockImplementation(async () => {
227
+ const printedOutput = consoleLogSpy.mock.calls.map(([message]) => message).join('\n');
228
+ const signInUrl = new URL(printedOutput.match(/https:\/\/\S+oauth2\/authorize\S+/)[0]);
229
+ return { signInCode: `pasted-code#${signInUrl.searchParams.get('state')}` };
230
+ });
231
+ }
232
+ beforeEach(() => {
233
+ jest.clearAllMocks();
234
+ process.env.CONTRAIL_CLI_EMAIL = 'dev@vibeiq.com';
235
+ delete process.env.CONTRAIL_CLI_PASSWORD;
236
+ config_1.getConfig.mockResolvedValue({ apiGateway: DEV_GATEWAY, orgSlug: 'adam-zone-1' });
237
+ sdk_1.getCurrentUser.mockResolvedValue({ id: 'user-1' });
238
+ mockAuthenticateUser.mockImplementation((_details, callbacks) => callbacks.onSuccess({ idToken: { jwtToken: 'cognito-id-token' } }));
239
+ consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined);
240
+ promptSpy = jest.spyOn(inquirer_1.default, 'prompt');
241
+ pasteCodeFromPrintedSignInUrl();
242
+ fetchMock = jest.fn();
243
+ global.fetch = fetchMock;
244
+ });
245
+ afterEach(() => {
246
+ promptSpy.mockRestore();
247
+ consoleLogSpy.mockRestore();
248
+ global.fetch = originalFetch;
249
+ restoreEnv('CONTRAIL_CLI_EMAIL', originalEmail);
250
+ restoreEnv('CONTRAIL_CLI_PASSWORD', originalPassword);
251
+ });
252
+ it('should sign in through the domain identity provider with a pasted code', async () => {
253
+ fetchMock
254
+ .mockResolvedValueOnce(jsonResponse(200, { identityProvider: 'sso-vibeiq-com' }))
255
+ .mockResolvedValueOnce(jsonResponse(200, { access_token: 'cognito-access', refresh_token: 'cognito-refresh' }));
256
+ const context = await (0, login_1.signIn)({ shouldOpenBrowser: false });
257
+ const [tokenUrl, tokenRequest] = fetchMock.mock.calls[1];
258
+ const tokenForm = new URLSearchParams(tokenRequest.body);
259
+ expect(tokenUrl).toBe(`${DEV_COGNITO_DOMAIN}/oauth2/token`);
260
+ expect(tokenForm.get('code')).toBe('pasted-code');
261
+ expect(tokenForm.get('redirect_uri')).toBe('https://login.dev.vibeiq.com/cli');
262
+ expect(context).toEqual({
263
+ apiUserToken: 'cognito-access',
264
+ apiRefreshToken: 'cognito-refresh',
265
+ apiGateway: DEV_GATEWAY,
266
+ orgSlug: 'adam-zone-1',
267
+ });
268
+ expect(config_1.storeConfig).toHaveBeenCalledWith({ ...context, signInMethod: 'sso' });
269
+ });
270
+ it('should reject a pasted code from a different sign-in attempt without saving tokens', async () => {
271
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { identityProvider: 'sso-vibeiq-com' }));
272
+ promptSpy.mockResolvedValue({ signInCode: 'pasted-code#another-state' });
273
+ await expect((0, login_1.signIn)({ shouldOpenBrowser: false })).rejects.toMatchObject({
274
+ code: 'SSO_SIGN_IN_CODE_MISMATCH',
275
+ });
276
+ expect(config_1.storeConfig).not.toHaveBeenCalled();
277
+ });
278
+ it('should ask for a password when the email domain has no SSO', async () => {
279
+ fetchMock
280
+ .mockResolvedValueOnce(new Response('', { status: 200 }))
281
+ .mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
282
+ promptSpy.mockResolvedValue({ password: 'secret' });
283
+ const context = await (0, login_1.signIn)({ shouldOpenBrowser: false });
284
+ expect(context.apiUserToken).toBe('vibe-access');
285
+ expect(config_1.storeConfig).toHaveBeenCalledWith({ ...context, signInMethod: 'password' });
286
+ });
287
+ it('should ask for a password when the email domain uses SSO the CLI cannot open', async () => {
288
+ fetchMock
289
+ .mockResolvedValueOnce(jsonResponse(200, { identityProvider: '', url: 'legacy' }))
290
+ .mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
291
+ promptSpy.mockResolvedValue({ password: 'secret' });
292
+ const context = await (0, login_1.signIn)({ shouldOpenBrowser: false });
293
+ expect(context.apiUserToken).toBe('vibe-access');
294
+ expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('The CLI does not support your SSO provider yet.'));
295
+ });
296
+ it('should refresh a stored SSO token through Cognito instead of the VibeIQ refresh endpoint', async () => {
297
+ config_1.getConfig.mockResolvedValue({
298
+ apiUserToken: 'expired-access',
299
+ apiRefreshToken: 'cognito-refresh',
300
+ apiGateway: DEV_GATEWAY,
301
+ orgSlug: 'adam-zone-1',
302
+ signInMethod: 'sso',
303
+ });
304
+ sdk_1.getCurrentUser
305
+ .mockRejectedValueOnce(new Error('Failed to fetch current user. Unauthorized'))
306
+ .mockResolvedValueOnce({ id: 'user-1' });
307
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { access_token: 'refreshed-access' }));
308
+ const context = await (0, login_1.authUser)();
309
+ const [tokenUrl, tokenRequest] = fetchMock.mock.calls[0];
310
+ expect(tokenUrl).toBe(`${DEV_COGNITO_DOMAIN}/oauth2/token`);
311
+ expect(new URLSearchParams(tokenRequest.body).get('refresh_token')).toBe('cognito-refresh');
312
+ expect(context.apiUserToken).toBe('refreshed-access');
313
+ });
314
+ it('should name the misconfiguration when a stored SSO token points at an unknown environment', async () => {
315
+ config_1.getConfig.mockResolvedValue({
316
+ apiUserToken: 'expired-access',
317
+ apiRefreshToken: 'cognito-refresh',
318
+ apiGateway: 'http://localhost:3000/api',
319
+ orgSlug: 'adam-zone-1',
320
+ signInMethod: 'sso',
321
+ });
322
+ sdk_1.getCurrentUser.mockRejectedValueOnce(new Error('Failed to fetch current user. Unauthorized'));
323
+ await expect((0, login_1.authUser)()).rejects.toMatchObject({ code: 'ENVIRONMENT_NOT_CONFIGURED' });
324
+ });
325
+ });
212
326
  describe('getVersionFromPackageJson', () => {
213
327
  it('should return the version value from package.json', () => {
214
328
  const version = (0, login_1.getVersionFromPackageJson)();
@@ -0,0 +1,7 @@
1
+ export type SignInErrorCode = 'ENVIRONMENT_NOT_CONFIGURED' | 'SSO_DOMAIN_CHECK_FAILED' | 'SSO_SIGN_IN_CODE_MISMATCH' | 'SSO_SIGN_IN_REJECTED' | 'SSO_UNEXPECTED_CALLBACK' | 'SSO_SIGN_IN_TIMED_OUT' | 'SSO_LOOPBACK_PORT_IN_USE' | 'SSO_TOKEN_REQUEST_FAILED' | 'API_KEY_CANNOT_REFRESH';
2
+ export declare class SignInError extends Error {
3
+ readonly code: SignInErrorCode;
4
+ readonly details: Record<string, string | number | undefined>;
5
+ constructor(code: SignInErrorCode, message: string, details?: Record<string, string | number | undefined>);
6
+ }
7
+ export declare function formatErrorForTerminal(error: Error): string;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatErrorForTerminal = exports.SignInError = void 0;
4
+ class SignInError extends Error {
5
+ code;
6
+ details;
7
+ constructor(code, message, details = {}) {
8
+ super(message);
9
+ this.code = code;
10
+ this.details = details;
11
+ this.name = 'SignInError';
12
+ }
13
+ }
14
+ exports.SignInError = SignInError;
15
+ function formatErrorForTerminal(error) {
16
+ if (!(error instanceof SignInError)) {
17
+ return error.message;
18
+ }
19
+ const details = Object.entries(error.details)
20
+ .filter(([, value]) => value !== undefined)
21
+ .map(([name, value]) => `${name}: ${value}`);
22
+ return details.length ? `${error.message} (${details.join(', ')})` : error.message;
23
+ }
24
+ exports.formatErrorForTerminal = formatErrorForTerminal;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const sign_in_error_1 = require("./sign-in-error");
4
+ describe('formatErrorForTerminal', () => {
5
+ it('should follow a sign-in error message with its details', () => {
6
+ const error = new sign_in_error_1.SignInError('SSO_TOKEN_REQUEST_FAILED', 'Cognito rejected the token request.', {
7
+ status: 400,
8
+ oauthError: 'invalid_grant',
9
+ });
10
+ expect((0, sign_in_error_1.formatErrorForTerminal)(error)).toBe('Cognito rejected the token request. (status: 400, oauthError: invalid_grant)');
11
+ });
12
+ it('should leave out details that are not set', () => {
13
+ const error = new sign_in_error_1.SignInError('SSO_TOKEN_REQUEST_FAILED', 'Cognito rejected the token request.', {
14
+ status: 400,
15
+ oauthError: undefined,
16
+ });
17
+ expect((0, sign_in_error_1.formatErrorForTerminal)(error)).toBe('Cognito rejected the token request. (status: 400)');
18
+ });
19
+ it('should show only the message for other errors', () => {
20
+ expect((0, sign_in_error_1.formatErrorForTerminal)(new Error('Something else.'))).toBe('Something else.');
21
+ });
22
+ });
@@ -0,0 +1,38 @@
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 SignInAttempt {
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 createSignInAttempt(): SignInAttempt;
27
+ export declare function buildAuthorizeUrl(client: SsoClient, identityProvider: string, redirectUri: string, signInAttempt: SignInAttempt): string;
28
+ export declare function parsePastedSignInCode(pasted: string, expectedState: string): string;
29
+ export interface LoopbackListener {
30
+ code: Promise<string>;
31
+ stop: () => void;
32
+ }
33
+ export declare function listenForLoopbackCode(expectedState: string): Promise<LoopbackListener>;
34
+ export declare function canOpenBrowser(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): boolean;
35
+ export declare function openBrowser(url: string): Promise<void>;
36
+ export declare function buildOpenBrowserCommand(url: string, platform: NodeJS.Platform): [string, string[]];
37
+ export declare function exchangeCodeForTokens(client: SsoClient, code: string, redirectUri: string, verifier: string): Promise<SsoTokens>;
38
+ export declare function refreshSsoAccessToken(client: SsoClient, refreshToken: string): Promise<string>;
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.refreshSsoAccessToken = exports.exchangeCodeForTokens = exports.buildOpenBrowserCommand = exports.openBrowser = exports.canOpenBrowser = exports.listenForLoopbackCode = exports.parsePastedSignInCode = exports.buildAuthorizeUrl = exports.createSignInAttempt = 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
+ const sign_in_error_1 = require("./sign-in-error");
8
+ // Must match the CLI client's loopback callback URL in contrail-api resources/cognito.
9
+ exports.LOOPBACK_PORT = 7731;
10
+ exports.LOOPBACK_CALLBACK_URL = `http://localhost:${exports.LOOPBACK_PORT}/callback`;
11
+ const BROWSER_SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000;
12
+ const OAUTH_SCOPES = ['openid', 'email', 'api.vibeiq.default/read', 'api.vibeiq.default/write'];
13
+ async function fetchSsoDomainCheck(email, apiGateway) {
14
+ const domain = email.split('@').pop().toLowerCase();
15
+ const response = await fetch(`${apiGateway}/sso-login/domain-check/${encodeURIComponent(domain)}`);
16
+ if (!response.ok) {
17
+ throw new sign_in_error_1.SignInError('SSO_DOMAIN_CHECK_FAILED', 'Could not check whether your email domain signs in with SSO.', { domain, status: response.status });
18
+ }
19
+ const body = await response.text();
20
+ if (!body) {
21
+ return { kind: 'none' };
22
+ }
23
+ const { identityProvider } = JSON.parse(body);
24
+ return identityProvider ? { kind: 'cognito', identityProvider } : { kind: 'legacy' };
25
+ }
26
+ exports.fetchSsoDomainCheck = fetchSsoDomainCheck;
27
+ function createSignInAttempt() {
28
+ // RFC 7636 needs a 43-128 character verifier: 32 random bytes encode to 43.
29
+ const verifier = (0, node_crypto_1.randomBytes)(32).toString('base64url');
30
+ return {
31
+ verifier,
32
+ challenge: (0, node_crypto_1.createHash)('sha256').update(verifier).digest('base64url'),
33
+ // RFC 6749 section 10.10 asks for at most a 2^-128 chance of guessing state.
34
+ state: (0, node_crypto_1.randomBytes)(16).toString('base64url'),
35
+ };
36
+ }
37
+ exports.createSignInAttempt = createSignInAttempt;
38
+ function buildAuthorizeUrl(client, identityProvider, redirectUri, signInAttempt) {
39
+ const params = new URLSearchParams({
40
+ response_type: 'code',
41
+ client_id: client.clientId,
42
+ redirect_uri: redirectUri,
43
+ scope: OAUTH_SCOPES.join(' '),
44
+ identity_provider: identityProvider,
45
+ code_challenge: signInAttempt.challenge,
46
+ code_challenge_method: 'S256',
47
+ state: signInAttempt.state,
48
+ });
49
+ return `${client.domain}/oauth2/authorize?${params}`;
50
+ }
51
+ exports.buildAuthorizeUrl = buildAuthorizeUrl;
52
+ function parsePastedSignInCode(pasted, expectedState) {
53
+ const [code, state] = pasted.trim().split('#');
54
+ if (!code || state !== expectedState) {
55
+ throw new sign_in_error_1.SignInError('SSO_SIGN_IN_CODE_MISMATCH', 'That sign-in code is not from this login attempt. Run the command again.');
56
+ }
57
+ return code;
58
+ }
59
+ exports.parsePastedSignInCode = parsePastedSignInCode;
60
+ function listenForLoopbackCode(expectedState) {
61
+ let resolveCode;
62
+ let rejectCode;
63
+ const code = new Promise((resolve, reject) => {
64
+ resolveCode = resolve;
65
+ rejectCode = reject;
66
+ });
67
+ const server = (0, node_http_1.createServer)((request, response) => {
68
+ const url = new URL(request.url, exports.LOOPBACK_CALLBACK_URL);
69
+ if (url.pathname !== '/callback') {
70
+ response.writeHead(404).end();
71
+ return;
72
+ }
73
+ if (url.searchParams.get('state') !== expectedState) {
74
+ response.writeHead(400, { 'Content-Type': 'text/plain' }).end('Unknown sign-in attempt.');
75
+ return;
76
+ }
77
+ const error = url.searchParams.get('error_description') ?? url.searchParams.get('error');
78
+ const receivedCode = url.searchParams.get('code');
79
+ const signedIn = !error && Boolean(receivedCode);
80
+ const page = signedIn
81
+ ? 'Sign-in received. Return to your terminal.'
82
+ : 'Sign-in failed. Return to your terminal.';
83
+ response
84
+ .writeHead(signedIn ? 200 : 400, { 'Content-Type': 'text/plain', Connection: 'close' })
85
+ .end(page, () => stopListening(request.socket, () => {
86
+ if (error) {
87
+ rejectCode(new sign_in_error_1.SignInError('SSO_SIGN_IN_REJECTED', 'Your identity provider did not complete the sign-in. Run the command again.', { oauthError: error }));
88
+ }
89
+ else if (!signedIn) {
90
+ rejectCode(new sign_in_error_1.SignInError('SSO_UNEXPECTED_CALLBACK', 'SSO sign-in returned an unexpected response. Run the command again.'));
91
+ }
92
+ else {
93
+ resolveCode(receivedCode);
94
+ }
95
+ }));
96
+ });
97
+ const openSockets = new Set();
98
+ server.on('connection', (socket) => {
99
+ openSockets.add(socket);
100
+ socket.once('close', () => openSockets.delete(socket));
101
+ });
102
+ const timeout = setTimeout(() => stopListening(undefined, () => rejectCode(new sign_in_error_1.SignInError('SSO_SIGN_IN_TIMED_OUT', 'Timed out waiting for the browser sign-in.'))), BROWSER_SIGN_IN_TIMEOUT_MS);
103
+ function stopListening(respondingSocket, settle) {
104
+ clearTimeout(timeout);
105
+ server.close();
106
+ openSockets.forEach((socket) => socket !== respondingSocket && socket.destroy());
107
+ settle();
108
+ }
109
+ return new Promise((resolve, reject) => {
110
+ server.once('error', (error) => {
111
+ clearTimeout(timeout);
112
+ if (error.code !== 'EADDRINUSE') {
113
+ reject(error);
114
+ return;
115
+ }
116
+ reject(new sign_in_error_1.SignInError('SSO_LOOPBACK_PORT_IN_USE', 'The sign-in port is in use. Run contrail login --no-browser instead.', { port: exports.LOOPBACK_PORT }));
117
+ });
118
+ server.listen(exports.LOOPBACK_PORT, 'localhost', () => resolve({ code, stop: () => stopListening(undefined, () => undefined) }));
119
+ });
120
+ }
121
+ exports.listenForLoopbackCode = listenForLoopbackCode;
122
+ function canOpenBrowser(env = process.env, platform = process.platform) {
123
+ const isRemoteShell = Boolean(env.SSH_CONNECTION || env.SSH_TTY);
124
+ const hasLinuxDisplay = Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
125
+ return !isRemoteShell && (platform !== 'linux' || hasLinuxDisplay);
126
+ }
127
+ exports.canOpenBrowser = canOpenBrowser;
128
+ function openBrowser(url) {
129
+ const [command, args] = buildOpenBrowserCommand(url, process.platform);
130
+ return new Promise((resolve, reject) => {
131
+ const browserProcess = (0, node_child_process_1.spawn)(command, args, { stdio: 'ignore', detached: true });
132
+ browserProcess.once('spawn', () => {
133
+ browserProcess.unref();
134
+ resolve();
135
+ });
136
+ browserProcess.once('error', reject);
137
+ });
138
+ }
139
+ exports.openBrowser = openBrowser;
140
+ function buildOpenBrowserCommand(url, platform) {
141
+ if (platform === 'darwin') {
142
+ return ['open', [url]];
143
+ }
144
+ if (platform === 'win32') {
145
+ return ['rundll32', ['url.dll,FileProtocolHandler', url]];
146
+ }
147
+ return ['xdg-open', [url]];
148
+ }
149
+ exports.buildOpenBrowserCommand = buildOpenBrowserCommand;
150
+ async function exchangeCodeForTokens(client, code, redirectUri, verifier) {
151
+ const tokens = await postToTokenEndpoint(client, {
152
+ grant_type: 'authorization_code',
153
+ client_id: client.clientId,
154
+ code,
155
+ redirect_uri: redirectUri,
156
+ code_verifier: verifier,
157
+ });
158
+ return { accessToken: tokens.access_token, refreshToken: tokens.refresh_token };
159
+ }
160
+ exports.exchangeCodeForTokens = exchangeCodeForTokens;
161
+ async function refreshSsoAccessToken(client, refreshToken) {
162
+ const tokens = await postToTokenEndpoint(client, {
163
+ grant_type: 'refresh_token',
164
+ client_id: client.clientId,
165
+ refresh_token: refreshToken,
166
+ });
167
+ return tokens.access_token;
168
+ }
169
+ exports.refreshSsoAccessToken = refreshSsoAccessToken;
170
+ async function postToTokenEndpoint(client, form) {
171
+ const response = await fetch(`${client.domain}/oauth2/token`, {
172
+ method: 'POST',
173
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
174
+ body: new URLSearchParams(form),
175
+ });
176
+ const body = await response.json();
177
+ if (!response.ok) {
178
+ throw new sign_in_error_1.SignInError('SSO_TOKEN_REQUEST_FAILED', 'Cognito rejected the token request.', {
179
+ status: response.status,
180
+ oauthError: body.error,
181
+ });
182
+ }
183
+ return body;
184
+ }
@@ -0,0 +1,191 @@
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('createSignInAttempt', () => {
11
+ it('should derive the challenge as the base64url SHA-256 of the verifier', () => {
12
+ const signInAttempt = (0, sso_1.createSignInAttempt)();
13
+ expect(signInAttempt.challenge).toBe((0, node_crypto_1.createHash)('sha256').update(signInAttempt.verifier).digest('base64url'));
14
+ });
15
+ it('should make a verifier of at least the 43 characters PKCE requires', () => {
16
+ expect((0, sso_1.createSignInAttempt)().verifier.length).toBeGreaterThanOrEqual(43);
17
+ });
18
+ });
19
+ describe('buildAuthorizeUrl', () => {
20
+ it('should send the user straight to their identity provider with a PKCE challenge', () => {
21
+ const url = new URL((0, sso_1.buildAuthorizeUrl)(ssoClient, 'sso-vibeiq-com', sso_1.LOOPBACK_CALLBACK_URL, {
22
+ verifier: 'verifier',
23
+ challenge: 'challenge',
24
+ state: 'state',
25
+ }));
26
+ expect(url.origin + url.pathname).toBe(`${ssoClient.domain}/oauth2/authorize`);
27
+ expect(Object.fromEntries(url.searchParams)).toEqual({
28
+ response_type: 'code',
29
+ client_id: 'cli-client',
30
+ redirect_uri: 'http://localhost:7731/callback',
31
+ scope: 'openid email api.vibeiq.default/read api.vibeiq.default/write',
32
+ identity_provider: 'sso-vibeiq-com',
33
+ code_challenge: 'challenge',
34
+ code_challenge_method: 'S256',
35
+ state: 'state',
36
+ });
37
+ });
38
+ });
39
+ describe('parsePastedSignInCode', () => {
40
+ it('should return the code when the pasted state matches this attempt', () => {
41
+ expect((0, sso_1.parsePastedSignInCode)(' the-code#the-state \n', 'the-state')).toBe('the-code');
42
+ });
43
+ it('should reject a code from another attempt', () => {
44
+ expect(() => (0, sso_1.parsePastedSignInCode)('the-code#other-state', 'the-state')).toThrow(expect.objectContaining({ code: 'SSO_SIGN_IN_CODE_MISMATCH' }));
45
+ });
46
+ it('should reject a code pasted without its state', () => {
47
+ expect(() => (0, sso_1.parsePastedSignInCode)('the-code', 'the-state')).toThrow(expect.objectContaining({ code: 'SSO_SIGN_IN_CODE_MISMATCH' }));
48
+ });
49
+ });
50
+ describe('canOpenBrowser', () => {
51
+ it('should open a browser on a local Mac', () => {
52
+ expect((0, sso_1.canOpenBrowser)({}, 'darwin')).toBe(true);
53
+ });
54
+ it('should not open a browser over SSH', () => {
55
+ expect((0, sso_1.canOpenBrowser)({ SSH_CONNECTION: '10.0.0.1 22 10.0.0.2 22' }, 'darwin')).toBe(false);
56
+ });
57
+ it('should not open a browser on Linux without a display', () => {
58
+ expect((0, sso_1.canOpenBrowser)({}, 'linux')).toBe(false);
59
+ });
60
+ it('should open a browser on a Linux desktop', () => {
61
+ expect((0, sso_1.canOpenBrowser)({ WAYLAND_DISPLAY: 'wayland-0' }, 'linux')).toBe(true);
62
+ });
63
+ });
64
+ describe('fetchSsoDomainCheck', () => {
65
+ const originalFetch = global.fetch;
66
+ afterEach(() => {
67
+ global.fetch = originalFetch;
68
+ });
69
+ function stubDomainCheckFetch(body, status = 200) {
70
+ global.fetch = jest.fn().mockResolvedValue(new Response(body, { status }));
71
+ }
72
+ it('should name the Cognito identity provider for an SSO domain', async () => {
73
+ stubDomainCheckFetch(JSON.stringify({ identityProvider: 'sso-vibeiq-com' }));
74
+ await expect((0, sso_1.fetchSsoDomainCheck)('Dev@VibeIQ.com', 'https://api')).resolves.toEqual({
75
+ kind: 'cognito',
76
+ identityProvider: 'sso-vibeiq-com',
77
+ });
78
+ expect(global.fetch).toHaveBeenCalledWith('https://api/sso-login/domain-check/vibeiq.com');
79
+ });
80
+ it('should report a legacy SSO domain', async () => {
81
+ stubDomainCheckFetch(JSON.stringify({ identityProvider: '', url: 'https://api/sso-login/login/acme.com' }));
82
+ await expect((0, sso_1.fetchSsoDomainCheck)('dev@acme.com', 'https://api')).resolves.toEqual({
83
+ kind: 'legacy',
84
+ });
85
+ });
86
+ it('should report no SSO for an empty response', async () => {
87
+ stubDomainCheckFetch('');
88
+ await expect((0, sso_1.fetchSsoDomainCheck)('dev@example.com', 'https://api')).resolves.toEqual({
89
+ kind: 'none',
90
+ });
91
+ });
92
+ it('should fail when the lookup fails', async () => {
93
+ stubDomainCheckFetch('{}', 502);
94
+ await expect((0, sso_1.fetchSsoDomainCheck)('dev@example.com', 'https://api')).rejects.toMatchObject({
95
+ code: 'SSO_DOMAIN_CHECK_FAILED',
96
+ details: { domain: 'example.com', status: 502 },
97
+ });
98
+ });
99
+ });
100
+ describe('listenForLoopbackCode', () => {
101
+ it('should resolve with the code the browser redirects back with', async () => {
102
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
103
+ const response = await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
104
+ expect(response.status).toBe(200);
105
+ await expect(listener.code).resolves.toBe('the-code');
106
+ });
107
+ it('should keep waiting for this attempt after a redirect from another attempt', async () => {
108
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
109
+ const staleResponse = await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=old-code&state=old-state`);
110
+ await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
111
+ expect(staleResponse.status).toBe(400);
112
+ await expect(listener.code).resolves.toBe('the-code');
113
+ });
114
+ it('should reject a redirect for this attempt that carries no code', async () => {
115
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
116
+ const rejection = expect(listener.code).rejects.toMatchObject({
117
+ code: 'SSO_UNEXPECTED_CALLBACK',
118
+ });
119
+ const response = await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?state=the-state`);
120
+ expect(response.status).toBe(400);
121
+ await rejection;
122
+ });
123
+ it('should reject when the identity provider reports an error', async () => {
124
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
125
+ const rejection = expect(listener.code).rejects.toMatchObject({
126
+ code: 'SSO_SIGN_IN_REJECTED',
127
+ details: { oauthError: 'User cancelled' },
128
+ });
129
+ await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?error=access_denied&error_description=User%20cancelled&state=the-state`);
130
+ await rejection;
131
+ });
132
+ it('should close idle browser connections once the code arrives', async () => {
133
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
134
+ const idleConnection = (0, node_net_1.connect)(sso_1.LOOPBACK_PORT, 'localhost');
135
+ await new Promise((resolve) => idleConnection.once('connect', resolve));
136
+ const idleConnectionClosed = new Promise((resolve) => idleConnection.once('close', resolve));
137
+ await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
138
+ await expect(listener.code).resolves.toBe('the-code');
139
+ await expect(idleConnectionClosed).resolves.toBe(false);
140
+ });
141
+ it('should tell the user to paste a code instead when the port is taken', async () => {
142
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
143
+ await expect((0, sso_1.listenForLoopbackCode)('another-state')).rejects.toMatchObject({
144
+ code: 'SSO_LOOPBACK_PORT_IN_USE',
145
+ details: { port: sso_1.LOOPBACK_PORT },
146
+ });
147
+ await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
148
+ await listener.code;
149
+ });
150
+ it('should free the port when stopped', async () => {
151
+ const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
152
+ listener.stop();
153
+ const nextListener = await (0, sso_1.listenForLoopbackCode)('next-state');
154
+ nextListener.stop();
155
+ });
156
+ });
157
+ describe('buildOpenBrowserCommand', () => {
158
+ it('should use open on a Mac', () => {
159
+ expect((0, sso_1.buildOpenBrowserCommand)('https://sign.in', 'darwin')).toEqual([
160
+ 'open',
161
+ ['https://sign.in'],
162
+ ]);
163
+ });
164
+ it('should pass the URL through rundll32 on Windows so the shell cannot split it', () => {
165
+ expect((0, sso_1.buildOpenBrowserCommand)('https://sign.in?a=1&b=2', 'win32')).toEqual([
166
+ 'rundll32',
167
+ ['url.dll,FileProtocolHandler', 'https://sign.in?a=1&b=2'],
168
+ ]);
169
+ });
170
+ it('should use xdg-open on Linux', () => {
171
+ expect((0, sso_1.buildOpenBrowserCommand)('https://sign.in', 'linux')).toEqual([
172
+ 'xdg-open',
173
+ ['https://sign.in'],
174
+ ]);
175
+ });
176
+ });
177
+ describe('exchangeCodeForTokens', () => {
178
+ const originalFetch = global.fetch;
179
+ afterEach(() => {
180
+ global.fetch = originalFetch;
181
+ });
182
+ it('should name the Cognito error when the exchange is refused', async () => {
183
+ global.fetch = jest
184
+ .fn()
185
+ .mockResolvedValue(new Response(JSON.stringify({ error: 'invalid_grant' }), { status: 400 }));
186
+ await expect((0, sso_1.exchangeCodeForTokens)(ssoClient, 'the-code', sso_1.LOOPBACK_CALLBACK_URL, 'verifier')).rejects.toMatchObject({
187
+ code: 'SSO_TOKEN_REQUEST_FAILED',
188
+ details: { status: 400, oauthError: 'invalid_grant' },
189
+ });
190
+ });
191
+ });
@@ -11,5 +11,8 @@ export declare abstract class BaseCommand extends Command {
11
11
  protected args: any;
12
12
  init(): Promise<void>;
13
13
  setLogLevel(logLevel: string, config?: any): void;
14
+ protected catch(error: Error & {
15
+ exitCode?: number;
16
+ }): Promise<unknown>;
14
17
  private confirmEnv;
15
18
  }