dotsec 4.0.0-beta.f6d5ebb.0 → 5.0.0-beta.2d72d7d

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/index.js DELETED
@@ -1,1504 +0,0 @@
1
- 'use strict';
2
-
3
- var commander = require('commander');
4
- var fs3 = require('fs');
5
- var path = require('path');
6
- var bundleRequire = require('bundle-require');
7
- var JoyCon = require('joycon');
8
- var fs2 = require('fs/promises');
9
- var prompts = require('prompts');
10
- var chalk2 = require('chalk');
11
- require('cli-table');
12
- var dotenvExpand = require('dotenv-expand');
13
- var camelCase = require('camel-case');
14
- var child_process = require('child_process');
15
- var Ajv = require('ajv');
16
- var yargsParser = require('yargs-parser');
17
-
18
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
19
-
20
- var fs3__default = /*#__PURE__*/_interopDefault(fs3);
21
- var path__default = /*#__PURE__*/_interopDefault(path);
22
- var JoyCon__default = /*#__PURE__*/_interopDefault(JoyCon);
23
- var fs2__default = /*#__PURE__*/_interopDefault(fs2);
24
- var prompts__default = /*#__PURE__*/_interopDefault(prompts);
25
- var chalk2__default = /*#__PURE__*/_interopDefault(chalk2);
26
- var Ajv__default = /*#__PURE__*/_interopDefault(Ajv);
27
- var yargsParser__default = /*#__PURE__*/_interopDefault(yargsParser);
28
-
29
- // src/cli/index.ts
30
-
31
- // src/constants.ts
32
- var DOTSEC_DEFAULT_CONFIG_FILE = "dotsec.config.ts";
33
- var DOTSEC_CONFIG_FILES = [DOTSEC_DEFAULT_CONFIG_FILE];
34
- var DOTSEC_DEFAULT_DOTSEC_FILENAME = ".sec";
35
- var DOTSEC_DEFAULT_DOTENV_FILENAME = ".env";
36
- var defaultConfig = {
37
- defaults: {
38
- // encryptionEngine: "pke",
39
- // plugins: {
40
- // pke: {},
41
- // },
42
- options: {
43
- showRedacted: false
44
- }
45
- }
46
- };
47
- function jsoncParse(data) {
48
- try {
49
- return new Function(`return ${data.trim()}`)();
50
- } catch {
51
- return {};
52
- }
53
- }
54
- var loadJson = async (filepath) => {
55
- try {
56
- return jsoncParse(await fs3__default.default.promises.readFile(filepath, "utf8"));
57
- } catch (error) {
58
- if (error instanceof Error) {
59
- throw new Error(
60
- `Failed to parse ${path__default.default.relative(process.cwd(), filepath)}: ${error.message}`
61
- );
62
- } else {
63
- throw error;
64
- }
65
- }
66
- };
67
- var getMagicalConfig = async (filename) => {
68
- const cwd = process.cwd();
69
- const configJoycon = new JoyCon__default.default();
70
- const configPath = await configJoycon.resolve({
71
- files: filename ? [filename] : [...DOTSEC_CONFIG_FILES, "package.json"],
72
- cwd,
73
- stopDir: path__default.default.parse(cwd).root,
74
- packageKey: "dotsec"
75
- });
76
- if (filename && configPath === null) {
77
- throw new Error(`Could not find config file ${filename}`);
78
- }
79
- if (configPath) {
80
- if (configPath.endsWith(".json")) {
81
- const rawData = await loadJson(configPath);
82
- let data;
83
- if (configPath.endsWith("package.json") && rawData.dotsec !== void 0) {
84
- data = rawData.dotsec;
85
- } else {
86
- data = rawData;
87
- }
88
- return {
89
- source: "json",
90
- contents: {
91
- ...defaultConfig,
92
- ...data,
93
- defaults: {
94
- ...data?.defaults,
95
- ...defaultConfig.defaults,
96
- options: {
97
- ...data?.defaults?.options,
98
- ...defaultConfig.defaults?.options
99
- },
100
- plugins: {
101
- ...data?.defaults?.plugins,
102
- ...defaultConfig.defaults?.plugins
103
- }
104
- },
105
- push: {
106
- ...data?.push
107
- }
108
- }
109
- };
110
- } else if (configPath.endsWith(".ts")) {
111
- const bundleRequireResult = await bundleRequire.bundleRequire({
112
- filepath: configPath
113
- });
114
- const data = bundleRequireResult.mod.dotsec || bundleRequireResult.mod.default || bundleRequireResult.mod;
115
- return {
116
- source: "ts",
117
- contents: {
118
- ...defaultConfig,
119
- ...data,
120
- defaults: {
121
- ...data?.defaults,
122
- ...defaultConfig.defaults,
123
- plugins: {
124
- ...data?.defaults?.plugins,
125
- ...defaultConfig.defaults?.plugins
126
- },
127
- options: {
128
- ...data?.defaults?.options,
129
- ...defaultConfig.defaults?.options
130
- }
131
- },
132
- push: {
133
- ...data?.push
134
- }
135
- }
136
- };
137
- }
138
- }
139
- return { source: "defaultConfig", contents: defaultConfig };
140
- };
141
-
142
- // src/lib/loadDotsecPlugin.ts
143
- var loadDotsecPlugin = async (options) => {
144
- return import(options.name).then((imported) => {
145
- return imported.default;
146
- });
147
- };
148
- var addPluginOptions = (options, command, mandatory) => {
149
- if (options) {
150
- Object.values(options).map((option) => {
151
- let optionProps;
152
- if (Array.isArray(option)) {
153
- const [flags, description, defaultValue] = option;
154
- optionProps = {
155
- flags,
156
- description,
157
- defaultValue
158
- };
159
- } else {
160
- const { flags, description, defaultValue, choices, env, fn } = option;
161
- optionProps = {
162
- flags,
163
- description,
164
- defaultValue,
165
- choices,
166
- env,
167
- fn
168
- };
169
- }
170
- if (optionProps) {
171
- const newOption = new commander.Option(
172
- optionProps.flags,
173
- optionProps.description
174
- );
175
- if (optionProps.fn) {
176
- newOption.argParser(optionProps.fn);
177
- }
178
- if (optionProps.defaultValue) {
179
- newOption.default(optionProps.defaultValue);
180
- }
181
- if (optionProps.env) {
182
- newOption.env(optionProps.env);
183
- }
184
- if (mandatory) {
185
- newOption.makeOptionMandatory(true);
186
- }
187
- if (optionProps.choices) {
188
- newOption.choices(optionProps.choices);
189
- }
190
- command.addOption(newOption);
191
- }
192
- });
193
- }
194
- };
195
- var readContentsFromFile = async (filePath) => {
196
- return await fs2__default.default.readFile(filePath, "utf-8");
197
- };
198
- var writeContentsToFile = async (filePath, contents) => {
199
- return await fs2__default.default.writeFile(filePath, contents, "utf-8");
200
- };
201
- var fileExists = async (source) => {
202
- try {
203
- await fs2.stat(source);
204
- return true;
205
- } catch {
206
- return false;
207
- }
208
- };
209
- var promptOverwriteIfFileExists = async ({
210
- filePath,
211
- skip
212
- }) => {
213
- let overwriteResponse;
214
- if (await fileExists(filePath) && skip !== true) {
215
- overwriteResponse = await prompts__default.default({
216
- type: "confirm",
217
- name: "overwrite",
218
- message: () => {
219
- return `Overwrite './${path__default.default.relative(process.cwd(), filePath)}' ?`;
220
- }
221
- });
222
- } else {
223
- overwriteResponse = void 0;
224
- }
225
- return overwriteResponse;
226
- };
227
-
228
- // src/lib/parse.ts
229
- var LINE = /^(#.*)|(\s?\r?\n)|(?:^|^)\s*(?:export\s+)?([\w.-]*)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?(\s*)(#.*)?(?:$|$)/gm;
230
- var parse = (src) => {
231
- const obj = {};
232
- const blocks = [];
233
- let lines = src.toString();
234
- lines = lines.replace(/\r\n?/gm, "\n");
235
- let match;
236
- while ((match = LINE.exec(lines)) != null) {
237
- const key = match[3];
238
- if (match?.[1]?.[0] === "#") {
239
- blocks.push({ type: "comment", raw: match[1] });
240
- } else if (match?.[2]) {
241
- blocks.push({ type: "whitespace", raw: match[2] });
242
- } else {
243
- let value = match[4] || "";
244
- value = value.trim();
245
- const maybeQuote = value[0];
246
- value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
247
- if (maybeQuote === '"') {
248
- value = value.replace(/\\n/g, "\n");
249
- value = value.replace(/\\r/g, "\r");
250
- }
251
- obj[key] = value;
252
- blocks.push({
253
- type: "value",
254
- key,
255
- value,
256
- raw: value + (match[5] ? match[5] : "") + (match[6] ? match[6] : "")
257
- });
258
- }
259
- }
260
- return { blocks, obj };
261
- };
262
- if (undefined) {
263
- const { it, expect } = undefined;
264
- it("parse", () => {
265
- const input1 = "KEY=value";
266
- const input2 = 'KEY="value"';
267
- const input3 = "KEY='value'";
268
- const input4 = "KEY=value # this is a comment";
269
- expect(parse(input1)).toMatchInlineSnapshot(`
270
- {
271
- "blocks": [
272
- {
273
- "key": "KEY",
274
- "raw": "value",
275
- "type": "value",
276
- "value": "value",
277
- },
278
- ],
279
- "obj": {
280
- "KEY": "value",
281
- },
282
- }
283
- `);
284
- expect(parse(input2)).toMatchInlineSnapshot(`
285
- {
286
- "blocks": [
287
- {
288
- "key": "KEY",
289
- "raw": "value",
290
- "type": "value",
291
- "value": "value",
292
- },
293
- ],
294
- "obj": {
295
- "KEY": "value",
296
- },
297
- }
298
- `);
299
- expect(parse(input3)).toMatchInlineSnapshot(`
300
- {
301
- "blocks": [
302
- {
303
- "key": "KEY",
304
- "raw": "value",
305
- "type": "value",
306
- "value": "value",
307
- },
308
- ],
309
- "obj": {
310
- "KEY": "value",
311
- },
312
- }
313
- `);
314
- expect(parse(input4)).toMatchInlineSnapshot(`
315
- {
316
- "blocks": [
317
- {
318
- "key": "KEY",
319
- "raw": "value# this is a comment",
320
- "type": "value",
321
- "value": "value",
322
- },
323
- ],
324
- "obj": {
325
- "KEY": "value",
326
- },
327
- }
328
- `);
329
- });
330
- }
331
- var strong = (str) => chalk2__default.default.yellow.bold(str);
332
-
333
- // src/types/colors.ts
334
- var backgroundColors = [
335
- "black",
336
- "red",
337
- "green",
338
- "yellow",
339
- "blue",
340
- "magenta",
341
- "cyan",
342
- "white",
343
- "black-bright",
344
- "gray",
345
- "grey",
346
- "red-bright",
347
- "green-bright",
348
- "yellow-bright",
349
- "blue-bright",
350
- "magenta-bright",
351
- "cyan-bright",
352
- "white-bright"
353
- ];
354
-
355
- // src/cli/options/sharedOptions.ts
356
- var envFileOption = {
357
- option: [
358
- "--env-file <envFile>",
359
- `Path to .env file. If not provided, will look for value in 'ENV_FILE' environment variable. If not provided, will look for '${DOTSEC_DEFAULT_DOTENV_FILENAME}' file in current directory.`,
360
- DOTSEC_DEFAULT_DOTENV_FILENAME
361
- ],
362
- env: "ENV_FILE"
363
- };
364
- var secFileOption = {
365
- option: [
366
- "--sec-file, <secFile>",
367
- `Path to .sec file. If not provided, will look for value in 'SEC_FILE' environment variable. If not provided, will look for '${DOTSEC_DEFAULT_DOTSEC_FILENAME}' file in current directory.`,
368
- DOTSEC_DEFAULT_DOTSEC_FILENAME
369
- ],
370
- env: "SEC_FILE"
371
- };
372
- var usingOption = {
373
- flags: "--using <using>",
374
- description: "Wether to use a dot env file or a dot sec file",
375
- choices: ["env", "sec"],
376
- env: "DOTSEC_USING"
377
- };
378
- var usingNoEncryptionEngineOption = {
379
- flags: "--using <using>",
380
- description: "Wether to use a dot env file or a dot sec file",
381
- choices: ["env"],
382
- env: "DOTSEC_USING"
383
- };
384
- var showOutputPrefixOption = {
385
- flags: "--show-output-prefix",
386
- description: "Show output prefix",
387
- env: "DOTSEC_SHOW_OUTPUT_PREFIX"
388
- };
389
- var outputPrefixOption = {
390
- flags: "--output-prefix <outputPrefix>",
391
- description: "Output prefix",
392
- env: "DOTSEC_OUTPUT_PREFIX"
393
- };
394
- var outputBackgroundColorOption = {
395
- flags: "--output-background-color <outputBackgroundColor>",
396
- description: "Background color of the output.",
397
- env: "DOTSEC_OUTPUT_BACKGROUND_COLOR",
398
- choices: [...backgroundColors, true]
399
- };
400
- var yesOption = {
401
- option: ["--yes", "Skip confirmation prompts"]
402
- };
403
- var configFileOption = {
404
- option: ["-c, --config-file, --configFile <configFile>", "Config file"],
405
- env: "DOTSEC_CONFIG_FILE"
406
- };
407
- var pluginOption = {
408
- option: ["--plugin <plugin>", "Comma-separated list of plugins to use"],
409
- env: "DOTSEC_PLUGIN"
410
- };
411
- var engineOption = {
412
- option: ["--engine <engine>", "Encryption engine to use"],
413
- env: "DOTSEC_ENGINE"
414
- };
415
- var createManifestOption = {
416
- option: [
417
- "--create-manifest",
418
- "Create a markdown manifest file. See the --manifest-file option for more information."
419
- ],
420
- env: "CREATE_MANIFEST"
421
- };
422
- var manifestFilePrefixOption = {
423
- option: [
424
- "--manifest-file-prefix <manifestFilePrefix>",
425
- "Mmanifest file prefix"
426
- ],
427
- env: "ENCRYPTION_MANIFEST_FILE"
428
- };
429
-
430
- // src/cli/options/decrypt.ts
431
- var decryptCommandDefaults = {
432
- decrypt: {
433
- options: {
434
- configFile: configFileOption,
435
- envFile: envFileOption,
436
- secFile: secFileOption,
437
- createManifest: createManifestOption,
438
- manifestFilePrefix: manifestFilePrefixOption,
439
- yes: yesOption
440
- },
441
- description: "Decrypt a sec file",
442
- helpText: `Examples:
443
-
444
-
445
- Decrypt .sec file to .env file
446
-
447
- $ npx dotsec decrypt
448
-
449
-
450
- Specify a different .sec file
451
-
452
- $ npx dotsec decrypt --sec-file .sec.dev
453
- $ SEC_FILE=.sec.dev npx dotsec decrypt
454
-
455
- Specify a different .env file
456
-
457
- $ npx dotsec decrypt --env-file .env.dev
458
- $ ENV_FILE=.env.dev npx dotsec decrypt
459
-
460
- Write a manifest markdown file
461
-
462
- $ npx dotsec decrypt --create-manifest
463
- $ CREATE_MANIFEST=true npx dotsec decrypt
464
-
465
- Specify a different manifest file
466
-
467
- $ npx dotsec decrypt --manifest-file .manifest.dev
468
- $ MANIFEST_FILE=decryption-manifest.md npx dotsec decrypt
469
- `
470
- }
471
- };
472
- var decrypt_default = decryptCommandDefaults;
473
-
474
- // src/cli/options/dotsec.ts
475
- var dotsecCommandDefaults = {
476
- dotsec: {
477
- options: {
478
- configFile: configFileOption,
479
- plugin: pluginOption
480
- }
481
- }
482
- };
483
- var dotsec_default = dotsecCommandDefaults;
484
-
485
- // src/cli/options/encrypt.ts
486
- var encryptCommandDefaults = {
487
- encrypt: {
488
- options: {
489
- configFile: configFileOption,
490
- envFile: envFileOption,
491
- secFile: secFileOption,
492
- createManifest: createManifestOption,
493
- manifestFile: manifestFilePrefixOption,
494
- yes: yesOption
495
- },
496
- description: "Encrypt an env file",
497
- helpText: `Examples:
498
-
499
-
500
- Encrypt .env file to .sec file
501
-
502
- $ npx dotsec encrypt
503
-
504
-
505
- Specify a different .env file
506
-
507
- $ npx dotsec encrypt --env-file .env.dev
508
- $ ENV_FILE=.env.dev npx dotsec encrypt
509
-
510
-
511
- Specify a different .sec file
512
-
513
- $ npx dotsec encrypt --sec-file .sec.dev
514
- $ SEC_FILE=.sec.dev npx dotsec encrypt
515
-
516
-
517
- Write a manifest markdown file
518
-
519
- $ npx dotsec encrypt --create-manifest
520
- $ CREATE_MANIFEST=true npx dotsec encrypt
521
-
522
-
523
- Specify a different manifest file
524
-
525
- $ npx dotsec encrypt --manifest-file manifest.dev
526
- $ MANIFEST_FILE=encryption-manifest.md npx dotsec encrypt
527
- `
528
- }
529
- };
530
- var encrypt_default = encryptCommandDefaults;
531
-
532
- // src/cli/options/init.ts
533
- var initCommandDefaults = {
534
- init: {
535
- options: {
536
- configFile: configFileOption,
537
- yes: yesOption
538
- },
539
- description: "Initialize a dotsec project by creating a dotsec.config.ts file.",
540
- helpText: `Examples:
541
-
542
- Create a dotsec.config.ts file in the current directory
543
-
544
- $ npx dotsec init
545
-
546
-
547
- Overwrite an existing dotsec.config.ts file in the current directory
548
-
549
- $ npx dotsec init --yes
550
-
551
-
552
- Create a dotsec config file in the current directory with a specific config file name
553
-
554
- By specifying the --config-file option, you can create a dotsec config file with a specific name.
555
-
556
- $ npx dotsec init --config-file dotsec.config.ts
557
-
558
- $ DOTSEC_CONFIG_FILE=my.config.ts npx dotsec init
559
- `
560
- }
561
- };
562
- var init_default = initCommandDefaults;
563
-
564
- // src/cli/options/push.ts
565
- var pushCommandDefaults = {
566
- push: {
567
- options: {
568
- configFile: configFileOption,
569
- envFile: envFileOption,
570
- secFile: secFileOption,
571
- yes: yesOption
572
- },
573
- requiredOptions: {
574
- using: usingOption
575
- },
576
- description: "Push variables from env or sec file to a remote",
577
- helpText: `Examples:
578
-
579
- Push variables from .env file to remote
580
-
581
- $ npx dotsec push --using env
582
- $ DOTSEC_USING=env npx dotsec push
583
-
584
-
585
- Push variables from .sec file to remote
586
-
587
- $ npx dotsec push --using sec
588
- $ DOTSEC_USING=sec npx dotsec push
589
- `
590
- }
591
- };
592
- var push_default = pushCommandDefaults;
593
-
594
- // src/cli/options/run.ts
595
- var runCommandDefaults = {
596
- runEnvOnly: {
597
- usage: "--using env [commandArgs...]",
598
- options: {
599
- configFile: configFileOption,
600
- envFile: envFileOption,
601
- yes: yesOption,
602
- engine: engineOption,
603
- outputBackgroundColor: outputBackgroundColorOption,
604
- showOutputPrefix: showOutputPrefixOption,
605
- outputPrefix: outputPrefixOption
606
- },
607
- requiredOptions: {
608
- using: usingNoEncryptionEngineOption
609
- },
610
- description: "Run a command in a separate process and populate env with contents of a dotenv file.",
611
- helpText: `Examples:
612
-
613
- Run a command with a .env file
614
-
615
- $ npx dotsec run --using env node -e "console.log(process.env)"
616
-
617
-
618
- Run a command with a specific .env file
619
-
620
- $ npx dotsec run --using env --env-file .env node -e "console.log(process.env)"
621
-
622
-
623
- Run a command with a specific ENV_FILE variable
624
-
625
- $ ENV_FILE=.env.dev npx dotsec run --using env node -e "console.log(process.env)"
626
-
627
-
628
- You can also specify 'using' as an environment variable
629
-
630
- $ DOTSEC_USING=env npx dotsec run node -e "console.log(process.env)"
631
- `
632
- },
633
- run: {
634
- options: {
635
- configFile: configFileOption,
636
- envFile: envFileOption,
637
- secFile: secFileOption,
638
- yes: yesOption,
639
- outputBackgroundColor: outputBackgroundColorOption,
640
- hideOutputPrefix: showOutputPrefixOption,
641
- outputPrefix: outputPrefixOption
642
- },
643
- requiredOptions: {
644
- using: usingOption
645
- },
646
- usage: "[--using env] [--using sec] [commandArgs...]",
647
- description: `Run a command in a separate process and populate env with either
648
- - contents of a dotenv file
649
- - decrypted values of a dotsec file.
650
-
651
- The --withEnv option will take precedence over the --withSec option. If neither are specified, the --withEnv option will be used by default.`,
652
- helpText: `${"Examples:"}
653
-
654
- ${"Run a command with a .env file"}
655
-
656
- $ dotsec run echo "hello world"
657
-
658
-
659
- ${"Run a command with a specific .env file"}
660
-
661
- $ dotsec run --with-env --env-file .env.dev echo "hello world"
662
-
663
-
664
- ${"Run a command with a .sec file"}
665
-
666
- $ dotsec run --with-sec echo "hello world"
667
-
668
-
669
- ${"Run a command with a specific .sec file"}
670
-
671
- $ dotsec run --with-sec --sec-file .sec.dev echo "hello world"
672
- `
673
- }
674
- // push: {
675
- // options: {
676
- // ...dotsecCommandDefaults.dotsec.options,
677
- // withEnv: withEnvOption,
678
- // withSec: withSecOption,
679
- // envFile: envFileOption,
680
- // secFile: secFileOption,
681
- // yes: yesOption,
682
- // },
683
- // requiredOptions: {
684
- // ...dotsecCommandDefaults.dotsec.requiredOptions,
685
- // },
686
- // },
687
- };
688
- var run_default = runCommandDefaults;
689
-
690
- // src/cli/options/index.ts
691
- var commandOptions = {
692
- ...dotsec_default,
693
- ...init_default,
694
- ...encrypt_default,
695
- ...decrypt_default,
696
- ...run_default,
697
- ...push_default
698
- };
699
- var expandCommandOption = (commandOption) => {
700
- if (Array.isArray(commandOption)) {
701
- const [flags, description, defaultValue] = commandOption;
702
- const optionProps = {
703
- flags,
704
- description,
705
- defaultValue
706
- };
707
- return optionProps;
708
- } else {
709
- if ("option" in commandOption) {
710
- const [flags, description, defaultValue] = commandOption.option;
711
- const optionProps = {
712
- flags,
713
- description,
714
- defaultValue,
715
- env: commandOption.env
716
- };
717
- return optionProps;
718
- }
719
- return commandOption;
720
- }
721
- };
722
- var createOption = (commandOption, options) => {
723
- const defaultOptionValueFromConfig = options?.dotsecConfig?.defaults?.options?.[options?.optionKey];
724
- const optionProps = expandCommandOption(commandOption);
725
- const newOption = new commander.Option(optionProps.flags, optionProps.description);
726
- if (optionProps.fn) {
727
- newOption.argParser(optionProps.fn);
728
- }
729
- if (optionProps.defaultValue) {
730
- newOption.default(defaultOptionValueFromConfig || optionProps.defaultValue);
731
- }
732
- if (optionProps.env) {
733
- newOption.env(optionProps.env);
734
- }
735
- if (options.required) {
736
- newOption.makeOptionMandatory(true);
737
- }
738
- if (optionProps.choices) {
739
- newOption.choices(optionProps.choices);
740
- }
741
- return newOption;
742
- };
743
- var setProgramOptions = (params) => {
744
- const { program: program2, commandName, dotsecConfig } = params;
745
- const programOptions = commandOptions[commandName || program2.name()];
746
- if (programOptions) {
747
- const { options, requiredOptions, description, usage, helpText } = programOptions;
748
- if (options) {
749
- Object.keys(options).forEach((optionKey) => {
750
- const commandOption = options[optionKey];
751
- const newOption = createOption(commandOption, {
752
- dotsecConfig,
753
- optionKey
754
- });
755
- program2.addOption(newOption);
756
- });
757
- }
758
- if (requiredOptions) {
759
- Object.keys(requiredOptions).forEach((requiredOptionKey) => {
760
- const requiredOption = requiredOptions[requiredOptionKey];
761
- const newOption = createOption(requiredOption, {
762
- required: true,
763
- dotsecConfig,
764
- optionKey: requiredOptionKey
765
- });
766
- program2.addOption(newOption);
767
- });
768
- }
769
- if (description) {
770
- program2.description(description);
771
- }
772
- if (usage) {
773
- program2.usage(usage);
774
- }
775
- if (helpText) {
776
- program2.description(helpText);
777
- }
778
- }
779
- };
780
-
781
- // src/cli/commands/decrypt.ts
782
- var addEncryptProgram = async (program2, options) => {
783
- const { dotsecConfig, decryptHandlers } = options;
784
- const subProgram = program2.enablePositionalOptions().passThroughOptions().command("decrypt").action(async (_options, command) => {
785
- try {
786
- const {
787
- // verbose,
788
- envFile,
789
- secFile,
790
- engine,
791
- createManifest,
792
- manifestFile,
793
- yes
794
- } = command.optsWithGlobals();
795
- const encryptionEngine = engine || dotsecConfig?.defaults?.encryptionEngine;
796
- const pluginCliDecrypt = (decryptHandlers || []).find((handler) => {
797
- return handler.triggerOptionValue === encryptionEngine;
798
- });
799
- if (!pluginCliDecrypt) {
800
- throw new Error(
801
- `No decryption plugin found, available decryption engine(s): ${options.decryptHandlers.map((e) => `--${e.triggerOptionValue}`).join(", ")}`
802
- );
803
- }
804
- console.log(
805
- "Decrypting with",
806
- strong(
807
- pluginCliDecrypt.encryptionEngineName || pluginCliDecrypt.triggerOptionValue
808
- ),
809
- "engine"
810
- );
811
- const allOptionKeys = [
812
- ...Object.keys(pluginCliDecrypt.options || {}),
813
- ...Object.keys(pluginCliDecrypt.requiredOptions || {})
814
- ];
815
- const allOptionsValues = Object.fromEntries(
816
- allOptionKeys.map((key) => {
817
- return [key, _options[key]];
818
- })
819
- );
820
- const dotsecString = await readContentsFromFile(secFile);
821
- const plaintext = await pluginCliDecrypt.handler({
822
- ciphertext: dotsecString,
823
- ...allOptionsValues
824
- });
825
- const dotenvOverwriteResponse = await promptOverwriteIfFileExists({
826
- filePath: envFile,
827
- skip: yes
828
- });
829
- if (dotenvOverwriteResponse === void 0 || dotenvOverwriteResponse.overwrite === true) {
830
- await writeContentsToFile(envFile, plaintext);
831
- console.log(
832
- `Wrote plaintext contents of ${strong(secFile)} file to ${strong(
833
- envFile
834
- )}`
835
- );
836
- }
837
- if (createManifest || dotsecConfig?.defaults?.options?.createManifest) {
838
- const dotenvVars = parse(plaintext).obj;
839
- const markdownManifest = `# Dotsec decryption manifest
840
-
841
- ## Overview
842
-
843
- - plaintext source: ${envFile}
844
- - ciphertext target: ${secFile}
845
- - created: ${( new Date()).toUTCString()}
846
- - Decryption engine: ${pluginCliDecrypt.encryptionEngineName || pluginCliDecrypt.triggerOptionValue}
847
- - Decryption engine options: ${JSON.stringify(allOptionsValues)}
848
-
849
- ## Variables
850
-
851
- | Key |
852
- | --- |
853
- ${Object.keys(dotenvVars).map((key) => {
854
- return `| \`${key} \`| `;
855
- }).join("\n")}
856
- `;
857
- const manifestTargetFile = manifestFile || `${envFile}.decryption-manifest.md`;
858
- await writeContentsToFile(manifestTargetFile, markdownManifest);
859
- console.log(
860
- `Wrote manifest of ${strong(envFile)} file to ${strong(
861
- manifestTargetFile
862
- )}`
863
- );
864
- }
865
- } catch (e) {
866
- console.error(strong(e.message));
867
- command.help();
868
- }
869
- });
870
- options.decryptHandlers.map((decryption) => {
871
- const { options: options2, requiredOptions } = decryption;
872
- addPluginOptions(options2, subProgram);
873
- addPluginOptions(requiredOptions, subProgram, true);
874
- });
875
- const engines = options.decryptHandlers.map((e) => e.triggerOptionValue);
876
- subProgram.option(
877
- "--engine <engine>",
878
- `Encryption engine${engines.length > 0 ? "s" : ""} to use: ${engines.length === 1 ? engines[0] : engines.join(", ")}`,
879
- engines.length === 1 ? engines[0] : void 0
880
- );
881
- setProgramOptions({ program: subProgram, dotsecConfig });
882
- return subProgram;
883
- };
884
- var decrypt_default2 = addEncryptProgram;
885
-
886
- // src/cli/commands/encrypt.ts
887
- var addEncryptProgram2 = async (program2, options) => {
888
- const { encryptHandlers, dotsecConfig } = options;
889
- const subProgram = program2.enablePositionalOptions().passThroughOptions().command("encrypt").action(async (_options, command) => {
890
- try {
891
- const {
892
- // verbose,
893
- envFile,
894
- secFile,
895
- engine,
896
- createManifest,
897
- manifestFile,
898
- yes
899
- } = command.optsWithGlobals();
900
- const encryptionEngine = engine || dotsecConfig?.defaults?.encryptionEngine;
901
- const pluginCliEncrypt = (encryptHandlers || []).find((handler) => {
902
- return handler.triggerOptionValue === encryptionEngine;
903
- });
904
- if (!pluginCliEncrypt) {
905
- throw new Error(
906
- `No encryption plugin found, available encryption engine(s): ${options.encryptHandlers.map((e) => e.triggerOptionValue).join(", ")}`
907
- );
908
- }
909
- const allOptionKeys = [
910
- ...Object.keys(pluginCliEncrypt.options || {}),
911
- ...Object.keys(pluginCliEncrypt.requiredOptions || {})
912
- ];
913
- const allOptionsValues = Object.fromEntries(
914
- allOptionKeys.map((key) => {
915
- return [key, _options[key]];
916
- })
917
- );
918
- const dotenvString = await readContentsFromFile(envFile);
919
- let dotsecString;
920
- try {
921
- dotsecString = await readContentsFromFile(secFile);
922
- } catch (e) {
923
- }
924
- const cipherText = await pluginCliEncrypt.handler({
925
- plaintext: dotenvString,
926
- ciphertext: dotsecString,
927
- ...allOptionsValues
928
- });
929
- const dotsecOverwriteResponse = await promptOverwriteIfFileExists({
930
- filePath: secFile,
931
- skip: yes
932
- });
933
- if (dotsecOverwriteResponse === void 0 || dotsecOverwriteResponse.overwrite === true) {
934
- await writeContentsToFile(secFile, cipherText);
935
- console.log(
936
- `Wrote encrypted contents of ${strong(envFile)} file to ${strong(
937
- secFile
938
- )}`
939
- );
940
- if (createManifest || dotsecConfig?.defaults?.options?.createManifest) {
941
- const dotenvVars = parse(dotenvString).obj;
942
- const markdownManifest = `# Dotsec encryption manifest
943
-
944
- ## Overview
945
-
946
- - plaintext source: ${envFile}
947
- - ciphertext target: ${secFile}
948
- - created: ${( new Date()).toUTCString()}
949
- - encryption engine: ${pluginCliEncrypt.encryptionEngineName || pluginCliEncrypt.triggerOptionValue}
950
- - encryption engine options: ${JSON.stringify(allOptionsValues)}
951
-
952
- ## Variables
953
-
954
- | Key |
955
- | --- |
956
- ${Object.keys(dotenvVars).map((key) => {
957
- return `| \`${key} \`| `;
958
- }).join("\n")}
959
- `;
960
- const manifestTargetFile = manifestFile || `${secFile}.encryption-manifest.md`;
961
- await writeContentsToFile(manifestTargetFile, markdownManifest);
962
- console.log(
963
- `Wrote manifest of ${strong(envFile)} file to ${strong(
964
- manifestTargetFile
965
- )}`
966
- );
967
- }
968
- }
969
- } catch (e) {
970
- console.error(strong(e.message));
971
- command.help();
972
- }
973
- });
974
- options.encryptHandlers.map((encryptionHandler) => {
975
- const { options: options2, requiredOptions } = encryptionHandler;
976
- addPluginOptions(options2, subProgram);
977
- addPluginOptions(requiredOptions, subProgram, true);
978
- });
979
- const engines = options.encryptHandlers.map((e) => e.triggerOptionValue);
980
- const encryptionEngineNames = options.encryptHandlers.map(
981
- (e) => e.encryptionEngineName
982
- );
983
- subProgram.option(
984
- "--engine <engine>",
985
- `Encryption engine${engines.length > 0 ? "s" : ""}: ${engines.length === 1 ? engines[0] : engines.join(", ")}`,
986
- engines.length === 1 ? engines[0] : void 0
987
- );
988
- setProgramOptions({ program: subProgram, dotsecConfig });
989
- subProgram.description(
990
- `Encrypt .env file using ${encryptionEngineNames.join(", ")}`
991
- );
992
- return subProgram;
993
- };
994
- var encrypt_default2 = addEncryptProgram2;
995
- var addInitProgram = async (program2, options) => {
996
- const { dotsecConfig } = options;
997
- const subProgram = program2.enablePositionalOptions().passThroughOptions().command("init").action(async (_options, command) => {
998
- const { configFile = "dotsec.config.ts", yes } = command.optsWithGlobals();
999
- try {
1000
- const configTemplate = await readContentsFromFile(
1001
- path__default.default.resolve(__dirname, "../../src/templates/dotsec.config.ts")
1002
- );
1003
- const dotsecConfigOverwriteResponse = await promptOverwriteIfFileExists(
1004
- {
1005
- filePath: configFile,
1006
- skip: yes
1007
- }
1008
- );
1009
- if (dotsecConfigOverwriteResponse === void 0 || dotsecConfigOverwriteResponse.overwrite === true) {
1010
- await writeContentsToFile(configFile, configTemplate);
1011
- console.log(`Wrote config file to ${strong(configFile)}`);
1012
- }
1013
- } catch (e) {
1014
- command.error(e);
1015
- }
1016
- });
1017
- setProgramOptions({ program: subProgram, dotsecConfig });
1018
- return subProgram;
1019
- };
1020
- var init_default2 = addInitProgram;
1021
- var addPushProgram = async (program2, options) => {
1022
- const { dotsecConfig, handlers } = options;
1023
- const subProgram = program2.enablePositionalOptions().passThroughOptions().command("push").action(async (_options, command) => {
1024
- try {
1025
- const {
1026
- // verbose,
1027
- using,
1028
- envFile,
1029
- secFile,
1030
- engine,
1031
- yes
1032
- } = command.optsWithGlobals();
1033
- const encryptionEngine = engine || dotsecConfig?.defaults?.encryptionEngine;
1034
- const pluginCliDecrypt = (handlers || []).find((handler) => {
1035
- return handler.decrypt?.triggerOptionValue === encryptionEngine;
1036
- })?.decrypt;
1037
- const pluginCliPush = (handlers || []).find((handler) => {
1038
- return handler.push?.triggerOptionValue === encryptionEngine;
1039
- })?.push;
1040
- if (!pluginCliPush) {
1041
- throw new Error("No push plugin found!");
1042
- }
1043
- const allOptionKeys = [
1044
- ...Object.keys(pluginCliDecrypt?.options || {}),
1045
- ...Object.keys(pluginCliDecrypt?.requiredOptions || {}),
1046
- ...Object.keys(pluginCliPush?.options || {}),
1047
- ...Object.keys(pluginCliPush?.requiredOptions || {})
1048
- ];
1049
- const allOptionsValues = Object.fromEntries(
1050
- allOptionKeys.map((key) => {
1051
- return [key, _options[key]];
1052
- })
1053
- );
1054
- let envContents;
1055
- if (using === "env") {
1056
- if (!envFile) {
1057
- throw new Error("No dotenv file specified in --env-file option");
1058
- }
1059
- envContents = fs3__default.default.readFileSync(envFile, "utf8");
1060
- } else {
1061
- if (!secFile) {
1062
- throw new Error("No dotsec file specified in --sec-file option");
1063
- }
1064
- if (!pluginCliDecrypt) {
1065
- throw new Error(
1066
- `No decryption plugin found, available decryption engine(s): ${handlers.map((e) => `--${e.decrypt?.triggerOptionValue}`).join(", ")}`
1067
- );
1068
- }
1069
- const dotSecContents = fs3__default.default.readFileSync(secFile, "utf8");
1070
- envContents = await pluginCliDecrypt.handler({
1071
- ciphertext: dotSecContents,
1072
- ...allOptionsValues
1073
- });
1074
- }
1075
- if (envContents) {
1076
- const dotenvVars = parse(envContents).obj;
1077
- const expandedEnvVars = dotenvExpand.expand({
1078
- ignoreProcessEnv: true,
1079
- parsed: {
1080
- // add standard env variables
1081
- ...process.env,
1082
- // add custom env variables, either from .env or .sec, (or empty object if none)
1083
- ...dotenvVars
1084
- }
1085
- });
1086
- if (expandedEnvVars.parsed) {
1087
- await pluginCliPush.handler({
1088
- push: expandedEnvVars.parsed,
1089
- yes,
1090
- ...allOptionsValues
1091
- });
1092
- }
1093
- } else {
1094
- throw new Error("No .env or .sec file provided");
1095
- }
1096
- } catch (e) {
1097
- console.error(e);
1098
- process.exit(1);
1099
- }
1100
- });
1101
- setProgramOptions({ program: subProgram, dotsecConfig });
1102
- const engines = options.handlers.map(
1103
- ({ decrypt }) => decrypt.triggerOptionValue
1104
- );
1105
- subProgram.option(
1106
- "--engine <engine>",
1107
- `Encryption engine${engines.length > 0 ? "s" : ""} to use: ${engines.length === 1 ? engines[0] : engines.join(", ")}`,
1108
- engines.length === 1 ? engines[0] : void 0
1109
- );
1110
- const allOptions = {};
1111
- options.handlers.forEach((handlers2) => {
1112
- Object.keys(handlers2).map((handlerName) => {
1113
- const { options: cliOptions, requiredOptions } = handlers2[handlerName];
1114
- Object.keys(cliOptions || {}).forEach((key) => {
1115
- allOptions[key] = Array.isArray(cliOptions[key]) ? cliOptions[key] : { ...allOptions[key], ...cliOptions[key] };
1116
- });
1117
- Object.keys(requiredOptions || {}).forEach((key) => {
1118
- allOptions[key] = Array.isArray(requiredOptions[key]) ? requiredOptions[key] : {
1119
- ...allOptions[key],
1120
- ...requiredOptions[key],
1121
- required: true
1122
- };
1123
- });
1124
- });
1125
- });
1126
- const usage = [];
1127
- const descriptions = [];
1128
- handlers.forEach((handler) => {
1129
- if (handler.push?.description) {
1130
- descriptions.push(handler.push.description);
1131
- }
1132
- if (handler.push?.usage) {
1133
- usage.push(handler.push.usage);
1134
- }
1135
- });
1136
- if (descriptions.length > 0) {
1137
- subProgram.description(descriptions.join("\n"));
1138
- }
1139
- if (usage.length > 0) {
1140
- subProgram.usage(usage.join("\n"));
1141
- }
1142
- addPluginOptions(
1143
- Object.fromEntries(
1144
- Object.entries(allOptions).filter(
1145
- ([_key, value]) => value.required !== true
1146
- )
1147
- ),
1148
- subProgram
1149
- );
1150
- addPluginOptions(
1151
- Object.fromEntries(
1152
- Object.entries(allOptions).filter(
1153
- ([_key, value]) => value.required === true
1154
- )
1155
- ),
1156
- subProgram,
1157
- true
1158
- );
1159
- return subProgram;
1160
- };
1161
- var push_default2 = addPushProgram;
1162
- var addRunProgam = (program2, options) => {
1163
- const { dotsecConfig, decryptHandlers } = options || {};
1164
- const hasDecryptEngine = decryptHandlers !== void 0 && decryptHandlers.length > 0;
1165
- const subProgram = program2.command("run <command...>").allowUnknownOption(true).enablePositionalOptions().passThroughOptions().showHelpAfterError(true).action(
1166
- async (commands, _options, command) => {
1167
- try {
1168
- const {
1169
- envFile,
1170
- using,
1171
- secFile,
1172
- engine,
1173
- outputBackgroundColor,
1174
- showOutputPrefix,
1175
- outputPrefix
1176
- } = command.optsWithGlobals();
1177
- let envContents;
1178
- if (using === "env" || hasDecryptEngine === false) {
1179
- if (!envFile) {
1180
- throw new Error("No dotenv file specified in --env-file option");
1181
- }
1182
- envContents = fs3__default.default.readFileSync(envFile, "utf8");
1183
- } else if (using === "sec") {
1184
- if (!secFile) {
1185
- throw new Error("No dotsec file specified in --sec-file option");
1186
- }
1187
- const encryptionEngine = engine || dotsecConfig?.defaults?.encryptionEngine;
1188
- const pluginCliDecrypt = (decryptHandlers || []).find((handler) => {
1189
- return handler.triggerOptionValue === encryptionEngine;
1190
- });
1191
- if (!pluginCliDecrypt) {
1192
- throw new Error(
1193
- `No decryption plugin found, available decryption engine(s): ${(decryptHandlers || []).map((e) => `--${e.triggerOptionValue}`).join(", ")}`
1194
- );
1195
- }
1196
- const allOptionKeys = [
1197
- ...Object.keys(pluginCliDecrypt.options || {}),
1198
- ...Object.keys(pluginCliDecrypt.requiredOptions || {})
1199
- ];
1200
- const allOptionsValues = Object.fromEntries(
1201
- allOptionKeys.map((key) => {
1202
- return [key, _options[key]];
1203
- })
1204
- );
1205
- try {
1206
- const dotSecContents = fs3__default.default.readFileSync(secFile, "utf8");
1207
- envContents = await pluginCliDecrypt.handler({
1208
- ciphertext: dotSecContents,
1209
- ...allOptionsValues
1210
- });
1211
- } catch (e) {
1212
- console.error("Something bad happened while decrypting.");
1213
- console.error(`File: ${secFile}`);
1214
- throw e;
1215
- }
1216
- }
1217
- if (envContents) {
1218
- const dotenvVars = parse(envContents).obj;
1219
- const expandedEnvVars = dotenvExpand.expand({
1220
- ignoreProcessEnv: true,
1221
- parsed: {
1222
- // add standard env variables
1223
- ...process.env,
1224
- // add custom env variables, either from .env or .sec, (or empty object if none)
1225
- ...dotenvVars
1226
- }
1227
- });
1228
- const [userCommand, ...userCommandArgs] = commands;
1229
- const waiter = await new Promise((resolve) => {
1230
- const cprocess = child_process.spawn(userCommand, [...userCommandArgs], {
1231
- stdio: "pipe",
1232
- shell: false,
1233
- env: {
1234
- ...expandedEnvVars.parsed,
1235
- ...process.env,
1236
- __DOTSEC_ENV__: JSON.stringify(Object.keys(dotenvVars))
1237
- }
1238
- });
1239
- const expandedEnvVarsWithoutEnv = dotenvExpand.expand({
1240
- ignoreProcessEnv: true,
1241
- parsed: {
1242
- // add standard env variables
1243
- // add custom env variables, either from .env or .sec, (or empty object if none)
1244
- ...dotenvVars
1245
- }
1246
- });
1247
- cprocess.stdout.setEncoding("utf8");
1248
- let backgroundColor = outputBackgroundColor || dotsecConfig.defaults?.options?.outputBackgroundColor;
1249
- if (typeof backgroundColor === "boolean" && backgroundColor === true) {
1250
- backgroundColor = "red-bright";
1251
- }
1252
- let addBackgroundColor = (str) => str;
1253
- if (backgroundColor) {
1254
- if (!backgroundColors.includes(backgroundColor)) {
1255
- throw new Error(
1256
- `Invalid background color: ${backgroundColor}`
1257
- );
1258
- }
1259
- const backgroundColorFnName = camelCase.camelCase(
1260
- `bg-${backgroundColor}`
1261
- );
1262
- if (chalk2__default.default[backgroundColorFnName]) {
1263
- addBackgroundColor = chalk2__default.default[backgroundColorFnName];
1264
- } else {
1265
- console.warn(
1266
- `Invalid background color: ${backgroundColorFnName}, using default: red`
1267
- );
1268
- addBackgroundColor = chalk2__default.default.bgRedBright;
1269
- }
1270
- }
1271
- const prefix = showOutputPrefix || dotsecConfig?.defaults?.options?.showOutputPrefix ? `${dotsecConfig?.defaults?.options?.outputPrefix || outputPrefix || "(dotsec) "}` : "";
1272
- let lineBuffer = "";
1273
- cprocess.stdout.on("data", function(data) {
1274
- lineBuffer += data.toString();
1275
- const lines = lineBuffer.split("\n");
1276
- for (let i = 0; i < lines.length - 1; i++) {
1277
- const line = lines[i];
1278
- const redactedLines = Object.entries(
1279
- expandedEnvVarsWithoutEnv.parsed || {}
1280
- ).sort(([, a], [, b]) => {
1281
- if (a.length > b.length) {
1282
- return -1;
1283
- } else if (a.length < b.length) {
1284
- return 1;
1285
- } else {
1286
- return 0;
1287
- }
1288
- }).reduce((acc, [key, value]) => {
1289
- if (dotsecConfig?.redaction?.show?.includes(key)) {
1290
- return acc;
1291
- } else {
1292
- const redactedValue = value.replace(/./g, "*");
1293
- return acc.replace(value, redactedValue);
1294
- }
1295
- }, line);
1296
- console.log(prefix + addBackgroundColor(redactedLines));
1297
- }
1298
- lineBuffer = lines[lines.length - 1];
1299
- });
1300
- cprocess.stdout.on("end", function() {
1301
- console.log(prefix + addBackgroundColor(lineBuffer));
1302
- });
1303
- cprocess.stderr.setEncoding("utf8");
1304
- cprocess.stderr.on("data", function(data) {
1305
- process.stderr.write(data.toString());
1306
- });
1307
- cprocess.on("exit", (code) => {
1308
- resolve(code);
1309
- });
1310
- });
1311
- if (waiter !== 0) {
1312
- process.exit(waiter || 1);
1313
- }
1314
- } else {
1315
- throw new Error("No .env or .sec file provided");
1316
- }
1317
- } catch (e) {
1318
- console.error(strong(e.message));
1319
- command.help();
1320
- }
1321
- }
1322
- );
1323
- setProgramOptions({
1324
- program: subProgram,
1325
- commandName: hasDecryptEngine ? "run" : "runEnvOnly",
1326
- dotsecConfig
1327
- });
1328
- if (hasDecryptEngine) {
1329
- decryptHandlers?.map((run) => {
1330
- const { options: options2, requiredOptions } = run;
1331
- addPluginOptions(options2, subProgram);
1332
- addPluginOptions(requiredOptions, subProgram, true);
1333
- });
1334
- const engines = decryptHandlers?.map((e) => e.triggerOptionValue);
1335
- subProgram.option(
1336
- "--engine <engine>",
1337
- `Encryption engine${engines.length > 0 ? "s" : ""}: ${engines.join(", "), engines.length === 1 ? engines[0] : void 0}`
1338
- // engines.length === 1 ? engines[0] : undefined,
1339
- );
1340
- }
1341
- return subProgram;
1342
- };
1343
- var run_default2 = addRunProgam;
1344
- var separator = {
1345
- keyword: "separator",
1346
- type: "string",
1347
- metaSchema: {
1348
- type: "string",
1349
- description: "value separator"
1350
- },
1351
- modifying: true,
1352
- valid: true,
1353
- errors: false,
1354
- compile: (schema) => (data, ctx) => {
1355
- if (ctx) {
1356
- const { parentData, parentDataProperty } = ctx;
1357
- parentData[parentDataProperty] = data === "" ? [] : data.split(schema);
1358
- return true;
1359
- } else {
1360
- return false;
1361
- }
1362
- }
1363
- };
1364
- var program = new commander.Command();
1365
- (async () => {
1366
- const parsedOptions = yargsParser__default.default(process.argv);
1367
- const argvPluginModules = [];
1368
- if (parsedOptions.plugin) {
1369
- if (Array.isArray(parsedOptions.plugin)) {
1370
- argvPluginModules.push(...parsedOptions.plugin);
1371
- } else {
1372
- argvPluginModules.push(parsedOptions.plugin);
1373
- }
1374
- }
1375
- const someConfigFile = parsedOptions.configFile || parsedOptions.c;
1376
- const configFile = [
1377
- ...Array.isArray(someConfigFile) ? someConfigFile : [someConfigFile]
1378
- ]?.[0] || process.env.DOTSEC_CONFIG_FILE;
1379
- const { contents: dotsecConfig = {} } = await getMagicalConfig(configFile);
1380
- const { defaults = {}, push: pushVariables, plugins } = dotsecConfig;
1381
- program.name("dotsec").description(".env, but secure").version("1.0.0").passThroughOptions().action((_options, other) => {
1382
- other.help();
1383
- });
1384
- setProgramOptions({ program, dotsecConfig });
1385
- const ajv = new Ajv__default.default({
1386
- allErrors: true,
1387
- removeAdditional: true,
1388
- useDefaults: true,
1389
- coerceTypes: true,
1390
- allowUnionTypes: true,
1391
- addUsedSchema: false,
1392
- keywords: [separator]
1393
- });
1394
- const pluginModules = {};
1395
- if (plugins) {
1396
- for (const pluginName of plugins) {
1397
- if (!defaults?.plugins?.[pluginName]) {
1398
- defaults.plugins = {
1399
- ...defaults.plugins,
1400
- [pluginName]: {}
1401
- };
1402
- }
1403
- }
1404
- }
1405
- if (argvPluginModules.length > 0) {
1406
- for (const pluginModule of argvPluginModules) {
1407
- const plugin = await loadDotsecPlugin({ name: pluginModule });
1408
- const loadedPlugin = await plugin({
1409
- dotsecConfig,
1410
- ajv,
1411
- configFile
1412
- });
1413
- pluginModules[loadedPlugin.name] = pluginModule;
1414
- if (argvPluginModules.length === 1) {
1415
- dotsecConfig.defaults = {
1416
- ...dotsecConfig.defaults,
1417
- encryptionEngine: String(loadedPlugin.name),
1418
- plugins: {
1419
- ...dotsecConfig.defaults?.plugins,
1420
- [loadedPlugin.name]: {
1421
- ...dotsecConfig.defaults?.plugins?.[loadedPlugin.name]
1422
- }
1423
- }
1424
- };
1425
- }
1426
- }
1427
- }
1428
- if (defaults?.encryptionEngine) {
1429
- if (!defaults?.plugins?.[defaults.encryptionEngine]) {
1430
- defaults.plugins = {
1431
- ...defaults.plugins,
1432
- [defaults.encryptionEngine]: {}
1433
- };
1434
- }
1435
- }
1436
- if (defaults?.plugins) {
1437
- Object.entries(defaults?.plugins).forEach(
1438
- ([pluginName, pluginModule]) => {
1439
- if (pluginModule?.name) {
1440
- pluginModules[pluginName] = pluginModule?.name;
1441
- } else {
1442
- pluginModules[pluginName] = `@dotsec/plugin-${pluginName}`;
1443
- }
1444
- }
1445
- );
1446
- }
1447
- Object.values(pushVariables || {}).forEach((pushVariable) => {
1448
- Object.keys(pushVariable).forEach((pluginName) => {
1449
- if (!pluginModules[pluginName]) {
1450
- pluginModules[pluginName] = `@dotsec/plugin-${pluginName}`;
1451
- }
1452
- });
1453
- });
1454
- const cliPluginEncryptHandlers = [];
1455
- const cliPluginDecryptHandlers = [];
1456
- const cliPluginPushHandlers = [];
1457
- for (const pluginName of Object.keys(pluginModules)) {
1458
- const pluginModule = pluginModules[pluginName];
1459
- const initDotsecPlugin = await loadDotsecPlugin({ name: pluginModule });
1460
- const { addCliCommand, cliHandlers: cli } = await initDotsecPlugin({
1461
- ajv,
1462
- dotsecConfig,
1463
- configFile
1464
- });
1465
- if (cli?.encrypt) {
1466
- cliPluginEncryptHandlers.push(cli.encrypt);
1467
- }
1468
- if (cli?.decrypt) {
1469
- cliPluginDecryptHandlers.push(cli.decrypt);
1470
- if (cli?.push) {
1471
- cliPluginPushHandlers.push({ push: cli.push, decrypt: cli.decrypt });
1472
- }
1473
- }
1474
- if (addCliCommand) {
1475
- addCliCommand({ program });
1476
- }
1477
- }
1478
- if (cliPluginEncryptHandlers.length) {
1479
- await encrypt_default2(program, {
1480
- dotsecConfig,
1481
- encryptHandlers: cliPluginEncryptHandlers
1482
- });
1483
- }
1484
- if (cliPluginDecryptHandlers.length) {
1485
- await decrypt_default2(program, {
1486
- dotsecConfig,
1487
- decryptHandlers: cliPluginDecryptHandlers
1488
- });
1489
- }
1490
- if (cliPluginPushHandlers.length) {
1491
- await push_default2(program, {
1492
- dotsecConfig,
1493
- handlers: cliPluginPushHandlers
1494
- });
1495
- }
1496
- await init_default2(program, { dotsecConfig });
1497
- await run_default2(program, {
1498
- dotsecConfig,
1499
- decryptHandlers: cliPluginDecryptHandlers
1500
- });
1501
- await program.parse();
1502
- })();
1503
- //# sourceMappingURL=out.js.map
1504
- //# sourceMappingURL=index.js.map