@smithy/shared-ini-file-loader 1.0.0

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 (51) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +105 -0
  3. package/dist-cjs/getConfigFilepath.js +8 -0
  4. package/dist-cjs/getCredentialsFilepath.js +8 -0
  5. package/dist-cjs/getHomeDir.js +16 -0
  6. package/dist-cjs/getProfileData.js +10 -0
  7. package/dist-cjs/getProfileName.js +7 -0
  8. package/dist-cjs/getSSOTokenFilepath.js +12 -0
  9. package/dist-cjs/getSSOTokenFromFile.js +12 -0
  10. package/dist-cjs/getSsoSessionData.js +8 -0
  11. package/dist-cjs/index.js +11 -0
  12. package/dist-cjs/loadSharedConfigFiles.js +30 -0
  13. package/dist-cjs/loadSsoSessionData.js +16 -0
  14. package/dist-cjs/mergeConfigFiles.js +18 -0
  15. package/dist-cjs/parseIni.js +34 -0
  16. package/dist-cjs/parseKnownFiles.js +10 -0
  17. package/dist-cjs/slurpFile.js +13 -0
  18. package/dist-cjs/types.js +2 -0
  19. package/dist-es/getConfigFilepath.js +4 -0
  20. package/dist-es/getCredentialsFilepath.js +4 -0
  21. package/dist-es/getHomeDir.js +12 -0
  22. package/dist-es/getProfileData.js +6 -0
  23. package/dist-es/getProfileName.js +3 -0
  24. package/dist-es/getSSOTokenFilepath.js +8 -0
  25. package/dist-es/getSSOTokenFromFile.js +8 -0
  26. package/dist-es/getSsoSessionData.js +4 -0
  27. package/dist-es/index.js +8 -0
  28. package/dist-es/loadSharedConfigFiles.js +26 -0
  29. package/dist-es/loadSsoSessionData.js +9 -0
  30. package/dist-es/mergeConfigFiles.js +14 -0
  31. package/dist-es/parseIni.js +30 -0
  32. package/dist-es/parseKnownFiles.js +6 -0
  33. package/dist-es/slurpFile.js +9 -0
  34. package/dist-es/types.js +1 -0
  35. package/dist-types/getConfigFilepath.d.ts +2 -0
  36. package/dist-types/getCredentialsFilepath.d.ts +2 -0
  37. package/dist-types/getHomeDir.d.ts +6 -0
  38. package/dist-types/getProfileData.d.ts +7 -0
  39. package/dist-types/getProfileName.d.ts +5 -0
  40. package/dist-types/getSSOTokenFilepath.d.ts +4 -0
  41. package/dist-types/getSSOTokenFromFile.d.ts +44 -0
  42. package/dist-types/getSsoSessionData.d.ts +6 -0
  43. package/dist-types/index.d.ts +8 -0
  44. package/dist-types/loadSharedConfigFiles.d.ts +21 -0
  45. package/dist-types/loadSsoSessionData.d.ts +10 -0
  46. package/dist-types/mergeConfigFiles.d.ts +7 -0
  47. package/dist-types/parseIni.d.ts +2 -0
  48. package/dist-types/parseKnownFiles.d.ts +15 -0
  49. package/dist-types/slurpFile.d.ts +5 -0
  50. package/dist-types/types.d.ts +13 -0
  51. package/package.json +61 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # @smithy/shared-ini-file-loader
2
+
3
+ [![NPM version](https://img.shields.io/npm/v/@smithy/shared-ini-file-loader/latest.svg)](https://www.npmjs.com/package/@smithy/shared-ini-file-loader)
4
+ [![NPM downloads](https://img.shields.io/npm/dm/@smithy/shared-ini-file-loader.svg)](https://www.npmjs.com/package/@smithy/shared-ini-file-loader)
5
+
6
+ ## AWS Shared Configuration File Loader
7
+
8
+ This module provides a function that reads from AWS SDK configuration files and
9
+ returns a promise that will resolve with a hash of the parsed contents of the
10
+ AWS credentials file and of the AWS config file. Given the [sample
11
+ files](#sample-files) below, the promise returned by `loadSharedConfigFiles`
12
+ would resolve with:
13
+
14
+ ```javascript
15
+ {
16
+ configFile: {
17
+ 'default': {
18
+ aws_access_key_id: 'foo',
19
+ aws_secret_access_key: 'bar',
20
+ },
21
+ dev: {
22
+ aws_access_key_id: 'foo1',
23
+ aws_secret_access_key: 'bar1',
24
+ },
25
+ prod: {
26
+ aws_access_key_id: 'foo2',
27
+ aws_secret_access_key: 'bar2',
28
+ },
29
+ 'testing host': {
30
+ aws_access_key_id: 'foo4',
31
+ aws_secret_access_key: 'bar4',
32
+ }
33
+ },
34
+ credentialsFile: {
35
+ 'default': {
36
+ aws_access_key_id: 'foo',
37
+ aws_secret_access_key: 'bar',
38
+ },
39
+ dev: {
40
+ aws_access_key_id: 'foo1',
41
+ aws_secret_access_key: 'bar1',
42
+ },
43
+ prod: {
44
+ aws_access_key_id: 'foo2',
45
+ aws_secret_access_key: 'bar2',
46
+ }
47
+ },
48
+ }
49
+ ```
50
+
51
+ If a file is not found, its key (`configFile` or `credentialsFile`) will instead
52
+ have a value of an empty object.
53
+
54
+ ## Supported configuration
55
+
56
+ You may customize how the files are loaded by providing an options hash to the
57
+ `loadSharedConfigFiles` function. The following options are supported:
58
+
59
+ - `filepath` - The path to the shared credentials file. If not specified, the
60
+ provider will use the value in the `AWS_SHARED_CREDENTIALS_FILE` environment
61
+ variable or a default of `~/.aws/credentials`.
62
+ - `configFilepath` - The path to the shared config file. If not specified, the
63
+ provider will use the value in the `AWS_CONFIG_FILE` environment variable or a
64
+ default of `~/.aws/config`.
65
+ - `ignoreCache` - The provider will normally cache the contents of the files it
66
+ loads. This option will force the provider to reload the files from disk.
67
+ Defaults to `false`.
68
+
69
+ ## Sample files
70
+
71
+ ### `~/.aws/credentials`
72
+
73
+ ```ini
74
+ [default]
75
+ aws_access_key_id=foo
76
+ aws_secret_access_key=bar
77
+
78
+ [dev]
79
+ aws_access_key_id=foo2
80
+ aws_secret_access_key=bar2
81
+
82
+ [prod]
83
+ aws_access_key_id=foo3
84
+ aws_secret_access_key=bar3
85
+ ```
86
+
87
+ ### `~/.aws/config`
88
+
89
+ ```ini
90
+ [default]
91
+ aws_access_key_id=foo
92
+ aws_secret_access_key=bar
93
+
94
+ [profile dev]
95
+ aws_access_key_id=foo2
96
+ aws_secret_access_key=bar2
97
+
98
+ [profile prod]
99
+ aws_access_key_id=foo3
100
+ aws_secret_access_key=bar3
101
+
102
+ [profile "testing host"]
103
+ aws_access_key_id=foo4
104
+ aws_secret_access_key=bar4
105
+ ```
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getConfigFilepath = exports.ENV_CONFIG_PATH = void 0;
4
+ const path_1 = require("path");
5
+ const getHomeDir_1 = require("./getHomeDir");
6
+ exports.ENV_CONFIG_PATH = "AWS_CONFIG_FILE";
7
+ const getConfigFilepath = () => process.env[exports.ENV_CONFIG_PATH] || (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "config");
8
+ exports.getConfigFilepath = getConfigFilepath;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCredentialsFilepath = exports.ENV_CREDENTIALS_PATH = void 0;
4
+ const path_1 = require("path");
5
+ const getHomeDir_1 = require("./getHomeDir");
6
+ exports.ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE";
7
+ const getCredentialsFilepath = () => process.env[exports.ENV_CREDENTIALS_PATH] || (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "credentials");
8
+ exports.getCredentialsFilepath = getCredentialsFilepath;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getHomeDir = void 0;
4
+ const os_1 = require("os");
5
+ const path_1 = require("path");
6
+ const getHomeDir = () => {
7
+ const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env;
8
+ if (HOME)
9
+ return HOME;
10
+ if (USERPROFILE)
11
+ return USERPROFILE;
12
+ if (HOMEPATH)
13
+ return `${HOMEDRIVE}${HOMEPATH}`;
14
+ return (0, os_1.homedir)();
15
+ };
16
+ exports.getHomeDir = getHomeDir;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getProfileData = void 0;
4
+ const profileKeyRegex = /^profile\s(["'])?([^\1]+)\1$/;
5
+ const getProfileData = (data) => Object.entries(data)
6
+ .filter(([key]) => profileKeyRegex.test(key))
7
+ .reduce((acc, [key, value]) => ({ ...acc, [profileKeyRegex.exec(key)[2]]: value }), {
8
+ ...(data.default && { default: data.default }),
9
+ });
10
+ exports.getProfileData = getProfileData;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getProfileName = exports.DEFAULT_PROFILE = exports.ENV_PROFILE = void 0;
4
+ exports.ENV_PROFILE = "AWS_PROFILE";
5
+ exports.DEFAULT_PROFILE = "default";
6
+ const getProfileName = (init) => init.profile || process.env[exports.ENV_PROFILE] || exports.DEFAULT_PROFILE;
7
+ exports.getProfileName = getProfileName;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSSOTokenFilepath = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const path_1 = require("path");
6
+ const getHomeDir_1 = require("./getHomeDir");
7
+ const getSSOTokenFilepath = (id) => {
8
+ const hasher = (0, crypto_1.createHash)("sha1");
9
+ const cacheName = hasher.update(id).digest("hex");
10
+ return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`);
11
+ };
12
+ exports.getSSOTokenFilepath = getSSOTokenFilepath;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSSOTokenFromFile = void 0;
4
+ const fs_1 = require("fs");
5
+ const getSSOTokenFilepath_1 = require("./getSSOTokenFilepath");
6
+ const { readFile } = fs_1.promises;
7
+ const getSSOTokenFromFile = async (id) => {
8
+ const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id);
9
+ const ssoTokenText = await readFile(ssoTokenFilepath, "utf8");
10
+ return JSON.parse(ssoTokenText);
11
+ };
12
+ exports.getSSOTokenFromFile = getSSOTokenFromFile;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSsoSessionData = void 0;
4
+ const ssoSessionKeyRegex = /^sso-session\s(["'])?([^\1]+)\1$/;
5
+ const getSsoSessionData = (data) => Object.entries(data)
6
+ .filter(([key]) => ssoSessionKeyRegex.test(key))
7
+ .reduce((acc, [key, value]) => ({ ...acc, [ssoSessionKeyRegex.exec(key)[2]]: value }), {});
8
+ exports.getSsoSessionData = getSsoSessionData;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./getHomeDir"), exports);
5
+ tslib_1.__exportStar(require("./getProfileName"), exports);
6
+ tslib_1.__exportStar(require("./getSSOTokenFilepath"), exports);
7
+ tslib_1.__exportStar(require("./getSSOTokenFromFile"), exports);
8
+ tslib_1.__exportStar(require("./loadSharedConfigFiles"), exports);
9
+ tslib_1.__exportStar(require("./loadSsoSessionData"), exports);
10
+ tslib_1.__exportStar(require("./parseKnownFiles"), exports);
11
+ tslib_1.__exportStar(require("./types"), exports);
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.loadSharedConfigFiles = void 0;
4
+ const getConfigFilepath_1 = require("./getConfigFilepath");
5
+ const getCredentialsFilepath_1 = require("./getCredentialsFilepath");
6
+ const getProfileData_1 = require("./getProfileData");
7
+ const parseIni_1 = require("./parseIni");
8
+ const slurpFile_1 = require("./slurpFile");
9
+ const swallowError = () => ({});
10
+ const loadSharedConfigFiles = async (init = {}) => {
11
+ const { filepath = (0, getCredentialsFilepath_1.getCredentialsFilepath)(), configFilepath = (0, getConfigFilepath_1.getConfigFilepath)() } = init;
12
+ const parsedFiles = await Promise.all([
13
+ (0, slurpFile_1.slurpFile)(configFilepath, {
14
+ ignoreCache: init.ignoreCache,
15
+ })
16
+ .then(parseIni_1.parseIni)
17
+ .then(getProfileData_1.getProfileData)
18
+ .catch(swallowError),
19
+ (0, slurpFile_1.slurpFile)(filepath, {
20
+ ignoreCache: init.ignoreCache,
21
+ })
22
+ .then(parseIni_1.parseIni)
23
+ .catch(swallowError),
24
+ ]);
25
+ return {
26
+ configFile: parsedFiles[0],
27
+ credentialsFile: parsedFiles[1],
28
+ };
29
+ };
30
+ exports.loadSharedConfigFiles = loadSharedConfigFiles;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.loadSsoSessionData = void 0;
4
+ const getConfigFilepath_1 = require("./getConfigFilepath");
5
+ const getSsoSessionData_1 = require("./getSsoSessionData");
6
+ const parseIni_1 = require("./parseIni");
7
+ const slurpFile_1 = require("./slurpFile");
8
+ const swallowError = () => ({});
9
+ const loadSsoSessionData = async (init = {}) => {
10
+ var _a;
11
+ return (0, slurpFile_1.slurpFile)((_a = init.configFilepath) !== null && _a !== void 0 ? _a : (0, getConfigFilepath_1.getConfigFilepath)())
12
+ .then(parseIni_1.parseIni)
13
+ .then(getSsoSessionData_1.getSsoSessionData)
14
+ .catch(swallowError);
15
+ };
16
+ exports.loadSsoSessionData = loadSsoSessionData;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mergeConfigFiles = void 0;
4
+ const mergeConfigFiles = (...files) => {
5
+ const merged = {};
6
+ for (const file of files) {
7
+ for (const [key, values] of Object.entries(file)) {
8
+ if (merged[key] !== undefined) {
9
+ Object.assign(merged[key], values);
10
+ }
11
+ else {
12
+ merged[key] = values;
13
+ }
14
+ }
15
+ }
16
+ return merged;
17
+ };
18
+ exports.mergeConfigFiles = mergeConfigFiles;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseIni = void 0;
4
+ const profileNameBlockList = ["__proto__", "profile __proto__"];
5
+ const parseIni = (iniData) => {
6
+ const map = {};
7
+ let currentSection;
8
+ for (let line of iniData.split(/\r?\n/)) {
9
+ line = line.split(/(^|\s)[;#]/)[0].trim();
10
+ const isSection = line[0] === "[" && line[line.length - 1] === "]";
11
+ if (isSection) {
12
+ currentSection = line.substring(1, line.length - 1);
13
+ if (profileNameBlockList.includes(currentSection)) {
14
+ throw new Error(`Found invalid profile name "${currentSection}"`);
15
+ }
16
+ }
17
+ else if (currentSection) {
18
+ const indexOfEqualsSign = line.indexOf("=");
19
+ const start = 0;
20
+ const end = line.length - 1;
21
+ const isAssignment = indexOfEqualsSign !== -1 && indexOfEqualsSign !== start && indexOfEqualsSign !== end;
22
+ if (isAssignment) {
23
+ const [name, value] = [
24
+ line.substring(0, indexOfEqualsSign).trim(),
25
+ line.substring(indexOfEqualsSign + 1).trim(),
26
+ ];
27
+ map[currentSection] = map[currentSection] || {};
28
+ map[currentSection][name] = value;
29
+ }
30
+ }
31
+ }
32
+ return map;
33
+ };
34
+ exports.parseIni = parseIni;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseKnownFiles = void 0;
4
+ const loadSharedConfigFiles_1 = require("./loadSharedConfigFiles");
5
+ const mergeConfigFiles_1 = require("./mergeConfigFiles");
6
+ const parseKnownFiles = async (init) => {
7
+ const parsedFiles = await (0, loadSharedConfigFiles_1.loadSharedConfigFiles)(init);
8
+ return (0, mergeConfigFiles_1.mergeConfigFiles)(parsedFiles.configFile, parsedFiles.credentialsFile);
9
+ };
10
+ exports.parseKnownFiles = parseKnownFiles;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.slurpFile = void 0;
4
+ const fs_1 = require("fs");
5
+ const { readFile } = fs_1.promises;
6
+ const filePromisesHash = {};
7
+ const slurpFile = (path, options) => {
8
+ if (!filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) {
9
+ filePromisesHash[path] = readFile(path, "utf8");
10
+ }
11
+ return filePromisesHash[path];
12
+ };
13
+ exports.slurpFile = slurpFile;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,4 @@
1
+ import { join } from "path";
2
+ import { getHomeDir } from "./getHomeDir";
3
+ export const ENV_CONFIG_PATH = "AWS_CONFIG_FILE";
4
+ export const getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || join(getHomeDir(), ".aws", "config");
@@ -0,0 +1,4 @@
1
+ import { join } from "path";
2
+ import { getHomeDir } from "./getHomeDir";
3
+ export const ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE";
4
+ export const getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || join(getHomeDir(), ".aws", "credentials");
@@ -0,0 +1,12 @@
1
+ import { homedir } from "os";
2
+ import { sep } from "path";
3
+ export const getHomeDir = () => {
4
+ const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${sep}` } = process.env;
5
+ if (HOME)
6
+ return HOME;
7
+ if (USERPROFILE)
8
+ return USERPROFILE;
9
+ if (HOMEPATH)
10
+ return `${HOMEDRIVE}${HOMEPATH}`;
11
+ return homedir();
12
+ };
@@ -0,0 +1,6 @@
1
+ const profileKeyRegex = /^profile\s(["'])?([^\1]+)\1$/;
2
+ export const getProfileData = (data) => Object.entries(data)
3
+ .filter(([key]) => profileKeyRegex.test(key))
4
+ .reduce((acc, [key, value]) => ({ ...acc, [profileKeyRegex.exec(key)[2]]: value }), {
5
+ ...(data.default && { default: data.default }),
6
+ });
@@ -0,0 +1,3 @@
1
+ export const ENV_PROFILE = "AWS_PROFILE";
2
+ export const DEFAULT_PROFILE = "default";
3
+ export const getProfileName = (init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE;
@@ -0,0 +1,8 @@
1
+ import { createHash } from "crypto";
2
+ import { join } from "path";
3
+ import { getHomeDir } from "./getHomeDir";
4
+ export const getSSOTokenFilepath = (id) => {
5
+ const hasher = createHash("sha1");
6
+ const cacheName = hasher.update(id).digest("hex");
7
+ return join(getHomeDir(), ".aws", "sso", "cache", `${cacheName}.json`);
8
+ };
@@ -0,0 +1,8 @@
1
+ import { promises as fsPromises } from "fs";
2
+ import { getSSOTokenFilepath } from "./getSSOTokenFilepath";
3
+ const { readFile } = fsPromises;
4
+ export const getSSOTokenFromFile = async (id) => {
5
+ const ssoTokenFilepath = getSSOTokenFilepath(id);
6
+ const ssoTokenText = await readFile(ssoTokenFilepath, "utf8");
7
+ return JSON.parse(ssoTokenText);
8
+ };
@@ -0,0 +1,4 @@
1
+ const ssoSessionKeyRegex = /^sso-session\s(["'])?([^\1]+)\1$/;
2
+ export const getSsoSessionData = (data) => Object.entries(data)
3
+ .filter(([key]) => ssoSessionKeyRegex.test(key))
4
+ .reduce((acc, [key, value]) => ({ ...acc, [ssoSessionKeyRegex.exec(key)[2]]: value }), {});
@@ -0,0 +1,8 @@
1
+ export * from "./getHomeDir";
2
+ export * from "./getProfileName";
3
+ export * from "./getSSOTokenFilepath";
4
+ export * from "./getSSOTokenFromFile";
5
+ export * from "./loadSharedConfigFiles";
6
+ export * from "./loadSsoSessionData";
7
+ export * from "./parseKnownFiles";
8
+ export * from "./types";
@@ -0,0 +1,26 @@
1
+ import { getConfigFilepath } from "./getConfigFilepath";
2
+ import { getCredentialsFilepath } from "./getCredentialsFilepath";
3
+ import { getProfileData } from "./getProfileData";
4
+ import { parseIni } from "./parseIni";
5
+ import { slurpFile } from "./slurpFile";
6
+ const swallowError = () => ({});
7
+ export const loadSharedConfigFiles = async (init = {}) => {
8
+ const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init;
9
+ const parsedFiles = await Promise.all([
10
+ slurpFile(configFilepath, {
11
+ ignoreCache: init.ignoreCache,
12
+ })
13
+ .then(parseIni)
14
+ .then(getProfileData)
15
+ .catch(swallowError),
16
+ slurpFile(filepath, {
17
+ ignoreCache: init.ignoreCache,
18
+ })
19
+ .then(parseIni)
20
+ .catch(swallowError),
21
+ ]);
22
+ return {
23
+ configFile: parsedFiles[0],
24
+ credentialsFile: parsedFiles[1],
25
+ };
26
+ };
@@ -0,0 +1,9 @@
1
+ import { getConfigFilepath } from "./getConfigFilepath";
2
+ import { getSsoSessionData } from "./getSsoSessionData";
3
+ import { parseIni } from "./parseIni";
4
+ import { slurpFile } from "./slurpFile";
5
+ const swallowError = () => ({});
6
+ export const loadSsoSessionData = async (init = {}) => slurpFile(init.configFilepath ?? getConfigFilepath())
7
+ .then(parseIni)
8
+ .then(getSsoSessionData)
9
+ .catch(swallowError);
@@ -0,0 +1,14 @@
1
+ export const mergeConfigFiles = (...files) => {
2
+ const merged = {};
3
+ for (const file of files) {
4
+ for (const [key, values] of Object.entries(file)) {
5
+ if (merged[key] !== undefined) {
6
+ Object.assign(merged[key], values);
7
+ }
8
+ else {
9
+ merged[key] = values;
10
+ }
11
+ }
12
+ }
13
+ return merged;
14
+ };
@@ -0,0 +1,30 @@
1
+ const profileNameBlockList = ["__proto__", "profile __proto__"];
2
+ export const parseIni = (iniData) => {
3
+ const map = {};
4
+ let currentSection;
5
+ for (let line of iniData.split(/\r?\n/)) {
6
+ line = line.split(/(^|\s)[;#]/)[0].trim();
7
+ const isSection = line[0] === "[" && line[line.length - 1] === "]";
8
+ if (isSection) {
9
+ currentSection = line.substring(1, line.length - 1);
10
+ if (profileNameBlockList.includes(currentSection)) {
11
+ throw new Error(`Found invalid profile name "${currentSection}"`);
12
+ }
13
+ }
14
+ else if (currentSection) {
15
+ const indexOfEqualsSign = line.indexOf("=");
16
+ const start = 0;
17
+ const end = line.length - 1;
18
+ const isAssignment = indexOfEqualsSign !== -1 && indexOfEqualsSign !== start && indexOfEqualsSign !== end;
19
+ if (isAssignment) {
20
+ const [name, value] = [
21
+ line.substring(0, indexOfEqualsSign).trim(),
22
+ line.substring(indexOfEqualsSign + 1).trim(),
23
+ ];
24
+ map[currentSection] = map[currentSection] || {};
25
+ map[currentSection][name] = value;
26
+ }
27
+ }
28
+ }
29
+ return map;
30
+ };
@@ -0,0 +1,6 @@
1
+ import { loadSharedConfigFiles } from "./loadSharedConfigFiles";
2
+ import { mergeConfigFiles } from "./mergeConfigFiles";
3
+ export const parseKnownFiles = async (init) => {
4
+ const parsedFiles = await loadSharedConfigFiles(init);
5
+ return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile);
6
+ };
@@ -0,0 +1,9 @@
1
+ import { promises as fsPromises } from "fs";
2
+ const { readFile } = fsPromises;
3
+ const filePromisesHash = {};
4
+ export const slurpFile = (path, options) => {
5
+ if (!filePromisesHash[path] || options?.ignoreCache) {
6
+ filePromisesHash[path] = readFile(path, "utf8");
7
+ }
8
+ return filePromisesHash[path];
9
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ export declare const ENV_CONFIG_PATH = "AWS_CONFIG_FILE";
2
+ export declare const getConfigFilepath: () => string;
@@ -0,0 +1,2 @@
1
+ export declare const ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE";
2
+ export declare const getCredentialsFilepath: () => string;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Get the HOME directory for the current runtime.
3
+ *
4
+ * @internal
5
+ */
6
+ export declare const getHomeDir: () => string;
@@ -0,0 +1,7 @@
1
+ import { ParsedIniData } from "@smithy/types";
2
+ /**
3
+ * Returns the profile data from parsed ini data.
4
+ * * Returns data for `default`
5
+ * * Reads profileName after profile prefix including/excluding quotes
6
+ */
7
+ export declare const getProfileData: (data: ParsedIniData) => ParsedIniData;
@@ -0,0 +1,5 @@
1
+ export declare const ENV_PROFILE = "AWS_PROFILE";
2
+ export declare const DEFAULT_PROFILE = "default";
3
+ export declare const getProfileName: (init: {
4
+ profile?: string;
5
+ }) => string;
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Returns the filepath of the file where SSO token is stored.
3
+ */
4
+ export declare const getSSOTokenFilepath: (id: string) => string;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Cached SSO token retrieved from SSO login flow.
3
+ */
4
+ export interface SSOToken {
5
+ /**
6
+ * A base64 encoded string returned by the sso-oidc service.
7
+ */
8
+ accessToken: string;
9
+ /**
10
+ * The expiration time of the accessToken as an RFC 3339 formatted timestamp.
11
+ */
12
+ expiresAt: string;
13
+ /**
14
+ * The token used to obtain an access token in the event that the accessToken is invalid or expired.
15
+ */
16
+ refreshToken?: string;
17
+ /**
18
+ * The unique identifier string for each client. The client ID generated when performing the registration
19
+ * portion of the OIDC authorization flow. This is used to refresh the accessToken.
20
+ */
21
+ clientId?: string;
22
+ /**
23
+ * A secret string generated when performing the registration portion of the OIDC authorization flow.
24
+ * This is used to refresh the accessToken.
25
+ */
26
+ clientSecret?: string;
27
+ /**
28
+ * The expiration time of the client registration (clientId and clientSecret) as an RFC 3339 formatted timestamp.
29
+ */
30
+ registrationExpiresAt?: string;
31
+ /**
32
+ * The configured sso_region for the profile that credentials are being resolved for.
33
+ */
34
+ region?: string;
35
+ /**
36
+ * The configured sso_start_url for the profile that credentials are being resolved for.
37
+ */
38
+ startUrl?: string;
39
+ }
40
+ /**
41
+ * @param id - can be either a start URL or the SSO session name.
42
+ * Returns the SSO token from the file system.
43
+ */
44
+ export declare const getSSOTokenFromFile: (id: string) => Promise<SSOToken>;
@@ -0,0 +1,6 @@
1
+ import { ParsedIniData } from "@smithy/types";
2
+ /**
3
+ * Returns the sso-session data from parsed ini data by reading
4
+ * ssoSessionName after sso-session prefix including/excluding quotes
5
+ */
6
+ export declare const getSsoSessionData: (data: ParsedIniData) => ParsedIniData;
@@ -0,0 +1,8 @@
1
+ export * from "./getHomeDir";
2
+ export * from "./getProfileName";
3
+ export * from "./getSSOTokenFilepath";
4
+ export * from "./getSSOTokenFromFile";
5
+ export * from "./loadSharedConfigFiles";
6
+ export * from "./loadSsoSessionData";
7
+ export * from "./parseKnownFiles";
8
+ export * from "./types";
@@ -0,0 +1,21 @@
1
+ import { SharedConfigFiles } from "@smithy/types";
2
+ export interface SharedConfigInit {
3
+ /**
4
+ * The path at which to locate the ini credentials file. Defaults to the
5
+ * value of the `AWS_SHARED_CREDENTIALS_FILE` environment variable (if
6
+ * defined) or `~/.aws/credentials` otherwise.
7
+ */
8
+ filepath?: string;
9
+ /**
10
+ * The path at which to locate the ini config file. Defaults to the value of
11
+ * the `AWS_CONFIG_FILE` environment variable (if defined) or
12
+ * `~/.aws/config` otherwise.
13
+ */
14
+ configFilepath?: string;
15
+ /**
16
+ * Configuration files are normally cached after the first time they are loaded. When this
17
+ * property is set, the provider will always reload any configuration files loaded before.
18
+ */
19
+ ignoreCache?: boolean;
20
+ }
21
+ export declare const loadSharedConfigFiles: (init?: SharedConfigInit) => Promise<SharedConfigFiles>;
@@ -0,0 +1,10 @@
1
+ import { ParsedIniData } from "@smithy/types";
2
+ export interface SsoSessionInit {
3
+ /**
4
+ * The path at which to locate the ini config file. Defaults to the value of
5
+ * the `AWS_CONFIG_FILE` environment variable (if defined) or
6
+ * `~/.aws/config` otherwise.
7
+ */
8
+ configFilepath?: string;
9
+ }
10
+ export declare const loadSsoSessionData: (init?: SsoSessionInit) => Promise<ParsedIniData>;
@@ -0,0 +1,7 @@
1
+ import { ParsedIniData } from "@smithy/types";
2
+ /**
3
+ * Merge multiple profile config files such that settings each file are kept together
4
+ *
5
+ * @internal
6
+ */
7
+ export declare const mergeConfigFiles: (...files: ParsedIniData[]) => ParsedIniData;
@@ -0,0 +1,2 @@
1
+ import { ParsedIniData } from "@smithy/types";
2
+ export declare const parseIni: (iniData: string) => ParsedIniData;
@@ -0,0 +1,15 @@
1
+ import { ParsedIniData } from "@smithy/types";
2
+ import { SharedConfigInit } from "./loadSharedConfigFiles";
3
+ export interface SourceProfileInit extends SharedConfigInit {
4
+ /**
5
+ * The configuration profile to use.
6
+ */
7
+ profile?: string;
8
+ }
9
+ /**
10
+ * Load profiles from credentials and config INI files and normalize them into a
11
+ * single profile list.
12
+ *
13
+ * @internal
14
+ */
15
+ export declare const parseKnownFiles: (init: SourceProfileInit) => Promise<ParsedIniData>;
@@ -0,0 +1,5 @@
1
+ interface SlurpFileOptions {
2
+ ignoreCache?: boolean;
3
+ }
4
+ export declare const slurpFile: (path: string, options?: SlurpFileOptions) => Promise<string>;
5
+ export {};
@@ -0,0 +1,13 @@
1
+ import { ParsedIniData as __ParsedIniData, Profile as __Profile, SharedConfigFiles as __SharedConfigFiles } from "@smithy/types";
2
+ /**
3
+ * @deprecated Use Profile from "@smithy/types" instead
4
+ */
5
+ export type Profile = __Profile;
6
+ /**
7
+ * @deprecated Use ParsedIniData from "@smithy/types" instead
8
+ */
9
+ export type ParsedIniData = __ParsedIniData;
10
+ /**
11
+ * @deprecated Use SharedConfigFiles from "@smithy/types" instead
12
+ */
13
+ export type SharedConfigFiles = __SharedConfigFiles;
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@smithy/shared-ini-file-loader",
3
+ "version": "1.0.0",
4
+ "dependencies": {
5
+ "@smithy/types": "workspace:^",
6
+ "tslib": "^2.5.0"
7
+ },
8
+ "devDependencies": {
9
+ "@tsconfig/recommended": "1.0.1",
10
+ "@types/node": "^14.14.31",
11
+ "concurrently": "7.0.0",
12
+ "downlevel-dts": "0.10.1",
13
+ "jest": "28.1.1",
14
+ "rimraf": "3.0.2",
15
+ "typedoc": "0.23.23",
16
+ "typescript": "~4.9.5"
17
+ },
18
+ "scripts": {
19
+ "build": "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
20
+ "build:cjs": "tsc -p tsconfig.cjs.json",
21
+ "build:es": "tsc -p tsconfig.es.json",
22
+ "build:types": "tsc -p tsconfig.types.json",
23
+ "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
24
+ "stage-release": "rimraf ./.release && yarn pack && mkdir ./.release && tar zxvf ./package.tgz --directory ./.release && rm ./package.tgz",
25
+ "clean": "rimraf ./dist-* && rimraf *.tsbuildinfo",
26
+ "lint": "eslint -c ../../.eslintrc.js \"src/**/*.ts\"",
27
+ "format": "prettier --config ../../prettier.config.js --ignore-path ../.prettierignore --write \"**/*.{ts,md,json}\"",
28
+ "extract:docs": "api-extractor run --local",
29
+ "test": "jest"
30
+ },
31
+ "author": {
32
+ "name": "AWS SDK for JavaScript Team",
33
+ "url": "https://aws.amazon.com/javascript/"
34
+ },
35
+ "license": "Apache-2.0",
36
+ "main": "./dist-cjs/index.js",
37
+ "module": "./dist-es/index.js",
38
+ "types": "./dist-types/index.d.ts",
39
+ "engines": {
40
+ "node": ">=14.0.0"
41
+ },
42
+ "typesVersions": {
43
+ "<4.0": {
44
+ "dist-types/*": [
45
+ "dist-types/ts3.4/*"
46
+ ]
47
+ }
48
+ },
49
+ "files": [
50
+ "dist-*/**"
51
+ ],
52
+ "homepage": "https://github.com/awslabs/smithy-typescript/tree/main/packages/shared-ini-file-loader",
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "https://github.com/awslabs/smithy-typescript.git",
56
+ "directory": "packages/shared-ini-file-loader"
57
+ },
58
+ "typedoc": {
59
+ "entryPoint": "src/index.ts"
60
+ }
61
+ }