@dotenvx/dotenvx 2.28.2 → 2.30.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 (82) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/README.md +47 -12
  3. package/package.json +3 -3
  4. package/src/cli/actions/armor/down.js +1 -1
  5. package/src/cli/actions/armor/move.js +1 -1
  6. package/src/cli/actions/armor/open.js +1 -1
  7. package/src/cli/actions/armor/pull.js +1 -1
  8. package/src/cli/actions/armor/push.js +1 -1
  9. package/src/cli/actions/armor/up.js +1 -1
  10. package/src/cli/actions/curl.js +2 -2
  11. package/src/cli/actions/decrypt.js +4 -10
  12. package/src/cli/actions/define.js +1 -1
  13. package/src/cli/actions/del.js +3 -5
  14. package/src/cli/actions/encrypt.js +4 -10
  15. package/src/cli/actions/ext/genexample.js +1 -1
  16. package/src/cli/actions/ext/gitignore.js +1 -0
  17. package/src/cli/actions/ext/prebuild.js +5 -28
  18. package/src/cli/actions/ext/precommit.js +8 -3
  19. package/src/cli/actions/ext/scan.js +2 -3
  20. package/src/cli/actions/get.js +4 -7
  21. package/src/cli/actions/keychain/down.js +1 -1
  22. package/src/cli/actions/keychain/pull.js +1 -1
  23. package/src/cli/actions/keychain/push.js +1 -1
  24. package/src/cli/actions/keychain/up.js +1 -1
  25. package/src/cli/actions/keypair.js +3 -3
  26. package/src/cli/actions/lock/down.js +2 -3
  27. package/src/cli/actions/lock/up.js +2 -3
  28. package/src/cli/actions/login.js +2 -2
  29. package/src/cli/actions/logout.js +1 -1
  30. package/src/cli/actions/ls.js +1 -1
  31. package/src/cli/actions/protect.js +75 -0
  32. package/src/cli/actions/protectDocker.js +30 -0
  33. package/src/cli/actions/protectProcess.js +126 -0
  34. package/src/cli/actions/protectStdin.js +64 -0
  35. package/src/cli/actions/run.js +5 -6
  36. package/src/cli/actions/set.js +5 -9
  37. package/src/cli/actions/settings/device.js +2 -2
  38. package/src/cli/actions/settings/hostname.js +2 -2
  39. package/src/cli/actions/settings/off.js +1 -1
  40. package/src/cli/actions/settings/on.js +1 -1
  41. package/src/cli/actions/settings/path.js +2 -2
  42. package/src/cli/actions/settings/token.js +2 -2
  43. package/src/cli/actions/settings/username.js +2 -2
  44. package/src/cli/actions/validate.js +2 -2
  45. package/src/cli/commandAction.js +16 -0
  46. package/src/cli/commands/armor.js +10 -9
  47. package/src/cli/commands/custody.js +6 -4
  48. package/src/cli/commands/ext.js +7 -7
  49. package/src/cli/commands/lock.js +3 -2
  50. package/src/cli/commands/native.js +5 -4
  51. package/src/cli/commands/settings.js +8 -7
  52. package/src/cli/dotenvx.js +31 -17
  53. package/src/cli/help.js +4 -3
  54. package/src/lib/events/backends/armor.js +31 -0
  55. package/src/lib/events/background.js +59 -0
  56. package/src/lib/events/catalog.js +14 -0
  57. package/src/lib/events/cli.js +40 -0
  58. package/src/lib/events/delivery.js +89 -0
  59. package/src/lib/events/index.js +73 -0
  60. package/src/lib/events/metadata.js +25 -0
  61. package/src/lib/events/sdk.js +44 -0
  62. package/src/lib/events/worker.js +29 -0
  63. package/src/lib/events/workerEnvironment.js +14 -0
  64. package/src/lib/helpers/checklist.js +50 -0
  65. package/src/lib/helpers/createProtectSpinner.js +13 -0
  66. package/src/lib/helpers/executeCommand.js +12 -1
  67. package/src/lib/helpers/hasPlaintextSecrets.js +7 -0
  68. package/src/lib/helpers/installPrecommitHook.js +1 -0
  69. package/src/lib/helpers/installProtectFilter.js +56 -0
  70. package/src/lib/helpers/installProtectIgnore.js +27 -0
  71. package/src/lib/helpers/logProtectedFiles.js +9 -0
  72. package/src/lib/helpers/precommitEnvPatterns.js +1 -0
  73. package/src/lib/helpers/prompts.js +24 -0
  74. package/src/lib/helpers/protectSettings.js +63 -0
  75. package/src/lib/helpers/removeLegacyProtectFilter.js +42 -0
  76. package/src/lib/helpers/uninstallPrecommitHook.js +66 -0
  77. package/src/lib/main.d.ts +14 -0
  78. package/src/lib/main.js +11 -3
  79. package/src/lib/services/prebuild.js +4 -5
  80. package/src/lib/services/precommit.js +2 -12
  81. package/src/cli/actions/ext/precommitClean.js +0 -21
  82. package/src/lib/helpers/installPrecommitFilter.js +0 -50
@@ -0,0 +1,44 @@
1
+ const createEvents = require('./index')
2
+
3
+ // An explicit, scoped SDK facade. Sync methods stay sync; applications can flush
4
+ // completed calls before shutdown without global hooks or process.exit changes.
5
+ module.exports = function withEvents (sdk, config = {}) {
6
+ const pending = new Set()
7
+
8
+ function complete (events) {
9
+ const completion = events.complete().catch(() => {})
10
+ pending.add(completion)
11
+ completion.finally(() => pending.delete(completion))
12
+ }
13
+
14
+ function invoke (name, options, metadata, action) {
15
+ const events = createEvents(`sdk/${name}`, options, config)
16
+ events.add(metadata)
17
+ try {
18
+ const result = action(events)
19
+ if (result && typeof result.then === 'function') {
20
+ return result.then(value => {
21
+ complete(events)
22
+ return value
23
+ }, error => {
24
+ events.fail(error)
25
+ complete(events)
26
+ throw error
27
+ })
28
+ }
29
+ complete(events)
30
+ return result
31
+ } catch (error) {
32
+ events.fail(error)
33
+ complete(events)
34
+ throw error
35
+ }
36
+ }
37
+
38
+ return {
39
+ config: (options = {}) => invoke('config', options, {}, events => sdk.config(options, events)),
40
+ get: (key, options = {}) => invoke('get', options, { key }, events => sdk.get(key, options, events)),
41
+ set: (key, value, options = {}) => invoke('set', options, { key }, events => sdk.set(key, value, options, events)),
42
+ async flushEvents () { await Promise.all([...pending]) }
43
+ }
44
+ }
@@ -0,0 +1,29 @@
1
+ const armor = require('./backends/armor')
2
+
3
+ // Internal, short-lived worker. No output, local logs, or retries.
4
+ module.exports = function deliverEvents () {
5
+ let input = ''
6
+ const stop = () => process.exit(0)
7
+ const timer = setTimeout(stop, 5000)
8
+ process.stdin.setEncoding('utf8')
9
+ process.stdin.on('error', stop)
10
+ process.stdin.on('data', chunk => {
11
+ input += chunk
12
+ if (Buffer.byteLength(input) > 1024 * 1024) stop()
13
+ })
14
+ process.stdin.on('end', async () => {
15
+ try {
16
+ const { options, events } = JSON.parse(input)
17
+ if (!Array.isArray(events) || events.length > 256) return
18
+ const backend = armor(options)
19
+ if (backend) {
20
+ for (let offset = 0; offset < events.length; offset += 50) {
21
+ await backend.send(events.slice(offset, offset + 50), { signal: AbortSignal.timeout(500) })
22
+ }
23
+ }
24
+ } catch {} finally {
25
+ clearTimeout(timer)
26
+ stop()
27
+ }
28
+ })
29
+ }
@@ -0,0 +1,14 @@
1
+ // Only account discovery, native credential-store access, and network settings.
2
+ // In particular, do not propagate application secrets or runtime injection flags.
3
+ const allowed = new Set([
4
+ 'DOTENVX_CONFIG', 'DOTENVX_NO_ARMOR',
5
+ 'HOME', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH', 'APPDATA', 'LOCALAPPDATA',
6
+ 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_RUNTIME_DIR', 'DBUS_SESSION_BUS_ADDRESS',
7
+ 'PATH', 'PATHEXT', 'SYSTEMROOT', 'WINDIR', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL',
8
+ 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY',
9
+ 'NODE_EXTRA_CA_CERTS', 'NODE_USE_SYSTEM_CA', 'SSL_CERT_FILE', 'SSL_CERT_DIR'
10
+ ])
11
+
12
+ module.exports = function workerEnvironment (env = process.env) {
13
+ return Object.fromEntries(Object.entries(env).filter(([key]) => allowed.has(key.toUpperCase())))
14
+ }
@@ -0,0 +1,50 @@
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
+ async render () {
40
+ if (this.state.submitted && !this.state.cancelled) {
41
+ this.clear(this.state.size)
42
+ this.state.prompt = ''
43
+ this.state.size = 0
44
+ return
45
+ }
46
+ return super.render()
47
+ }
48
+ }
49
+
50
+ 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
+ }
@@ -5,6 +5,7 @@ const { logger } = require('./../../shared/logger')
5
5
  const Errors = require('./errors')
6
6
  const { createRedactedStreamWriter, redactOutput } = require('./redactOutput')
7
7
  const ptyCommand = require('./ptyCommand')
8
+ const { finished } = require('stream/promises')
8
9
 
9
10
  async function executeCommand (commandArgs, env, sensitiveValues = [], onComplete) {
10
11
  const FORWARD_SIGNAL_GRACE_MS = 1000
@@ -18,8 +19,11 @@ async function executeCommand (commandArgs, env, sensitiveValues = [], onComplet
18
19
 
19
20
  let child
20
21
  let commandExitCode
22
+ let commandError
23
+ let commandSignal
21
24
  let signalSent
22
25
  let sigintCount = 0
26
+ const outputFinished = []
23
27
  const signalForwardTimers = new Set()
24
28
  const otherSignalHandlers = new Map()
25
29
  const isInteractiveTTY = Boolean(process.stdin && process.stdin.isTTY)
@@ -137,12 +141,14 @@ async function executeCommand (commandArgs, env, sensitiveValues = [], onComplet
137
141
  const stdoutWriter = createRedactedStreamWriter(process.stdout, sensitiveValues, child.stdout)
138
142
  child.stdout.on('data', stdoutWriter.write)
139
143
  child.stdout.once('end', stdoutWriter.flush)
144
+ outputFinished.push(finished(child.stdout).catch(() => {}))
140
145
  }
141
146
 
142
147
  if (redactStderr && child.stderr) {
143
148
  const stderrWriter = createRedactedStreamWriter(process.stderr, sensitiveValues, child.stderr)
144
149
  child.stderr.on('data', stderrWriter.write)
145
150
  child.stderr.once('end', stderrWriter.flush)
151
+ outputFinished.push(finished(child.stderr).catch(() => {}))
146
152
  }
147
153
 
148
154
  process.on('SIGINT', sigintHandler)
@@ -164,6 +170,8 @@ async function executeCommand (commandArgs, env, sensitiveValues = [], onComplet
164
170
  throw error
165
171
  }
166
172
  } catch (error) {
173
+ commandSignal = signalSent || error.signal
174
+ if (error.code === 'ENOENT') commandError = { code: 'COMMAND_NOT_FOUND' }
167
175
  const commandExited = Number.isInteger(error.exitCode) && (error.code === 'COMMAND_EXITED_WITH_CODE' || error.command)
168
176
 
169
177
  // no color on these errors as they can be standard errors for things like jest exiting with exitCode 1 for a single failed test.
@@ -178,6 +186,9 @@ async function executeCommand (commandArgs, env, sensitiveValues = [], onComplet
178
186
  // Exit with the error code from the command process, or 1 if unavailable
179
187
  commandExitCode = error.exitCode || 1
180
188
  } finally {
189
+ // Child exit can precede pipe EOF. Let redaction flush its held-back tail
190
+ // before the action returns and the CLI exits.
191
+ await Promise.all(outputFinished)
181
192
  signalForwardTimers.forEach(timer => clearTimeout(timer))
182
193
  signalForwardTimers.clear()
183
194
 
@@ -192,7 +203,7 @@ async function executeCommand (commandArgs, env, sensitiveValues = [], onComplet
192
203
  if (onComplete) await onComplete()
193
204
  }
194
205
 
195
- if (commandExitCode) process.exit(commandExitCode)
206
+ return { exitCode: commandExitCode || 0, signal: commandSignal, error: commandError }
196
207
  }
197
208
 
198
209
  module.exports = executeCommand
@@ -0,0 +1,7 @@
1
+ const { sealed } = require('@dotenvx/primitives')
2
+
3
+ function hasPlaintextSecrets (src) {
4
+ return !sealed(src)
5
+ }
6
+
7
+ 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') }
@@ -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
package/src/lib/main.d.ts CHANGED
@@ -1,5 +1,19 @@
1
1
  import type { URL } from 'url';
2
2
 
3
+ export interface EventSdk {
4
+ config: typeof config;
5
+ get: typeof get;
6
+ set: typeof set;
7
+ /** Flush event delivery for calls that have completed. Await operations first. */
8
+ flushEvents(): Promise<void>;
9
+ }
10
+
11
+ /**
12
+ * Create an explicitly instrumented SDK client using connected Armor. config() remains synchronous;
13
+ * get()/set() preserve their results and errors. Plain SDK calls are unchanged.
14
+ */
15
+ export function withEvents(): EventSdk;
16
+
3
17
  export interface DotenvParseOptions {
4
18
  /**
5
19
  * Override any environment variables that have already been set on your machine with values from your .env file.
package/src/lib/main.js CHANGED
@@ -42,7 +42,7 @@ function uniqueInjectedKeys (processedEnvs) {
42
42
  }
43
43
 
44
44
  /** @type {import('./main').config} */
45
- const config = function (options = {}) {
45
+ const config = function (options = {}, events) {
46
46
  options = normalizeDotenvConfigQuiet(options)
47
47
  options = normalizeDotenvConfigConvention(options)
48
48
  options = normalizeDotenvConfigIgnore(options)
@@ -148,6 +148,7 @@ const config = function (options = {}) {
148
148
  }
149
149
  }
150
150
 
151
+ if (events) events.add({ files: readableFilepaths, injected_count: uniqueInjectedKeys(processedEnvs).size })
151
152
  let msg = `injected env (${uniqueInjectedKeys(processedEnvs).size})`
152
153
  if (readableFilepaths.length > 0) {
153
154
  msg += ` from ${readableFilepaths.join(', ')}`
@@ -155,11 +156,13 @@ const config = function (options = {}) {
155
156
  logger.success(`⟐ ${msg}`)
156
157
 
157
158
  if (lastError) {
159
+ if (events) events.fail(lastError)
158
160
  return { parsed: parsedAll, error: lastError }
159
161
  } else {
160
162
  return { parsed: parsedAll }
161
163
  }
162
164
  } catch (error) {
165
+ if (events) events.fail(error)
163
166
  if (strict) throw error // throw immediately if strict
164
167
 
165
168
  logger.error(error.messageWithHelp || error.message)
@@ -223,7 +226,7 @@ const parse = function (src, options = {}) {
223
226
  }
224
227
 
225
228
  /* @type {import('./main').set} */
226
- const set = async function (key, value, options = {}) {
229
+ const set = async function (key, value, options = {}, events) {
227
230
  options = normalizeDotenvConfigQuiet(options)
228
231
 
229
232
  // encrypt
@@ -288,7 +291,9 @@ const set = async function (key, value, options = {}) {
288
291
  logger.verbose(`${processedEnv.key} set${withEncryption} (${processedEnv.envFilepath})`)
289
292
  logger.debug(`${processedEnv.key} set${withEncryption} to ${processedEnv.value} (${processedEnv.envFilepath})`)
290
293
  }
294
+ if (events) events.file(processedEnv, { key, output: 'file' })
291
295
  }
296
+ if (events) events.add({ error_count: processedEnvs.filter(env => env.error).length })
292
297
 
293
298
  let keyAddedSuffix = ''
294
299
  const localKeyAddedEnv = processedEnvs.find((processedEnv) => processedEnv.localPrivateKeyAdded)
@@ -323,7 +328,7 @@ const set = async function (key, value, options = {}) {
323
328
  }
324
329
 
325
330
  /* @type {import('./main').get} */
326
- const get = async function (key, options = {}) {
331
+ const get = async function (key, options = {}, events) {
327
332
  options = normalizeDotenvConfigConvention(options)
328
333
  options = normalizeDotenvConfigIgnore(options)
329
334
 
@@ -359,11 +364,13 @@ const get = async function (key, options = {}) {
359
364
  continue // ignore error
360
365
  }
361
366
 
367
+ if (events) events.fail(error)
362
368
  if (options.strict) throw error // throw immediately if strict
363
369
 
364
370
  logger.error(error.messageWithHelp || error.message)
365
371
  }
366
372
 
373
+ if (events) events.add({ error_count: (errors || []).filter(error => !ignore.includes(error.code)).length })
367
374
  if (key) {
368
375
  const single = parsed[key]
369
376
  if (single === undefined) {
@@ -418,6 +425,7 @@ function resolveNoNative (options = {}) {
418
425
  }
419
426
 
420
427
  module.exports = {
428
+ withEvents: () => require('./events/sdk')({ config, get, set }),
421
429
  // dotenv proxies
422
430
  config,
423
431
  parse,