@dotenvx/dotenvx 2.28.1 → 2.29.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.
Files changed (35) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/README.md +47 -12
  3. package/package.json +1 -1
  4. package/src/cli/actions/encrypt.js +1 -1
  5. package/src/cli/actions/ext/gitignore.js +1 -0
  6. package/src/cli/actions/ext/prebuild.js +5 -28
  7. package/src/cli/actions/ext/precommit.js +8 -3
  8. package/src/cli/actions/protect.js +72 -0
  9. package/src/cli/actions/protectDocker.js +30 -0
  10. package/src/cli/actions/protectProcess.js +123 -0
  11. package/src/cli/actions/protectStdin.js +63 -0
  12. package/src/cli/actions/set.js +1 -1
  13. package/src/cli/commands/ext.js +3 -4
  14. package/src/cli/dotenvx.js +17 -7
  15. package/src/cli/help.js +4 -3
  16. package/src/lib/helpers/checklist.js +45 -0
  17. package/src/lib/helpers/createProtectSpinner.js +13 -0
  18. package/src/lib/helpers/fsx.js +16 -5
  19. package/src/lib/helpers/hasPlaintextSecrets.js +11 -0
  20. package/src/lib/helpers/installPrecommitHook.js +1 -0
  21. package/src/lib/helpers/installProtectFilter.js +56 -0
  22. package/src/lib/helpers/installProtectIgnore.js +27 -0
  23. package/src/lib/helpers/logProtectedFiles.js +9 -0
  24. package/src/lib/helpers/precommitEnvPatterns.js +1 -0
  25. package/src/lib/helpers/prompts.js +24 -0
  26. package/src/lib/helpers/protectSettings.js +63 -0
  27. package/src/lib/helpers/removeEnvKey.js +2 -1
  28. package/src/lib/helpers/removeLegacyProtectFilter.js +42 -0
  29. package/src/lib/helpers/uninstallPrecommitHook.js +66 -0
  30. package/src/lib/helpers/upsertEnvKey.js +2 -1
  31. package/src/lib/main.js +1 -1
  32. package/src/lib/services/prebuild.js +4 -5
  33. package/src/lib/services/precommit.js +2 -12
  34. package/src/cli/actions/ext/precommitClean.js +0 -21
  35. package/src/lib/helpers/installPrecommitFilter.js +0 -50
package/CHANGELOG.md CHANGED
@@ -2,7 +2,25 @@
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.28.1...main)
5
+ [Unreleased](https://github.com/dotenvx/dotenvx/compare/v2.29.0...main)
6
+
7
+ ## [2.29.0](https://github.com/dotenvx/dotenvx/compare/v2.28.2...v2.29.0) (2026-09-21)
8
+
9
+ ### Added
10
+
11
+ * Add `dotenvx protect` to prevent plaintext .env files from being committed to code on a machine ([#980](https://github.com/dotenvx/dotenvx/pull/980))
12
+
13
+ ### Changed
14
+
15
+ * Deprecate `dotenvx gitignore`. Use `dotenvx protect`.
16
+ * Deprecate `dotenvx precommit`. Use `dotenvx protect`.
17
+ * Deprecate `dotenvx prebuild`. Use `dotenvx protect --docker`.
18
+
19
+ ## [2.28.2](https://github.com/dotenvx/dotenvx/compare/v2.28.1...v2.28.2) (2026-09-19)
20
+
21
+ ### Changed
22
+
23
+ * Only owner can write to and read from .env.keys file ([#979](https://github.com/dotenvx/dotenvx/pull/979))
6
24
 
7
25
  ## [2.28.1](https://github.com/dotenvx/dotenvx/compare/v2.28.0...v2.28.1) (2026-09-19)
8
26
 
package/README.md CHANGED
@@ -2924,6 +2924,8 @@ $ dotenvx gitignore --pattern .env.keys
2924
2924
  </details>
2925
2925
  <details><summary>`precommit`</summary><br>
2926
2926
 
2927
+ Deprecated in favor of `dotenvx protect`. Existing hooks continue checking files and print a migration notice on each invocation. Run `dotenvx protect` inside the repository to install global staging protection and remove its recognized dotenvx hook block. Other hook commands are preserved; customized or shared hooks may require manual cleanup.
2928
+
2927
2929
  Prevent `.env` files from being committed to code.
2928
2930
 
2929
2931
  ```sh
@@ -2934,24 +2936,57 @@ $ dotenvx precommit
2934
2936
  </details>
2935
2937
  <details><summary>`precommit --install`</summary><br>
2936
2938
 
2937
- Install a pre-commit hook and a required Git clean filter in the current repository. The filter rejects plaintext `.env*` files before staging, including with `git add -A` or `git add -f`. Encrypted files pass through unchanged. `.env.example`, `.env.vault`, and `.env.x` retain their exemptions; `.env.keys*` files are always rejected.
2939
+ Install a pre-commit hook in the current repository:
2940
+
2941
+ ```sh
2942
+ $ dotenvx precommit --install
2943
+ ▣ dotenvx precommit installed [.git/hooks/pre-commit]
2944
+ ```
2945
+
2946
+ For protection during staging, use `dotenvx protect`.
2938
2947
 
2939
- The filter uses repository-local Git configuration and `info/attributes`; run the installer in each clone. Keep the installed dotenvx executable available, or staging protected files will fail. It does not inspect content already staged before installation, and local Git configuration can be overridden.
2948
+ </details>
2949
+ <details><summary>`precommit --uninstall`</summary><br>
2940
2950
 
2941
- To enable the clean filter for all existing and future repositories for your user, run this once, even outside a Git repository:
2951
+ Remove the installed dotenvx pre-commit hook without installing replacement protection:
2942
2952
 
2943
2953
  ```sh
2944
- $ dotenvx precommit --install --global
2954
+ $ dotenvx precommit --uninstall
2945
2955
  ```
2946
2956
 
2947
- This writes the filter configuration to your global Git config and adds the `.env*` rule to your global attributes file. It preserves an existing `core.attributesFile`; otherwise it uses `$XDG_CONFIG_HOME/git/attributes` or `~/.config/git/attributes`. It leaves hooks unchanged. Repository attributes and configuration can override the global protection. Use a persistent dotenvx installation: moving or removing its executable requires reinstalling the filter.
2957
+ This removes recognized dotenvx installer blocks while preserving other hook commands. It also supports `dotenvx ext precommit --uninstall`. Unrecognized, symlinked, or external shared hooks are left unchanged with a manual-cleanup message.
2958
+
2959
+ </details>
2960
+ <details><summary>`protect` (hidden)</summary><br>
2961
+
2962
+ For a Docker build-time check instead of Git setup, use `RUN dotenvx protect --docker` in your Dockerfile, or `RUN dotenvx protect --docker apps/backend` for a specific directory. This replaces `prebuild` with the same checks, without prompts or Git configuration changes. It does not edit Dockerfiles or prevent files from reaching the builder; use `.dockerignore` for that.
2963
+
2964
+ Install a required Git clean filter for all existing and future repositories for your user. Run this once, even outside a Git repository:
2948
2965
 
2949
2966
  ```sh
2950
- $ dotenvx precommit --install
2951
- ▣ dotenvx precommit installed [.git/hooks/pre-commit]
2952
- ▣ dotenvx required clean filter installed (blocks staging plaintext .env files)
2967
+ $ dotenvx protect
2968
+ ```
2969
+
2970
+ Interactive setup shows one checklist with both protections selected every time, even if you previously turned them off:
2971
+
2972
+ ```text
2973
+ Set protections
2974
+ ● Protect plaintext secrets from code commits (.env*)
2975
+ ● Protect private keys from code commits (.env.keys*)
2976
+
2977
+ Install protections
2953
2978
  ```
2954
2979
 
2980
+ Use arrow keys to move and Enter or Space to toggle a choice. The action row changes to **Install protections**, **Apply changes**, **Remove protections**, or **Done**. Press Enter on that row to apply. Unchecking removes that protection; clearing both reports `⛉ unprotected (none)`. Cancelling leaves settings unchanged.
2981
+
2982
+ The first installs the staging filter. The second adds `.env.keys*` to your global Git ignore file, preserving existing rules and any configured `core.excludesFile`. Otherwise, it uses `$XDG_CONFIG_HOME/git/ignore` or `~/.config/git/ignore`. This skips private-key files during normal adds; the filter still rejects forced adds when enabled. Only dotenvx-owned ignore rules are removed. Older or manually added `.env.keys*` rules without an ownership record require manual removal. Noninteractive and CI runs retain filter-only installation without prompting or removing existing protections.
2983
+
2984
+ When run inside a repository with the filter selected, this also removes recognized dotenvx pre-commit hook blocks and legacy repo-local `precommit --clean` filter registrations after global protection is successfully installed. Custom filter commands are preserved. Run it in each repository with an old hook or filter override to migrate that repository.
2985
+
2986
+ The filter rejects plaintext `.env*`, `*.env`, `.flaskenv`, `.dev.vars*`, and files directly inside `.env.d/` directories at any depth before staging, including with `git add -A` or `git add -f`. Encrypted files pass through unchanged. `.env.example`, `.env.vault`, and `.env.x` retain their exemptions; `.env.keys*` files are always rejected.
2987
+
2988
+ This writes the filter configuration to your global Git config and adds the env-file rules to your global attributes file. Re-run `dotenvx protect` with the filter selected to refresh it after upgrading or moving the executable. It preserves an existing `core.attributesFile`; otherwise it uses `$XDG_CONFIG_HOME/git/attributes` or `~/.config/git/attributes`. It does not inspect content already staged before installation. Repository attributes and configuration can override the global protection. Use a persistent dotenvx installation.
2989
+
2955
2990
  </details>
2956
2991
  <details><summary>`precommit directory`</summary><br>
2957
2992
 
@@ -2969,7 +3004,7 @@ $ dotenvx precommit apps/backend
2969
3004
  </details>
2970
3005
  <details><summary>`prebuild`</summary><br>
2971
3006
 
2972
- Prevent `.env` files from being built into your docker containers.
3007
+ Deprecated. Use `dotenvx protect --docker` for the same build-time check.
2973
3008
 
2974
3009
  Add it to your `Dockerfile`.
2975
3010
 
@@ -2982,14 +3017,14 @@ COPY --from=dotenv/dotenvx:latest /usr/local/bin/dotenvx /bin/local/bin
2982
3017
 
2983
3018
  # ... orther container commands
2984
3019
 
2985
- RUN dotenvx prebuild
3020
+ RUN dotenvx protect --docker
2986
3021
  CMD ["/usr/local/bin/dotenvx", "run", "--", "node", "index.js"]
2987
3022
  ```
2988
3023
 
2989
3024
  </details>
2990
3025
  <details><summary>`prebuild directory`</summary><br>
2991
3026
 
2992
- Prevent `.env` files from being built into your docker containers inside a specified path to a directory.
3027
+ Deprecated. Use `dotenvx protect --docker <directory>` for the same build-time check in a specified directory.
2993
3028
 
2994
3029
  Add it to your `Dockerfile`.
2995
3030
 
@@ -3002,7 +3037,7 @@ COPY --from=dotenv/dotenvx:latest /usr/local/bin/dotenvx /bin/local/bin
3002
3037
 
3003
3038
  # ... orther container commands
3004
3039
 
3005
- RUN dotenvx prebuild apps/backend
3040
+ RUN dotenvx protect --docker apps/backend
3006
3041
  CMD ["/usr/local/bin/dotenvx", "run", "--", "node", "apps/backend/index.js"]
3007
3042
  ```
3008
3043
 
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.28.1",
2
+ "version": "2.29.0",
3
3
  "name": "@dotenvx/dotenvx",
4
4
  "description": "a secure dotenv–from the creator of `dotenv`",
5
5
  "author": "@motdotla",
@@ -54,7 +54,7 @@ async function encryptAction () {
54
54
  const { keysSrc, processedEnvs, changedFilepaths, unchangedFilepaths } = await encryptTransform({ envs, ik, ek, fk, noArmor, noCreate, noNative, no1Password, noBitwarden })
55
55
 
56
56
  if (keysSrc) {
57
- await fsx.writeFileX(fk, keysSrc)
57
+ await fsx.writeKeyFile(fk, keysSrc)
58
58
  }
59
59
 
60
60
  if (spinner) spinner.stop()
@@ -86,6 +86,7 @@ class Vercel {
86
86
  }
87
87
 
88
88
  function gitignore () {
89
+ logger.warn('[DEPRECATED] dotenvx gitignore. fix: run [dotenvx protect]')
89
90
  const options = this.opts()
90
91
  logger.debug(`options: ${JSON.stringify(options)}`)
91
92
 
@@ -1,30 +1,7 @@
1
- const { logger } = require('./../../../shared/logger')
1
+ const { logger } = require('../../../shared/logger')
2
+ const protectDocker = require('../protectDocker')
2
3
 
3
- const Prebuild = require('./../../../lib/services/prebuild')
4
- const catchAndLog = require('./../../../lib/helpers/catchAndLog')
5
-
6
- function prebuild (directory) {
7
- // debug args
8
- logger.debug(`directory: ${directory}`)
9
-
10
- const options = this.opts()
11
- logger.debug(`options: ${JSON.stringify(options)}`)
12
-
13
- try {
14
- const {
15
- successMessage,
16
- warnings
17
- } = new Prebuild(directory, options).run()
18
-
19
- for (const warning of warnings) {
20
- logger.warn(warning.messageWithHelp || warning.message)
21
- }
22
-
23
- logger.success(successMessage)
24
- } catch (error) {
25
- catchAndLog(error)
26
- process.exit(1)
27
- }
4
+ module.exports = function prebuild (directory) {
5
+ logger.warn('[DEPRECATED] dotenvx prebuild. fix: run [dotenvx protect --docker]')
6
+ return protectDocker.call(this, directory)
28
7
  }
29
-
30
- module.exports = prebuild
@@ -4,9 +4,6 @@ const Precommit = require('./../../../lib/services/precommit')
4
4
  const catchAndLog = require('./../../../lib/helpers/catchAndLog')
5
5
 
6
6
  function precommit (directory) {
7
- if (this.opts().clean !== undefined) {
8
- return require('./precommitClean')(this.opts().clean)
9
- }
10
7
  // debug args
11
8
  logger.debug(`directory: ${directory}`)
12
9
 
@@ -14,6 +11,14 @@ function precommit (directory) {
14
11
  logger.debug(`options: ${JSON.stringify(options)}`)
15
12
 
16
13
  try {
14
+ if (options.uninstall) {
15
+ if (options.install) throw new Error('--install and --uninstall cannot be used together')
16
+ const { removed, warning } = require('../../../lib/helpers/uninstallPrecommitHook')(directory)
17
+ if (warning) logger.warn(warning)
18
+ else logger.success(removed ? '▣ uninstalled (dotenvx precommit hook)' : '○ no dotenvx precommit hook found')
19
+ return
20
+ }
21
+ logger.warn('[DEPRECATED] dotenvx precommit. fix: run [dotenvx protect]')
17
22
  const {
18
23
  successMessage,
19
24
  warnings
@@ -0,0 +1,72 @@
1
+ const installProtectFilter = require('../../lib/helpers/installProtectFilter')
2
+ const installProtectIgnore = require('../../lib/helpers/installProtectIgnore')
3
+ const prompts = require('../../lib/helpers/prompts')
4
+ const { logger } = require('../../shared/logger')
5
+ const catchAndLog = require('../../lib/helpers/catchAndLog')
6
+ const settings = require('../../lib/helpers/protectSettings')
7
+ const createSpinner = require('../../lib/helpers/createSpinner')
8
+
9
+ module.exports = async function protect (directory) {
10
+ if (this.opts().docker) return require('./protectDocker').call(this, directory)
11
+ const filterOptions = typeof this.optsWithGlobals === 'function' ? this.optsWithGlobals() : this.opts()
12
+ if (this.opts().gitProcess) return require('./protectProcess')(filterOptions)
13
+ if (this.opts().gitFile !== undefined) {
14
+ return require('./protectStdin')(this.opts().gitFile, filterOptions)
15
+ }
16
+ let spinner
17
+ try {
18
+ let filter = true
19
+ let ignore = false
20
+ let current
21
+ const interactive = !process.env.CI && process.stdin.isTTY && process.stderr.isTTY
22
+ if (interactive) {
23
+ current = settings.state()
24
+ const protections = await prompts.multiselect({
25
+ message: 'Set protections',
26
+ submitLabel: selected => {
27
+ if (current.configured && ['filter', 'ignore'].every(key => selected.includes(key) === current[key])) return 'Done'
28
+ if (!selected.length) return 'Remove protections'
29
+ return current.configured ? 'Apply changes' : 'Install protections'
30
+ },
31
+ choices: [
32
+ { name: 'Protect plaintext secrets from code commits (.env*)', value: 'filter' },
33
+ { name: 'Protect private keys from code commits (.env.keys*)', value: 'ignore' }
34
+ ],
35
+ initial: ['filter', 'ignore']
36
+ })
37
+ filter = protections.includes('filter')
38
+ ignore = protections.includes('ignore')
39
+ }
40
+ const options = this.opts()
41
+ const spinnerOptions = typeof this.optsWithGlobals === 'function' ? this.optsWithGlobals() : options
42
+ spinner = await createSpinner({ ...spinnerOptions, ...options, text: filter || ignore ? 'protecting' : 'unprotecting' })
43
+ if (interactive) {
44
+ // Check ownership-sensitive removal before changing the filter.
45
+ if (!ignore && current.ignore) settings.removeIgnore()
46
+ if (!filter && current.filter) settings.removeFilter()
47
+ }
48
+ const protectedFiles = []
49
+ let hookWarning
50
+ if (filter) {
51
+ installProtectFilter()
52
+ require('../../lib/helpers/removeLegacyProtectFilter')()
53
+ const { warning } = require('../../lib/helpers/uninstallPrecommitHook')()
54
+ hookWarning = warning
55
+ protectedFiles.push('.env*')
56
+ }
57
+ if (ignore) {
58
+ if (!current || !current.ignore) installProtectIgnore()
59
+ protectedFiles.push('.env.keys*')
60
+ }
61
+ if (interactive) settings.markConfigured()
62
+ if (spinner) spinner.stop()
63
+ if (hookWarning) logger.warn(hookWarning)
64
+ const status = protectedFiles.length === 2 ? 'full' : 'partial'
65
+ if (protectedFiles.length) logger.success(`⛉ protection: ${status} (${protectedFiles.join(', ')})`)
66
+ else logger.success('⛉ protection: none')
67
+ } catch (error) {
68
+ if (spinner) spinner.stop()
69
+ catchAndLog(error)
70
+ process.exitCode = 1
71
+ }
72
+ }
@@ -0,0 +1,30 @@
1
+ const { logger } = require('../../shared/logger')
2
+
3
+ const Prebuild = require('../../lib/services/prebuild')
4
+ const catchAndLog = require('../../lib/helpers/catchAndLog')
5
+
6
+ function protectDocker (directory) {
7
+ // debug args
8
+ logger.debug(`directory: ${directory}`)
9
+
10
+ const options = this.opts()
11
+ logger.debug(`options: ${JSON.stringify(options)}`)
12
+
13
+ try {
14
+ const {
15
+ successMessage,
16
+ warnings
17
+ } = new Prebuild(directory, options).run()
18
+
19
+ for (const warning of warnings) {
20
+ logger.warn(warning.messageWithHelp || warning.message)
21
+ }
22
+
23
+ logger.success(successMessage)
24
+ } catch (error) {
25
+ catchAndLog(error)
26
+ process.exit(1)
27
+ }
28
+ }
29
+
30
+ module.exports = protectDocker
@@ -0,0 +1,123 @@
1
+ const { once } = require('events')
2
+ const { check, exempt } = require('./protectStdin')
3
+ const { logger } = require('../../shared/logger')
4
+ const createProtectSpinner = require('../../lib/helpers/createProtectSpinner')
5
+ const logProtectedFiles = require('../../lib/helpers/logProtectedFiles')
6
+
7
+ // Git's v2 filter protocol frames every message and blob with pkt-line lengths.
8
+ async function * packets (input) {
9
+ let buffer = Buffer.alloc(0)
10
+ for await (const chunk of input) {
11
+ buffer = Buffer.concat([buffer, chunk])
12
+ while (buffer.length >= 4) {
13
+ const header = buffer.subarray(0, 4).toString('ascii')
14
+ if (!/^[0-9a-fA-F]{4}$/.test(header)) throw new Error('Invalid Git filter packet')
15
+ const length = parseInt(header, 16)
16
+ if (length !== 0 && (length < 4 || length > 65520)) throw new Error('Invalid Git filter packet length')
17
+ if (buffer.length < (length || 4)) break
18
+ const packet = length ? buffer.subarray(4, length) : null
19
+ buffer = buffer.subarray(length || 4)
20
+ yield packet
21
+ }
22
+ }
23
+ if (buffer.length) throw new Error('Incomplete Git filter packet')
24
+ }
25
+
26
+ module.exports = async function protectProcess (options = {}) {
27
+ let spinner
28
+ let started = false
29
+ let failed = false
30
+ let activeRequest = false
31
+ let reported = false
32
+ const checkedFiles = new Set()
33
+ const stop = () => { if (spinner) spinner.stop() }
34
+ const finish = () => {
35
+ stop()
36
+ if (spinner && !failed && !activeRequest && !reported) {
37
+ reported = true
38
+ logProtectedFiles(checkedFiles)
39
+ }
40
+ }
41
+ // Git may terminate an idle filter with SIGTERM instead of closing stdin.
42
+ const onExit = code => { if (code === 0 || code === 143) finish() }
43
+ process.once('exit', onExit)
44
+ const reader = packets(process.stdin)
45
+ const write = async data => {
46
+ if (!process.stdout.write(data)) await once(process.stdout, 'drain')
47
+ }
48
+ const packet = async data => {
49
+ if (data === null) return write('0000')
50
+ const bytes = Buffer.isBuffer(data) ? data : Buffer.from(data)
51
+ await write(Buffer.from((bytes.length + 4).toString(16).padStart(4, '0')))
52
+ await write(bytes)
53
+ }
54
+ const list = async (allowEOF = false) => {
55
+ const result = []
56
+ while (true) {
57
+ const item = await reader.next()
58
+ if (item.done) {
59
+ if (allowEOF && !result.length) return null
60
+ throw new Error('Incomplete Git filter request')
61
+ }
62
+ if (item.value === null) return result
63
+ result.push(item.value)
64
+ }
65
+ }
66
+ const lines = entries => entries.map(entry => entry.toString('utf8').replace(/\n$/, ''))
67
+ try {
68
+ const hello = lines(await list())
69
+ if (hello[0] !== 'git-filter-client' || !hello.includes('version=2')) throw new Error('Unsupported Git filter handshake')
70
+ await packet('git-filter-server\n')
71
+ await packet('version=2\n')
72
+ await packet(null)
73
+ const capabilities = lines(await list())
74
+ if (!capabilities.includes('capability=clean')) throw new Error('Git filter requires clean capability')
75
+ await packet('capability=clean\n')
76
+ const smudge = capabilities.includes('capability=smudge')
77
+ if (smudge) await packet('capability=smudge\n')
78
+ await packet(null)
79
+ while (true) {
80
+ const headers = await list(true)
81
+ if (headers === null) return
82
+ activeRequest = true
83
+ const fields = new Map(lines(headers).map(line => {
84
+ const index = line.indexOf('=')
85
+ return [line.slice(0, index), line.slice(index + 1)]
86
+ }))
87
+ const command = fields.get('command')
88
+ if ((command !== 'clean' && !(smudge && command === 'smudge')) || !fields.has('pathname')) throw new Error('Invalid Git filter request')
89
+ if (command === 'clean' && !started) {
90
+ started = true
91
+ spinner = await createProtectSpinner(options)
92
+ }
93
+ const content = Buffer.concat(await list())
94
+ // Checkout must remain a byte-for-byte passthrough, even for existing plaintext history.
95
+ if (command === 'clean' && !check(fields.get('pathname'), content, stop)) {
96
+ failed = true
97
+ await packet('status=error\n')
98
+ await packet(null)
99
+ activeRequest = false
100
+ continue
101
+ }
102
+ await packet('status=success\n')
103
+ await packet(null)
104
+ for (let offset = 0; offset < content.length; offset += 65516) {
105
+ await packet(content.subarray(offset, offset + 65516))
106
+ }
107
+ await packet(null)
108
+ await packet(null)
109
+ if (command === 'clean' && !exempt(fields.get('pathname'))) checkedFiles.add(fields.get('pathname'))
110
+ activeRequest = false
111
+ }
112
+ } catch {
113
+ failed = true
114
+ stop()
115
+ // Never include malformed protocol data: it may contain secret contents.
116
+ logger.error('Git protection filter protocol failed')
117
+ process.exitCode = 1
118
+ process.stdin.destroy()
119
+ } finally {
120
+ finish()
121
+ process.removeListener('exit', onExit)
122
+ }
123
+ }
@@ -0,0 +1,63 @@
1
+ const fs = require('fs')
2
+ const path = require('path')
3
+ const hasPlaintextSecrets = require('../../lib/helpers/hasPlaintextSecrets')
4
+ const { logger } = require('../../shared/logger')
5
+ const createProtectSpinner = require('../../lib/helpers/createProtectSpinner')
6
+ const logProtectedFiles = require('../../lib/helpers/logProtectedFiles')
7
+
8
+ function exempt (filepath) {
9
+ return ['.env.example', '.env.vault', '.env.x'].includes(path.posix.basename(filepath))
10
+ }
11
+
12
+ function fixMessage (filepath, privateKeyFile) {
13
+ if (Array.from(filepath).some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)) {
14
+ return privateKeyFile ? 'fix: add this private-key file to .gitignore' : 'fix: encrypt this env file or add it to .gitignore'
15
+ }
16
+ const argument = /^[a-zA-Z0-9_./-]+$/.test(filepath) ? filepath : "'" + filepath.replace(/'/g, "'\\''") + "'"
17
+ return privateKeyFile
18
+ ? `fix: run [dotenvx gitignore --pattern ${argument}]`
19
+ : `fix: run [dotenvx encrypt -f ${argument}]`
20
+ }
21
+
22
+ function check (filepath, content, beforeError = () => {}) {
23
+ const filename = path.posix.basename(filepath)
24
+ const privateKeyFile = filename.startsWith('.env.keys')
25
+ if (privateKeyFile || (!exempt(filepath) && hasPlaintextSecrets(content.toString('utf8')))) {
26
+ const code = privateKeyFile ? 'PRIVATE_KEY_FILE' : 'PLAINTEXT_ENV'
27
+ const fix = fixMessage(filepath, privateKeyFile)
28
+ const message = privateKeyFile
29
+ ? `refusing to stage ${JSON.stringify(filepath)}`
30
+ : `${JSON.stringify(filepath)} contains plaintext secrets`
31
+ beforeError()
32
+ logger.error(`[${code}] ${message}. ${fix}`)
33
+ return false
34
+ }
35
+ return true
36
+ }
37
+
38
+ async function protectStdin (filepath, options = {}) {
39
+ let spinner
40
+ const stop = () => { if (spinner) spinner.stop() }
41
+ try {
42
+ spinner = await createProtectSpinner(options)
43
+ const content = fs.readFileSync(0)
44
+ if (!check(filepath, content, stop)) {
45
+ process.exitCode = 1
46
+ return
47
+ }
48
+ // stdout is Git's blob content: no logging, normalization, or extra newline.
49
+ process.stdout.write(content)
50
+ stop()
51
+ if (spinner && !exempt(filepath)) logProtectedFiles([filepath])
52
+ } catch (error) {
53
+ stop()
54
+ logger.error(error.message)
55
+ process.exitCode = 1
56
+ } finally {
57
+ stop()
58
+ }
59
+ }
60
+
61
+ module.exports = protectStdin
62
+ module.exports.check = check
63
+ module.exports.exempt = exempt
@@ -70,7 +70,7 @@ async function set (key, value) {
70
70
  const { keysSrc, processedEnvs, changedFilepaths, unchangedFilepaths } = await setTransform({ envs, key, value, fk, noArmor, noCreate, encrypt, noNative, no1Password, noBitwarden })
71
71
 
72
72
  if (keysSrc) {
73
- await fsx.writeFileX(fk, keysSrc)
73
+ await fsx.writeKeyFile(fk, keysSrc)
74
74
  }
75
75
 
76
76
  let withEncryption = ''
@@ -49,7 +49,7 @@ ext.command('gitignore')
49
49
 
50
50
  // dotenvx ext prebuild
51
51
  ext.command('prebuild')
52
- .description('prevent including .env files in docker')
52
+ .description('deprecated. use [dotenvx protect --docker]')
53
53
  .addHelpText('after', help.prebuild)
54
54
  .argument('[directory]', 'directory to prevent including .env files from', '.')
55
55
  .action(function (...args) {
@@ -61,9 +61,8 @@ ext.command('precommit')
61
61
  .description('prevent committing .env files to code')
62
62
  .addHelpText('after', help.precommit)
63
63
  .argument('[directory]', 'directory to prevent committing .env files from', '.')
64
- .option('-i, --install', 'install a pre-commit hook and required Git clean filter')
65
- .option('--global', 'with --install, install the clean filter for all repositories')
66
- .addOption(ext.createOption('--clean <path>', 'validate Git filter input from stdin').hideHelp())
64
+ .option('-i, --install', 'install a pre-commit hook')
65
+ .option('--uninstall', 'remove the dotenvx pre-commit hook')
67
66
  .action(function (...args) {
68
67
  return require('./../actions/ext/precommit').apply(this, args)
69
68
  })
@@ -261,7 +261,7 @@ program.command('validate', { hidden: true })
261
261
 
262
262
  // dotenvx gitignore
263
263
  program.command('gitignore', { hidden: true })
264
- .description('append to .gitignore')
264
+ .description('deprecated. use [dotenvx protect]')
265
265
  .addHelpText('after', help.gitignore)
266
266
  .option('--pattern <patterns...>', 'pattern(s) to gitignore', ['.env*'])
267
267
  .action(function (...args) {
@@ -279,19 +279,29 @@ program.command('genexample', { hidden: true })
279
279
 
280
280
  // dotenvx precommit
281
281
  program.command('precommit', { hidden: true })
282
- .description('prevent committing .env files to code')
282
+ .description('deprecated. use [dotenvx protect]')
283
283
  .addHelpText('after', help.precommit)
284
284
  .argument('[directory]', 'directory to prevent committing .env files from', '.')
285
- .option('-i, --install', 'install a pre-commit hook and required Git clean filter')
286
- .option('--global', 'with --install, install the clean filter for all repositories')
287
- .addOption(program.createOption('--clean <path>', 'validate Git filter input from stdin').hideHelp())
285
+ .option('-i, --install', 'install a pre-commit hook')
286
+ .option('--uninstall', 'remove the dotenvx pre-commit hook')
288
287
  .action(function (...args) {
289
288
  return require('./actions/ext/precommit').apply(this, args)
290
289
  })
291
290
 
291
+ // dotenvx protect
292
+ program.command('protect', { hidden: true })
293
+ .description('protect secrets and private keys from code commits')
294
+ .argument('[directory]', 'directory to check with --docker', '.')
295
+ .addOption(program.createOption('--docker', 'check env files are encrypted or dockerignored').conflicts(['gitFile', 'gitProcess']))
296
+ .addOption(program.createOption('--git-file <pathname>', 'check stdin contents for the given Git pathname').hideHelp())
297
+ .addOption(program.createOption('--git-process', 'run the Git protection filter protocol').hideHelp())
298
+ .action(function () {
299
+ return require('./actions/protect').apply(this, arguments)
300
+ })
301
+
292
302
  // dotenvx prebuild
293
303
  program.command('prebuild', { hidden: true })
294
- .description('prevent including .env files in docker')
304
+ .description('deprecated. use [dotenvx protect --docker]')
295
305
  .addHelpText('after', help.prebuild)
296
306
  .argument('[directory]', 'directory to prevent including .env files from', '.')
297
307
  .action(function (...args) {
@@ -310,7 +320,7 @@ program.command('doctor', { hidden: true })
310
320
  program.command('hidden')
311
321
  .allowExcessArguments(false)
312
322
  .description('hidden features')
313
- .addHelpText('after', '\nHidden Commands:\n init create an Envfile from .env.example and .env\n define define your environment in an Envfile\n validate validate .env file(s) against Envfile\n genexample [directory] generate .env.example\n gitignore append to .gitignore\n ls [directory] print all .env files in a tree structure\n prebuild [directory] prevent including .env files in docker\n precommit [directory] prevent committing .env files to code\n lock ⊡ lock private keys with a local passphrase\n native ⌥ move private keys in/out of your OS secret store\n 1password □ move private keys in/out of 1Password\n bitwarden □ move private keys in/out of Bitwarden\n armor ⛨ move private keys in/out of Dotenvx Armor [www.dotenvx.com/armor]\n curl ⛨ call authenticated api Dotenvx Armor [www.dotenvx.com/armor]\n\nRun directly: dotenvx <command>')
323
+ .addHelpText('after', '\nHidden Commands:\n protect protect secrets and private keys from code commits\n ls [directory] print all .env files in a tree structure\n genexample [directory] generate .env.example\n lock ⊡ lock private keys with a local passphrase\n native ⌥ move private keys in/out of your OS secret store\n 1password □ move private keys in/out of 1Password\n bitwarden □ move private keys in/out of Bitwarden\n armor ⛨ move private keys in/out of Dotenvx Armor [www.dotenvx.com/armor]\n curl ⛨ call authenticated api Dotenvx Armor [www.dotenvx.com/armor]\n\nBeta Commands:\n init create an Envfile from .env.example and .env\n define define your environment in an Envfile\n validate validate .env file(s) against Envfile\n\nDeprecated Commands:\n gitignore deprecated. use [dotenvx protect]\n precommit [directory] deprecated. use [dotenvx protect]\n prebuild [directory] deprecated. use [dotenvx protect --docker]\n\nRun directly: dotenvx <command>')
314
324
  .action(function () { this.outputHelp() })
315
325
 
316
326
  // dotenvx update
package/src/cli/help.js CHANGED
@@ -42,17 +42,18 @@ Try it:
42
42
 
43
43
  const prebuild = function () {
44
44
  return `
45
+ Deprecated. Use [dotenvx protect --docker].
46
+
45
47
  Examples:
46
48
 
47
49
  \`\`\`
48
- $ dotenvx prebuild
50
+ $ dotenvx protect --docker
49
51
  \`\`\`
50
52
 
51
53
  Try it:
52
54
 
53
55
  \`\`\`
54
- $ dotenvx prebuild
55
- [dotenvx@0.10.0][prebuild] success
56
+ $ dotenvx protect --docker apps/backend
56
57
  \`\`\`
57
58
  `
58
59
  }
@@ -0,0 +1,45 @@
1
+ const { Enquirer } = require('@dotenvx/tooling')
2
+
3
+ class Checklist extends Enquirer.prompts.MultiSelect {
4
+ constructor (options) {
5
+ super({
6
+ ...options,
7
+ pointer: '❯',
8
+ choices: [...options.choices, { name: '__submit', message: options.submitLabel, action: true }]
9
+ })
10
+ }
11
+
12
+ indicator (choice) {
13
+ if (choice.action) return ' '
14
+ return choice.enabled ? '●' : this.styles.muted('○')
15
+ }
16
+
17
+ async renderChoice (choice, index) {
18
+ if (choice.action && typeof this.options.submitLabel === 'function') {
19
+ choice.message = this.options.submitLabel(this.selected.map(item => item.name))
20
+ }
21
+ const line = await super.renderChoice(choice, index)
22
+ return choice.action ? '\n' + line : line
23
+ }
24
+
25
+ toggle (choice, enabled) {
26
+ if (choice.action) return choice
27
+ return super.toggle(choice, enabled)
28
+ }
29
+
30
+ submit () {
31
+ if (!this.focused || !this.focused.action) return this.space()
32
+ return super.submit()
33
+ }
34
+
35
+ get selected () {
36
+ return super.selected.filter(choice => !choice.action)
37
+ }
38
+
39
+ format () {
40
+ if (!this.state.submitted || this.state.cancelled) return ''
41
+ return this.selected.map(choice => this.styles.primary(choice.message)).join(', ')
42
+ }
43
+ }
44
+
45
+ module.exports = Checklist
@@ -0,0 +1,13 @@
1
+ const createSpinner = require('./createSpinner')
2
+
3
+ module.exports = async function createProtectSpinner (options = {}) {
4
+ // Git pipes stdin/stdout; only stderr can tell us whether a user is watching.
5
+ if (!process.stderr.isTTY || 'CI' in process.env || process.env.TERM === 'dumb') return null
6
+ const spinner = await createSpinner({ ...options, text: 'dotenvx protecting...', frames: ['⛉'] })
7
+ // Temporary, opt-in preview delay for checking the staging indicator.
8
+ const delay = Number(process.env.DOTENVX_PROTECT_PREVIEW_MS)
9
+ if (spinner && Number.isFinite(delay) && delay > 0) {
10
+ await new Promise(resolve => setTimeout(resolve, Math.min(delay, 5000)))
11
+ }
12
+ return spinner
13
+ }
@@ -2,6 +2,7 @@ const fs = require('fs')
2
2
  const Errors = require('./errors')
3
3
 
4
4
  const ENCODING = 'utf8'
5
+ const KEY_FILE_OPTIONS = { encoding: ENCODING, mode: 0o600 }
5
6
 
6
7
  async function readFileX (filepath, encoding = null) {
7
8
  if (!encoding) {
@@ -19,9 +20,9 @@ function readFileXSync (filepath, encoding = null) {
19
20
  return fs.readFileSync(filepath, encoding) // utf8 default so it returns a string
20
21
  }
21
22
 
22
- function writeFileXSync (filepath, str) {
23
+ function writeFileXSync (filepath, str, options = ENCODING) {
23
24
  try {
24
- return fs.writeFileSync(filepath, str, ENCODING) // utf8 always
25
+ return fs.writeFileSync(filepath, str, options)
25
26
  } catch (error) {
26
27
  if (error.code === 'EACCES' || error.code === 'EPERM') {
27
28
  throw new Errors({ filepath }).fileNotWritable()
@@ -31,9 +32,9 @@ function writeFileXSync (filepath, str) {
31
32
  }
32
33
  }
33
34
 
34
- async function writeFileX (filepath, str) {
35
+ async function writeFileX (filepath, str, options = ENCODING) {
35
36
  try {
36
- return await fs.promises.writeFile(filepath, str, ENCODING)
37
+ return await fs.promises.writeFile(filepath, str, options)
37
38
  } catch (error) {
38
39
  if (error.code === 'EACCES' || error.code === 'EPERM') {
39
40
  throw new Errors({ filepath }).fileNotWritable()
@@ -43,6 +44,14 @@ async function writeFileX (filepath, str) {
43
44
  }
44
45
  }
45
46
 
47
+ function writeKeyFile (filepath, str) {
48
+ return writeFileX(filepath, str, KEY_FILE_OPTIONS)
49
+ }
50
+
51
+ function writeKeyFileSync (filepath, str) {
52
+ return writeFileXSync(filepath, str, KEY_FILE_OPTIONS)
53
+ }
54
+
46
55
  async function exists (filepath) {
47
56
  try {
48
57
  await fs.promises.access(filepath)
@@ -65,7 +74,9 @@ const fsx = {
65
74
  readFileX,
66
75
  readFileXSync,
67
76
  writeFileX,
68
- writeFileXSync
77
+ writeFileXSync,
78
+ writeKeyFile,
79
+ writeKeyFileSync
69
80
  }
70
81
 
71
82
  module.exports = fsx
@@ -0,0 +1,11 @@
1
+ const { scan, encrypted } = require('@dotenvx/primitives')
2
+
3
+ function hasPlaintextSecrets (src) {
4
+ const { parsed } = scan(src)
5
+ return Object.entries(parsed).some(([key, values]) => {
6
+ if (key.startsWith('DOTENV_PUBLIC_KEY') || key.endsWith('_PLAIN')) return false
7
+ return values.some(value => value.trim() !== '' && !encrypted(value))
8
+ })
9
+ }
10
+
11
+ module.exports = hasPlaintextSecrets
@@ -79,3 +79,4 @@ class InstallPrecommitHook {
79
79
  }
80
80
 
81
81
  module.exports = InstallPrecommitHook
82
+ module.exports.HOOK_SCRIPT = HOOK_SCRIPT
@@ -0,0 +1,56 @@
1
+ const fs = require('fs')
2
+ const path = require('path')
3
+ const os = require('os')
4
+ const { execFileSync } = require('child_process')
5
+
6
+ const patterns = require('./precommitEnvPatterns')
7
+ const ATTRIBUTES = patterns.map(pattern => `${pattern.includes('/') ? '**/' : ''}${pattern} filter=dotenvx.protect`)
8
+
9
+ function quote (value) {
10
+ return "'" + value.replace(/'/g, "'\\''") + "'"
11
+ }
12
+
13
+ function installProtectFilter () {
14
+ const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim()
15
+ let attributesPath
16
+ try {
17
+ attributesPath = git('config', '--global', '--includes', '--path', '--get', 'core.attributesFile')
18
+ } catch (error) {
19
+ if (error.status !== 1) throw error
20
+ }
21
+ if (!attributesPath) {
22
+ attributesPath = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'git/attributes')
23
+ git('config', '--global', 'core.attributesFile', attributesPath)
24
+ }
25
+ let current = fs.existsSync(attributesPath) ? fs.readFileSync(attributesPath, 'utf8') : ''
26
+ // Use the installed executable, including standalone builds. Never download a
27
+ // replacement via npx while Git is handling secret input.
28
+ const executable = process.pkg
29
+ ? quote(process.execPath)
30
+ : `${quote(process.execPath)} ${quote(path.resolve(__dirname, '../../cli/dotenvx.js'))}`
31
+
32
+ // Git's filter_buffer_or_fd shell-quotes the filename with sq_quote_buf
33
+ // before substituting %f (convert.c). Keep the placeholder unquoted here.
34
+ git('config', '--global', 'filter.dotenvx.clean', `${executable} protect --git-file %f`)
35
+ git('config', '--global', 'filter.dotenvx.process', `${executable} protect --git-process`)
36
+ git('config', '--global', 'filter.dotenvx.required', 'true')
37
+ // Keep the old driver working for repositories with older attributes.
38
+ git('config', '--global', 'filter.dotenvx.protect.clean', `${executable} protect --git-file %f`)
39
+ git('config', '--global', 'filter.dotenvx.protect.process', `${executable} protect --git-process`)
40
+ git('config', '--global', 'filter.dotenvx.protect.required', 'true')
41
+ fs.mkdirSync(path.dirname(attributesPath), { recursive: true })
42
+ const migrated = current.split(/(?<=\n)/).map(line => {
43
+ const value = line.replace(/\r?\n$/, '')
44
+ return ATTRIBUTES.includes(value + '.protect') ? line.replace('filter=dotenvx', 'filter=dotenvx.protect') : line
45
+ }).join('')
46
+ if (migrated !== current) fs.writeFileSync(attributesPath, migrated)
47
+ current = migrated
48
+ const existing = new Set(current.split(/\r?\n/))
49
+ const missing = ATTRIBUTES.filter(attribute => !existing.has(attribute))
50
+ if (missing.length > 0) {
51
+ fs.appendFileSync(attributesPath, `${current && !current.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`)
52
+ }
53
+ return attributesPath
54
+ }
55
+
56
+ module.exports = installProtectFilter
@@ -0,0 +1,27 @@
1
+ const fs = require('fs')
2
+ const path = require('path')
3
+ const os = require('os')
4
+ const { execFileSync } = require('child_process')
5
+
6
+ function installProtectIgnore () {
7
+ const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim()
8
+ let ignorePath
9
+ try {
10
+ ignorePath = git('config', '--global', '--includes', '--path', '--get', 'core.excludesFile')
11
+ } catch (error) {
12
+ if (error.status !== 1) throw error
13
+ }
14
+ if (!ignorePath) {
15
+ ignorePath = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'git/ignore')
16
+ git('config', '--global', 'core.excludesFile', ignorePath)
17
+ }
18
+ const current = fs.existsSync(ignorePath) ? fs.readFileSync(ignorePath, 'utf8') : ''
19
+ if (!current.split(/\r?\n/).includes('.env.keys*')) {
20
+ fs.mkdirSync(path.dirname(ignorePath), { recursive: true })
21
+ fs.appendFileSync(ignorePath, `${current && !current.endsWith('\n') ? '\n' : ''}.env.keys*\n`)
22
+ git('config', '--global', 'dotenvx.protect.ignoreFile', ignorePath)
23
+ }
24
+ return ignorePath
25
+ }
26
+
27
+ module.exports = installProtectIgnore
@@ -0,0 +1,9 @@
1
+ const { logger } = require('../../shared/logger')
2
+
3
+ module.exports = function logProtectedFiles (files) {
4
+ const names = [...new Set(files)]
5
+ if (!names.length) return
6
+ const display = names.slice(0, 3).map(name => /^[\w./-]+$/.test(name) ? name : JSON.stringify(name))
7
+ if (names.length > 3) display.push(`+${names.length - 3} more`)
8
+ logger.success(`⛉ safe to commit (${display.join(', ')})`)
9
+ }
@@ -0,0 +1 @@
1
+ module.exports = ['.env*', '*.env', '.flaskenv', '.dev.vars*', '.env.d/*']
@@ -51,6 +51,29 @@ async function select ({ message, choices }, context) {
51
51
  return answer.value
52
52
  }
53
53
 
54
+ async function multiselect ({ message, choices, initial = [], submitLabel }, context) {
55
+ try {
56
+ const options = {
57
+ type: 'multiselect',
58
+ name: 'value',
59
+ message,
60
+ choices: choicesForSelect(choices),
61
+ initial,
62
+ ...enquirerOptions(context)
63
+ }
64
+ if (submitLabel) {
65
+ const Checklist = require('./checklist')
66
+ return await new Checklist({ ...options, submitLabel }).run()
67
+ }
68
+ const answer = await enquirer.prompt(options)
69
+ return answer.value
70
+ } catch {
71
+ const error = new Error('prompt cancelled')
72
+ error.code = 'PROMPT_CANCELLED'
73
+ throw error
74
+ }
75
+ }
76
+
54
77
  async function confirm ({ message, initial = false }, context) {
55
78
  try {
56
79
  const answer = await enquirer.prompt({
@@ -103,6 +126,7 @@ async function password ({ message, prefix, separator }, context) {
103
126
 
104
127
  module.exports = {
105
128
  confirm,
129
+ multiselect,
106
130
  password,
107
131
  select
108
132
  }
@@ -0,0 +1,63 @@
1
+ const fs = require('fs')
2
+ const path = require('path')
3
+ const os = require('os')
4
+ const { execFileSync } = require('child_process')
5
+ const patterns = require('./precommitEnvPatterns')
6
+
7
+ const git = (...args) => execFileSync('git', ['config', '--global', ...args], { encoding: 'utf8' }).trim()
8
+ function get (key, pathname = false) {
9
+ try { return git('--includes', ...(pathname ? ['--path'] : []), '--get', key) } catch (error) {
10
+ if (error.status !== 1) throw error
11
+ return ''
12
+ }
13
+ }
14
+ function file (key, name) {
15
+ return get(key, true) || path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'git', name)
16
+ }
17
+ function read (filename) {
18
+ return fs.existsSync(filename) ? fs.readFileSync(filename, 'utf8') : ''
19
+ }
20
+ function removeLines (filename, lines) {
21
+ const current = read(filename)
22
+ const updated = current.split(/(?<=\n)/).filter(line => !lines.includes(line.replace(/\r?\n$/, ''))).join('')
23
+ if (updated !== current) fs.writeFileSync(filename, updated)
24
+ }
25
+ function state () {
26
+ const attributes = read(file('core.attributesFile', 'attributes'))
27
+ const filter = ['dotenvx', 'dotenvx.protect'].some(driver => {
28
+ const clean = get(`filter.${driver}.clean`)
29
+ const processFilter = get(`filter.${driver}.process`)
30
+ const recognized = processFilter ? / protect --git-process$/.test(processFilter) : /(?:protect --git-file|precommit --clean) %f$/.test(clean)
31
+ return recognized && get(`filter.${driver}.required`) === 'true' && attributes.split(/\r?\n/).some(line => line.endsWith(` filter=${driver}`))
32
+ })
33
+ const ignore = read(file('core.excludesFile', 'ignore')).split(/\r?\n/).includes('.env.keys*')
34
+ return { filter, ignore, configured: get('dotenvx.protect.configured') === 'true' || filter || ignore }
35
+ }
36
+ function removeFilter () {
37
+ const drivers = ['dotenvx', 'dotenvx.protect']
38
+ for (const driver of drivers) {
39
+ const processFilter = get(`filter.${driver}.process`)
40
+ if (processFilter && !/ protect --git-process$/.test(processFilter)) throw new Error(`Custom filter.${driver}.process found; remove it manually to disable protection.`)
41
+ const clean = get(`filter.${driver}.clean`)
42
+ if (clean && clean !== 'cat' && !/(?:protect --git-file|precommit --clean) %f$/.test(clean)) {
43
+ throw new Error(`Custom filter.${driver}.clean found; remove it manually to disable protection.`)
44
+ }
45
+ }
46
+ removeLines(file('core.attributesFile', 'attributes'), drivers.flatMap(driver => patterns.map(pattern => `${pattern.includes('/') ? '**/' : ''}${pattern} filter=${driver}`)))
47
+ // Keep any remaining or inherited attributes harmless, including custom patterns.
48
+ for (const driver of drivers) {
49
+ git(`filter.${driver}.required`, 'false')
50
+ git(`filter.${driver}.process`, '')
51
+ git(`filter.${driver}.clean`, 'cat')
52
+ }
53
+ }
54
+ function removeIgnore () {
55
+ const filename = file('core.excludesFile', 'ignore')
56
+ if (!read(filename).split(/\r?\n/).includes('.env.keys*')) return
57
+ if (get('dotenvx.protect.ignoreFile', true) !== filename) {
58
+ throw new Error(`The existing .env.keys* rule in ${filename} has no dotenvx ownership record. Remove it manually to disable it; other ignore rules will be preserved.`)
59
+ }
60
+ removeLines(filename, ['.env.keys*'])
61
+ git('--unset-all', 'dotenvx.protect.ignoreFile')
62
+ }
63
+ module.exports = { state, removeFilter, removeIgnore, markConfigured: () => git('dotenvx.protect.configured', 'true') }
@@ -1,5 +1,6 @@
1
1
  const fs = require('fs')
2
2
  const path = require('path')
3
+ const fsx = require('./fsx')
3
4
 
4
5
  function escapeForRegex (value) {
5
6
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
@@ -34,7 +35,7 @@ function removeEnvKey (key, keysFilepath = '.env.keys') {
34
35
 
35
36
  if (hasRemainingKeys) {
36
37
  const nextSrc = `${nextLines.join(eol)}${eol}`
37
- fs.writeFileSync(resolvedKeysFilepath, nextSrc, 'utf8')
38
+ fsx.writeKeyFileSync(resolvedKeysFilepath, nextSrc)
38
39
  } else {
39
40
  fs.rmSync(resolvedKeysFilepath, { force: true })
40
41
  }
@@ -0,0 +1,42 @@
1
+ const path = require('path')
2
+ const fs = require('fs')
3
+ const patterns = require('./precommitEnvPatterns')
4
+ const { execFileSync } = require('child_process')
5
+
6
+ function isLegacy (command) {
7
+ const tokens = command.match(/'[^']*'|"[^"]*"|[^\s'";&|`$<>]+/g) || []
8
+ if (tokens.join(' ') !== command.trim()) return false
9
+ const args = tokens.map(token => /^['"]/.test(token) ? token.slice(1, -1) : token)
10
+ if (args.slice(-3).join(' ') !== 'precommit --clean %f') return false
11
+ const executable = args.slice(0, -3)
12
+ return (executable.length === 1 && path.basename(executable[0]) === 'dotenvx') ||
13
+ (executable.length === 2 && ['node', 'node.exe'].includes(path.basename(executable[0])) && path.basename(executable[1]) === 'dotenvx.js')
14
+ }
15
+
16
+ function removeLegacyProtectFilter (directory = process.cwd()) {
17
+ const git = (...args) => execFileSync('git', args, { cwd: directory, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim()
18
+ let commands
19
+ try {
20
+ commands = git('config', '--local', '--get-all', 'filter.dotenvx.clean').split('\n')
21
+ } catch (error) {
22
+ if (error.status === 128) return
23
+ if (error.status !== 1) throw error
24
+ commands = []
25
+ }
26
+ // Only remove an entirely recognized legacy registration, never custom shell commands.
27
+ if (!commands.every(isLegacy)) return
28
+ if (commands.length) git('config', '--local', '--unset-all', 'filter.dotenvx.clean')
29
+ try {
30
+ if (commands.length) git('config', '--local', '--fixed-value', '--unset-all', 'filter.dotenvx.required', 'true')
31
+ } catch (error) {
32
+ if (error.status !== 5) throw error
33
+ }
34
+ const attributesPath = path.resolve(directory, git('rev-parse', '--git-path', 'info/attributes'))
35
+ if (!fs.existsSync(attributesPath) || fs.lstatSync(attributesPath).isSymbolicLink()) return
36
+ const oldRules = patterns.map(pattern => `${pattern.includes('/') ? '**/' : ''}${pattern} filter=dotenvx`)
37
+ const source = fs.readFileSync(attributesPath, 'utf8')
38
+ 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
+ }
41
+
42
+ module.exports = removeLegacyProtectFilter
@@ -0,0 +1,66 @@
1
+ const fs = require('fs')
2
+ const path = require('path')
3
+ const { execFileSync } = require('child_process')
4
+ const { HOOK_SCRIPT } = require('./installPrecommitHook')
5
+
6
+ const LEGACY_SCRIPT = `#!/bin/sh
7
+
8
+ if command -v dotenvx 2>&1 >/dev/null
9
+ then
10
+ dotenvx ext precommit
11
+ elif npx dotenvx -V >/dev/null 2>&1
12
+ then
13
+ npx dotenvx ext precommit
14
+ else
15
+ echo "[dotenvx][precommit] 'dotenvx' command not found"
16
+ echo "[dotenvx][precommit] ? install it with [curl -fsS https://dotenvx.sh | sh]"
17
+ echo "[dotenvx][precommit] ? other install options [https://dotenvx.com/docs/install]"
18
+ exit 1
19
+ fi
20
+ `
21
+
22
+ function within (directory, file) {
23
+ const relative = path.relative(directory, file)
24
+ return relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative)
25
+ }
26
+
27
+ function uninstallPrecommitHook (directory = process.cwd()) {
28
+ const git = (...args) => execFileSync('git', args, { cwd: directory, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim()
29
+ let root
30
+ try {
31
+ root = git('rev-parse', '--show-toplevel')
32
+ } catch (error) {
33
+ if (error.status === 128) return { removed: false }
34
+ throw error
35
+ }
36
+ const hookPath = path.resolve(directory, git('rev-parse', '--git-path', 'hooks/pre-commit'))
37
+ const commonDir = path.resolve(directory, git('rev-parse', '--git-common-dir'))
38
+ const manual = () => ({ removed: false, warning: `pre-commit hook left unchanged; remove its dotenvx precommit entry manually [${hookPath}]` })
39
+ let stat
40
+ try {
41
+ stat = fs.lstatSync(hookPath)
42
+ } catch (error) {
43
+ if (error.code === 'ENOENT') return { removed: false }
44
+ throw error
45
+ }
46
+ // Never modify symlinked hooks or shared hooks outside this repository.
47
+ if (!stat.isFile() || (!within(root, fs.realpathSync(hookPath)) && !within(commonDir, fs.realpathSync(hookPath)))) return manual()
48
+ const source = fs.readFileSync(hookPath, 'utf8')
49
+ const templates = [HOOK_SCRIPT, LEGACY_SCRIPT, HOOK_SCRIPT.replaceAll('dotenvx precommit', 'dotenvx ext precommit'), LEGACY_SCRIPT.replaceAll('dotenvx ext precommit', 'dotenvx precommit')]
50
+ let next = source
51
+ for (const template of templates) {
52
+ for (const block of [template, template.replaceAll('\n', '\r\n')]) {
53
+ // Match whole, known installer blocks; do not guess at shell structure.
54
+ const escaped = block.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
55
+ next = next.replace(new RegExp('(^|\\n)' + escaped, 'g'), '$1')
56
+ }
57
+ }
58
+ if (next === source) {
59
+ return /dotenvx\s+(?:ext\s+)?precommit/.test(source) ? manual() : { removed: false }
60
+ }
61
+ if (next.trim() === '') fs.unlinkSync(hookPath)
62
+ else fs.writeFileSync(hookPath, next, 'utf8')
63
+ return { removed: true, warning: /dotenvx\s+(?:ext\s+)?precommit/.test(next) ? manual().warning : undefined }
64
+ }
65
+
66
+ module.exports = uninstallPrecommitHook
@@ -1,5 +1,6 @@
1
1
  const fs = require('fs')
2
2
  const path = require('path')
3
+ const fsx = require('./fsx')
3
4
 
4
5
  function escapeForRegex (value) {
5
6
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
@@ -46,7 +47,7 @@ function upsertEnvKey (key, value, keysFilepath = '.env.keys') {
46
47
  const changed = created || nextSrc !== src
47
48
 
48
49
  if (changed) {
49
- fs.writeFileSync(resolvedKeysFilepath, nextSrc, 'utf8')
50
+ fsx.writeKeyFileSync(resolvedKeysFilepath, nextSrc)
50
51
  }
51
52
 
52
53
  return {
package/src/lib/main.js CHANGED
@@ -266,7 +266,7 @@ const set = async function (key, value, options = {}) {
266
266
  })
267
267
 
268
268
  if (keysSrc) {
269
- fsx.writeFileXSync(envKeysFilepath || '.env.keys', keysSrc)
269
+ fsx.writeKeyFileSync(envKeysFilepath || '.env.keys', keysSrc)
270
270
  }
271
271
 
272
272
  let withEncryption = ''
@@ -5,7 +5,7 @@ const { ignore } = require('@dotenvx/tooling')
5
5
 
6
6
  const ls = require('../resolvers/ls')
7
7
  const Errors = require('../helpers/errors')
8
- const { sealed } = require('@dotenvx/primitives')
8
+ const hasPlaintextSecrets = require('../helpers/hasPlaintextSecrets')
9
9
 
10
10
  const MISSING_DOCKERIGNORE = '.env.keys' // by default only ignore .env.keys. all other .env* files COULD be included - as long as they are encrypted
11
11
 
@@ -53,13 +53,12 @@ class Prebuild {
53
53
  } else {
54
54
  if (file !== '.env.example' && file !== '.env.vault' && file !== '.env.x') {
55
55
  const src = fsx.readFileXSync(file)
56
- const encrypted = sealed(src)
56
+ const privateKeyFile = path.basename(file).startsWith('.env.keys')
57
57
 
58
- // if contents are encrypted don't raise an error
59
- if (!encrypted) {
58
+ if (privateKeyFile || hasPlaintextSecrets(src)) {
60
59
  let errorMsg = `${file} not encrypted/dockerignored`
61
60
  let errorHelp = `fix: [dotenvx encrypt -f ${file}] or [dotenvx gitignore --pattern ${file}]`
62
- if (file.includes('.env.keys')) {
61
+ if (privateKeyFile) {
63
62
  errorMsg = `${file} not dockerignored`
64
63
  errorHelp = `fix: [dotenvx gitignore --pattern ${file}]`
65
64
  }
@@ -17,14 +17,10 @@ class Precommit {
17
17
  this.directory = directory
18
18
  // options
19
19
  this.install = options.install
20
- this.global = options.global
21
20
  this.excludeEnvFile = ['test/**', 'tests/**', 'spec/**', 'specs/**', 'pytest/**', 'test_suite/**']
22
21
  }
23
22
 
24
23
  run () {
25
- if (this.global && !this.install) {
26
- throw new Error('--global requires --install')
27
- }
28
24
  if (this.install) {
29
25
  const {
30
26
  successMessage
@@ -107,6 +103,7 @@ class Precommit {
107
103
  _filepaths () {
108
104
  return ls.sync({
109
105
  directory: this.directory,
106
+ envFile: require('../helpers/precommitEnvPatterns'),
110
107
  excludeEnvFile: this.excludeEnvFile
111
108
  })
112
109
  }
@@ -140,14 +137,7 @@ class Precommit {
140
137
  }
141
138
 
142
139
  _installPrecommitHook () {
143
- if (this.global) {
144
- const attributesPath = require('../helpers/installPrecommitFilter')(true)
145
- return { successMessage: `▣ dotenvx required clean filter installed globally [${attributesPath}]` }
146
- }
147
- const hookPath = require('../helpers/installPrecommitFilter')()
148
- const result = new InstallPrecommitHook(hookPath).run()
149
- result.successMessage += '\n▣ dotenvx required clean filter installed (blocks staging plaintext .env files)'
150
- return result
140
+ return new InstallPrecommitHook().run()
151
141
  }
152
142
  }
153
143
 
@@ -1,21 +0,0 @@
1
- const fs = require('fs')
2
- const path = require('path')
3
- const { sealed } = require('@dotenvx/primitives')
4
-
5
- function precommitClean (filepath) {
6
- try {
7
- const content = fs.readFileSync(0)
8
- const filename = path.posix.basename(filepath)
9
- const exempt = ['.env.example', '.env.vault', '.env.x'].includes(filename)
10
- if (filename.startsWith('.env.keys') || (!exempt && !sealed(content.toString('utf8')))) {
11
- throw new Error(`refusing to stage ${JSON.stringify(filepath)}: encrypt this env file or add it to .gitignore`)
12
- }
13
- // stdout is Git's blob content: no logging, normalization, or extra newline.
14
- process.stdout.write(content)
15
- } catch (error) {
16
- process.stderr.write(`dotenvx: ${error.message}\n`)
17
- process.exitCode = 1
18
- }
19
- }
20
-
21
- module.exports = precommitClean
@@ -1,50 +0,0 @@
1
- const fs = require('fs')
2
- const path = require('path')
3
- const os = require('os')
4
- const { execFileSync } = require('child_process')
5
-
6
- const ATTRIBUTE = '.env* filter=dotenvx'
7
-
8
- function quote (value) {
9
- return "'" + value.replace(/'/g, "'\\''") + "'"
10
- }
11
-
12
- function installPrecommitFilter (global = false) {
13
- const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim()
14
- let attributesPath
15
- if (global) {
16
- try {
17
- attributesPath = git('config', '--global', '--includes', '--path', '--get', 'core.attributesFile')
18
- } catch (error) {
19
- if (error.status !== 1) throw error
20
- }
21
- if (!attributesPath) {
22
- attributesPath = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'git/attributes')
23
- git('config', '--global', 'core.attributesFile', attributesPath)
24
- }
25
- } else {
26
- attributesPath = git('rev-parse', '--git-path', 'info/attributes')
27
- }
28
- const hookPath = global ? null : git('rev-parse', '--git-path', 'hooks/pre-commit')
29
- const current = fs.existsSync(attributesPath) ? fs.readFileSync(attributesPath, 'utf8') : ''
30
- // Use the installed executable, including standalone builds. Never download a
31
- // replacement via npx while Git is handling secret input.
32
- const executable = process.pkg
33
- ? quote(process.execPath)
34
- : `${quote(process.execPath)} ${quote(path.resolve(__dirname, '../../cli/dotenvx.js'))}`
35
-
36
- const scope = global ? '--global' : '--local'
37
- // Git's filter_buffer_or_fd shell-quotes the filename with sq_quote_buf
38
- // before substituting %f (convert.c). Keep the placeholder unquoted here.
39
- git('config', scope, 'filter.dotenvx.clean', `${executable} precommit --clean %f`)
40
- git('config', scope, 'filter.dotenvx.required', 'true')
41
- fs.mkdirSync(path.dirname(attributesPath), { recursive: true })
42
- if (!current.split(/\r?\n/).includes(ATTRIBUTE)) {
43
- fs.appendFileSync(attributesPath, `${current && !current.endsWith('\n') ? '\n' : ''}${ATTRIBUTE}\n`)
44
- }
45
- if (global) return attributesPath
46
- fs.mkdirSync(path.dirname(hookPath), { recursive: true })
47
- return hookPath
48
- }
49
-
50
- module.exports = installPrecommitFilter