-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathindex.ts
More file actions
1035 lines (928 loc) · 31.2 KB
/
index.ts
File metadata and controls
1035 lines (928 loc) · 31.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import * as yargs from 'yargs';
import execa from 'execa';
import clipboardy from 'clipboardy';
import { outputFile, readFile } from 'fs-extra';
import { resolve } from 'json-schema-ref-parser';
import { stripIndents } from 'common-tags';
import { Json, JsonObject } from '@app-config/utils';
import {
flattenObjectTree,
renameInFlattenedTree,
FileType,
stringify,
AppConfigError,
FailedToSelectSubObject,
EmptyStdinOrPromptResponse,
} from '@app-config/core';
import { promptUser, consumeStdin, asEnvOptions } from '@app-config/node';
import { checkTTY, LogLevel, logger } from '@app-config/logging';
import {
LoadedConfiguration,
ConfigLoadingOptions,
loadUnvalidatedConfig,
loadValidatedConfig,
} from '@app-config/config';
import {
keyDirs,
initializeLocalKeys,
loadPrivateKeyLazy,
loadPublicKeyLazy,
encryptValue,
decryptValue,
loadKey,
initializeKeys,
deleteLocalKeys,
loadSymmetricKeys,
saveNewSymmetricKey,
generateSymmetricKey,
latestSymmetricKeyRevision,
loadTeamMembersLazy,
trustTeamMember,
untrustTeamMember,
shouldUseSecretAgent,
startAgent,
disconnectAgents,
} from '@app-config/encryption';
import { loadSchema, JSONSchema } from '@app-config/schema';
import { generateTypeFiles } from '@app-config/generate';
import { loadMetaConfigLazy } from '@app-config/meta';
import { validateAllConfigVariants } from './validation';
enum OptionGroups {
Options = 'Options:',
General = 'General:',
Logging = 'Logging:',
}
type SubcommandOptions<
Options extends { [name: string]: yargs.Options },
PositionalOptions extends { [name: string]: yargs.PositionalOptions },
> = {
name: string | string[];
description?: string;
examples?: [string, string][];
options?: Options;
positional?: PositionalOptions;
};
type SubcommandFn<Options extends { [name: string]: yargs.Options }> = (
args: yargs.InferredOptionTypes<Options> & { _: string[] },
) => Promise<void> | void;
function subcommand<
Options extends { [name: string]: yargs.Options },
PositionalOptions extends { [name: string]: yargs.PositionalOptions },
>(
desc: SubcommandOptions<Options, PositionalOptions>,
run: SubcommandFn<Options & PositionalOptions>,
): yargs.CommandModule {
const { name, description, examples = [], options, positional } = desc;
const [command, ...aliases] = Array.isArray(name) ? name : [name];
return {
command,
aliases,
describe: description,
builder: (args) => {
if (positional) {
for (const [key, opt] of Object.entries(positional)) {
args.positional(key, opt);
}
}
if (options) {
args.options(options);
}
args.example(examples);
return args;
},
async handler(args) {
if (typeof args.cwd === 'string') process.chdir(args.cwd);
if (args.verbose) logger.setLevel(LogLevel.Verbose);
if (args.quiet) logger.setLevel(LogLevel.Error);
if (args.silent) logger.setLevel(LogLevel.None);
const running = Promise.resolve()
.then(() =>
run(args as { _: string[] } & yargs.InferredOptionTypes<Options & PositionalOptions>),
)
.then(() =>
// cleanup any secret agent clients right away, so it's safe to exit
disconnectAgents(),
);
Object.assign(args, { running });
return running;
},
};
}
const noSchemaOption = {
alias: 'q',
type: 'boolean',
default: false,
description: 'Avoids doing schema validation of your app-config (dangerous!)',
group: OptionGroups.Options,
} as const;
const fileNameBaseOption = {
type: 'string',
description: 'Changes what file name prefix is used when looking for app-config files',
group: OptionGroups.Options,
} as const;
const environmentOverrideOption = {
type: 'string',
description:
'Explicitly overrides the current environment (set by APP_CONFIG_ENV | NODE_ENV | ENV)',
group: OptionGroups.Options,
} as const;
const secretsOption = {
alias: 's',
type: 'boolean',
default: false,
description: 'Include secrets in the output',
group: OptionGroups.Options,
} as const;
const prefixOption = {
alias: 'p',
type: 'string',
default: 'APP_CONFIG',
description: 'Prefix for environment variable names',
group: OptionGroups.Options,
} as const;
const renameVariablesOption = {
alias: 'r',
type: 'string',
array: true,
description: 'Renames environment variables (eg. HTTP_PORT=FOO)',
group: OptionGroups.Options,
} as const;
const aliasVariablesOption = {
type: 'string',
array: true,
description: 'Like --rename, but keeps original name in results',
group: OptionGroups.Options,
} as const;
const onlyVariablesOption = {
type: 'string',
array: true,
description: 'Limits which environment variables are exported',
group: OptionGroups.Options,
} as const;
const environmentVariableNameOption = {
type: 'string',
default: 'APP_CONFIG',
description: 'Environment variable name to read full config from',
group: OptionGroups.Options,
} as const;
const formatOption = {
alias: 'f',
type: 'string',
default: 'yaml' as string,
choices: ['yaml', 'yml', 'json', 'json5', 'toml', 'raw'],
group: OptionGroups.Options,
} as const;
const selectOption = {
alias: 'S',
type: 'string',
description: 'A JSON pointer to select a nested property in the object',
group: OptionGroups.Options,
} as const;
const clipboardOption = {
alias: 'c',
type: 'boolean',
description: 'Copies the value to the system clipboard',
group: OptionGroups.Options,
} as const;
const secretAgentOption = {
type: 'boolean',
default: true,
description: 'Uses the secret-agent, if available',
group: OptionGroups.Options,
} as const;
interface LoadConfigCLIOptions {
secrets?: boolean;
select?: string;
noSchema?: boolean;
fileNameBase?: string;
environmentOverride?: string;
environmentVariableName?: string;
}
async function loadConfigWithOptions({
secrets: includeSecrets,
select,
noSchema,
fileNameBase,
environmentOverride,
environmentVariableName,
}: LoadConfigCLIOptions): Promise<[JsonObject, JSONSchema | undefined]> {
const options: ConfigLoadingOptions = {
fileNameBase,
environmentOverride,
environmentVariableName,
};
let loaded: LoadedConfiguration;
if (noSchema) {
loaded = await loadUnvalidatedConfig(options);
} else {
loaded = await loadValidatedConfig(options);
}
const { fullConfig, parsedNonSecrets, schema } = loaded;
let jsonConfig: JsonObject;
if (includeSecrets || !parsedNonSecrets) {
jsonConfig = fullConfig as JsonObject;
} else {
jsonConfig = parsedNonSecrets.toJSON() as JsonObject;
}
if (select) {
jsonConfig = (await resolve(jsonConfig)).get(select) as JsonObject;
if (jsonConfig === undefined) {
throw new FailedToSelectSubObject(`Failed to select property ${select}`);
}
}
return [jsonConfig, schema];
}
async function loadVarsWithOptions({
prefix,
rename,
alias,
only,
...opts
}: LoadConfigCLIOptions & {
prefix: string;
rename?: string[];
alias?: string[];
only?: string[];
}): Promise<[ReturnType<typeof flattenObjectTree>, JsonObject, JSONSchema | undefined]> {
const [config, schema] = await loadConfigWithOptions(opts);
let flattened = flattenObjectTree(config, prefix);
flattened = renameInFlattenedTree(flattened, rename, false);
flattened = renameInFlattenedTree(flattened, alias, true);
if (only) {
const filtered: typeof flattened = {};
for (const variable of Object.keys(flattened)) {
if (only.includes(variable)) {
filtered[variable] = flattened[variable];
}
}
return [filtered, config, schema];
}
return [flattened, config, schema];
}
function fileTypeForFormatOption(option: string): FileType {
switch (option) {
case 'json':
return FileType.JSON;
case 'json5':
return FileType.JSON5;
case 'toml':
return FileType.TOML;
case 'yml':
case 'yaml':
return FileType.YAML;
case 'raw':
return FileType.RAW;
default:
throw new AppConfigError(`${option} is not a valid file type`);
}
}
async function loadEnvironmentOptions(opts: {
environmentOverride?: string;
environmentVariableName?: string;
}) {
const {
value: { environmentAliases, environmentSourceNames },
} = await loadMetaConfigLazy();
return asEnvOptions(
opts.environmentOverride,
environmentAliases,
opts.environmentVariableName ?? environmentSourceNames,
);
}
export const cli = yargs
.scriptName('app-config')
.wrap(Math.max(yargs.terminalWidth() - 5, 80))
.strict()
.version()
.alias('v', 'version')
.help('h', 'Show help message with examples and options')
.alias('h', 'help')
.options({
cwd: {
alias: 'C',
nargs: 1,
type: 'string',
description: 'Run app-config in the context of this directory',
},
})
.options({
verbose: {
type: 'boolean',
description: 'Outputs verbose messages with internal details',
},
quiet: {
type: 'boolean',
description: 'Only outputs errors that user should be aware of',
},
silent: {
type: 'boolean',
description: 'Do not print anything non-functional',
},
})
.group('cwd', OptionGroups.General)
.group('help', OptionGroups.General)
.group('version', OptionGroups.General)
.group('verbose', OptionGroups.Logging)
.group('quiet', OptionGroups.Logging)
.group('silent', OptionGroups.Logging)
.command(
subcommand(
{
name: ['completion [shell]', 'completions [shell]'],
description: 'Prints bash completions',
examples: [
['source <($0 completion bash)', 'Adds bash completions, put this in your bashrc'],
],
positional: {
shell: {
type: 'string',
demandOption: false,
default: 'bash',
},
},
},
async ({ shell }) => {
if (shell !== 'bash') {
throw new AppConfigError('Only bash autocompletions are available');
}
yargs.showCompletionScript();
},
),
)
.command(
subcommand(
{
name: ['vars', 'variables', 'v'],
description: 'Prints out the generated environment variables',
examples: [
['$0 vars --secrets > .env', 'Prints all environment variables, including secret values'],
[
'export $($0 vars | xargs -L 1)',
'Export the generated environment variables to the current shell',
],
],
options: {
secrets: secretsOption,
prefix: prefixOption,
rename: renameVariablesOption,
alias: aliasVariablesOption,
only: onlyVariablesOption,
select: selectOption,
noSchema: noSchemaOption,
fileNameBase: fileNameBaseOption,
environmentOverride: environmentOverrideOption,
environmentVariableName: environmentVariableNameOption,
agent: secretAgentOption,
},
},
async (opts) => {
shouldUseSecretAgent(opts.agent);
const [env] = await loadVarsWithOptions(opts);
process.stdout.write(
Object.entries(env)
.map(([key, value]) => `${key}=${JSON.stringify(value)}`)
.join('\n'),
);
process.stdout.write('\n');
},
),
)
.command(
subcommand(
{
name: ['create', 'c'],
description: 'Prints out the current configuration, in a file format',
examples: [
['$0 create --format json', 'Prints configuration in JSON format'],
['$0 create --select "#/kubernetes"', 'Prints out a section of the configuration'],
],
options: {
secrets: secretsOption,
format: formatOption,
select: selectOption,
noSchema: noSchemaOption,
fileNameBase: fileNameBaseOption,
environmentOverride: environmentOverrideOption,
environmentVariableName: environmentVariableNameOption,
agent: secretAgentOption,
},
},
async (opts) => {
shouldUseSecretAgent(opts.agent);
const [toPrint] = await loadConfigWithOptions(opts);
process.stdout.write(stringify(toPrint, fileTypeForFormatOption(opts.format), true));
process.stdout.write('\n');
},
),
)
.command(
subcommand(
{
name: 'create-schema',
description:
'Prints the current schema object, in a file format, with all references resolves and flattened',
examples: [
['$0 create-schema --format json', 'Prints out the schema in JSON format'],
[
'$0 create-schema --select "#/definitions/WebServer"',
'Prints out a specific section of the schema',
],
],
options: {
format: formatOption,
select: selectOption,
},
},
async (opts) => {
const { schema } = await loadSchema();
let toPrint: Json;
if (opts.select) {
const refs = await resolve(schema);
toPrint = refs.get(opts.select);
if (toPrint === undefined) {
throw new FailedToSelectSubObject(`Failed to select property ${opts.select}`);
}
} else {
toPrint = schema as Json;
}
process.stdout.write(stringify(toPrint, fileTypeForFormatOption(opts.format), true));
process.stdout.write('\n');
},
),
)
.command(
subcommand(
{
name: ['validate'],
description: 'Checks all environment variants against your schema',
options: {
environment: {
alias: 'env',
type: 'string',
description: 'Validates only using one environment',
group: OptionGroups.Options,
},
includeNoEnvironment: {
type: 'boolean',
description: 'Validates config with no environment selected',
group: OptionGroups.Options,
},
},
},
async ({ environment, includeNoEnvironment }) => {
if (environment) {
await loadValidatedConfig({ environmentOverride: environment });
} else {
await validateAllConfigVariants({ includeNoEnvironment });
}
},
),
)
.command(
subcommand(
{
name: ['generate', 'gen', 'g'],
description: 'Run code generation as specified by meta file',
},
async () => {
const output = await generateTypeFiles();
if (output.length === 0) {
logger.warn('No files generated - did you add the correct meta properties?');
} else {
logger.info(`Generated: [ ${output.map(({ file }) => file).join(', ')} ]`);
}
},
),
)
.command({
command: 'secrets',
aliases: ['secret', 's'],
describe: 'Encryption subcommands',
handler: () => {},
builder: (args) =>
args
.demandCommand()
.command(
subcommand(
{
name: 'init',
description: 'Initializes your encryption keychain',
examples: [['$0 secrets init', 'Sets up your machine-local encryption key']],
},
async () => {
const initialized = await initializeLocalKeys();
if (initialized === false) {
throw new AppConfigError(
'Secrets were already initialized. Reset them if you want to create a new key.',
);
}
process.stdout.write(`\nYour app-config key was set up in ${keyDirs.keychain}\n\n`);
process.stdout.write(initialized.publicKeyArmored);
process.stdout.write('\n');
},
),
)
.command(
subcommand(
{
name: 'init-repo',
description:
'Creates initial symmetric key and initializes team members for a repository',
examples: [
[
'$0 secrets init-repo',
'Creates properties in meta file, making you the first trusted user',
],
],
options: {
environmentOverride: environmentOverrideOption,
environmentVariableName: environmentVariableNameOption,
},
},
async (opts) => {
const environmentOptions = await loadEnvironmentOptions(opts);
const myKey = await loadPublicKeyLazy();
const privateKey = await loadPrivateKeyLazy();
// we trust ourselves, essentially
await trustTeamMember(myKey, privateKey, environmentOptions);
logger.info('Initialized team members and a symmetric key');
},
),
)
.command(
subcommand(
{
name: 'init-key',
description: 'Creates a new symmetric key for encrypting new secrets',
examples: [
[
'$0 secrets init-key',
'Sets up a new symmetric key with the latest revision number',
],
],
options: {
environmentOverride: environmentOverrideOption,
environmentVariableName: environmentVariableNameOption,
},
},
async (opts) => {
const environmentOptions = await loadEnvironmentOptions(opts);
const keys = await loadSymmetricKeys(undefined, environmentOptions);
const teamMembers = await loadTeamMembersLazy(environmentOptions);
let revision: number;
if (keys.length > 0) {
revision = latestSymmetricKeyRevision(keys) + 1;
} else {
revision = 1;
}
await saveNewSymmetricKey(
await generateSymmetricKey(revision),
teamMembers,
environmentOptions,
);
logger.info(`Saved a new symmetric key, revision ${revision}`);
},
),
)
.command(
subcommand({ name: 'reset', description: 'Removes your encryption keys' }, async () => {
const confirm = await promptUser({
type: 'confirm',
initial: false,
message:
"Are you sure? You won't be able to any decrypt secrets that were signed for you.",
});
if (confirm) {
await deleteLocalKeys();
logger.warn('Your keys are now removed.');
}
}),
)
.command(
subcommand({ name: 'key', description: 'View your public key' }, async () => {
process.stdout.write((await loadPublicKeyLazy()).armor());
}),
)
.command(
subcommand(
{
name: 'export <path>',
description: 'Writes your public key to a file',
examples: [
[
'$0 secrets export /mnt/my-usb/joe-blow.asc',
'Writes your public key to a file, so it can be trusted by other users',
],
],
positional: {
path: {
type: 'string',
demandOption: true,
description: 'File to write key to',
},
},
},
async (opts) => {
const key = await loadPublicKeyLazy();
await outputFile(opts.path, key.armor());
logger.info(`The file ${opts.path} was written with your public key`);
},
),
)
.command(
subcommand(
{
name: 'ci',
description:
'Creates an encryption key that can be used without a passphrase (useful for CI)',
options: {
environmentOverride: environmentOverrideOption,
environmentVariableName: environmentVariableNameOption,
},
},
async (opts) => {
const environmentOptions = await loadEnvironmentOptions(opts);
logger.info('Creating a new trusted CI encryption key');
const { privateKeyArmored, publicKeyArmored } = await initializeKeys(false);
await trustTeamMember(
await loadKey(publicKeyArmored),
await loadPrivateKeyLazy(),
environmentOptions,
);
process.stdout.write(`\n${publicKeyArmored}\n\n${privateKeyArmored}\n\n`);
process.stdout.write(
stripIndents`
Public and private keys are printed above.
To use them, add CI variables called APP_CONFIG_SECRETS_KEY and APP_CONFIG_SECRETS_PUBLIC_KEY.
Ensure that (especially the private key) they are "protected" variables and not visible in logs.
`,
);
process.stdout.write('\n');
},
),
)
.command(
subcommand(
{
name: 'trust <keyPath>',
description: 'Adds a team member who can encrypt and decrypt values',
examples: [
[
'$0 secrets trust /mnt/my-usb/joe-blow.asc',
"Trusts a new team member's public key, allowing them to encrypt and decrypt values",
],
],
positional: {
keyPath: {
type: 'string',
demandOption: true,
description: 'Filepath of public key',
},
},
options: {
environmentOverride: environmentOverrideOption,
environmentVariableName: environmentVariableNameOption,
},
},
async (opts) => {
const environmentOptions = await loadEnvironmentOptions(opts);
const key = await loadKey(await readFile(opts.keyPath));
const privateKey = await loadPrivateKeyLazy();
await trustTeamMember(key, privateKey, environmentOptions);
logger.info(`Trusted ${key.getUserIds().join(', ')}`);
},
),
)
.command(
subcommand(
{
name: 'untrust <email>',
description: 'Revokes encryption access (in future) for a trusted team member',
examples: [
[
'$0 secrets untrust joe.blow@example.com',
'Creates a new symmetric key for all future encryption',
],
],
positional: {
email: {
type: 'string',
demandOption: true,
description: 'User ID email address',
},
},
options: {
environmentOverride: environmentOverrideOption,
environmentVariableName: environmentVariableNameOption,
},
},
async (opts) => {
const environmentOptions = await loadEnvironmentOptions(opts);
const privateKey = await loadPrivateKeyLazy();
// TODO: by default, untrust for all envs?
await untrustTeamMember(opts.email, privateKey, environmentOptions);
},
),
)
.command(
subcommand(
{
name: ['encrypt [secretValue]', 'enc [secretValue]', 'e [secretValue]'],
description: 'Encrypts a secret value',
examples: [
['$0 secrets encrypt "super-secret-value"', 'Encrypts the text given'],
[`$0 secrets encrypt '{ "nested": { "object": true } }'`, 'Encrypts JSON value'],
],
positional: {
secretValue: {
type: 'string',
description: 'JSON value to encrypt',
},
},
options: {
clipboard: clipboardOption,
agent: secretAgentOption,
environmentOverride: environmentOverrideOption,
environmentVariableName: environmentVariableNameOption,
},
},
async (opts) => {
const environmentOptions = await loadEnvironmentOptions(opts);
shouldUseSecretAgent(opts.agent);
// load these right away, so user unlocks asap
if (!shouldUseSecretAgent()) await loadPrivateKeyLazy();
let { secretValue }: { secretValue?: Json } = opts;
if (!secretValue) {
if (checkTTY()) {
secretValue = await promptUser({
type: 'password',
message: 'Value to encrypt (can be JSON)',
});
} else {
secretValue = await consumeStdin();
}
}
if (!secretValue) {
throw new EmptyStdinOrPromptResponse('Failed to read from stdin or prompt');
}
if (typeof secretValue === 'string') {
const isJson = secretValue.startsWith('{') && secretValue.endsWith('}');
try {
secretValue = JSON.parse(secretValue) as Json;
} catch (err) {
if (isJson) throw err;
// only complain if it's definitely supposed to be JSON
}
}
const encrypted = await encryptValue(secretValue, undefined, environmentOptions);
if (opts.clipboard) {
await clipboardy.write(encrypted);
process.stderr.write('Wrote encrypted text to system clipboard\n');
}
process.stdout.write(encrypted);
process.stdout.write('\n');
},
),
)
.command(
subcommand(
{
name: ['decrypt [encryptedText]', 'dec [encryptedText]', 'd [encryptedText]'],
description: 'Decrypts a secret value',
examples: [],
positional: {
encryptedText: {
type: 'string',
description: 'JSON value to encrypt',
group: OptionGroups.Options,
},
},
options: {
clipboard: clipboardOption,
agent: secretAgentOption,
environmentOverride: environmentOverrideOption,
environmentVariableName: environmentVariableNameOption,
},
},
async (opts) => {
const environmentOptions = await loadEnvironmentOptions(opts);
shouldUseSecretAgent(opts.agent);
// load these right away, so user unlocks asap
if (!shouldUseSecretAgent()) await loadPrivateKeyLazy();
let { encryptedText } = opts;
if (!encryptedText && opts.clipboard) {
encryptedText = await clipboardy.read();
if (encryptedText) process.stderr.write('Read value from system clipboard\n');
}
if (!encryptedText) {
if (checkTTY()) {
encryptedText = await promptUser({
type: 'password',
message: 'Value to decrypt',
});
} else {
encryptedText = await consumeStdin();
}
}
if (!encryptedText) {
throw new EmptyStdinOrPromptResponse('Failed to read from stdin or prompt');
}
const decrypted = await decryptValue(encryptedText, undefined, environmentOptions);
process.stdout.write(JSON.stringify(decrypted));
process.stdout.write('\n');
},
),
)
.command(
subcommand(
{
name: 'agent',
description: 'Starts the secret-agent daemon',
},
async () => {
await startAgent();
// wait forever
await new Promise(() => {});
},
),
),
})
.command(
subcommand(
{
name: '*',
description:
'Runs a command, with some environment variables injected (APP_CONFIG_*). Allows accessing app-config without node.js.',
examples: [
[
'$0 -- docker-compose up -d',
'Run Docker Compose with the generated environment variables',
],
['$0 -- bash-script.sh', 'Run some script, that uses $APP_CONFIG_FOO variables'],
['$0 -- env', 'Print environment variables, with app-config variables injected'],
// users are directed to these examples when just running app-config, so let's show some other subcommands
['$0 vars --secrets', 'Prints app config environment variables, including secret values'],
['$0 create -f json5', 'Prints app config as a format like YAML or JSON'],
['$0 generate', 'Run code generation as specified by the app-config meta file'],
],
options: {
secrets: secretsOption,
prefix: prefixOption,
rename: renameVariablesOption,
alias: aliasVariablesOption,
only: onlyVariablesOption,
format: { ...formatOption, default: 'json' },
select: selectOption,
noSchema: noSchemaOption,
fileNameBase: fileNameBaseOption,
environmentOverride: environmentOverrideOption,
environmentVariableName: environmentVariableNameOption,
agent: secretAgentOption,
},
},
async (opts) => {
shouldUseSecretAgent(opts.agent);
const [command, ...args] = opts._;
if (!command) {
yargs.showHelp();
process.exit(1);
}
const [env, fullConfig, schema] = await loadVarsWithOptions(opts);
// if prefix is set to something non-zero, set it as the full config
if (opts.prefix.length > 0) {
// this is almost always just APP_CONFIG
const variableName = opts.prefix;
// if we specified --only FOO, don't include APP_CONFIG
if (!opts.only || opts.only.includes(variableName)) {
env[variableName] = stringify(fullConfig, fileTypeForFormatOption(opts.format), true);
}
// this is APP_CONFIG_SCHEMA, a special variable used by programs to do their own validation