@dotenvx/dotenvx 2.34.1 → 2.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -1
- package/README.md +8 -0
- package/package.json +5 -4
- package/src/cli/actions/armor/down.js +2 -2
- package/src/cli/actions/armor/pull.js +2 -2
- package/src/cli/actions/armor/push.js +2 -2
- package/src/cli/actions/armor/up.js +2 -2
- package/src/cli/actions/decrypt.js +10 -2
- package/src/cli/actions/encrypt.js +24 -10
- package/src/cli/actions/run.js +10 -2
- package/src/cli/dotenvx.js +1 -0
- package/src/lib/helpers/errors.js +8 -0
- package/src/lib/helpers/fsx.js +30 -2
- package/src/lib/helpers/installProtectFilter.js +6 -5
- package/src/lib/helpers/parseWithDecryptor.js +17 -7
- package/src/lib/helpers/protectSettings.js +2 -1
- package/src/lib/helpers/removeLegacyProtectFilter.js +2 -1
- package/src/lib/helpers/uninstallPrecommitHook.js +2 -1
- package/src/lib/main.js +10 -2
- package/src/lib/providers/index.js +16 -3
- package/src/lib/resolvers/envs.js +26 -2
- package/src/lib/services/init.js +8 -1
- package/src/lib/transforms/decrypt.js +12 -2
- package/src/lib/transforms/encrypt.js +23 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,7 +2,23 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
|
|
4
4
|
|
|
5
|
-
[Unreleased](https://github.com/dotenvx/dotenvx/compare/v2.
|
|
5
|
+
[Unreleased](https://github.com/dotenvx/dotenvx/compare/v2.35.0...main)
|
|
6
|
+
|
|
7
|
+
## [2.35.0](https://github.com/dotenvx/dotenvx/compare/v2.34.2...v2.35.0) (2026-10-13)
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
* Add `encrypt --with` to bring public key. Useful for Dotenvx Armor's new remote enclaved private keys. Encrypt locally but decrypt only on the remote software enclave. Private keys never leave. ([#1022](https://github.com/dotenvx/dotenvx/pull/1022))
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
|
|
15
|
+
* Use atomic file writes in `protect` ([#1019](https://github.com/dotenvx/dotenvx/pull/1019))
|
|
16
|
+
|
|
17
|
+
## [2.34.2](https://github.com/dotenvx/dotenvx/compare/v2.34.1...v2.34.2) (2026-10-09)
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
|
|
21
|
+
* Patch: fix atomic edge case of writing .env and .env.keys file ([#1014](https://github.com/dotenvx/dotenvx/pull/1014))
|
|
6
22
|
|
|
7
23
|
## [2.34.1](https://github.com/dotenvx/dotenvx/compare/v2.34.0...v2.34.1) (2026-10-08)
|
|
8
24
|
|
package/README.md
CHANGED
|
@@ -117,6 +117,14 @@ $ dotenvx encrypt
|
|
|
117
117
|
◈ encrypted (.env)
|
|
118
118
|
```
|
|
119
119
|
|
|
120
|
+
To encrypt a fresh plaintext file with a public key created elsewhere:
|
|
121
|
+
|
|
122
|
+
```sh
|
|
123
|
+
dotenvx encrypt -f .env.production --with <public-key>
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
This writes the supplied public key into the file and encrypts its values without creating or storing a private key. If every existing `DOTENV_PUBLIC_KEY*` entry matches the supplied key, it reuses that key, preserves existing ciphertext, and encrypts new plaintext values. A different public key, or an `encrypted:` value without a matching declared public key, fails with `ALREADY_ENCRYPTED` and leaves the file unchanged.
|
|
127
|
+
|
|
120
128
|
*Commit* your encrypted `.env` files with your code. It's safe. Now you can securely share secrets through git.
|
|
121
129
|
|
|
122
130
|
```sh
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "2.
|
|
2
|
+
"version": "2.35.0",
|
|
3
3
|
"name": "@dotenvx/dotenvx",
|
|
4
4
|
"description": "a secure dotenv–from the creator of `dotenv`",
|
|
5
5
|
"author": "@motdotla",
|
|
@@ -53,10 +53,11 @@
|
|
|
53
53
|
},
|
|
54
54
|
"funding": "https://dotenvx.com",
|
|
55
55
|
"dependencies": {
|
|
56
|
-
"@dotenvx/primitives": "^3.
|
|
57
|
-
"@dotenvx/providers": "^0.3.
|
|
58
|
-
"@dotenvx/tooling": "^1.0.
|
|
56
|
+
"@dotenvx/primitives": "^3.3.0",
|
|
57
|
+
"@dotenvx/providers": "^0.3.5",
|
|
58
|
+
"@dotenvx/tooling": "^1.0.5",
|
|
59
59
|
"undici": "^6.28.1",
|
|
60
|
+
"write-file-atomic": "^5.0.1",
|
|
60
61
|
"yocto-spinner": "^1.2.1"
|
|
61
62
|
},
|
|
62
63
|
"devDependencies": {
|
|
@@ -24,9 +24,9 @@ async function down () {
|
|
|
24
24
|
|
|
25
25
|
if (spinner) spinner.stop()
|
|
26
26
|
if (changed) {
|
|
27
|
-
logger.success(`◇ dearmored
|
|
27
|
+
logger.success(`◇ dearmored ${options.envFile || '.env'} (${keyDisplay}) to .env.keys`)
|
|
28
28
|
} else {
|
|
29
|
-
logger.info(`○ no change (${keyDisplay})`)
|
|
29
|
+
logger.info(`○ no change to ${options.envFile || '.env'} (${keyDisplay})`)
|
|
30
30
|
}
|
|
31
31
|
} catch (error) {
|
|
32
32
|
if (spinner) spinner.stop()
|
|
@@ -24,9 +24,9 @@ async function pull () {
|
|
|
24
24
|
|
|
25
25
|
if (spinner) spinner.stop()
|
|
26
26
|
if (changed) {
|
|
27
|
-
logger.success(`◇ pulled
|
|
27
|
+
logger.success(`◇ pulled ${options.envFile || '.env'} (${keyDisplay}) to .env.keys`)
|
|
28
28
|
} else {
|
|
29
|
-
logger.info(`○ no change (${keyDisplay})`)
|
|
29
|
+
logger.info(`○ no change to ${options.envFile || '.env'} (${keyDisplay})`)
|
|
30
30
|
}
|
|
31
31
|
} catch (error) {
|
|
32
32
|
if (spinner) spinner.stop()
|
|
@@ -24,9 +24,9 @@ async function push () {
|
|
|
24
24
|
|
|
25
25
|
if (spinner) spinner.stop()
|
|
26
26
|
if (changed) {
|
|
27
|
-
logger.success(`⛨ pushed (${keyDisplay})`)
|
|
27
|
+
logger.success(`⛨ pushed ${options.envFile || '.env'} (${keyDisplay}) to Armor`)
|
|
28
28
|
} else {
|
|
29
|
-
logger.info(`○ no change (${keyDisplay})`)
|
|
29
|
+
logger.info(`○ no change to ${options.envFile || '.env'} (${keyDisplay})`)
|
|
30
30
|
}
|
|
31
31
|
} catch (error) {
|
|
32
32
|
if (spinner) spinner.stop()
|
|
@@ -24,9 +24,9 @@ async function up () {
|
|
|
24
24
|
|
|
25
25
|
if (spinner) spinner.stop()
|
|
26
26
|
if (changed) {
|
|
27
|
-
logger.success(`⛨ armored (${keyDisplay})`)
|
|
27
|
+
logger.success(`⛨ armored ${options.envFile || '.env'} (${keyDisplay})`)
|
|
28
28
|
} else {
|
|
29
|
-
logger.info(`○ no change (${keyDisplay})`)
|
|
29
|
+
logger.info(`○ no change to ${options.envFile || '.env'} (${keyDisplay})`)
|
|
30
30
|
}
|
|
31
31
|
} catch (error) {
|
|
32
32
|
if (spinner) spinner.stop()
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const { publickeys, injectsummary } = require('@dotenvx/primitives')
|
|
1
2
|
const fsx = require('./../../lib/helpers/fsx')
|
|
2
3
|
const { logger } = require('./../../shared/logger')
|
|
3
4
|
|
|
@@ -98,10 +99,17 @@ async function decrypt () {
|
|
|
98
99
|
}
|
|
99
100
|
|
|
100
101
|
if (spinner) spinner.stop()
|
|
102
|
+
const summaryRows = new Map(processedEnvs.map(row => [row.envFilepath, {
|
|
103
|
+
filepath: row.envFilepath,
|
|
104
|
+
publicKeys: publickeys(row.envSrc || ''),
|
|
105
|
+
keySources: row.keySources
|
|
106
|
+
}]))
|
|
101
107
|
if (changedFilepaths.length > 0) {
|
|
102
|
-
|
|
108
|
+
const summary = injectsummary.sources(changedFilepaths.map(filepath => summaryRows.get(filepath) || filepath))
|
|
109
|
+
logger.success(`◇ decrypted ${summary.files.join(',')}${summary.suffix}`)
|
|
103
110
|
} else if (unchangedFilepaths.length > 0) {
|
|
104
|
-
|
|
111
|
+
const summary = injectsummary.sources(unchangedFilepaths.map(filepath => summaryRows.get(filepath) || filepath))
|
|
112
|
+
logger.info(`○ no change to ${summary.files.join(',')}${summary.suffix}`)
|
|
105
113
|
} else {
|
|
106
114
|
// do nothing - scenario when no .env files found
|
|
107
115
|
}
|
|
@@ -5,6 +5,8 @@ const encryptTransform = require('./../../lib/transforms/encrypt')
|
|
|
5
5
|
|
|
6
6
|
const catchAndLog = require('../../lib/helpers/catchAndLog')
|
|
7
7
|
const createSpinner = require('../../lib/helpers/createSpinner')
|
|
8
|
+
const keypair = require('../../lib/resolvers/keypair')
|
|
9
|
+
const { publickeys, injectsummary } = require('@dotenvx/primitives')
|
|
8
10
|
|
|
9
11
|
async function encryptAction () {
|
|
10
12
|
const options = this.opts()
|
|
@@ -28,7 +30,7 @@ async function encryptAction () {
|
|
|
28
30
|
|
|
29
31
|
// stdout - should not have a try so that exit codes can surface to stdout
|
|
30
32
|
if (options.stdout) {
|
|
31
|
-
const { processedEnvs } = await encryptTransform({ profile: options.profile, envs, ik, ek, fk, noArmor, token: options.token, noCreate, noNative, no1Password, noBitwarden })
|
|
33
|
+
const { processedEnvs } = await encryptTransform({ with: options.with, profile: options.profile, envs, ik, ek, fk, noArmor, token: options.token, noCreate, noNative, no1Password, noBitwarden })
|
|
32
34
|
|
|
33
35
|
if (spinner) spinner.stop()
|
|
34
36
|
for (const processedEnv of processedEnvs) {
|
|
@@ -45,9 +47,9 @@ async function encryptAction () {
|
|
|
45
47
|
}
|
|
46
48
|
|
|
47
49
|
try {
|
|
48
|
-
const { keysSrc, processedEnvs, changedFilepaths, unchangedFilepaths } = await encryptTransform({ profile: options.profile, envs, ik, ek, fk, noArmor, token: options.token, noCreate, noNative, no1Password, noBitwarden })
|
|
50
|
+
const { keysSrc, processedEnvs, changedFilepaths, unchangedFilepaths } = await encryptTransform({ with: options.with, profile: options.profile, envs, ik, ek, fk, noArmor, token: options.token, noCreate, noNative, no1Password, noBitwarden })
|
|
49
51
|
|
|
50
|
-
if (keysSrc) {
|
|
52
|
+
if (keysSrc && options.with === undefined) {
|
|
51
53
|
await fsx.writeKeyFile(fk, keysSrc)
|
|
52
54
|
}
|
|
53
55
|
|
|
@@ -65,15 +67,27 @@ async function encryptAction () {
|
|
|
65
67
|
}
|
|
66
68
|
}
|
|
67
69
|
|
|
70
|
+
// Existing public keys can encrypt without private-key access. Metadata
|
|
71
|
+
// lookup must never turn successful encryption into a failure.
|
|
72
|
+
for (const row of processedEnvs) {
|
|
73
|
+
if (options.with !== undefined || options.quiet || row.error || row.keySources || !publickeys(row.envSrc || '').length) continue
|
|
74
|
+
try {
|
|
75
|
+
const resolved = await keypair({ ...options, envFile: [row.filepath], envKeysFile: fk, noArmor, noNative, no1Password, noBitwarden, includeProvider: true })
|
|
76
|
+
row.keySources = { [publickeys(row.envSrc)[0]]: resolved.provider }
|
|
77
|
+
} catch {}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const summaryRows = new Map(processedEnvs.map(row => [row.envFilepath, {
|
|
81
|
+
filepath: row.envFilepath,
|
|
82
|
+
publicKeys: publickeys(row.envSrc || ''),
|
|
83
|
+
keySources: row.keySources
|
|
84
|
+
}]))
|
|
68
85
|
if (changedFilepaths.length > 0) {
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
// if (remoteKeyAddedEnv) {
|
|
72
|
-
// msg += ' · armored ⛨'
|
|
73
|
-
// }
|
|
74
|
-
logger.success(msg)
|
|
86
|
+
const summary = injectsummary.sources(changedFilepaths.map(filepath => summaryRows.get(filepath) || filepath))
|
|
87
|
+
logger.success(`◈ encrypted ${summary.files.join(',')}${summary.suffix}`)
|
|
75
88
|
} else if (unchangedFilepaths.length > 0) {
|
|
76
|
-
|
|
89
|
+
const summary = injectsummary.sources(unchangedFilepaths.map(filepath => summaryRows.get(filepath) || filepath))
|
|
90
|
+
logger.info(`○ no change to ${summary.files.join(',')}${summary.suffix}`)
|
|
77
91
|
} else {
|
|
78
92
|
// do nothing - scenario when no .env files found
|
|
79
93
|
}
|
package/src/cli/actions/run.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const path = require('path')
|
|
2
|
-
const { injectsummary } = require('@dotenvx/primitives')
|
|
2
|
+
const { injectsummary, publickeys } = require('@dotenvx/primitives')
|
|
3
3
|
const { logger } = require('./../../shared/logger')
|
|
4
4
|
|
|
5
5
|
const executeCommand = require('./../../lib/helpers/executeCommand')
|
|
@@ -180,7 +180,15 @@ async function run () {
|
|
|
180
180
|
const injectedKeys = uniqueInjectedKeys(processedEnvs)
|
|
181
181
|
|
|
182
182
|
if (spinner) spinner.stop()
|
|
183
|
-
|
|
183
|
+
const summaryRows = readableFilepaths.map(filepath => {
|
|
184
|
+
const row = processedEnvs.find(row => row.filepath === filepath)
|
|
185
|
+
return {
|
|
186
|
+
filepath,
|
|
187
|
+
publicKeys: row ? publickeys(row.src || '') : [],
|
|
188
|
+
keySources: row && row.keySources
|
|
189
|
+
}
|
|
190
|
+
})
|
|
191
|
+
logger.success(injectsummary(injectedKeys.size, summaryRows))
|
|
184
192
|
} catch (error) {
|
|
185
193
|
if (spinner) spinner.stop()
|
|
186
194
|
if (error.code === 'PROMPT_CANCELLED') {
|
package/src/cli/dotenvx.js
CHANGED
|
@@ -157,6 +157,7 @@ program.command('del')
|
|
|
157
157
|
function configureEncryptCommand (command) {
|
|
158
158
|
return command
|
|
159
159
|
.description('encrypt .env file(s)')
|
|
160
|
+
.option('--with <public-key>', 'encrypt with this public key; accepts a fresh file or matching existing public key')
|
|
160
161
|
.option('--profile <name>', 'select an Envfile profile')
|
|
161
162
|
.option('-f, --env-file <path>', 'path(s) to your env file(s)', collectEnvs('envFile'), [])
|
|
162
163
|
.option('-fk, --env-keys-file <path>', 'path to your .env.keys file (default: same path as your env file)')
|
|
@@ -159,6 +159,14 @@ class Errors {
|
|
|
159
159
|
return e
|
|
160
160
|
}
|
|
161
161
|
|
|
162
|
+
alreadyEncrypted () {
|
|
163
|
+
const e = new Error(`[ALREADY_ENCRYPTED] ${this.envFilepath || '.env'} is already configured for encryption`)
|
|
164
|
+
e.code = 'ALREADY_ENCRYPTED'
|
|
165
|
+
e.help = 'fix: use a fresh .env file'
|
|
166
|
+
e.messageWithHelp = `${e.message}. ${e.help}`
|
|
167
|
+
return e
|
|
168
|
+
}
|
|
169
|
+
|
|
162
170
|
invalidPublicKey () {
|
|
163
171
|
const code = 'INVALID_PUBLIC_KEY'
|
|
164
172
|
const message = `[${code}] could not encrypt using public key '${this.publicKeyName}=${truncate(this.publicKey)}'`
|
package/src/lib/helpers/fsx.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
const fs = require('fs')
|
|
2
|
+
const path = require('path')
|
|
3
|
+
const writeFileAtomic = require('write-file-atomic')
|
|
2
4
|
const Errors = require('./errors')
|
|
3
5
|
|
|
4
6
|
const ENCODING = 'utf8'
|
|
@@ -22,7 +24,8 @@ function readFileXSync (filepath, encoding = null) {
|
|
|
22
24
|
|
|
23
25
|
function writeFileXSync (filepath, str, options = ENCODING) {
|
|
24
26
|
try {
|
|
25
|
-
return
|
|
27
|
+
if (options && options.followSymlinks === false) return writeFileNoFollowSync(filepath, str, options)
|
|
28
|
+
return writeFileAtomic.sync(filepath, str, typeof options === 'string' ? options : { ...options })
|
|
26
29
|
} catch (error) {
|
|
27
30
|
if (error.code === 'EACCES' || error.code === 'EPERM') {
|
|
28
31
|
throw new Errors({ filepath }).fileNotWritable()
|
|
@@ -32,9 +35,34 @@ function writeFileXSync (filepath, str, options = ENCODING) {
|
|
|
32
35
|
}
|
|
33
36
|
}
|
|
34
37
|
|
|
38
|
+
function writeFileNoFollowSync (filepath, str, options) {
|
|
39
|
+
const regularFile = () => {
|
|
40
|
+
const stat = fs.lstatSync(filepath, { throwIfNoEntry: false })
|
|
41
|
+
if (stat && !stat.isFile()) throw new Error(`Cannot replace file: expected a regular file (${filepath})`)
|
|
42
|
+
return stat
|
|
43
|
+
}
|
|
44
|
+
const stat = regularFile()
|
|
45
|
+
const { followSymlinks, ...atomicOptions } = options
|
|
46
|
+
if (stat) {
|
|
47
|
+
if (atomicOptions.mode == null) atomicOptions.mode = stat.mode
|
|
48
|
+
if (atomicOptions.chown == null && process.getuid) atomicOptions.chown = { uid: stat.uid, gid: stat.gid }
|
|
49
|
+
}
|
|
50
|
+
// write-file-atomic resolves symlinks. Stage in a private sibling directory so
|
|
51
|
+
// it never resolves the destination, then rename over the directory entry.
|
|
52
|
+
const staging = fs.mkdtempSync(path.join(path.dirname(filepath), '.dotenvx-write-'))
|
|
53
|
+
try {
|
|
54
|
+
const stagedFile = path.join(staging, 'content')
|
|
55
|
+
writeFileAtomic.sync(stagedFile, str, atomicOptions)
|
|
56
|
+
regularFile()
|
|
57
|
+
fs.renameSync(stagedFile, filepath) // rename never follows the destination symlink
|
|
58
|
+
} finally {
|
|
59
|
+
fs.rmSync(staging, { recursive: true, force: true })
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
35
63
|
async function writeFileX (filepath, str, options = ENCODING) {
|
|
36
64
|
try {
|
|
37
|
-
return await
|
|
65
|
+
return await writeFileAtomic(filepath, str, typeof options === 'string' ? options : { ...options })
|
|
38
66
|
} catch (error) {
|
|
39
67
|
if (error.code === 'EACCES' || error.code === 'EPERM') {
|
|
40
68
|
throw new Errors({ filepath }).fileNotWritable()
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const fs = require('fs')
|
|
2
|
+
const fsx = require('./fsx')
|
|
2
3
|
const path = require('path')
|
|
3
4
|
const os = require('os')
|
|
4
5
|
const { execFileSync } = require('child_process')
|
|
@@ -22,7 +23,7 @@ function installProtectFilter () {
|
|
|
22
23
|
attributesPath = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'git/attributes')
|
|
23
24
|
git('config', '--global', 'core.attributesFile', attributesPath)
|
|
24
25
|
}
|
|
25
|
-
|
|
26
|
+
const current = fs.existsSync(attributesPath) ? fs.readFileSync(attributesPath, 'utf8') : ''
|
|
26
27
|
// Use the installed executable, including standalone builds. Never download a
|
|
27
28
|
// replacement via npx while Git is handling secret input.
|
|
28
29
|
const executable = process.pkg
|
|
@@ -43,13 +44,13 @@ function installProtectFilter () {
|
|
|
43
44
|
const value = line.replace(/\r?\n$/, '')
|
|
44
45
|
return ATTRIBUTES.includes(value + '.protect') ? line.replace('filter=dotenvx', 'filter=dotenvx.protect') : line
|
|
45
46
|
}).join('')
|
|
46
|
-
|
|
47
|
-
current = migrated
|
|
48
|
-
const existing = new Set(current.split(/\r?\n/))
|
|
47
|
+
const existing = new Set(migrated.split(/\r?\n/))
|
|
49
48
|
const missing = ATTRIBUTES.filter(attribute => !existing.has(attribute))
|
|
49
|
+
let next = migrated
|
|
50
50
|
if (missing.length > 0) {
|
|
51
|
-
|
|
51
|
+
next = `${next}${next && !next.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`
|
|
52
52
|
}
|
|
53
|
+
if (next !== current) fsx.writeFileXSync(attributesPath, next)
|
|
53
54
|
return attributesPath
|
|
54
55
|
}
|
|
55
56
|
|
|
@@ -1,21 +1,31 @@
|
|
|
1
|
-
const { parse, parseSync, parsearrays, publickeys } = require('@dotenvx/primitives')
|
|
1
|
+
const { parse, parseSync, parsearrays, publickeys, keyringSync } = require('@dotenvx/primitives')
|
|
2
2
|
const { file } = require('@dotenvx/providers')
|
|
3
3
|
const SERVER_SIDE_DECRYPTION_REQUIRED = 'SERVER_SIDE_DECRYPTION_REQUIRED'
|
|
4
4
|
|
|
5
5
|
function withFileKeys (src, options, sync = false) {
|
|
6
6
|
const keys = file({ fk: options.fk })
|
|
7
7
|
const fallback = options.provider
|
|
8
|
+
const keySources = {}
|
|
9
|
+
const environment = keyringSync({ processEnv: options.processEnv || process.env, fk: [], provider: null })
|
|
10
|
+
for (const key of publickeys(src)) {
|
|
11
|
+
if (environment[key]) keySources[key] = 'environment'
|
|
12
|
+
}
|
|
13
|
+
function found (publicKey, ring, source) {
|
|
14
|
+
if (ring[publicKey]) keySources[publicKey] = source || 'custom'
|
|
15
|
+
return ring
|
|
16
|
+
}
|
|
8
17
|
const provider = sync
|
|
9
18
|
? publicKey => {
|
|
10
19
|
const ring = keys.getSync(publicKey)
|
|
11
|
-
return ring[publicKey] ? ring : (fallback ? fallback(publicKey) : {})
|
|
20
|
+
return ring[publicKey] ? found(publicKey, ring, '.env.keys') : found(publicKey, fallback ? fallback(publicKey) : {}, fallback && fallback.sourceFor && fallback.sourceFor(publicKey))
|
|
12
21
|
}
|
|
13
22
|
: async publicKey => {
|
|
14
23
|
const ring = await keys.get(publicKey)
|
|
15
|
-
return ring[publicKey] ? ring : (fallback ? fallback(publicKey) : {})
|
|
24
|
+
return ring[publicKey] ? found(publicKey, ring, '.env.keys') : found(publicKey, fallback ? await fallback(publicKey) : {}, fallback && fallback.sourceFor && fallback.sourceFor(publicKey))
|
|
16
25
|
}
|
|
17
26
|
return {
|
|
18
27
|
...options,
|
|
28
|
+
keySources,
|
|
19
29
|
provider,
|
|
20
30
|
// Provider lookup requires a public key. Keep legacy key discovery for
|
|
21
31
|
// encrypted files that do not declare one, and for error recovery.
|
|
@@ -61,7 +71,7 @@ parseWithDecryptor.arrays = async function parsearraysWithDecryptor (src, option
|
|
|
61
71
|
async function parseWith (src, options, parser) {
|
|
62
72
|
options = withFileKeys(src, options)
|
|
63
73
|
try {
|
|
64
|
-
return await parser(src, options)
|
|
74
|
+
return { ...await parser(src, options), keySources: options.keySources }
|
|
65
75
|
} catch (error) {
|
|
66
76
|
if (error.code !== SERVER_SIDE_DECRYPTION_REQUIRED || typeof options.decryptor !== 'function') {
|
|
67
77
|
if (typeof options.provider !== 'function') throw error
|
|
@@ -72,7 +82,7 @@ async function parseWith (src, options, parser) {
|
|
|
72
82
|
|
|
73
83
|
try {
|
|
74
84
|
const result = await options.decryptor(src, decryptOptions(error))
|
|
75
|
-
return await parser(result.src, parseOptionsWithoutProvider(options))
|
|
85
|
+
return { ...await parser(result.src, parseOptionsWithoutProvider(options)), keySources: { [decryptOptions(error).publicKey]: 'armor' } }
|
|
76
86
|
} catch (decryptorError) {
|
|
77
87
|
const result = await parser(src, parseOptionsWithoutProvider(options))
|
|
78
88
|
return failedKeyAccessFallback(result, decryptorError)
|
|
@@ -83,7 +93,7 @@ async function parseWith (src, options, parser) {
|
|
|
83
93
|
parseWithDecryptor.sync = function parseWithDecryptorSync (src, options = {}) {
|
|
84
94
|
options = withFileKeys(src, options, true)
|
|
85
95
|
try {
|
|
86
|
-
return parseSync(src, options)
|
|
96
|
+
return { ...parseSync(src, options), keySources: options.keySources }
|
|
87
97
|
} catch (error) {
|
|
88
98
|
if (error.code !== SERVER_SIDE_DECRYPTION_REQUIRED || typeof options.decryptor !== 'function') {
|
|
89
99
|
if (typeof options.provider !== 'function') throw error
|
|
@@ -94,7 +104,7 @@ parseWithDecryptor.sync = function parseWithDecryptorSync (src, options = {}) {
|
|
|
94
104
|
|
|
95
105
|
try {
|
|
96
106
|
const result = options.decryptor(src, decryptOptions(error))
|
|
97
|
-
return parseSync(result.src, parseOptionsWithoutProvider(options))
|
|
107
|
+
return { ...parseSync(result.src, parseOptionsWithoutProvider(options)), keySources: { [decryptOptions(error).publicKey]: 'armor' } }
|
|
98
108
|
} catch (decryptorError) {
|
|
99
109
|
const result = parseSync(src, parseOptionsWithoutProvider(options))
|
|
100
110
|
return failedKeyAccessFallback(result, decryptorError)
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const fs = require('fs')
|
|
2
|
+
const fsx = require('./fsx')
|
|
2
3
|
const path = require('path')
|
|
3
4
|
const os = require('os')
|
|
4
5
|
const { execFileSync } = require('child_process')
|
|
@@ -20,7 +21,7 @@ function read (filename) {
|
|
|
20
21
|
function removeLines (filename, lines) {
|
|
21
22
|
const current = read(filename)
|
|
22
23
|
const updated = current.split(/(?<=\n)/).filter(line => !lines.includes(line.replace(/\r?\n$/, ''))).join('')
|
|
23
|
-
if (updated !== current)
|
|
24
|
+
if (updated !== current) fsx.writeFileXSync(filename, updated)
|
|
24
25
|
}
|
|
25
26
|
function state () {
|
|
26
27
|
const attributes = read(file('core.attributesFile', 'attributes'))
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const path = require('path')
|
|
2
2
|
const fs = require('fs')
|
|
3
|
+
const fsx = require('./fsx')
|
|
3
4
|
const patterns = require('./precommitEnvPatterns')
|
|
4
5
|
const { execFileSync } = require('child_process')
|
|
5
6
|
|
|
@@ -36,7 +37,7 @@ function removeLegacyProtectFilter (directory = process.cwd()) {
|
|
|
36
37
|
const oldRules = patterns.map(pattern => `${pattern.includes('/') ? '**/' : ''}${pattern} filter=dotenvx`)
|
|
37
38
|
const source = fs.readFileSync(attributesPath, 'utf8')
|
|
38
39
|
const updated = source.split(/(?<=\n)/).map(line => oldRules.includes(line.replace(/\r?\n$/, '')) ? line.replace('filter=dotenvx', 'filter=dotenvx.protect') : line).join('')
|
|
39
|
-
if (updated !== source)
|
|
40
|
+
if (updated !== source) fsx.writeFileXSync(attributesPath, updated)
|
|
40
41
|
}
|
|
41
42
|
|
|
42
43
|
module.exports = removeLegacyProtectFilter
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const fs = require('fs')
|
|
2
|
+
const fsx = require('./fsx')
|
|
2
3
|
const path = require('path')
|
|
3
4
|
const { execFileSync } = require('child_process')
|
|
4
5
|
const { HOOK_SCRIPT } = require('./installPrecommitHook')
|
|
@@ -59,7 +60,7 @@ function uninstallPrecommitHook (directory = process.cwd()) {
|
|
|
59
60
|
return /dotenvx\s+(?:ext\s+)?precommit/.test(source) ? manual() : { removed: false }
|
|
60
61
|
}
|
|
61
62
|
if (next.trim() === '') fs.unlinkSync(hookPath)
|
|
62
|
-
else
|
|
63
|
+
else fsx.writeFileXSync(hookPath, next, 'utf8')
|
|
63
64
|
return { removed: true, warning: /dotenvx\s+(?:ext\s+)?precommit/.test(next) ? manual().warning : undefined }
|
|
64
65
|
}
|
|
65
66
|
|
package/src/lib/main.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @ts-check
|
|
2
2
|
const path = require('path')
|
|
3
|
-
const { encrypted, parseSync, injectsummary } = require('@dotenvx/primitives')
|
|
3
|
+
const { encrypted, parseSync, injectsummary, publickeys } = require('@dotenvx/primitives')
|
|
4
4
|
|
|
5
5
|
// shared
|
|
6
6
|
const { setLogLevel, setLogName, setLogVersion, logger } = require('./../shared/logger')
|
|
@@ -171,7 +171,15 @@ const config = function (options = {}, events) {
|
|
|
171
171
|
}
|
|
172
172
|
|
|
173
173
|
if (events) events.add({ files: readableFilepaths, injected_count: uniqueInjectedKeys(processedEnvs).size })
|
|
174
|
-
|
|
174
|
+
const summaryRows = readableFilepaths.map(filepath => {
|
|
175
|
+
const row = processedEnvs.find(row => row.filepath === filepath)
|
|
176
|
+
return {
|
|
177
|
+
filepath,
|
|
178
|
+
publicKeys: row ? publickeys(row.src || '') : [],
|
|
179
|
+
keySources: row && row.keySources
|
|
180
|
+
}
|
|
181
|
+
})
|
|
182
|
+
logger.success(injectsummary(uniqueInjectedKeys(processedEnvs).size, summaryRows))
|
|
175
183
|
|
|
176
184
|
if (lastError) {
|
|
177
185
|
if (events) events.fail(lastError)
|
|
@@ -9,8 +9,9 @@ const nativeNames = { darwin: 'macosKeychain', win32: 'windowsCredentialManager'
|
|
|
9
9
|
|
|
10
10
|
function lookup (publicKey, options, sync) {
|
|
11
11
|
let source
|
|
12
|
+
let armorError
|
|
12
13
|
let cleanup = () => {}
|
|
13
|
-
const
|
|
14
|
+
const providerOptions = {
|
|
14
15
|
...options,
|
|
15
16
|
// File keys are already resolved against the selected env file by callers.
|
|
16
17
|
fk: [],
|
|
@@ -20,15 +21,24 @@ function lookup (publicKey, options, sync) {
|
|
|
20
21
|
// synchronous path reads BW_SESSION without prompting.
|
|
21
22
|
noBitwarden: sync ? options.noBitwarden : true,
|
|
22
23
|
onLookup (name) { source = name },
|
|
24
|
+
onLookupEnd (name) {
|
|
25
|
+
if (name === 'armor') {
|
|
26
|
+
cleanup()
|
|
27
|
+
cleanup = () => {}
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
onArmorError (error) { armorError = error },
|
|
23
31
|
onApprovalRequired: options.onStatus && (({ approvalUri, code }) => {
|
|
24
32
|
cleanup()
|
|
25
33
|
const display = armoredKeyDisplay(publicKey)
|
|
26
34
|
options.onStatus(`[${code}] press Enter to open [${approvalUri}] and approve${display ? ` (${display})` : ''}`)
|
|
27
35
|
cleanup = listenForOpenKey(() => openUrl(approvalUri))
|
|
28
36
|
})
|
|
29
|
-
}
|
|
37
|
+
}
|
|
38
|
+
const keys = provider(providerOptions)
|
|
30
39
|
|
|
31
40
|
function found (ring) {
|
|
41
|
+
if (!ring[publicKey] && armorError) throw armorError
|
|
32
42
|
if (ring[publicKey] && options.onProvider) {
|
|
33
43
|
options.onProvider(source === 'native' ? nativeNames[process.platform] || source : source, publicKey)
|
|
34
44
|
}
|
|
@@ -36,7 +46,10 @@ function lookup (publicKey, options, sync) {
|
|
|
36
46
|
}
|
|
37
47
|
|
|
38
48
|
if (sync) {
|
|
39
|
-
try {
|
|
49
|
+
try {
|
|
50
|
+
const ring = keys.getSync(publicKey)
|
|
51
|
+
return found(ring)
|
|
52
|
+
} finally { cleanup() }
|
|
40
53
|
}
|
|
41
54
|
|
|
42
55
|
return (async () => {
|
|
@@ -95,11 +95,13 @@ async function injectEnv ({ env, overload, processEnv, envKeysFilepath, provider
|
|
|
95
95
|
|
|
96
96
|
const {
|
|
97
97
|
parsed,
|
|
98
|
+
keySources,
|
|
98
99
|
errors,
|
|
99
100
|
injected,
|
|
100
101
|
existed
|
|
101
102
|
} = await parseWithDecryptor(env.value, parseOptions)
|
|
102
103
|
|
|
104
|
+
row.keySources = keySources
|
|
103
105
|
row.parsed = parsed
|
|
104
106
|
row.errors = decryptErrors(parsed, errors)
|
|
105
107
|
row.injected = injected || {}
|
|
@@ -148,11 +150,13 @@ function injectEnvSync ({ env, overload, processEnv, envKeysFilepath, provider,
|
|
|
148
150
|
|
|
149
151
|
const {
|
|
150
152
|
parsed,
|
|
153
|
+
keySources,
|
|
151
154
|
errors,
|
|
152
155
|
injected,
|
|
153
156
|
existed
|
|
154
157
|
} = parseWithDecryptor.sync(env.value, parseOptions)
|
|
155
158
|
|
|
159
|
+
row.keySources = keySources
|
|
156
160
|
row.parsed = parsed
|
|
157
161
|
row.errors = decryptErrors(parsed, errors)
|
|
158
162
|
row.injected = injected || {}
|
|
@@ -202,12 +206,14 @@ async function injectEnvFile ({ env, overload, processEnv, envKeysFilepath, prov
|
|
|
202
206
|
|
|
203
207
|
const {
|
|
204
208
|
parsed,
|
|
209
|
+
keySources,
|
|
205
210
|
errors,
|
|
206
211
|
injected,
|
|
207
212
|
existed
|
|
208
213
|
} = await parseWithDecryptor(src, parseOptions)
|
|
209
214
|
|
|
210
215
|
row.src = src
|
|
216
|
+
row.keySources = keySources
|
|
211
217
|
row.parsed = parsed
|
|
212
218
|
row.injected = injected || {}
|
|
213
219
|
row.errors = decryptErrors(parsed, errors)
|
|
@@ -262,12 +268,14 @@ function injectEnvFileSync ({ env, overload, processEnv, envKeysFilepath, provid
|
|
|
262
268
|
|
|
263
269
|
const {
|
|
264
270
|
parsed,
|
|
271
|
+
keySources,
|
|
265
272
|
errors,
|
|
266
273
|
injected,
|
|
267
274
|
existed
|
|
268
275
|
} = parseWithDecryptor.sync(src, parseOptions)
|
|
269
276
|
|
|
270
277
|
row.src = src
|
|
278
|
+
row.keySources = keySources
|
|
271
279
|
row.parsed = parsed
|
|
272
280
|
row.injected = injected || {}
|
|
273
281
|
row.errors = decryptErrors(parsed, errors)
|
|
@@ -305,7 +313,15 @@ async function envs (options = {}) {
|
|
|
305
313
|
const envKeysFilepath = options.envKeysFilepath || options.envKeysFile || null
|
|
306
314
|
const no1Password = options.no1Password === true || process.env.DOTENVX_NO_1PASSWORD === 'true'
|
|
307
315
|
const noBitwarden = options.noBitwarden === true || process.env.DOTENVX_NO_BITWARDEN === 'true'
|
|
308
|
-
const
|
|
316
|
+
const sources = new Map()
|
|
317
|
+
const provider = await providers({
|
|
318
|
+
...options,
|
|
319
|
+
onProvider: (name, key) => {
|
|
320
|
+
sources.set(key, name)
|
|
321
|
+
if (options.onProvider) options.onProvider(name, key)
|
|
322
|
+
}
|
|
323
|
+
})
|
|
324
|
+
if (provider) provider.sourceFor = key => sources.get(key)
|
|
309
325
|
const decryptor = await decryptors(options)
|
|
310
326
|
for (const env of options.envs || []) {
|
|
311
327
|
if (env.type === TYPE_ENV_FILE) {
|
|
@@ -349,7 +365,15 @@ function envsSync (options = {}) {
|
|
|
349
365
|
const envKeysFilepath = options.envKeysFilepath || options.envKeysFile || null
|
|
350
366
|
const no1Password = options.no1Password === true || process.env.DOTENVX_NO_1PASSWORD === 'true'
|
|
351
367
|
const noBitwarden = options.noBitwarden === true || process.env.DOTENVX_NO_BITWARDEN === 'true'
|
|
352
|
-
const
|
|
368
|
+
const sources = new Map()
|
|
369
|
+
const provider = providers.sync({
|
|
370
|
+
...options,
|
|
371
|
+
onProvider: (name, key) => {
|
|
372
|
+
sources.set(key, name)
|
|
373
|
+
if (options.onProvider) options.onProvider(name, key)
|
|
374
|
+
}
|
|
375
|
+
})
|
|
376
|
+
if (provider) provider.sourceFor = key => sources.get(key)
|
|
353
377
|
const decryptor = decryptors.sync(options)
|
|
354
378
|
|
|
355
379
|
for (const env of options.envs || []) {
|
package/src/lib/services/init.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const fs = require('node:fs')
|
|
2
|
+
const fsx = require('../helpers/fsx')
|
|
2
3
|
const path = require('node:path')
|
|
3
4
|
const { scan, encrypted } = require('@dotenvx/primitives')
|
|
4
5
|
|
|
@@ -67,7 +68,13 @@ module.exports = function init ({ directory = process.cwd(), envFile, envFiles,
|
|
|
67
68
|
const content = renderEnvfile(document)
|
|
68
69
|
if (stdout) return { created: false, content }
|
|
69
70
|
try {
|
|
70
|
-
|
|
71
|
+
if (overwrite) {
|
|
72
|
+
const stat = fs.lstatSync(target, { throwIfNoEntry: false })
|
|
73
|
+
if (stat && !stat.isFile()) throw new Error(`Cannot replace Envfile: expected a regular file (${target})`)
|
|
74
|
+
fsx.writeFileXSync(target, content, { followSymlinks: false })
|
|
75
|
+
} else {
|
|
76
|
+
fs.writeFileSync(target, content, { flag: 'wx' })
|
|
77
|
+
}
|
|
71
78
|
} catch (error) {
|
|
72
79
|
if (error.code === 'EEXIST') return { created: false }
|
|
73
80
|
throw error
|
|
@@ -24,7 +24,15 @@ async function decrypt (options = {}) {
|
|
|
24
24
|
const ik = options.ik
|
|
25
25
|
const ek = options.ek
|
|
26
26
|
const fk = options.fk
|
|
27
|
-
const
|
|
27
|
+
const sources = new Map()
|
|
28
|
+
const provider = await providers({
|
|
29
|
+
...options,
|
|
30
|
+
onProvider: (name, key) => {
|
|
31
|
+
sources.set(key, name)
|
|
32
|
+
if (options.onProvider) options.onProvider(name, key)
|
|
33
|
+
}
|
|
34
|
+
})
|
|
35
|
+
if (provider) provider.sourceFor = key => sources.get(key)
|
|
28
36
|
const decryptor = await decryptors(options)
|
|
29
37
|
|
|
30
38
|
const processedEnvs = []
|
|
@@ -44,7 +52,9 @@ async function decrypt (options = {}) {
|
|
|
44
52
|
const encoding = await detectEncoding(filepath)
|
|
45
53
|
row.envSrc = await fsx.readFileX(filepath, { encoding })
|
|
46
54
|
|
|
47
|
-
const { parsed, errors } = await parseWithDecryptor.arrays(row.envSrc, { fk, ik, ek, provider, decryptor })
|
|
55
|
+
const { parsed, errors, keySources } = await parseWithDecryptor.arrays(row.envSrc, { fk, ik, ek, provider, decryptor })
|
|
56
|
+
|
|
57
|
+
row.keySources = keySources
|
|
48
58
|
|
|
49
59
|
if (errors.length > 0) {
|
|
50
60
|
row.error = parseError(errors[0])
|
|
@@ -29,7 +29,7 @@ async function encryptTransform (options = {}) {
|
|
|
29
29
|
|
|
30
30
|
// set up keysSrc
|
|
31
31
|
let keysSrc
|
|
32
|
-
if (await fsx.exists(fk)) {
|
|
32
|
+
if (options.with === undefined && await fsx.exists(fk)) {
|
|
33
33
|
try {
|
|
34
34
|
const encoding = await detectEncoding(fk)
|
|
35
35
|
keysSrc = await fsx.readFileX(fk, { encoding })
|
|
@@ -67,6 +67,27 @@ async function encryptTransform (options = {}) {
|
|
|
67
67
|
row.changed = true
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
+
if (options.with !== undefined) {
|
|
71
|
+
// Inspect every assignment before selection or schema rules can hide it.
|
|
72
|
+
const { parsed: existing } = scan(row.envSrc)
|
|
73
|
+
const declaredKeys = Object.entries(existing).filter(([key]) => isDotenvPublicKey(key)).flatMap(([, values]) => values)
|
|
74
|
+
const matchingKey = declaredKeys.length > 0 && declaredKeys.every(value => value.toLowerCase() === options.with.toLowerCase())
|
|
75
|
+
if (!matchingKey && (declaredKeys.length > 0 || Object.values(existing).some(values => values.some(encrypted)))) {
|
|
76
|
+
throw new Errors({ envFilepath }).alreadyEncrypted()
|
|
77
|
+
}
|
|
78
|
+
const { publicKeyName } = keynames(envFilepath)
|
|
79
|
+
try {
|
|
80
|
+
if (!/^(?:0[23][0-9a-f]{64}|04[0-9a-f]{128})$/i.test(options.with)) throw new Error('Invalid public key format')
|
|
81
|
+
encrypt(options.with, '') // Validate the curve point even if no values need encryption.
|
|
82
|
+
} catch {
|
|
83
|
+
throw new Errors({ publicKeyName, publicKey: options.with }).invalidPublicKey()
|
|
84
|
+
}
|
|
85
|
+
if (!matchingKey) {
|
|
86
|
+
row.envSrc = mutateSrc({ envSrc: row.envSrc, envFilepath, publicKeyName, publicKeyValue: options.with }).envSrc
|
|
87
|
+
row.changed = true
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
70
91
|
const { parsed } = scan(row.envSrc, { ik, ek })
|
|
71
92
|
const selected = Object.entries(parsed).filter(([key]) => {
|
|
72
93
|
if (isDotenvPublicKey(key)) return false
|
|
@@ -96,6 +117,7 @@ async function encryptTransform (options = {}) {
|
|
|
96
117
|
|
|
97
118
|
const result = await storeKeyStorage(storage, publicKey, privateKey, options, Object.assign(custodyContext, { keysSrc, privateKeyName, comment, keysFilepath: fk }))
|
|
98
119
|
storage = result.storage
|
|
120
|
+
row.keySources = { [publicKey]: Object.prototype.hasOwnProperty.call(result.stored, 'keysSrc') ? 'file' : (typeof storage === 'string' ? storage : storage.id) }
|
|
99
121
|
const stored = result.stored
|
|
100
122
|
if (Object.prototype.hasOwnProperty.call(stored, 'keysSrc')) keysSrc = stored.keysSrc
|
|
101
123
|
if (stored.nativePrivateKeyAdded) row.nativePrivateKeyAdded = true
|