@dotenvx/dotenvx 2.32.4 → 2.34.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 (90) hide show
  1. package/CHANGELOG.md +22 -1
  2. package/README.md +24 -26
  3. package/package.json +5 -13
  4. package/src/cli/actions/check.js +6 -11
  5. package/src/cli/actions/encrypt.js +2 -2
  6. package/src/cli/actions/get.js +4 -5
  7. package/src/cli/actions/init.js +4 -4
  8. package/src/cli/actions/keypair.js +1 -0
  9. package/src/cli/actions/policy.js +14 -0
  10. package/src/cli/actions/primitivesCheck.js +32 -0
  11. package/src/cli/actions/primitivesProfile.js +15 -0
  12. package/src/cli/actions/primitivesRedact.js +19 -0
  13. package/src/cli/actions/protectStdin.js +2 -2
  14. package/src/cli/actions/run.js +8 -46
  15. package/src/cli/actions/set.js +1 -1
  16. package/src/cli/commands/primitives.js +28 -1
  17. package/src/cli/dotenvx.js +6 -6
  18. package/src/db/session.js +1 -1
  19. package/src/lib/custodians/index.js +12 -10
  20. package/src/lib/custodians/local/bitwarden.js +5 -15
  21. package/src/lib/custodians/local/native/backend.js +4 -10
  22. package/src/lib/custodians/local/native/index.js +1 -1
  23. package/src/lib/custodians/local/onepassword.js +7 -29
  24. package/src/lib/custodians/managed/armor/index.js +0 -10
  25. package/src/lib/custodians/resolveLocalKey.js +3 -4
  26. package/src/lib/decryptors/armor/index.js +6 -7
  27. package/src/lib/{envspec → envfile}/discovery/discoverEnvFiles.js +1 -1
  28. package/src/lib/{envspec → envfile}/discovery/scanSource.js +1 -1
  29. package/src/lib/{envspec/parsing/formatEnvspecSyntaxError.js → envfile/parsing/formatEnvfileSyntaxError.js} +1 -1
  30. package/src/lib/envfile/parsing/readEnvfile.js +43 -0
  31. package/src/lib/envfile/parsing/resolveEnvfilePath.js +5 -0
  32. package/src/lib/{envspec/rendering/normalizeEnvspec.js → envfile/rendering/normalizeEnvfile.js} +1 -1
  33. package/src/lib/{envspec/rendering/previewEnvspec.js → envfile/rendering/previewEnvfile.js} +7 -15
  34. package/src/lib/{envspec/rendering/renderEnvspec.js → envfile/rendering/renderEnvfile.js} +3 -3
  35. package/src/lib/{envspec/validation/protectEnvspec.js → envfile/validation/protectEnvfile.js} +7 -7
  36. package/src/lib/envfile/validation/validateEnvfile.js +14 -0
  37. package/src/lib/helpers/errors.js +3 -25
  38. package/src/lib/helpers/executeCommand.js +1 -2
  39. package/src/lib/helpers/matchesStoredKey.js +1 -12
  40. package/src/lib/helpers/parseWithDecryptor.js +27 -12
  41. package/src/lib/helpers/redactOutput.js +30 -32
  42. package/src/lib/helpers/redactProcessOutput.js +58 -0
  43. package/src/lib/helpers/redactedValues.js +2 -2
  44. package/src/lib/helpers/selectEnvfileEnvs.js +29 -0
  45. package/src/lib/helpers/selectKeyStorage.js +1 -1
  46. package/src/lib/helpers/storeKeyStorage.js +0 -1
  47. package/src/lib/main.d.ts +12 -6
  48. package/src/lib/main.js +16 -29
  49. package/src/lib/providers/index.js +53 -53
  50. package/src/lib/resolvers/envs.js +7 -26
  51. package/src/lib/resolvers/get.js +2 -3
  52. package/src/lib/resolvers/keypair.js +39 -4
  53. package/src/lib/services/init.js +4 -4
  54. package/src/lib/services/validate.js +20 -32
  55. package/src/lib/transforms/encrypt.js +5 -5
  56. package/src/lib/transforms/set.js +5 -3
  57. package/src/cli/actions/lock/down.js +0 -54
  58. package/src/cli/actions/lock/up.js +0 -62
  59. package/src/cli/commands/lock.js +0 -36
  60. package/src/lib/api/postArmorDecrypt.js +0 -49
  61. package/src/lib/api/postArmorKeyring.js +0 -50
  62. package/src/lib/custodians/lock.js +0 -80
  63. package/src/lib/custodians/managed/armor/get.js +0 -44
  64. package/src/lib/envspec/parsing/envspec.peggy +0 -105
  65. package/src/lib/envspec/parsing/envspecParser.js +0 -2851
  66. package/src/lib/envspec/parsing/readEnvspec.js +0 -144
  67. package/src/lib/envspec/parsing/resolveEnvspecPath.js +0 -11
  68. package/src/lib/envspec/validation/encryptedSources.js +0 -15
  69. package/src/lib/envspec/validation/validate.js +0 -109
  70. package/src/lib/envspec/validation/validateEnvspec.js +0 -57
  71. package/src/lib/helpers/isValidEmail.js +0 -11
  72. package/src/lib/helpers/isValidUrl.js +0 -9
  73. package/src/lib/helpers/lockedValue.js +0 -24
  74. package/src/lib/helpers/resolveLockPassword.js +0 -5
  75. package/src/lib/helpers/unlockedValue.js +0 -26
  76. package/src/lib/helpers/withLockedKeys.js +0 -41
  77. package/src/lib/providers/provider-worker.js +0 -6
  78. package/src/lib/proxy/configureProxy.js +0 -55
  79. package/src/lib/proxy/eligibleHeaders.js +0 -16
  80. package/src/lib/proxy/prepareProxy.js +0 -24
  81. package/src/lib/proxy/proxyCertificates.js +0 -44
  82. package/src/lib/proxy/proxyForward.js +0 -65
  83. package/src/lib/proxy/proxyPreload.js +0 -21
  84. package/src/lib/proxy/proxyPreloadSource.js +0 -3
  85. package/src/lib/proxy/proxyServer.js +0 -175
  86. package/src/lib/services/armorKeyring.js +0 -119
  87. package/src/lib/services/lockDown.js +0 -157
  88. package/src/lib/services/lockUp.js +0 -150
  89. /package/src/lib/{envspec → envfile}/discovery/extractEnvKeys.js +0 -0
  90. /package/src/lib/{envspec → envfile}/validation/diagnosticLocation.js +0 -0
@@ -27,9 +27,36 @@ function output (operation, required = false) {
27
27
 
28
28
  module.exports = function primitives (command) {
29
29
  command
30
- .description('standalone primitives without env file reads or writes')
30
+ .description('standalone primitive operations')
31
31
  .action(function () { this.help() })
32
32
 
33
+ command.command('profile')
34
+ .description('resolve an Envfile profile to comma-separated filenames')
35
+ .option('--profile <name>', 'explicit profile name')
36
+ .option('-f, --file <paths>', 'explicit comma-separated files, overriding profile selection', (value, previous) => previous === undefined ? value : `${previous},${value}`)
37
+ .allowExcessArguments(false)
38
+ .action(commandAction(require('../actions/primitivesProfile')))
39
+
40
+ command.command('redact')
41
+ .description('replace secret strings in text with [REDACTED]')
42
+ .argument('[text]', 'text to redact')
43
+ .requiredOption('-s, --secret <value>', 'literal secret to redact (repeat for multiple secrets)', (value, previous) => [...(previous || []), value])
44
+ .option('--stdin', 'read text from stdin')
45
+ .allowExcessArguments(false)
46
+ .action(commandAction(require('../actions/primitivesRedact')))
47
+
48
+ command.command('policy')
49
+ .description('print the Envfile policy for selected files as JSON')
50
+ .option('-f, --file <paths>', 'comma-separated env files, first file wins (default: .env)', (value, previous) => previous === undefined ? value : `${previous},${value}`)
51
+ .allowExcessArguments(false)
52
+ .action(commandAction(require('../actions/policy')))
53
+
54
+ command.command('check')
55
+ .description('check selected env files against Envfile and print redacted JSON')
56
+ .option('-f, --file <paths>', 'comma-separated env files, first file wins (default: .env)', (value, previous) => previous === undefined ? value : `${previous},${value}`)
57
+ .allowExcessArguments(false)
58
+ .action(commandAction(require('../actions/primitivesCheck')))
59
+
33
60
  command.command('keypair')
34
61
  .description('generate or restore a keypair and print JSON')
35
62
  .argument('[privateKey]', 'hex-encoded private key to restore')
@@ -74,12 +74,12 @@ program.command('run')
74
74
  .option('-fk, --env-keys-file <path>', 'path(s) to your .env.keys file(s) (default: same path as your env file)', collectEnvKeys)
75
75
  .option('-o, --overload', 'override existing env variables (by default, existing env vars take precedence over .env files)')
76
76
  .option('--strict', 'process.exit(1) on any errors', false)
77
+ .option('--profile <name>', 'select an Envfile profile')
77
78
  .option('--convention <name>', 'load a .env convention (available conventions: [\'nextjs\', \'flow\'])')
78
79
  .option('--ignore <errorCodes...>', 'error code(s) to ignore (example: --ignore=MISSING_ENV_FILE)')
79
80
  .option('--token <token>', 'set Armor ⛨ token')
80
81
  .option('--mask [characters]', 'inject masked values, optionally setting visible characters')
81
82
  .option('--redact', 'redact injected values except public keys (Envfile rules take precedence)', false)
82
- .option('--lock-password <password>', 'password to unlock private keys (defaults to DOTENVX_LOCK_PASSWORD)')
83
83
  .option('--no-armor', 'disable Dotenvx Armor features')
84
84
  .option('--no-native', 'disable OS secret store features')
85
85
  .option('--no-1password', 'disable 1Password secret reference resolution')
@@ -99,6 +99,7 @@ program.command('get')
99
99
  .option('-fk, --env-keys-file <path>', 'path(s) to your .env.keys file(s) (default: same path as your env file)', collectEnvKeys)
100
100
  .option('-o, --overload', 'override existing env variables (by default, existing env vars take precedence over .env files)')
101
101
  .option('--strict', 'process.exit(1) on any errors', false)
102
+ .option('--profile <name>', 'select an Envfile profile')
102
103
  .option('--convention <name>', 'load a .env convention (available conventions: [\'nextjs\', \'flow\'])')
103
104
  .option('--ignore <errorCodes...>', 'error code(s) to ignore (example: --ignore=MISSING_ENV_FILE)')
104
105
  .option('-a, --all', 'include all machine envs as well')
@@ -108,7 +109,6 @@ program.command('get')
108
109
  .option('-pp, --pretty-print', 'pretty print output')
109
110
  .option('--pp', 'pretty print output (alias)')
110
111
  .option('--format <type>', 'format of the output (json, shell, colon, eval, eval-export)', 'json')
111
- .option('--lock-password <password>', 'password to unlock private keys (defaults to DOTENVX_LOCK_PASSWORD)')
112
112
  .option('--no-armor', 'disable Dotenvx Armor features')
113
113
  .option('--no-native', 'disable OS secret store features')
114
114
  .option('--no-1password', 'disable 1Password secret reference resolution')
@@ -122,6 +122,7 @@ program.command('get')
122
122
  program.command('set')
123
123
  .usage('<KEY> [value] [options]')
124
124
  .description('encrypt a single environment variable')
125
+ .option('--profile <name>', 'select an Envfile profile')
125
126
  .addHelpText('after', help.set)
126
127
  .allowUnknownOption()
127
128
  .argument('KEY', 'KEY')
@@ -156,6 +157,7 @@ program.command('del')
156
157
  function configureEncryptCommand (command) {
157
158
  return command
158
159
  .description('encrypt .env file(s)')
160
+ .option('--profile <name>', 'select an Envfile profile')
159
161
  .option('-f, --env-file <path>', 'path(s) to your env file(s)', collectEnvs('envFile'), [])
160
162
  .option('-fk, --env-keys-file <path>', 'path to your .env.keys file (default: same path as your env file)')
161
163
  .option('-k, --key <keys...>', 'keys(s) to encrypt (default: all keys in file)')
@@ -241,6 +243,7 @@ program.command('check', { hidden: true })
241
243
  .option('-f, --env-file <path>', 'path(s) to your env file(s)', collectEnvs('envFile'), [])
242
244
  .option('-fk, --env-keys-file <path>', 'path(s) to your .env.keys file(s) (default: same path as your env file)', collectEnvKeys)
243
245
  .option('-o, --overload', 'override existing env variables (by default, existing env vars take precedence over .env files)')
246
+ .option('--profile <name>', 'select an Envfile profile')
244
247
  .option('--convention <name>', 'load a .env convention (available conventions: [\'nextjs\', \'flow\'])')
245
248
  .option('--ignore <errorCodes...>', 'error code(s) to ignore (example: --ignore=MISSING_ENV_FILE)')
246
249
  .option('--token <token>', 'set Armor ⛨ token')
@@ -336,7 +339,7 @@ function hiddenSubcommands (name) {
336
339
  program.command('hidden')
337
340
  .allowExcessArguments(false)
338
341
  .description('hidden features')
339
- .addHelpText('after', () => `\nHidden Commands:\n update update dotenvx\n feedback [message] send feedback to dotenvx\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 spec create an Envfile\n check check Envfile rules against .env file(s)\n${hiddenSubcommands('primitives')}\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>`)
342
+ .addHelpText('after', () => `\nHidden Commands:\n update update dotenvx\n feedback [message] send feedback to dotenvx\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 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 spec create an Envfile\n check check Envfile rules against .env file(s)\n${hiddenSubcommands('primitives')}\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>`)
340
343
  .action(function () { this.outputHelp() })
341
344
 
342
345
  // dotenvx update
@@ -403,9 +406,6 @@ require('./commands/custody')(program.command('bitwarden', { hidden: true }), 'B
403
406
  // dotenvx native
404
407
  require('./commands/native')(program.command('native', { hidden: true }))
405
408
 
406
- // dotenvx lock
407
- require('./commands/lock')(program.command('lock', { hidden: true }))
408
-
409
409
  // dotenvx armor
410
410
  require('./commands/armor')(program.command('armor', { hidden: true }))
411
411
 
package/src/db/session.js CHANGED
@@ -5,7 +5,7 @@ const { Conf, dotenv, envPaths } = require('@dotenvx/tooling')
5
5
  const jsonToEnv = require('./../lib/helpers/jsonToEnv')
6
6
  const packageJson = require('./../lib/helpers/packageJson')
7
7
  const { http } = require('./../lib/helpers/http')
8
- const nativeProvider = require('./../lib/providers/native')
8
+ const nativeProvider = require('./../lib/custodians/local/native/backend')
9
9
  const { logger } = require('./../shared/logger')
10
10
 
11
11
  const HOURS_24 = 60 * 60 * 24 * 1000
@@ -1,4 +1,4 @@
1
- const protection = require('./lock')
1
+ const nativeProviders = { darwin: 'macosKeychain', win32: 'windowsCredentialManager', linux: 'linuxSecretService' }
2
2
 
3
3
  // Explicit registration keeps bundling predictable and avoids executing
4
4
  // arbitrary modules discovered in a project's working directory.
@@ -45,21 +45,23 @@ function createRegistry (custodians) {
45
45
  const method = sync ? 'getSync' : 'get'
46
46
  if (!custodian.enabled(options) || !custodian.get || (custodian.configured && !custodian.configured())) continue
47
47
  if (typeof custodian[method] !== 'function') throw new Error(`custodian ${custodian.id} does not support synchronous reads`)
48
- if (sync) {
49
- providers.push(publicKey => protection.unlockSync(publicKey, custodian[method](publicKey), options))
50
- } else {
51
- providers.push(async publicKey => protection.unlock(publicKey, await custodian[method](publicKey), options))
48
+ function found (publicKey, ring) {
49
+ if (ring && ring[publicKey] && options.onProvider) {
50
+ const name = custodian.id === 'native' ? nativeProviders[process.platform] || custodian.id : custodian.id
51
+ options.onProvider(name, publicKey)
52
+ }
53
+ return ring
52
54
  }
55
+ const provider = sync
56
+ ? publicKey => found(publicKey, custodian[method](publicKey))
57
+ : async publicKey => found(publicKey, await custodian[method](publicKey))
58
+ providers.push(provider)
53
59
  }
54
60
  return providers
55
61
  },
56
62
  async store (selection, publicKey, privateKey, context = {}) {
57
- const { id, lock = false } = typeof selection === 'string' ? { id: selection } : selection
63
+ const { id } = typeof selection === 'string' ? { id: selection } : selection
58
64
  const custodian = get(id)
59
- if (lock) {
60
- if (custodian.custody === 'managed') throw new Error('password locking is only supported for local custody')
61
- privateKey = await protection.lock(publicKey, privateKey, context)
62
- }
63
65
  const result = await custodian.store(publicKey, privateKey, context) || {}
64
66
  // Only the native custodian's unavailable-write path requests fallback.
65
67
  // Authentication and verification errors propagate without writing a file.
@@ -1,4 +1,5 @@
1
- const { execFile, execFileSync } = require('child_process')
1
+ const { bitwarden } = require('@dotenvx/providers')
2
+ const { execFile } = require('child_process')
2
3
  const matchesStoredKey = require('../../helpers/matchesStoredKey')
3
4
  const Session = require('../../../db/session')
4
5
  const prompts = require('../../helpers/prompts')
@@ -97,10 +98,6 @@ async function authenticate (loc) {
97
98
  }
98
99
  }
99
100
 
100
- function requireSession () {
101
- if (!unlockedSession && !process.env.BW_SESSION) throw failure('Bitwarden requires an unlocked BW_SESSION; run bw login, then bw unlock --raw and set BW_SESSION')
102
- }
103
-
104
101
  function checkIdentity (status, loc) {
105
102
  if (!status || status.status !== 'unlocked' || !ID.test(status.userId || '')) throw commandFailure()
106
103
  if (loc && (status.userId !== loc.userId || (status.serverUrl || '') !== loc.serverUrl)) {
@@ -118,18 +115,11 @@ async function get (publicKey) {
118
115
  const loc = location(publicKey)
119
116
  if (!loc) return {}
120
117
  await authenticate(loc)
121
- return verified(publicKey, (await run(['get', 'password', loc.item])).trim())
118
+ return bitwarden({ processEnv: commandEnv() }).get(publicKey)
122
119
  }
123
120
 
124
121
  function getSync (publicKey) {
125
- const loc = location(publicKey)
126
- if (!loc) return {}
127
- requireSession()
128
- function read (args) {
129
- try { return execFileSync('bw', [...args, '--nointeraction'], { ...COMMAND_OPTIONS, env: commandEnv(), stdio: ['ignore', 'pipe', 'pipe'] }) } catch { throw commandFailure() }
130
- }
131
- checkIdentity(parse(read(['status'])), loc)
132
- return verified(publicKey, read(['get', 'password', loc.item]).trim())
122
+ return bitwarden({ processEnv: commandEnv() }).getSync(publicKey)
133
123
  }
134
124
 
135
125
  async function set (publicKey, privateKey) {
@@ -172,4 +162,4 @@ function enabled (options = {}) {
172
162
  return options.noBitwarden !== true && process.env.DOTENVX_NO_BITWARDEN !== 'true'
173
163
  }
174
164
 
175
- module.exports = { id: 'bitwarden', name: 'Bitwarden', enabled, store: set, available, configured, get, getSync, set, delete: remove }
165
+ module.exports = { id: 'bitwarden', name: 'Bitwarden', enabled, store: set, available, configured, get, getSync, set, delete: remove, commandEnv }
@@ -43,17 +43,11 @@ index.delete = function (key) {
43
43
  }
44
44
 
45
45
  function index (publicKeyHex) {
46
- if (!['darwin', 'linux', 'win32'].includes(process.platform)) return {}
47
-
48
- try {
49
- const privateKeyHex = get(publicKeyHex)
50
-
51
- if (!privateKeyHex) return {}
46
+ return require('@dotenvx/providers').native().getSync(publicKeyHex)
47
+ }
52
48
 
53
- return { [publicKeyHex]: privateKeyHex }
54
- } catch {
55
- return {}
56
- }
49
+ index.async = function (publicKeyHex) {
50
+ return require('@dotenvx/providers').native().get(publicKeyHex)
57
51
  }
58
52
 
59
53
  index.set = set
@@ -17,7 +17,7 @@ module.exports = {
17
17
  enabled,
18
18
  available: () => true,
19
19
  configured: () => true,
20
- get: backend,
20
+ get: backend.async,
21
21
  getSync: backend,
22
22
  set: backend.set,
23
23
  delete: backend.delete,
@@ -1,5 +1,5 @@
1
- const { execFile, execFileSync } = require('child_process')
2
- const matchesStoredKey = require('../../helpers/matchesStoredKey')
1
+ const { execFile } = require('child_process')
2
+ const { onepassword } = require('@dotenvx/providers')
3
3
  const Session = require('../../../db/session')
4
4
  const armoredKeyDisplay = require('../../helpers/armoredKeyDisplay')
5
5
 
@@ -70,11 +70,9 @@ function parseResponse (value) {
70
70
  async function available () {
71
71
  try {
72
72
  const version = await run(['--version'], undefined, 2000)
73
- if (!/^2\./.test(version.trim())) return false
74
- if (process.env.OP_SERVICE_ACCOUNT_TOKEN) return true
75
- // Account discovery is local; authenticate only after the user selects 1Password.
76
- const accounts = parseResponse(await run(['account', 'list', '--format=json'], undefined, 2000))
77
- return Array.isArray(accounts) && accounts.length > 0
73
+ // Availability means the CLI is installed. Account setup and authentication
74
+ // are checked by set() only after the user selects 1Password.
75
+ return /^2\./.test(version.trim())
78
76
  } catch {
79
77
  return false
80
78
  }
@@ -96,32 +94,12 @@ function location (publicKey) {
96
94
  return { account, reference }
97
95
  }
98
96
 
99
- function verified (publicKey, privateKey) {
100
- try {
101
- if (matchesStoredKey(publicKey, privateKey)) return { [publicKey]: privateKey }
102
- } catch {}
103
- throw failure('1Password private key does not match the .env public key')
104
- }
105
-
106
97
  async function get (publicKey) {
107
- const loc = location(publicKey)
108
- if (!loc) return {}
109
- const privateKey = await run(['read', loc.reference, '--no-newline', `--account=${loc.account}`])
110
- return verified(publicKey, privateKey.trim())
98
+ return onepassword().get(publicKey)
111
99
  }
112
100
 
113
101
  function getSync (publicKey) {
114
- const loc = location(publicKey)
115
- if (!loc) return {}
116
- let privateKey
117
- try {
118
- privateKey = execFileSync('op', ['read', loc.reference, '--no-newline', `--account=${loc.account}`], {
119
- ...COMMAND_OPTIONS, stdio: ['ignore', 'pipe', 'pipe']
120
- }).trim()
121
- } catch {
122
- throw failure('1Password CLI could not read the private key; check sign-in and vault permissions')
123
- }
124
- return verified(publicKey, privateKey)
102
+ return onepassword().getSync(publicKey)
125
103
  }
126
104
 
127
105
  async function set (publicKey, privateKey) {
@@ -1,5 +1,4 @@
1
1
  const Session = require('../../../../db/session')
2
- const get = require('./get')
3
2
  const store = require('./store')
4
3
 
5
4
  module.exports = {
@@ -11,14 +10,5 @@ module.exports = {
11
10
  async configured (options = {}) {
12
11
  return !!options.token || !await new Session().noArmor()
13
12
  },
14
- configuredSync (options = {}) {
15
- return !!options.token || !new Session().noArmorSync()
16
- },
17
- get,
18
- getSync (publicKey) {
19
- const { createSyncFn } = require('@dotenvx/tooling')
20
- const runProviderSync = createSyncFn(require.resolve('../../../providers/provider-worker.js'))
21
- return runProviderSync(publicKey)
22
- },
23
13
  store
24
14
  }
@@ -2,7 +2,6 @@ const fs = require('node:fs')
2
2
  const path = require('node:path')
3
3
  const { scan, derive } = require('@dotenvx/primitives')
4
4
  const custodians = require('./index')
5
- const protection = require('./lock')
6
5
  const keynames = require('../conventions/keynames')
7
6
  const matchesStoredKey = require('../helpers/matchesStoredKey')
8
7
  const removeEnvKey = require('../helpers/removeEnvKey')
@@ -31,10 +30,10 @@ module.exports = async function resolveLocalKey (envFile = '.env', { allowMissin
31
30
  }
32
31
 
33
32
  async function result (stored, remove, reread) {
34
- // A file-only push remains supported, including password-locked keys.
35
- if (!publicKey) publicKey = stored.startsWith('locked:') ? stored.split(':')[1] : derive(stored)
33
+ // A file-only push remains supported.
34
+ if (!publicKey) publicKey = derive(stored)
36
35
  if (!matchesStoredKey(publicKey, stored)) throw new Error('private key does not match the .env public key')
37
- const privateKey = (await protection.unlock(publicKey, { [publicKey]: stored }))[publicKey]
36
+ const privateKey = stored
38
37
  return {
39
38
  publicKey,
40
39
  privateKey,
@@ -1,21 +1,20 @@
1
1
  const Session = require('../../../db/session')
2
- const PostArmorDecrypt = require('../../api/postArmorDecrypt')
2
+ const { armor } = require('@dotenvx/providers')
3
+ const { version } = require('../../helpers/packageJson')
3
4
 
4
5
  async function index (src, options = {}) {
5
6
  const sesh = new Session()
6
7
 
7
8
  const hostname = sesh.hostname()
8
- const token = sesh.token()
9
+ const token = options.token || sesh.token()
9
10
  const devicePublicKey = sesh.devicePublicKey()
10
11
 
11
- return await new PostArmorDecrypt(
12
+ return await armor({
12
13
  hostname,
13
14
  token,
14
15
  devicePublicKey,
15
- options.publicKey,
16
- src,
17
- options.grantToken
18
- ).run()
16
+ cliVersion: version
17
+ }).decrypt(src, { publicKey: options.publicKey, grantToken: options.grantToken })
19
18
  }
20
19
 
21
20
  module.exports = index
@@ -11,7 +11,7 @@ module.exports = function discoverEnvFiles ({ directory = process.cwd() } = {})
11
11
  function walk (current) {
12
12
  const entries = fs.readdirSync(current, { withFileTypes: true })
13
13
  // Stop at nested packages and initialized projects, including symlinked markers.
14
- if (current !== root && entries.some(entry => ['Envfile', 'Envspec', 'Dotenvspec', 'package.json'].includes(entry.name))) return
14
+ if (current !== root && entries.some(entry => ['Envfile', 'package.json'].includes(entry.name))) return
15
15
  for (const entry of entries) {
16
16
  const filename = path.join(current, entry.name)
17
17
  if (entry.isDirectory()) {
@@ -4,7 +4,7 @@ const { ignore } = require('@dotenvx/tooling')
4
4
  const extractEnvKeys = require('./extractEnvKeys')
5
5
 
6
6
  const ignoredDirectories = new Set(['.git', 'node_modules', 'dist', 'build', '.next', 'vendor', '.venv', 'coverage', '__pycache__'])
7
- const projectMarkers = new Set(['package.json', 'Envfile', 'Envspec', 'Dotenvspec', '.env.schema'])
7
+ const projectMarkers = new Set(['package.json', 'Envfile', '.env.schema'])
8
8
  const languages = {
9
9
  js: 'js',
10
10
  mjs: 'js',
@@ -1,6 +1,6 @@
1
1
  const path = require('node:path')
2
2
 
3
- module.exports = function formatEnvspecSyntaxError (error, src, filepath) {
3
+ module.exports = function formatEnvfileSyntaxError (error, src, filepath) {
4
4
  const location = error.location?.start
5
5
  if (!location) return error.message
6
6
 
@@ -0,0 +1,43 @@
1
+ const fs = require('node:fs')
2
+ const path = require('node:path')
3
+ const { policy } = require('@dotenvx/primitives')
4
+ const resolveEnvfilePath = require('./resolveEnvfilePath')
5
+ const formatEnvfileSyntaxError = require('./formatEnvfileSyntaxError')
6
+
7
+ function readSource (filepath = resolveEnvfilePath()) {
8
+ try {
9
+ return { source: fs.readFileSync(filepath, 'utf8'), filepath, exists: true }
10
+ } catch (error) {
11
+ if (error.code !== 'ENOENT') throw error
12
+ if (fs.lstatSync(filepath, { throwIfNoEntry: false })) throw new Error(`Cannot read Envfile: ${filepath}`)
13
+ return { filepath, exists: false }
14
+ }
15
+ }
16
+
17
+ function readEnvfile (filepath, files = ['.env']) {
18
+ const document = readSource(filepath)
19
+ if (!document.exists) return { keys: {}, exists: false }
20
+ // File paths arrive relative to the caller; file blocks are relative to Envfile.
21
+ const selected = files.flatMap(file => {
22
+ const absolute = path.resolve(file)
23
+ return [path.relative(path.dirname(document.filepath), absolute), absolute]
24
+ }).join(',')
25
+ try {
26
+ return { ...policy(document.source, selected), exists: true }
27
+ } catch (error) {
28
+ formatError(error, document)
29
+ throw error
30
+ }
31
+ }
32
+
33
+ module.exports = readEnvfile
34
+ module.exports.source = readSource
35
+
36
+ function formatError (error, document) {
37
+ if (error.location) {
38
+ error.message = `[${error.code}] ${formatEnvfileSyntaxError(error.cause || error, document.source, document.filepath)}`
39
+ error.messageWithHelp = error.message
40
+ }
41
+ return error
42
+ }
43
+ module.exports.formatError = formatError
@@ -0,0 +1,5 @@
1
+ const path = require('node:path')
2
+
3
+ module.exports = function resolveEnvfilePath (directory = process.cwd()) {
4
+ return path.resolve(directory, 'Envfile')
5
+ }
@@ -1,5 +1,5 @@
1
1
  // Pure final pass over independently inferred file rules. Never mutates inputs.
2
- module.exports = function normalizeEnvspec ({ files, codeDeclarations = [] }) {
2
+ module.exports = function normalizeEnvfile ({ files, codeDeclarations = [] }) {
3
3
  const hasNamedEnvironment = files.some(file => !['.env', '.env.example'].includes(file.filename))
4
4
  const rootFiles = []
5
5
  const environments = []
@@ -9,33 +9,25 @@ function displayValue (value) {
9
9
  }
10
10
 
11
11
  // Show final resolved values once, not source contents or unrelated shell variables.
12
- module.exports = function previewEnvspec (processedEnvs, schema, processEnv, proxyCredentials = [], diagnostics = []) {
12
+ module.exports = function previewEnvfile (processedEnvs, schema, checked, diagnostics = []) {
13
13
  const keys = new Set((processedEnvs || []).flatMap(row => [...Object.keys(row.parsed || {}), ...Object.keys(row.injected || {}), ...Object.keys(row.existed || {})]))
14
- for (const key of schema.redactionRules.keys()) keys.add(key)
15
- const proxyKeys = new Set(proxyCredentials.map(credential => credential.name))
14
+ for (const key of Object.keys(schema.keys)) keys.add(key)
16
15
  const location = diagnosticLocations(processedEnvs || [], 'process.env', { environmentLabel: 'process.env' })
17
16
  const rows = []
18
17
  const errors = new Map()
19
18
  for (const diagnostic of diagnostics) {
20
19
  keys.add(diagnostic.key)
21
- const message = diagnostic.rule
22
- ? `!${diagnostic.rule}`
23
- : diagnostic.code === 'EXPECTED_ENCRYPTED'
24
- ? '!encrypted'
25
- : diagnostic.code === 'MISSING_REQUIRED'
26
- ? '!required'
27
- : `! ${diagnostic.message.slice(diagnostic.key.length + 1).replace(/^is /, '')}`
20
+ const message = diagnostic.rule ? `!${diagnostic.rule}` : `! ${diagnostic.message}`
28
21
  errors.set(diagnostic.key, [...new Set([...(errors.get(diagnostic.key) || []), message])])
29
22
  }
30
23
  for (const key of keys) {
31
- const missing = processEnv[key] === undefined
24
+ const missing = checked[key] === undefined
32
25
  if (/^DOTENV_(?:PUBLIC|PRIVATE)_KEY/.test(key) || (missing && !errors.has(key))) continue
33
- const value = String(processEnv[key])
34
- const redacted = schema.redactionRules.get(key) ?? true
35
- const display = missing ? '[MISSING]' : redacted || encrypted(value) || proxyKeys.has(key) ? '[REDACTED]' : displayValue(value)
26
+ const value = String(checked[key])
27
+ const display = missing ? '[MISSING]' : displayValue(encrypted(value) ? '[REDACTED]' : value)
36
28
  const source = missing ? '' : displayValue(location(key))
37
29
  const error = errors.has(key) ? errors.get(key).join(', ') : ''
38
- const unspecced = !schema.redactionRules.has(key)
30
+ const unspecced = !Object.hasOwn(schema.keys, key)
39
31
  const status = [unspecced ? '!declared' : '', error].filter(Boolean).join(', ')
40
32
  rows.push({ assignment: `${key}=${display}`, comment: [source, status].filter(Boolean).join(' '), error, unspecced })
41
33
  }
@@ -17,8 +17,8 @@ function renderFile (file) {
17
17
  return lines.join('\n')
18
18
  }
19
19
 
20
- module.exports = function renderEnvspec (document) {
21
- const sections = []
20
+ module.exports = function renderEnvfile (document) {
21
+ const sections = ['strict true']
22
22
  if (document.declarations.length) sections.push(document.declarations.map(declaration).join('\n'))
23
23
  for (const file of document.files) {
24
24
  sections.push(renderFile(file))
@@ -26,5 +26,5 @@ module.exports = function renderEnvspec (document) {
26
26
  if (document.codeDeclarations.length) {
27
27
  sections.push('# additionally found in code\n' + document.codeDeclarations.map(declaration).join('\n'))
28
28
  }
29
- return '# Envfile (safe to commit)\n# ------------------------\n\n' + sections.join('\n\n') + (sections.length ? '\n' : '')
29
+ return '# Envfile (safe to commit)\n# ------------------------\n\n' + sections.join('\n\n') + '\n'
30
30
  }
@@ -1,12 +1,12 @@
1
1
  const fs = require('node:fs')
2
2
  const path = require('node:path')
3
3
  const { execFileSync } = require('node:child_process')
4
- const readEnvspec = require('../parsing/readEnvspec')
5
- const resolveEnvspecPath = require('../parsing/resolveEnvspecPath')
4
+ const readEnvfile = require('../parsing/readEnvfile')
5
+ const resolveEnvfilePath = require('../parsing/resolveEnvfilePath')
6
6
  const plaintextKeys = require('../../helpers/plaintextKeys')
7
7
 
8
8
  function readPolicy (policyPath, file) {
9
- const schema = readEnvspec(policyPath, [file])
9
+ const schema = readEnvfile(policyPath, [file])
10
10
  if (!schema.exists) {
11
11
  // A dangling policy symlink is a broken policy, not an absent policy.
12
12
  if (fs.lstatSync(policyPath, { throwIfNoEntry: false })) throw new Error(`Cannot read Envfile: ${policyPath}`)
@@ -16,10 +16,10 @@ function readPolicy (policyPath, file) {
16
16
  }
17
17
 
18
18
  // Inspect Git's incoming blob, never the working-tree env values or shell overrides.
19
- module.exports = function protectEnvspec (filepath, content) {
19
+ module.exports = function protectEnvfile (filepath, content) {
20
20
  const file = path.resolve(filepath)
21
21
  const directory = path.dirname(file)
22
- let schema = readPolicy(resolveEnvspecPath(directory), file)
22
+ let schema = readPolicy(resolveEnvfilePath(directory), file)
23
23
  if (!schema) {
24
24
  let root
25
25
  try {
@@ -32,9 +32,9 @@ module.exports = function protectEnvspec (filepath, content) {
32
32
  // Outside a Git working tree, only an adjacent policy can apply.
33
33
  return null
34
34
  }
35
- if (path.resolve(root) !== directory) schema = readPolicy(resolveEnvspecPath(root), file)
35
+ if (path.resolve(root) !== directory) schema = readPolicy(resolveEnvfilePath(root), file)
36
36
  }
37
37
  if (!schema) return null
38
38
 
39
- return plaintextKeys(content).filter(key => /^DOTENV_PRIVATE_KEY(?:_|$)/.test(key) || (schema.encryptionRules.get(key) ?? true))
39
+ return plaintextKeys(content).filter(key => /^DOTENV_PRIVATE_KEY(?:_|$)/.test(key) || (schema.keys[key]?.fs.encrypted ?? true))
40
40
  }
@@ -0,0 +1,14 @@
1
+ const { check } = require('@dotenvx/primitives')
2
+ const Errors = require('../../helpers/errors')
3
+
4
+ module.exports = function validateEnvfile (policy, env) {
5
+ if (!policy.exists) return { checked: {}, errors: [] }
6
+ return check(policy, env)
7
+ }
8
+
9
+ module.exports.error = function validationError (diagnostics) {
10
+ if (!diagnostics.length) return
11
+ const error = new Errors({ message: diagnostics.map(item => item.message).join('; ') }).invalidEnv()
12
+ error.diagnostics = diagnostics
13
+ return error
14
+ }
@@ -6,7 +6,6 @@ const ISSUE_BY_CODE = {
6
6
  DECRYPTION_FAILED: 'https://github.com/dotenvx/dotenvx/issues/757',
7
7
  INVALID_COLOR: 'must be 256 colors',
8
8
  INVALID_CONVENTION: 'https://github.com/dotenvx/dotenvx/issues/761',
9
- INVALID_PASSPHRASE: 'try again with the correct passphrase',
10
9
  INVALID_PRIVATE_KEY: 'https://github.com/dotenvx/dotenvx/issues/465',
11
10
  INVALID_PUBLIC_KEY: 'https://github.com/dotenvx/dotenvx/issues/756',
12
11
  '1PASSWORD_FAILED': 'https://www.1password.dev/cli/get-started',
@@ -172,18 +171,6 @@ class Errors {
172
171
  return e
173
172
  }
174
173
 
175
- invalidPassphrase () {
176
- const code = 'INVALID_PASSPHRASE'
177
- const message = `[${code}] could not unlock ${this.privateKeyName || 'DOTENV_PRIVATE_KEY'} using passphrase`
178
- const help = `fix: [${ISSUE_BY_CODE[code]}]`
179
-
180
- const e = new Error(message)
181
- e.code = code
182
- e.help = help
183
- e.messageWithHelp = `${message}. ${help}`
184
- return e
185
- }
186
-
187
174
  malformedEncryptedData () {
188
175
  const code = 'MALFORMED_ENCRYPTED_DATA'
189
176
  const message = `[${code}] could not decrypt ${this.key} because encrypted data appears malformed`
@@ -233,9 +220,9 @@ class Errors {
233
220
  return e
234
221
  }
235
222
 
236
- envspecRequired () {
237
- const e = new Error('[ENVSPEC_REQUIRED] check requires an Envfile')
238
- e.code = 'ENVSPEC_REQUIRED'
223
+ envfileRequired () {
224
+ const e = new Error('[ENVFILE_REQUIRED] check requires an Envfile')
225
+ e.code = 'ENVFILE_REQUIRED'
239
226
  e.help = 'fix: run [dotenvx spec]'
240
227
  e.messageWithHelp = `${e.message}. ${e.help}`
241
228
  return e
@@ -339,15 +326,6 @@ class Errors {
339
326
  return e
340
327
  }
341
328
 
342
- malformedEnvspec () {
343
- const code = 'MALFORMED_ENVSPEC'
344
- const message = `[${code}] ${this.message}`
345
- const e = new Error(message)
346
- e.code = code
347
- e.messageWithHelp = message
348
- return e
349
- }
350
-
351
329
  invalidEnv () {
352
330
  const code = 'INVALID_ENV'
353
331
  const message = `[${code}] ${this.message}`