@contrail/cli 3.6.0-alpha.f45f126 → 3.7.0-alpha.1c66a91

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 (105) hide show
  1. package/README.md +207 -3
  2. package/dist/api/types.d.ts +35 -0
  3. package/dist/api/types.js +49 -1
  4. package/dist/auth/login.d.ts +1 -1
  5. package/dist/auth/login.js +46 -29
  6. package/dist/auth/login.spec.js +31 -15
  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.d.ts +1 -0
  10. package/dist/auth/sign-in-error.spec.js +22 -0
  11. package/dist/auth/sso.d.ts +5 -3
  12. package/dist/auth/sso.js +34 -18
  13. package/dist/auth/sso.spec.js +63 -10
  14. package/dist/basecommand.d.ts +3 -0
  15. package/dist/basecommand.js +10 -3
  16. package/dist/commands/app/getApiKey.js +2 -2
  17. package/dist/commands/app/publish.js +1 -1
  18. package/dist/commands/app/version/prerelease.d.ts +11 -0
  19. package/dist/commands/app/version/prerelease.js +32 -0
  20. package/dist/commands/entities/create.d.ts +49 -0
  21. package/dist/commands/entities/create.js +618 -0
  22. package/dist/commands/entities/create.spec.d.ts +1 -0
  23. package/dist/commands/entities/create.spec.js +581 -0
  24. package/dist/commands/entities/delete.d.ts +20 -0
  25. package/dist/commands/entities/delete.js +146 -0
  26. package/dist/commands/entities/get.d.ts +25 -0
  27. package/dist/commands/entities/get.js +298 -0
  28. package/dist/commands/entities/grammar.spec.d.ts +1 -0
  29. package/dist/commands/entities/grammar.spec.js +79 -0
  30. package/dist/commands/entities/output.spec.d.ts +1 -0
  31. package/dist/commands/entities/output.spec.js +72 -0
  32. package/dist/commands/entities/update.d.ts +32 -0
  33. package/dist/commands/entities/update.js +212 -0
  34. package/dist/commands/login.js +1 -1
  35. package/dist/commands/webhooks/delete.js +2 -3
  36. package/dist/common.d.ts +10 -1
  37. package/dist/common.js +37 -1
  38. package/dist/common.spec.d.ts +1 -0
  39. package/dist/common.spec.js +40 -0
  40. package/dist/helpers/app/app-config-validators.js +4 -4
  41. package/dist/helpers/app/app-config-validators.spec.js +36 -0
  42. package/dist/helpers/app/app-deployer.d.ts +1 -0
  43. package/dist/helpers/app/app-deployer.js +34 -0
  44. package/dist/helpers/app/upgrade-version.d.ts +3 -1
  45. package/dist/helpers/app/upgrade-version.js +7 -8
  46. package/dist/helpers/app/upgrade-version.spec.js +15 -0
  47. package/dist/helpers/config/config.d.ts +3 -3
  48. package/dist/helpers/config/config.js +3 -3
  49. package/dist/helpers/entities/assortment-items.d.ts +11 -0
  50. package/dist/helpers/entities/assortment-items.js +76 -0
  51. package/dist/helpers/entities/batchFetch.d.ts +11 -0
  52. package/dist/helpers/entities/batchFetch.js +50 -0
  53. package/dist/helpers/entities/index.d.ts +3 -0
  54. package/dist/helpers/entities/index.js +6 -0
  55. package/dist/helpers/entities/items.d.ts +6 -0
  56. package/dist/helpers/entities/items.js +60 -0
  57. package/dist/helpers/entities/items.spec.d.ts +1 -0
  58. package/dist/helpers/entities/items.spec.js +19 -0
  59. package/dist/helpers/entities/project-items.d.ts +2 -0
  60. package/dist/helpers/entities/project-items.js +44 -0
  61. package/dist/helpers/file-helpers.d.ts +1 -0
  62. package/dist/helpers/file-helpers.js +20 -3
  63. package/dist/helpers/propertySpecifications/dateRanges.d.ts +34 -0
  64. package/dist/helpers/propertySpecifications/dateRanges.js +91 -0
  65. package/dist/helpers/propertySpecifications/dateRanges.spec.d.ts +1 -0
  66. package/dist/helpers/propertySpecifications/dateRanges.spec.js +97 -0
  67. package/dist/helpers/propertySpecifications/propertySpecifications.d.ts +39 -0
  68. package/dist/helpers/propertySpecifications/propertySpecifications.js +102 -0
  69. package/dist/helpers/propertySpecifications/propertySpecifications.spec.d.ts +1 -0
  70. package/dist/helpers/propertySpecifications/propertySpecifications.spec.js +387 -0
  71. package/dist/helpers/propertySpecifications/propertyValues.d.ts +31 -0
  72. package/dist/helpers/propertySpecifications/propertyValues.js +132 -0
  73. package/dist/helpers/propertySpecifications/propertyValues.spec.d.ts +1 -0
  74. package/dist/helpers/propertySpecifications/propertyValues.spec.js +156 -0
  75. package/dist/logger.js +4 -1
  76. package/dist/logger.spec.d.ts +1 -0
  77. package/dist/logger.spec.js +12 -0
  78. package/node_modules/@contrail/entity-compare/package.json +6 -3
  79. package/node_modules/@contrail/loader/lib/common/conditional-columns.js +1 -1
  80. package/node_modules/@contrail/loader/lib/constants.d.ts +0 -8
  81. package/node_modules/@contrail/loader/lib/constants.js +1 -9
  82. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.d.ts +0 -4
  83. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.js +0 -57
  84. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.spec.js +34 -492
  85. package/node_modules/@contrail/loader/lib/pipeline/validate.js +52 -2
  86. package/node_modules/@contrail/loader/lib/pipeline/validate.spec.js +85 -0
  87. package/node_modules/@contrail/loader/package.json +2 -2
  88. package/node_modules/@contrail/sdk/.github/workflows/publish-to-npm.yml +1 -4
  89. package/node_modules/@contrail/sdk/lib/auth/login.js +1 -1
  90. package/node_modules/@contrail/sdk/lib/config/config.d.ts +3 -0
  91. package/node_modules/@contrail/sdk/lib/config/config.js +13 -7
  92. package/node_modules/@contrail/sdk/lib/core/request.js +6 -2
  93. package/node_modules/@contrail/sdk/lib/entities/entities.client.d.ts +2 -0
  94. package/node_modules/@contrail/sdk/lib/entities/entities.client.js +3 -1
  95. package/node_modules/@contrail/sdk/lib/entities/entity.resource.registry.js +1 -0
  96. package/node_modules/@contrail/sdk/lib/image-search/image-search.d.ts +34 -0
  97. package/node_modules/@contrail/sdk/lib/image-search/image-search.js +42 -0
  98. package/node_modules/@contrail/sdk/lib/image-search/index.d.ts +1 -0
  99. package/node_modules/@contrail/sdk/lib/image-search/index.js +17 -0
  100. package/node_modules/@contrail/sdk/lib/index.d.ts +1 -0
  101. package/node_modules/@contrail/sdk/lib/index.js +1 -0
  102. package/node_modules/@contrail/sdk/package.json +1 -1
  103. package/node_modules/@contrail/sdk/scripts/replicate-bug.js +69 -0
  104. package/oclif.manifest.json +492 -2
  105. package/package.json +6 -12
@@ -3,9 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
4
  const amazon_cognito_identity_js_1 = require("amazon-cognito-identity-js");
5
5
  const sdk_1 = require("@contrail/sdk");
6
- const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
6
+ const common = tslib_1.__importStar(require("../common"));
7
7
  const config_1 = require("../helpers/config/config");
8
- const logger_1 = tslib_1.__importDefault(require("../logger"));
9
8
  const login_1 = require("./login");
10
9
  const mockAuthenticateUser = jest.fn();
11
10
  jest.mock('amazon-cognito-identity-js', () => ({
@@ -104,14 +103,17 @@ describe('authUser with email and password', () => {
104
103
  apiGateway: 'api.dev.vibeiq.com/dev/api',
105
104
  orgSlug: 'adam-zone-1',
106
105
  });
107
- 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
+ });
108
110
  });
109
111
  it('should fail without saving tokens when no pool is known for the environment', async () => {
110
112
  config_1.getConfig.mockResolvedValue({
111
113
  apiGateway: 'http://localhost:3000/api',
112
114
  orgSlug: 'adam-zone-1',
113
115
  });
114
- 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' });
115
117
  expect(config_1.storeConfig).not.toHaveBeenCalled();
116
118
  });
117
119
  it('should tell the user to update the CLI when its Cognito client or pool no longer exists', async () => {
@@ -172,7 +174,7 @@ describe('authUser with stored tokens', () => {
172
174
  const context = await (0, login_1.authUser)();
173
175
  expect(fetchMock).toHaveBeenCalledWith(`${DEV_GATEWAY}/auth/jwt_refresh/`, expect.objectContaining({ body: JSON.stringify({ refreshToken: 'stored-refresh' }) }));
174
176
  expect(context).toEqual({ ...storedConfig, apiUserToken: 'refreshed-access' });
175
- expect(config_1.storeConfig).toHaveBeenCalledWith(context);
177
+ expect(config_1.storeConfig).toHaveBeenCalledWith({ ...context, signInMethod: 'password' });
176
178
  });
177
179
  it('should keep a still-valid access token without refreshing it', async () => {
178
180
  acceptedTokens = ['expired-access'];
@@ -219,10 +221,11 @@ describe('signIn with SSO', () => {
219
221
  const DEV_COGNITO_DOMAIN = 'https://dev-vibeiq.auth.us-east-1.amazoncognito.com';
220
222
  let fetchMock;
221
223
  let promptSpy;
224
+ let consoleLogSpy;
222
225
  function pasteCodeFromPrintedSignInUrl() {
223
226
  promptSpy.mockImplementation(async () => {
224
- const printed = logger_1.default.info.mock.calls.map(([message]) => message).join('\n');
225
- const signInUrl = new URL(printed.match(/https:\/\/\S+oauth2\/authorize\S+/)[0]);
227
+ const printedOutput = consoleLogSpy.mock.calls.map(([message]) => message).join('\n');
228
+ const signInUrl = new URL(printedOutput.match(/https:\/\/\S+oauth2\/authorize\S+/)[0]);
226
229
  return { signInCode: `pasted-code#${signInUrl.searchParams.get('state')}` };
227
230
  });
228
231
  }
@@ -233,13 +236,15 @@ describe('signIn with SSO', () => {
233
236
  config_1.getConfig.mockResolvedValue({ apiGateway: DEV_GATEWAY, orgSlug: 'adam-zone-1' });
234
237
  sdk_1.getCurrentUser.mockResolvedValue({ id: 'user-1' });
235
238
  mockAuthenticateUser.mockImplementation((_details, callbacks) => callbacks.onSuccess({ idToken: { jwtToken: 'cognito-id-token' } }));
236
- promptSpy = jest.spyOn(inquirer_1.default, 'prompt');
239
+ consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined);
240
+ promptSpy = jest.spyOn(common, 'promptOnStderr');
237
241
  pasteCodeFromPrintedSignInUrl();
238
242
  fetchMock = jest.fn();
239
243
  global.fetch = fetchMock;
240
244
  });
241
245
  afterEach(() => {
242
246
  promptSpy.mockRestore();
247
+ consoleLogSpy.mockRestore();
243
248
  global.fetch = originalFetch;
244
249
  restoreEnv('CONTRAIL_CLI_EMAIL', originalEmail);
245
250
  restoreEnv('CONTRAIL_CLI_PASSWORD', originalPassword);
@@ -248,8 +253,7 @@ describe('signIn with SSO', () => {
248
253
  fetchMock
249
254
  .mockResolvedValueOnce(jsonResponse(200, { identityProvider: 'sso-vibeiq-com' }))
250
255
  .mockResolvedValueOnce(jsonResponse(200, { access_token: 'cognito-access', refresh_token: 'cognito-refresh' }));
251
- const context = await (0, login_1.signIn)({ openBrowser: false });
252
- expect(fetchMock.mock.calls[0][0]).toBe(`${DEV_GATEWAY}/sso-login/domain-check/vibeiq.com`);
256
+ const context = await (0, login_1.signIn)({ shouldOpenBrowser: false });
253
257
  const [tokenUrl, tokenRequest] = fetchMock.mock.calls[1];
254
258
  const tokenForm = new URLSearchParams(tokenRequest.body);
255
259
  expect(tokenUrl).toBe(`${DEV_COGNITO_DOMAIN}/oauth2/token`);
@@ -266,7 +270,9 @@ describe('signIn with SSO', () => {
266
270
  it('should reject a pasted code from a different sign-in attempt without saving tokens', async () => {
267
271
  fetchMock.mockResolvedValueOnce(jsonResponse(200, { identityProvider: 'sso-vibeiq-com' }));
268
272
  promptSpy.mockResolvedValue({ signInCode: 'pasted-code#another-state' });
269
- await expect((0, login_1.signIn)({ openBrowser: false })).rejects.toThrow('That sign-in code is not from this login attempt.');
273
+ await expect((0, login_1.signIn)({ shouldOpenBrowser: false })).rejects.toMatchObject({
274
+ code: 'SSO_SIGN_IN_CODE_MISMATCH',
275
+ });
270
276
  expect(config_1.storeConfig).not.toHaveBeenCalled();
271
277
  });
272
278
  it('should ask for a password when the email domain has no SSO', async () => {
@@ -274,8 +280,7 @@ describe('signIn with SSO', () => {
274
280
  .mockResolvedValueOnce(new Response('', { status: 200 }))
275
281
  .mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
276
282
  promptSpy.mockResolvedValue({ password: 'secret' });
277
- const context = await (0, login_1.signIn)({ openBrowser: false });
278
- expect(mockAuthenticateUser).toHaveBeenCalled();
283
+ const context = await (0, login_1.signIn)({ shouldOpenBrowser: false });
279
284
  expect(context.apiUserToken).toBe('vibe-access');
280
285
  expect(config_1.storeConfig).toHaveBeenCalledWith({ ...context, signInMethod: 'password' });
281
286
  });
@@ -284,9 +289,9 @@ describe('signIn with SSO', () => {
284
289
  .mockResolvedValueOnce(jsonResponse(200, { identityProvider: '', url: 'legacy' }))
285
290
  .mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
286
291
  promptSpy.mockResolvedValue({ password: 'secret' });
287
- const context = await (0, login_1.signIn)({ openBrowser: false });
292
+ const context = await (0, login_1.signIn)({ shouldOpenBrowser: false });
288
293
  expect(context.apiUserToken).toBe('vibe-access');
289
- expect(logger_1.default.info).toHaveBeenCalledWith(expect.stringContaining('The CLI does not support your SSO provider yet.'));
294
+ expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('The CLI does not support your SSO provider yet.'));
290
295
  });
291
296
  it('should refresh a stored SSO token through Cognito instead of the VibeIQ refresh endpoint', async () => {
292
297
  config_1.getConfig.mockResolvedValue({
@@ -306,6 +311,17 @@ describe('signIn with SSO', () => {
306
311
  expect(new URLSearchParams(tokenRequest.body).get('refresh_token')).toBe('cognito-refresh');
307
312
  expect(context.apiUserToken).toBe('refreshed-access');
308
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
+ });
309
325
  });
310
326
  describe('getVersionFromPackageJson', () => {
311
327
  it('should return the version value from package.json', () => {
@@ -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 @@
1
+ export {};
@@ -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
+ });
@@ -9,7 +9,7 @@ export interface SsoTokens {
9
9
  accessToken: string;
10
10
  refreshToken: string;
11
11
  }
12
- export interface PkceChallenge {
12
+ export interface SignInAttempt {
13
13
  verifier: string;
14
14
  challenge: string;
15
15
  state: string;
@@ -23,14 +23,16 @@ export type SsoDomainCheck = {
23
23
  kind: 'none';
24
24
  };
25
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;
26
+ export declare function createSignInAttempt(): SignInAttempt;
27
+ export declare function buildAuthorizeUrl(client: SsoClient, identityProvider: string, redirectUri: string, signInAttempt: SignInAttempt): string;
28
28
  export declare function parsePastedSignInCode(pasted: string, expectedState: string): string;
29
29
  export interface LoopbackListener {
30
30
  code: Promise<string>;
31
+ stop: () => void;
31
32
  }
32
33
  export declare function listenForLoopbackCode(expectedState: string): Promise<LoopbackListener>;
33
34
  export declare function canOpenBrowser(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): boolean;
34
35
  export declare function openBrowser(url: string): Promise<void>;
36
+ export declare function buildOpenBrowserCommand(url: string, platform: NodeJS.Platform): [string, string[]];
35
37
  export declare function exchangeCodeForTokens(client: SsoClient, code: string, redirectUri: string, verifier: string): Promise<SsoTokens>;
36
38
  export declare function refreshSsoAccessToken(client: SsoClient, refreshToken: string): Promise<string>;
package/dist/auth/sso.js CHANGED
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
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;
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
4
  const node_crypto_1 = require("node:crypto");
5
5
  const node_http_1 = require("node:http");
6
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.
7
9
  exports.LOOPBACK_PORT = 7731;
8
10
  exports.LOOPBACK_CALLBACK_URL = `http://localhost:${exports.LOOPBACK_PORT}/callback`;
9
11
  const BROWSER_SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000;
@@ -12,7 +14,7 @@ async function fetchSsoDomainCheck(email, apiGateway) {
12
14
  const domain = email.split('@').pop().toLowerCase();
13
15
  const response = await fetch(`${apiGateway}/sso-login/domain-check/${encodeURIComponent(domain)}`);
14
16
  if (!response.ok) {
15
- throw new Error(`SSO lookup for ${domain} failed (${response.status}).`);
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 });
16
18
  }
17
19
  const body = await response.text();
18
20
  if (!body) {
@@ -22,25 +24,27 @@ async function fetchSsoDomainCheck(email, apiGateway) {
22
24
  return identityProvider ? { kind: 'cognito', identityProvider } : { kind: 'legacy' };
23
25
  }
24
26
  exports.fetchSsoDomainCheck = fetchSsoDomainCheck;
25
- function createPkceChallenge() {
27
+ function createSignInAttempt() {
28
+ // RFC 7636 needs a 43-128 character verifier: 32 random bytes encode to 43.
26
29
  const verifier = (0, node_crypto_1.randomBytes)(32).toString('base64url');
27
30
  return {
28
31
  verifier,
29
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.
30
34
  state: (0, node_crypto_1.randomBytes)(16).toString('base64url'),
31
35
  };
32
36
  }
33
- exports.createPkceChallenge = createPkceChallenge;
34
- function buildAuthorizeUrl(client, identityProvider, redirectUri, pkce) {
37
+ exports.createSignInAttempt = createSignInAttempt;
38
+ function buildAuthorizeUrl(client, identityProvider, redirectUri, signInAttempt) {
35
39
  const params = new URLSearchParams({
36
40
  response_type: 'code',
37
41
  client_id: client.clientId,
38
42
  redirect_uri: redirectUri,
39
43
  scope: OAUTH_SCOPES.join(' '),
40
44
  identity_provider: identityProvider,
41
- code_challenge: pkce.challenge,
45
+ code_challenge: signInAttempt.challenge,
42
46
  code_challenge_method: 'S256',
43
- state: pkce.state,
47
+ state: signInAttempt.state,
44
48
  });
45
49
  return `${client.domain}/oauth2/authorize?${params}`;
46
50
  }
@@ -48,7 +52,7 @@ exports.buildAuthorizeUrl = buildAuthorizeUrl;
48
52
  function parsePastedSignInCode(pasted, expectedState) {
49
53
  const [code, state] = pasted.trim().split('#');
50
54
  if (!code || state !== expectedState) {
51
- throw new Error('That sign-in code is not from this login attempt. Run the command again.');
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.');
52
56
  }
53
57
  return code;
54
58
  }
@@ -78,32 +82,40 @@ function listenForLoopbackCode(expectedState) {
78
82
  : 'Sign-in failed. Return to your terminal.';
79
83
  response
80
84
  .writeHead(signedIn ? 200 : 400, { 'Content-Type': 'text/plain', Connection: 'close' })
81
- .end(page, () => stopListening(() => {
85
+ .end(page, () => stopListening(request.socket, () => {
82
86
  if (error) {
83
- rejectCode(new Error(`SSO sign-in failed: ${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 }));
84
88
  }
85
89
  else if (!signedIn) {
86
- rejectCode(new Error('SSO sign-in returned an unexpected response. Run the command again.'));
90
+ rejectCode(new sign_in_error_1.SignInError('SSO_UNEXPECTED_CALLBACK', 'SSO sign-in returned an unexpected response. Run the command again.'));
87
91
  }
88
92
  else {
89
93
  resolveCode(receivedCode);
90
94
  }
91
95
  }));
92
96
  });
93
- const timeout = setTimeout(() => stopListening(() => rejectCode(new Error('Timed out waiting for the browser sign-in.'))), BROWSER_SIGN_IN_TIMEOUT_MS);
94
- function stopListening(settle) {
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) {
95
104
  clearTimeout(timeout);
96
105
  server.close();
106
+ openSockets.forEach((socket) => socket !== respondingSocket && socket.destroy());
97
107
  settle();
98
108
  }
99
109
  return new Promise((resolve, reject) => {
100
110
  server.once('error', (error) => {
101
111
  clearTimeout(timeout);
102
- reject(error.code === 'EADDRINUSE'
103
- ? new Error(`Port ${exports.LOOPBACK_PORT} is in use. Run contrail login --no-browser instead.`)
104
- : error);
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 }));
105
117
  });
106
- server.listen(exports.LOOPBACK_PORT, 'localhost', () => resolve({ code }));
118
+ server.listen(exports.LOOPBACK_PORT, 'localhost', () => resolve({ code, stop: () => stopListening(undefined, () => undefined) }));
107
119
  });
108
120
  }
109
121
  exports.listenForLoopbackCode = listenForLoopbackCode;
@@ -134,6 +146,7 @@ function buildOpenBrowserCommand(url, platform) {
134
146
  }
135
147
  return ['xdg-open', [url]];
136
148
  }
149
+ exports.buildOpenBrowserCommand = buildOpenBrowserCommand;
137
150
  async function exchangeCodeForTokens(client, code, redirectUri, verifier) {
138
151
  const tokens = await postToTokenEndpoint(client, {
139
152
  grant_type: 'authorization_code',
@@ -162,7 +175,10 @@ async function postToTokenEndpoint(client, form) {
162
175
  });
163
176
  const body = await response.json();
164
177
  if (!response.ok) {
165
- throw new Error(`SSO token request failed (${response.status} ${body.error}).`);
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
+ });
166
182
  }
167
183
  return body;
168
184
  }
@@ -1,15 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const node_crypto_1 = require("node:crypto");
4
+ const node_net_1 = require("node:net");
4
5
  const sso_1 = require("./sso");
5
6
  const ssoClient = {
6
7
  domain: 'https://dev-vibeiq.auth.us-east-1.amazoncognito.com',
7
8
  clientId: 'cli-client',
8
9
  };
9
- describe('createPkceChallenge', () => {
10
+ describe('createSignInAttempt', () => {
10
11
  it('should derive the challenge as the base64url SHA-256 of the verifier', () => {
11
- const pkce = (0, sso_1.createPkceChallenge)();
12
- expect(pkce.challenge).toBe((0, node_crypto_1.createHash)('sha256').update(pkce.verifier).digest('base64url'));
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);
13
17
  });
14
18
  });
15
19
  describe('buildAuthorizeUrl', () => {
@@ -37,10 +41,10 @@ describe('parsePastedSignInCode', () => {
37
41
  expect((0, sso_1.parsePastedSignInCode)(' the-code#the-state \n', 'the-state')).toBe('the-code');
38
42
  });
39
43
  it('should reject a code from another attempt', () => {
40
- expect(() => (0, sso_1.parsePastedSignInCode)('the-code#other-state', 'the-state')).toThrow('That sign-in code is not from this login attempt.');
44
+ expect(() => (0, sso_1.parsePastedSignInCode)('the-code#other-state', 'the-state')).toThrow(expect.objectContaining({ code: 'SSO_SIGN_IN_CODE_MISMATCH' }));
41
45
  });
42
46
  it('should reject a code pasted without its state', () => {
43
- expect(() => (0, sso_1.parsePastedSignInCode)('the-code', 'the-state')).toThrow('That sign-in code is not from this login attempt.');
47
+ expect(() => (0, sso_1.parsePastedSignInCode)('the-code', 'the-state')).toThrow(expect.objectContaining({ code: 'SSO_SIGN_IN_CODE_MISMATCH' }));
44
48
  });
45
49
  });
46
50
  describe('canOpenBrowser', () => {
@@ -87,7 +91,10 @@ describe('fetchSsoDomainCheck', () => {
87
91
  });
88
92
  it('should fail when the lookup fails', async () => {
89
93
  stubDomainCheckFetch('{}', 502);
90
- await expect((0, sso_1.fetchSsoDomainCheck)('dev@example.com', 'https://api')).rejects.toThrow('SSO lookup for example.com failed (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
+ });
91
98
  });
92
99
  });
93
100
  describe('listenForLoopbackCode', () => {
@@ -106,23 +113,66 @@ describe('listenForLoopbackCode', () => {
106
113
  });
107
114
  it('should reject a redirect for this attempt that carries no code', async () => {
108
115
  const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
109
- const rejection = expect(listener.code).rejects.toThrow('SSO sign-in returned an unexpected response.');
116
+ const rejection = expect(listener.code).rejects.toMatchObject({
117
+ code: 'SSO_UNEXPECTED_CALLBACK',
118
+ });
110
119
  const response = await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?state=the-state`);
111
120
  expect(response.status).toBe(400);
112
121
  await rejection;
113
122
  });
114
123
  it('should reject when the identity provider reports an error', async () => {
115
124
  const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
116
- const rejection = expect(listener.code).rejects.toThrow('SSO sign-in failed: User cancelled');
125
+ const rejection = expect(listener.code).rejects.toMatchObject({
126
+ code: 'SSO_SIGN_IN_REJECTED',
127
+ details: { oauthError: 'User cancelled' },
128
+ });
117
129
  await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?error=access_denied&error_description=User%20cancelled&state=the-state`);
118
130
  await rejection;
119
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
+ });
120
141
  it('should tell the user to paste a code instead when the port is taken', async () => {
121
142
  const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
122
- await expect((0, sso_1.listenForLoopbackCode)('another-state')).rejects.toThrow('Port 7731 is in use. Run contrail login --no-browser instead.');
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
+ });
123
147
  await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
124
148
  await listener.code;
125
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
+ });
126
176
  });
127
177
  describe('exchangeCodeForTokens', () => {
128
178
  const originalFetch = global.fetch;
@@ -133,6 +183,9 @@ describe('exchangeCodeForTokens', () => {
133
183
  global.fetch = jest
134
184
  .fn()
135
185
  .mockResolvedValue(new Response(JSON.stringify({ error: 'invalid_grant' }), { status: 400 }));
136
- await expect((0, sso_1.exchangeCodeForTokens)(ssoClient, 'the-code', sso_1.LOOPBACK_CALLBACK_URL, 'verifier')).rejects.toThrow('SSO token request failed (400 invalid_grant).');
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
+ });
137
190
  });
138
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
  }
@@ -3,11 +3,12 @@ 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");
6
7
  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");
11
+ const sign_in_error_1 = require("./auth/sign-in-error");
11
12
  const baseFlags_1 = require("./baseFlags");
12
13
  class BaseCommand extends core_1.Command {
13
14
  static description = 'Global Flags';
@@ -48,11 +49,17 @@ class BaseCommand extends core_1.Command {
48
49
  logger_1.default.level = config.logLevel;
49
50
  }
50
51
  }
52
+ async catch(error) {
53
+ if (error instanceof sign_in_error_1.SignInError) {
54
+ this.error((0, sign_in_error_1.formatErrorForTerminal)(error), { exit: 1 });
55
+ }
56
+ return super.catch(error);
57
+ }
51
58
  async confirmEnv() {
52
59
  let config = await (0, config_1.getConfig)();
53
60
  if ((0, lodash_1.keys)(config).length === 0) {
54
61
  await (0, login_1.authUser)().catch((e) => {
55
- console.log(`Error: ${e.message}\n\nCheck if you are using the correct environment configuration and credentials.`);
62
+ console.log(`Error: ${(0, sign_in_error_1.formatErrorForTerminal)(e)}\n\nCheck if you are using the correct environment configuration and credentials.`);
56
63
  this.exit(1);
57
64
  });
58
65
  config = await (0, config_1.getConfig)();
@@ -73,7 +80,7 @@ class BaseCommand extends core_1.Command {
73
80
  choices: ['yes', 'no'],
74
81
  default: 'no',
75
82
  });
76
- const { confirm } = await inquirer_1.default.prompt(questions);
83
+ const { confirm } = await (0, common_1.promptOnStderr)(questions);
77
84
  if (confirm === 'no') {
78
85
  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
86
  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
- logger_1.default.info(`App API key: (app:${answers.appApiKey})`);
38
+ this.log(`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
- logger_1.default.info(`App API key: (app:${appFound.apiKey.apiKey})`);
46
+ this.log(`App API key: (app:${appFound.apiKey.apiKey})`);
47
47
  }
48
48
  }
49
49
  }
@@ -11,7 +11,7 @@ const upgrade_1 = require("./upgrade");
11
11
  const basecommand_1 = require("../../basecommand");
12
12
  const logger_1 = tslib_1.__importDefault(require("../../logger"));
13
13
  class PublishApp extends basecommand_1.BaseCommand {
14
- static description = 'Publish the app to the marketplace. This visibility of your app depends on the app.yml configuration ("visibility" property)';
14
+ static description = 'Publish the app to the marketplace. This visibility of your app depends on the app.yml configuration ("visibility" property). A pre-release version (e.g. "1.4.0-alpha.1") is published without becoming the latest version of the app.';
15
15
  static examples = [
16
16
  `$ contrail app publish
17
17
  `,
@@ -0,0 +1,11 @@
1
+ import { BaseCommand } from '../../../basecommand';
2
+ export default class AppPrereleaseVersionUpgrade extends BaseCommand {
3
+ skipConfirmEnv: boolean;
4
+ static description: string;
5
+ static examples: string[];
6
+ static flags: {
7
+ alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
8
+ logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
9
+ };
10
+ run(): Promise<void>;
11
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const load_app_config_1 = require("../../../helpers/app/load-app-config");
5
+ const basecommand_1 = require("../../../basecommand");
6
+ const logger_1 = tslib_1.__importDefault(require("../../../logger"));
7
+ const update_app_config_1 = require("../../../helpers/app/update-app-config");
8
+ const upgrade_version_1 = require("../../../helpers/app/upgrade-version");
9
+ class AppPrereleaseVersionUpgrade extends basecommand_1.BaseCommand {
10
+ skipConfirmEnv = true;
11
+ static description = 'Upgrade the Pre-release app version. A stable version becomes the first alpha of the next patch (1.2.3 to 1.2.4-alpha.0). A pre-release version gets its number bumped (1.2.4-alpha.0 to 1.2.4-alpha.1).';
12
+ static examples = [
13
+ `$ contrail app version prerelease
14
+ `,
15
+ ];
16
+ static flags = {
17
+ ...basecommand_1.BaseCommand.baseFlags,
18
+ };
19
+ async run() {
20
+ try {
21
+ const appDeclaration = (0, load_app_config_1.loadAppConfig)({ skipValidation: true });
22
+ logger_1.default.info(`Upgrading Pre-release Version for ${appDeclaration.version}`);
23
+ const version = (0, upgrade_version_1.upgradeVersion)(appDeclaration.version, 'prerelease');
24
+ (0, update_app_config_1.updateAppConfig)({ ...appDeclaration, version });
25
+ logger_1.default.info(`Pre-release Version Upgraded to ${version}`);
26
+ }
27
+ catch (e) {
28
+ logger_1.default.error(`Application Pre-release Version Upgrade Failed: ${e}`);
29
+ }
30
+ }
31
+ }
32
+ exports.default = AppPrereleaseVersionUpgrade;