@dotenvx/dotenvx 2.34.2 → 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 CHANGED
@@ -2,7 +2,17 @@
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.34.2...main)
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))
6
16
 
7
17
  ## [2.34.2](https://github.com/dotenvx/dotenvx/compare/v2.34.1...v2.34.2) (2026-10-09)
8
18
 
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.34.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",
@@ -30,7 +30,7 @@ async function encryptAction () {
30
30
 
31
31
  // stdout - should not have a try so that exit codes can surface to stdout
32
32
  if (options.stdout) {
33
- 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 })
34
34
 
35
35
  if (spinner) spinner.stop()
36
36
  for (const processedEnv of processedEnvs) {
@@ -47,9 +47,9 @@ async function encryptAction () {
47
47
  }
48
48
 
49
49
  try {
50
- 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 })
51
51
 
52
- if (keysSrc) {
52
+ if (keysSrc && options.with === undefined) {
53
53
  await fsx.writeKeyFile(fk, keysSrc)
54
54
  }
55
55
 
@@ -70,7 +70,7 @@ async function encryptAction () {
70
70
  // Existing public keys can encrypt without private-key access. Metadata
71
71
  // lookup must never turn successful encryption into a failure.
72
72
  for (const row of processedEnvs) {
73
- if (options.quiet || row.error || row.keySources || !publickeys(row.envSrc || '').length) continue
73
+ if (options.with !== undefined || options.quiet || row.error || row.keySources || !publickeys(row.envSrc || '').length) continue
74
74
  try {
75
75
  const resolved = await keypair({ ...options, envFile: [row.filepath], envKeysFile: fk, noArmor, noNative, no1Password, noBitwarden, includeProvider: true })
76
76
  row.keySources = { [publickeys(row.envSrc)[0]]: resolved.provider }
@@ -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)}'`
@@ -1,4 +1,5 @@
1
1
  const fs = require('fs')
2
+ const path = require('path')
2
3
  const writeFileAtomic = require('write-file-atomic')
3
4
  const Errors = require('./errors')
4
5
 
@@ -23,6 +24,7 @@ function readFileXSync (filepath, encoding = null) {
23
24
 
24
25
  function writeFileXSync (filepath, str, options = ENCODING) {
25
26
  try {
27
+ if (options && options.followSymlinks === false) return writeFileNoFollowSync(filepath, str, options)
26
28
  return writeFileAtomic.sync(filepath, str, typeof options === 'string' ? options : { ...options })
27
29
  } catch (error) {
28
30
  if (error.code === 'EACCES' || error.code === 'EPERM') {
@@ -33,6 +35,31 @@ function writeFileXSync (filepath, str, options = ENCODING) {
33
35
  }
34
36
  }
35
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
+
36
63
  async function writeFileX (filepath, str, options = ENCODING) {
37
64
  try {
38
65
  return await writeFileAtomic(filepath, str, typeof options === 'string' ? options : { ...options })
@@ -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
- let current = fs.existsSync(attributesPath) ? fs.readFileSync(attributesPath, 'utf8') : ''
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
- if (migrated !== current) fs.writeFileSync(attributesPath, migrated)
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
- fs.appendFileSync(attributesPath, `${current && !current.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`)
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,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) fs.writeFileSync(filename, updated)
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) fs.writeFileSync(attributesPath, updated)
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 fs.writeFileSync(hookPath, next, 'utf8')
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
 
@@ -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
- fs.writeFileSync(target, content, { flag: overwrite ? fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_TRUNC | fs.constants.O_NOFOLLOW : 'wx' })
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
@@ -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