dotsec 1.0.0-alpha.2 → 1.0.0-alpha.20

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/dist/cli.js DELETED
@@ -1,2237 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __defProps = Object.defineProperties;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
- var __getProtoOf = Object.getPrototypeOf;
9
- var __hasOwnProp = Object.prototype.hasOwnProperty;
10
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
- var __spreadValues = (a, b) => {
13
- for (var prop in b || (b = {}))
14
- if (__hasOwnProp.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- if (__getOwnPropSymbols)
17
- for (var prop of __getOwnPropSymbols(b)) {
18
- if (__propIsEnum.call(b, prop))
19
- __defNormalProp(a, prop, b[prop]);
20
- }
21
- return a;
22
- };
23
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
- var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
25
- var __export = (target, all) => {
26
- __markAsModule(target);
27
- for (var name in all)
28
- __defProp(target, name, { get: all[name], enumerable: true });
29
- };
30
- var __reExport = (target, module2, desc10) => {
31
- if (module2 && typeof module2 === "object" || typeof module2 === "function") {
32
- for (let key of __getOwnPropNames(module2))
33
- if (!__hasOwnProp.call(target, key) && key !== "default")
34
- __defProp(target, key, { get: () => module2[key], enumerable: !(desc10 = __getOwnPropDesc(module2, key)) || desc10.enumerable });
35
- }
36
- return target;
37
- };
38
- var __toModule = (module2) => {
39
- return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
40
- };
41
-
42
- // src/cli.ts
43
- var import_helpers = __toModule(require("yargs/helpers"));
44
- var import_yargs = __toModule(require("yargs/yargs"));
45
-
46
- // src/commonCliOptions.ts
47
- var commonCliOptions = {
48
- awsProfile: {
49
- string: true,
50
- describe: "AWS profile"
51
- },
52
- awsRegion: {
53
- string: true,
54
- describe: "AWS region"
55
- },
56
- awsKeyAlias: {
57
- string: true,
58
- describe: "AWS KMS key alias"
59
- },
60
- awsKeyArn: {
61
- string: true,
62
- describe: "AWS KMS key id"
63
- },
64
- awsKey: {
65
- string: true,
66
- describe: "AWS KMS key arn"
67
- },
68
- envFile: {
69
- string: true,
70
- describe: ".env file"
71
- },
72
- ignoreMissingEnvFile: {
73
- boolean: true,
74
- describe: `Don't halt on missing .env file`
75
- },
76
- secFile: {
77
- string: true,
78
- describe: ".sec file",
79
- default: ".sec"
80
- },
81
- awsAssumeRoleArn: {
82
- string: true,
83
- describe: "arn or role to assume. Can also be set using the AWS_ASSUME_ROLE_ARN environment variable, or, when using --env-file in the target env file. The cli option overrides the environment variable."
84
- },
85
- awsAssumeRoleSessionDuration: {
86
- number: true,
87
- describe: "Duration of assume role sessions. Defaults to 3600 seconds. Can also be set using the AWS_ASSUME_ROLE_SESSION_DURATION environment variable, or, when using --env-file in the target env file. The cli option overrides the environment variable."
88
- },
89
- useTopLevelsAsEnvironments: {
90
- boolean: true,
91
- describe: "Use top level keys as environments"
92
- },
93
- verbose: {
94
- boolean: true,
95
- describe: "Be verbose"
96
- },
97
- encryptedSecretsFile: {
98
- string: true,
99
- describe: "filename of json file for reading encrypted secrets"
100
- },
101
- jsonFilter: {
102
- string: true,
103
- describe: "dot separated filter path, for example a.b.c will return { a: { b: { c: ... }}}"
104
- },
105
- searchpath: {
106
- string: true,
107
- describe: "search path in which to look for secrets tree"
108
- },
109
- yes: {
110
- boolean: true,
111
- describe: "Proceeds without confirmation"
112
- },
113
- dryRun: {
114
- boolean: true,
115
- describe: "Do a dry run"
116
- }
117
- };
118
-
119
- // src/commands/convert.ts
120
- var convertModule = {
121
- command: "convert",
122
- describe: "does stuff",
123
- builder: {
124
- "env-file": commonCliOptions.envFile,
125
- "search-path": commonCliOptions.searchpath,
126
- "aws-profile": commonCliOptions.awsProfile,
127
- "aws-region": commonCliOptions.awsRegion,
128
- "aws-key-alias": commonCliOptions.awsKeyAlias,
129
- "aws-assume-role-arn": commonCliOptions.awsAssumeRoleArn,
130
- "aws-assume-role-session-duration": commonCliOptions.awsAssumeRoleSessionDuration,
131
- "use-top-levels-as-environments": commonCliOptions.useTopLevelsAsEnvironments,
132
- verbose: commonCliOptions.verbose,
133
- yes: __spreadValues({}, commonCliOptions.yes)
134
- },
135
- handler: (a) => {
136
- console.log(a.d);
137
- console.log(a["env-file"]);
138
- }
139
- };
140
- var convert_default = convertModule;
141
-
142
- // src/commands/defaultCommand.ts
143
- var defaultCommand_exports = {};
144
- __export(defaultCommand_exports, {
145
- builder: () => builder,
146
- command: () => command,
147
- desc: () => desc,
148
- handler: () => handler
149
- });
150
- var import_node_fs = __toModule(require("node:fs"));
151
- var import_node_path4 = __toModule(require("node:path"));
152
- var import_client_kms2 = __toModule(require("@aws-sdk/client-kms"));
153
- var import_chalk3 = __toModule(require("chalk"));
154
- var import_constant_case = __toModule(require("constant-case"));
155
- var import_cross_spawn = __toModule(require("cross-spawn"));
156
- var import_dotenv = __toModule(require("dotenv"));
157
- var import_flat = __toModule(require("flat"));
158
-
159
- // src/lib/config-old/index.ts
160
- var import_node_path2 = __toModule(require("node:path"));
161
- var import_bundle_require = __toModule(require("bundle-require"));
162
- var import_joycon = __toModule(require("joycon"));
163
-
164
- // src/lib/json.ts
165
- var import_fs = __toModule(require("fs"));
166
- var import_node_path = __toModule(require("node:path"));
167
- function jsoncParse(data) {
168
- try {
169
- return new Function("return " + data.trim())();
170
- } catch {
171
- return {};
172
- }
173
- }
174
- var loadJson = async (filepath) => {
175
- try {
176
- return jsoncParse(await import_fs.default.promises.readFile(filepath, "utf8"));
177
- } catch (error) {
178
- if (error instanceof Error) {
179
- throw new Error(`Failed to parse ${import_node_path.default.relative(process.cwd(), filepath)}: ${error.message}`);
180
- } else {
181
- throw error;
182
- }
183
- }
184
- };
185
-
186
- // src/lib/config-old/constants.ts
187
- var defaultConfig = {
188
- aws: {
189
- keyAlias: "alias/top-secret"
190
- }
191
- };
192
-
193
- // src/lib/config-old/index.ts
194
- var getConfig = async () => {
195
- const cwd = process.cwd();
196
- const configJoycon = new import_joycon.default();
197
- const configPath = await configJoycon.resolve({
198
- files: [
199
- "dotsec.config.ts",
200
- "dotsec.config.js",
201
- "dotsec.config.cjs",
202
- "dotsec.config.mjs",
203
- "dotsec.config.json",
204
- "package.json"
205
- ],
206
- cwd,
207
- stopDir: import_node_path2.default.parse(cwd).root,
208
- packageKey: "dotsec"
209
- });
210
- if (configPath) {
211
- if (configPath.endsWith(".json")) {
212
- const rawData = await loadJson(configPath);
213
- let data;
214
- if (configPath.endsWith("package.json") && rawData.dotsec !== void 0) {
215
- data = rawData.dotsec;
216
- } else {
217
- data = rawData;
218
- }
219
- return __spreadProps(__spreadValues(__spreadValues({}, defaultConfig), data), {
220
- aws: __spreadValues(__spreadValues({}, defaultConfig.aws), data.aws)
221
- });
222
- }
223
- const config = await (0, import_bundle_require.bundleRequire)({
224
- filepath: configPath
225
- });
226
- const retrievedConfig = config.mod.dotsec || config.mod.default || config.mod;
227
- return __spreadValues(__spreadValues({}, defaultConfig), retrievedConfig);
228
- }
229
- return __spreadValues({}, defaultConfig);
230
- };
231
-
232
- // src/lib/encryptedSecrets.ts
233
- var import_fs2 = __toModule(require("fs"));
234
- var import_path = __toModule(require("path"));
235
- var import_chalk = __toModule(require("chalk"));
236
-
237
- // src/utils/io.ts
238
- var import_promises = __toModule(require("fs/promises"));
239
- var import_prompts = __toModule(require("prompts"));
240
- var import_node_path3 = __toModule(require("node:path"));
241
- var fileExists = async (source) => {
242
- try {
243
- await (0, import_promises.stat)(source);
244
- return true;
245
- } catch {
246
- return false;
247
- }
248
- };
249
- var promptOverwriteIfFileExists = async ({
250
- filePath,
251
- skip
252
- }) => {
253
- let overwriteResponse;
254
- if (await fileExists(filePath) && skip !== true) {
255
- overwriteResponse = await (0, import_prompts.default)({
256
- type: "confirm",
257
- name: "overwrite",
258
- message: () => {
259
- return `Overwrite './${import_node_path3.default.relative(process.cwd(), filePath)}' ?`;
260
- }
261
- });
262
- } else {
263
- overwriteResponse = void 0;
264
- }
265
- return overwriteResponse;
266
- };
267
-
268
- // src/lib/encryptedSecrets.ts
269
- var loadEncryptedSecrets = async ({
270
- encryptedSecretsFile
271
- }) => {
272
- const encryptedSecretsPath = import_path.default.resolve(process.cwd(), encryptedSecretsFile);
273
- if (!await fileExists(encryptedSecretsPath)) {
274
- throw new Error(`Could not open ${(0, import_chalk.redBright)(encryptedSecretsPath)}`);
275
- }
276
- const encryptedSecrets = JSON.parse(import_fs2.default.readFileSync(encryptedSecretsPath, { encoding: "utf8" }));
277
- if (!encryptedSecrets) {
278
- throw new Error(`No encrypted secrets found in ${(0, import_chalk.redBright)(encryptedSecretsPath)}`);
279
- }
280
- if (!encryptedSecrets.encryptedParameters) {
281
- throw new Error(`Expected 'encryptedParameters' property, but got none`);
282
- }
283
- return encryptedSecrets;
284
- };
285
-
286
- // src/utils/getCredentialsProfileRegion.ts
287
- var import_credential_providers = __toModule(require("@aws-sdk/credential-providers"));
288
- var import_shared_ini_file_loader = __toModule(require("@aws-sdk/shared-ini-file-loader"));
289
-
290
- // src/utils/logger.ts
291
- var import_chalk2 = __toModule(require("chalk"));
292
- var import_cli_highlight = __toModule(require("cli-highlight"));
293
- var _logger;
294
- var getLogger = () => {
295
- if (!_logger) {
296
- _logger = console;
297
- }
298
- return _logger;
299
- };
300
- var emphasis = (str) => import_chalk2.default.yellowBright(str);
301
- var strong = (str) => import_chalk2.default.yellow.bold(str);
302
- var myTheme = {
303
- attr: import_chalk2.default.yellow.bold,
304
- string: import_chalk2.default.yellowBright.dim,
305
- params: import_chalk2.default.red,
306
- deletion: import_chalk2.default.red.strikethrough,
307
- number: import_cli_highlight.plain
308
- };
309
- var prettyCode = (str) => {
310
- return (0, import_cli_highlight.highlight)(str, { theme: myTheme });
311
- };
312
-
313
- // src/utils/getCredentialsProfileRegion.ts
314
- var getCredentialsProfileRegion = async ({
315
- argv,
316
- env
317
- }) => {
318
- var _a, _b, _c;
319
- const sharedConfigFiles = await (0, import_shared_ini_file_loader.loadSharedConfigFiles)();
320
- let credentialsAndOrigin = void 0;
321
- let profileAndOrigin = void 0;
322
- let regionAndOrigin = void 0;
323
- if (argv.profile) {
324
- profileAndOrigin = {
325
- value: argv.profile,
326
- origin: `command line option: ${emphasis(argv.profile)}`
327
- };
328
- credentialsAndOrigin = {
329
- value: await (0, import_credential_providers.fromIni)({
330
- profile: argv.profile
331
- })(),
332
- origin: `${emphasis(`[${argv.profile}]`)} in credentials file`
333
- };
334
- } else if (env.AWS_PROFILE) {
335
- profileAndOrigin = {
336
- value: env.AWS_PROFILE,
337
- origin: `env variable ${emphasis("AWS_PROFILE")}: ${strong(env.AWS_PROFILE)}`
338
- };
339
- credentialsAndOrigin = {
340
- value: await (0, import_credential_providers.fromIni)({
341
- profile: env.AWS_PROFILE
342
- })(),
343
- origin: `env variable ${emphasis("AWS_PROFILE")}: ${strong(env.AWS_PROFILE)}`
344
- };
345
- } else if (env.AWS_ACCESS_KEY_ID && env.AWS_SECRET_ACCESS_KEY) {
346
- credentialsAndOrigin = {
347
- value: await (0, import_credential_providers.fromEnv)()(),
348
- origin: `env variables ${emphasis("AWS_ACCESS_KEY_ID")} and ${emphasis("AWS_SECRET_ACCESS_KEY")}`
349
- };
350
- } else if ((_a = sharedConfigFiles.credentialsFile) == null ? void 0 : _a.default) {
351
- profileAndOrigin = {
352
- value: "default",
353
- origin: `${emphasis("[default]")} in credentials file`
354
- };
355
- credentialsAndOrigin = {
356
- value: await (0, import_credential_providers.fromIni)({
357
- profile: "default"
358
- })(),
359
- origin: `profile ${emphasis("[default]")}`
360
- };
361
- }
362
- if (argv.region) {
363
- regionAndOrigin = {
364
- value: argv.region,
365
- origin: `command line option: ${emphasis(argv.region)}`
366
- };
367
- } else if (env.AWS_REGION) {
368
- regionAndOrigin = {
369
- value: env.AWS_REGION,
370
- origin: `env variable ${emphasis("AWS_REGION")}: ${strong(env.AWS_REGION)}`
371
- };
372
- } else if (env.AWS_DEFAULT_REGION) {
373
- regionAndOrigin = {
374
- value: env.AWS_DEFAULT_REGION,
375
- origin: `env variable ${emphasis("AWS_DEFAULT_REGION")}: ${strong(env.AWS_DEFAULT_REGION)}`
376
- };
377
- } else if (profileAndOrigin) {
378
- const foundRegion = (_c = (_b = sharedConfigFiles == null ? void 0 : sharedConfigFiles.configFile) == null ? void 0 : _b[profileAndOrigin.value]) == null ? void 0 : _c.region;
379
- if (foundRegion) {
380
- regionAndOrigin = {
381
- value: foundRegion,
382
- origin: `${emphasis(`[profile ${profileAndOrigin.value}]`)} in config file`
383
- };
384
- }
385
- }
386
- const assumedRole = argv.assumeRoleArn || env.AWS_ASSUME_ROLE_ARN;
387
- if (assumedRole) {
388
- const origin = argv.assumeRoleArn ? "command line option" : "env variable";
389
- credentialsAndOrigin = {
390
- value: await (0, import_credential_providers.fromTemporaryCredentials)({
391
- masterCredentials: credentialsAndOrigin == null ? void 0 : credentialsAndOrigin.value,
392
- params: {
393
- DurationSeconds: argv.assumeRoleSessionDuration || Number(env.AWS_ASSUME_ROLE_SESSION_DURATION) || 3600,
394
- RoleArn: assumedRole
395
- },
396
- clientConfig: {
397
- region: regionAndOrigin == null ? void 0 : regionAndOrigin.value
398
- }
399
- })(),
400
- origin: `${origin} ${emphasis(`[${assumedRole}]`)}`
401
- };
402
- }
403
- return { credentialsAndOrigin, regionAndOrigin, profileAndOrigin };
404
- };
405
- var printVerboseCredentialsProfileRegion = ({
406
- credentialsAndOrigin,
407
- regionAndOrigin,
408
- profileAndOrigin
409
- }) => {
410
- const out = [];
411
- if (profileAndOrigin) {
412
- out.push(`Got profile name from ${profileAndOrigin.origin}`);
413
- }
414
- if (credentialsAndOrigin) {
415
- out.push(`Resolved credentials from ${credentialsAndOrigin.origin}`);
416
- }
417
- if (regionAndOrigin) {
418
- out.push(`Resolved region from ${regionAndOrigin.origin}`);
419
- }
420
- return out.join("\n");
421
- };
422
-
423
- // src/lib/partial-commands/handleCredentialsAndRegion.ts
424
- var handleCredentialsAndRegion = async ({
425
- argv,
426
- env
427
- }) => {
428
- const { credentialsAndOrigin, regionAndOrigin, profileAndOrigin } = await getCredentialsProfileRegion({
429
- argv: {
430
- region: argv.awsRegion,
431
- profile: argv.awsProfile,
432
- assumeRoleArn: argv.awsAssumeRoleArn,
433
- assumeRoleSessionDuration: argv.awsAssumeRoleSessionDuration
434
- },
435
- env: __spreadValues({}, env)
436
- });
437
- if (argv.verbose === true) {
438
- console.log(printVerboseCredentialsProfileRegion({
439
- credentialsAndOrigin,
440
- regionAndOrigin,
441
- profileAndOrigin
442
- }));
443
- }
444
- if (!credentialsAndOrigin || !regionAndOrigin) {
445
- if (!credentialsAndOrigin) {
446
- console.error("Could not find credentials");
447
- throw new Error("Could not find credentials");
448
- }
449
- if (!regionAndOrigin) {
450
- console.error("Could not find region");
451
- throw new Error("Could not find region");
452
- }
453
- }
454
- return { credentialsAndOrigin, regionAndOrigin };
455
- };
456
-
457
- // src/utils/kms.ts
458
- var import_client_kms = __toModule(require("@aws-sdk/client-kms"));
459
- var getKMSClient = ({
460
- configuration
461
- }) => {
462
- const kmsClient = new import_client_kms.KMSClient(configuration);
463
- return kmsClient;
464
- };
465
- var getEncryptionAlgorithm = async (kmsClient, awsKeyAlias) => {
466
- var _a, _b;
467
- const describeKeyCommand = new import_client_kms.DescribeKeyCommand({
468
- KeyId: awsKeyAlias
469
- });
470
- const describeKeyResult = await kmsClient.send(describeKeyCommand);
471
- const encryptionAlgorithm = (_b = (_a = describeKeyResult.KeyMetadata) == null ? void 0 : _a.EncryptionAlgorithms) == null ? void 0 : _b[0];
472
- if (encryptionAlgorithm === void 0) {
473
- throw new Error(`Could not determine encryption algorithm`);
474
- }
475
- return encryptionAlgorithm;
476
- };
477
-
478
- // src/commands/defaultCommand.ts
479
- var command = "$0 <command>";
480
- var desc = "Decrypts a .sec file, injects the results into a separate process and runs a command";
481
- var builder = {
482
- "aws-profile": commonCliOptions.awsProfile,
483
- "aws-region": commonCliOptions.awsRegion,
484
- "aws-key-alias": commonCliOptions.awsKeyAlias,
485
- "sec-file": commonCliOptions.secFile,
486
- "env-file": commonCliOptions.envFile,
487
- "ignore-missing-env-file": commonCliOptions.ignoreMissingEnvFile,
488
- "aws-assume-role-arn": commonCliOptions.awsAssumeRoleArn,
489
- "aws-assume-role-session-duration": commonCliOptions.awsAssumeRoleSessionDuration,
490
- "encrypted-secrets-file": commonCliOptions.encryptedSecretsFile,
491
- "json-filter": commonCliOptions.jsonFilter,
492
- verbose: commonCliOptions.verbose,
493
- command: { string: true, required: true }
494
- };
495
- var handleSec = async ({
496
- secFile,
497
- credentialsAndOrigin,
498
- regionAndOrigin,
499
- awsKeyAlias
500
- }) => {
501
- const secSource = import_node_path4.default.resolve(process.cwd(), secFile);
502
- if (!await fileExists(secSource)) {
503
- console.error(`Could not open ${(0, import_chalk3.redBright)(secSource)}`);
504
- return;
505
- }
506
- const parsedSec = (0, import_dotenv.parse)(import_node_fs.default.readFileSync(secSource, { encoding: "utf8" }));
507
- const kmsClient = new import_client_kms2.KMSClient({
508
- credentials: credentialsAndOrigin.value,
509
- region: regionAndOrigin.value
510
- });
511
- const encryptionAlgorithm = await getEncryptionAlgorithm(kmsClient, awsKeyAlias);
512
- const envEntries = await Promise.all(Object.entries(parsedSec).map(async ([key, cipherText]) => {
513
- const decryptCommand = new import_client_kms2.DecryptCommand({
514
- KeyId: awsKeyAlias,
515
- CiphertextBlob: Buffer.from(cipherText, "base64"),
516
- EncryptionAlgorithm: encryptionAlgorithm
517
- });
518
- const decryptionResult = await kmsClient.send(decryptCommand);
519
- if (!(decryptionResult == null ? void 0 : decryptionResult.Plaintext)) {
520
- throw new Error(`No: ${JSON.stringify({
521
- key,
522
- cipherText,
523
- decryptCommand
524
- })}`);
525
- }
526
- const value = Buffer.from(decryptionResult.Plaintext).toString();
527
- return [key, value];
528
- }));
529
- const env = Object.fromEntries(envEntries);
530
- return env;
531
- };
532
- var handleEncryptedJson = async ({
533
- encryptedSecretsFile,
534
- jsonFilter,
535
- credentialsAndOrigin,
536
- regionAndOrigin,
537
- awsKeyAlias
538
- }) => {
539
- const encryptedSecrets = await loadEncryptedSecrets({
540
- encryptedSecretsFile
541
- });
542
- const flattened = import_flat.default.flatten(encryptedSecrets.encryptedParameters, {
543
- delimiter: "__",
544
- transformKey: (key) => {
545
- return (0, import_constant_case.constantCase)(key);
546
- }
547
- });
548
- const kmsClient = new import_client_kms2.KMSClient({
549
- credentials: credentialsAndOrigin.value,
550
- region: regionAndOrigin.value
551
- });
552
- const encryptionAlgorithm = await getEncryptionAlgorithm(kmsClient, awsKeyAlias);
553
- const filterKey = jsonFilter == null ? void 0 : jsonFilter.split(".").map((part) => (0, import_constant_case.constantCase)(part)).join("__");
554
- const envEntries = await Promise.all(Object.entries(flattened).filter(([key]) => {
555
- if (filterKey) {
556
- return key.indexOf(filterKey) === 0;
557
- }
558
- return true;
559
- }).map(async ([key, cipherText]) => {
560
- const decryptCommand = new import_client_kms2.DecryptCommand({
561
- KeyId: awsKeyAlias,
562
- CiphertextBlob: Buffer.from(cipherText, "base64"),
563
- EncryptionAlgorithm: encryptionAlgorithm
564
- });
565
- const decryptionResult = await kmsClient.send(decryptCommand);
566
- if (!(decryptionResult == null ? void 0 : decryptionResult.Plaintext)) {
567
- throw new Error(`No: ${JSON.stringify({
568
- key,
569
- cipherText,
570
- decryptCommand
571
- })}`);
572
- }
573
- const value = Buffer.from(decryptionResult.Plaintext).toString();
574
- return [key, value];
575
- }));
576
- const env = Object.fromEntries(envEntries);
577
- return env;
578
- };
579
- var handler = async (argv) => {
580
- const config = await getConfig();
581
- try {
582
- let env;
583
- let awsEnv;
584
- try {
585
- if (argv.envFile) {
586
- env = (0, import_dotenv.parse)(import_node_fs.default.readFileSync(argv.envFile, { encoding: "utf8" }));
587
- if (argv.awsAssumeRoleArn || process.env.AWS_ASSUME_ROLE_ARN || (env == null ? void 0 : env.AWS_ASSUME_ROLE_ARN)) {
588
- const { credentialsAndOrigin, regionAndOrigin } = await handleCredentialsAndRegion({
589
- argv: __spreadProps(__spreadValues({}, argv), {
590
- awsRegion: config.aws.region || argv.awsRegion,
591
- awsProfile: config.aws.profile || argv.awsProfile,
592
- awsAssumeRoleArn: config.aws.assumeRoleArn || argv.awsAssumeRoleArn,
593
- awsAssumeRoleSessionDuration: config.aws.assumeRoleSessionDuration || argv.awsAssumeRoleSessionDuration
594
- }),
595
- env: __spreadValues({}, process.env)
596
- });
597
- awsEnv = {
598
- AWS_ACCESS_KEY_ID: credentialsAndOrigin.value.accessKeyId,
599
- AWS_SECRET_ACCESS_KEY: credentialsAndOrigin.value.secretAccessKey
600
- };
601
- if (credentialsAndOrigin.value.sessionToken) {
602
- awsEnv.AWS_SESSION_TOKEN = credentialsAndOrigin.value.sessionToken;
603
- }
604
- }
605
- } else {
606
- const { credentialsAndOrigin, regionAndOrigin } = await handleCredentialsAndRegion({
607
- argv: __spreadProps(__spreadValues({}, argv), {
608
- awsRegion: config.aws.region || argv.awsRegion,
609
- awsProfile: config.aws.profile || argv.awsProfile,
610
- awsAssumeRoleArn: config.aws.assumeRoleArn || argv.awsAssumeRoleArn,
611
- awsAssumeRoleSessionDuration: config.aws.assumeRoleSessionDuration || argv.awsAssumeRoleSessionDuration
612
- }),
613
- env: __spreadValues({}, process.env)
614
- });
615
- if ((argv.awsAssumeRoleArn || process.env.AWS_ASSUME_ROLE_ARN || (env == null ? void 0 : env.AWS_ASSUME_ROLE_ARN)) && credentialsAndOrigin.value.sessionToken !== void 0) {
616
- awsEnv = {
617
- AWS_ACCESS_KEY_ID: credentialsAndOrigin.value.accessKeyId,
618
- AWS_SECRET_ACCESS_KEY: credentialsAndOrigin.value.secretAccessKey,
619
- AWS_SESSION_TOKEN: credentialsAndOrigin.value.sessionToken
620
- };
621
- }
622
- if (argv.verbose) {
623
- console.log({ credentialsAndOrigin, regionAndOrigin });
624
- }
625
- const awsKeyAlias = argv.awsKeyAlias || config.aws.keyAlias;
626
- if (argv.encryptedSecretsFile) {
627
- env = await handleEncryptedJson({
628
- encryptedSecretsFile: argv.encryptedSecretsFile,
629
- jsonFilter: argv.jsonFilter,
630
- credentialsAndOrigin,
631
- regionAndOrigin,
632
- awsKeyAlias
633
- });
634
- } else {
635
- env = await handleSec({
636
- secFile: argv.secFile,
637
- credentialsAndOrigin,
638
- regionAndOrigin,
639
- awsKeyAlias
640
- });
641
- }
642
- }
643
- } catch (e) {
644
- if (argv.ignoreMissingEnvFile !== true) {
645
- throw e;
646
- }
647
- }
648
- const userCommandArgs = process.argv.slice(process.argv.indexOf(argv.command) + 1);
649
- if (argv.command) {
650
- (0, import_cross_spawn.spawn)(argv.command, [...userCommandArgs], {
651
- stdio: "inherit",
652
- shell: false,
653
- env: __spreadValues(__spreadValues(__spreadValues({}, process.env), awsEnv), env)
654
- });
655
- }
656
- } catch (e) {
657
- console.error(e);
658
- }
659
- };
660
-
661
- // src/commands/dot-sec-to-dot-env.ts
662
- var dot_sec_to_dot_env_exports = {};
663
- __export(dot_sec_to_dot_env_exports, {
664
- builder: () => builder2,
665
- command: () => command2,
666
- desc: () => desc2,
667
- handler: () => handler2
668
- });
669
- var import_node_fs3 = __toModule(require("node:fs"));
670
- var import_node_path8 = __toModule(require("node:path"));
671
- var dotenv = __toModule(require("dotenv"));
672
-
673
- // src/lib/wtf/crypto.ts
674
- var import_client_kms3 = __toModule(require("@aws-sdk/client-kms"));
675
- var import_client_secrets_manager2 = __toModule(require("@aws-sdk/client-secrets-manager"));
676
- var import_client_ssm2 = __toModule(require("@aws-sdk/client-ssm"));
677
- var import_constant_case2 = __toModule(require("constant-case"));
678
-
679
- // src/utils/secretsManager.ts
680
- var import_client_secrets_manager = __toModule(require("@aws-sdk/client-secrets-manager"));
681
- var getSecretsManagerClient = ({
682
- configuration
683
- }) => {
684
- const secretsManagerClient = new import_client_secrets_manager.SecretsManagerClient(configuration);
685
- return secretsManagerClient;
686
- };
687
-
688
- // src/utils/ssm.ts
689
- var import_client_ssm = __toModule(require("@aws-sdk/client-ssm"));
690
- var getSSMClient = ({
691
- configuration
692
- }) => {
693
- const ssmClient = new import_client_ssm.SSMClient(configuration);
694
- return ssmClient;
695
- };
696
-
697
- // src/lib/wtf/types.ts
698
- var isString = (value) => {
699
- return typeof value === "string";
700
- };
701
- var isNumber = (value) => {
702
- return typeof value === "number";
703
- };
704
- var isBoolean = (value) => {
705
- return typeof value === "boolean";
706
- };
707
- var isSSMParameter = (leafOrTree) => {
708
- const ssmParameter = leafOrTree;
709
- return typeof ssmParameter === "object" && ssmParameter !== null && "type" in ssmParameter && ssmParameter.type === "ssm";
710
- };
711
- var isRegularParameterObject = (value) => {
712
- const regularParameter = value;
713
- return typeof regularParameter === "object" && regularParameter !== null && "type" in regularParameter && regularParameter.type === "standard";
714
- };
715
- var isRegularParameter = (leafOrTree) => {
716
- const leaf = leafOrTree;
717
- return isString(leaf) || isNumber(leaf) || isBoolean(leaf) || isRegularParameterObject(leaf);
718
- };
719
- var isEncryptedSSMParameter = (leafOrTree) => {
720
- const leaf = leafOrTree;
721
- return leaf.type !== void 0 && leaf.type === "ssm" && leaf.encryptedValue !== void 0;
722
- };
723
- var isEncryptedRegularParameter = (leafOrTree) => {
724
- const leaf = leafOrTree;
725
- return leaf.type !== void 0 && leaf.type === "standard" && leaf.encryptedValue !== void 0;
726
- };
727
- var isSecretsManagerParameter = (leafOrTree) => {
728
- const leaf = leafOrTree;
729
- return leaf.type !== void 0 && leaf.type === "secretsManager" && !(isString(leaf) || isNumber(leaf) || isBoolean(leaf));
730
- };
731
- var isDotSecTree = (leafOrTree) => {
732
- if (typeof leafOrTree === "object" && !Array.isArray(leafOrTree) && leafOrTree !== null && !isSSMParameter(leafOrTree) && !isRegularParameter(leafOrTree) && !isEncryptedSSMParameter(leafOrTree) && !isEncryptedRegularParameter(leafOrTree) && !isSecretsManagerParameter(leafOrTree)) {
733
- return true;
734
- }
735
- return false;
736
- };
737
-
738
- // src/lib/wtf/flat.ts
739
- var flattenTree = (tree) => {
740
- const lazy = {};
741
- const innerParser = (leafOrTree, paths = []) => {
742
- if (isDotSecTree(leafOrTree)) {
743
- Object.entries(leafOrTree).map(([key, value]) => {
744
- innerParser(value, [...paths, key]);
745
- });
746
- } else {
747
- lazy[paths.join("/")] = leafOrTree;
748
- }
749
- };
750
- innerParser(tree);
751
- return lazy;
752
- };
753
- var flattenPlainText = (dotSec) => {
754
- return __spreadProps(__spreadValues({}, dotSec), { plaintext: flattenTree(dotSec.plaintext) });
755
- };
756
- var flattenEncrypted = (dotSec) => {
757
- return __spreadProps(__spreadValues({}, dotSec), { encrypted: flattenTree(dotSec.encrypted) });
758
- };
759
- var expandTree = (tree) => {
760
- const lazy = {};
761
- Object.entries(tree).map(([key, value]) => {
762
- const paths = key.split("/");
763
- let current = lazy;
764
- paths.forEach((pathKey, index) => {
765
- if (!current[pathKey]) {
766
- if (index === paths.length - 1) {
767
- current[pathKey] = value;
768
- } else {
769
- current[pathKey] = {};
770
- }
771
- }
772
- current = current[pathKey];
773
- });
774
- });
775
- return lazy;
776
- };
777
- var expandPlainText = (dotSec) => {
778
- return __spreadProps(__spreadValues({}, dotSec), { plaintext: expandTree(dotSec.plaintext) });
779
- };
780
- var expandEncrypted = (dotSec) => {
781
- return __spreadProps(__spreadValues({}, dotSec), { encrypted: expandTree(dotSec.encrypted) });
782
- };
783
-
784
- // src/lib/wtf/crypto.ts
785
- var maybeJson = (value) => {
786
- try {
787
- return JSON.parse(value);
788
- } catch (e) {
789
- return value;
790
- }
791
- };
792
- var decryptedEncrypted = async (options) => {
793
- var _a, _b;
794
- const { dotSecEncrypted, credentials, region, verbose, keyAlias } = options;
795
- const dotSecEncryptedFlattened = flattenEncrypted(dotSecEncrypted);
796
- const { info, table } = getLogger();
797
- const kmsClient = getKMSClient({
798
- configuration: {
799
- credentials,
800
- region
801
- },
802
- verbose
803
- });
804
- const awsKeyAlias = keyAlias || ((_b = (_a = dotSecEncrypted.config) == null ? void 0 : _a.aws) == null ? void 0 : _b.keyAlias);
805
- if (!awsKeyAlias) {
806
- throw new Error("No key alias specified");
807
- }
808
- if (verbose) {
809
- info(`Encrypting using key alias ${emphasis(awsKeyAlias)} in ${emphasis(await kmsClient.config.region())}`);
810
- const describeKeyCommand = new import_client_kms3.DescribeKeyCommand({
811
- KeyId: awsKeyAlias
812
- });
813
- const describeKeyResult = await kmsClient.send(describeKeyCommand);
814
- info("keyMetaData", __spreadValues({}, describeKeyResult.KeyMetadata));
815
- }
816
- const encryptionAlgorithm = await getEncryptionAlgorithm(kmsClient, awsKeyAlias);
817
- const dotSecFlattened = {
818
- config: __spreadValues({}, dotSecEncrypted.config),
819
- plaintext: {}
820
- };
821
- for (const [key, encryptedValue] of Object.entries(dotSecEncryptedFlattened.encrypted)) {
822
- const decryptCommand = new import_client_kms3.DecryptCommand({
823
- KeyId: awsKeyAlias,
824
- CiphertextBlob: Buffer.from(encryptedValue.encryptedValue, "base64"),
825
- EncryptionAlgorithm: encryptionAlgorithm
826
- });
827
- const decryptionResult = await kmsClient.send(decryptCommand);
828
- if (!decryptionResult.Plaintext) {
829
- throw new Error(`Something bad happened: ${JSON.stringify({
830
- key,
831
- cipherText: encryptedValue,
832
- decryptCommand
833
- })}`);
834
- }
835
- if (verbose) {
836
- info(`Decrypting key ${emphasis(key)} ${strong("ok")}`);
837
- }
838
- const decryptedValue = Buffer.from(decryptionResult.Plaintext).toString();
839
- const decryptedKeyValue = JSON.parse(decryptedValue);
840
- dotSecFlattened.plaintext[key] = maybeJson(decryptedKeyValue.value);
841
- }
842
- return expandPlainText(dotSecFlattened);
843
- };
844
- var encryptPlainText = async (options) => {
845
- var _a, _b;
846
- const { dotSecPlainText, credentials, region, verbose, keyAlias } = options;
847
- const dotSecFlattened = flattenPlainText(dotSecPlainText);
848
- const { info } = getLogger();
849
- const kmsClient = getKMSClient({
850
- configuration: {
851
- credentials,
852
- region
853
- },
854
- verbose
855
- });
856
- const awsKeyAlias = keyAlias || ((_b = (_a = dotSecFlattened.config) == null ? void 0 : _a.aws) == null ? void 0 : _b.keyAlias);
857
- if (!awsKeyAlias) {
858
- throw new Error("No key alias specified");
859
- }
860
- if (verbose) {
861
- info(`Encrypting using key alias ${emphasis(awsKeyAlias)} in ${emphasis(await kmsClient.config.region())}`);
862
- const describeKeyCommand = new import_client_kms3.DescribeKeyCommand({
863
- KeyId: awsKeyAlias
864
- });
865
- const describeKeyResult = await kmsClient.send(describeKeyCommand);
866
- info("keyMetaData", __spreadValues({}, describeKeyResult.KeyMetadata));
867
- }
868
- const encryptionAlgorithm = await getEncryptionAlgorithm(kmsClient, awsKeyAlias);
869
- const encryptedDotSecFlattened = {
870
- config: __spreadValues({}, dotSecFlattened.config),
871
- encrypted: {}
872
- };
873
- for (const [key, plainTextValue] of Object.entries(dotSecFlattened.plaintext)) {
874
- let plainTextValueCopy = plainTextValue;
875
- if (typeof plainTextValueCopy !== "string" && typeof plainTextValueCopy !== "number" && typeof plainTextValueCopy !== "boolean") {
876
- plainTextValueCopy = JSON.stringify(plainTextValue);
877
- }
878
- const damn = JSON.stringify({ key, value: plainTextValueCopy });
879
- const encryptCommand = new import_client_kms3.EncryptCommand({
880
- KeyId: awsKeyAlias,
881
- Plaintext: Buffer.from(String(damn)),
882
- EncryptionAlgorithm: encryptionAlgorithm
883
- });
884
- const encryptionResult = await kmsClient.send(encryptCommand);
885
- if (!encryptionResult.CiphertextBlob) {
886
- throw new Error(`Something bad happened: ${JSON.stringify({
887
- key,
888
- value: plainTextValue,
889
- encryptCommand
890
- })}`);
891
- }
892
- if (verbose) {
893
- info(`Encrypting key ${emphasis(key)} ${strong("ok")}`);
894
- }
895
- const cipherText = Buffer.from(encryptionResult.CiphertextBlob).toString("base64");
896
- if (isRegularParameter(plainTextValue)) {
897
- encryptedDotSecFlattened.encrypted[key] = {
898
- type: "standard",
899
- encryptedValue: cipherText
900
- };
901
- } else if (isSSMParameter(plainTextValue)) {
902
- encryptedDotSecFlattened.encrypted[key] = {
903
- type: "ssm",
904
- encryptedValue: cipherText
905
- };
906
- } else if (isSecretsManagerParameter(plainTextValue)) {
907
- encryptedDotSecFlattened.encrypted[key] = {
908
- type: "secretsManager",
909
- encryptedValue: cipherText
910
- };
911
- }
912
- }
913
- return expandEncrypted(encryptedDotSecFlattened);
914
- };
915
- var createStorePlaintextTasks = async (options) => {
916
- var _a, _b, _c, _d, _e, _f, _g, _h;
917
- const { dotSecPlainText, credentials, region, verbose, keyAlias } = options;
918
- const dotSecPlainTextFlattened = flattenPlainText(dotSecPlainText);
919
- const { info } = getLogger();
920
- const ssmClient = getSSMClient({
921
- configuration: {
922
- credentials,
923
- region
924
- },
925
- verbose
926
- });
927
- const secretsManagerClient = getSecretsManagerClient({
928
- configuration: {
929
- credentials,
930
- region
931
- },
932
- verbose
933
- });
934
- const secretNameArnTuples = (_b = (_a = await secretsManagerClient.send(new import_client_secrets_manager2.ListSecretsCommand({}))) == null ? void 0 : _a.SecretList) == null ? void 0 : _b.map((secret) => [secret.Name, secret.ARN]).filter(([name, ARN]) => name && ARN);
935
- const existingSecrets = secretNameArnTuples ? Object.fromEntries(secretNameArnTuples) : {};
936
- const awsKeyAlias = keyAlias || ((_d = (_c = dotSecPlainText.config) == null ? void 0 : _c.aws) == null ? void 0 : _d.keyAlias);
937
- if (!awsKeyAlias) {
938
- throw new Error(`No key alias specified`);
939
- }
940
- if (verbose) {
941
- info(`Encrypting to SSM and/or SecretsManager in ${emphasis(region)}`);
942
- }
943
- const putParameterCommands = [];
944
- const createSecretCommands = [];
945
- const putSecretValueCommands = [];
946
- for (const [keyPath, plainTextValue] of Object.entries(dotSecPlainTextFlattened.plaintext)) {
947
- let storageValue;
948
- if (isRegularParameter(plainTextValue)) {
949
- if (isRegularParameterObject(plainTextValue)) {
950
- storageValue = plainTextValue.value;
951
- } else {
952
- storageValue = plainTextValue;
953
- }
954
- } else if (isSSMParameter(plainTextValue)) {
955
- storageValue = plainTextValue.value;
956
- } else if (isSecretsManagerParameter(plainTextValue)) {
957
- storageValue = plainTextValue.value;
958
- } else {
959
- throw new Error("Invalid parameter type");
960
- }
961
- if (!isString(storageValue) && !isNumber(storageValue) && !isBoolean(storageValue)) {
962
- storageValue = JSON.stringify(storageValue);
963
- }
964
- if (isSSMParameter(plainTextValue) || isRegularParameter(plainTextValue) && ((_e = dotSecPlainText.config) == null ? void 0 : _e.standardParameterStorageType) === "ssm" && (isRegularParameterObject(plainTextValue) ? plainTextValue.dontStore !== true : true)) {
965
- let parameterTier = import_client_ssm2.ParameterTier.STANDARD;
966
- let parameterType = import_client_ssm2.ParameterType.STRING;
967
- let description;
968
- if (isSSMParameter(plainTextValue)) {
969
- if ((_f = plainTextValue == null ? void 0 : plainTextValue.ssm) == null ? void 0 : _f.tier) {
970
- parameterTier = plainTextValue.ssm.tier;
971
- }
972
- if ((_g = plainTextValue == null ? void 0 : plainTextValue.ssm) == null ? void 0 : _g.type) {
973
- parameterType = plainTextValue.ssm.type;
974
- }
975
- if (plainTextValue == null ? void 0 : plainTextValue.description) {
976
- description = plainTextValue.description;
977
- }
978
- }
979
- const putParameterCommand = new import_client_ssm2.PutParameterCommand({
980
- Name: `/${keyPath}`,
981
- Value: String(storageValue),
982
- Type: parameterType,
983
- Tier: parameterTier,
984
- Description: description,
985
- Overwrite: true
986
- });
987
- putParameterCommands.push(putParameterCommand);
988
- } else if (isSecretsManagerParameter(plainTextValue) || isRegularParameter(plainTextValue) && ((_h = dotSecPlainText.config) == null ? void 0 : _h.standardParameterStorageType) === "secretsManager" && (isRegularParameterObject(plainTextValue) ? plainTextValue.dontStore !== true : true)) {
989
- const existingSecretARN = existingSecrets[keyPath];
990
- if (!existingSecretARN) {
991
- const createSecretCommand = new import_client_secrets_manager2.CreateSecretCommand({
992
- Name: keyPath,
993
- SecretString: String(storageValue)
994
- });
995
- createSecretCommands.push(createSecretCommand);
996
- } else {
997
- const putSecretCommand = new import_client_secrets_manager2.PutSecretValueCommand({
998
- SecretId: existingSecretARN,
999
- SecretString: String(storageValue)
1000
- });
1001
- putSecretValueCommands.push(putSecretCommand);
1002
- }
1003
- }
1004
- }
1005
- return {
1006
- total: putParameterCommands.length + createSecretCommands.length + putSecretValueCommands.length,
1007
- putParameterCommands,
1008
- createSecretCommands,
1009
- putSecretValueCommands
1010
- };
1011
- };
1012
- var executeStorePlainTextTasks = async (options) => {
1013
- const { credentials, region, verbose, tasks } = options;
1014
- const { info } = getLogger();
1015
- const ssmClient = getSSMClient({
1016
- configuration: {
1017
- credentials,
1018
- region
1019
- },
1020
- verbose
1021
- });
1022
- const secretsManagerClient = getSecretsManagerClient({
1023
- configuration: {
1024
- credentials,
1025
- region
1026
- },
1027
- verbose
1028
- });
1029
- for (const putParameterCommand of tasks.putParameterCommands) {
1030
- process.stdout.write(`Storing SSM parameter ${emphasis(putParameterCommand.input.Name || "<unnamed> ")}... `);
1031
- await ssmClient.send(putParameterCommand);
1032
- process.stdout.write(`done
1033
- `);
1034
- }
1035
- for (const createSecretCommand of tasks.createSecretCommands) {
1036
- process.stdout.write(`Creating Secret ${emphasis(createSecretCommand.input.Name || "<unnamed> ")}... `);
1037
- await secretsManagerClient.send(createSecretCommand);
1038
- process.stdout.write(`done
1039
- `);
1040
- }
1041
- for (const putSecretValueCommand of tasks.putSecretValueCommands) {
1042
- process.stdout.write(`Updating Secret ${emphasis(putSecretValueCommand.input.SecretId || "<unknown id> ")}... `);
1043
- await secretsManagerClient.send(putSecretValueCommand);
1044
- process.stdout.write(`done
1045
- `);
1046
- }
1047
- };
1048
- var prettyPrintTasks = (tasks) => {
1049
- const { info, table } = getLogger();
1050
- const { putParameterCommands, createSecretCommands, putSecretValueCommands } = tasks;
1051
- const ssmTasks = putParameterCommands.map((command10) => {
1052
- return {
1053
- name: command10.input.Name,
1054
- description: command10.input.Description || "<no description>",
1055
- tier: command10.input.Tier,
1056
- type: command10.input.Type,
1057
- value: command10.input.Value
1058
- };
1059
- });
1060
- info(emphasis(`AWS Systems Manager > Parameter Store: create or update`));
1061
- table(ssmTasks);
1062
- const createSecretTasks = createSecretCommands.map((command10) => {
1063
- return {
1064
- secretName: command10.input.Name,
1065
- description: command10.input.Description || "<no description>",
1066
- value: "**** redacted ****>"
1067
- };
1068
- });
1069
- if (createSecretTasks.length) {
1070
- info(emphasis(`AWS Secrets Manager Secrets: create`));
1071
- table(createSecretTasks);
1072
- }
1073
- const updateSecretTasks = putSecretValueCommands.map((command10) => {
1074
- return {
1075
- secretName: command10.input.SecretId,
1076
- value: "**** redacted ****>"
1077
- };
1078
- });
1079
- if (updateSecretTasks.length) {
1080
- info(emphasis(`AWS Secrets Manager Secrets: update`));
1081
- table(updateSecretTasks);
1082
- }
1083
- };
1084
- var decryptRawDotSecValues = async (options) => {
1085
- const { info } = getLogger();
1086
- const {
1087
- dotSecKeysValues: rawDotSec,
1088
- credentials,
1089
- region,
1090
- verbose,
1091
- keyAlias,
1092
- searchPath
1093
- } = options;
1094
- const kmsClient = getKMSClient({
1095
- configuration: {
1096
- credentials,
1097
- region
1098
- },
1099
- verbose
1100
- });
1101
- const s = searchPath == null ? void 0 : searchPath.split(".").map((part) => `${(0, import_constant_case2.constantCase)(part)}_`).join("");
1102
- const awsKeyAlias = keyAlias;
1103
- if (!keyAlias) {
1104
- throw new Error("No key alias specified");
1105
- }
1106
- const encryptionAlgorithm = await getEncryptionAlgorithm(kmsClient, keyAlias);
1107
- const dotEnvLines = [];
1108
- const filtered = s ? Object.fromEntries(Object.entries(rawDotSec).filter(([key]) => key.startsWith(s)).map(([key, value]) => [key.replace(s, ""), value])) : rawDotSec;
1109
- for (const [key, encryptedValue] of Object.entries(filtered)) {
1110
- const decryptCommand = new import_client_kms3.DecryptCommand({
1111
- KeyId: awsKeyAlias,
1112
- CiphertextBlob: Buffer.from(encryptedValue, "base64"),
1113
- EncryptionAlgorithm: encryptionAlgorithm
1114
- });
1115
- const decryptionResult = await kmsClient.send(decryptCommand);
1116
- if (!decryptionResult.Plaintext) {
1117
- throw new Error(`Something bad happened: ${JSON.stringify({
1118
- key,
1119
- cipherText: encryptedValue,
1120
- decryptCommand
1121
- })}`);
1122
- }
1123
- if (verbose) {
1124
- info(`Decrypting key ${emphasis(key)} ${strong("ok")}`);
1125
- }
1126
- const decryptedValue = Buffer.from(decryptionResult.Plaintext).toString();
1127
- const parsedValue = JSON.parse(decryptedValue);
1128
- const stringOrJson = maybeJson(parsedValue.value);
1129
- if (isRegularParameter(stringOrJson)) {
1130
- if (isRegularParameterObject(stringOrJson)) {
1131
- dotEnvLines.push(`${key}=${JSON.stringify(stringOrJson.value)}`);
1132
- } else {
1133
- dotEnvLines.push(`${key}=${String(stringOrJson)}`);
1134
- }
1135
- } else if (isSSMParameter(stringOrJson)) {
1136
- dotEnvLines.push(`${key}=${JSON.stringify(stringOrJson.value)}`);
1137
- } else if (isSecretsManagerParameter(stringOrJson)) {
1138
- dotEnvLines.push(`${key}=${JSON.stringify(stringOrJson.value)}`);
1139
- }
1140
- }
1141
- return dotEnvLines.join("\n");
1142
- };
1143
-
1144
- // src/lib/wtf/io.ts
1145
- var import_node_fs2 = __toModule(require("node:fs"));
1146
- var import_node_path7 = __toModule(require("node:path"));
1147
- var import_bundle_require2 = __toModule(require("bundle-require"));
1148
- var import_joycon2 = __toModule(require("joycon"));
1149
-
1150
- // src/lib/wtf/json.ts
1151
- var import_fs3 = __toModule(require("fs"));
1152
- var import_node_path5 = __toModule(require("node:path"));
1153
- function jsoncParse2(data) {
1154
- try {
1155
- return new Function("return " + data.trim())();
1156
- } catch {
1157
- return {};
1158
- }
1159
- }
1160
- var loadJson2 = async (filepath) => {
1161
- try {
1162
- return jsoncParse2(await import_fs3.default.promises.readFile(filepath, "utf8"));
1163
- } catch (error) {
1164
- if (error instanceof Error) {
1165
- throw new Error(`Failed to parse ${import_node_path5.default.relative(process.cwd(), filepath)}: ${error.message}`);
1166
- } else {
1167
- throw error;
1168
- }
1169
- }
1170
- };
1171
-
1172
- // src/lib/wtf/yaml.ts
1173
- var import_fs4 = __toModule(require("fs"));
1174
- var import_node_path6 = __toModule(require("node:path"));
1175
- var import_yaml = __toModule(require("yaml"));
1176
- var loadYml = async (filepath) => {
1177
- try {
1178
- return import_yaml.default.parse(await import_fs4.default.promises.readFile(filepath, "utf8"));
1179
- } catch (error) {
1180
- if (error instanceof Error) {
1181
- throw new Error(`Failed to parse ${import_node_path6.default.relative(process.cwd(), filepath)}: ${error.message}`);
1182
- } else {
1183
- throw error;
1184
- }
1185
- }
1186
- };
1187
-
1188
- // src/lib/wtf/io.ts
1189
- var getDotSecPlainText = async ({
1190
- defaultConfig: defaultConfig2,
1191
- options
1192
- }) => {
1193
- var _a, _b, _c, _d, _e, _f;
1194
- const { info } = getLogger();
1195
- const { filename, verbose } = options || {};
1196
- const cwd = process.cwd();
1197
- const configJoycon = new import_joycon2.default();
1198
- const files = filename ? [filename] : [
1199
- "secrets.json",
1200
- "secrets.yaml",
1201
- "secrets.yml",
1202
- "secrets.ts"
1203
- ];
1204
- if (verbose) {
1205
- info(`Looking for file(s) with the following signature(s): ${strong(files.join(", "))}`);
1206
- }
1207
- const configPath = await configJoycon.resolve({
1208
- files,
1209
- cwd,
1210
- stopDir: import_node_path7.default.parse(cwd).root,
1211
- packageKey: "secrets"
1212
- });
1213
- if (configPath) {
1214
- if (verbose) {
1215
- info(`Found plaintext secrets at ${strong(configPath)}`);
1216
- }
1217
- let configType;
1218
- let data;
1219
- if (configPath.endsWith(".json")) {
1220
- configType = "json";
1221
- data = await loadJson2(configPath);
1222
- } else if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
1223
- configType = "yml";
1224
- data = await loadYml(configPath);
1225
- } else if (configPath.endsWith(".ts")) {
1226
- const bundleRequireResult = await (0, import_bundle_require2.bundleRequire)({
1227
- filepath: configPath
1228
- });
1229
- configType = "ts";
1230
- data = bundleRequireResult.mod.dotsec || bundleRequireResult.mod.default || bundleRequireResult.mod;
1231
- }
1232
- if (!configType) {
1233
- throw new Error(`Expected configType, but got none`);
1234
- }
1235
- if (!data) {
1236
- throw new Error(`Expected data, but got none`);
1237
- }
1238
- const validatedConfig = {
1239
- config: __spreadProps(__spreadValues({}, data.config), {
1240
- aws: {
1241
- regions: ((_b = (_a = data == null ? void 0 : data.config) == null ? void 0 : _a.aws) == null ? void 0 : _b.regions) && Array.isArray((_d = (_c = data == null ? void 0 : data.config) == null ? void 0 : _c.aws) == null ? void 0 : _d.regions) ? data.config.aws.regions : defaultConfig2.config.aws.regions,
1242
- keyAlias: ((_f = (_e = data == null ? void 0 : data.config) == null ? void 0 : _e.aws) == null ? void 0 : _f.keyAlias) || defaultConfig2.config.aws.keyAlias
1243
- }
1244
- })
1245
- };
1246
- return {
1247
- fileType: configType,
1248
- path: configPath,
1249
- dotSecPlainText: __spreadValues(__spreadValues({}, data), validatedConfig)
1250
- };
1251
- }
1252
- throw new Error("No secrets file found");
1253
- };
1254
- var getDotSecEncrypted = async ({
1255
- defaultConfig: defaultConfig2,
1256
- options
1257
- }) => {
1258
- var _a, _b, _c, _d, _e, _f;
1259
- const { filename, verbose } = options || {};
1260
- const cwd = process.cwd();
1261
- const configJoycon = new import_joycon2.default();
1262
- const configPath = await configJoycon.resolve({
1263
- files: filename ? [filename] : [
1264
- "secrets.encrypted.json",
1265
- "secrets.encrypted.yaml",
1266
- "secrets.encrypted.yml",
1267
- "secrets.encrypted.ts"
1268
- ],
1269
- cwd,
1270
- stopDir: import_node_path7.default.parse(cwd).root,
1271
- packageKey: "secrets"
1272
- });
1273
- if (configPath) {
1274
- if (verbose) {
1275
- console.log(`Found encrypted secrets file at ${configPath}`);
1276
- }
1277
- let configType;
1278
- let data;
1279
- if (configPath.endsWith(".json")) {
1280
- configType = "json";
1281
- data = await loadJson2(configPath);
1282
- } else if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
1283
- configType = import_node_path7.default.parse(configPath).ext.substring(1);
1284
- data = await loadYml(configPath);
1285
- }
1286
- if (!configType) {
1287
- throw new Error(`Config file ${configPath} is not supported`);
1288
- }
1289
- if (!data) {
1290
- throw new Error("Did not find any data");
1291
- }
1292
- const validatedConfig = {
1293
- config: __spreadProps(__spreadValues({}, data.config), {
1294
- aws: {
1295
- regions: ((_b = (_a = data == null ? void 0 : data.config) == null ? void 0 : _a.aws) == null ? void 0 : _b.regions) && Array.isArray((_d = (_c = data == null ? void 0 : data.config) == null ? void 0 : _c.aws) == null ? void 0 : _d.regions) ? data.config.aws.regions : defaultConfig2.config.aws.regions,
1296
- keyAlias: ((_f = (_e = data == null ? void 0 : data.config) == null ? void 0 : _e.aws) == null ? void 0 : _f.keyAlias) || defaultConfig2.config.aws.keyAlias
1297
- }
1298
- })
1299
- };
1300
- return {
1301
- fileType: configType,
1302
- path: configPath,
1303
- dotSecEncrypted: __spreadValues(__spreadValues({}, data), validatedConfig)
1304
- };
1305
- }
1306
- throw new Error("No encrypted secrets file found");
1307
- };
1308
- var loadFile = async (filepath) => {
1309
- try {
1310
- return await import_node_fs2.default.promises.readFile(filepath, "utf8");
1311
- } catch (error) {
1312
- if (error instanceof Error) {
1313
- throw new Error(`Failed to parse ${import_node_path7.default.relative(process.cwd(), filepath)}: ${error.message}`);
1314
- } else {
1315
- throw error;
1316
- }
1317
- }
1318
- };
1319
-
1320
- // src/commands/dot-sec-to-dot-env.ts
1321
- var command2 = "dot-sec-to-dot-env";
1322
- var desc2 = `Creates .env file from a .sec file.`;
1323
- var builder2 = {
1324
- "sec-file": commonCliOptions.secFile,
1325
- "env-file": commonCliOptions.envFile,
1326
- "aws-profile": commonCliOptions.awsProfile,
1327
- "aws-region": commonCliOptions.awsRegion,
1328
- "aws-key-alias": commonCliOptions.awsKeyAlias,
1329
- "aws-assume-role-arn": commonCliOptions.awsAssumeRoleArn,
1330
- "aws-assume-role-session-duration": commonCliOptions.awsAssumeRoleSessionDuration,
1331
- "use-top-levels-as-environments": commonCliOptions.useTopLevelsAsEnvironments,
1332
- verbose: commonCliOptions.verbose,
1333
- yes: __spreadValues({}, commonCliOptions.yes)
1334
- };
1335
- var handler2 = async (argv) => {
1336
- const config = await getConfig();
1337
- const { error } = getLogger();
1338
- try {
1339
- const defaultRegion = config.aws.region || argv.awsRegion;
1340
- const { credentialsAndOrigin, regionAndOrigin } = await handleCredentialsAndRegion({
1341
- argv: __spreadProps(__spreadValues({}, argv), {
1342
- awsRegion: defaultRegion,
1343
- awsProfile: config.aws.profile || argv.awsProfile,
1344
- awsAssumeRoleArn: config.aws.assumeRoleArn || argv.awsAssumeRoleArn,
1345
- awsAssumeRoleSessionDuration: config.aws.assumeRoleSessionDuration || argv.awsAssumeRoleSessionDuration
1346
- }),
1347
- env: __spreadValues({}, process.env)
1348
- });
1349
- const dotSecFilename = argv.secFile || ".sec";
1350
- const dotSecPath = import_node_path8.default.resolve(process.cwd(), dotSecFilename);
1351
- const dotSecString = await loadFile(dotSecPath);
1352
- const dotSecKeysValues = dotenv.parse(dotSecString);
1353
- const dotEnvString = await decryptRawDotSecValues({
1354
- dotSecKeysValues,
1355
- credentials: credentialsAndOrigin.value,
1356
- region: regionAndOrigin.value,
1357
- keyAlias: argv.awsKeyAlias || "alias/dotsec",
1358
- verbose: argv.verbose
1359
- });
1360
- const dotEnvFilename = argv.envFile || `.env`;
1361
- const dotEnvPath = import_node_path8.default.resolve(process.cwd(), dotEnvFilename);
1362
- const overwriteResponse = await promptOverwriteIfFileExists({
1363
- filePath: dotEnvPath,
1364
- skip: argv.yes
1365
- });
1366
- if (overwriteResponse === void 0 || overwriteResponse.overwrite === true) {
1367
- import_node_fs3.default.writeFileSync(dotEnvPath, dotEnvString);
1368
- }
1369
- } catch (e) {
1370
- error(e);
1371
- }
1372
- };
1373
-
1374
- // src/commands/encrypted-secrets-to-dot-env.ts
1375
- var encrypted_secrets_to_dot_env_exports = {};
1376
- __export(encrypted_secrets_to_dot_env_exports, {
1377
- builder: () => builder3,
1378
- command: () => command3,
1379
- desc: () => desc3,
1380
- handler: () => handler3
1381
- });
1382
- var import_fs5 = __toModule(require("fs"));
1383
- var import_node_path9 = __toModule(require("node:path"));
1384
-
1385
- // src/lib/wtf/dotenv.ts
1386
- var import_constant_case3 = __toModule(require("constant-case"));
1387
- var fromPlainTextLeafsToEnvEntries = (leafs) => {
1388
- return Object.entries(leafs).map(([key, plainTextValue]) => {
1389
- const parts = key.split("/");
1390
- const dotEnvKeyPath = parts.map((k) => (0, import_constant_case3.constantCase)(k)).join("_");
1391
- let storageValue;
1392
- if (isRegularParameter(plainTextValue)) {
1393
- if (isRegularParameterObject(plainTextValue)) {
1394
- storageValue = plainTextValue.value;
1395
- } else {
1396
- storageValue = plainTextValue;
1397
- }
1398
- } else if (isSSMParameter(plainTextValue)) {
1399
- storageValue = plainTextValue.value;
1400
- } else if (isSecretsManagerParameter(plainTextValue)) {
1401
- storageValue = plainTextValue.value;
1402
- } else {
1403
- throw new Error("Invalid parameter type");
1404
- }
1405
- if (!isString(storageValue) && !isNumber(storageValue) && !isBoolean(storageValue)) {
1406
- storageValue = JSON.stringify(storageValue);
1407
- }
1408
- return `${dotEnvKeyPath}=${String(storageValue)}`;
1409
- });
1410
- };
1411
- var toDotEnv = (options) => {
1412
- const { info } = getLogger();
1413
- const { dotSecPlainText, searchPath, verbose } = options;
1414
- let tree = dotSecPlainText.plaintext;
1415
- if (searchPath) {
1416
- if (verbose) {
1417
- info(`Searching for path: ${strong(searchPath)}`);
1418
- }
1419
- const pathParts = searchPath.split("/");
1420
- for (const pathPart of pathParts) {
1421
- tree = tree[pathPart];
1422
- if (tree === void 0) {
1423
- throw new Error(`Invalid search path: '${searchPath}', part: '${pathPart}' could not be found`);
1424
- }
1425
- }
1426
- }
1427
- const flattenedTree = flattenTree(tree);
1428
- return fromPlainTextLeafsToEnvEntries(flattenedTree).join("\n");
1429
- };
1430
- var toDotEnvPerEnvironment = (options) => {
1431
- const { info } = getLogger();
1432
- const { dotSecPlainText, searchPath, verbose } = options;
1433
- const environments = Object.keys(dotSecPlainText.plaintext);
1434
- return Object.fromEntries(environments.map((environment) => {
1435
- let tree = dotSecPlainText.plaintext[environment];
1436
- if (searchPath) {
1437
- if (verbose) {
1438
- info(`Searching for path: ${strong(searchPath)}`);
1439
- }
1440
- const pathParts = searchPath.split("/");
1441
- for (const pathPart of pathParts) {
1442
- tree = tree[pathPart];
1443
- if (tree === void 0) {
1444
- throw new Error(`Invalid search path: '${searchPath}', part: '${pathPart}' could not be found`);
1445
- }
1446
- }
1447
- }
1448
- return [
1449
- environment,
1450
- fromPlainTextLeafsToEnvEntries(flattenTree(tree)).join("\n")
1451
- ];
1452
- }));
1453
- };
1454
-
1455
- // src/commands/encrypted-secrets-to-dot-env.ts
1456
- var command3 = "encrypted-secrets-to-dot-env";
1457
- var desc3 = `Creates .env file from an encrypted secrets file.
1458
- If '--use-top-levels-as-environments' is set, it will create a .env file for each top level key in the encrypted secrets file.`;
1459
- var builder3 = {
1460
- "encrypted-secrets-file": {
1461
- string: true,
1462
- describe: "filename of json file for writing encrypted secrets",
1463
- default: "secrets.encrypted.json"
1464
- },
1465
- "env-file": commonCliOptions.envFile,
1466
- "search-path": commonCliOptions.searchpath,
1467
- "aws-profile": commonCliOptions.awsProfile,
1468
- "aws-region": commonCliOptions.awsRegion,
1469
- "aws-key-alias": commonCliOptions.awsKeyAlias,
1470
- "aws-assume-role-arn": commonCliOptions.awsAssumeRoleArn,
1471
- "aws-assume-role-session-duration": commonCliOptions.awsAssumeRoleSessionDuration,
1472
- "use-top-levels-as-environments": commonCliOptions.useTopLevelsAsEnvironments,
1473
- verbose: commonCliOptions.verbose,
1474
- yes: __spreadValues({}, commonCliOptions.yes)
1475
- };
1476
- var handler3 = async (argv) => {
1477
- var _a;
1478
- const config = await getConfig();
1479
- const { info, error } = getLogger();
1480
- try {
1481
- const defaultRegion = config.aws.region || argv.awsRegion;
1482
- const { credentialsAndOrigin, regionAndOrigin } = await handleCredentialsAndRegion({
1483
- argv: __spreadProps(__spreadValues({}, argv), {
1484
- awsRegion: defaultRegion,
1485
- awsProfile: config.aws.profile || argv.awsProfile,
1486
- awsAssumeRoleArn: config.aws.assumeRoleArn || argv.awsAssumeRoleArn,
1487
- awsAssumeRoleSessionDuration: config.aws.assumeRoleSessionDuration || argv.awsAssumeRoleSessionDuration
1488
- }),
1489
- env: __spreadValues({}, process.env)
1490
- });
1491
- const { fileType, dotSecEncrypted } = await getDotSecEncrypted({
1492
- defaultConfig: {
1493
- config: {
1494
- aws: {
1495
- keyAlias: "alias/dotsec",
1496
- regions: [regionAndOrigin.value]
1497
- }
1498
- }
1499
- },
1500
- options: {
1501
- verbose: argv.verbose
1502
- }
1503
- });
1504
- if (!dotSecEncrypted.encrypted) {
1505
- throw new Error(`Expected 'encrypted' property, but got none`);
1506
- }
1507
- const dotSecPlainText = await decryptedEncrypted({
1508
- dotSecEncrypted,
1509
- credentials: credentialsAndOrigin.value,
1510
- region: regionAndOrigin.value,
1511
- keyAlias: argv.awsKeyAlias,
1512
- verbose: argv.verbose
1513
- });
1514
- if (argv.useTopLevelsAsEnvironments || ((_a = dotSecEncrypted.config) == null ? void 0 : _a.useTopLevelsAsEnvironments)) {
1515
- const dotEnvsPerEnvironment = toDotEnvPerEnvironment({
1516
- dotSecPlainText,
1517
- verbose: argv.verbose
1518
- });
1519
- for (const [environment, dotEnv] of Object.entries(dotEnvsPerEnvironment)) {
1520
- const fileName = `.env.${environment}`;
1521
- const dotEnvPath = import_node_path9.default.resolve(process.cwd(), fileName);
1522
- info(`target: ${strong(dotEnvPath)}
1523
- `);
1524
- info(prettyCode(dotEnv));
1525
- info(`
1526
- `);
1527
- const overwriteResponse = await promptOverwriteIfFileExists({
1528
- filePath: dotEnvPath,
1529
- skip: argv.yes
1530
- });
1531
- if (overwriteResponse === void 0 || overwriteResponse.overwrite === true) {
1532
- import_fs5.default.writeFileSync(dotEnvPath, dotEnv);
1533
- }
1534
- }
1535
- } else {
1536
- const dotEnv = toDotEnv({
1537
- dotSecPlainText,
1538
- verbose: argv.verbose,
1539
- searchPath: argv.searchPath
1540
- });
1541
- const fileName = argv.envFile || `.env`;
1542
- const dotEnvPath = import_node_path9.default.resolve(process.cwd(), fileName);
1543
- info(`target: ${strong(dotEnvPath)}
1544
- `);
1545
- info(prettyCode(dotEnv));
1546
- info(`
1547
- `);
1548
- const overwriteResponse = await promptOverwriteIfFileExists({
1549
- filePath: dotEnvPath,
1550
- skip: argv.yes
1551
- });
1552
- if (overwriteResponse === void 0 || overwriteResponse.overwrite === true) {
1553
- import_fs5.default.writeFileSync(dotEnvPath, dotEnv);
1554
- }
1555
- }
1556
- } catch (e) {
1557
- error(e);
1558
- }
1559
- };
1560
-
1561
- // src/commands/encrypted-secrets-to-dot-sec.ts
1562
- var encrypted_secrets_to_dot_sec_exports = {};
1563
- __export(encrypted_secrets_to_dot_sec_exports, {
1564
- builder: () => builder4,
1565
- command: () => command4,
1566
- desc: () => desc4,
1567
- handler: () => handler4
1568
- });
1569
- var import_fs6 = __toModule(require("fs"));
1570
- var import_node_path10 = __toModule(require("node:path"));
1571
-
1572
- // src/lib/wtf/dotsec.ts
1573
- var import_constant_case4 = __toModule(require("constant-case"));
1574
- var fromEncryptedLeafsToEnvEntries = (leafs) => {
1575
- return Object.entries(leafs).map(([key, plainTextValue]) => {
1576
- const parts = key.split("/");
1577
- const dotEnvKeyPath = parts.map((k) => (0, import_constant_case4.constantCase)(k)).join("_");
1578
- let storageValue;
1579
- if (isEncryptedRegularParameter(plainTextValue)) {
1580
- storageValue = plainTextValue.encryptedValue;
1581
- } else if (isEncryptedSSMParameter(plainTextValue)) {
1582
- storageValue = plainTextValue.encryptedValue;
1583
- } else if (isSecretsManagerParameter(plainTextValue)) {
1584
- storageValue = plainTextValue.encryptedValue;
1585
- } else {
1586
- throw new Error("Invalid parameter type");
1587
- }
1588
- return `${dotEnvKeyPath}=${String(storageValue)}`;
1589
- });
1590
- };
1591
- var toDotSec = (options) => {
1592
- const { info } = getLogger();
1593
- const { dotSecEncrypted, searchPath, verbose } = options;
1594
- let tree = dotSecEncrypted.encrypted;
1595
- if (searchPath) {
1596
- if (verbose) {
1597
- info(`Searching for path: ${strong(searchPath)}`);
1598
- }
1599
- const pathParts = searchPath.split("/");
1600
- for (const pathPart of pathParts) {
1601
- tree = tree[pathPart];
1602
- }
1603
- }
1604
- const flattenedTree = flattenTree(tree);
1605
- return fromEncryptedLeafsToEnvEntries(flattenedTree).join("\n");
1606
- };
1607
- var toDotSecPerEnvironment = (options) => {
1608
- const { info } = getLogger();
1609
- const { dotSecEncrypted, searchPath, verbose } = options;
1610
- const environments = Object.keys(dotSecEncrypted.encrypted);
1611
- return Object.fromEntries(environments.map((environment) => {
1612
- let tree = dotSecEncrypted.encrypted[environment];
1613
- if (searchPath) {
1614
- if (verbose) {
1615
- info(`Searching for path: ${strong(searchPath)}`);
1616
- }
1617
- const pathParts = searchPath.split("/");
1618
- for (const pathPart of pathParts) {
1619
- tree = tree[pathPart];
1620
- }
1621
- }
1622
- return [
1623
- environment,
1624
- fromEncryptedLeafsToEnvEntries(flattenTree(tree)).join("\n")
1625
- ];
1626
- }));
1627
- };
1628
-
1629
- // src/commands/encrypted-secrets-to-dot-sec.ts
1630
- var command4 = "encrypted-secrets-to-dot-sec";
1631
- var desc4 = `Creates .sec file from an encrypted secrets file.
1632
- If '--use-top-levels-as-environments' is set, it will create a .sec file for each top level key in the encrypted secrets file.`;
1633
- var builder4 = {
1634
- "encrypted-secrets-file": {
1635
- string: true,
1636
- describe: "filename of json file for writing encrypted secrets",
1637
- default: "secrets.encrypted.json"
1638
- },
1639
- "sec-file": commonCliOptions.secFile,
1640
- "search-path": commonCliOptions.searchpath,
1641
- "aws-profile": commonCliOptions.awsProfile,
1642
- "aws-region": commonCliOptions.awsRegion,
1643
- "aws-key-alias": commonCliOptions.awsKeyAlias,
1644
- "aws-assume-role-arn": commonCliOptions.awsAssumeRoleArn,
1645
- "aws-assume-role-session-duration": commonCliOptions.awsAssumeRoleSessionDuration,
1646
- "use-top-levels-as-environments": commonCliOptions.useTopLevelsAsEnvironments,
1647
- verbose: commonCliOptions.verbose,
1648
- yes: __spreadValues({}, commonCliOptions.yes)
1649
- };
1650
- var handler4 = async (argv) => {
1651
- var _a;
1652
- const config = await getConfig();
1653
- const { info, error } = getLogger();
1654
- try {
1655
- const defaultRegion = config.aws.region || argv.awsRegion;
1656
- const { credentialsAndOrigin, regionAndOrigin } = await handleCredentialsAndRegion({
1657
- argv: __spreadProps(__spreadValues({}, argv), {
1658
- awsRegion: defaultRegion,
1659
- awsProfile: config.aws.profile || argv.awsProfile,
1660
- awsAssumeRoleArn: config.aws.assumeRoleArn || argv.awsAssumeRoleArn,
1661
- awsAssumeRoleSessionDuration: config.aws.assumeRoleSessionDuration || argv.awsAssumeRoleSessionDuration
1662
- }),
1663
- env: __spreadValues({}, process.env)
1664
- });
1665
- const { fileType, dotSecEncrypted } = await getDotSecEncrypted({
1666
- defaultConfig: {
1667
- config: {
1668
- aws: {
1669
- keyAlias: "alias/dotsec",
1670
- regions: [regionAndOrigin.value]
1671
- }
1672
- }
1673
- },
1674
- options: {
1675
- verbose: argv.verbose
1676
- }
1677
- });
1678
- if (!dotSecEncrypted.encrypted) {
1679
- throw new Error(`Expected 'encrypted' property, but got none`);
1680
- }
1681
- const dotSecPlainText = await decryptedEncrypted({
1682
- dotSecEncrypted,
1683
- credentials: credentialsAndOrigin.value,
1684
- region: regionAndOrigin.value,
1685
- keyAlias: argv.awsKeyAlias,
1686
- verbose: argv.verbose
1687
- });
1688
- if (argv.useTopLevelsAsEnvironments || ((_a = dotSecEncrypted.config) == null ? void 0 : _a.useTopLevelsAsEnvironments)) {
1689
- const dotSecsPerEnvironment = toDotSecPerEnvironment({
1690
- dotSecEncrypted,
1691
- searchPath: argv.searchPath,
1692
- verbose: argv.verbose
1693
- });
1694
- for (const [environment, dotSec] of Object.entries(dotSecsPerEnvironment)) {
1695
- const fileName = `.sec.${environment}`;
1696
- const dotSecPath = import_node_path10.default.resolve(process.cwd(), fileName);
1697
- info(`target: ${strong(dotSecPath)}
1698
- `);
1699
- info(prettyCode(dotSec));
1700
- info(`
1701
- `);
1702
- const overwriteResponse = await promptOverwriteIfFileExists({
1703
- filePath: dotSecPath,
1704
- skip: argv.yes
1705
- });
1706
- if (overwriteResponse === void 0 || overwriteResponse.overwrite === true) {
1707
- import_fs6.default.writeFileSync(dotSecPath, dotSec);
1708
- }
1709
- }
1710
- } else {
1711
- const dotSec = toDotSec({
1712
- dotSecEncrypted,
1713
- searchPath: argv.searchPath,
1714
- verbose: argv.verbose
1715
- });
1716
- const fileName = argv.secFile || `.sec`;
1717
- const dotSecPath = import_node_path10.default.resolve(process.cwd(), fileName);
1718
- info(`target: ${strong(dotSecPath)}
1719
- `);
1720
- info(prettyCode(dotSec));
1721
- info(`
1722
- `);
1723
- const overwriteResponse = await promptOverwriteIfFileExists({
1724
- filePath: dotSecPath,
1725
- skip: argv.yes
1726
- });
1727
- if (overwriteResponse === void 0 || overwriteResponse.overwrite === true) {
1728
- import_fs6.default.writeFileSync(dotSecPath, dotSec);
1729
- }
1730
- }
1731
- } catch (e) {
1732
- error(e);
1733
- }
1734
- };
1735
-
1736
- // src/commands/encrypted-secrets-to-plaintext-secrets.ts
1737
- var encrypted_secrets_to_plaintext_secrets_exports = {};
1738
- __export(encrypted_secrets_to_plaintext_secrets_exports, {
1739
- builder: () => builder5,
1740
- command: () => command5,
1741
- desc: () => desc5,
1742
- handler: () => handler5
1743
- });
1744
- var import_node_fs4 = __toModule(require("node:fs"));
1745
- var import_node_path11 = __toModule(require("node:path"));
1746
- var import_yaml3 = __toModule(require("yaml"));
1747
- var command5 = "encrypted-secrets-to-plaintext-secrets";
1748
- var desc5 = "Decrypts an encrypted file and stores the result in a plaintext file";
1749
- var builder5 = {
1750
- "secrets-file": {
1751
- string: true,
1752
- describe: "filename of json file reading secrets",
1753
- default: "secrets.json"
1754
- },
1755
- "encrypted-secrets-file": {
1756
- string: true,
1757
- describe: "filename of json file for writing encrypted secrets",
1758
- default: "secrets.encrypted.json"
1759
- },
1760
- "aws-profile": commonCliOptions.awsProfile,
1761
- "aws-region": commonCliOptions.awsRegion,
1762
- "aws-key-alias": commonCliOptions.awsKeyAlias,
1763
- "aws-assume-role-arn": commonCliOptions.awsAssumeRoleArn,
1764
- "aws-assume-role-session-duration": commonCliOptions.awsAssumeRoleSessionDuration,
1765
- verbose: commonCliOptions.verbose,
1766
- yes: __spreadValues({}, commonCliOptions.yes)
1767
- };
1768
- var handler5 = async (argv) => {
1769
- const config = await getConfig();
1770
- const { info, error } = getLogger();
1771
- try {
1772
- const defaultRegion = config.aws.region || argv.awsRegion;
1773
- const { credentialsAndOrigin, regionAndOrigin } = await handleCredentialsAndRegion({
1774
- argv: __spreadProps(__spreadValues({}, argv), {
1775
- awsRegion: defaultRegion,
1776
- awsProfile: config.aws.profile || argv.awsProfile,
1777
- awsAssumeRoleArn: config.aws.assumeRoleArn || argv.awsAssumeRoleArn,
1778
- awsAssumeRoleSessionDuration: config.aws.assumeRoleSessionDuration || argv.awsAssumeRoleSessionDuration
1779
- }),
1780
- env: __spreadValues({}, process.env)
1781
- });
1782
- const { fileType, dotSecEncrypted } = await getDotSecEncrypted({
1783
- defaultConfig: {
1784
- config: {
1785
- aws: {
1786
- keyAlias: "alias/dotsec",
1787
- regions: [regionAndOrigin.value]
1788
- }
1789
- }
1790
- },
1791
- options: {}
1792
- });
1793
- if (!dotSecEncrypted.encrypted) {
1794
- throw new Error(`Expected 'encrypted' property, but got none`);
1795
- }
1796
- const dotSecPlainText = await decryptedEncrypted({
1797
- dotSecEncrypted,
1798
- credentials: credentialsAndOrigin.value,
1799
- region: regionAndOrigin.value,
1800
- keyAlias: argv.awsKeyAlias,
1801
- verbose: argv.verbose
1802
- });
1803
- if (argv.secretsFile) {
1804
- const secretsFileExtension = import_node_path11.default.extname(argv.secretsFile).substring(1);
1805
- }
1806
- const secretsPath = import_node_path11.default.resolve(process.cwd(), import_node_path11.default.parse(argv.secretsFile || `secrets.json`).name + "." + fileType);
1807
- console.log("secretsPath", fileType, import_node_path11.default.parse(argv.secretsFile || `secrets.json`).name);
1808
- const converted = fileType === "yaml" || fileType === "yml" ? import_yaml3.default.stringify(dotSecPlainText) : JSON.stringify(dotSecPlainText, null, 2);
1809
- info(`target: ${strong(secretsPath)}
1810
- `);
1811
- info(prettyCode(converted));
1812
- info(`
1813
- `);
1814
- const overwriteResponse = await promptOverwriteIfFileExists({
1815
- filePath: secretsPath,
1816
- skip: argv.yes
1817
- });
1818
- if (overwriteResponse === void 0 || overwriteResponse.overwrite === true) {
1819
- import_node_fs4.default.writeFileSync(secretsPath, converted);
1820
- }
1821
- } catch (e) {
1822
- error(e);
1823
- }
1824
- };
1825
-
1826
- // src/commands/offload-plaintext-secrets.ts
1827
- var offload_plaintext_secrets_exports = {};
1828
- __export(offload_plaintext_secrets_exports, {
1829
- builder: () => builder6,
1830
- command: () => command6,
1831
- desc: () => desc6,
1832
- handler: () => handler6
1833
- });
1834
- var import_prompts2 = __toModule(require("prompts"));
1835
- var command6 = "offload-plaintext-secrets";
1836
- var desc6 = "Decrypts and pushes secret values to AWS SSM and SecretsManager";
1837
- var builder6 = {
1838
- "encrypted-secrets-file": {
1839
- string: true,
1840
- describe: "filename of json file for writing encrypted secrets",
1841
- default: "secrets.encrypted.json"
1842
- },
1843
- "aws-profile": commonCliOptions.awsProfile,
1844
- "aws-region": commonCliOptions.awsRegion,
1845
- "aws-key-alias": commonCliOptions.awsKeyAlias,
1846
- "aws-assume-role-arn": commonCliOptions.awsAssumeRoleArn,
1847
- "aws-assume-role-session-duration": commonCliOptions.awsAssumeRoleSessionDuration,
1848
- verbose: commonCliOptions.verbose,
1849
- yes: __spreadValues({}, commonCliOptions.yes)
1850
- };
1851
- var handler6 = async (argv) => {
1852
- const config = await getConfig();
1853
- const { info, error } = getLogger();
1854
- try {
1855
- const defaultRegion = config.aws.region || argv.awsRegion;
1856
- const { credentialsAndOrigin, regionAndOrigin } = await handleCredentialsAndRegion({
1857
- argv: __spreadProps(__spreadValues({}, argv), {
1858
- awsRegion: defaultRegion,
1859
- awsProfile: config.aws.profile || argv.awsProfile,
1860
- awsAssumeRoleArn: config.aws.assumeRoleArn || argv.awsAssumeRoleArn,
1861
- awsAssumeRoleSessionDuration: config.aws.assumeRoleSessionDuration || argv.awsAssumeRoleSessionDuration
1862
- }),
1863
- env: __spreadValues({}, process.env)
1864
- });
1865
- const { fileType, dotSecEncrypted } = await getDotSecEncrypted({
1866
- defaultConfig: {
1867
- config: {
1868
- aws: {
1869
- keyAlias: "alias/dotsec",
1870
- regions: [regionAndOrigin.value]
1871
- }
1872
- }
1873
- },
1874
- options: {}
1875
- });
1876
- if (!dotSecEncrypted.encrypted) {
1877
- throw new Error(`Expected 'encrypted' property, but got none`);
1878
- }
1879
- const dotSecPlainText = await decryptedEncrypted({
1880
- dotSecEncrypted,
1881
- credentials: credentialsAndOrigin.value,
1882
- region: regionAndOrigin.value,
1883
- keyAlias: argv.awsKeyAlias,
1884
- verbose: argv.verbose
1885
- });
1886
- const tasks = await createStorePlaintextTasks({
1887
- dotSecPlainText,
1888
- credentials: credentialsAndOrigin.value,
1889
- region: regionAndOrigin.value,
1890
- keyAlias: argv.awsKeyAlias,
1891
- verbose: argv.verbose
1892
- });
1893
- if (tasks.total > 0) {
1894
- prettyPrintTasks(tasks);
1895
- let proceed = argv.yes === true;
1896
- if (proceed === false) {
1897
- proceed = await (0, import_prompts2.default)({
1898
- type: "confirm",
1899
- name: "proceed",
1900
- message: () => {
1901
- return `Proceed ?`;
1902
- }
1903
- }).then((r) => r.proceed);
1904
- }
1905
- if (proceed) {
1906
- await executeStorePlainTextTasks({
1907
- credentials: credentialsAndOrigin.value,
1908
- region: regionAndOrigin.value,
1909
- verbose: argv.verbose,
1910
- tasks
1911
- });
1912
- }
1913
- } else {
1914
- info("Nothing to do");
1915
- }
1916
- } catch (e) {
1917
- error(e);
1918
- }
1919
- };
1920
-
1921
- // src/commands/plaintext-secrets-to-dot-env.ts
1922
- var plaintext_secrets_to_dot_env_exports = {};
1923
- __export(plaintext_secrets_to_dot_env_exports, {
1924
- builder: () => builder7,
1925
- command: () => command7,
1926
- desc: () => desc7,
1927
- handler: () => handler7
1928
- });
1929
- var import_fs7 = __toModule(require("fs"));
1930
- var import_node_path12 = __toModule(require("node:path"));
1931
- var command7 = "plaintext-secrets-to-dot-env";
1932
- var desc7 = `Creates .env file from a secrets file.
1933
- If '--use-top-levels-as-environments' is set, it will create a .env file for each top level key in the secrets file.`;
1934
- var builder7 = {
1935
- "secrets-file": {
1936
- string: true,
1937
- describe: "filename of json file reading secrets",
1938
- default: "secrets.json"
1939
- },
1940
- "env-file": commonCliOptions.envFile,
1941
- "search-path": commonCliOptions.searchpath,
1942
- "aws-profile": commonCliOptions.awsProfile,
1943
- "aws-region": commonCliOptions.awsRegion,
1944
- "aws-key-alias": commonCliOptions.awsKeyAlias,
1945
- "aws-assume-role-arn": commonCliOptions.awsAssumeRoleArn,
1946
- "aws-assume-role-session-duration": commonCliOptions.awsAssumeRoleSessionDuration,
1947
- "use-top-levels-as-environments": commonCliOptions.useTopLevelsAsEnvironments,
1948
- verbose: commonCliOptions.verbose,
1949
- yes: __spreadValues({}, commonCliOptions.yes),
1950
- "dry-run": commonCliOptions.dryRun
1951
- };
1952
- var handler7 = async (argv) => {
1953
- var _a;
1954
- const config = await getConfig();
1955
- const { info, error } = getLogger();
1956
- try {
1957
- const defaultRegion = config.aws.region || argv.awsRegion;
1958
- const { regionAndOrigin } = await handleCredentialsAndRegion({
1959
- argv: __spreadProps(__spreadValues({}, argv), {
1960
- awsRegion: defaultRegion,
1961
- awsProfile: config.aws.profile || argv.awsProfile,
1962
- awsAssumeRoleArn: config.aws.assumeRoleArn || argv.awsAssumeRoleArn,
1963
- awsAssumeRoleSessionDuration: config.aws.assumeRoleSessionDuration || argv.awsAssumeRoleSessionDuration
1964
- }),
1965
- env: __spreadValues({}, process.env)
1966
- });
1967
- const { dotSecPlainText } = await getDotSecPlainText({
1968
- defaultConfig: {
1969
- config: {
1970
- aws: {
1971
- keyAlias: "alias/dotsec",
1972
- regions: [regionAndOrigin.value]
1973
- }
1974
- }
1975
- },
1976
- options: {
1977
- filename: argv.secretsFile,
1978
- verbose: argv.verbose
1979
- }
1980
- });
1981
- if (!dotSecPlainText.plaintext) {
1982
- throw new Error(`Expected 'encrypted' property, but got none`);
1983
- }
1984
- if (argv.useTopLevelsAsEnvironments || ((_a = dotSecPlainText.config) == null ? void 0 : _a.useTopLevelsAsEnvironments)) {
1985
- const dotEnvsPerEnvironment = toDotEnvPerEnvironment({
1986
- dotSecPlainText,
1987
- verbose: argv.verbose
1988
- });
1989
- for (const [environment, dotEnv] of Object.entries(dotEnvsPerEnvironment)) {
1990
- const fileName = `.env.${environment}`;
1991
- const dotEnvPath = import_node_path12.default.resolve(process.cwd(), fileName);
1992
- if (argv.dryRun) {
1993
- info(strong(`// ${dotEnvPath}`));
1994
- info(emphasis(dotEnv));
1995
- } else {
1996
- const overwriteResponse = await promptOverwriteIfFileExists({
1997
- filePath: dotEnvPath,
1998
- skip: argv.yes
1999
- });
2000
- if (overwriteResponse === void 0 || overwriteResponse.overwrite === true) {
2001
- import_fs7.default.writeFileSync(dotEnvPath, dotEnv);
2002
- }
2003
- }
2004
- }
2005
- } else {
2006
- const dotEnv = toDotEnv({
2007
- dotSecPlainText,
2008
- verbose: argv.verbose,
2009
- searchPath: argv.searchPath
2010
- });
2011
- const fileName = argv.envFile || `.env`;
2012
- const dotEnvPath = import_node_path12.default.resolve(process.cwd(), fileName);
2013
- info(`target: ${strong(dotEnvPath)}
2014
- `);
2015
- info(prettyCode(dotEnv));
2016
- info(`
2017
- `);
2018
- const overwriteResponse = await promptOverwriteIfFileExists({
2019
- filePath: dotEnvPath,
2020
- skip: argv.yes
2021
- });
2022
- if (overwriteResponse === void 0 || overwriteResponse.overwrite === true) {
2023
- import_fs7.default.writeFileSync(dotEnvPath, dotEnv);
2024
- }
2025
- }
2026
- } catch (e) {
2027
- error(e);
2028
- }
2029
- };
2030
-
2031
- // src/commands/plaintext-secrets-to-dot-sec.ts
2032
- var plaintext_secrets_to_dot_sec_exports = {};
2033
- __export(plaintext_secrets_to_dot_sec_exports, {
2034
- builder: () => builder8,
2035
- command: () => command8,
2036
- desc: () => desc8,
2037
- handler: () => handler8
2038
- });
2039
- var import_fs8 = __toModule(require("fs"));
2040
- var import_node_path13 = __toModule(require("node:path"));
2041
- var command8 = "plaintext-secrets-to-dot-sec";
2042
- var desc8 = `Creates .sec file from an secrets file.
2043
- If '--use-top-levels-as-environments' is set, it will create a .sec file for each top level key in the ecrets file.`;
2044
- var builder8 = {
2045
- "secrets-file": {
2046
- string: true,
2047
- describe: "filename of json file reading secrets"
2048
- },
2049
- "sec-file": commonCliOptions.secFile,
2050
- "aws-profile": commonCliOptions.awsProfile,
2051
- "aws-region": commonCliOptions.awsRegion,
2052
- "aws-key-alias": commonCliOptions.awsKeyAlias,
2053
- "aws-assume-role-arn": commonCliOptions.awsAssumeRoleArn,
2054
- "aws-assume-role-session-duration": commonCliOptions.awsAssumeRoleSessionDuration,
2055
- "use-top-levels-as-environments": commonCliOptions.useTopLevelsAsEnvironments,
2056
- verbose: commonCliOptions.verbose,
2057
- yes: __spreadValues({}, commonCliOptions.yes)
2058
- };
2059
- var handler8 = async (argv) => {
2060
- var _a;
2061
- const config = await getConfig();
2062
- const { info, error } = getLogger();
2063
- try {
2064
- const defaultRegion = config.aws.region || argv.awsRegion;
2065
- const { credentialsAndOrigin, regionAndOrigin } = await handleCredentialsAndRegion({
2066
- argv: __spreadProps(__spreadValues({}, argv), {
2067
- awsRegion: defaultRegion,
2068
- awsProfile: config.aws.profile || argv.awsProfile,
2069
- awsAssumeRoleArn: config.aws.assumeRoleArn || argv.awsAssumeRoleArn,
2070
- awsAssumeRoleSessionDuration: config.aws.assumeRoleSessionDuration || argv.awsAssumeRoleSessionDuration
2071
- }),
2072
- env: __spreadValues({}, process.env)
2073
- });
2074
- const { fileType, dotSecPlainText } = await getDotSecPlainText({
2075
- defaultConfig: {
2076
- config: {
2077
- aws: {
2078
- keyAlias: "alias/dotsec",
2079
- regions: [regionAndOrigin.value]
2080
- }
2081
- }
2082
- },
2083
- options: {
2084
- filename: argv.secretsFile,
2085
- verbose: argv.verbose
2086
- }
2087
- });
2088
- console.log("dotSecPlainText", dotSecPlainText);
2089
- const dotSecEncrypted = await encryptPlainText({
2090
- dotSecPlainText,
2091
- credentials: credentialsAndOrigin.value,
2092
- region: regionAndOrigin.value,
2093
- keyAlias: argv.awsKeyAlias,
2094
- verbose: argv.verbose
2095
- });
2096
- if (!dotSecPlainText.plaintext) {
2097
- throw new Error(`Expected 'encrypted' property, but got none`);
2098
- }
2099
- if (!dotSecEncrypted.encrypted) {
2100
- throw new Error(`Expected 'encrypted' property, but got none`);
2101
- }
2102
- if (argv.useTopLevelsAsEnvironments || ((_a = dotSecPlainText.config) == null ? void 0 : _a.useTopLevelsAsEnvironments)) {
2103
- const dotSecsPerEnvironment = toDotSecPerEnvironment({
2104
- dotSecEncrypted,
2105
- verbose: argv.verbose
2106
- });
2107
- for (const [environment, dotSec] of Object.entries(dotSecsPerEnvironment)) {
2108
- const fileName = `.sec.${environment}`;
2109
- const dotSecPath = import_node_path13.default.resolve(process.cwd(), fileName);
2110
- info(`target: ${strong(dotSecPath)}
2111
- `);
2112
- info(prettyCode(dotSec));
2113
- info(`
2114
- `);
2115
- const overwriteResponse = await promptOverwriteIfFileExists({
2116
- filePath: dotSecPath,
2117
- skip: argv.yes
2118
- });
2119
- if (overwriteResponse === void 0 || overwriteResponse.overwrite === true) {
2120
- import_fs8.default.writeFileSync(dotSecPath, dotSec);
2121
- }
2122
- }
2123
- } else {
2124
- const dotSec = toDotSec({
2125
- dotSecEncrypted,
2126
- verbose: argv.verbose
2127
- });
2128
- const fileName = argv.secFile || `.sec`;
2129
- const dotSecPath = import_node_path13.default.resolve(process.cwd(), fileName);
2130
- info(`target: ${strong(dotSecPath)}
2131
- `);
2132
- info(prettyCode(dotSec));
2133
- info(`
2134
- `);
2135
- const overwriteResponse = await promptOverwriteIfFileExists({
2136
- filePath: dotSecPath,
2137
- skip: argv.yes
2138
- });
2139
- if (overwriteResponse === void 0 || overwriteResponse.overwrite === true) {
2140
- import_fs8.default.writeFileSync(dotSecPath, dotSec);
2141
- }
2142
- }
2143
- } catch (e) {
2144
- error(e);
2145
- }
2146
- };
2147
-
2148
- // src/commands/plaintext-secrets-to-encrypted-secrets.ts
2149
- var plaintext_secrets_to_encrypted_secrets_exports = {};
2150
- __export(plaintext_secrets_to_encrypted_secrets_exports, {
2151
- builder: () => builder9,
2152
- command: () => command9,
2153
- desc: () => desc9,
2154
- handler: () => handler9
2155
- });
2156
- var import_node_fs5 = __toModule(require("node:fs"));
2157
- var import_node_path14 = __toModule(require("node:path"));
2158
- var import_yaml4 = __toModule(require("yaml"));
2159
- var command9 = "plaintext-secrets-to-encrypted-secrets";
2160
- var desc9 = "Encrypts an unencrypted secretsfile";
2161
- var builder9 = {
2162
- "secrets-file": {
2163
- string: true,
2164
- describe: "filename of json file reading secrets"
2165
- },
2166
- "encrypted-secrets-file": {
2167
- string: true,
2168
- describe: "filename of json file for writing encrypted secrets",
2169
- default: "secrets.encrypted.json"
2170
- },
2171
- "aws-profile": commonCliOptions.awsProfile,
2172
- "aws-region": commonCliOptions.awsRegion,
2173
- "aws-key-alias": commonCliOptions.awsKeyAlias,
2174
- "aws-assume-role-arn": commonCliOptions.awsAssumeRoleArn,
2175
- "aws-assume-role-session-duration": commonCliOptions.awsAssumeRoleSessionDuration,
2176
- verbose: commonCliOptions.verbose,
2177
- yes: __spreadValues({}, commonCliOptions.yes)
2178
- };
2179
- var handler9 = async (argv) => {
2180
- const config = await getConfig();
2181
- const { info, error } = getLogger();
2182
- try {
2183
- const defaultRegion = config.aws.region || argv.awsRegion;
2184
- const { credentialsAndOrigin, regionAndOrigin } = await handleCredentialsAndRegion({
2185
- argv: __spreadProps(__spreadValues({}, argv), {
2186
- awsRegion: defaultRegion,
2187
- awsProfile: config.aws.profile || argv.awsProfile,
2188
- awsAssumeRoleArn: config.aws.assumeRoleArn || argv.awsAssumeRoleArn,
2189
- awsAssumeRoleSessionDuration: config.aws.assumeRoleSessionDuration || argv.awsAssumeRoleSessionDuration
2190
- }),
2191
- env: __spreadValues({}, process.env)
2192
- });
2193
- const { fileType, dotSecPlainText } = await getDotSecPlainText({
2194
- defaultConfig: {
2195
- config: {
2196
- aws: {
2197
- keyAlias: "alias/dotsec",
2198
- regions: [regionAndOrigin.value]
2199
- }
2200
- }
2201
- },
2202
- options: {
2203
- filename: argv.secretsFile
2204
- }
2205
- });
2206
- if (!dotSecPlainText.plaintext) {
2207
- throw new Error(`Expected 'plaintext' property, but got none`);
2208
- }
2209
- const dotSecEncrypted = await encryptPlainText({
2210
- dotSecPlainText,
2211
- credentials: credentialsAndOrigin.value,
2212
- region: regionAndOrigin.value,
2213
- keyAlias: argv.awsKeyAlias,
2214
- verbose: argv.verbose
2215
- });
2216
- const encryptedSecretsPath = import_node_path14.default.resolve(process.cwd(), import_node_path14.default.parse(argv.encryptedSecretsFile || `secrets.encrypted.json`).name + "." + fileType);
2217
- const converted = fileType === "yaml" || fileType === "yml" ? import_yaml4.default.stringify(dotSecEncrypted) : JSON.stringify(dotSecEncrypted, null, 2);
2218
- info(`target: ${strong(encryptedSecretsPath)}
2219
- `);
2220
- info(prettyCode(converted));
2221
- info(`
2222
- `);
2223
- const overwriteResponse = await promptOverwriteIfFileExists({
2224
- filePath: encryptedSecretsPath,
2225
- skip: argv.yes
2226
- });
2227
- if (overwriteResponse === void 0 || overwriteResponse.overwrite === true) {
2228
- import_node_fs5.default.writeFileSync(encryptedSecretsPath, converted);
2229
- }
2230
- } catch (e) {
2231
- error(e);
2232
- }
2233
- };
2234
-
2235
- // src/cli.ts
2236
- void (0, import_yargs.default)((0, import_helpers.hideBin)(process.argv)).command(convert_default).command(defaultCommand_exports).command(plaintext_secrets_to_encrypted_secrets_exports).command(encrypted_secrets_to_plaintext_secrets_exports).command(encrypted_secrets_to_dot_env_exports).command(encrypted_secrets_to_dot_sec_exports).command(plaintext_secrets_to_dot_env_exports).command(plaintext_secrets_to_dot_sec_exports).command(dot_sec_to_dot_env_exports).command(offload_plaintext_secrets_exports).parse();
2237
- //# sourceMappingURL=cli.js.map