dotsec 1.0.0-alpha.1 → 1.0.0-alpha.10

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/README.md CHANGED
@@ -1,105 +1,165 @@
1
1
  # dotsec
2
2
 
3
- Secure dot env. Encrypts your .env so you can safely store it in your project.
3
+ Like dotenv, but encrypted.
4
4
 
5
- ## Usage
5
+ Encrypts your .env file with the AWS Encryption SDK so you can safely commit it to your repository.
6
6
 
7
- ### Execute a command and use the values of a .env file in its environment
7
+ ## Features
8
8
 
9
- ```sh
10
- npx dotsec --env-file .env {command}
11
- ```
9
+ - Encryption of .env files to .sec files.
10
+ - Decryption of .sec files to .env files.
11
+ - Run a command with the values of a .env file in its environment.
12
+ - Run a command with the values of a .sec file in its environment.
13
+ - Push selected .env/.sec entries to AWS Systems Manager Parameter Store.
14
+ - Push selected .env/.sec entries to AWS Secrets Manager.
12
15
 
13
- This command also supports injecting AWS assumed role credentials into the process environment.
16
+ ## Requirements
14
17
 
15
- You can specify the ARN of the role to assume in three ways:
18
+ - For initialisation enough credentials for creating a KMS key, and alias.
19
+ - For usage enough credentials for using the KMS key to encrypt and/or decrypt.
20
+ - An AWS KMS key with an alias.
16
21
 
17
- - By adding the `--aws-assume-role-arn` flag
18
- - By setting the `AWS_ASSUME_ROLE_ARN` environment variable
19
- - By adding the `AWS_ASSUME_ROLE_ARN` environment variable to your target `.env` file
22
+ ## Usage
20
23
 
21
- #### By adding the `--aws-assume-role-arn` flag
24
+ If you don't have an AWS KMS key with an alias, you can create one with the following command:
22
25
 
23
26
  ```sh
24
- npx dotsec --env-file .env --aws-assume-role-arn arn:aws:iam::123456789012:role/special-role {command}
27
+ aws kms create-key --description "Dotsec key" --region eu-west-1
25
28
  ```
26
29
 
27
- #### By setting the `AWS_ASSUME_ROLE_ARN` environment variable
30
+ Take not of the `KeyMetadata.KeyId` value, and create an alias for it:
31
+
32
+ > Note: You are free to pick any allowed alias name.
28
33
 
29
34
  ```sh
30
- AWS_ASSUME_ROLE_ARN=arn:aws:iam::123456789012:role/special-role npx dotsec --env-file .env {command}
35
+ aws kms create-alias --alias-name alias/dotsec --target-key-id <key-id>
31
36
  ```
32
37
 
33
- #### By adding the `AWS_ASSUME_ROLE_ARN` environment variable to your target `.env` file
38
+ ### Execute a command and use the values of a .env file in its environment
39
+
40
+ Create a .env file if you don't have one already, and add some values:
41
+
42
+ ```sh
43
+ echo "MY_FANCY_ENV_VAR='yes yes yallzies'\nHEY_HO='Let\'s go'" > .env
44
+ ```
34
45
 
35
- ...
36
- AWS_ASSUME_ROLE_ARN=arn:aws:iam::123456789012:role/special-role
37
- ...
46
+ The following command will create an encrypted version of the `.env` file, and store it in a file called `.sec`. It will also create a config file called `dotsec.config.ts` which contains the KMS key alias, and AWS region. (Note: you don't have to add the key alias and region to the config file, you can also pass them as options to the dotsec aws sub command. See `dotsec init aws --help` for more information.)
38
47
 
39
48
  ```sh
40
- npx dotsec --env-file .env {command}
49
+ npx dotsec init --aws-region eu-west-1 [--aws-key-alias alias/dotsec]
41
50
  ```
42
51
 
43
- Please refer to `dotsec help` for more information on other command line options.
52
+ The following files will be created:
44
53
 
45
- #### Secure usage
54
+ - `.sec` - The encrypted version of the `.env` file.
55
+ - `dotsec.config.ts` - The config file containing the KMS key alias and AWS region.
46
56
 
47
- Create a user managed AWS KMS key, add an alias. Refer to the AWS documentation for [creating keys](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html) and [managing aliases](https://docs.aws.amazon.com/kms/latest/developerguide/alias-manage.html#alias-create)
57
+ ### Add files to Git
48
58
 
49
- > the default key alias is set to `alias/top-secret`
59
+ Add the `.sec` and `dotsec.config.ts` files to your repository, and commit these accordingly.
50
60
 
51
- ### Execute a command and use the decrypted values of a .sec file in its environment
61
+ ### Run a process with your .env file
52
62
 
53
63
  ```sh
54
- npx dotsec {command}
64
+ npx dotsec run --env .env command env
55
65
  ```
56
66
 
57
- #### Other commands
58
-
59
- ### Encrypting a `.env` file into a `.sec` file
67
+ ### Run a process with your .sec file
60
68
 
61
69
  ```sh
62
- npx dotsec encrypt-env
70
+ npx dotsec run --sec .sec command env
63
71
  ```
64
72
 
65
- ### Decrypting a `.sec` file into a `.env` file
73
+ For more options see `dotsec run --help`.
74
+
75
+ ### Decrypt a .sec file to .env
66
76
 
67
77
  ```sh
68
- npx dotsec decrypt-env
78
+ npx dotsec decrypt
69
79
  ```
70
80
 
71
- ### Using a `.sec` file as environment variables
81
+ For more options see `dotsec decrypt --help`.
82
+
83
+ ### Encrypt a .env file to .sec
72
84
 
73
85
  ```sh
74
- npx dotsec node index.js
86
+ npx dotsec encrypt
75
87
  ```
76
88
 
77
- ## Using json secrets
89
+ For more options see `dotsec encrypt --help`.
78
90
 
79
- ### Encrypting a `secrets.json` file into a `secrets.encrypted.json` file
91
+ ### Push selected .env/.sec entries to AWS Systems Manager Parameter Store
80
92
 
81
- ```sh
82
- npx dotsec encrypt-secrets-json
93
+ Take your favorite editor, and edit the `dotsec.config.ts` file. Add the following to the `aws` object:
94
+
95
+ ```ts
96
+ {
97
+ variables: {
98
+ "NAME_OF_ENV_VAR_YOU_WANT_TO_PUSH": {
99
+ push: {
100
+ aws: {
101
+ ssm: true
102
+ }
103
+ }
104
+ }
105
+ }
106
+ }
83
107
  ```
84
108
 
85
- ### Decrypting a `secrets.encrypted.json` file into a `secrets.json` file
109
+ > Take a look at the DotsecConfig type for more options on how to configure SSM pushes.
86
110
 
87
111
  ```sh
88
- npx dotsec decrypt-secrets-json
112
+ npx dotsec push --env --to-aws-ssm
89
113
  ```
90
114
 
91
- ### Offload a `secrets.encrypted.json` file to SSM
115
+ ### Push selected .env/.sec entries to AWS Secrets Manager
116
+
117
+ Take your favorite editor, and edit the `dotsec.config.ts` file. Add the following to the `aws` object:
118
+
119
+ ```ts
120
+ {
121
+ variables: {
122
+ "NAME_OF_ENV_VAR_YOU_WANT_TO_PUSH": {
123
+ push: {
124
+ aws: {
125
+ secretsManager: true
126
+ }
127
+ }
128
+ }
129
+ }
130
+ }
131
+ ```
132
+
133
+ > Take a look at the DotsecConfig type for more options on how to configure Secrets Manager pushes.
92
134
 
93
135
  ```sh
94
- npx dotsec offload-secrets-json-to-ssm
136
+ npx dotsec push --env --to-aws-secrets-manager
95
137
  ```
96
138
 
97
139
  ### FAQ
98
140
 
99
- #### Is it safe to commit a `.sec` file alongside your code?
141
+ #### Is it safe to commit a `.sec` and `dotsec.config.ts` file alongside your code?
100
142
 
101
- Yes it is. The encryption key is managed by AWS, as long as you audit which principals can encrypt and decrypt you're good.
143
+ Yes it is. But it is up to you to make sure that access to the KMS key is restricted to the people who need to decrypt and/or encrypt the `.sec` file.
102
144
 
103
145
  #### Should I use this in production?
104
146
 
105
147
  We do, however, since this package is relatively new, I don't think you should.
148
+
149
+ ## Roadmap
150
+
151
+ - Write some tests already.
152
+ - Add support in-code use like `dotsec.config()`
153
+ - Add support for Node preload modules like `node -r dotsec/register index.js`
154
+ - Add watcher for `.env` file changes and automatically encrypt
155
+ - Write guide on postinstall for npm/yarn/pnpm
156
+ - Add chunking for encoding larger files with assymetric keys. Current limit is 4kb.
157
+ - Add support for other encryption SDKs like GCP KMS, Azure Key Vault, etc.
158
+ - Split up dotsec package in multiple packages, one for each SDK.
159
+ - Add support for pulling entries to GitHub actions secrets.
160
+
161
+ ## Limitations
162
+
163
+ - The only supported encryption SDK is the AWS Encryption SDK. For now.
164
+ - Assymetric keys are supported, but the encrypted file size is limited to the payload size of the key. Until chunking is implemented, that is.
165
+ - AWS Secrets Manager secrets which are marked for deletion **cannot** be updated until the deletion is complete. As of writing, the minimum deletion time is 7 days. This means that if you want to update a deleted AWS Secrets Manager secret, you have to wait at least 7 days before you can update it again. This is a limitation of AWS Secrets Manager, not dotsec
package/bin/dotsec.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- require("../dist/ds/cli");
3
+ require('../dist/cli');
@@ -0,0 +1,9 @@
1
+ var nn=Object.create;var ue=Object.defineProperty,on=Object.defineProperties,tn=Object.getOwnPropertyDescriptor,rn=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertyNames,ve=Object.getOwnPropertySymbols,an=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty,cn=Object.prototype.propertyIsEnumerable;var _e=(e,n,t)=>n in e?ue(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,r=(e,n)=>{for(var t in n||(n={}))Oe.call(n,t)&&_e(e,t,n[t]);if(ve)for(var t of ve(n))cn.call(n,t)&&_e(e,t,n[t]);return e},k=(e,n)=>on(e,rn(n)),mn=e=>ue(e,"__esModule",{value:!0});var pn=(e,n,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of sn(n))!Oe.call(e,o)&&o!=="default"&&ue(e,o,{get:()=>n[o],enumerable:!(t=tn(n,o))||t.enumerable});return e},y=e=>pn(mn(ue(e!=null?nn(an(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e);var Xe=y(require("commander"));var Z=y(require("@aws-sdk/client-kms"));var H=y(require("@aws-sdk/credential-providers")),Re=y(require("@aws-sdk/shared-ini-file-loader"));var Ae=y(require("chalk"));var T=e=>Ae.default.yellowBright(e),h=e=>Ae.default.yellow.bold(e);var Pe=async({argv:e,env:n})=>{var l,g,w;let t=await(0,Re.loadSharedConfigFiles)(),o,c,s;if(e.profile?(c={value:e.profile,origin:`command line option: ${T(e.profile)}`},o={value:await(0,H.fromIni)({profile:e.profile})(),origin:`${T(`[${e.profile}]`)} in credentials file`}):n.AWS_PROFILE?(c={value:n.AWS_PROFILE,origin:`env variable ${T("AWS_PROFILE")}: ${h(n.AWS_PROFILE)}`},o={value:await(0,H.fromIni)({profile:n.AWS_PROFILE})(),origin:`env variable ${T("AWS_PROFILE")}: ${h(n.AWS_PROFILE)}`}):n.AWS_ACCESS_KEY_ID&&n.AWS_SECRET_ACCESS_KEY?o={value:await(0,H.fromEnv)()(),origin:`env variables ${T("AWS_ACCESS_KEY_ID")} and ${T("AWS_SECRET_ACCESS_KEY")}`}:((l=t.credentialsFile)==null?void 0:l.default)&&(c={value:"default",origin:`${T("[default]")} in credentials file`},o={value:await(0,H.fromIni)({profile:"default"})(),origin:`profile ${T("[default]")}`}),e.region)s={value:e.region,origin:`command line option: ${T(e.region)}`};else if(n.AWS_REGION)s={value:n.AWS_REGION,origin:`env variable ${T("AWS_REGION")}: ${h(n.AWS_REGION)}`};else if(n.AWS_DEFAULT_REGION)s={value:n.AWS_DEFAULT_REGION,origin:`env variable ${T("AWS_DEFAULT_REGION")}: ${h(n.AWS_DEFAULT_REGION)}`};else if(c){let p=(w=(g=t==null?void 0:t.configFile)==null?void 0:g[c.value])==null?void 0:w.region;p&&(s={value:p,origin:`${T(`[profile ${c.value}]`)} in config file`})}let m=e.assumeRoleArn||n.AWS_ASSUME_ROLE_ARN;if(m){let p=e.assumeRoleArn?"command line option":"env variable";o={value:await(0,H.fromTemporaryCredentials)({masterCredentials:o==null?void 0:o.value,params:{DurationSeconds:e.assumeRoleSessionDuration||Number(n.AWS_ASSUME_ROLE_SESSION_DURATION)||3600,RoleArn:m},clientConfig:{region:s==null?void 0:s.value}})(),origin:`${p} ${T(`[${m}]`)}`}}return{credentialsAndOrigin:o,regionAndOrigin:s,profileAndOrigin:c}},be=({credentialsAndOrigin:e,regionAndOrigin:n,profileAndOrigin:t})=>{let o=[];return t&&o.push(`Got profile name from ${t.origin}`),e&&o.push(`Resolved credentials from ${e.origin}`),n&&o.push(`Resolved region from ${n.origin}`),o.join(`
2
+ `)};var ie=async({argv:e,env:n})=>{let{credentialsAndOrigin:t,regionAndOrigin:o,profileAndOrigin:c}=await Pe({argv:{region:e.awsRegion,profile:e.awsProfile,assumeRoleArn:e.awsAssumeRoleArn,assumeRoleSessionDuration:e.awsAssumeRoleSessionDuration},env:r({},n)});if(e.verbose===!0&&console.log(be({credentialsAndOrigin:t,regionAndOrigin:o,profileAndOrigin:c})),!(t&&o)){if(!t)throw console.error("Could not find credentials"),new Error("Could not find credentials");if(!o)throw console.error("Could not find region"),new Error("Could not find region")}return{credentialsAndOrigin:t,regionAndOrigin:o}};var L=async e=>{var w,p;let{kms:{keyAlias:n}={},region:t}=e,{credentialsAndOrigin:o,regionAndOrigin:c}=await ie({argv:{},env:r({},process.env)}),s=new Z.KMSClient({credentials:o.value,region:t||c.value}),m=new Z.DescribeKeyCommand({KeyId:n}),g=(p=(w=(await s.send(m)).KeyMetadata)==null?void 0:w.EncryptionAlgorithms)==null?void 0:p[0];if(g===void 0)throw new Error("Could not determine encryption algorithm");return{async encrypt(a){let d=new Z.EncryptCommand({KeyId:n,Plaintext:Buffer.from(a),EncryptionAlgorithm:g}),i=await s.send(d);if(!i.CiphertextBlob)throw new Error(`Something bad happened: ${JSON.stringify({encryptCommand:d})}`);return Buffer.from(i.CiphertextBlob).toString("base64")},async decrypt(a){let d=new Z.DecryptCommand({KeyId:n,CiphertextBlob:Buffer.from(a,"base64"),EncryptionAlgorithm:g}),i=await s.send(d);if(!i.Plaintext)throw new Error(`Something bad happened: ${JSON.stringify({cipherText:a,decryptCommand:d})}`);let A=Buffer.from(i.Plaintext).toString();return this.verbose&&console.info(`Decrypting key '${a}'`),A},other:()=>{}}};var pe=y(require("node:fs/promises")),Fe=y(require("prompts")),ke=y(require("node:path")),se=async e=>await pe.default.readFile(e,"utf-8"),ne=async(e,n)=>await pe.default.writeFile(e,n,"utf-8"),ln=async e=>{try{return await(0,pe.stat)(e),!0}catch{return!1}},oe=async({filePath:e,skip:n})=>{let t;return await ln(e)&&n!==!0?t=await(0,Fe.default)({type:"confirm",name:"overwrite",message:()=>`Overwrite './${ke.default.relative(process.cwd(),e)}' ?`}):t=void 0,t};var De=y(require("node:path"));var v=y(require("typescript")),Te=y(require("node:fs")),xe=e=>{let n=v.createPrinter(),t=Te.default.readFileSync(e.configFile,"utf8"),o=g=>w=>{function p(a){var d,i,A,C,E,S,P,b,O,M,D,q,U,j,V,Y,B,J;if(a=v.visitEachChild(a,p,g),a.kind===v.SyntaxKind.StringLiteral){let u=(i=(d=a==null?void 0:a.parent)==null?void 0:d.parent)==null?void 0:i.parent;if(((E=(C=(A=e.config)==null?void 0:A.aws)==null?void 0:C.kms)==null?void 0:E.keyAlias)&&((S=u==null?void 0:u.getChildAt(0))==null?void 0:S.getText())==="kms"){let _=(P=u==null?void 0:u.parent)==null?void 0:P.parent;if((_==null?void 0:_.getChildAt(0).getText())==="aws")return v.createStringLiteral((M=(O=(b=e.config)==null?void 0:b.aws)==null?void 0:O.kms)==null?void 0:M.keyAlias)}if(((q=(D=e.config)==null?void 0:D.aws)==null?void 0:q.region)&&((j=(U=a==null?void 0:a.parent)==null?void 0:U.getChildAt(0))==null?void 0:j.getText())==="region"){let _=(Y=(V=a==null?void 0:a.parent)==null?void 0:V.parent)==null?void 0:Y.parent;if((_==null?void 0:_.getChildAt(0).getText())==="aws")return v.createStringLiteral((J=(B=e.config)==null?void 0:B.aws)==null?void 0:J.region)}}return a}return v.visitNode(w,p)},c=v.createSourceFile("test.ts",t,v.ScriptTarget.ES2015,!0,v.ScriptKind.TS),s=v.transform(c,[o]),m=s.transformed[0],l=n.printFile(m);return s.dispose(),l};var we="dotsec.config.ts",Ie=[we],ae=".sec",ce=".env",le="alias/dotsec",gn="SecureString",R={config:{aws:{kms:{keyAlias:le},ssm:{parameterType:gn}}}};var fn={dotsec:{options:{verbose:["--verbose","Verbose output",!1],configFile:["-c, --config-file, --configFile <configFile>","Config file",we]}},init:{options:{verbose:["--verbose","Verbose output",!1],configFile:["-c, --config-file, --configFile <configFile>","Config file",we],env:["--env","Path to .env file",ce],sec:["--sec","Path to .sec file",ae],yes:["--yes","Skip confirmation prompts",!1],awsKeyAlias:["--aws-key-alias <awsKeyAlias>","AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)","alias/dotsec"],awsRegion:["--aws-region <awsRegion>","AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION"]}},decrypt:{inheritsFrom:["dotsec"],options:{env:["--env <env>","Path to .env file",ce],sec:["--sec <sec>","Path to .sec file",ae],yes:["--yes","Skip confirmation prompts",!1],awsKeyAlias:["--aws-key-alias <awsKeyAlias>","AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)","alias/dotsec"],awsRegion:["--aws-region <awsRegion>","AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION"]}},encrypt:{inheritsFrom:["dotsec"],options:{env:["--env <env>","Path to .env file",ce],sec:["--sec <sec>","Path to .sec file",ae],yes:["--yes","Skip confirmation prompts",!1],awsKeyAlias:["--aws-key-alias <awsKeyAlias>","AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)","alias/dotsec"],awsRegion:["--aws-region <awsRegion>","AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION"]}},run:{inheritsFrom:["dotsec"],options:{env:["--env <env>","Path to .env file"],sec:["--sec [sec]","Path to .sec file"],awsKeyAlias:["--aws-key-alias <awsKeyAlias>","AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)","alias/dotsec"],awsRegion:["--aws-region <awsRegion>","AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION"]}},push:{inheritsFrom:["dotsec"],options:{toAwsSsm:["--to-aws-ssm, --toAwsSsm","Push to AWS SSM"],toAwsSecretsManager:["--to-aws-secrets-manager, --toAwsSecretsManager","Push to AWS Secrets Manager"],env:["--env [env]","Path to .env file"],sec:["--sec [sec]","Path to .sec file"],yes:["--yes","Skip confirmation prompts",!1],awsKeyAlias:["--aws-key-alias <awsKeyAlias>","AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)","alias/dotsec"],awsRegion:["--aws-region <awsRegion>","AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION"]}}},We=(e,n,t={})=>{let o=e[n];if(o)return o.inheritsFrom?o==null?void 0:o.inheritsFrom.reduce((c,s)=>{let m=We(e,s,c);return r({},m)},{options:r(r({},t.options),o.options),requiredOptions:r(r({},t.requiredOptions),o.requiredOptions)}):{options:r(r({},t.options),o.options),requiredOptions:r(r({},t.requiredOptions),o.requiredOptions)}},W=(e,n)=>{let t=We(fn,n||e.name());(t==null?void 0:t.options)&&Object.values(t.options).forEach(([o,c,s])=>{e.option(o,c,s)}),(t==null?void 0:t.requiredOptions)&&Object.values(t.requiredOptions).forEach(([o,c,s])=>{e.requiredOption(o,c,s)})};var dn=async e=>{let n=e.enablePositionalOptions().passThroughOptions().command("init").action(async(t,o)=>{var a,d,i,A,C,E;let{verbose:c,configFile:s,env:m,sec:l,awskeyAlias:g,awsRegion:w,yes:p}=o.optsWithGlobals();try{let S;S=await L({verbose:c,region:w||process.env.AWS_REGION||((d=(a=R.config)==null?void 0:a.aws)==null?void 0:d.region),kms:{keyAlias:g||((E=(C=(A=(i=R)==null?void 0:i.config)==null?void 0:A.aws)==null?void 0:C.kms)==null?void 0:E.keyAlias)}});let P=await se(m),b=await S.encrypt(P),O=await oe({filePath:l,skip:p});(O===void 0||O.overwrite===!0)&&(await ne(l,b),console.log(`Wrote encrypted contents of ${h(m)} contents file to ${h(l)}`));let M=xe({configFile:De.default.resolve(__dirname,"../../src/templates/dotsec.config.ts"),config:{aws:{kms:{keyAlias:g||le},region:w||process.env.AWS_REGION}}}),D=await oe({filePath:s,skip:p});(D===void 0||D.overwrite===!0)&&(await ne(s,M),console.log(`Wrote config file to ${h(s)}`))}catch(S){o.error(S)}});return W(n),n},Ne=dn;var Ee=y(require("node:fs")),Ue=y(require("cross-spawn")),je=y(require("dotenv"));var Ke=y(require("node:path")),Ge=y(require("bundle-require")),qe=y(require("joycon"));var Me=y(require("fs")),Le=y(require("node:path"));function un(e){try{return new Function(`return ${e.trim()}`)()}catch{return{}}}var $e=async e=>{try{return un(await Me.default.promises.readFile(e,"utf8"))}catch(n){throw n instanceof Error?new Error(`Failed to parse ${Le.default.relative(process.cwd(),e)}: ${n.message}`):n}};var z=async e=>{var c,s,m,l,g,w,p,a,d,i,A,C,E,S,P,b,O,M,D,q,U,j,V,Y,B,J,u,_,te,X,re,N,K,G,F,x;let n=process.cwd(),o=await new qe.default().resolve({files:e?[e]:[...Ie,"package.json"],cwd:n,stopDir:Ke.default.parse(n).root,packageKey:"dotsec"});if(e&&o===null)throw new Error(`Could not find config file ${e}`);if(o){if(o.endsWith(".json")){let I=await $e(o),f;return o.endsWith("package.json")&&I.dotsec!==void 0?f=I.dotsec:f=I,{source:"json",contents:k(r(r({},R),f),{config:k(r(r({},f==null?void 0:f.config),R.config),{aws:k(r(r({},(c=f==null?void 0:f.config)==null?void 0:c.aws),(m=(s=R)==null?void 0:s.config)==null?void 0:m.aws),{kms:r(r({},(w=(g=(l=R)==null?void 0:l.config)==null?void 0:g.aws)==null?void 0:w.kms),(a=(p=f.config)==null?void 0:p.aws)==null?void 0:a.kms),ssm:r(r({},(A=(i=(d=R)==null?void 0:d.config)==null?void 0:i.aws)==null?void 0:A.ssm),(E=(C=f.config)==null?void 0:C.aws)==null?void 0:E.ssm),secretsManager:r(r({},(b=(P=(S=R)==null?void 0:S.config)==null?void 0:P.aws)==null?void 0:b.secretsManager),(M=(O=f.config)==null?void 0:O.aws)==null?void 0:M.secretsManager)})})})}}else if(o.endsWith(".ts")){let I=await(0,Ge.bundleRequire)({filepath:o}),f=I.mod.dotsec||I.mod.default||I.mod;return{source:"ts",contents:k(r(r({},R),f),{config:k(r(r({},f==null?void 0:f.config),R.config),{aws:k(r(r({},(D=f==null?void 0:f.config)==null?void 0:D.aws),(U=(q=R)==null?void 0:q.config)==null?void 0:U.aws),{kms:r(r({},(Y=(V=(j=R)==null?void 0:j.config)==null?void 0:V.aws)==null?void 0:Y.kms),(J=(B=f.config)==null?void 0:B.aws)==null?void 0:J.kms),ssm:r(r({},(te=(_=(u=R)==null?void 0:u.config)==null?void 0:_.aws)==null?void 0:te.ssm),(re=(X=f.config)==null?void 0:X.aws)==null?void 0:re.ssm),secretsManager:r(r({},(G=(K=(N=R)==null?void 0:N.config)==null?void 0:K.aws)==null?void 0:G.secretsManager),(x=(F=f.config)==null?void 0:F.aws)==null?void 0:x.secretsManager)})})})}}}return{source:"defaultConfig",contents:R}};var wn=e=>{let n=e.command("run <command...>").allowUnknownOption().description("Run a command in a separate process and populate env with decrypted .env or encrypted .sec values").action(async(t,o,c)=>{var i,A,C;let{configFile:s,env:m,sec:l,keyAlias:g,region:w}=c.optsWithGlobals(),{contents:{config:p}={}}=await z(s),a=await L({verbose:!0,kms:{keyAlias:g||((A=(i=p==null?void 0:p.aws)==null?void 0:i.kms)==null?void 0:A.keyAlias)||le},region:w||((C=p==null?void 0:p.aws)==null?void 0:C.region)}),d;if(m)d=Ee.default.readFileSync(m,"utf8");else if(l){let E=Ee.default.readFileSync(l,"utf8");d=await a.decrypt(E)}else throw new Error('Must provide either "--env" or "--sec"');if(d){let E=(0,je.parse)(d),[S,...P]=t;(0,Ue.default)(S,[...P],{stdio:"inherit",shell:!1,env:k(r(r({},process.env),E),{__DOTSEC_ENV__:JSON.stringify(Object.keys(E))})}),c.help()}else throw new Error("No .env or .sec file provided")});return W(n,"run"),n},Ve=wn;var Sn=async e=>{let n=e.enablePositionalOptions().passThroughOptions().command("decrypt").action(async(t,o)=>{var d,i,A,C,E;let{configFile:c,verbose:s,env:m,sec:l,awskeyAlias:g,awsRegion:w,yes:p}=o.optsWithGlobals(),{contents:a}=await z(c);try{let S;S=await L({verbose:s,region:w||process.env.AWS_REGION||((i=(d=a.config)==null?void 0:d.aws)==null?void 0:i.region),kms:{keyAlias:g||((E=(C=(A=a==null?void 0:a.config)==null?void 0:A.aws)==null?void 0:C.kms)==null?void 0:E.keyAlias)}});let P=await se(l),b=await S.decrypt(P),O=await oe({filePath:m,skip:p});(O===void 0||O.overwrite===!0)&&(await ne(m,b),console.log(`Wrote plaintext contents of ${h(l)} file to ${h(m)}`))}catch(S){o.error(S)}});return W(n),n},Ye=Sn;var yn=async e=>{let n=e.enablePositionalOptions().passThroughOptions().command("encrypt").action(async(t,o)=>{var d,i,A,C,E;let{verbose:c,configFile:s,env:m,sec:l,awskeyAlias:g,awsRegion:w,yes:p}=o.optsWithGlobals(),{contents:a}=await z(s);try{let S;S=await L({verbose:c,region:w||process.env.AWS_REGION||((i=(d=a.config)==null?void 0:d.aws)==null?void 0:i.region),kms:{keyAlias:g||((E=(C=(A=a==null?void 0:a.config)==null?void 0:A.aws)==null?void 0:C.kms)==null?void 0:E.keyAlias)}});let P=await se(m),b=await S.encrypt(P),O=await oe({filePath:l,skip:p});(O===void 0||O.overwrite===!0)&&(await ne(l,b),console.log(`Wrote encrypted contents of ${h(m)} file to ${h(l)}`))}catch(S){o.error(S)}});return W(n),n},Be=yn;var ge=e=>typeof e=="boolean";var Ce=y(require("node:fs"));var ze=y(require("dotenv"));var Je=y(require("prompts")),Se=async({predicate:e,skip:n,message:t})=>n===!0?{confirm:!0}:(e?await e():!0)?await(0,Je.default)({type:"confirm",name:"confirm",message:()=>t}):{confirm:!0};var ye=y(require("@aws-sdk/client-ssm"));var He=async e=>{let{region:n}=e||{},{credentialsAndOrigin:t,regionAndOrigin:o}=await ie({argv:{},env:r({},process.env)}),c=new ye.SSMClient({credentials:t.value,region:n||o.value});return{async put(s){for(let m of s){let l=new ye.PutParameterCommand(k(r({},m),{Overwrite:!0}));await c.send(l)}}}};var $=y(require("@aws-sdk/client-secrets-manager"));var Ze=async e=>{let{region:n}=e||{},{credentialsAndOrigin:t,regionAndOrigin:o}=await ie({argv:{},env:r({},process.env)}),c=new $.SecretsManagerClient({credentials:t.value,region:n||o.value});return{async push(s){let m=[],l=[];for(let g of s){let w=new $.DescribeSecretCommand({SecretId:g.Name});try{let p=await c.send(w);l.push(new $.UpdateSecretCommand({SecretId:p.ARN,SecretString:g.SecretString}))}catch(p){p instanceof $.ResourceNotFoundException&&m.push(new $.CreateSecretCommand({Name:g.Name,SecretString:g.SecretString}))}}return{createSecretCommands:m,updateSecretCommands:l,push:async()=>{for(let g of m)await c.send(g);for(let g of l)await c.send(g)}}}}};var An=async e=>{let n=e.enablePositionalOptions().passThroughOptions().command("push").action(async(t,o)=>{var S,P,b,O,M,D,q,U,j,V,Y,B,J;let{configFile:c,verbose:s,env:m,sec:l,awskeyAlias:g,awsRegion:w,yes:p,toAwsSsm:a,toAwsSecretsManager:d}=o.optsWithGlobals();if(!(a||d))throw new Error("You must specify at least one of --to-aws-ssm or --to-aws-secrets-manager");let{contents:i}=await z(c),A,C;if(A=await L({verbose:s,region:w||process.env.AWS_REGION||((P=(S=i.config)==null?void 0:S.aws)==null?void 0:P.region),kms:{keyAlias:g||((M=(O=(b=i==null?void 0:i.config)==null?void 0:b.aws)==null?void 0:O.kms)==null?void 0:M.keyAlias)}}),m){let u=ge(m)?ce:m;C=Ce.default.readFileSync(u,"utf8")}else if(l){let u=ge(l)?ae:l,_=Ce.default.readFileSync(u,"utf8");C=await A.decrypt(_)}else throw new Error('Must provide either "--env" or "--sec"');let E=(0,ze.parse)(C);try{if(a){let u=(q=(D=i==null?void 0:i.config)==null?void 0:D.aws)==null?void 0:q.ssm,_=(u==null?void 0:u.parameterType)||"SecureString",te=(u==null?void 0:u.pathPrefix)||"",X=Object.entries(E).reduce((N,[K,G])=>{var F,x,I,f;if((F=i.variables)==null?void 0:F[K]){let ee=(x=i.variables)==null?void 0:x[K];if(ee){let me=`${te}${K}`;if((f=(I=ee.push)==null?void 0:I.aws)==null?void 0:f.ssm){let fe=ge(ee.push.aws.ssm)?{Name:me,Value:G,Type:_}:k(r({Name:me,Type:_},ee.push.aws.ssm),{Value:G});N.push(fe)}}}return N},[]),{confirm:re}=await Se({message:`Are you sure you want to push the following variables to AWS SSM Parameter Store?
3
+ ${X.map(({Name:N})=>`- ${h(N||"[no name]")}`).join(`
4
+ `)}`,skip:p});re===!0&&(console.log("pushing to AWS SSM Parameter Store"),await(await He({region:w||((j=(U=i==null?void 0:i.config)==null?void 0:U.aws)==null?void 0:j.region)})).put(X))}if(d){let u=(Y=(V=i==null?void 0:i.config)==null?void 0:V.aws)==null?void 0:Y.secretsManager,_=(u==null?void 0:u.pathPrefix)||"",te=await Ze({region:w||process.env.AWS_REGION||((J=(B=i.config)==null?void 0:B.aws)==null?void 0:J.region)}),X=Object.entries(E).reduce((F,[x,I])=>{var f,ee,me,fe;if((f=i.variables)==null?void 0:f[x]){let de=(ee=i.variables)==null?void 0:ee[x];if(de){let he=`${_}${x}`;if((fe=(me=de.push)==null?void 0:me.aws)==null?void 0:fe.ssm){let en=ge(de.push.aws.ssm)?{Name:he,SecretString:I}:k(r({Name:he},de.push.aws.ssm),{SecretString:I});F.push(en)}}}return F},[]),{push:re,updateSecretCommands:N,createSecretCommands:K}=await te.push(X),G=[];if(N.length>0){let{confirm:F}=await Se({message:`Are you sure you want to update the following variables to AWS SSM Secrets Manager?
5
+ ${N.map(({input:{SecretId:x}})=>`- ${h(x||"[no name]")}`).join(`
6
+ `)}`,skip:p});G.push(F)}if(K.length>0){let{confirm:F}=await Se({message:`Are you sure you want to create the following variables to AWS SSM Secrets Manager?
7
+ ${K.map(({input:{Name:x}})=>`- ${h(x||"[no name]")}`).join(`
8
+ `)}`,skip:p});G.push(F)}G.find(F=>F===!1)||(console.log("pushing to AWS Secrets Manager"),await re())}}catch(u){o.error(u)}});return W(n),n},Qe=An;var Q=new Xe.Command;Q.name("dotsec").description(".env, but secure").version("1.0.0").enablePositionalOptions().action((e,n)=>{n.help()});W(Q);(async()=>{await Ne(Q),await Ve(Q),await Ye(Q),await Be(Q),await Qe(Q),Q.parse()})();
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/cli/index.ts", "../../src/lib/aws/AwsKmsEncryptionEngine.ts", "../../src/lib/aws/getCredentialsProfileRegion.ts", "../../src/utils/logger.ts", "../../src/lib/aws/handleCredentialsAndRegion.ts", "../../src/lib/io.ts", "../../src/cli/commands/init.ts", "../../src/lib/transformer.ts", "../../src/constants.ts", "../../src/cli/options.ts", "../../src/cli/commands/run.ts", "../../src/lib/config/index.ts", "../../src/lib/json.ts", "../../src/cli/commands/decrypt.ts", "../../src/cli/commands/encrypt.ts", "../../src/types.ts", "../../src/cli/commands/push.ts", "../../src/utils/prompts.ts", "../../src/lib/aws/AwsSsm.ts", "../../src/lib/aws/AwsSecretsManager.ts"],
4
+ "sourcesContent": ["import { Command } from \"commander\";\n\nimport addInitCommand from \"./commands/init\";\nimport addRunCommand from \"./commands/run\";\nimport addDecryptCommand from \"./commands/decrypt\";\nimport addEncryptCommand from \"./commands/encrypt\";\nimport addPushProgram from \"./commands/push\";\nimport { setProgramOptions } from \"./options\";\nconst program = new Command();\n\nprogram\n\t.name(\"dotsec\")\n\t.description(\".env, but secure\")\n\t.version(\"1.0.0\")\n\t.enablePositionalOptions()\n\t.action((_options, other: Command) => {\n\t\tother.help();\n\t});\n\nsetProgramOptions(program);\n(async () => {\n\tawait addInitCommand(program);\n\tawait addRunCommand(program);\n\tawait addDecryptCommand(program);\n\tawait addEncryptCommand(program);\n\tawait addPushProgram(program);\n\n\tprogram.parse();\n})();\n", "import {\n\tDecryptCommand,\n\tDescribeKeyCommand,\n\tEncryptCommand,\n\tKMSClient,\n} from \"@aws-sdk/client-kms\";\nimport { EncryptionEngineFactory } from \"../../types\";\nimport { handleCredentialsAndRegion } from \"./handleCredentialsAndRegion\";\n\nexport type AwsEncryptionEngineFactory = EncryptionEngineFactory<\n\t{ region?: string; kms?: { keyAlias?: string } },\n\t{ other: () => void }\n>;\n\nexport const awsEncryptionEngineFactory: AwsEncryptionEngineFactory = async (\n\toptions,\n) => {\n\tconst {\n\t\tkms: { keyAlias } = {},\n\t\tregion,\n\t} = options;\n\n\tconst { credentialsAndOrigin, regionAndOrigin } =\n\t\tawait handleCredentialsAndRegion({\n\t\t\targv: {},\n\t\t\tenv: { ...process.env },\n\t\t});\n\n\tconst kmsClient = new KMSClient({\n\t\tcredentials: credentialsAndOrigin.value,\n\t\tregion: region || regionAndOrigin.value,\n\t});\n\n\tconst describeKeyCommand = new DescribeKeyCommand({\n\t\tKeyId: keyAlias,\n\t});\n\n\tconst describeKeyResult = await kmsClient.send(describeKeyCommand);\n\tconst encryptionAlgorithm =\n\t\tdescribeKeyResult.KeyMetadata?.EncryptionAlgorithms?.[0];\n\n\tif (encryptionAlgorithm === undefined) {\n\t\tthrow new Error(\"Could not determine encryption algorithm\");\n\t}\n\n\treturn {\n\t\tasync encrypt(plaintext: string): Promise<string> {\n\t\t\tconst encryptCommand = new EncryptCommand({\n\t\t\t\tKeyId: keyAlias,\n\t\t\t\tPlaintext: Buffer.from(plaintext),\n\t\t\t\tEncryptionAlgorithm: encryptionAlgorithm,\n\t\t\t});\n\t\t\tconst encryptionResult = await kmsClient.send(encryptCommand);\n\n\t\t\tif (!encryptionResult.CiphertextBlob) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Something bad happened: ${JSON.stringify({\n\t\t\t\t\t\tencryptCommand,\n\t\t\t\t\t})}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst cipherText = Buffer.from(encryptionResult.CiphertextBlob).toString(\n\t\t\t\t\"base64\",\n\t\t\t);\n\n\t\t\treturn cipherText;\n\t\t},\n\t\tasync decrypt(cipherText: string): Promise<string> {\n\t\t\tconst decryptCommand = new DecryptCommand({\n\t\t\t\tKeyId: keyAlias,\n\t\t\t\tCiphertextBlob: Buffer.from(cipherText, \"base64\"),\n\t\t\t\tEncryptionAlgorithm: encryptionAlgorithm,\n\t\t\t});\n\n\t\t\tconst decryptionResult = await kmsClient.send(decryptCommand);\n\n\t\t\tif (!decryptionResult.Plaintext) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Something bad happened: ${JSON.stringify({\n\t\t\t\t\t\tcipherText: cipherText,\n\t\t\t\t\t\tdecryptCommand: decryptCommand,\n\t\t\t\t\t})}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst decryptedValue = Buffer.from(decryptionResult.Plaintext).toString();\n\n\t\t\tif (this.verbose) {\n\t\t\t\tconsole.info(`Decrypting key '${cipherText}'`);\n\t\t\t}\n\n\t\t\treturn decryptedValue;\n\t\t},\n\t\tother: () => {},\n\t};\n};\n", "import {\n\tfromEnv,\n\tfromIni,\n\tfromTemporaryCredentials,\n} from \"@aws-sdk/credential-providers\";\nimport { loadSharedConfigFiles } from \"@aws-sdk/shared-ini-file-loader\";\nimport { emphasis, strong } from \"../../utils/logger\";\n\nimport {\n\tCredentialsAndOrigin,\n\tProfileAndOrigin,\n\tRegionAndOrigin,\n} from \"./types\";\n\nexport const getCredentialsProfileRegion = async ({\n\targv,\n\tenv,\n}: {\n\targv: {\n\t\tprofile?: string;\n\t\tregion?: string;\n\t\tassumeRoleArn?: string;\n\t\tassumeRoleSessionDuration?: number;\n\t};\n\tenv: {\n\t\tAWS_PROFILE?: string;\n\t\tAWS_ACCESS_KEY_ID?: string;\n\t\tAWS_SECRET_ACCESS_KEY?: string;\n\t\tAWS_REGION?: string;\n\t\tAWS_DEFAULT_REGION?: string;\n\t\tAWS_ASSUME_ROLE_ARN?: string | undefined;\n\t\tAWS_ASSUME_ROLE_SESSION_DURATION?: string | undefined;\n\t\tTZ?: string;\n\t};\n}) => {\n\tconst sharedConfigFiles = await loadSharedConfigFiles();\n\tlet credentialsAndOrigin: CredentialsAndOrigin | undefined = undefined;\n\tlet profileAndOrigin: ProfileAndOrigin | undefined = undefined;\n\tlet regionAndOrigin: RegionAndOrigin | undefined = undefined;\n\tif (argv.profile) {\n\t\tprofileAndOrigin = {\n\t\t\tvalue: argv.profile,\n\t\t\torigin: `command line option: ${emphasis(argv.profile)}`,\n\t\t};\n\t\tcredentialsAndOrigin = {\n\t\t\tvalue: await fromIni({\n\t\t\t\tprofile: argv.profile,\n\t\t\t})(),\n\t\t\torigin: `${emphasis(`[${argv.profile}]`)} in credentials file`,\n\t\t};\n\t} else if (env.AWS_PROFILE) {\n\t\tprofileAndOrigin = {\n\t\t\tvalue: env.AWS_PROFILE,\n\t\t\torigin: `env variable ${emphasis(\"AWS_PROFILE\")}: ${strong(\n\t\t\t\tenv.AWS_PROFILE,\n\t\t\t)}`,\n\t\t};\n\t\tcredentialsAndOrigin = {\n\t\t\tvalue: await fromIni({\n\t\t\t\tprofile: env.AWS_PROFILE,\n\t\t\t})(),\n\t\t\torigin: `env variable ${emphasis(\"AWS_PROFILE\")}: ${strong(\n\t\t\t\tenv.AWS_PROFILE,\n\t\t\t)}`,\n\t\t};\n\t} else if (env.AWS_ACCESS_KEY_ID && env.AWS_SECRET_ACCESS_KEY) {\n\t\tcredentialsAndOrigin = {\n\t\t\tvalue: await fromEnv()(),\n\t\t\torigin: `env variables ${emphasis(\"AWS_ACCESS_KEY_ID\")} and ${emphasis(\n\t\t\t\t\"AWS_SECRET_ACCESS_KEY\",\n\t\t\t)}`,\n\t\t};\n\t} else if (sharedConfigFiles.credentialsFile?.default) {\n\t\tprofileAndOrigin = {\n\t\t\tvalue: \"default\",\n\t\t\torigin: `${emphasis(\"[default]\")} in credentials file`,\n\t\t};\n\t\tcredentialsAndOrigin = {\n\t\t\tvalue: await fromIni({\n\t\t\t\tprofile: \"default\",\n\t\t\t})(),\n\t\t\torigin: `profile ${emphasis(\"[default]\")}`,\n\t\t};\n\t}\n\n\tif (argv.region) {\n\t\tregionAndOrigin = {\n\t\t\tvalue: argv.region,\n\t\t\torigin: `command line option: ${emphasis(argv.region)}`,\n\t\t};\n\t} else if (env.AWS_REGION) {\n\t\tregionAndOrigin = {\n\t\t\tvalue: env.AWS_REGION,\n\t\t\torigin: `env variable ${emphasis(\"AWS_REGION\")}: ${strong(\n\t\t\t\tenv.AWS_REGION,\n\t\t\t)}`,\n\t\t};\n\t} else if (env.AWS_DEFAULT_REGION) {\n\t\tregionAndOrigin = {\n\t\t\tvalue: env.AWS_DEFAULT_REGION,\n\t\t\torigin: `env variable ${emphasis(\"AWS_DEFAULT_REGION\")}: ${strong(\n\t\t\t\tenv.AWS_DEFAULT_REGION,\n\t\t\t)}`,\n\t\t};\n\t} else if (profileAndOrigin) {\n\t\tconst foundRegion =\n\t\t\tsharedConfigFiles?.configFile?.[profileAndOrigin.value]?.region;\n\n\t\tif (foundRegion) {\n\t\t\tregionAndOrigin = {\n\t\t\t\tvalue: foundRegion,\n\t\t\t\torigin: `${emphasis(\n\t\t\t\t\t`[profile ${profileAndOrigin.value}]`,\n\t\t\t\t)} in config file`,\n\t\t\t};\n\t\t}\n\t}\n\n\tconst assumedRole = argv.assumeRoleArn || env.AWS_ASSUME_ROLE_ARN;\n\tif (assumedRole) {\n\t\tconst origin = argv.assumeRoleArn ? \"command line option\" : \"env variable\";\n\t\tcredentialsAndOrigin = {\n\t\t\tvalue: await fromTemporaryCredentials({\n\t\t\t\tmasterCredentials: credentialsAndOrigin?.value,\n\n\t\t\t\tparams: {\n\t\t\t\t\tDurationSeconds:\n\t\t\t\t\t\targv.assumeRoleSessionDuration ||\n\t\t\t\t\t\tNumber(env.AWS_ASSUME_ROLE_SESSION_DURATION) ||\n\t\t\t\t\t\t3600,\n\t\t\t\t\tRoleArn: assumedRole,\n\t\t\t\t},\n\n\t\t\t\tclientConfig: {\n\t\t\t\t\tregion: regionAndOrigin?.value,\n\t\t\t\t},\n\t\t\t})(),\n\t\t\torigin: `${origin} ${emphasis(`[${assumedRole}]`)}`,\n\t\t};\n\t}\n\n\treturn { credentialsAndOrigin, regionAndOrigin, profileAndOrigin };\n};\n\nexport const printVerboseCredentialsProfileRegion = ({\n\tcredentialsAndOrigin,\n\tregionAndOrigin,\n\tprofileAndOrigin,\n}: {\n\tcredentialsAndOrigin?: CredentialsAndOrigin;\n\tregionAndOrigin?: RegionAndOrigin;\n\tprofileAndOrigin?: ProfileAndOrigin;\n}): string => {\n\tconst out: string[] = [];\n\tif (profileAndOrigin) {\n\t\tout.push(`Got profile name from ${profileAndOrigin.origin}`);\n\t}\n\tif (credentialsAndOrigin) {\n\t\tout.push(`Resolved credentials from ${credentialsAndOrigin.origin}`);\n\t}\n\tif (regionAndOrigin) {\n\t\tout.push(`Resolved region from ${regionAndOrigin.origin}`);\n\t}\n\treturn out.join(\"\\n\");\n};\n", "import chalk from \"chalk\";\nlet _logger: Pick<Console, \"info\" | \"error\" | \"table\">;\nexport const getLogger = () => {\n\tif (!_logger) {\n\t\t_logger = console;\n\t}\n\n\treturn _logger;\n};\nexport const writeLine = (str: string) => {\n\tprocess.stdout.write(str);\n};\nexport const emphasis = (str: string): string => chalk.yellowBright(str);\nexport const strong = (str: string): string => chalk.yellow.bold(str);\n\nexport const clientLogger = {\n\tdebug(content: object) {\n\t\tconsole.log(content);\n\t},\n\tinfo(content: object) {\n\t\tconsole.log(content);\n\t},\n\twarn(content: object) {\n\t\tconsole.log(content);\n\t},\n\terror(content: object) {\n\t\tconsole.error(content);\n\t},\n};\n", "import {\n\tgetCredentialsProfileRegion,\n\tprintVerboseCredentialsProfileRegion,\n} from \"./getCredentialsProfileRegion\";\n\nexport const handleCredentialsAndRegion = async ({\n\targv,\n\tenv,\n}: {\n\targv: {\n\t\tawsRegion?: string;\n\t\tawsProfile?: string;\n\t\tverbose?: boolean;\n\t\tawsAssumeRoleArn?: string;\n\t\tawsAssumeRoleSessionDuration?: number;\n\t};\n\tenv: {\n\t\tAWS_PROFILE?: string | undefined;\n\t\tAWS_ACCESS_KEY_ID?: string | undefined;\n\t\tAWS_SECRET_ACCESS_KEY?: string | undefined;\n\t\tAWS_REGION?: string | undefined;\n\t\tAWS_DEFAULT_REGION?: string | undefined;\n\t\tAWS_ASSUME_ROLE_ARN?: string | undefined;\n\t\tAWS_ASSUME_ROLE_SESSION_DURATION?: string | undefined;\n\t\tTZ?: string;\n\t};\n}) => {\n\tconst { credentialsAndOrigin, regionAndOrigin, profileAndOrigin } =\n\t\tawait getCredentialsProfileRegion({\n\t\t\targv: {\n\t\t\t\tregion: argv.awsRegion,\n\t\t\t\tprofile: argv.awsProfile,\n\t\t\t\tassumeRoleArn: argv.awsAssumeRoleArn,\n\t\t\t\tassumeRoleSessionDuration: argv.awsAssumeRoleSessionDuration,\n\t\t\t},\n\t\t\tenv: {\n\t\t\t\t...env,\n\t\t\t},\n\t\t});\n\n\tif (argv.verbose === true) {\n\t\tconsole.log(\n\t\t\tprintVerboseCredentialsProfileRegion({\n\t\t\t\tcredentialsAndOrigin,\n\t\t\t\tregionAndOrigin,\n\t\t\t\tprofileAndOrigin,\n\t\t\t}),\n\t\t);\n\t}\n\n\tif (!(credentialsAndOrigin && regionAndOrigin)) {\n\t\tif (!credentialsAndOrigin) {\n\t\t\tconsole.error(\"Could not find credentials\");\n\t\t\tthrow new Error(\"Could not find credentials\");\n\t\t}\n\t\tif (!regionAndOrigin) {\n\t\t\tconsole.error(\"Could not find region\");\n\t\t\tthrow new Error(\"Could not find region\");\n\t\t}\n\t}\n\n\treturn { credentialsAndOrigin, regionAndOrigin };\n};\n", "import fs, { stat } from \"node:fs/promises\";\nimport prompts from \"prompts\";\nimport path from \"node:path\";\n\nexport const readContentsFromFile = async (\n\tfilePath: string,\n): Promise<string> => {\n\treturn await fs.readFile(filePath, \"utf-8\");\n};\n\nexport const writeContentsToFile = async (\n\tfilePath: string,\n\tcontents: string,\n): Promise<void> => {\n\treturn await fs.writeFile(filePath, contents, \"utf-8\");\n};\n\nexport const fileExists = async (source: string): Promise<boolean> => {\n\ttry {\n\t\tawait stat(source);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nexport const promptOverwriteIfFileExists = async ({\n\tfilePath,\n\tskip,\n}: {\n\tfilePath: string;\n\tskip?: boolean;\n}) => {\n\tlet overwriteResponse: prompts.Answers<\"overwrite\"> | undefined;\n\n\tif ((await fileExists(filePath)) && skip !== true) {\n\t\toverwriteResponse = await prompts({\n\t\t\ttype: \"confirm\",\n\t\t\tname: \"overwrite\",\n\t\t\tmessage: () => {\n\t\t\t\treturn `Overwrite './${path.relative(process.cwd(), filePath)}' ?`;\n\t\t\t},\n\t\t});\n\t} else {\n\t\toverwriteResponse = undefined;\n\t}\n\treturn overwriteResponse;\n};\n", "import { Command } from \"commander\";\nimport { awsEncryptionEngineFactory } from \"../../lib/aws/AwsKmsEncryptionEngine\";\nimport {\n\tpromptOverwriteIfFileExists,\n\treadContentsFromFile,\n\twriteContentsToFile,\n} from \"../../lib/io\";\nimport { EncryptionEngine, Init2CommandOptions } from \"../../types\";\n\nimport path from \"node:path\";\nimport { patchConfigFile } from \"../../lib/transformer\";\nimport { setProgramOptions } from \"../options\";\nimport { strong } from \"../../utils/logger\";\nimport {\n\tdefaultConfig,\n\tDOTSEC_DEFAULT_AWS_KMS_KEY_ALIAS,\n} from \"../../constants\";\ntype Formats = {\n\tenv?: string;\n\tawsKeyAlias?: string;\n};\n\nconst addInitProgram = async (program: Command) => {\n\tconst subProgram = program\n\t\t.enablePositionalOptions()\n\t\t.passThroughOptions()\n\t\t.command(\"init\")\n\t\t.action(async (_options: Formats, command: Command) => {\n\t\t\tconst {\n\t\t\t\tverbose,\n\t\t\t\tconfigFile,\n\t\t\t\tenv: dotenvFilename,\n\t\t\t\tsec: dotsecFilename,\n\t\t\t\tawskeyAlias,\n\t\t\t\tawsRegion,\n\t\t\t\tyes,\n\t\t\t} = command.optsWithGlobals<Init2CommandOptions>();\n\t\t\t// get dotsec config\n\n\t\t\ttry {\n\t\t\t\tlet encryptionEngine: EncryptionEngine;\n\n\t\t\t\tencryptionEngine = await awsEncryptionEngineFactory({\n\t\t\t\t\tverbose,\n\t\t\t\t\tregion:\n\t\t\t\t\t\tawsRegion ||\n\t\t\t\t\t\tprocess.env.AWS_REGION ||\n\t\t\t\t\t\tdefaultConfig.config?.aws?.region,\n\t\t\t\t\tkms: {\n\t\t\t\t\t\tkeyAlias: awskeyAlias || defaultConfig?.config?.aws?.kms?.keyAlias,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\t// get current dot env file\n\t\t\t\tconst dotenvString = await readContentsFromFile(dotenvFilename);\n\n\t\t\t\t// encrypt\n\t\t\t\tconst cipherText = await encryptionEngine.encrypt(dotenvString);\n\n\t\t\t\tconst dotsecOverwriteResponse = await promptOverwriteIfFileExists({\n\t\t\t\t\tfilePath: dotsecFilename,\n\t\t\t\t\tskip: yes,\n\t\t\t\t});\n\t\t\t\tif (\n\t\t\t\t\tdotsecOverwriteResponse === undefined ||\n\t\t\t\t\tdotsecOverwriteResponse.overwrite === true\n\t\t\t\t) {\n\t\t\t\t\tawait writeContentsToFile(dotsecFilename, cipherText);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`Wrote encrypted contents of ${strong(\n\t\t\t\t\t\t\tdotenvFilename,\n\t\t\t\t\t\t)} contents file to ${strong(dotsecFilename)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst patchedConfigTemplate = patchConfigFile({\n\t\t\t\t\tconfigFile: path.resolve(\n\t\t\t\t\t\t__dirname,\n\t\t\t\t\t\t\"../../src/templates/dotsec.config.ts\",\n\t\t\t\t\t),\n\t\t\t\t\tconfig: {\n\t\t\t\t\t\taws: {\n\t\t\t\t\t\t\tkms: {\n\t\t\t\t\t\t\t\tkeyAlias: awskeyAlias || DOTSEC_DEFAULT_AWS_KMS_KEY_ALIAS,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tregion: awsRegion || process.env.AWS_REGION,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tconst dotsecConfigOverwriteResponse = await promptOverwriteIfFileExists(\n\t\t\t\t\t{\n\t\t\t\t\t\tfilePath: configFile,\n\t\t\t\t\t\tskip: yes,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (\n\t\t\t\t\tdotsecConfigOverwriteResponse === undefined ||\n\t\t\t\t\tdotsecConfigOverwriteResponse.overwrite === true\n\t\t\t\t) {\n\t\t\t\t\tawait writeContentsToFile(configFile, patchedConfigTemplate);\n\t\t\t\t\tconsole.log(`Wrote config file to ${strong(configFile)}`);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tcommand.error(e);\n\t\t\t}\n\t\t});\n\n\tsetProgramOptions(subProgram);\n\n\treturn subProgram;\n};\n\nexport default addInitProgram;\n", "import * as ts from \"typescript\";\nimport fs from \"node:fs\";\n\nexport const patchConfigFile = (options: {\n\tconfigFile: string;\n\tconfig?: {\n\t\taws?: {\n\t\t\tregion?: string;\n\t\t\tkms?: {\n\t\t\t\tkeyAlias?: string;\n\t\t\t};\n\t\t};\n\t};\n}) => {\n\tconst printer: ts.Printer = ts.createPrinter();\n\tconst source = fs.readFileSync(options.configFile, \"utf8\");\n\n\tconst transformer =\n\t\t<T extends ts.Node>(context: ts.TransformationContext) =>\n\t\t(rootNode: T) => {\n\t\t\tfunction visit(node: ts.Node): ts.Node {\n\t\t\t\tnode = ts.visitEachChild(node, visit, context);\n\t\t\t\tif (node.kind === ts.SyntaxKind.StringLiteral) {\n\t\t\t\t\tconst kmsNode = node?.parent?.parent?.parent;\n\t\t\t\t\tif (options.config?.aws?.kms?.keyAlias) {\n\t\t\t\t\t\tif (kmsNode?.getChildAt(0)?.getText() === \"kms\") {\n\t\t\t\t\t\t\tconst awsNode = kmsNode?.parent?.parent;\n\t\t\t\t\t\t\tif (awsNode?.getChildAt(0).getText() === \"aws\") {\n\t\t\t\t\t\t\t\t// console.log(\n\t\t\t\t\t\t\t\t// \t\"parent is aws\",\n\t\t\t\t\t\t\t\t// \tnode.parent?.getChildAt(2).getText(),\n\t\t\t\t\t\t\t\t// );\n\t\t\t\t\t\t\t\treturn ts.createStringLiteral(\n\t\t\t\t\t\t\t\t\toptions.config?.aws?.kms?.keyAlias,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (options.config?.aws?.region) {\n\t\t\t\t\t\tif (node?.parent?.getChildAt(0)?.getText() === \"region\") {\n\t\t\t\t\t\t\tconst awsNode = node?.parent?.parent?.parent;\n\n\t\t\t\t\t\t\t// const awsNode = kmsNode?.parent?.parent;\n\t\t\t\t\t\t\tif (awsNode?.getChildAt(0).getText() === \"aws\") {\n\t\t\t\t\t\t\t\treturn ts.createStringLiteral(options.config?.aws?.region);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn node;\n\t\t\t}\n\t\t\treturn ts.visitNode(rootNode, visit);\n\t\t};\n\n\tconst sourceFile: ts.SourceFile = ts.createSourceFile(\n\t\t\"test.ts\",\n\t\tsource,\n\t\tts.ScriptTarget.ES2015,\n\t\ttrue,\n\t\tts.ScriptKind.TS,\n\t);\n\n\t// Options may be passed to transform\n\tconst result: ts.TransformationResult<ts.SourceFile> =\n\t\tts.transform<ts.SourceFile>(sourceFile, [transformer]);\n\n\tconst transformedSourceFile: ts.SourceFile = result.transformed[0];\n\n\tconst transformedSource = printer.printFile(transformedSourceFile);\n\tresult.dispose();\n\n\treturn transformedSource;\n};\n", "import { DotsecConfig } from \"./types\";\n\nexport const DOTSEC_DEFAULT_CONFIG_FILE = \"dotsec.config.ts\";\nexport const DOTSEC_CONFIG_FILES = [DOTSEC_DEFAULT_CONFIG_FILE];\nexport const DOTSEC_DEFAULT_DOTSEC_FILENAME = \".sec\";\nexport const DOTSEC_DEFAULT_DOTENV_FILENAME = \".env\";\nexport const DOTSEC_DEFAULT_AWS_KMS_KEY_ALIAS = \"alias/dotsec\";\nexport const DOTSEC_DEFAULT_AWS_SSM_PARAMETER_TYPE = \"SecureString\";\n\nexport const defaultConfig: DotsecConfig = {\n\tconfig: {\n\t\taws: {\n\t\t\tkms: {\n\t\t\t\tkeyAlias: DOTSEC_DEFAULT_AWS_KMS_KEY_ALIAS,\n\t\t\t},\n\t\t\tssm: {\n\t\t\t\tparameterType: DOTSEC_DEFAULT_AWS_SSM_PARAMETER_TYPE,\n\t\t\t},\n\t\t},\n\t},\n};\n", "import { Command } from \"commander\";\nimport {\n\tDOTSEC_DEFAULT_CONFIG_FILE,\n\tDOTSEC_DEFAULT_DOTENV_FILENAME,\n\tDOTSEC_DEFAULT_DOTSEC_FILENAME,\n} from \"../constants\";\n\ntype Options = {\n\t[optionName: string]:\n\t\t| [string, string]\n\t\t| [string, string, string | boolean | string[]];\n};\n\ntype CommandOptions = {\n\t[commandName: string]: {\n\t\tinheritsFrom?: string[];\n\t\toptions?: Options;\n\t\trequiredOptions?: Options;\n\t};\n};\nexport const commandOptions: CommandOptions = {\n\tdotsec: {\n\t\toptions: {\n\t\t\tverbose: [\"--verbose\", \"Verbose output\", false],\n\t\t\tconfigFile: [\n\t\t\t\t\"-c, --config-file, --configFile <configFile>\",\n\t\t\t\t\"Config file\",\n\t\t\t\tDOTSEC_DEFAULT_CONFIG_FILE,\n\t\t\t],\n\t\t},\n\t},\n\tinit: {\n\t\toptions: {\n\t\t\tverbose: [\"--verbose\", \"Verbose output\", false],\n\t\t\tconfigFile: [\n\t\t\t\t\"-c, --config-file, --configFile <configFile>\",\n\t\t\t\t\"Config file\",\n\t\t\t\tDOTSEC_DEFAULT_CONFIG_FILE,\n\t\t\t],\n\n\t\t\tenv: [\"--env\", \"Path to .env file\", DOTSEC_DEFAULT_DOTENV_FILENAME],\n\t\t\tsec: [\"--sec\", \"Path to .sec file\", DOTSEC_DEFAULT_DOTSEC_FILENAME],\n\t\t\tyes: [\"--yes\", \"Skip confirmation prompts\", false],\n\t\t\tawsKeyAlias: [\n\t\t\t\t\"--aws-key-alias <awsKeyAlias>\",\n\t\t\t\t\"AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)\",\n\t\t\t\t\"alias/dotsec\",\n\t\t\t],\n\t\t\tawsRegion: [\n\t\t\t\t\"--aws-region <awsRegion>\",\n\t\t\t\t\"AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION\",\n\t\t\t],\n\t\t},\n\t},\n\tdecrypt: {\n\t\tinheritsFrom: [\"dotsec\"],\n\t\toptions: {\n\t\t\tenv: [\"--env <env>\", \"Path to .env file\", DOTSEC_DEFAULT_DOTENV_FILENAME],\n\t\t\tsec: [\"--sec <sec>\", \"Path to .sec file\", DOTSEC_DEFAULT_DOTSEC_FILENAME],\n\t\t\tyes: [\"--yes\", \"Skip confirmation prompts\", false],\n\t\t\tawsKeyAlias: [\n\t\t\t\t\"--aws-key-alias <awsKeyAlias>\",\n\t\t\t\t\"AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)\",\n\t\t\t\t\"alias/dotsec\",\n\t\t\t],\n\t\t\tawsRegion: [\n\t\t\t\t\"--aws-region <awsRegion>\",\n\t\t\t\t\"AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION\",\n\t\t\t],\n\t\t},\n\t},\n\tencrypt: {\n\t\tinheritsFrom: [\"dotsec\"],\n\t\toptions: {\n\t\t\tenv: [\"--env <env>\", \"Path to .env file\", DOTSEC_DEFAULT_DOTENV_FILENAME],\n\t\t\tsec: [\"--sec <sec>\", \"Path to .sec file\", DOTSEC_DEFAULT_DOTSEC_FILENAME],\n\t\t\tyes: [\"--yes\", \"Skip confirmation prompts\", false],\n\t\t\tawsKeyAlias: [\n\t\t\t\t\"--aws-key-alias <awsKeyAlias>\",\n\t\t\t\t\"AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)\",\n\t\t\t\t\"alias/dotsec\",\n\t\t\t],\n\t\t\tawsRegion: [\n\t\t\t\t\"--aws-region <awsRegion>\",\n\t\t\t\t\"AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION\",\n\t\t\t],\n\t\t},\n\t},\n\n\trun: {\n\t\tinheritsFrom: [\"dotsec\"],\n\t\toptions: {\n\t\t\tenv: [\"--env <env>\", \"Path to .env file\"],\n\t\t\tsec: [\"--sec [sec]\", \"Path to .sec file\"],\n\t\t\tawsKeyAlias: [\n\t\t\t\t\"--aws-key-alias <awsKeyAlias>\",\n\t\t\t\t\"AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)\",\n\t\t\t\t\"alias/dotsec\",\n\t\t\t],\n\t\t\tawsRegion: [\n\t\t\t\t\"--aws-region <awsRegion>\",\n\t\t\t\t\"AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION\",\n\t\t\t],\n\t\t},\n\t},\n\tpush: {\n\t\tinheritsFrom: [\"dotsec\"],\n\t\toptions: {\n\t\t\ttoAwsSsm: [\"--to-aws-ssm, --toAwsSsm\", \"Push to AWS SSM\"],\n\t\t\ttoAwsSecretsManager: [\n\t\t\t\t\"--to-aws-secrets-manager, --toAwsSecretsManager\",\n\t\t\t\t\"Push to AWS Secrets Manager\",\n\t\t\t],\n\n\t\t\t// toGitHubSecrets: [\n\t\t\t// \t\"--to-github-secrets, --toGitHubSecrets <toGitHubSecrets>\",\n\t\t\t// \t\"Push to GitHub Secrets\",\n\t\t\t// ],\n\n\t\t\tenv: [\"--env [env]\", \"Path to .env file\"],\n\t\t\tsec: [\"--sec [sec]\", \"Path to .sec file\"],\n\t\t\tyes: [\"--yes\", \"Skip confirmation prompts\", false],\n\t\t\tawsKeyAlias: [\n\t\t\t\t\"--aws-key-alias <awsKeyAlias>\",\n\t\t\t\t\"AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)\",\n\t\t\t\t\"alias/dotsec\",\n\t\t\t],\n\t\t\tawsRegion: [\n\t\t\t\t\"--aws-region <awsRegion>\",\n\t\t\t\t\"AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION\",\n\t\t\t],\n\t\t},\n\t},\n};\n\nconst getInheritedOptions = (\n\tcopts: CommandOptions,\n\tcommandName: string,\n\tresult: { options?: Options; requiredOptions?: Options } = {},\n): { options?: Options; requiredOptions?: Options } | undefined => {\n\tconst command = copts[commandName];\n\tif (command) {\n\t\tif (command.inheritsFrom) {\n\t\t\treturn command?.inheritsFrom.reduce(\n\t\t\t\t(acc, inheritedCommandName) => {\n\t\t\t\t\tconst r = getInheritedOptions(copts, inheritedCommandName, acc);\n\t\t\t\t\treturn { ...r };\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\toptions: { ...result.options, ...command.options },\n\t\t\t\t\trequiredOptions: {\n\t\t\t\t\t\t...result.requiredOptions,\n\t\t\t\t\t\t...command.requiredOptions,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t} else {\n\t\t\treturn {\n\t\t\t\toptions: { ...result.options, ...command.options },\n\t\t\t\trequiredOptions: {\n\t\t\t\t\t...result.requiredOptions,\n\t\t\t\t\t...command.requiredOptions,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n};\n\nexport const setProgramOptions = (program: Command, commandName?: string) => {\n\tconst programOptions = getInheritedOptions(\n\t\tcommandOptions,\n\t\tcommandName || program.name(),\n\t);\n\n\tif (programOptions?.options) {\n\t\tObject.values(programOptions.options).forEach(\n\t\t\t([option, description, defaultValue]) => {\n\t\t\t\tprogram.option(option, description, defaultValue);\n\t\t\t},\n\t\t);\n\t}\n\tif (programOptions?.requiredOptions) {\n\t\tObject.values(programOptions.requiredOptions).forEach(\n\t\t\t([option, description, defaultValue]) => {\n\t\t\t\tprogram.requiredOption(option, description, defaultValue);\n\t\t\t},\n\t\t);\n\t}\n};\n", "import fs from \"node:fs\";\n\nimport { Command } from \"commander\";\nimport spawn from \"cross-spawn\";\nimport { parse } from \"dotenv\";\n\nimport { DOTSEC_DEFAULT_AWS_KMS_KEY_ALIAS } from \"../../constants\";\nimport { awsEncryptionEngineFactory } from \"../../lib/aws/AwsKmsEncryptionEngine\";\nimport { RunCommandOptions } from \"../../types\";\nimport { setProgramOptions } from \"../options\";\nimport { getConfig } from \"../../lib/config\";\nconst addRunProgam = (program: Command) => {\n\tconst subProgram = program\n\t\t.command(\"run <command...>\")\n\t\t.allowUnknownOption()\n\t\t.description(\n\t\t\t\"Run a command in a separate process and populate env with decrypted .env or encrypted .sec values\",\n\t\t)\n\t\t.action(\n\t\t\tasync (\n\t\t\t\tcommands: string[],\n\t\t\t\t_options: Record<string, string>,\n\t\t\t\tcommand: Command,\n\t\t\t) => {\n\t\t\t\tconst {\n\t\t\t\t\tconfigFile,\n\t\t\t\t\tenv: dotenv,\n\t\t\t\t\tsec: dotsec,\n\t\t\t\t\tkeyAlias,\n\t\t\t\t\tregion,\n\t\t\t\t} = command.optsWithGlobals<RunCommandOptions>();\n\n\t\t\t\tconst {\n\t\t\t\t\tcontents: { config } = {},\n\t\t\t\t} = await getConfig(configFile);\n\n\t\t\t\tconst encryptionPlugin = await awsEncryptionEngineFactory({\n\t\t\t\t\tverbose: true,\n\t\t\t\t\tkms: {\n\t\t\t\t\t\tkeyAlias:\n\t\t\t\t\t\t\tkeyAlias ||\n\t\t\t\t\t\t\tconfig?.aws?.kms?.keyAlias ||\n\t\t\t\t\t\t\tDOTSEC_DEFAULT_AWS_KMS_KEY_ALIAS,\n\t\t\t\t\t},\n\t\t\t\t\tregion: region || config?.aws?.region,\n\t\t\t\t});\n\n\t\t\t\tlet envContents: string | undefined;\n\n\t\t\t\tif (dotenv) {\n\t\t\t\t\tenvContents = fs.readFileSync(dotenv, \"utf8\");\n\t\t\t\t} else if (dotsec) {\n\t\t\t\t\tconst dotSecContents = fs.readFileSync(dotsec, \"utf8\");\n\t\t\t\t\tenvContents = await encryptionPlugin.decrypt(dotSecContents);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error('Must provide either \"--env\" or \"--sec\"');\n\t\t\t\t}\n\t\t\t\tif (envContents) {\n\t\t\t\t\tconst dotenvVars = parse(envContents);\n\t\t\t\t\tconst [userCommand, ...userCommandArgs] = commands;\n\t\t\t\t\tspawn(userCommand, [...userCommandArgs], {\n\t\t\t\t\t\tstdio: \"inherit\",\n\t\t\t\t\t\tshell: false,\n\t\t\t\t\t\tenv: {\n\t\t\t\t\t\t\t...process.env,\n\t\t\t\t\t\t\t...dotenvVars,\n\t\t\t\t\t\t\t__DOTSEC_ENV__: JSON.stringify(Object.keys(dotenvVars)),\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\n\t\t\t\t\tcommand.help();\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error(\"No .env or .sec file provided\");\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\tsetProgramOptions(subProgram, \"run\");\n\n\treturn subProgram;\n};\n\nexport default addRunProgam;\n", "import path from \"node:path\";\n\nimport { bundleRequire } from \"bundle-require\";\nimport JoyCon from \"joycon\";\n\nimport { loadJson } from \"../json\";\nimport { DotsecConfig, DotsecConfigAndSource } from \"../../types\";\nimport { defaultConfig, DOTSEC_CONFIG_FILES } from \"../../constants\";\n\nexport const getConfig = async (\n\tfilename?: string,\n): Promise<DotsecConfigAndSource> => {\n\tconst cwd = process.cwd();\n\tconst configJoycon = new JoyCon();\n\tconst configPath = await configJoycon.resolve({\n\t\tfiles: filename ? [filename] : [...DOTSEC_CONFIG_FILES, \"package.json\"],\n\t\tcwd,\n\t\tstopDir: path.parse(cwd).root,\n\t\tpackageKey: \"dotsec\",\n\t});\n\tif (filename && configPath === null) {\n\t\tthrow new Error(`Could not find config file ${filename}`);\n\t}\n\tif (configPath) {\n\t\tif (configPath.endsWith(\".json\")) {\n\t\t\tconst rawData = (await loadJson(configPath)) as Partial<DotsecConfig>;\n\n\t\t\tlet data: Partial<DotsecConfig>;\n\n\t\t\tif (\n\t\t\t\tconfigPath.endsWith(\"package.json\") &&\n\t\t\t\t(rawData as { dotsec: Partial<DotsecConfig> }).dotsec !== undefined\n\t\t\t) {\n\t\t\t\tdata = (rawData as { dotsec: Partial<DotsecConfig> }).dotsec;\n\t\t\t} else {\n\t\t\t\tdata = rawData as Partial<DotsecConfig>;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tsource: \"json\",\n\t\t\t\tcontents: {\n\t\t\t\t\t...defaultConfig,\n\t\t\t\t\t...data,\n\t\t\t\t\tconfig: {\n\t\t\t\t\t\t...data?.config,\n\t\t\t\t\t\t...defaultConfig.config,\n\t\t\t\t\t\taws: {\n\t\t\t\t\t\t\t...data?.config?.aws,\n\t\t\t\t\t\t\t...defaultConfig?.config?.aws,\n\t\t\t\t\t\t\tkms: {\n\t\t\t\t\t\t\t\t...defaultConfig?.config?.aws?.kms,\n\t\t\t\t\t\t\t\t...data.config?.aws?.kms,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tssm: {\n\t\t\t\t\t\t\t\t...defaultConfig?.config?.aws?.ssm,\n\t\t\t\t\t\t\t\t...data.config?.aws?.ssm,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tsecretsManager: {\n\t\t\t\t\t\t\t\t...defaultConfig?.config?.aws?.secretsManager,\n\t\t\t\t\t\t\t\t...data.config?.aws?.secretsManager,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t};\n\t\t} else if (configPath.endsWith(\".ts\")) {\n\t\t\tconst bundleRequireResult = await bundleRequire({\n\t\t\t\tfilepath: configPath,\n\t\t\t});\n\t\t\tconst data = (bundleRequireResult.mod.dotsec ||\n\t\t\t\tbundleRequireResult.mod.default ||\n\t\t\t\tbundleRequireResult.mod) as Partial<DotsecConfig>;\n\n\t\t\treturn {\n\t\t\t\tsource: \"ts\",\n\t\t\t\tcontents: {\n\t\t\t\t\t...defaultConfig,\n\t\t\t\t\t...data,\n\t\t\t\t\tconfig: {\n\t\t\t\t\t\t...data?.config,\n\t\t\t\t\t\t...defaultConfig.config,\n\t\t\t\t\t\taws: {\n\t\t\t\t\t\t\t...data?.config?.aws,\n\t\t\t\t\t\t\t...defaultConfig?.config?.aws,\n\t\t\t\t\t\t\tkms: {\n\t\t\t\t\t\t\t\t...defaultConfig?.config?.aws?.kms,\n\t\t\t\t\t\t\t\t...data.config?.aws?.kms,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tssm: {\n\t\t\t\t\t\t\t\t...defaultConfig?.config?.aws?.ssm,\n\t\t\t\t\t\t\t\t...data.config?.aws?.ssm,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tsecretsManager: {\n\t\t\t\t\t\t\t\t...defaultConfig?.config?.aws?.secretsManager,\n\t\t\t\t\t\t\t\t...data.config?.aws?.secretsManager,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\treturn { source: \"defaultConfig\", contents: defaultConfig };\n};\n", "import fs from \"fs\";\nimport path from \"node:path\";\n\nexport function jsoncParse(data: string) {\n\ttry {\n\t\treturn new Function(`return ${data.trim()}`)();\n\t} catch {\n\t\t// Silently ignore any error\n\t\t// That's what tsc/jsonc-parser did after all\n\t\treturn {};\n\t}\n}\n\nexport const loadJson = async (filepath: string) => {\n\ttry {\n\t\treturn jsoncParse(await fs.promises.readFile(filepath, \"utf8\"));\n\t} catch (error) {\n\t\tif (error instanceof Error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to parse ${path.relative(process.cwd(), filepath)}: ${\n\t\t\t\t\terror.message\n\t\t\t\t}`,\n\t\t\t);\n\t\t} else {\n\t\t\tthrow error;\n\t\t}\n\t}\n};\n", "import { Command } from \"commander\";\nimport { awsEncryptionEngineFactory } from \"../../lib/aws/AwsKmsEncryptionEngine\";\nimport {\n\tpromptOverwriteIfFileExists,\n\treadContentsFromFile,\n\twriteContentsToFile,\n} from \"../../lib/io\";\nimport { EncryptionEngine, Init2CommandOptions } from \"../../types\";\n\nimport { getConfig } from \"../../lib/config\";\nimport { setProgramOptions } from \"../options\";\nimport { strong } from \"../../utils/logger\";\n\nconst addDecryptProgram = async (program: Command) => {\n\tconst subProgram = program\n\t\t.enablePositionalOptions()\n\t\t.passThroughOptions()\n\t\t.command(\"decrypt\")\n\t\t.action(async (_options, command: Command) => {\n\t\t\tconst {\n\t\t\t\tconfigFile,\n\t\t\t\tverbose,\n\t\t\t\tenv: dotenvFilename,\n\t\t\t\tsec: dotsecFilename,\n\t\t\t\tawskeyAlias,\n\t\t\t\tawsRegion,\n\t\t\t\tyes,\n\t\t\t} = command.optsWithGlobals<Init2CommandOptions>();\n\n\t\t\t// get dotsec config\n\t\t\tconst { contents: dotsecConfig } = await getConfig(configFile);\n\t\t\ttry {\n\t\t\t\tlet encryptionEngine: EncryptionEngine;\n\n\t\t\t\tencryptionEngine = await awsEncryptionEngineFactory({\n\t\t\t\t\tverbose,\n\t\t\t\t\tregion:\n\t\t\t\t\t\tawsRegion ||\n\t\t\t\t\t\tprocess.env.AWS_REGION ||\n\t\t\t\t\t\tdotsecConfig.config?.aws?.region,\n\t\t\t\t\tkms: {\n\t\t\t\t\t\tkeyAlias: awskeyAlias || dotsecConfig?.config?.aws?.kms?.keyAlias,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\t// get current dot env file\n\t\t\t\tconst dotsecString = await readContentsFromFile(dotsecFilename);\n\n\t\t\t\t// encrypt\n\t\t\t\tconst plaintext = await encryptionEngine.decrypt(dotsecString);\n\n\t\t\t\tconst dotenvOverwriteResponse = await promptOverwriteIfFileExists({\n\t\t\t\t\tfilePath: dotenvFilename,\n\t\t\t\t\tskip: yes,\n\t\t\t\t});\n\t\t\t\tif (\n\t\t\t\t\tdotenvOverwriteResponse === undefined ||\n\t\t\t\t\tdotenvOverwriteResponse.overwrite === true\n\t\t\t\t) {\n\t\t\t\t\tawait writeContentsToFile(dotenvFilename, plaintext);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`Wrote plaintext contents of ${strong(\n\t\t\t\t\t\t\tdotsecFilename,\n\t\t\t\t\t\t)} file to ${strong(dotenvFilename)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tcommand.error(e);\n\t\t\t}\n\t\t});\n\n\tsetProgramOptions(subProgram);\n\n\treturn subProgram;\n};\n\nexport default addDecryptProgram;\n", "import { Command } from \"commander\";\nimport { awsEncryptionEngineFactory } from \"../../lib/aws/AwsKmsEncryptionEngine\";\nimport {\n\tpromptOverwriteIfFileExists,\n\treadContentsFromFile,\n\twriteContentsToFile,\n} from \"../../lib/io\";\nimport { EncryptionEngine, Init2CommandOptions } from \"../../types\";\n\nimport { getConfig } from \"../../lib/config\";\nimport { setProgramOptions } from \"../options\";\nimport { strong } from \"../../utils/logger\";\n\nconst addEncryptProgram = async (program: Command) => {\n\tconst subProgram = program\n\t\t.enablePositionalOptions()\n\t\t.passThroughOptions()\n\t\t.command(\"encrypt\")\n\t\t.action(async (_options, command: Command) => {\n\t\t\tconst {\n\t\t\t\tverbose,\n\t\t\t\tconfigFile,\n\t\t\t\tenv: dotenvFilename,\n\t\t\t\tsec: dotsecFilename,\n\t\t\t\tawskeyAlias,\n\t\t\t\tawsRegion,\n\t\t\t\tyes,\n\t\t\t} = command.optsWithGlobals<Init2CommandOptions>();\n\n\t\t\t// get dotsec config\n\t\t\tconst { contents: dotsecConfig } = await getConfig(configFile);\n\t\t\ttry {\n\t\t\t\tlet encryptionEngine: EncryptionEngine;\n\n\t\t\t\tencryptionEngine = await awsEncryptionEngineFactory({\n\t\t\t\t\tverbose,\n\t\t\t\t\tregion:\n\t\t\t\t\t\tawsRegion ||\n\t\t\t\t\t\tprocess.env.AWS_REGION ||\n\t\t\t\t\t\tdotsecConfig.config?.aws?.region,\n\t\t\t\t\tkms: {\n\t\t\t\t\t\tkeyAlias: awskeyAlias || dotsecConfig?.config?.aws?.kms?.keyAlias,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\t// get current dot env file\n\t\t\t\tconst dotenvString = await readContentsFromFile(dotenvFilename);\n\n\t\t\t\t// encrypt\n\t\t\t\tconst cipherText = await encryptionEngine.encrypt(dotenvString);\n\n\t\t\t\tconst dotsecOverwriteResponse = await promptOverwriteIfFileExists({\n\t\t\t\t\tfilePath: dotsecFilename,\n\t\t\t\t\tskip: yes,\n\t\t\t\t});\n\t\t\t\tif (\n\t\t\t\t\tdotsecOverwriteResponse === undefined ||\n\t\t\t\t\tdotsecOverwriteResponse.overwrite === true\n\t\t\t\t) {\n\t\t\t\t\tawait writeContentsToFile(dotsecFilename, cipherText);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`Wrote encrypted contents of ${strong(\n\t\t\t\t\t\t\tdotenvFilename,\n\t\t\t\t\t\t)} file to ${strong(dotsecFilename)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tcommand.error(e);\n\t\t\t}\n\t\t});\n\n\tsetProgramOptions(subProgram);\n\n\treturn subProgram;\n};\n\nexport default addEncryptProgram;\n", "import { PutParameterRequest } from \"@aws-sdk/client-ssm\";\n\n// utility types\nexport type DeepPartial<T> = T extends object\n\t? {\n\t\t\t[P in keyof T]?: DeepPartial<T[P]>;\n\t }\n\t: T;\n\nexport type EncryptionEngineFactoryProps = { verbose?: boolean };\nexport type EncryptionEngine<T = {}> = {\n\tencrypt(plaintext: string): Promise<string>;\n\tdecrypt(ciphertext: string): Promise<string>;\n} & T;\n\nexport type EncryptionEngineFactory<\n\tT = {},\n\tV extends Record<string, unknown> = {},\n> = {\n\t(options: EncryptionEngineFactoryProps & T): Promise<EncryptionEngine<V>>;\n};\n\nexport abstract class EncryptionPlugin {\n\tprotected verbose: boolean | undefined;\n\tconstructor(options: EncryptionEngineFactoryProps) {\n\t\tthis.verbose = options?.verbose;\n\t}\n\tabstract encrypt(plaintext: string): Promise<string>;\n\tabstract decrypt(ciphertext: string): Promise<string>;\n}\n\nexport type DotsecConfig = {\n\tconfig?: {\n\t\taws?: {\n\t\t\tregion?: string;\n\t\t\tkms?: {\n\t\t\t\tkeyAlias?: string;\n\t\t\t\tencryptionAlgorithm?:\n\t\t\t\t\t| \"RSAES_OAEP_SHA_1\"\n\t\t\t\t\t| \"RSAES_OAEP_SHA_256\"\n\t\t\t\t\t| \"SYMMETRIC_DEFAULT\";\n\t\t\t};\n\t\t\tssm?: {\n\t\t\t\tpathPrefix?: string;\n\t\t\t\tparameterType?: \"String\" | \"SecureString\";\n\t\t\t};\n\t\t\tsecretsManager?: {\n\t\t\t\tpathPrefix?: string;\n\t\t\t};\n\t\t};\n\t};\n\tvariables?: {\n\t\t[key: string]: {\n\t\t\tpush?: {\n\t\t\t\taws?: {\n\t\t\t\t\tssm?:\n\t\t\t\t\t\t| boolean\n\t\t\t\t\t\t| (Omit<PutParameterRequest, \"Name\" | \"Value\"> & { Name?: string });\n\t\t\t\t\tsecretsManager?: boolean;\n\t\t\t\t};\n\t\t\t\t// githubSecrets?: boolean;\n\t\t\t};\n\t\t};\n\t};\n};\n\n// Dotsec config file\nexport type DotsecConfigAndSource = {\n\tsource: \"json\" | \"ts\" | \"defaultConfig\";\n\tcontents: DotsecConfig;\n};\n\n// CLI types\nexport type GlobalCommandOptions = {\n\tconfigFile: string;\n\tverbose: false;\n};\n\nexport type Init2CommandOptions = {\n\tconfigFile: string;\n\tverbose: false;\n\tenv: string;\n\tsec: string;\n\tyes: boolean;\n\tawskeyAlias: string;\n\tawsRegion?: string;\n\tperformInit: (encryptionEngine: EncryptionEngine) => Promise<void>;\n};\n\nexport type RunCommandOptions = GlobalCommandOptions & {\n\tenv?: string;\n\tsec?: string;\n\tkeyAlias?: string;\n\tregion?: string;\n};\n\nexport type PushCommandOptions = {\n\tconfigFile: string;\n\tverbose: false;\n\tenv: string | boolean;\n\tsec: string | boolean;\n\tyes: boolean;\n\tawskeyAlias: string;\n\tawsRegion?: string;\n\ttoAwsSsm?: boolean;\n\ttoAwsSecretsManager?: boolean;\n};\n\nexport const isString = (value: unknown): value is string => {\n\treturn typeof value === \"string\";\n};\n\nexport const isNumber = (value: unknown): value is number => {\n\treturn typeof value === \"number\";\n};\nexport const isBoolean = (value: unknown): value is boolean => {\n\treturn typeof value === \"boolean\";\n};\n", "import { Command } from \"commander\";\nimport { awsEncryptionEngineFactory } from \"../../lib/aws/AwsKmsEncryptionEngine\";\nimport { EncryptionEngine, isBoolean, PushCommandOptions } from \"../../types\";\nimport fs from \"node:fs\";\n\nimport { getConfig } from \"../../lib/config\";\nimport { setProgramOptions } from \"../options\";\nimport {\n\tDOTSEC_DEFAULT_DOTENV_FILENAME,\n\tDOTSEC_DEFAULT_DOTSEC_FILENAME,\n} from \"../../constants\";\nimport { parse } from \"dotenv\";\nimport { PutParameterRequest } from \"@aws-sdk/client-ssm\";\nimport { strong } from \"../../utils/logger\";\nimport { promptConfirm } from \"../../utils/prompts\";\nimport { AwsSsm } from \"../../lib/aws/AwsSsm\";\nimport { AwsSecretsManager } from \"../../lib/aws/AwsSecretsManager\";\nimport { CreateSecretRequest } from \"@aws-sdk/client-secrets-manager\";\n\nconst addPushProgram = async (program: Command) => {\n\tconst subProgram = program\n\t\t.enablePositionalOptions()\n\t\t.passThroughOptions()\n\t\t.command(\"push\")\n\t\t.action(async (_options, command: Command) => {\n\t\t\tconst {\n\t\t\t\tconfigFile,\n\t\t\t\tverbose,\n\t\t\t\tenv,\n\t\t\t\tsec,\n\t\t\t\tawskeyAlias,\n\t\t\t\tawsRegion,\n\t\t\t\tyes,\n\t\t\t\ttoAwsSsm,\n\t\t\t\ttoAwsSecretsManager,\n\t\t\t} = command.optsWithGlobals<PushCommandOptions>();\n\n\t\t\tif (!(toAwsSsm || toAwsSecretsManager)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"You must specify at least one of --to-aws-ssm or --to-aws-secrets-manager\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst { contents: dotsecConfig } = await getConfig(configFile);\n\n\t\t\tlet encryptionEngine: EncryptionEngine;\n\t\t\tlet envContents: string | undefined;\n\t\t\tencryptionEngine = await awsEncryptionEngineFactory({\n\t\t\t\tverbose,\n\t\t\t\tregion:\n\t\t\t\t\tawsRegion ||\n\t\t\t\t\tprocess.env.AWS_REGION ||\n\t\t\t\t\tdotsecConfig.config?.aws?.region,\n\t\t\t\tkms: {\n\t\t\t\t\tkeyAlias: awskeyAlias || dotsecConfig?.config?.aws?.kms?.keyAlias,\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (env) {\n\t\t\t\tconst dotenvFilename = isBoolean(env)\n\t\t\t\t\t? DOTSEC_DEFAULT_DOTENV_FILENAME\n\t\t\t\t\t: env;\n\t\t\t\tenvContents = fs.readFileSync(dotenvFilename, \"utf8\");\n\t\t\t} else if (sec) {\n\t\t\t\tconst dotsecFilename = isBoolean(sec)\n\t\t\t\t\t? DOTSEC_DEFAULT_DOTSEC_FILENAME\n\t\t\t\t\t: sec;\n\t\t\t\tconst dotSecContents = fs.readFileSync(dotsecFilename, \"utf8\");\n\t\t\t\tenvContents = await encryptionEngine.decrypt(dotSecContents);\n\t\t\t} else {\n\t\t\t\tthrow new Error('Must provide either \"--env\" or \"--sec\"');\n\t\t\t}\n\n\t\t\tconst envObject = parse(envContents);\n\n\t\t\t// get dotsec config\n\t\t\ttry {\n\t\t\t\tif (toAwsSsm) {\n\t\t\t\t\tconst ssmDefaults = dotsecConfig?.config?.aws?.ssm;\n\t\t\t\t\tconst ssmType = ssmDefaults?.parameterType || \"SecureString\";\n\n\t\t\t\t\tconst pathPrefix = ssmDefaults?.pathPrefix || \"\";\n\t\t\t\t\tconst putParameterRequests = Object.entries(envObject).reduce<\n\t\t\t\t\t\tPutParameterRequest[]\n\t\t\t\t\t>((acc, [key, value]) => {\n\t\t\t\t\t\tif (dotsecConfig.variables?.[key]) {\n\t\t\t\t\t\t\tconst entry = dotsecConfig.variables?.[key];\n\t\t\t\t\t\t\tif (entry) {\n\t\t\t\t\t\t\t\tconst keyName = `${pathPrefix}${key}`;\n\t\t\t\t\t\t\t\tif (entry.push?.aws?.ssm) {\n\t\t\t\t\t\t\t\t\tconst putParameterRequest: PutParameterRequest = isBoolean(\n\t\t\t\t\t\t\t\t\t\tentry.push.aws.ssm,\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\tName: keyName,\n\t\t\t\t\t\t\t\t\t\t\t\tValue: value,\n\t\t\t\t\t\t\t\t\t\t\t\tType: ssmType,\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\t\tName: keyName,\n\t\t\t\t\t\t\t\t\t\t\t\tType: ssmType,\n\t\t\t\t\t\t\t\t\t\t\t\t...entry.push.aws.ssm,\n\t\t\t\t\t\t\t\t\t\t\t\tValue: value,\n\t\t\t\t\t\t\t\t\t\t };\n\n\t\t\t\t\t\t\t\t\tacc.push(putParameterRequest);\n\t\t\t\t\t\t\t\t\t// return putParameterRequest;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn acc;\n\t\t\t\t\t}, []);\n\n\t\t\t\t\tconst { confirm } = await promptConfirm({\n\t\t\t\t\t\tmessage: `Are you sure you want to push the following variables to AWS SSM Parameter Store?\n${putParameterRequests\n\t.map(({ Name }) => `- ${strong(Name || \"[no name]\")}`)\n\t.join(\"\\n\")}`,\n\t\t\t\t\t\tskip: yes,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (confirm === true) {\n\t\t\t\t\t\tconsole.log(\"pushing to AWS SSM Parameter Store\");\n\t\t\t\t\t\tconst meh = await AwsSsm({\n\t\t\t\t\t\t\tregion: awsRegion || dotsecConfig?.config?.aws?.region,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tawait meh.put(putParameterRequests);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// secrets manager\n\t\t\t\tif (toAwsSecretsManager) {\n\t\t\t\t\t// create secretss\n\t\t\t\t\tconst secretsManagerDefaults =\n\t\t\t\t\t\tdotsecConfig?.config?.aws?.secretsManager;\n\t\t\t\t\tconst pathPrefix = secretsManagerDefaults?.pathPrefix || \"\";\n\t\t\t\t\tconst awsSecretsMananger = await AwsSecretsManager({\n\t\t\t\t\t\tregion:\n\t\t\t\t\t\t\tawsRegion ||\n\t\t\t\t\t\t\tprocess.env.AWS_REGION ||\n\t\t\t\t\t\t\tdotsecConfig.config?.aws?.region,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst createSecretRequests = Object.entries(envObject).reduce<\n\t\t\t\t\t\tCreateSecretRequest[]\n\t\t\t\t\t>((acc, [key, value]) => {\n\t\t\t\t\t\tif (dotsecConfig.variables?.[key]) {\n\t\t\t\t\t\t\tconst entry = dotsecConfig.variables?.[key];\n\t\t\t\t\t\t\tif (entry) {\n\t\t\t\t\t\t\t\tconst keyName = `${pathPrefix}${key}`;\n\t\t\t\t\t\t\t\tif (entry.push?.aws?.ssm) {\n\t\t\t\t\t\t\t\t\tconst createSecretRequest: CreateSecretRequest = isBoolean(\n\t\t\t\t\t\t\t\t\t\tentry.push.aws.ssm,\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\tName: keyName,\n\t\t\t\t\t\t\t\t\t\t\t\tSecretString: value,\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\t\tName: keyName,\n\t\t\t\t\t\t\t\t\t\t\t\t...entry.push.aws.ssm,\n\t\t\t\t\t\t\t\t\t\t\t\tSecretString: value,\n\t\t\t\t\t\t\t\t\t\t };\n\n\t\t\t\t\t\t\t\t\tacc.push(createSecretRequest);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn acc;\n\t\t\t\t\t}, []);\n\t\t\t\t\tconst { push, updateSecretCommands, createSecretCommands } =\n\t\t\t\t\t\tawait awsSecretsMananger.push(createSecretRequests);\n\t\t\t\t\tconst confirmations: boolean[] = [];\n\t\t\t\t\tif (updateSecretCommands.length > 0) {\n\t\t\t\t\t\tconst { confirm: confirmUpdate } = await promptConfirm({\n\t\t\t\t\t\t\tmessage: `Are you sure you want to update the following variables to AWS SSM Secrets Manager?\n${updateSecretCommands\n\t.map(({ input: { SecretId } }) => `- ${strong(SecretId || \"[no name]\")}`)\n\t.join(\"\\n\")}`,\n\t\t\t\t\t\t\tskip: yes,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tconfirmations.push(confirmUpdate);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (createSecretCommands.length > 0) {\n\t\t\t\t\t\tconst { confirm: confirmCreate } = await promptConfirm({\n\t\t\t\t\t\t\tmessage: `Are you sure you want to create the following variables to AWS SSM Secrets Manager?\n${createSecretCommands\n\t.map(({ input: { Name } }) => `- ${strong(Name || \"[no name]\")}`)\n\t.join(\"\\n\")}`,\n\t\t\t\t\t\t\tskip: yes,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tconfirmations.push(confirmCreate);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!confirmations.find((c) => c === false)) {\n\t\t\t\t\t\tconsole.log(\"pushing to AWS Secrets Manager\");\n\n\t\t\t\t\t\tawait push();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tcommand.error(e);\n\t\t\t}\n\t\t});\n\n\tsetProgramOptions(subProgram);\n\n\treturn subProgram;\n};\n\nexport default addPushProgram;\n", "import prompts from \"prompts\";\nexport const promptConfirm = async ({\n\tpredicate,\n\tskip,\n\tmessage,\n}: {\n\tpredicate?: (...args: unknown[]) => Promise<boolean> | boolean;\n\tskip?: boolean;\n\tmessage: string;\n}): Promise<{ confirm: boolean }> => {\n\tif (skip === true) {\n\t\treturn { confirm: true };\n\t} else {\n\t\tconst result = predicate ? await predicate() : true;\n\t\tif (result) {\n\t\t\treturn await prompts({\n\t\t\t\ttype: \"confirm\",\n\t\t\t\tname: \"confirm\",\n\t\t\t\tmessage: () => {\n\t\t\t\t\treturn message;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\treturn { confirm: true };\n};\n", "import {\n\tPutParameterCommand,\n\tPutParameterRequest,\n\tSSMClient,\n} from \"@aws-sdk/client-ssm\";\nimport { handleCredentialsAndRegion } from \"./handleCredentialsAndRegion\";\n\nexport const AwsSsm = async (options?: {\n\tregion?: string;\n}) => {\n\tconst { region } = options || {};\n\n\tconst { credentialsAndOrigin, regionAndOrigin } =\n\t\tawait handleCredentialsAndRegion({\n\t\t\targv: {},\n\t\t\tenv: { ...process.env },\n\t\t});\n\n\tconst ssmClient = new SSMClient({\n\t\tcredentials: credentialsAndOrigin.value,\n\t\tregion: region || regionAndOrigin.value,\n\t});\n\n\treturn {\n\t\tasync put(putParameterRequests: PutParameterRequest[]): Promise<void> {\n\t\t\tfor (const putParameterRequest of putParameterRequests) {\n\t\t\t\tconst command = new PutParameterCommand({\n\t\t\t\t\t...putParameterRequest,\n\t\t\t\t\tOverwrite: true,\n\t\t\t\t});\n\t\t\t\tawait ssmClient.send(command);\n\t\t\t}\n\t\t},\n\t};\n};\n", "import {\n\tCreateSecretCommand,\n\tDescribeSecretCommand,\n\tUpdateSecretCommand,\n\tCreateSecretRequest,\n\tSecretsManagerClient,\n\tResourceNotFoundException,\n} from \"@aws-sdk/client-secrets-manager\";\nimport { handleCredentialsAndRegion } from \"./handleCredentialsAndRegion\";\n\nexport const AwsSecretsManager = async (options?: {\n\tregion?: string;\n}) => {\n\tconst { region } = options || {};\n\n\tconst { credentialsAndOrigin, regionAndOrigin } =\n\t\tawait handleCredentialsAndRegion({\n\t\t\targv: {},\n\t\t\tenv: { ...process.env },\n\t\t});\n\n\tconst secretsManagerClient = new SecretsManagerClient({\n\t\tcredentials: credentialsAndOrigin.value,\n\t\tregion: region || regionAndOrigin.value,\n\t});\n\n\treturn {\n\t\tasync push(createSecretRequests: CreateSecretRequest[]) {\n\t\t\tconst createSecretCommands: CreateSecretCommand[] = [];\n\n\t\t\tconst updateSecretCommands: UpdateSecretCommand[] = [];\n\t\t\tfor (const createSecretRequest of createSecretRequests) {\n\t\t\t\t// create secret\n\t\t\t\t// check if secret exists\n\t\t\t\tconst describeSecretCommand = new DescribeSecretCommand({\n\t\t\t\t\tSecretId: createSecretRequest.Name,\n\t\t\t\t});\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await secretsManagerClient.send(describeSecretCommand);\n\t\t\t\t\t// update secret\n\t\t\t\t\tupdateSecretCommands.push(\n\t\t\t\t\t\tnew UpdateSecretCommand({\n\t\t\t\t\t\t\tSecretId: result.ARN,\n\t\t\t\t\t\t\tSecretString: createSecretRequest.SecretString,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (e instanceof ResourceNotFoundException) {\n\t\t\t\t\t\t// create secret\n\t\t\t\t\t\tcreateSecretCommands.push(\n\t\t\t\t\t\t\tnew CreateSecretCommand({\n\t\t\t\t\t\t\t\tName: createSecretRequest.Name,\n\t\t\t\t\t\t\t\tSecretString: createSecretRequest.SecretString,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tcreateSecretCommands,\n\t\t\t\tupdateSecretCommands,\n\t\t\t\tpush: async () => {\n\t\t\t\t\tfor (const createSecretCommand of createSecretCommands) {\n\t\t\t\t\t\tawait secretsManagerClient.send(createSecretCommand);\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (const updateSecretCommand of updateSecretCommands) {\n\t\t\t\t\t\tawait secretsManagerClient.send(updateSecretCommand);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n};\n"],
5
+ "mappings": "u4BAAA,OAAwB,wBCAxB,MAKO,kCCLP,MAIO,4CACP,GAAsC,8CCLtC,OAAkB,oBAYX,GAAM,GAAW,AAAC,GAAwB,WAAM,aAAa,GACvD,EAAS,AAAC,GAAwB,WAAM,OAAO,KAAK,GDC1D,GAAM,IAA8B,MAAO,CACjD,OACA,SAkBK,CAlCN,UAmCC,GAAM,GAAoB,KAAM,+BAC5B,EACA,EACA,EA+CJ,GA9CA,AAAI,EAAK,QACR,GAAmB,CAClB,MAAO,EAAK,QACZ,OAAQ,wBAAwB,EAAS,EAAK,YAE/C,EAAuB,CACtB,MAAO,KAAM,cAAQ,CACpB,QAAS,EAAK,YAEf,OAAQ,GAAG,EAAS,IAAI,EAAK,oCAExB,AAAI,EAAI,YACd,GAAmB,CAClB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Y,MAAZ,eAAiB,IAAK,CACzB,GAAM,IAA2C,GAChD,GAAM,KAAK,IAAI,KAEb,CACA,KAAM,GACN,aAAc,GAEd,KACA,KAAM,IACH,GAAM,KAAK,IAAI,KAFlB,CAGA,aAAc,IAGjB,EAAI,KAAK,MAKZ,MAAO,IACL,IACG,CAAE,QAAM,uBAAsB,wBACnC,KAAM,IAAmB,KAAK,GACzB,EAA2B,GACjC,GAAI,EAAqB,OAAS,EAAG,CACpC,GAAM,CAAE,QAAS,GAAkB,KAAM,IAAc,CACtD,QAAS;AAAA,EACd,EACA,IAAI,CAAC,CAAE,MAAO,CAAE,eAAiB,KAAK,EAAO,GAAY,gBACzD,KAAK;AAAA,KACA,KAAM,IAGP,EAAc,KAAK,GAGpB,GAAI,EAAqB,OAAS,EAAG,CACpC,GAAM,CAAE,QAAS,GAAkB,KAAM,IAAc,CACtD,QAAS;AAAA,EACd,EACA,IAAI,CAAC,CAAE,MAAO,CAAE,WAAa,KAAK,EAAO,GAAQ,gBACjD,KAAK;AAAA,KACA,KAAM,IAGP,EAAc,KAAK,GAGpB,AAAK,EAAc,KAAK,AAAC,GAAM,IAAM,KACpC,SAAQ,IAAI,kCAEZ,KAAM,cAGA,EAAP,CACD,EAAQ,MAAM,MAIjB,SAAkB,GAEX,GAGD,GAAQ,GhB9Mf,GAAM,GAAU,GAAI,YAEpB,EACE,KAAK,UACL,YAAY,oBACZ,QAAQ,SACR,0BACA,OAAO,CAAC,EAAU,IAAmB,CACrC,EAAM,SAGR,EAAkB,GAClB,AAAC,UAAY,CACZ,KAAM,IAAe,GACrB,KAAM,IAAc,GACpB,KAAM,IAAkB,GACxB,KAAM,IAAkB,GACxB,KAAM,IAAe,GAErB,EAAQ",
6
+ "names": []
7
+ }
@@ -0,0 +1,9 @@
1
+ var We=Object.defineProperty,De=Object.defineProperties;var Ne=Object.getOwnPropertyDescriptors;var fe=Object.getOwnPropertySymbols;var Me=Object.prototype.hasOwnProperty,Le=Object.prototype.propertyIsEnumerable;var de=(e,n,t)=>n in e?We(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,r=(e,n)=>{for(var t in n||(n={}))Me.call(n,t)&&de(e,t,n[t]);if(fe)for(var t of fe(n))Le.call(n,t)&&de(e,t,n[t]);return e},b=(e,n)=>De(e,Ne(n));import{Command as Tn}from"commander";import{DecryptCommand as qe,DescribeKeyCommand as Ue,EncryptCommand as je,KMSClient as Ve}from"@aws-sdk/client-kms";import{fromEnv as $e,fromIni as le,fromTemporaryCredentials as Ke}from"@aws-sdk/credential-providers";import{loadSharedConfigFiles as Ge}from"@aws-sdk/shared-ini-file-loader";import ue from"chalk";var F=e=>ue.yellowBright(e),C=e=>ue.yellow.bold(e);var we=async({argv:e,env:n})=>{var l,g,w;let t=await Ge(),o,c,s;if(e.profile?(c={value:e.profile,origin:`command line option: ${F(e.profile)}`},o={value:await le({profile:e.profile})(),origin:`${F(`[${e.profile}]`)} in credentials file`}):n.AWS_PROFILE?(c={value:n.AWS_PROFILE,origin:`env variable ${F("AWS_PROFILE")}: ${C(n.AWS_PROFILE)}`},o={value:await le({profile:n.AWS_PROFILE})(),origin:`env variable ${F("AWS_PROFILE")}: ${C(n.AWS_PROFILE)}`}):n.AWS_ACCESS_KEY_ID&&n.AWS_SECRET_ACCESS_KEY?o={value:await $e()(),origin:`env variables ${F("AWS_ACCESS_KEY_ID")} and ${F("AWS_SECRET_ACCESS_KEY")}`}:((l=t.credentialsFile)==null?void 0:l.default)&&(c={value:"default",origin:`${F("[default]")} in credentials file`},o={value:await le({profile:"default"})(),origin:`profile ${F("[default]")}`}),e.region)s={value:e.region,origin:`command line option: ${F(e.region)}`};else if(n.AWS_REGION)s={value:n.AWS_REGION,origin:`env variable ${F("AWS_REGION")}: ${C(n.AWS_REGION)}`};else if(n.AWS_DEFAULT_REGION)s={value:n.AWS_DEFAULT_REGION,origin:`env variable ${F("AWS_DEFAULT_REGION")}: ${C(n.AWS_DEFAULT_REGION)}`};else if(c){let p=(w=(g=t==null?void 0:t.configFile)==null?void 0:g[c.value])==null?void 0:w.region;p&&(s={value:p,origin:`${F(`[profile ${c.value}]`)} in config file`})}let m=e.assumeRoleArn||n.AWS_ASSUME_ROLE_ARN;if(m){let p=e.assumeRoleArn?"command line option":"env variable";o={value:await Ke({masterCredentials:o==null?void 0:o.value,params:{DurationSeconds:e.assumeRoleSessionDuration||Number(n.AWS_ASSUME_ROLE_SESSION_DURATION)||3600,RoleArn:m},clientConfig:{region:s==null?void 0:s.value}})(),origin:`${p} ${F(`[${m}]`)}`}}return{credentialsAndOrigin:o,regionAndOrigin:s,profileAndOrigin:c}},Se=({credentialsAndOrigin:e,regionAndOrigin:n,profileAndOrigin:t})=>{let o=[];return t&&o.push(`Got profile name from ${t.origin}`),e&&o.push(`Resolved credentials from ${e.origin}`),n&&o.push(`Resolved region from ${n.origin}`),o.join(`
2
+ `)};var ee=async({argv:e,env:n})=>{let{credentialsAndOrigin:t,regionAndOrigin:o,profileAndOrigin:c}=await we({argv:{region:e.awsRegion,profile:e.awsProfile,assumeRoleArn:e.awsAssumeRoleArn,assumeRoleSessionDuration:e.awsAssumeRoleSessionDuration},env:r({},n)});if(e.verbose===!0&&console.log(Se({credentialsAndOrigin:t,regionAndOrigin:o,profileAndOrigin:c})),!(t&&o)){if(!t)throw console.error("Could not find credentials"),new Error("Could not find credentials");if(!o)throw console.error("Could not find region"),new Error("Could not find region")}return{credentialsAndOrigin:t,regionAndOrigin:o}};var N=async e=>{var w,p;let{kms:{keyAlias:n}={},region:t}=e,{credentialsAndOrigin:o,regionAndOrigin:c}=await ee({argv:{},env:r({},process.env)}),s=new Ve({credentials:o.value,region:t||c.value}),m=new Ue({KeyId:n}),g=(p=(w=(await s.send(m)).KeyMetadata)==null?void 0:w.EncryptionAlgorithms)==null?void 0:p[0];if(g===void 0)throw new Error("Could not determine encryption algorithm");return{async encrypt(a){let d=new je({KeyId:n,Plaintext:Buffer.from(a),EncryptionAlgorithm:g}),i=await s.send(d);if(!i.CiphertextBlob)throw new Error(`Something bad happened: ${JSON.stringify({encryptCommand:d})}`);return Buffer.from(i.CiphertextBlob).toString("base64")},async decrypt(a){let d=new qe({KeyId:n,CiphertextBlob:Buffer.from(a,"base64"),EncryptionAlgorithm:g}),i=await s.send(d);if(!i.Plaintext)throw new Error(`Something bad happened: ${JSON.stringify({cipherText:a,decryptCommand:d})}`);let y=Buffer.from(i.Plaintext).toString();return this.verbose&&console.info(`Decrypting key '${a}'`),y},other:()=>{}}};import ye,{stat as Ye}from"node:fs/promises";import Be from"prompts";import Je from"node:path";var ne=async e=>await ye.readFile(e,"utf-8"),Z=async(e,n)=>await ye.writeFile(e,n,"utf-8"),He=async e=>{try{return await Ye(e),!0}catch{return!1}},z=async({filePath:e,skip:n})=>{let t;return await He(e)&&n!==!0?t=await Be({type:"confirm",name:"overwrite",message:()=>`Overwrite './${Je.relative(process.cwd(),e)}' ?`}):t=void 0,t};import cn from"node:path";import{ScriptKind as tn,ScriptTarget as on,SyntaxKind as Xe,createPrinter as ze,createSourceFile as nn,createStringLiteral as Ee,transform as rn,visitEachChild as Qe,visitNode as en}from"typescript";import Ze from"node:fs";var Ae=e=>{let n=ze(),t=Ze.readFileSync(e.configFile,"utf8"),o=g=>w=>{function p(a){var d,i,y,E,A,S,_,R,h,D,I,$,K,G,q,U,j,V;if(a=Qe(a,p,g),a.kind===Xe.StringLiteral){let u=(i=(d=a==null?void 0:a.parent)==null?void 0:d.parent)==null?void 0:i.parent;if(((A=(E=(y=e.config)==null?void 0:y.aws)==null?void 0:E.kms)==null?void 0:A.keyAlias)&&((S=u==null?void 0:u.getChildAt(0))==null?void 0:S.getText())==="kms"){let v=(_=u==null?void 0:u.parent)==null?void 0:_.parent;if((v==null?void 0:v.getChildAt(0).getText())==="aws")return Ee((D=(h=(R=e.config)==null?void 0:R.aws)==null?void 0:h.kms)==null?void 0:D.keyAlias)}if((($=(I=e.config)==null?void 0:I.aws)==null?void 0:$.region)&&((G=(K=a==null?void 0:a.parent)==null?void 0:K.getChildAt(0))==null?void 0:G.getText())==="region"){let v=(U=(q=a==null?void 0:a.parent)==null?void 0:q.parent)==null?void 0:U.parent;if((v==null?void 0:v.getChildAt(0).getText())==="aws")return Ee((V=(j=e.config)==null?void 0:j.aws)==null?void 0:V.region)}}return a}return en(w,p)},c=nn("test.ts",t,on.ES2015,!0,tn.TS),s=rn(c,[o]),m=s.transformed[0],l=n.printFile(m);return s.dispose(),l};var me="dotsec.config.ts",Ce=[me],oe=".sec",te=".env",ie="alias/dotsec",sn="SecureString",O={config:{aws:{kms:{keyAlias:ie},ssm:{parameterType:sn}}}};var an={dotsec:{options:{verbose:["--verbose","Verbose output",!1],configFile:["-c, --config-file, --configFile <configFile>","Config file",me]}},init:{options:{verbose:["--verbose","Verbose output",!1],configFile:["-c, --config-file, --configFile <configFile>","Config file",me],env:["--env","Path to .env file",te],sec:["--sec","Path to .sec file",oe],yes:["--yes","Skip confirmation prompts",!1],awsKeyAlias:["--aws-key-alias <awsKeyAlias>","AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)","alias/dotsec"],awsRegion:["--aws-region <awsRegion>","AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION"]}},decrypt:{inheritsFrom:["dotsec"],options:{env:["--env <env>","Path to .env file",te],sec:["--sec <sec>","Path to .sec file",oe],yes:["--yes","Skip confirmation prompts",!1],awsKeyAlias:["--aws-key-alias <awsKeyAlias>","AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)","alias/dotsec"],awsRegion:["--aws-region <awsRegion>","AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION"]}},encrypt:{inheritsFrom:["dotsec"],options:{env:["--env <env>","Path to .env file",te],sec:["--sec <sec>","Path to .sec file",oe],yes:["--yes","Skip confirmation prompts",!1],awsKeyAlias:["--aws-key-alias <awsKeyAlias>","AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)","alias/dotsec"],awsRegion:["--aws-region <awsRegion>","AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION"]}},run:{inheritsFrom:["dotsec"],options:{env:["--env <env>","Path to .env file"],sec:["--sec [sec]","Path to .sec file"],awsKeyAlias:["--aws-key-alias <awsKeyAlias>","AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)","alias/dotsec"],awsRegion:["--aws-region <awsRegion>","AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION"]}},push:{inheritsFrom:["dotsec"],options:{toAwsSsm:["--to-aws-ssm, --toAwsSsm","Push to AWS SSM"],toAwsSecretsManager:["--to-aws-secrets-manager, --toAwsSecretsManager","Push to AWS Secrets Manager"],env:["--env [env]","Path to .env file"],sec:["--sec [sec]","Path to .sec file"],yes:["--yes","Skip confirmation prompts",!1],awsKeyAlias:["--aws-key-alias <awsKeyAlias>","AWS KMS key alias, overrides the value provided in dotsec.config (config.aws.kms.keyAlias)","alias/dotsec"],awsRegion:["--aws-region <awsRegion>","AWS region, overrides the value provided in dotsec.config (config.aws.region) and AWS_REGION"]}}},he=(e,n,t={})=>{let o=e[n];if(o)return o.inheritsFrom?o==null?void 0:o.inheritsFrom.reduce((c,s)=>{let m=he(e,s,c);return r({},m)},{options:r(r({},t.options),o.options),requiredOptions:r(r({},t.requiredOptions),o.requiredOptions)}):{options:r(r({},t.options),o.options),requiredOptions:r(r({},t.requiredOptions),o.requiredOptions)}},x=(e,n)=>{let t=he(an,n||e.name());(t==null?void 0:t.options)&&Object.values(t.options).forEach(([o,c,s])=>{e.option(o,c,s)}),(t==null?void 0:t.requiredOptions)&&Object.values(t.requiredOptions).forEach(([o,c,s])=>{e.requiredOption(o,c,s)})};var mn=async e=>{let n=e.enablePositionalOptions().passThroughOptions().command("init").action(async(t,o)=>{var a,d,i,y,E,A;let{verbose:c,configFile:s,env:m,sec:l,awskeyAlias:g,awsRegion:w,yes:p}=o.optsWithGlobals();try{let S;S=await N({verbose:c,region:w||process.env.AWS_REGION||((d=(a=O.config)==null?void 0:a.aws)==null?void 0:d.region),kms:{keyAlias:g||((A=(E=(y=(i=O)==null?void 0:i.config)==null?void 0:y.aws)==null?void 0:E.kms)==null?void 0:A.keyAlias)}});let _=await ne(m),R=await S.encrypt(_),h=await z({filePath:l,skip:p});(h===void 0||h.overwrite===!0)&&(await Z(l,R),console.log(`Wrote encrypted contents of ${C(m)} contents file to ${C(l)}`));let D=Ae({configFile:cn.resolve(__dirname,"../../src/templates/dotsec.config.ts"),config:{aws:{kms:{keyAlias:g||ie},region:w||process.env.AWS_REGION}}}),I=await z({filePath:s,skip:p});(I===void 0||I.overwrite===!0)&&(await Z(s,D),console.log(`Wrote config file to ${C(s)}`))}catch(S){o.error(S)}});return x(n),n},ve=mn;import _e from"node:fs";import wn from"cross-spawn";import{parse as Sn}from"dotenv";import fn from"node:path";import{bundleRequire as dn}from"bundle-require";import un from"joycon";import pn from"fs";import ln from"node:path";function gn(e){try{return new Function(`return ${e.trim()}`)()}catch{return{}}}var Oe=async e=>{try{return gn(await pn.promises.readFile(e,"utf8"))}catch(n){throw n instanceof Error?new Error(`Failed to parse ${ln.relative(process.cwd(),e)}: ${n.message}`):n}};var Y=async e=>{var c,s,m,l,g,w,p,a,d,i,y,E,A,S,_,R,h,D,I,$,K,G,q,U,j,V,u,v,Q,J,X,W,M,L,P,k;let n=process.cwd(),o=await new un().resolve({files:e?[e]:[...Ce,"package.json"],cwd:n,stopDir:fn.parse(n).root,packageKey:"dotsec"});if(e&&o===null)throw new Error(`Could not find config file ${e}`);if(o){if(o.endsWith(".json")){let T=await Oe(o),f;return o.endsWith("package.json")&&T.dotsec!==void 0?f=T.dotsec:f=T,{source:"json",contents:b(r(r({},O),f),{config:b(r(r({},f==null?void 0:f.config),O.config),{aws:b(r(r({},(c=f==null?void 0:f.config)==null?void 0:c.aws),(m=(s=O)==null?void 0:s.config)==null?void 0:m.aws),{kms:r(r({},(w=(g=(l=O)==null?void 0:l.config)==null?void 0:g.aws)==null?void 0:w.kms),(a=(p=f.config)==null?void 0:p.aws)==null?void 0:a.kms),ssm:r(r({},(y=(i=(d=O)==null?void 0:d.config)==null?void 0:i.aws)==null?void 0:y.ssm),(A=(E=f.config)==null?void 0:E.aws)==null?void 0:A.ssm),secretsManager:r(r({},(R=(_=(S=O)==null?void 0:S.config)==null?void 0:_.aws)==null?void 0:R.secretsManager),(D=(h=f.config)==null?void 0:h.aws)==null?void 0:D.secretsManager)})})})}}else if(o.endsWith(".ts")){let T=await dn({filepath:o}),f=T.mod.dotsec||T.mod.default||T.mod;return{source:"ts",contents:b(r(r({},O),f),{config:b(r(r({},f==null?void 0:f.config),O.config),{aws:b(r(r({},(I=f==null?void 0:f.config)==null?void 0:I.aws),(K=($=O)==null?void 0:$.config)==null?void 0:K.aws),{kms:r(r({},(U=(q=(G=O)==null?void 0:G.config)==null?void 0:q.aws)==null?void 0:U.kms),(V=(j=f.config)==null?void 0:j.aws)==null?void 0:V.kms),ssm:r(r({},(Q=(v=(u=O)==null?void 0:u.config)==null?void 0:v.aws)==null?void 0:Q.ssm),(X=(J=f.config)==null?void 0:J.aws)==null?void 0:X.ssm),secretsManager:r(r({},(L=(M=(W=O)==null?void 0:W.config)==null?void 0:M.aws)==null?void 0:L.secretsManager),(k=(P=f.config)==null?void 0:P.aws)==null?void 0:k.secretsManager)})})})}}}return{source:"defaultConfig",contents:O}};var yn=e=>{let n=e.command("run <command...>").allowUnknownOption().description("Run a command in a separate process and populate env with decrypted .env or encrypted .sec values").action(async(t,o,c)=>{var i,y,E;let{configFile:s,env:m,sec:l,keyAlias:g,region:w}=c.optsWithGlobals(),{contents:{config:p}={}}=await Y(s),a=await N({verbose:!0,kms:{keyAlias:g||((y=(i=p==null?void 0:p.aws)==null?void 0:i.kms)==null?void 0:y.keyAlias)||ie},region:w||((E=p==null?void 0:p.aws)==null?void 0:E.region)}),d;if(m)d=_e.readFileSync(m,"utf8");else if(l){let A=_e.readFileSync(l,"utf8");d=await a.decrypt(A)}else throw new Error('Must provide either "--env" or "--sec"');if(d){let A=Sn(d),[S,..._]=t;wn(S,[..._],{stdio:"inherit",shell:!1,env:b(r(r({},process.env),A),{__DOTSEC_ENV__:JSON.stringify(Object.keys(A))})}),c.help()}else throw new Error("No .env or .sec file provided")});return x(n,"run"),n},Re=yn;var An=async e=>{let n=e.enablePositionalOptions().passThroughOptions().command("decrypt").action(async(t,o)=>{var d,i,y,E,A;let{configFile:c,verbose:s,env:m,sec:l,awskeyAlias:g,awsRegion:w,yes:p}=o.optsWithGlobals(),{contents:a}=await Y(c);try{let S;S=await N({verbose:s,region:w||process.env.AWS_REGION||((i=(d=a.config)==null?void 0:d.aws)==null?void 0:i.region),kms:{keyAlias:g||((A=(E=(y=a==null?void 0:a.config)==null?void 0:y.aws)==null?void 0:E.kms)==null?void 0:A.keyAlias)}});let _=await ne(l),R=await S.decrypt(_),h=await z({filePath:m,skip:p});(h===void 0||h.overwrite===!0)&&(await Z(m,R),console.log(`Wrote plaintext contents of ${C(l)} file to ${C(m)}`))}catch(S){o.error(S)}});return x(n),n},Pe=An;var En=async e=>{let n=e.enablePositionalOptions().passThroughOptions().command("encrypt").action(async(t,o)=>{var d,i,y,E,A;let{verbose:c,configFile:s,env:m,sec:l,awskeyAlias:g,awsRegion:w,yes:p}=o.optsWithGlobals(),{contents:a}=await Y(s);try{let S;S=await N({verbose:c,region:w||process.env.AWS_REGION||((i=(d=a.config)==null?void 0:d.aws)==null?void 0:i.region),kms:{keyAlias:g||((A=(E=(y=a==null?void 0:a.config)==null?void 0:y.aws)==null?void 0:E.kms)==null?void 0:A.keyAlias)}});let _=await ne(m),R=await S.encrypt(_),h=await z({filePath:l,skip:p});(h===void 0||h.overwrite===!0)&&(await Z(l,R),console.log(`Wrote encrypted contents of ${C(m)} file to ${C(l)}`))}catch(S){o.error(S)}});return x(n),n},be=En;var se=e=>typeof e=="boolean";import Te from"node:fs";import{parse as Fn}from"dotenv";import Cn from"prompts";var pe=async({predicate:e,skip:n,message:t})=>n===!0?{confirm:!0}:(e?await e():!0)?await Cn({type:"confirm",name:"confirm",message:()=>t}):{confirm:!0};import{PutParameterCommand as hn,SSMClient as vn}from"@aws-sdk/client-ssm";var Fe=async e=>{let{region:n}=e||{},{credentialsAndOrigin:t,regionAndOrigin:o}=await ee({argv:{},env:r({},process.env)}),c=new vn({credentials:t.value,region:n||o.value});return{async put(s){for(let m of s){let l=new hn(b(r({},m),{Overwrite:!0}));await c.send(l)}}}};import{CreateSecretCommand as On,DescribeSecretCommand as _n,UpdateSecretCommand as Rn,SecretsManagerClient as Pn,ResourceNotFoundException as bn}from"@aws-sdk/client-secrets-manager";var ke=async e=>{let{region:n}=e||{},{credentialsAndOrigin:t,regionAndOrigin:o}=await ee({argv:{},env:r({},process.env)}),c=new Pn({credentials:t.value,region:n||o.value});return{async push(s){let m=[],l=[];for(let g of s){let w=new _n({SecretId:g.Name});try{let p=await c.send(w);l.push(new Rn({SecretId:p.ARN,SecretString:g.SecretString}))}catch(p){p instanceof bn&&m.push(new On({Name:g.Name,SecretString:g.SecretString}))}}return{createSecretCommands:m,updateSecretCommands:l,push:async()=>{for(let g of m)await c.send(g);for(let g of l)await c.send(g)}}}}};var kn=async e=>{let n=e.enablePositionalOptions().passThroughOptions().command("push").action(async(t,o)=>{var S,_,R,h,D,I,$,K,G,q,U,j,V;let{configFile:c,verbose:s,env:m,sec:l,awskeyAlias:g,awsRegion:w,yes:p,toAwsSsm:a,toAwsSecretsManager:d}=o.optsWithGlobals();if(!(a||d))throw new Error("You must specify at least one of --to-aws-ssm or --to-aws-secrets-manager");let{contents:i}=await Y(c),y,E;if(y=await N({verbose:s,region:w||process.env.AWS_REGION||((_=(S=i.config)==null?void 0:S.aws)==null?void 0:_.region),kms:{keyAlias:g||((D=(h=(R=i==null?void 0:i.config)==null?void 0:R.aws)==null?void 0:h.kms)==null?void 0:D.keyAlias)}}),m){let u=se(m)?te:m;E=Te.readFileSync(u,"utf8")}else if(l){let u=se(l)?oe:l,v=Te.readFileSync(u,"utf8");E=await y.decrypt(v)}else throw new Error('Must provide either "--env" or "--sec"');let A=Fn(E);try{if(a){let u=($=(I=i==null?void 0:i.config)==null?void 0:I.aws)==null?void 0:$.ssm,v=(u==null?void 0:u.parameterType)||"SecureString",Q=(u==null?void 0:u.pathPrefix)||"",J=Object.entries(A).reduce((W,[M,L])=>{var P,k,T,f;if((P=i.variables)==null?void 0:P[M]){let H=(k=i.variables)==null?void 0:k[M];if(H){let re=`${Q}${M}`;if((f=(T=H.push)==null?void 0:T.aws)==null?void 0:f.ssm){let ae=se(H.push.aws.ssm)?{Name:re,Value:L,Type:v}:b(r({Name:re,Type:v},H.push.aws.ssm),{Value:L});W.push(ae)}}}return W},[]),{confirm:X}=await pe({message:`Are you sure you want to push the following variables to AWS SSM Parameter Store?
3
+ ${J.map(({Name:W})=>`- ${C(W||"[no name]")}`).join(`
4
+ `)}`,skip:p});X===!0&&(console.log("pushing to AWS SSM Parameter Store"),await(await Fe({region:w||((G=(K=i==null?void 0:i.config)==null?void 0:K.aws)==null?void 0:G.region)})).put(J))}if(d){let u=(U=(q=i==null?void 0:i.config)==null?void 0:q.aws)==null?void 0:U.secretsManager,v=(u==null?void 0:u.pathPrefix)||"",Q=await ke({region:w||process.env.AWS_REGION||((V=(j=i.config)==null?void 0:j.aws)==null?void 0:V.region)}),J=Object.entries(A).reduce((P,[k,T])=>{var f,H,re,ae;if((f=i.variables)==null?void 0:f[k]){let ce=(H=i.variables)==null?void 0:H[k];if(ce){let ge=`${v}${k}`;if((ae=(re=ce.push)==null?void 0:re.aws)==null?void 0:ae.ssm){let Ie=se(ce.push.aws.ssm)?{Name:ge,SecretString:T}:b(r({Name:ge},ce.push.aws.ssm),{SecretString:T});P.push(Ie)}}}return P},[]),{push:X,updateSecretCommands:W,createSecretCommands:M}=await Q.push(J),L=[];if(W.length>0){let{confirm:P}=await pe({message:`Are you sure you want to update the following variables to AWS SSM Secrets Manager?
5
+ ${W.map(({input:{SecretId:k}})=>`- ${C(k||"[no name]")}`).join(`
6
+ `)}`,skip:p});L.push(P)}if(M.length>0){let{confirm:P}=await pe({message:`Are you sure you want to create the following variables to AWS SSM Secrets Manager?
7
+ ${M.map(({input:{Name:k}})=>`- ${C(k||"[no name]")}`).join(`
8
+ `)}`,skip:p});L.push(P)}L.find(P=>P===!1)||(console.log("pushing to AWS Secrets Manager"),await X())}}catch(u){o.error(u)}});return x(n),n},xe=kn;var B=new Tn;B.name("dotsec").description(".env, but secure").version("1.0.0").enablePositionalOptions().action((e,n)=>{n.help()});x(B);(async()=>{await ve(B),await Re(B),await Pe(B),await be(B),await xe(B),B.parse()})();
9
+ //# sourceMappingURL=index.mjs.map