@contrail/cli 3.6.0-alpha-8-alpha.2ab4f80 → 3.6.0-alpha.693d785
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -151
- package/dist/api/feature-flags.d.ts +3 -0
- package/dist/api/feature-flags.js +29 -0
- package/dist/api/types.d.ts +0 -35
- package/dist/api/types.js +1 -49
- package/dist/api/users.d.ts +1 -0
- package/dist/api/users.js +10 -1
- package/dist/auth/login.d.ts +4 -0
- package/dist/auth/login.js +169 -94
- package/dist/auth/login.spec.js +305 -0
- package/dist/auth/sso.d.ts +36 -0
- package/dist/auth/sso.js +168 -0
- package/dist/auth/sso.spec.js +138 -0
- package/dist/basecommand.d.ts +1 -3
- package/dist/basecommand.js +4 -4
- package/dist/commands/app/getApiKey.js +2 -2
- package/dist/commands/config/set.js +1 -1
- package/dist/commands/feature-flags/export.d.ts +19 -0
- package/dist/commands/feature-flags/export.js +66 -0
- package/dist/commands/feature-flags/export.spec.js +109 -0
- package/dist/commands/feature-flags/import.d.ts +42 -0
- package/dist/commands/feature-flags/import.js +191 -0
- package/dist/commands/feature-flags/import.spec.js +194 -0
- package/dist/commands/instance/export.d.ts +9 -0
- package/dist/commands/instance/export.js +18 -3
- package/dist/commands/instance/export.spec.js +32 -0
- package/dist/commands/instance/import.d.ts +3 -0
- package/dist/commands/instance/import.js +5 -0
- package/dist/commands/instance/import.spec.js +4 -0
- package/dist/commands/login.d.ts +12 -0
- package/dist/commands/login.js +25 -0
- package/dist/common.d.ts +1 -4
- package/dist/common.js +1 -18
- package/dist/helpers/config/config.d.ts +5 -4
- package/dist/helpers/config/config.js +10 -12
- package/dist/helpers/file-helpers.d.ts +0 -1
- package/dist/helpers/file-helpers.js +3 -20
- package/dist/logger.js +1 -4
- package/node_modules/@contrail/entity-compare/package.json +3 -6
- package/node_modules/@contrail/loader/lib/common/conditional-columns.js +1 -1
- package/node_modules/@contrail/loader/lib/constants.d.ts +8 -0
- package/node_modules/@contrail/loader/lib/constants.js +9 -1
- package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.d.ts +4 -0
- package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.js +57 -0
- package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.spec.js +492 -34
- package/node_modules/@contrail/loader/lib/pipeline/validate.js +2 -52
- package/node_modules/@contrail/loader/lib/pipeline/validate.spec.js +0 -85
- package/node_modules/@contrail/loader/package.json +2 -2
- package/node_modules/@contrail/sdk/.github/workflows/publish-to-npm.yml +4 -1
- package/node_modules/@contrail/sdk/lib/auth/login.js +1 -1
- package/node_modules/@contrail/sdk/lib/config/config.d.ts +0 -3
- package/node_modules/@contrail/sdk/lib/config/config.js +7 -13
- package/node_modules/@contrail/sdk/lib/core/request.js +2 -6
- package/node_modules/@contrail/sdk/lib/entities/entities.client.d.ts +0 -2
- package/node_modules/@contrail/sdk/lib/entities/entities.client.js +1 -3
- package/node_modules/@contrail/sdk/lib/entities/entity.resource.registry.js +0 -1
- package/node_modules/@contrail/sdk/package.json +1 -1
- package/oclif.manifest.json +75 -365
- package/package.json +15 -5
- package/dist/commands/entities/create.d.ts +0 -49
- package/dist/commands/entities/create.js +0 -643
- package/dist/commands/entities/create.spec.js +0 -545
- package/dist/commands/entities/delete.d.ts +0 -20
- package/dist/commands/entities/delete.js +0 -137
- package/dist/commands/entities/get.d.ts +0 -25
- package/dist/commands/entities/get.js +0 -276
- package/dist/commands/entities/grammar.spec.js +0 -80
- package/dist/commands/entities/output.spec.js +0 -72
- package/dist/commands/entities/update.d.ts +0 -32
- package/dist/commands/entities/update.js +0 -160
- package/dist/helpers/entities/assortment-items.d.ts +0 -12
- package/dist/helpers/entities/assortment-items.js +0 -87
- package/dist/helpers/entities/batchFetch.d.ts +0 -8
- package/dist/helpers/entities/batchFetch.js +0 -49
- package/dist/helpers/entities/index.d.ts +0 -3
- package/dist/helpers/entities/index.js +0 -6
- package/dist/helpers/entities/items.d.ts +0 -10
- package/dist/helpers/entities/items.js +0 -102
- package/dist/helpers/entities/project-items.d.ts +0 -3
- package/dist/helpers/entities/project-items.js +0 -65
- package/dist/helpers/propertySpecifications/dateRanges.d.ts +0 -38
- package/dist/helpers/propertySpecifications/dateRanges.js +0 -89
- package/dist/helpers/propertySpecifications/dateRanges.spec.js +0 -95
- package/dist/helpers/propertySpecifications/propertySpecifications.d.ts +0 -40
- package/dist/helpers/propertySpecifications/propertySpecifications.js +0 -109
- package/dist/helpers/propertySpecifications/propertySpecifications.spec.d.ts +0 -1
- package/dist/helpers/propertySpecifications/propertySpecifications.spec.js +0 -373
- package/dist/logger.spec.d.ts +0 -1
- package/dist/logger.spec.js +0 -12
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/.github/pull_request_template.md +0 -31
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/.github/workflows/check-code-formatting.yml +0 -34
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/.github/workflows/empty.yml +0 -10
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/.github/workflows/generate-sdk-docs.yml +0 -32
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/.github/workflows/publish-to-npm.yml +0 -117
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/.github/workflows/sdk-lib.yml +0 -27
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/.prettierrc.yaml +0 -2
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/README.md +0 -72
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/home-hero.svg +0 -11
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/assets/assets.d.ts +0 -9
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/assets/assets.js +0 -54
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/assets/index.d.ts +0 -1
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/assets/index.js +0 -17
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/auth/auth.d.ts +0 -10
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/auth/auth.js +0 -6
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/auth/index.d.ts +0 -2
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/auth/index.js +0 -18
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/auth/login.d.ts +0 -10
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/auth/login.js +0 -209
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/config/config.d.ts +0 -48
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/config/config.js +0 -42
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/config/index.d.ts +0 -1
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/config/index.js +0 -17
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/content/content.d.ts +0 -12
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/content/content.js +0 -70
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/content/index.d.ts +0 -1
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/content/index.js +0 -17
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/core/index.d.ts +0 -1
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/core/index.js +0 -17
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/core/request.d.ts +0 -15
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/core/request.js +0 -241
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/entities/entities.client.d.ts +0 -101
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/entities/entities.client.js +0 -306
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/entities/entity-reference-expander.d.ts +0 -9
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/entities/entity-reference-expander.js +0 -86
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/entities/entity-reference.d.ts +0 -6
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/entities/entity-reference.js +0 -19
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/entities/entity.resource.registry.d.ts +0 -5
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/entities/entity.resource.registry.js +0 -59
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/entities/index.d.ts +0 -3
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/entities/index.js +0 -19
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/files/file-type-helper.d.ts +0 -3
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/files/file-type-helper.js +0 -24
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/files/files.d.ts +0 -19
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/files/files.js +0 -151
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/files/index.d.ts +0 -1
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/files/index.js +0 -17
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/index.d.ts +0 -10
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/index.js +0 -26
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/notifications/index.d.ts +0 -1
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/notifications/index.js +0 -17
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/notifications/notifications-dispatcher.d.ts +0 -16
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/notifications/notifications-dispatcher.js +0 -37
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/policies/index.d.ts +0 -1
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/policies/index.js +0 -17
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/policies/policies-cache.d.ts +0 -12
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/policies/policies-cache.js +0 -55
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/policies/policies.client.d.ts +0 -9
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/policies/policies.client.js +0 -74
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/types/index.d.ts +0 -2
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/types/index.js +0 -18
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/types/sub-types-helper.d.ts +0 -18
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/types/sub-types-helper.js +0 -98
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/types/types-cache.d.ts +0 -19
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/types/types-cache.js +0 -73
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/types/types.client.d.ts +0 -42
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/types/types.client.js +0 -217
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/package.json +0 -64
- package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/scripts/replicate-bug.js +0 -69
- package/node_modules/@contrail/sdk/scripts/replicate-bug.js +0 -69
- /package/dist/{commands/entities/create.spec.d.ts → auth/sso.spec.d.ts} +0 -0
- /package/dist/commands/{entities/grammar.spec.d.ts → feature-flags/export.spec.d.ts} +0 -0
- /package/dist/commands/{entities/output.spec.d.ts → feature-flags/import.spec.d.ts} +0 -0
- /package/dist/{helpers/propertySpecifications/dateRanges.spec.d.ts → commands/instance/export.spec.d.ts} +0 -0
package/dist/auth/login.js
CHANGED
|
@@ -1,18 +1,35 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getVersionFromPackageJson = exports.authUser = void 0;
|
|
3
|
+
exports.getVersionFromPackageJson = exports.signIn = exports.authUser = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const amazon_cognito_identity_js_1 = require("amazon-cognito-identity-js");
|
|
6
|
+
const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
|
|
6
7
|
const sdk_1 = require("@contrail/sdk");
|
|
7
8
|
const config_1 = require("../helpers/config/config");
|
|
8
9
|
const logger_1 = tslib_1.__importDefault(require("../logger"));
|
|
10
|
+
const sso_1 = require("./sso");
|
|
9
11
|
const path_1 = tslib_1.__importDefault(require("path"));
|
|
10
12
|
const fs_1 = tslib_1.__importDefault(require("fs"));
|
|
11
|
-
const
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
const DEFAULT_API_GATEWAY = config_1.ENVIRONMENTS.prod;
|
|
14
|
+
const COGNITO_CONFIGS = {
|
|
15
|
+
dev: {
|
|
16
|
+
userPoolId: 'us-east-1_e2cA0nJWu',
|
|
17
|
+
clientId: '209s9c62o165cqab0fu5ihjtu9',
|
|
18
|
+
sso: {
|
|
19
|
+
domain: 'https://dev-vibeiq.auth.us-east-1.amazoncognito.com',
|
|
20
|
+
clientId: '4nrd626t15ukbertqmcngfnom3',
|
|
21
|
+
pastedCodeCallbackUrl: 'https://login.dev.vibeiq.com/cli',
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
prod: {
|
|
25
|
+
userPoolId: 'us-east-1_qIaNZdUfm',
|
|
26
|
+
clientId: '7knkt34gfacbgd0ghnuspefdfg',
|
|
27
|
+
sso: {
|
|
28
|
+
domain: 'https://prod-vibeiq.auth.us-east-1.amazoncognito.com',
|
|
29
|
+
clientId: 'PROD_CLI_CLIENT_ID',
|
|
30
|
+
pastedCodeCallbackUrl: 'https://login.vibeiq.com/cli',
|
|
31
|
+
},
|
|
32
|
+
},
|
|
16
33
|
};
|
|
17
34
|
async function authUser() {
|
|
18
35
|
logger_1.default.debug('authorizing user...');
|
|
@@ -37,32 +54,88 @@ async function authUser() {
|
|
|
37
54
|
};
|
|
38
55
|
(0, sdk_1.setConfig)(sdk_1.Auth.config);
|
|
39
56
|
try {
|
|
40
|
-
|
|
41
|
-
return await refreshCurrentUserOrg().catch(async () => {
|
|
42
|
-
await (0, common_1.delay)(100);
|
|
43
|
-
return await refreshCurrentUserOrg().catch(async () => {
|
|
44
|
-
await (0, common_1.delay)(1000);
|
|
45
|
-
return await refreshCurrentUserOrg();
|
|
46
|
-
});
|
|
47
|
-
});
|
|
57
|
+
return await signInWithStoredTokens(config.signInMethod ?? 'password');
|
|
48
58
|
}
|
|
49
59
|
catch (e) {
|
|
60
|
+
logger_1.default.debug(`stored tokens rejected: ${e?.message}`);
|
|
50
61
|
if (isNetworkConnectionError(e)) {
|
|
51
62
|
logger_1.default.error("Encountered a network connection issue. Please ensure you're connected to the internet and try again");
|
|
52
63
|
process.exit(1);
|
|
53
64
|
}
|
|
54
|
-
logger_1.default.info(
|
|
65
|
+
logger_1.default.info('Token expired. Requesting auth credentials...');
|
|
55
66
|
}
|
|
56
67
|
}
|
|
57
|
-
|
|
58
|
-
await (0, config_1.storeConfig)(authContext);
|
|
59
|
-
return authContext;
|
|
68
|
+
return await signIn({ openBrowser: true });
|
|
60
69
|
}
|
|
61
70
|
exports.authUser = authUser;
|
|
71
|
+
async function signIn(options) {
|
|
72
|
+
const config = await (0, config_1.getConfig)();
|
|
73
|
+
const apiGateway = getApiGateway(config);
|
|
74
|
+
const environment = (0, config_1.findEnvironmentName)(apiGateway);
|
|
75
|
+
if (!environment) {
|
|
76
|
+
throw new Error(`No Cognito user pool is known for ${apiGateway}. Sign-in works for ${Object.keys(COGNITO_CONFIGS).join(' and ')}; use CONTRAIL_CLI_API_KEY for other environments.`);
|
|
77
|
+
}
|
|
78
|
+
const email = process.env.CONTRAIL_CLI_EMAIL || (await promptForEmail());
|
|
79
|
+
const params = {
|
|
80
|
+
email,
|
|
81
|
+
orgSlug: await getOrgSlug(config),
|
|
82
|
+
apiGateway,
|
|
83
|
+
environment,
|
|
84
|
+
};
|
|
85
|
+
if (process.env.CONTRAIL_CLI_PASSWORD) {
|
|
86
|
+
return authenticateWithUsernamePassword(params);
|
|
87
|
+
}
|
|
88
|
+
const domainCheck = await (0, sso_1.fetchSsoDomainCheck)(email, apiGateway);
|
|
89
|
+
if (domainCheck.kind === 'cognito') {
|
|
90
|
+
return signInWithSso(params, domainCheck.identityProvider, options);
|
|
91
|
+
}
|
|
92
|
+
if (domainCheck.kind === 'legacy') {
|
|
93
|
+
logger_1.default.info('The CLI does not support your SSO provider yet. Sign in with your VibeIQ password, or set CONTRAIL_CLI_API_KEY.');
|
|
94
|
+
}
|
|
95
|
+
return authenticateWithUsernamePassword(params);
|
|
96
|
+
}
|
|
97
|
+
exports.signIn = signIn;
|
|
98
|
+
async function promptForEmail() {
|
|
99
|
+
const answers = await inquirer_1.default.prompt([
|
|
100
|
+
{ type: 'input', name: 'email', validate: (val) => !!val, message: 'Email' },
|
|
101
|
+
]);
|
|
102
|
+
return answers.email;
|
|
103
|
+
}
|
|
104
|
+
async function signInWithSso(params, identityProvider, options) {
|
|
105
|
+
const ssoClient = COGNITO_CONFIGS[params.environment].sso;
|
|
106
|
+
const pkce = (0, sso_1.createPkceChallenge)();
|
|
107
|
+
const usesLoopback = options.openBrowser && (0, sso_1.canOpenBrowser)();
|
|
108
|
+
const redirectUri = usesLoopback ? sso_1.LOOPBACK_CALLBACK_URL : ssoClient.pastedCodeCallbackUrl;
|
|
109
|
+
const authorizeUrl = (0, sso_1.buildAuthorizeUrl)(ssoClient, identityProvider, redirectUri, pkce);
|
|
110
|
+
let code;
|
|
111
|
+
if (usesLoopback) {
|
|
112
|
+
const loopbackListener = await (0, sso_1.listenForLoopbackCode)(pkce.state);
|
|
113
|
+
logger_1.default.info(`Opening your browser to sign in. If it does not open, visit:\n${authorizeUrl}`);
|
|
114
|
+
await (0, sso_1.openBrowser)(authorizeUrl).catch(() => logger_1.default.info('Could not open a browser. Open the URL above to sign in.'));
|
|
115
|
+
code = await loopbackListener.code;
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
logger_1.default.info(`Open this URL in any browser to sign in:\n${authorizeUrl}`);
|
|
119
|
+
const answers = await inquirer_1.default.prompt([
|
|
120
|
+
{ type: 'input', name: 'signInCode', validate: (val) => !!val, message: 'Sign-in code' },
|
|
121
|
+
]);
|
|
122
|
+
code = (0, sso_1.parsePastedSignInCode)(answers.signInCode, pkce.state);
|
|
123
|
+
}
|
|
124
|
+
const tokens = await (0, sso_1.exchangeCodeForTokens)(ssoClient, code, redirectUri, pkce.verifier);
|
|
125
|
+
sdk_1.Auth.config = {
|
|
126
|
+
apiUserToken: tokens.accessToken,
|
|
127
|
+
apiRefreshToken: tokens.refreshToken,
|
|
128
|
+
apiGateway: params.apiGateway,
|
|
129
|
+
orgSlug: params.orgSlug,
|
|
130
|
+
};
|
|
131
|
+
(0, sdk_1.setConfig)(sdk_1.Auth.config);
|
|
132
|
+
await (0, sdk_1.getCurrentUser)();
|
|
133
|
+
return returnAndStoreConfig(sdk_1.Auth.config, 'sso');
|
|
134
|
+
}
|
|
62
135
|
async function getOrgSlug(config) {
|
|
63
136
|
const orgSlug = config?.orgSlug || process.env.CONTRAIL_CLI_ORG_SLUG;
|
|
64
137
|
if (!orgSlug) {
|
|
65
|
-
const answers = await
|
|
138
|
+
const answers = await inquirer_1.default.prompt([
|
|
66
139
|
{
|
|
67
140
|
type: 'input',
|
|
68
141
|
name: 'orgSlug',
|
|
@@ -75,54 +148,28 @@ async function getOrgSlug(config) {
|
|
|
75
148
|
return orgSlug;
|
|
76
149
|
}
|
|
77
150
|
async function authenticateWithApiKey(config, apiKey, orgSlug) {
|
|
78
|
-
const apiGateway = config
|
|
151
|
+
const apiGateway = getApiGateway(config);
|
|
79
152
|
sdk_1.Auth.config = {
|
|
80
153
|
apiUserToken: apiKey,
|
|
81
|
-
apiRefreshToken:
|
|
154
|
+
apiRefreshToken: null,
|
|
82
155
|
apiGateway,
|
|
83
156
|
orgSlug,
|
|
84
157
|
};
|
|
85
158
|
(0, sdk_1.setConfig)(sdk_1.Auth.config);
|
|
86
159
|
await (0, sdk_1.getCurrentUser)();
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const
|
|
92
|
-
if (!process.env.CONTRAIL_CLI_EMAIL) {
|
|
93
|
-
questions.push({
|
|
94
|
-
type: 'input',
|
|
95
|
-
name: 'email',
|
|
96
|
-
validate: (val) => !!val,
|
|
97
|
-
message: 'Email',
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
if (!process.env.CONTRAIL_CLI_PASSWORD) {
|
|
101
|
-
questions.push({
|
|
102
|
-
type: 'password',
|
|
103
|
-
name: 'password',
|
|
104
|
-
validate: (val) => !!val,
|
|
105
|
-
message: 'Password',
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
const answers = await (0, common_1.promptOnStderr)(questions);
|
|
109
|
-
const params = {
|
|
110
|
-
email: process.env.CONTRAIL_CLI_EMAIL || answers.email,
|
|
111
|
-
password: process.env.CONTRAIL_CLI_PASSWORD || answers.password,
|
|
112
|
-
orgSlug: await getOrgSlug(config),
|
|
113
|
-
...(config?.apiGateway && { apiGateway: config.apiGateway }),
|
|
114
|
-
};
|
|
115
|
-
if (!params.email || !params.password) {
|
|
116
|
-
throw new Error('Email and Password required');
|
|
117
|
-
}
|
|
160
|
+
return returnAndStoreConfig(sdk_1.Auth.config);
|
|
161
|
+
}
|
|
162
|
+
async function authenticateWithUsernamePassword(params) {
|
|
163
|
+
const cognitoConfig = COGNITO_CONFIGS[params.environment];
|
|
164
|
+
const password = process.env.CONTRAIL_CLI_PASSWORD || (await promptForPassword());
|
|
118
165
|
const poolData = {
|
|
119
|
-
UserPoolId:
|
|
120
|
-
ClientId:
|
|
166
|
+
UserPoolId: cognitoConfig.userPoolId,
|
|
167
|
+
ClientId: cognitoConfig.clientId,
|
|
121
168
|
};
|
|
122
169
|
const userPool = new amazon_cognito_identity_js_1.CognitoUserPool(poolData);
|
|
123
170
|
const authData = {
|
|
124
171
|
Username: params.email,
|
|
125
|
-
Password:
|
|
172
|
+
Password: password,
|
|
126
173
|
};
|
|
127
174
|
const authDetails = new amazon_cognito_identity_js_1.AuthenticationDetails(authData);
|
|
128
175
|
const userData = {
|
|
@@ -133,64 +180,82 @@ async function authenticateWithUsernamePassword(config) {
|
|
|
133
180
|
return new Promise((resolve, reject) => {
|
|
134
181
|
cognitoUser.authenticateUser(authDetails, {
|
|
135
182
|
onSuccess: async (result) => {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
183
|
+
try {
|
|
184
|
+
resolve(await setAuthContext(result, params));
|
|
185
|
+
}
|
|
186
|
+
catch (e) {
|
|
187
|
+
reject(e);
|
|
188
|
+
}
|
|
139
189
|
},
|
|
140
190
|
onFailure: (err) => {
|
|
191
|
+
if (err?.code === 'ResourceNotFoundException') {
|
|
192
|
+
reject(new Error(`This version of the CLI has outdated ${params.environment} sign-in settings (${err.message}). Update the CLI: npm i -g @contrail/cli`));
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
141
195
|
reject(err);
|
|
142
196
|
},
|
|
143
197
|
});
|
|
144
198
|
});
|
|
145
199
|
}
|
|
200
|
+
async function promptForPassword() {
|
|
201
|
+
const answers = await inquirer_1.default.prompt([
|
|
202
|
+
{ type: 'password', name: 'password', validate: (val) => !!val, message: 'Password' },
|
|
203
|
+
]);
|
|
204
|
+
return answers.password;
|
|
205
|
+
}
|
|
146
206
|
async function setAuthContext(user, params) {
|
|
147
|
-
const apiGateway = params
|
|
148
|
-
const { vibeAccessToken, vibeRefreshToken } = await getVibeAccessTokenFromCognitoAccessToken(user.idToken.jwtToken, apiGateway);
|
|
207
|
+
const apiGateway = params.apiGateway;
|
|
208
|
+
const { vibeAccessToken, vibeRefreshToken } = await getVibeAccessTokenFromCognitoAccessToken(user.idToken.jwtToken, apiGateway, params.environment);
|
|
209
|
+
// Set Auth Config
|
|
149
210
|
sdk_1.Auth.config = {
|
|
150
211
|
apiUserToken: vibeAccessToken,
|
|
151
212
|
apiRefreshToken: vibeRefreshToken,
|
|
152
213
|
apiGateway,
|
|
153
214
|
orgSlug: params.orgSlug,
|
|
154
215
|
};
|
|
216
|
+
// SET SDK CONFIG
|
|
155
217
|
(0, sdk_1.setConfig)(sdk_1.Auth.config);
|
|
156
218
|
return refreshCurrentUserOrg();
|
|
157
219
|
}
|
|
158
|
-
async function
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
}
|
|
166
|
-
throw e;
|
|
167
|
-
});
|
|
168
|
-
if (!currentUser) {
|
|
169
|
-
const config = await (0, config_1.getConfig)();
|
|
170
|
-
try {
|
|
171
|
-
const newVibeAccessToken = await requestRefreshedAccessToken(config.apiRefreshToken, config.apiGateway);
|
|
172
|
-
sdk_1.Auth.config = {
|
|
173
|
-
apiUserToken: newVibeAccessToken,
|
|
174
|
-
apiRefreshToken: config.apiRefreshToken,
|
|
175
|
-
apiGateway: config.apiGateway,
|
|
176
|
-
orgSlug: config.orgSlug,
|
|
177
|
-
};
|
|
178
|
-
(0, sdk_1.setConfig)(sdk_1.Auth.config);
|
|
179
|
-
}
|
|
180
|
-
catch (e) {
|
|
181
|
-
throw Error(`Could not get refresh token: ${e}`);
|
|
220
|
+
async function signInWithStoredTokens(signInMethod) {
|
|
221
|
+
try {
|
|
222
|
+
await (0, sdk_1.getCurrentUser)();
|
|
223
|
+
}
|
|
224
|
+
catch (e) {
|
|
225
|
+
if (isNetworkConnectionError(e)) {
|
|
226
|
+
throw e;
|
|
182
227
|
}
|
|
183
|
-
|
|
228
|
+
logger_1.default.debug('access token rejected, refreshing it...');
|
|
229
|
+
await refreshAccessToken(signInMethod);
|
|
230
|
+
await (0, sdk_1.getCurrentUser)();
|
|
184
231
|
}
|
|
232
|
+
return returnAndStoreConfig(sdk_1.Auth.config);
|
|
233
|
+
}
|
|
234
|
+
async function refreshCurrentUserOrg() {
|
|
235
|
+
logger_1.default.debug('refreshing current user org...');
|
|
236
|
+
await (0, sdk_1.getCurrentUser)();
|
|
185
237
|
// TODO: To uncomment when telemetry backend is developed.
|
|
186
238
|
// const current_Version = getVersionFromPackageJson();
|
|
187
239
|
// await checkTelemetry(current_Version);
|
|
188
|
-
return
|
|
240
|
+
return returnAndStoreConfig(sdk_1.Auth.config, 'password');
|
|
189
241
|
}
|
|
190
|
-
function
|
|
191
|
-
|
|
242
|
+
async function refreshAccessToken(signInMethod) {
|
|
243
|
+
const newAccessToken = await fetchRefreshedAccessTokenForSignInMethod(signInMethod);
|
|
244
|
+
sdk_1.Auth.config = { ...sdk_1.Auth.config, apiUserToken: newAccessToken };
|
|
245
|
+
(0, sdk_1.setConfig)(sdk_1.Auth.config);
|
|
246
|
+
}
|
|
247
|
+
async function fetchRefreshedAccessTokenForSignInMethod(signInMethod) {
|
|
248
|
+
const { apiRefreshToken, apiGateway } = sdk_1.Auth.config;
|
|
249
|
+
if (signInMethod === 'sso') {
|
|
250
|
+
const ssoClient = COGNITO_CONFIGS[(0, config_1.findEnvironmentName)(apiGateway)].sso;
|
|
251
|
+
return (0, sso_1.refreshSsoAccessToken)(ssoClient, apiRefreshToken);
|
|
252
|
+
}
|
|
253
|
+
return requestRefreshedAccessToken(apiRefreshToken, apiGateway);
|
|
192
254
|
}
|
|
193
|
-
|
|
255
|
+
function getApiGateway(config) {
|
|
256
|
+
return config?.apiGateway ?? DEFAULT_API_GATEWAY;
|
|
257
|
+
}
|
|
258
|
+
async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiGateway, environment) {
|
|
194
259
|
const url = `${apiGateway}/auth/cognito/`;
|
|
195
260
|
const response = await fetch(url, {
|
|
196
261
|
method: 'POST',
|
|
@@ -200,9 +265,11 @@ async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiG
|
|
|
200
265
|
},
|
|
201
266
|
body: JSON.stringify({ accessToken: cognitoAccessToken }),
|
|
202
267
|
});
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
}
|
|
268
|
+
if (!response.ok) {
|
|
269
|
+
throw new Error(`${environment} rejected the sign-in (${response.status}).`);
|
|
270
|
+
}
|
|
271
|
+
const data = await response.json();
|
|
272
|
+
return { vibeAccessToken: data.accessToken, vibeRefreshToken: data.refreshToken };
|
|
206
273
|
}
|
|
207
274
|
async function requestRefreshedAccessToken(vibeRefreshToken, apiGateway) {
|
|
208
275
|
const url = `${apiGateway}/auth/jwt_refresh/`;
|
|
@@ -214,9 +281,12 @@ async function requestRefreshedAccessToken(vibeRefreshToken, apiGateway) {
|
|
|
214
281
|
},
|
|
215
282
|
body: JSON.stringify({ refreshToken: vibeRefreshToken }),
|
|
216
283
|
});
|
|
284
|
+
if (!response.ok) {
|
|
285
|
+
throw new Error(`Token refresh failed with status ${response.status}`);
|
|
286
|
+
}
|
|
217
287
|
const data = await response.json();
|
|
218
|
-
if (!
|
|
219
|
-
throw new Error(
|
|
288
|
+
if (!data.accessToken) {
|
|
289
|
+
throw new Error('Token refresh response did not contain an access token');
|
|
220
290
|
}
|
|
221
291
|
return data.accessToken;
|
|
222
292
|
}
|
|
@@ -231,6 +301,11 @@ function getVersionFromPackageJson() {
|
|
|
231
301
|
return packageJson.version;
|
|
232
302
|
}
|
|
233
303
|
exports.getVersionFromPackageJson = getVersionFromPackageJson;
|
|
304
|
+
async function returnAndStoreConfig(config, signInMethod) {
|
|
305
|
+
const configCopy = Object.assign({}, config);
|
|
306
|
+
await (0, config_1.storeConfig)(signInMethod ? { ...configCopy, signInMethod } : configCopy);
|
|
307
|
+
return configCopy;
|
|
308
|
+
}
|
|
234
309
|
function isNetworkConnectionError(e) {
|
|
235
310
|
const cause = e?.cause;
|
|
236
311
|
return cause?.code === 'ENOTFOUND' || cause?.code === 'ECONNREFUSED';
|
package/dist/auth/login.spec.js
CHANGED
|
@@ -1,6 +1,311 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const tslib_1 = require("tslib");
|
|
4
|
+
const amazon_cognito_identity_js_1 = require("amazon-cognito-identity-js");
|
|
5
|
+
const sdk_1 = require("@contrail/sdk");
|
|
6
|
+
const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
|
|
7
|
+
const config_1 = require("../helpers/config/config");
|
|
8
|
+
const logger_1 = tslib_1.__importDefault(require("../logger"));
|
|
3
9
|
const login_1 = require("./login");
|
|
10
|
+
const mockAuthenticateUser = jest.fn();
|
|
11
|
+
jest.mock('amazon-cognito-identity-js', () => ({
|
|
12
|
+
CognitoUserPool: jest.fn(),
|
|
13
|
+
AuthenticationDetails: jest.fn(),
|
|
14
|
+
CognitoUser: jest.fn().mockImplementation(() => ({
|
|
15
|
+
authenticateUser: (details, callbacks) => mockAuthenticateUser(details, callbacks),
|
|
16
|
+
})),
|
|
17
|
+
}));
|
|
18
|
+
jest.mock('@contrail/sdk', () => ({
|
|
19
|
+
Auth: { config: {} },
|
|
20
|
+
getCurrentUser: jest.fn(),
|
|
21
|
+
setConfig: jest.fn(),
|
|
22
|
+
}));
|
|
23
|
+
jest.mock('../helpers/config/config', () => ({
|
|
24
|
+
...jest.requireActual('../helpers/config/config'),
|
|
25
|
+
getConfig: jest.fn(),
|
|
26
|
+
storeConfig: jest.fn(),
|
|
27
|
+
}));
|
|
28
|
+
jest.mock('../logger', () => ({
|
|
29
|
+
__esModule: true,
|
|
30
|
+
default: { debug: jest.fn(), info: jest.fn(), error: jest.fn() },
|
|
31
|
+
}));
|
|
32
|
+
const DEV_GATEWAY = 'https://api.dev.vibeiq.com/dev/api';
|
|
33
|
+
function restoreEnv(name, value) {
|
|
34
|
+
if (value === undefined) {
|
|
35
|
+
delete process.env[name];
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
process.env[name] = value;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function jsonResponse(status, body = {}) {
|
|
42
|
+
return new Response(JSON.stringify(body), { status });
|
|
43
|
+
}
|
|
44
|
+
describe('authUser with email and password', () => {
|
|
45
|
+
const originalFetch = global.fetch;
|
|
46
|
+
const originalEmail = process.env.CONTRAIL_CLI_EMAIL;
|
|
47
|
+
const originalPassword = process.env.CONTRAIL_CLI_PASSWORD;
|
|
48
|
+
let fetchMock;
|
|
49
|
+
beforeEach(() => {
|
|
50
|
+
jest.clearAllMocks();
|
|
51
|
+
process.env.CONTRAIL_CLI_EMAIL = 'dev@vibeiq.com';
|
|
52
|
+
process.env.CONTRAIL_CLI_PASSWORD = 'secret';
|
|
53
|
+
config_1.getConfig.mockResolvedValue({ apiGateway: DEV_GATEWAY, orgSlug: 'adam-zone-1' });
|
|
54
|
+
sdk_1.getCurrentUser.mockResolvedValue({ id: 'user-1' });
|
|
55
|
+
mockAuthenticateUser.mockImplementation((_details, callbacks) => callbacks.onSuccess({ idToken: { jwtToken: 'cognito-id-token' } }));
|
|
56
|
+
fetchMock = jest.fn();
|
|
57
|
+
global.fetch = fetchMock;
|
|
58
|
+
});
|
|
59
|
+
afterEach(() => {
|
|
60
|
+
global.fetch = originalFetch;
|
|
61
|
+
restoreEnv('CONTRAIL_CLI_EMAIL', originalEmail);
|
|
62
|
+
restoreEnv('CONTRAIL_CLI_PASSWORD', originalPassword);
|
|
63
|
+
});
|
|
64
|
+
it('should sign in through the dev pool when the config points at dev', async () => {
|
|
65
|
+
fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
|
|
66
|
+
const context = await (0, login_1.authUser)();
|
|
67
|
+
expect(amazon_cognito_identity_js_1.CognitoUserPool).toHaveBeenCalledWith({
|
|
68
|
+
UserPoolId: 'us-east-1_e2cA0nJWu',
|
|
69
|
+
ClientId: '209s9c62o165cqab0fu5ihjtu9',
|
|
70
|
+
});
|
|
71
|
+
expect(context).toEqual({
|
|
72
|
+
apiUserToken: 'vibe-access',
|
|
73
|
+
apiRefreshToken: 'vibe-refresh',
|
|
74
|
+
apiGateway: DEV_GATEWAY,
|
|
75
|
+
orgSlug: 'adam-zone-1',
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
it('should sign in through the prod pool when the config points at prod', async () => {
|
|
79
|
+
config_1.getConfig.mockResolvedValue({
|
|
80
|
+
apiGateway: 'https://api.vibeiq.com/prod/api',
|
|
81
|
+
orgSlug: 'adam-zone-1',
|
|
82
|
+
});
|
|
83
|
+
fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
|
|
84
|
+
await (0, login_1.authUser)();
|
|
85
|
+
expect(amazon_cognito_identity_js_1.CognitoUserPool).toHaveBeenCalledWith({
|
|
86
|
+
UserPoolId: 'us-east-1_qIaNZdUfm',
|
|
87
|
+
ClientId: '7knkt34gfacbgd0ghnuspefdfg',
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
it('should match the dev pool despite a trailing slash or different case in the gateway', async () => {
|
|
91
|
+
config_1.getConfig.mockResolvedValue({
|
|
92
|
+
apiGateway: 'https://API.dev.vibeiq.com/dev/api/',
|
|
93
|
+
orgSlug: 'adam-zone-1',
|
|
94
|
+
});
|
|
95
|
+
fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
|
|
96
|
+
await (0, login_1.authUser)();
|
|
97
|
+
expect(amazon_cognito_identity_js_1.CognitoUserPool).toHaveBeenCalledWith({
|
|
98
|
+
UserPoolId: 'us-east-1_e2cA0nJWu',
|
|
99
|
+
ClientId: '209s9c62o165cqab0fu5ihjtu9',
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
it('should explain an unknown gateway even when it has no scheme', async () => {
|
|
103
|
+
config_1.getConfig.mockResolvedValue({
|
|
104
|
+
apiGateway: 'api.dev.vibeiq.com/dev/api',
|
|
105
|
+
orgSlug: 'adam-zone-1',
|
|
106
|
+
});
|
|
107
|
+
await expect((0, login_1.authUser)()).rejects.toThrow('No Cognito user pool is known for api.dev.vibeiq.com/dev/api.');
|
|
108
|
+
});
|
|
109
|
+
it('should fail without saving tokens when no pool is known for the environment', async () => {
|
|
110
|
+
config_1.getConfig.mockResolvedValue({
|
|
111
|
+
apiGateway: 'http://localhost:3000/api',
|
|
112
|
+
orgSlug: 'adam-zone-1',
|
|
113
|
+
});
|
|
114
|
+
await expect((0, login_1.authUser)()).rejects.toThrow('No Cognito user pool is known for http://localhost:3000/api.');
|
|
115
|
+
expect(config_1.storeConfig).not.toHaveBeenCalled();
|
|
116
|
+
});
|
|
117
|
+
it('should tell the user to update the CLI when its Cognito client or pool no longer exists', async () => {
|
|
118
|
+
mockAuthenticateUser.mockImplementation((_details, callbacks) => callbacks.onFailure({
|
|
119
|
+
code: 'ResourceNotFoundException',
|
|
120
|
+
message: 'User pool client 209s9c62o165cqab0fu5ihjtu9 does not exist.',
|
|
121
|
+
}));
|
|
122
|
+
await expect((0, login_1.authUser)()).rejects.toThrow('This version of the CLI has outdated dev sign-in settings (User pool client 209s9c62o165cqab0fu5ihjtu9 does not exist.). Update the CLI: npm i -g @contrail/cli');
|
|
123
|
+
expect(config_1.storeConfig).not.toHaveBeenCalled();
|
|
124
|
+
});
|
|
125
|
+
it('should fail without saving tokens when the environment rejects the sign-in', async () => {
|
|
126
|
+
fetchMock.mockResolvedValueOnce(jsonResponse(401, { message: 'Unauthorized' }));
|
|
127
|
+
await expect((0, login_1.authUser)()).rejects.toThrow('dev rejected the sign-in (401).');
|
|
128
|
+
expect(config_1.storeConfig).not.toHaveBeenCalled();
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
describe('authUser with stored tokens', () => {
|
|
132
|
+
const originalFetch = global.fetch;
|
|
133
|
+
const originalEmail = process.env.CONTRAIL_CLI_EMAIL;
|
|
134
|
+
const originalPassword = process.env.CONTRAIL_CLI_PASSWORD;
|
|
135
|
+
const storedConfig = {
|
|
136
|
+
apiUserToken: 'expired-access',
|
|
137
|
+
apiRefreshToken: 'stored-refresh',
|
|
138
|
+
apiGateway: DEV_GATEWAY,
|
|
139
|
+
orgSlug: 'adam-zone-1',
|
|
140
|
+
};
|
|
141
|
+
let acceptedTokens;
|
|
142
|
+
let fetchMock;
|
|
143
|
+
let exitSpy;
|
|
144
|
+
function acceptOnlyTokensGivenToTheSdk() {
|
|
145
|
+
sdk_1.getCurrentUser.mockImplementation(async () => {
|
|
146
|
+
const token = sdk_1.setConfig.mock.calls.at(-1)?.[0]?.apiUserToken;
|
|
147
|
+
if (!acceptedTokens.includes(token)) {
|
|
148
|
+
throw new Error('Failed to fetch current user. Unauthorized');
|
|
149
|
+
}
|
|
150
|
+
return { id: 'user-1' };
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
beforeEach(() => {
|
|
154
|
+
jest.clearAllMocks();
|
|
155
|
+
process.env.CONTRAIL_CLI_EMAIL = 'dev@vibeiq.com';
|
|
156
|
+
process.env.CONTRAIL_CLI_PASSWORD = 'secret';
|
|
157
|
+
config_1.getConfig.mockResolvedValue(storedConfig);
|
|
158
|
+
acceptedTokens = ['refreshed-access', 'vibe-access'];
|
|
159
|
+
acceptOnlyTokensGivenToTheSdk();
|
|
160
|
+
mockAuthenticateUser.mockImplementation((_details, callbacks) => callbacks.onSuccess({ idToken: { jwtToken: 'cognito-id-token' } }));
|
|
161
|
+
fetchMock = jest.fn();
|
|
162
|
+
global.fetch = fetchMock;
|
|
163
|
+
});
|
|
164
|
+
afterEach(() => {
|
|
165
|
+
exitSpy?.mockRestore();
|
|
166
|
+
global.fetch = originalFetch;
|
|
167
|
+
restoreEnv('CONTRAIL_CLI_EMAIL', originalEmail);
|
|
168
|
+
restoreEnv('CONTRAIL_CLI_PASSWORD', originalPassword);
|
|
169
|
+
});
|
|
170
|
+
it('should refresh an expired access token without asking for a password', async () => {
|
|
171
|
+
fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'refreshed-access' }));
|
|
172
|
+
const context = await (0, login_1.authUser)();
|
|
173
|
+
expect(fetchMock).toHaveBeenCalledWith(`${DEV_GATEWAY}/auth/jwt_refresh/`, expect.objectContaining({ body: JSON.stringify({ refreshToken: 'stored-refresh' }) }));
|
|
174
|
+
expect(context).toEqual({ ...storedConfig, apiUserToken: 'refreshed-access' });
|
|
175
|
+
expect(config_1.storeConfig).toHaveBeenCalledWith(context);
|
|
176
|
+
});
|
|
177
|
+
it('should keep a still-valid access token without refreshing it', async () => {
|
|
178
|
+
acceptedTokens = ['expired-access'];
|
|
179
|
+
const context = await (0, login_1.authUser)();
|
|
180
|
+
expect(context).toEqual(storedConfig);
|
|
181
|
+
});
|
|
182
|
+
it('should fall back to the password sign-in when the refresh token is rejected', async () => {
|
|
183
|
+
fetchMock
|
|
184
|
+
.mockResolvedValueOnce(jsonResponse(401, { message: 'Unauthorized' }))
|
|
185
|
+
.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
|
|
186
|
+
const context = await (0, login_1.authUser)();
|
|
187
|
+
expect(context).toEqual({
|
|
188
|
+
...storedConfig,
|
|
189
|
+
apiUserToken: 'vibe-access',
|
|
190
|
+
apiRefreshToken: 'vibe-refresh',
|
|
191
|
+
});
|
|
192
|
+
});
|
|
193
|
+
it('should report a rejected password sign-in without refreshing the token it was just issued', async () => {
|
|
194
|
+
config_1.getConfig.mockResolvedValue({ apiGateway: DEV_GATEWAY, orgSlug: 'adam-zone-1' });
|
|
195
|
+
acceptedTokens = [];
|
|
196
|
+
fetchMock
|
|
197
|
+
.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }))
|
|
198
|
+
.mockResolvedValueOnce(jsonResponse(400, { message: 'Bad Request' }));
|
|
199
|
+
await expect((0, login_1.authUser)()).rejects.toThrow('Failed to fetch current user. Unauthorized');
|
|
200
|
+
expect(config_1.storeConfig).not.toHaveBeenCalled();
|
|
201
|
+
});
|
|
202
|
+
it('should exit with a connection error instead of prompting when the network is down', async () => {
|
|
203
|
+
const networkError = Object.assign(new TypeError('fetch failed'), {
|
|
204
|
+
cause: { code: 'ENOTFOUND' },
|
|
205
|
+
});
|
|
206
|
+
sdk_1.getCurrentUser.mockRejectedValue(networkError);
|
|
207
|
+
exitSpy = jest.spyOn(process, 'exit').mockImplementation((code) => {
|
|
208
|
+
throw new Error(`exit ${code}`);
|
|
209
|
+
});
|
|
210
|
+
await expect((0, login_1.authUser)()).rejects.toThrow('exit 1');
|
|
211
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
212
|
+
expect(mockAuthenticateUser).not.toHaveBeenCalled();
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
describe('signIn with SSO', () => {
|
|
216
|
+
const originalFetch = global.fetch;
|
|
217
|
+
const originalEmail = process.env.CONTRAIL_CLI_EMAIL;
|
|
218
|
+
const originalPassword = process.env.CONTRAIL_CLI_PASSWORD;
|
|
219
|
+
const DEV_COGNITO_DOMAIN = 'https://dev-vibeiq.auth.us-east-1.amazoncognito.com';
|
|
220
|
+
let fetchMock;
|
|
221
|
+
let promptSpy;
|
|
222
|
+
function pasteCodeFromPrintedSignInUrl() {
|
|
223
|
+
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]);
|
|
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
|
+
promptSpy = jest.spyOn(inquirer_1.default, 'prompt');
|
|
236
|
+
pasteCodeFromPrintedSignInUrl();
|
|
237
|
+
fetchMock = jest.fn();
|
|
238
|
+
global.fetch = fetchMock;
|
|
239
|
+
});
|
|
240
|
+
afterEach(() => {
|
|
241
|
+
promptSpy.mockRestore();
|
|
242
|
+
global.fetch = originalFetch;
|
|
243
|
+
restoreEnv('CONTRAIL_CLI_EMAIL', originalEmail);
|
|
244
|
+
restoreEnv('CONTRAIL_CLI_PASSWORD', originalPassword);
|
|
245
|
+
});
|
|
246
|
+
it('should sign in through the domain identity provider with a pasted code', async () => {
|
|
247
|
+
fetchMock
|
|
248
|
+
.mockResolvedValueOnce(jsonResponse(200, { identityProvider: 'sso-vibeiq-com' }))
|
|
249
|
+
.mockResolvedValueOnce(jsonResponse(200, { access_token: 'cognito-access', refresh_token: 'cognito-refresh' }));
|
|
250
|
+
const context = await (0, login_1.signIn)({ openBrowser: false });
|
|
251
|
+
expect(fetchMock.mock.calls[0][0]).toBe(`${DEV_GATEWAY}/sso-login/domain-check/vibeiq.com`);
|
|
252
|
+
const [tokenUrl, tokenRequest] = fetchMock.mock.calls[1];
|
|
253
|
+
const tokenForm = new URLSearchParams(tokenRequest.body);
|
|
254
|
+
expect(tokenUrl).toBe(`${DEV_COGNITO_DOMAIN}/oauth2/token`);
|
|
255
|
+
expect(tokenForm.get('code')).toBe('pasted-code');
|
|
256
|
+
expect(tokenForm.get('redirect_uri')).toBe('https://login.dev.vibeiq.com/cli');
|
|
257
|
+
expect(context).toEqual({
|
|
258
|
+
apiUserToken: 'cognito-access',
|
|
259
|
+
apiRefreshToken: 'cognito-refresh',
|
|
260
|
+
apiGateway: DEV_GATEWAY,
|
|
261
|
+
orgSlug: 'adam-zone-1',
|
|
262
|
+
});
|
|
263
|
+
expect(config_1.storeConfig).toHaveBeenCalledWith({ ...context, signInMethod: 'sso' });
|
|
264
|
+
});
|
|
265
|
+
it('should reject a pasted code from a different sign-in attempt without saving tokens', async () => {
|
|
266
|
+
fetchMock.mockResolvedValueOnce(jsonResponse(200, { identityProvider: 'sso-vibeiq-com' }));
|
|
267
|
+
promptSpy.mockResolvedValue({ signInCode: 'pasted-code#another-state' });
|
|
268
|
+
await expect((0, login_1.signIn)({ openBrowser: false })).rejects.toThrow('That sign-in code is not from this login attempt.');
|
|
269
|
+
expect(config_1.storeConfig).not.toHaveBeenCalled();
|
|
270
|
+
});
|
|
271
|
+
it('should ask for a password when the email domain has no SSO', async () => {
|
|
272
|
+
fetchMock
|
|
273
|
+
.mockResolvedValueOnce(new Response('', { status: 200 }))
|
|
274
|
+
.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
|
|
275
|
+
promptSpy.mockResolvedValue({ password: 'secret' });
|
|
276
|
+
const context = await (0, login_1.signIn)({ openBrowser: false });
|
|
277
|
+
expect(mockAuthenticateUser).toHaveBeenCalled();
|
|
278
|
+
expect(context.apiUserToken).toBe('vibe-access');
|
|
279
|
+
expect(config_1.storeConfig).toHaveBeenCalledWith({ ...context, signInMethod: 'password' });
|
|
280
|
+
});
|
|
281
|
+
it('should ask for a password when the email domain uses SSO the CLI cannot open', async () => {
|
|
282
|
+
fetchMock
|
|
283
|
+
.mockResolvedValueOnce(jsonResponse(200, { identityProvider: '', url: 'legacy' }))
|
|
284
|
+
.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
|
|
285
|
+
promptSpy.mockResolvedValue({ password: 'secret' });
|
|
286
|
+
const context = await (0, login_1.signIn)({ openBrowser: false });
|
|
287
|
+
expect(context.apiUserToken).toBe('vibe-access');
|
|
288
|
+
expect(logger_1.default.info).toHaveBeenCalledWith(expect.stringContaining('The CLI does not support your SSO provider yet.'));
|
|
289
|
+
});
|
|
290
|
+
it('should refresh a stored SSO token through Cognito instead of the VibeIQ refresh endpoint', async () => {
|
|
291
|
+
config_1.getConfig.mockResolvedValue({
|
|
292
|
+
apiUserToken: 'expired-access',
|
|
293
|
+
apiRefreshToken: 'cognito-refresh',
|
|
294
|
+
apiGateway: DEV_GATEWAY,
|
|
295
|
+
orgSlug: 'adam-zone-1',
|
|
296
|
+
signInMethod: 'sso',
|
|
297
|
+
});
|
|
298
|
+
sdk_1.getCurrentUser
|
|
299
|
+
.mockRejectedValueOnce(new Error('Failed to fetch current user. Unauthorized'))
|
|
300
|
+
.mockResolvedValueOnce({ id: 'user-1' });
|
|
301
|
+
fetchMock.mockResolvedValueOnce(jsonResponse(200, { access_token: 'refreshed-access' }));
|
|
302
|
+
const context = await (0, login_1.authUser)();
|
|
303
|
+
const [tokenUrl, tokenRequest] = fetchMock.mock.calls[0];
|
|
304
|
+
expect(tokenUrl).toBe(`${DEV_COGNITO_DOMAIN}/oauth2/token`);
|
|
305
|
+
expect(new URLSearchParams(tokenRequest.body).get('refresh_token')).toBe('cognito-refresh');
|
|
306
|
+
expect(context.apiUserToken).toBe('refreshed-access');
|
|
307
|
+
});
|
|
308
|
+
});
|
|
4
309
|
describe('getVersionFromPackageJson', () => {
|
|
5
310
|
it('should return the version value from package.json', () => {
|
|
6
311
|
const version = (0, login_1.getVersionFromPackageJson)();
|