@contrail/cli 3.6.0-alpha-8-alpha.694fd70 → 3.6.0-alpha-8-alpha.351376b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +80 -58
  2. package/dist/api/feature-flags.d.ts +3 -0
  3. package/dist/api/feature-flags.js +29 -0
  4. package/dist/api/users.d.ts +1 -0
  5. package/dist/api/users.js +10 -1
  6. package/dist/auth/login.js +41 -24
  7. package/dist/auth/login.spec.js +124 -0
  8. package/dist/basecommand.js +1 -1
  9. package/dist/commands/app/getApiKey.js +2 -2
  10. package/dist/commands/entities/create.d.ts +1 -12
  11. package/dist/commands/entities/create.js +30 -93
  12. package/dist/commands/entities/create.spec.js +3 -28
  13. package/dist/commands/entities/delete.d.ts +2 -5
  14. package/dist/commands/entities/delete.js +52 -68
  15. package/dist/commands/entities/get.d.ts +0 -3
  16. package/dist/commands/entities/get.js +15 -63
  17. package/dist/commands/entities/update.d.ts +2 -14
  18. package/dist/commands/entities/update.js +44 -77
  19. package/dist/commands/feature-flags/export.d.ts +19 -0
  20. package/dist/commands/feature-flags/export.js +66 -0
  21. package/dist/commands/feature-flags/export.spec.js +109 -0
  22. package/dist/commands/feature-flags/import.d.ts +42 -0
  23. package/dist/commands/feature-flags/import.js +191 -0
  24. package/dist/commands/feature-flags/import.spec.js +194 -0
  25. package/dist/commands/instance/export.d.ts +9 -0
  26. package/dist/commands/instance/export.js +18 -3
  27. package/dist/commands/instance/export.spec.js +32 -0
  28. package/dist/commands/instance/import.d.ts +3 -0
  29. package/dist/commands/instance/import.js +5 -0
  30. package/dist/commands/instance/import.spec.js +4 -0
  31. package/dist/common.d.ts +0 -2
  32. package/dist/common.js +1 -13
  33. package/dist/helpers/config/config.d.ts +2 -0
  34. package/dist/helpers/config/config.js +6 -1
  35. package/dist/helpers/propertySpecifications/propertySpecifications.d.ts +0 -8
  36. package/dist/helpers/propertySpecifications/propertySpecifications.js +9 -21
  37. package/dist/helpers/propertySpecifications/propertySpecifications.spec.js +10 -20
  38. package/dist/logger.js +1 -4
  39. package/node_modules/@contrail/entity-compare/package.json +3 -6
  40. package/node_modules/@contrail/loader/lib/common/conditional-columns.js +1 -1
  41. package/node_modules/@contrail/loader/lib/constants.d.ts +8 -0
  42. package/node_modules/@contrail/loader/lib/constants.js +9 -1
  43. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.d.ts +4 -0
  44. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.js +57 -0
  45. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.spec.js +492 -34
  46. package/node_modules/@contrail/loader/lib/pipeline/validate.js +2 -52
  47. package/node_modules/@contrail/loader/lib/pipeline/validate.spec.js +0 -85
  48. package/node_modules/@contrail/loader/package.json +2 -2
  49. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/image-search/image-search.d.ts +34 -0
  50. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/image-search/image-search.js +42 -0
  51. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/image-search/index.d.ts +1 -0
  52. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/image-search/index.js +17 -0
  53. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/index.d.ts +1 -0
  54. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/index.js +1 -0
  55. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/package.json +1 -1
  56. package/oclif.manifest.json +137 -99
  57. package/package.json +4 -1
  58. package/dist/commands/entities/grammar.spec.js +0 -80
  59. package/dist/commands/entities/output.spec.js +0 -72
  60. package/dist/logger.spec.js +0 -12
  61. /package/dist/commands/{entities/grammar.spec.d.ts → feature-flags/export.spec.d.ts} +0 -0
  62. /package/dist/commands/{entities/output.spec.d.ts → feature-flags/import.spec.d.ts} +0 -0
  63. /package/dist/{logger.spec.d.ts → commands/instance/export.spec.d.ts} +0 -0
package/README.md CHANGED
@@ -17,7 +17,7 @@ $ npm install -g @contrail/cli
17
17
  $ contrail COMMAND
18
18
  running command...
19
19
  $ contrail (--version)
20
- @contrail/cli/3.6.0-alpha-8-alpha.694fd70 linux-x64 node-v24.21.0
20
+ @contrail/cli/3.6.0-alpha-8-alpha.351376b linux-x64 node-v24.22.1
21
21
  $ contrail --help [COMMAND]
22
22
  USAGE
23
23
  $ contrail COMMAND
@@ -52,9 +52,11 @@ To get instructions on how to set up autocomplete for your shell, run `contrail
52
52
  * [`contrail config set`](#contrail-config-set)
53
53
  * [`contrail config use [NAME]`](#contrail-config-use-name)
54
54
  * [`contrail entities create PATH`](#contrail-entities-create-path)
55
- * [`contrail entities delete ENTITYNAME [IDS]`](#contrail-entities-delete-entityname-ids)
56
- * [`contrail entities get TYPEPATH [IDS]`](#contrail-entities-get-typepath-ids)
57
- * [`contrail entities update ENTITYNAME [IDS]`](#contrail-entities-update-entityname-ids)
55
+ * [`contrail entities delete ENTITYNAME`](#contrail-entities-delete-entityname)
56
+ * [`contrail entities get TYPEPATH`](#contrail-entities-get-typepath)
57
+ * [`contrail entities update ENTITYNAME [ID]`](#contrail-entities-update-entityname-id)
58
+ * [`contrail feature-flags export`](#contrail-feature-flags-export)
59
+ * [`contrail feature-flags import`](#contrail-feature-flags-import)
58
60
  * [`contrail file upload FILELOCATION CONTENTTYPE`](#contrail-file-upload-filelocation-contenttype)
59
61
  * [`contrail groups export`](#contrail-groups-export)
60
62
  * [`contrail groups import GROUPSFILE`](#contrail-groups-import-groupsfile)
@@ -543,18 +545,17 @@ EXAMPLES
543
545
 
544
546
  ## `contrail entities create PATH`
545
547
 
546
- Create entities
548
+ (BETA) Create entities
547
549
 
548
550
  ```
549
551
  USAGE
550
552
  $ contrail entities create PATH [-l error|warn|info|debug] [-e true|false] [-n <value>] [-d] [-i <value>] [-o
551
- <value>] [-g] [-r] [-S] [--suffix <value>] [--apiVersion 1|2]
553
+ <value>] [-g] [-r] [-s]
552
554
 
553
555
  ARGUMENTS
554
556
  PATH Path of the entity type to create
555
557
 
556
558
  FLAGS
557
- -S, --skipHydrateRelationships If true, does not hydrate relationships for the created entities
558
559
  -d, --dryRun If true, does not create the entity but simulates the creation
559
560
  -e, --alwaysConfirmEnv=<option> [default: true] The Environment variables
560
561
  <options: true|false>
@@ -568,13 +569,10 @@ FLAGS
568
569
  -n, --count=<value> Number of random entities to create
569
570
  -o, --outputFile=<value> File to save the output (optional)
570
571
  -r, --readableIds If true, uses readable IDs for the created entities
571
- --apiVersion=<option> Api-Version header to send; selects the V1 or V2 variant of the endpoint
572
- <options: 1|2>
573
- --suffix=<value> Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets
574
- /<entities>/synchronous)
572
+ -s, --skipHydrateRelationships If true, does not hydrate relationships for the created entities
575
573
 
576
574
  DESCRIPTION
577
- Create entities
575
+ (BETA) Create entities
578
576
 
579
577
  EXAMPLES
580
578
  $ contrail entities create color -g -n=10 # creates 10 random colors
@@ -596,55 +594,46 @@ EXAMPLES
596
594
  $ contrail entities create color -o /tmp/colors.json -- name=Blue green=1 red=2 blue=3 # creates a color and saves the output to /tmp/colors.json
597
595
  ```
598
596
 
599
- ## `contrail entities delete ENTITYNAME [IDS]`
597
+ ## `contrail entities delete ENTITYNAME`
600
598
 
601
- Delete entities by id
599
+ (BETA) Delete an entity
602
600
 
603
601
  ```
604
602
  USAGE
605
- $ contrail entities delete ENTITYNAME [IDS] [-l error|warn|info|debug] [-e true|false] [-d] [-i <value>] [--suffix
606
- <value>] [--apiVersion 1|2]
603
+ $ contrail entities delete ENTITYNAME [-l error|warn|info|debug] [-e true|false] [-d] [-i <value>] [--id <value>]
607
604
 
608
605
  ARGUMENTS
609
606
  ENTITYNAME The name of the entity type to delete
610
- IDS One or more entity ids to delete
611
607
 
612
608
  FLAGS
613
- -d, --dryRun If true, does not delete the entities but simulates the deletion
609
+ -d, --dryRun If true, does not delete the entity but simulates the deletion
614
610
  -e, --alwaysConfirmEnv=<option> [default: true] The Environment variables
615
611
  <options: true|false>
616
- -i, --inputFile=<value> A file with a JSON array of objects; only each object's id is used. Deletes every
617
- entity in the file.
612
+ -i, --input=<value> A JSON array of objects where each object is one entity to create. Cannot be used
613
+ with --count. Unless --precise is specified, any missing values will be populated
614
+ with random values.
618
615
  -l, --logLevel=<option> The Log Level
619
616
  <options: error|warn|info|debug>
620
- --apiVersion=<option> Api-Version header to send; selects the V1 or V2 variant of the endpoint
621
- <options: 1|2>
622
- --suffix=<value> Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets
623
- /<entities>/synchronous)
617
+ --id=<value> The unique identifier of the entity
624
618
 
625
619
  DESCRIPTION
626
- Delete entities by id
620
+ (BETA) Delete an entity
627
621
 
628
622
  EXAMPLES
629
623
  $ contrail entities delete color 123
630
-
631
- $ contrail entities delete color id1 id2 id3
632
-
633
- $ contrail entities delete item -i ids.json
634
624
  ```
635
625
 
636
- ## `contrail entities get TYPEPATH [IDS]`
626
+ ## `contrail entities get TYPEPATH`
637
627
 
638
- Get an entity
628
+ (BETA) Get an entity
639
629
 
640
630
  ```
641
631
  USAGE
642
- $ contrail entities get TYPEPATH [IDS] [-l error|warn|info|debug] [-e true|false] [-o <value>] [-p <value>] [-P]
643
- [-s <value>] [-S] [-t <value>] [-r <value>] [--suffix <value>] [--apiVersion 1|2]
632
+ $ contrail entities get TYPEPATH [-l error|warn|info|debug] [-e true|false] [-o <value>] [-p <value>] [-P] [-s
633
+ <value>] [-S] [-t <value>] [-r <value>]
644
634
 
645
635
  ARGUMENTS
646
636
  TYPEPATH The name of the entity type to fetch
647
- IDS One or more entity ids; shorthand for the id/ids criteria
648
637
 
649
638
  FLAGS
650
639
  -P, --paginated If true, fetches all entities in a paginated manner
@@ -658,19 +647,11 @@ FLAGS
658
647
  -r, --relations=<value> Comma-separated list of relations to include in the output
659
648
  -s, --skip=<value> Number of entities to skip (used with paginated fetch)
660
649
  -t, --take=<value> Number of entities to fetch in a single request (default is 100)
661
- --apiVersion=<option> Api-Version header to send; selects the V1 or V2 variant of the endpoint
662
- <options: 1|2>
663
- --suffix=<value> Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets
664
- /<entities>/synchronous)
665
650
 
666
651
  DESCRIPTION
667
- Get an entity
652
+ (BETA) Get an entity
668
653
 
669
654
  EXAMPLES
670
- $ contrail entities get color 123
671
-
672
- $ contrail entities get color id1 id2 id3
673
-
674
655
  $ contrail entities get color -- id=123
675
656
 
676
657
  $ contrail entities get loader-processes -- createdOn=2025-09-15..2025-09-16
@@ -680,43 +661,84 @@ EXAMPLES
680
661
  $ contrail entities get events -- timestamp=..2025-09-16T23:59:59Z
681
662
  ```
682
663
 
683
- ## `contrail entities update ENTITYNAME [IDS]`
664
+ ## `contrail entities update ENTITYNAME [ID]`
684
665
 
685
- Update an entity
666
+ (BETA) Update an entity
686
667
 
687
668
  ```
688
669
  USAGE
689
- $ contrail entities update ENTITYNAME [IDS] [-l error|warn|info|debug] [-e true|false] [-S] [-d] [-i <value>]
690
- [--suffix <value>] [--apiVersion 1|2]
670
+ $ contrail entities update ENTITYNAME [ID] [-l error|warn|info|debug] [-e true|false] [-s] [-d] [-i <value>] [-F]
691
671
 
692
672
  ARGUMENTS
693
673
  ENTITYNAME The name of the entity type to update
694
- IDS One or more entity ids to update
674
+ ID The unique identifier of the entity
695
675
 
696
676
  FLAGS
697
- -S, --skipHydrateRelationships Skip hydrating relationships when updating the entity
698
- -d, --dryRun If true, does not update the entities but simulates the update
677
+ -F, --force Force update without validation. Internal use only
678
+ -d, --dryRun If true, does not create the entity but simulates the creation
699
679
  -e, --alwaysConfirmEnv=<option> [default: true] The Environment variables
700
680
  <options: true|false>
701
- -i, --inputFile=<value> A file with a JSON array of {id, ...} objects; each object is one entity to update.
681
+ -i, --inputFile=<value> File containing properties to update the entity (optional)
702
682
  -l, --logLevel=<option> The Log Level
703
683
  <options: error|warn|info|debug>
704
- --apiVersion=<option> Api-Version header to send; selects the V1 or V2 variant of the endpoint
705
- <options: 1|2>
706
- --suffix=<value> Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets
707
- /<entities>/synchronous)
684
+ -s, --skipHydrateRelationships Skip hydrating relationships when updating the entity
708
685
 
709
686
  DESCRIPTION
710
- Update an entity
687
+ (BETA) Update an entity
711
688
 
712
689
  EXAMPLES
713
690
  $ contrail entities update color 123 -- name=obsidian hex=000000
714
691
 
715
- $ contrail entities update item id1 id2 id3 -- status=archived # apply the same change to several entities
716
-
717
692
  $ contrail entities update color 123 -- description= notes='""' # Unset description, set notes to empty string
718
693
  ```
719
694
 
695
+ ## `contrail feature-flags export`
696
+
697
+ Export the enabled feature flags for your Org
698
+
699
+ ```
700
+ USAGE
701
+ $ contrail feature-flags export [-l error|warn|info|debug] [-e true|false] [-d <value>] [-f]
702
+
703
+ FLAGS
704
+ -d, --outDir=<value> [default: .] The directory to which to export the feature flags. Defaults to the
705
+ current directory
706
+ -e, --alwaysConfirmEnv=<option> [default: true] The Environment variables
707
+ <options: true|false>
708
+ -f, --overwrite Replaces any existing export files in outDir
709
+ -l, --logLevel=<option> The Log Level
710
+ <options: error|warn|info|debug>
711
+
712
+ DESCRIPTION
713
+ Export the enabled feature flags for your Org
714
+
715
+ EXAMPLES
716
+ $ contrail feature-flags export
717
+ ```
718
+
719
+ ## `contrail feature-flags import`
720
+
721
+ Upload an extracted set of feature flags
722
+
723
+ ```
724
+ USAGE
725
+ $ contrail feature-flags import [-l error|warn|info|debug] [-e true|false] [-d <value>]
726
+
727
+ FLAGS
728
+ -d, --dir=<value> [default: .] The directory from which to import the feature flags. Defaults to the
729
+ current directory. The feature flags will be loaded from $dir/feature-flags.yml
730
+ -e, --alwaysConfirmEnv=<option> [default: true] The Environment variables
731
+ <options: true|false>
732
+ -l, --logLevel=<option> The Log Level
733
+ <options: error|warn|info|debug>
734
+
735
+ DESCRIPTION
736
+ Upload an extracted set of feature flags
737
+
738
+ EXAMPLES
739
+ $ contrail feature-flags import
740
+ ```
741
+
720
742
  ## `contrail file upload FILELOCATION CONTENTTYPE`
721
743
 
722
744
  Uploads a file to the VibeIQ platform
@@ -0,0 +1,3 @@
1
+ export declare function getFeatureFlags(options?: any): Promise<any[]>;
2
+ export declare function createFeatureFlag(featureName: string): Promise<any>;
3
+ export declare function deleteFeatureFlag(id: string): Promise<any>;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deleteFeatureFlag = exports.createFeatureFlag = exports.getFeatureFlags = void 0;
4
+ const sdk_1 = require("@contrail/sdk");
5
+ // a feature flag record exists only for features that are turned ON for the org,
6
+ // and carries no configuration beyond its featureName
7
+ async function getFeatureFlags(options) {
8
+ return new sdk_1.Entities().get({
9
+ entityName: 'feature-flag',
10
+ ...options,
11
+ });
12
+ }
13
+ exports.getFeatureFlags = getFeatureFlags;
14
+ // the API treats create as an upsert on featureName, so creating an already
15
+ // enabled flag returns the existing record instead of failing
16
+ async function createFeatureFlag(featureName) {
17
+ return new sdk_1.Entities().create({
18
+ entityName: 'feature-flag',
19
+ object: { featureName },
20
+ });
21
+ }
22
+ exports.createFeatureFlag = createFeatureFlag;
23
+ async function deleteFeatureFlag(id) {
24
+ return new sdk_1.Entities().delete({
25
+ entityName: 'feature-flag',
26
+ id,
27
+ });
28
+ }
29
+ exports.deleteFeatureFlag = deleteFeatureFlag;
@@ -1,2 +1,3 @@
1
1
  export declare function getUserOrgs(options?: any): Promise<any[]>;
2
2
  export declare function getGroups(options?: any): Promise<any[]>;
3
+ export declare function getCurrentUserWithPlatformRoles(): Promise<any>;
package/dist/api/users.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getGroups = exports.getUserOrgs = void 0;
3
+ exports.getCurrentUserWithPlatformRoles = exports.getGroups = exports.getUserOrgs = void 0;
4
4
  const sdk_1 = require("@contrail/sdk");
5
5
  async function getUserOrgs(options) {
6
6
  return new sdk_1.Entities().get({
@@ -16,3 +16,12 @@ async function getGroups(options) {
16
16
  });
17
17
  }
18
18
  exports.getGroups = getGroups;
19
+ // GET /users/current only populates platformRoles when it is asked for as a relation
20
+ async function getCurrentUserWithPlatformRoles() {
21
+ return new sdk_1.Entities().get({
22
+ entityName: 'user',
23
+ id: 'current',
24
+ relations: ['platformRoles'],
25
+ });
26
+ }
27
+ exports.getCurrentUserWithPlatformRoles = getCurrentUserWithPlatformRoles;
@@ -10,10 +10,10 @@ const logger_1 = tslib_1.__importDefault(require("../logger"));
10
10
  const path_1 = tslib_1.__importDefault(require("path"));
11
11
  const fs_1 = tslib_1.__importDefault(require("fs"));
12
12
  const common_1 = require("../common");
13
- const CONFIGURATION = {
14
- userPoolId: 'us-east-1_qIaNZdUfm',
15
- clientId: process.env.CONTRAIL_COGNITO_CLIENT_ID || '7knkt34gfacbgd0ghnuspefdfg',
16
- apiGateway: 'https://api.vibeiq.com/prod/api',
13
+ const DEFAULT_API_GATEWAY = config_1.ENVIRONMENTS.prod;
14
+ const COGNITO_CONFIGS = {
15
+ dev: { userPoolId: 'us-east-1_e2cA0nJWu', clientId: '209s9c62o165cqab0fu5ihjtu9' },
16
+ prod: { userPoolId: 'us-east-1_qIaNZdUfm', clientId: '7knkt34gfacbgd0ghnuspefdfg' },
17
17
  };
18
18
  async function authUser() {
19
19
  logger_1.default.debug('authorizing user...');
@@ -76,7 +76,7 @@ async function getOrgSlug(config) {
76
76
  return orgSlug;
77
77
  }
78
78
  async function authenticateWithApiKey(config, apiKey, orgSlug) {
79
- const apiGateway = config?.apiGateway ?? CONFIGURATION.apiGateway;
79
+ const apiGateway = getApiGateway(config);
80
80
  sdk_1.Auth.config = {
81
81
  apiUserToken: apiKey,
82
82
  apiRefreshToken: undefined,
@@ -89,6 +89,12 @@ async function authenticateWithApiKey(config, apiKey, orgSlug) {
89
89
  return Object.assign({}, sdk_1.Auth.config);
90
90
  }
91
91
  async function authenticateWithUsernamePassword(config) {
92
+ const apiGateway = getApiGateway(config);
93
+ const environment = (0, config_1.findEnvironmentName)(apiGateway);
94
+ const cognitoConfig = environment ? COGNITO_CONFIGS[environment] : undefined;
95
+ if (!environment || !cognitoConfig) {
96
+ throw new Error(`No Cognito user pool is known for ${apiGateway}. Email and password sign-in works for ${Object.keys(COGNITO_CONFIGS).join(' and ')}; use CONTRAIL_CLI_API_KEY for other environments.`);
97
+ }
92
98
  const questions = [];
93
99
  if (!process.env.CONTRAIL_CLI_EMAIL) {
94
100
  questions.push({
@@ -111,14 +117,15 @@ async function authenticateWithUsernamePassword(config) {
111
117
  email: process.env.CONTRAIL_CLI_EMAIL || answers.email,
112
118
  password: process.env.CONTRAIL_CLI_PASSWORD || answers.password,
113
119
  orgSlug: await getOrgSlug(config),
114
- ...(config?.apiGateway && { apiGateway: config.apiGateway }),
120
+ apiGateway,
121
+ environment,
115
122
  };
116
123
  if (!params.email || !params.password) {
117
124
  throw new Error('Email and Password required');
118
125
  }
119
126
  const poolData = {
120
- UserPoolId: CONFIGURATION.userPoolId,
121
- ClientId: CONFIGURATION.clientId,
127
+ UserPoolId: cognitoConfig.userPoolId,
128
+ ClientId: cognitoConfig.clientId,
122
129
  };
123
130
  const userPool = new amazon_cognito_identity_js_1.CognitoUserPool(poolData);
124
131
  const authData = {
@@ -134,19 +141,26 @@ async function authenticateWithUsernamePassword(config) {
134
141
  return new Promise((resolve, reject) => {
135
142
  cognitoUser.authenticateUser(authDetails, {
136
143
  onSuccess: async (result) => {
137
- const user = result;
138
- const config = await setAuthContext(user, params);
139
- resolve(config);
144
+ try {
145
+ resolve(await setAuthContext(result, params));
146
+ }
147
+ catch (e) {
148
+ reject(e);
149
+ }
140
150
  },
141
151
  onFailure: (err) => {
152
+ if (err?.code === 'ResourceNotFoundException') {
153
+ reject(new Error(`This version of the CLI has outdated ${environment} sign-in settings (${err.message}). Update the CLI: npm i -g @contrail/cli`));
154
+ return;
155
+ }
142
156
  reject(err);
143
157
  },
144
158
  });
145
159
  });
146
160
  }
147
161
  async function setAuthContext(user, params) {
148
- const apiGateway = params?.apiGateway ?? CONFIGURATION.apiGateway;
149
- const { vibeAccessToken, vibeRefreshToken } = await getVibeAccessTokenFromCognitoAccessToken(user.idToken.jwtToken, apiGateway);
162
+ const apiGateway = params.apiGateway;
163
+ const { vibeAccessToken, vibeRefreshToken } = await getVibeAccessTokenFromCognitoAccessToken(user.idToken.jwtToken, apiGateway, params.environment);
150
164
  sdk_1.Auth.config = {
151
165
  apiUserToken: vibeAccessToken,
152
166
  apiRefreshToken: vibeRefreshToken,
@@ -161,7 +175,7 @@ async function refreshCurrentUserOrg() {
161
175
  const currentUser = await (0, sdk_1.getCurrentUser)().catch((e) => {
162
176
  console.error('error getting current user', e.message);
163
177
  if (isExpiredTokenError(e)) {
164
- console.error('access token expired; attempting refresh');
178
+ console.log('try frefreshing');
165
179
  return;
166
180
  }
167
181
  throw e;
@@ -176,7 +190,7 @@ async function refreshCurrentUserOrg() {
176
190
  apiGateway: config.apiGateway,
177
191
  orgSlug: config.orgSlug,
178
192
  };
179
- (0, sdk_1.setConfig)(sdk_1.Auth.config);
193
+ console.log('fetched new access token from refresh token', newVibeAccessToken);
180
194
  }
181
195
  catch (e) {
182
196
  throw Error(`Could not get refresh token: ${e}`);
@@ -191,7 +205,10 @@ async function refreshCurrentUserOrg() {
191
205
  function isExpiredTokenError(e) {
192
206
  return e?.message?.includes('token is expired');
193
207
  }
194
- async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiGateway) {
208
+ function getApiGateway(config) {
209
+ return config?.apiGateway ?? DEFAULT_API_GATEWAY;
210
+ }
211
+ async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiGateway, environment) {
195
212
  const url = `${apiGateway}/auth/cognito/`;
196
213
  const response = await fetch(url, {
197
214
  method: 'POST',
@@ -201,9 +218,11 @@ async function getVibeAccessTokenFromCognitoAccessToken(cognitoAccessToken, apiG
201
218
  },
202
219
  body: JSON.stringify({ accessToken: cognitoAccessToken }),
203
220
  });
204
- return await response.json().then((data) => {
205
- return { vibeAccessToken: data.accessToken, vibeRefreshToken: data.refreshToken };
206
- });
221
+ if (!response.ok) {
222
+ throw new Error(`${environment} rejected the sign-in (${response.status}).`);
223
+ }
224
+ const data = await response.json();
225
+ return { vibeAccessToken: data.accessToken, vibeRefreshToken: data.refreshToken };
207
226
  }
208
227
  async function requestRefreshedAccessToken(vibeRefreshToken, apiGateway) {
209
228
  const url = `${apiGateway}/auth/jwt_refresh/`;
@@ -215,11 +234,9 @@ async function requestRefreshedAccessToken(vibeRefreshToken, apiGateway) {
215
234
  },
216
235
  body: JSON.stringify({ refreshToken: vibeRefreshToken }),
217
236
  });
218
- const data = await response.json();
219
- if (!response.ok || !data.accessToken) {
220
- throw new Error(`jwt_refresh returned ${response.status} with no access token`);
221
- }
222
- return data.accessToken;
237
+ return await response.json().then((data) => {
238
+ return data.accessToken;
239
+ });
223
240
  }
224
241
  function getVersionFromPackageJson() {
225
242
  // Get the path to the package.json file
@@ -1,6 +1,130 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const amazon_cognito_identity_js_1 = require("amazon-cognito-identity-js");
4
+ const sdk_1 = require("@contrail/sdk");
5
+ const config_1 = require("../helpers/config/config");
3
6
  const login_1 = require("./login");
7
+ const mockAuthenticateUser = jest.fn();
8
+ jest.mock('amazon-cognito-identity-js', () => ({
9
+ CognitoUserPool: jest.fn(),
10
+ AuthenticationDetails: jest.fn(),
11
+ CognitoUser: jest.fn().mockImplementation(() => ({
12
+ authenticateUser: (details, callbacks) => mockAuthenticateUser(details, callbacks),
13
+ })),
14
+ }));
15
+ jest.mock('@contrail/sdk', () => ({
16
+ Auth: { config: {} },
17
+ getCurrentUser: jest.fn(),
18
+ setConfig: jest.fn(),
19
+ }));
20
+ jest.mock('../helpers/config/config', () => ({
21
+ ...jest.requireActual('../helpers/config/config'),
22
+ getConfig: jest.fn(),
23
+ storeConfig: jest.fn(),
24
+ }));
25
+ jest.mock('../logger', () => ({
26
+ __esModule: true,
27
+ default: { debug: jest.fn(), info: jest.fn() },
28
+ }));
29
+ const DEV_GATEWAY = 'https://api.dev.vibeiq.com/dev/api';
30
+ function restoreEnv(name, value) {
31
+ if (value === undefined) {
32
+ delete process.env[name];
33
+ }
34
+ else {
35
+ process.env[name] = value;
36
+ }
37
+ }
38
+ function jsonResponse(status, body = {}) {
39
+ return new Response(JSON.stringify(body), { status });
40
+ }
41
+ describe('authUser with email and password', () => {
42
+ const originalFetch = global.fetch;
43
+ const originalEmail = process.env.CONTRAIL_CLI_EMAIL;
44
+ const originalPassword = process.env.CONTRAIL_CLI_PASSWORD;
45
+ let fetchMock;
46
+ beforeEach(() => {
47
+ jest.clearAllMocks();
48
+ process.env.CONTRAIL_CLI_EMAIL = 'dev@vibeiq.com';
49
+ process.env.CONTRAIL_CLI_PASSWORD = 'secret';
50
+ config_1.getConfig.mockResolvedValue({ apiGateway: DEV_GATEWAY, orgSlug: 'adam-zone-1' });
51
+ sdk_1.getCurrentUser.mockResolvedValue({ id: 'user-1' });
52
+ mockAuthenticateUser.mockImplementation((_details, callbacks) => callbacks.onSuccess({ idToken: { jwtToken: 'cognito-id-token' } }));
53
+ fetchMock = jest.fn();
54
+ global.fetch = fetchMock;
55
+ });
56
+ afterEach(() => {
57
+ global.fetch = originalFetch;
58
+ restoreEnv('CONTRAIL_CLI_EMAIL', originalEmail);
59
+ restoreEnv('CONTRAIL_CLI_PASSWORD', originalPassword);
60
+ });
61
+ it('should sign in through the dev pool when the config points at dev', async () => {
62
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
63
+ const context = await (0, login_1.authUser)();
64
+ expect(amazon_cognito_identity_js_1.CognitoUserPool).toHaveBeenCalledWith({
65
+ UserPoolId: 'us-east-1_e2cA0nJWu',
66
+ ClientId: '209s9c62o165cqab0fu5ihjtu9',
67
+ });
68
+ expect(context).toEqual({
69
+ apiUserToken: 'vibe-access',
70
+ apiRefreshToken: 'vibe-refresh',
71
+ apiGateway: DEV_GATEWAY,
72
+ orgSlug: 'adam-zone-1',
73
+ });
74
+ });
75
+ it('should sign in through the prod pool when the config points at prod', async () => {
76
+ config_1.getConfig.mockResolvedValue({
77
+ apiGateway: 'https://api.vibeiq.com/prod/api',
78
+ orgSlug: 'adam-zone-1',
79
+ });
80
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
81
+ await (0, login_1.authUser)();
82
+ expect(amazon_cognito_identity_js_1.CognitoUserPool).toHaveBeenCalledWith({
83
+ UserPoolId: 'us-east-1_qIaNZdUfm',
84
+ ClientId: '7knkt34gfacbgd0ghnuspefdfg',
85
+ });
86
+ });
87
+ it('should match the dev pool despite a trailing slash or different case in the gateway', async () => {
88
+ config_1.getConfig.mockResolvedValue({
89
+ apiGateway: 'https://API.dev.vibeiq.com/dev/api/',
90
+ orgSlug: 'adam-zone-1',
91
+ });
92
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'vibe-access', refreshToken: 'vibe-refresh' }));
93
+ await (0, login_1.authUser)();
94
+ expect(amazon_cognito_identity_js_1.CognitoUserPool).toHaveBeenCalledWith({
95
+ UserPoolId: 'us-east-1_e2cA0nJWu',
96
+ ClientId: '209s9c62o165cqab0fu5ihjtu9',
97
+ });
98
+ });
99
+ it('should explain an unknown gateway even when it has no scheme', async () => {
100
+ config_1.getConfig.mockResolvedValue({
101
+ apiGateway: 'api.dev.vibeiq.com/dev/api',
102
+ orgSlug: 'adam-zone-1',
103
+ });
104
+ await expect((0, login_1.authUser)()).rejects.toThrow('No Cognito user pool is known for api.dev.vibeiq.com/dev/api.');
105
+ });
106
+ it('should fail without saving tokens when no pool is known for the environment', async () => {
107
+ config_1.getConfig.mockResolvedValue({
108
+ apiGateway: 'http://localhost:3000/api',
109
+ orgSlug: 'adam-zone-1',
110
+ });
111
+ await expect((0, login_1.authUser)()).rejects.toThrow('No Cognito user pool is known for http://localhost:3000/api.');
112
+ expect(config_1.storeConfig).not.toHaveBeenCalled();
113
+ });
114
+ it('should tell the user to update the CLI when its Cognito client or pool no longer exists', async () => {
115
+ mockAuthenticateUser.mockImplementation((_details, callbacks) => callbacks.onFailure({
116
+ code: 'ResourceNotFoundException',
117
+ message: 'User pool client 209s9c62o165cqab0fu5ihjtu9 does not exist.',
118
+ }));
119
+ 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');
120
+ expect(config_1.storeConfig).not.toHaveBeenCalled();
121
+ });
122
+ it('should fail without saving tokens when the environment rejects the sign-in', async () => {
123
+ fetchMock.mockResolvedValueOnce(jsonResponse(401, { message: 'Unauthorized' }));
124
+ await expect((0, login_1.authUser)()).rejects.toThrow('dev rejected the sign-in (401).');
125
+ expect(config_1.storeConfig).not.toHaveBeenCalled();
126
+ });
127
+ });
4
128
  describe('getVersionFromPackageJson', () => {
5
129
  it('should return the version value from package.json', () => {
6
130
  const version = (0, login_1.getVersionFromPackageJson)();
@@ -60,7 +60,7 @@ class BaseCommand extends core_1.Command {
60
60
  const data = (0, lodash_1.pick)(config, ['orgSlug', 'apiGateway']);
61
61
  let env = '';
62
62
  if (data.apiGateway) {
63
- env = Object.keys(config_1.ENVIRONMENTS).find((key) => config_1.ENVIRONMENTS[key] === data.apiGateway);
63
+ env = (0, config_1.findEnvironmentName)(data.apiGateway);
64
64
  }
65
65
  data.environment = env;
66
66
  delete data.apiGateway;
@@ -35,7 +35,7 @@ class GetAPIKeyApp extends basecommand_1.BaseCommand {
35
35
  },
36
36
  ];
37
37
  const answers = await inquirer_1.default.prompt(questions);
38
- this.log(`App API key: (app:${answers.appApiKey})`);
38
+ logger_1.default.info(`App API key: (app:${answers.appApiKey})`);
39
39
  }
40
40
  else {
41
41
  const appFound = installedApps.find((x) => x.app.identifier === this.flags.appIdentifier);
@@ -43,7 +43,7 @@ class GetAPIKeyApp extends basecommand_1.BaseCommand {
43
43
  logger_1.default.info('You do not have such an app installed');
44
44
  return;
45
45
  }
46
- this.log(`App API key: (app:${appFound.apiKey.apiKey})`);
46
+ logger_1.default.info(`App API key: (app:${appFound.apiKey.apiKey})`);
47
47
  }
48
48
  }
49
49
  }
@@ -1,4 +1,4 @@
1
- import { PropertyLevel, PropertyType } from '@contrail/types';
1
+ import { PropertyLevel } from '@contrail/types';
2
2
  import { ColonDelimited, TypeProperty as ExtendedTypeProperty, TypeReferencesCacheByPath } from '../../api/types';
3
3
  import { TypeWithProperties } from '../../api/types';
4
4
  import { BaseCommand } from '../../basecommand';
@@ -14,8 +14,6 @@ export default class CreateEntity extends BaseCommand {
14
14
  generateValues: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
15
15
  readableIds: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
16
16
  skipHydrateRelationships: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
17
- suffix: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
18
- apiVersion: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
19
17
  alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
20
18
  logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
21
19
  };
@@ -25,14 +23,6 @@ export default class CreateEntity extends BaseCommand {
25
23
  static strict: boolean;
26
24
  run(): Promise<void>;
27
25
  }
28
- export type CreateSummary = {
29
- created: any[];
30
- failed: {
31
- input: any;
32
- error: string;
33
- }[];
34
- };
35
- export declare function summarizeSettledCreates(inputs: any[], settled: PromiseSettledResult<any>[]): CreateSummary;
36
26
  export type WithId = {
37
27
  id: string;
38
28
  [key: string]: any;
@@ -40,7 +30,6 @@ export type WithId = {
40
30
  export type ObjectReferenceCache = Map<string, WithId>;
41
31
  type ObjectReferenceCachesByTypePath = Map<string, ObjectReferenceCache>;
42
32
  export declare function pickRandomValueForProperty(property: ExtendedTypeProperty, objectReferencesCache: ObjectReferenceCachesByTypePath, typeReferencesCache: TypeReferencesCacheByPath): number | string | string[] | boolean | null;
43
- export declare function castValueToPropertyType(value: string | number | string[] | number[], propertyType: PropertyType): any;
44
33
  export declare function getReferencedObjectPaths(type: TypeWithProperties): ColonDelimited[];
45
34
  export declare function buildObjectReferenceCache(entities: any[]): ObjectReferenceCache;
46
35
  export declare function selectRandomObject(cache: ObjectReferenceCache): WithId;