@contrail/cli 3.6.0-alpha-8-alpha.694fd70 → 3.6.0-alpha.aae3e70
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 +167 -93
- package/dist/auth/login.spec.js +305 -0
- package/dist/auth/sso.d.ts +36 -0
- package/dist/auth/sso.js +164 -0
- package/dist/auth/sso.spec.js +119 -0
- package/dist/basecommand.d.ts +1 -3
- package/dist/basecommand.js +2 -2
- 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 -3
- package/dist/common.js +1 -13
- 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 +1 -18
- 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 -48
- package/dist/commands/entities/create.js +0 -639
- package/dist/commands/entities/create.spec.js +0 -541
- package/dist/commands/entities/delete.d.ts +0 -19
- package/dist/commands/entities/delete.js +0 -134
- package/dist/commands/entities/get.d.ts +0 -24
- package/dist/commands/entities/get.js +0 -273
- 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 -31
- package/dist/commands/entities/update.js +0 -157
- package/dist/helpers/entities/assortment-items.d.ts +0 -10
- package/dist/helpers/entities/assortment-items.js +0 -84
- 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,19 +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
6
|
const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
|
|
7
7
|
const sdk_1 = require("@contrail/sdk");
|
|
8
8
|
const config_1 = require("../helpers/config/config");
|
|
9
9
|
const logger_1 = tslib_1.__importDefault(require("../logger"));
|
|
10
|
+
const sso_1 = require("./sso");
|
|
10
11
|
const path_1 = tslib_1.__importDefault(require("path"));
|
|
11
12
|
const fs_1 = tslib_1.__importDefault(require("fs"));
|
|
12
|
-
const
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
+
},
|
|
17
33
|
};
|
|
18
34
|
async function authUser() {
|
|
19
35
|
logger_1.default.debug('authorizing user...');
|
|
@@ -38,28 +54,84 @@ async function authUser() {
|
|
|
38
54
|
};
|
|
39
55
|
(0, sdk_1.setConfig)(sdk_1.Auth.config);
|
|
40
56
|
try {
|
|
41
|
-
|
|
42
|
-
return await refreshCurrentUserOrg().catch(async () => {
|
|
43
|
-
await (0, common_1.delay)(100);
|
|
44
|
-
return await refreshCurrentUserOrg().catch(async () => {
|
|
45
|
-
await (0, common_1.delay)(1000);
|
|
46
|
-
return await refreshCurrentUserOrg();
|
|
47
|
-
});
|
|
48
|
-
});
|
|
57
|
+
return await signInWithStoredTokens(config.signInMethod ?? 'password');
|
|
49
58
|
}
|
|
50
59
|
catch (e) {
|
|
60
|
+
logger_1.default.debug(`stored tokens rejected: ${e?.message}`);
|
|
51
61
|
if (isNetworkConnectionError(e)) {
|
|
52
62
|
logger_1.default.error("Encountered a network connection issue. Please ensure you're connected to the internet and try again");
|
|
53
63
|
process.exit(1);
|
|
54
64
|
}
|
|
55
|
-
logger_1.default.info(
|
|
65
|
+
logger_1.default.info('Token expired. Requesting auth credentials...');
|
|
56
66
|
}
|
|
57
67
|
}
|
|
58
|
-
|
|
59
|
-
await (0, config_1.storeConfig)(authContext);
|
|
60
|
-
return authContext;
|
|
68
|
+
return await signIn({ openBrowser: true });
|
|
61
69
|
}
|
|
62
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
|
+
}
|
|
63
135
|
async function getOrgSlug(config) {
|
|
64
136
|
const orgSlug = config?.orgSlug || process.env.CONTRAIL_CLI_ORG_SLUG;
|
|
65
137
|
if (!orgSlug) {
|
|
@@ -76,54 +148,28 @@ async function getOrgSlug(config) {
|
|
|
76
148
|
return orgSlug;
|
|
77
149
|
}
|
|
78
150
|
async function authenticateWithApiKey(config, apiKey, orgSlug) {
|
|
79
|
-
const apiGateway = config
|
|
151
|
+
const apiGateway = getApiGateway(config);
|
|
80
152
|
sdk_1.Auth.config = {
|
|
81
153
|
apiUserToken: apiKey,
|
|
82
|
-
apiRefreshToken:
|
|
154
|
+
apiRefreshToken: null,
|
|
83
155
|
apiGateway,
|
|
84
156
|
orgSlug,
|
|
85
157
|
};
|
|
86
158
|
(0, sdk_1.setConfig)(sdk_1.Auth.config);
|
|
87
159
|
await (0, sdk_1.getCurrentUser)();
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
const
|
|
93
|
-
if (!process.env.CONTRAIL_CLI_EMAIL) {
|
|
94
|
-
questions.push({
|
|
95
|
-
type: 'input',
|
|
96
|
-
name: 'email',
|
|
97
|
-
validate: (val) => !!val,
|
|
98
|
-
message: 'Email',
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
if (!process.env.CONTRAIL_CLI_PASSWORD) {
|
|
102
|
-
questions.push({
|
|
103
|
-
type: 'password',
|
|
104
|
-
name: 'password',
|
|
105
|
-
validate: (val) => !!val,
|
|
106
|
-
message: 'Password',
|
|
107
|
-
});
|
|
108
|
-
}
|
|
109
|
-
const answers = await inquirer_1.default.prompt(questions);
|
|
110
|
-
const params = {
|
|
111
|
-
email: process.env.CONTRAIL_CLI_EMAIL || answers.email,
|
|
112
|
-
password: process.env.CONTRAIL_CLI_PASSWORD || answers.password,
|
|
113
|
-
orgSlug: await getOrgSlug(config),
|
|
114
|
-
...(config?.apiGateway && { apiGateway: config.apiGateway }),
|
|
115
|
-
};
|
|
116
|
-
if (!params.email || !params.password) {
|
|
117
|
-
throw new Error('Email and Password required');
|
|
118
|
-
}
|
|
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());
|
|
119
165
|
const poolData = {
|
|
120
|
-
UserPoolId:
|
|
121
|
-
ClientId:
|
|
166
|
+
UserPoolId: cognitoConfig.userPoolId,
|
|
167
|
+
ClientId: cognitoConfig.clientId,
|
|
122
168
|
};
|
|
123
169
|
const userPool = new amazon_cognito_identity_js_1.CognitoUserPool(poolData);
|
|
124
170
|
const authData = {
|
|
125
171
|
Username: params.email,
|
|
126
|
-
Password:
|
|
172
|
+
Password: password,
|
|
127
173
|
};
|
|
128
174
|
const authDetails = new amazon_cognito_identity_js_1.AuthenticationDetails(authData);
|
|
129
175
|
const userData = {
|
|
@@ -134,64 +180,82 @@ async function authenticateWithUsernamePassword(config) {
|
|
|
134
180
|
return new Promise((resolve, reject) => {
|
|
135
181
|
cognitoUser.authenticateUser(authDetails, {
|
|
136
182
|
onSuccess: async (result) => {
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
183
|
+
try {
|
|
184
|
+
resolve(await setAuthContext(result, params));
|
|
185
|
+
}
|
|
186
|
+
catch (e) {
|
|
187
|
+
reject(e);
|
|
188
|
+
}
|
|
140
189
|
},
|
|
141
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
|
+
}
|
|
142
195
|
reject(err);
|
|
143
196
|
},
|
|
144
197
|
});
|
|
145
198
|
});
|
|
146
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
|
+
}
|
|
147
206
|
async function setAuthContext(user, params) {
|
|
148
|
-
const apiGateway = params
|
|
149
|
-
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
|
|
150
210
|
sdk_1.Auth.config = {
|
|
151
211
|
apiUserToken: vibeAccessToken,
|
|
152
212
|
apiRefreshToken: vibeRefreshToken,
|
|
153
213
|
apiGateway,
|
|
154
214
|
orgSlug: params.orgSlug,
|
|
155
215
|
};
|
|
216
|
+
// SET SDK CONFIG
|
|
156
217
|
(0, sdk_1.setConfig)(sdk_1.Auth.config);
|
|
157
218
|
return refreshCurrentUserOrg();
|
|
158
219
|
}
|
|
159
|
-
async function
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
}
|
|
167
|
-
throw e;
|
|
168
|
-
});
|
|
169
|
-
if (!currentUser) {
|
|
170
|
-
const config = await (0, config_1.getConfig)();
|
|
171
|
-
try {
|
|
172
|
-
const newVibeAccessToken = await requestRefreshedAccessToken(config.apiRefreshToken, config.apiGateway);
|
|
173
|
-
sdk_1.Auth.config = {
|
|
174
|
-
apiUserToken: newVibeAccessToken,
|
|
175
|
-
apiRefreshToken: config.apiRefreshToken,
|
|
176
|
-
apiGateway: config.apiGateway,
|
|
177
|
-
orgSlug: config.orgSlug,
|
|
178
|
-
};
|
|
179
|
-
(0, sdk_1.setConfig)(sdk_1.Auth.config);
|
|
180
|
-
}
|
|
181
|
-
catch (e) {
|
|
182
|
-
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;
|
|
183
227
|
}
|
|
184
|
-
|
|
228
|
+
logger_1.default.debug('access token rejected, refreshing it...');
|
|
229
|
+
await refreshAccessToken(signInMethod);
|
|
230
|
+
await (0, sdk_1.getCurrentUser)();
|
|
185
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)();
|
|
186
237
|
// TODO: To uncomment when telemetry backend is developed.
|
|
187
238
|
// const current_Version = getVersionFromPackageJson();
|
|
188
239
|
// await checkTelemetry(current_Version);
|
|
189
|
-
return
|
|
240
|
+
return returnAndStoreConfig(sdk_1.Auth.config, 'password');
|
|
190
241
|
}
|
|
191
|
-
function
|
|
192
|
-
|
|
242
|
+
async function refreshAccessToken(signInMethod) {
|
|
243
|
+
const newAccessToken = await requestAccessTokenForSignInMethod(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 requestAccessTokenForSignInMethod(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);
|
|
193
254
|
}
|
|
194
|
-
|
|
255
|
+
function getApiGateway(config) {
|
|
256
|
+
return config?.apiGateway ?? DEFAULT_API_GATEWAY;
|
|
257
|
+
}
|
|
258
|
+
async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiGateway, environment) {
|
|
195
259
|
const url = `${apiGateway}/auth/cognito/`;
|
|
196
260
|
const response = await fetch(url, {
|
|
197
261
|
method: 'POST',
|
|
@@ -201,9 +265,11 @@ async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiG
|
|
|
201
265
|
},
|
|
202
266
|
body: JSON.stringify({ accessToken: cognitoAccessToken }),
|
|
203
267
|
});
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
}
|
|
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 };
|
|
207
273
|
}
|
|
208
274
|
async function requestRefreshedAccessToken(vibeRefreshToken, apiGateway) {
|
|
209
275
|
const url = `${apiGateway}/auth/jwt_refresh/`;
|
|
@@ -215,9 +281,12 @@ async function requestRefreshedAccessToken(vibeRefreshToken, apiGateway) {
|
|
|
215
281
|
},
|
|
216
282
|
body: JSON.stringify({ refreshToken: vibeRefreshToken }),
|
|
217
283
|
});
|
|
284
|
+
if (!response.ok) {
|
|
285
|
+
throw new Error(`Token refresh failed with status ${response.status}`);
|
|
286
|
+
}
|
|
218
287
|
const data = await response.json();
|
|
219
|
-
if (!
|
|
220
|
-
throw new Error(
|
|
288
|
+
if (!data.accessToken) {
|
|
289
|
+
throw new Error('Token refresh response did not contain an access token');
|
|
221
290
|
}
|
|
222
291
|
return data.accessToken;
|
|
223
292
|
}
|
|
@@ -232,6 +301,11 @@ function getVersionFromPackageJson() {
|
|
|
232
301
|
return packageJson.version;
|
|
233
302
|
}
|
|
234
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
|
+
}
|
|
235
309
|
function isNetworkConnectionError(e) {
|
|
236
310
|
const cause = e?.cause;
|
|
237
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)();
|