@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
@@ -7,7 +7,7 @@ const { createRedactedStreamWriter, redactOutput } = require('./redactOutput')
7
7
  const ptyCommand = require('./ptyCommand')
8
8
  const { finished } = require('stream/promises')
9
9
 
10
- async function executeCommand (commandArgs, env, sensitiveValues = [], onComplete) {
10
+ async function executeCommand (commandArgs, env, sensitiveValues = []) {
11
11
  const FORWARD_SIGNAL_GRACE_MS = 1000
12
12
  const FORCE_KILL_GRACE_MS = 1000
13
13
  const signals = [
@@ -200,7 +200,6 @@ async function executeCommand (commandArgs, env, sensitiveValues = [], onComplet
200
200
  otherSignalHandlers.forEach((handler, signal) => {
201
201
  process.removeListener(signal, handler)
202
202
  })
203
- if (onComplete) await onComplete()
204
203
  }
205
204
 
206
205
  return { exitCode: commandExitCode || 0, signal: commandSignal, error: commandError }
@@ -1,16 +1,5 @@
1
1
  const { derive } = require('@dotenvx/primitives')
2
2
 
3
- // Locked values can be transported without unlocking. Validate the envelope
4
- // here; authenticate and derive the actual key when unlocking for use.
5
- function matchesStoredKey (publicKey, value) {
6
- if (typeof value !== 'string') return false
7
- if (value.startsWith('locked:')) {
8
- const parts = value.split(':')
9
- if (parts.length !== 3 || parts[1] !== publicKey || !/^(02|03)[a-f0-9]{64}$/i.test(publicKey)) return false
10
- const payload = Buffer.from(parts[2], 'base64url')
11
- return payload.length === 109 && payload[0] === 1 && payload.toString('base64url') === parts[2]
12
- }
3
+ module.exports = function matchesStoredKey (publicKey, value) {
13
4
  try { return derive(value) === publicKey } catch { return false }
14
5
  }
15
-
16
- module.exports = matchesStoredKey
@@ -1,8 +1,29 @@
1
- const { parse, parseSync, parsearrays, scan, encrypted } = require('@dotenvx/primitives')
2
- const prepareProxy = require('../proxy/prepareProxy')
3
- const withLockedKeys = require('./withLockedKeys')
1
+ const { parse, parseSync, parsearrays, publickeys } = require('@dotenvx/primitives')
2
+ const { file } = require('@dotenvx/providers')
4
3
  const SERVER_SIDE_DECRYPTION_REQUIRED = 'SERVER_SIDE_DECRYPTION_REQUIRED'
5
4
 
5
+ function withFileKeys (src, options, sync = false) {
6
+ const keys = file({ fk: options.fk })
7
+ const fallback = options.provider
8
+ const provider = sync
9
+ ? publicKey => {
10
+ const ring = keys.getSync(publicKey)
11
+ return ring[publicKey] ? ring : (fallback ? fallback(publicKey) : {})
12
+ }
13
+ : async publicKey => {
14
+ const ring = await keys.get(publicKey)
15
+ return ring[publicKey] ? ring : (fallback ? fallback(publicKey) : {})
16
+ }
17
+ return {
18
+ ...options,
19
+ provider,
20
+ // Provider lookup requires a public key. Keep legacy key discovery for
21
+ // encrypted files that do not declare one, and for error recovery.
22
+ fk: publickeys(src).length ? [] : options.fk,
23
+ fallbackFk: options.fk
24
+ }
25
+ }
26
+
6
27
  function decryptOptions (error) {
7
28
  const meta = error.meta || {}
8
29
 
@@ -16,6 +37,7 @@ function decryptOptions (error) {
16
37
  function parseOptionsWithoutProvider (options) {
17
38
  return {
18
39
  ...options,
40
+ fk: options.fallbackFk,
19
41
  provider: null,
20
42
  decryptor: null
21
43
  }
@@ -29,13 +51,6 @@ function failedKeyAccessFallback (result, error) {
29
51
  }
30
52
 
31
53
  async function parseWithDecryptor (src, options = {}) {
32
- if (options.proxyCredentials) {
33
- const original = src
34
- src = prepareProxy(src, options.proxyCredentials, options.processEnv, options.proxyRules)
35
- if (src !== original && !Object.values(scan(src).parsed).flat().some(encrypted)) {
36
- options = parseOptionsWithoutProvider(options)
37
- }
38
- }
39
54
  return parseWith(src, options, parse)
40
55
  }
41
56
 
@@ -44,7 +59,7 @@ parseWithDecryptor.arrays = async function parsearraysWithDecryptor (src, option
44
59
  }
45
60
 
46
61
  async function parseWith (src, options, parser) {
47
- options = withLockedKeys(options)
62
+ options = withFileKeys(src, options)
48
63
  try {
49
64
  return await parser(src, options)
50
65
  } catch (error) {
@@ -66,7 +81,7 @@ async function parseWith (src, options, parser) {
66
81
  }
67
82
 
68
83
  parseWithDecryptor.sync = function parseWithDecryptorSync (src, options = {}) {
69
- options = withLockedKeys(options, true)
84
+ options = withFileKeys(src, options, true)
70
85
  try {
71
86
  return parseSync(src, options)
72
87
  } catch (error) {
@@ -1,4 +1,4 @@
1
- const redact = require('./redact')
1
+ const { redact } = require('@dotenvx/primitives')
2
2
  const { StringDecoder } = require('string_decoder')
3
3
 
4
4
  function normalizedValues (values) {
@@ -26,11 +26,7 @@ function redactOutput (value, sensitiveValues) {
26
26
 
27
27
  if (typeof value !== 'string') return value
28
28
 
29
- let result = value
30
- for (const sensitiveValue of values) {
31
- result = result.split(sensitiveValue).join(redact(sensitiveValue))
32
- }
33
- return result
29
+ return redact(value, values)
34
30
  }
35
31
 
36
32
  function partialMatchLength (value, sensitiveValues) {
@@ -71,16 +67,35 @@ function safeBoundary (value, boundary, sensitiveValues) {
71
67
  return result
72
68
  }
73
69
 
74
- function createRedactedStreamWriter (stream, sensitiveValues, source) {
75
- const values = normalizedValues(sensitiveValues)
70
+ function createRedactor (sensitiveValues) {
71
+ const values = new Set(normalizedValues(sensitiveValues))
76
72
  const decoder = new StringDecoder('utf8')
77
73
  let pending = ''
78
- let waitingForDrain = false
74
+ return {
75
+ add: secrets => normalizedValues(secrets).forEach(secret => values.add(secret)),
76
+ write (chunk) {
77
+ pending += decoder.write(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)
78
+ const secrets = [...values]
79
+ const boundary = safeBoundary(pending, pending.length - partialMatchLength(pending, secrets), secrets)
80
+ const output = redact(pending.slice(0, boundary), secrets)
81
+ pending = pending.slice(boundary)
82
+ return output
83
+ },
84
+ flush (maskPending = false) {
85
+ pending += decoder.end()
86
+ const output = maskPending && pending ? '[REDACTED]' : redact(pending, [...values])
87
+ pending = ''
88
+ return output
89
+ }
90
+ }
91
+ }
79
92
 
93
+ function createRedactedStreamWriter (stream, sensitiveValues, source) {
94
+ const redactor = createRedactor(sensitiveValues)
95
+ let waitingForDrain = false
80
96
  const writeToStream = (value) => {
81
97
  if (!value) return
82
-
83
- const canContinue = stream.write(redactOutput(value, values))
98
+ const canContinue = stream.write(value)
84
99
  if (!canContinue && source && !waitingForDrain) {
85
100
  waitingForDrain = true
86
101
  source.pause()
@@ -90,31 +105,14 @@ function createRedactedStreamWriter (stream, sensitiveValues, source) {
90
105
  })
91
106
  }
92
107
  }
93
-
94
- const flush = () => {
95
- pending += decoder.end()
96
- if (!pending) return
97
- writeToStream(pending)
98
- pending = ''
108
+ return {
109
+ write: chunk => writeToStream(redactor.write(chunk)),
110
+ flush: () => writeToStream(redactor.flush())
99
111
  }
100
-
101
- const write = (chunk) => {
102
- pending += Buffer.isBuffer(chunk) ? decoder.write(chunk) : `${chunk}`
103
-
104
- const holdbackLength = partialMatchLength(pending, values)
105
- let boundary = pending.length - holdbackLength
106
- boundary = safeBoundary(pending, boundary, values)
107
-
108
- const output = pending.slice(0, boundary)
109
- pending = pending.slice(boundary)
110
-
111
- writeToStream(output)
112
- }
113
-
114
- return { write, flush }
115
112
  }
116
113
 
117
114
  module.exports = {
118
115
  redactOutput,
116
+ createRedactor,
119
117
  createRedactedStreamWriter
120
118
  }
@@ -0,0 +1,58 @@
1
+ const fs = require('node:fs')
2
+ const { createRedactor } = require('./redactOutput')
3
+
4
+ const stateKey = Symbol.for('dotenvx.redactProcessOutput')
5
+
6
+ // Keep a possible secret prefix between writes, including split UTF-8 buffers.
7
+ function install (stream, secrets) {
8
+ if (stream[stateKey]) {
9
+ stream[stateKey].add(secrets)
10
+ return
11
+ }
12
+ const redactor = createRedactor(secrets)
13
+ const write = stream.write.bind(stream)
14
+ const end = stream.end.bind(stream)
15
+ const consume = (chunk, encoding) => redactor.write(typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk)
16
+ // Do not release an unfinished secret prefix at shutdown.
17
+ const flush = () => redactor.flush(true)
18
+
19
+ stream.write = function (chunk, encoding, callback) {
20
+ if (typeof encoding === 'function') {
21
+ callback = encoding
22
+ encoding = undefined
23
+ }
24
+ if (!(typeof chunk === 'string' || chunk instanceof Uint8Array) || (callback !== undefined && typeof callback !== 'function')) {
25
+ return write(chunk, encoding, callback)
26
+ }
27
+ return write(consume(chunk, encoding), 'utf8', callback)
28
+ }
29
+ stream.end = function (chunk, encoding, callback) {
30
+ if (typeof chunk === 'function') {
31
+ callback = chunk
32
+ chunk = undefined
33
+ } else if (typeof encoding === 'function') {
34
+ callback = encoding
35
+ encoding = undefined
36
+ }
37
+ const output = chunk === undefined || chunk === null ? '' : consume(chunk, encoding)
38
+ return end(output + flush(), 'utf8', callback)
39
+ }
40
+ stream[stateKey] = redactor
41
+ process.on('beforeExit', () => {
42
+ const output = flush()
43
+ if (output) write(output)
44
+ })
45
+ process.on('exit', () => {
46
+ const output = flush()
47
+ if (output) {
48
+ try { fs.writeSync(stream.fd, output) } catch { /* The destination may already be closed. */ }
49
+ }
50
+ })
51
+ }
52
+
53
+ module.exports = function redactProcessOutput (secrets) {
54
+ const values = secrets.filter(value => typeof value === 'string' && value.length > 0)
55
+ if (!values.length) return
56
+ install(process.stdout, values)
57
+ install(process.stderr, values)
58
+ }
@@ -6,7 +6,7 @@ function redactedValues (processedEnvs, schema, processEnv = {}, legacyRedact =
6
6
 
7
7
  const rows = [...(processedEnvs || [])]
8
8
  if (schema?.exists) {
9
- rows.push({ injected: Object.fromEntries([...schema.redactionRules.keys()].map(key => [key, processEnv[key]])) })
9
+ rows.push({ injected: Object.fromEntries(Object.keys(schema.keys).map(key => [key, processEnv[key]])) })
10
10
  }
11
11
  for (const processedEnv of rows) {
12
12
  const values = {
@@ -15,7 +15,7 @@ function redactedValues (processedEnvs, schema, processEnv = {}, legacyRedact =
15
15
  }
16
16
 
17
17
  for (const [key, value] of Object.entries(values)) {
18
- const redacted = schema?.exists ? (schema.redactionRules.get(key) ?? schema.redacted) : !isPublicKey(key)
18
+ const redacted = schema?.exists ? (schema.keys[key]?.stdio.redacted ?? true) : !isPublicKey(key)
19
19
  if (!redacted) continue
20
20
  if (value === undefined || value === null || value === '') continue
21
21
 
@@ -0,0 +1,29 @@
1
+ const { profile } = require('@dotenvx/primitives')
2
+ const readEnvfile = require('../envfile/parsing/readEnvfile')
3
+ const normalizeDotenvConfigPath = require('./normalizeDotenvConfigPath')
4
+ const buildCommandEnvs = require('./buildCommandEnvs')
5
+ const determine = require('./envResolution/determine')
6
+
7
+ module.exports = function selectEnvfileEnvs (envs = [], options = {}, processEnv = process.env) {
8
+ const resolve = values => options.resolveDirectories === false ? values : buildCommandEnvs(values, options.convention)
9
+ const document = readEnvfile.source()
10
+ if (!document.exists) {
11
+ if (options.profile !== undefined) throw new Error('Profile selection requires an Envfile')
12
+ return determine(resolve(normalizeDotenvConfigPath(envs, processEnv)), processEnv)
13
+ }
14
+ // Keep explicit CLI file/inline-env ordering; profiles only supply file selection.
15
+ const explicit = resolve(envs)
16
+ const files = explicit.filter(env => env.type === 'envFile')
17
+ let selected
18
+ try {
19
+ selected = profile(document.source, {
20
+ f: files.length ? files.map(env => env.value).join(',') : undefined,
21
+ profile: options.profile,
22
+ processEnv
23
+ })
24
+ } catch (error) {
25
+ throw readEnvfile.formatError(error, document)
26
+ }
27
+ if (files.length) return explicit
28
+ return resolve((selected ? selected.split(',').map(value => ({ type: 'envFile', value })) : []).concat(explicit))
29
+ }
@@ -27,7 +27,7 @@ async function selectKeyStorage (options = {}) {
27
27
  setup.set(id, `Install the ${custodian.name} CLI (${command}), then retry this command.`)
28
28
  } else if (id === 'armored' && !await custodian.configured(options)) {
29
29
  name += ' (sign in)'
30
- setup.set(id, 'Sign in with [dotenvx armor login], then retry this command.')
30
+ setup.set(id, 'Sign in with [dotenvx login], then retry this command.')
31
31
  }
32
32
  entries.push({ name, value: id })
33
33
  }
@@ -2,7 +2,6 @@ const selectKeyStorage = require('./selectKeyStorage')
2
2
  const custodians = require('../custodians')
3
3
 
4
4
  async function storeKeyStorage (storage, publicKey, privateKey, options, context) {
5
- // Preserve the operation context so locked custody can reuse its passphrase.
6
5
  context.allowCustodyBack = true
7
6
  while (true) {
8
7
  storage = storage || await selectKeyStorage(options)
package/src/lib/main.d.ts CHANGED
@@ -64,8 +64,6 @@ export function parse<T extends DotenvParseOutput = DotenvParseOutput>(
64
64
  ): T;
65
65
 
66
66
  export interface DotenvConfigOptions {
67
- /** Password to unlock private keys in memory. Defaults to DOTENVX_LOCK_PASSWORD. */
68
- lockPassword?: string;
69
67
 
70
68
  /**
71
69
  * Specify explicit env sources. When set, `path` and `convention` are ignored.
@@ -86,6 +84,9 @@ export interface DotenvConfigOptions {
86
84
  */
87
85
  path?: string | string[] | URL;
88
86
 
87
+ /** Select a named Envfile profile when no explicit paths are supplied. */
88
+ profile?: string;
89
+
89
90
  /**
90
91
  * Specify the encoding of your file containing environment variables.
91
92
  *
@@ -257,9 +258,10 @@ export interface DotenvPopulateInput {
257
258
  /**
258
259
  * Loads `.env` file contents into process.env by default.
259
260
  * Reads Envfile from the current directory and validates the final resolved environment.
260
- * Falls back to Envspec, then Dotenvspec, when earlier filenames are absent.
261
261
  * Validation failures warn and return an error, or throw when strictness is enabled.
262
- * Invalid Envfile syntax and active proxy rules always throw; use run for proxy support.
262
+ * Invalid Envfile syntax always throws.
263
+ * With an Envfile, subsequent Node stdout/stderr writes are automatically redacted.
264
+ * Environment and returned values remain unchanged; native writes and inherited child output bypass redaction.
263
265
  *
264
266
  * @see https://dotenvx.com/docs
265
267
  *
@@ -280,6 +282,9 @@ export interface SetOptions {
280
282
  */
281
283
  path?: string | string[] | URL;
282
284
 
285
+ /** Select a named Envfile profile when no explicit paths are supplied. */
286
+ profile?: string;
287
+
283
288
  /**
284
289
  * Customize the path to your .env.keys file. This is useful with monorepos.
285
290
  * @default []
@@ -361,8 +366,6 @@ export function set(
361
366
  ): Promise<SetOutput>;
362
367
 
363
368
  export interface GetOptions {
364
- /** Password to unlock private keys in memory. Defaults to DOTENVX_LOCK_PASSWORD. */
365
- lockPassword?: string;
366
369
 
367
370
  /**
368
371
  * Specify a custom path if your file containing environment variables is located elsewhere.
@@ -374,6 +377,9 @@ export interface GetOptions {
374
377
  */
375
378
  path?: string | string[] | URL;
376
379
 
380
+ /** Select a named Envfile profile when no explicit paths are supplied. */
381
+ profile?: string;
382
+
377
383
  /**
378
384
  * Mask returned values, optionally setting the number of visible characters.
379
385
  * @default false
package/src/lib/main.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @ts-check
2
2
  const path = require('path')
3
- const { encrypted, parseSync } = require('@dotenvx/primitives')
3
+ const { encrypted, parseSync, injectsummary } = require('@dotenvx/primitives')
4
4
 
5
5
  // shared
6
6
  const { setLogLevel, setLogName, setLogVersion, logger } = require('./../shared/logger')
@@ -19,7 +19,6 @@ const setTransform = require('./transforms/set')
19
19
  // helpers
20
20
  const buildEnvs = require('./helpers/buildEnvs')
21
21
  const buildConfigEnvs = require('./helpers/buildConfigEnvs')
22
- const { determine } = require('./helpers/envResolution')
23
22
  const escape = require('./helpers/escape')
24
23
  const fsx = require('./helpers/fsx')
25
24
  const decryptKeyValue = require('./helpers/cryptography/decryptKeyValue')
@@ -27,12 +26,13 @@ const Errors = require('./helpers/errors')
27
26
  const normalizeDotenvConfigQuiet = require('./helpers/normalizeDotenvConfigQuiet')
28
27
  const normalizeDotenvConfigConvention = require('./helpers/normalizeDotenvConfigConvention')
29
28
  const normalizeDotenvConfigIgnore = require('./helpers/normalizeDotenvConfigIgnore')
30
- const normalizeDotenvConfigPath = require('./helpers/normalizeDotenvConfigPath')
29
+ const selectEnvfileEnvs = require('./helpers/selectEnvfileEnvs')
31
30
  const mask = require('./helpers/mask')
32
31
  const maskProcessedEnvs = require('./helpers/maskProcessedEnvs')
33
- const readEnvspec = require('./envspec/parsing/readEnvspec')
34
- const validateEnvspec = require('./envspec/validation/validateEnvspec')
32
+ const readEnvfile = require('./envfile/parsing/readEnvfile')
33
+ const validateEnvfile = require('./envfile/validation/validateEnvfile')
35
34
  const redactedValues = require('./helpers/redactedValues')
35
+ const redactProcessOutput = require('./helpers/redactProcessOutput')
36
36
  const { redactOutput } = require('./helpers/redactOutput')
37
37
 
38
38
  function uniqueInjectedKeys (processedEnvs) {
@@ -82,15 +82,8 @@ const config = function (options = {}, events) {
82
82
  let fatal = false
83
83
  let sensitiveValues = []
84
84
  try {
85
- let envs = normalizeDotenvConfigPath(buildConfigEnvs(options))
86
- if (!options.envs) {
87
- envs = determine(envs, processEnv)
88
- }
89
- const schema = readEnvspec(undefined, envs.filter(env => env.type === 'envFile').map(env => env.value))
90
- if (schema.proxyRules.size > 0) {
91
- fatal = true
92
- throw new Error('Envfile proxy is not supported by synchronous config(). Use dotenvx run -- yourcommand.')
93
- }
85
+ const envs = options.envs || selectEnvfileEnvs(buildConfigEnvs(options), { ...options, convention: undefined }, { ...process.env, ...processEnv })
86
+ const schema = readEnvfile(undefined, envs.filter(env => env.type === 'envFile').map(env => env.value))
94
87
  const {
95
88
  processedEnvs,
96
89
  readableFilepaths
@@ -103,13 +96,13 @@ const config = function (options = {}, events) {
103
96
  noNative,
104
97
  no1Password: options.no1Password,
105
98
  noBitwarden: options.noBitwarden,
106
- lockPassword: options.lockPassword,
107
99
  noSpinner: options.noSpinner,
108
100
  token: options.token
109
101
  })
110
102
 
111
- const validationError = validateEnvspec(schema, processEnv, processedEnvs)
103
+ const validationError = validateEnvfile.error(validateEnvfile(schema, processEnv).errors)
112
104
  sensitiveValues = redactedValues(processedEnvs, schema, processEnv)
105
+ if (schema.exists) redactProcessOutput(sensitiveValues)
113
106
 
114
107
  if (options.mask !== undefined) {
115
108
  const showChar = options.mask === true ? 6 : options.mask
@@ -130,10 +123,7 @@ const config = function (options = {}, events) {
130
123
  continue // ignore error
131
124
  }
132
125
 
133
- const policyStrict = processedEnv.type === 'envFile'
134
- ? (schema.strictByFile?.get(path.resolve(processedEnv.filepath)) ?? schema.strict)
135
- : schema.strict
136
- if (strict || policyStrict) {
126
+ if (strict) {
137
127
  fatal = true
138
128
  throw error
139
129
  }
@@ -181,11 +171,7 @@ const config = function (options = {}, events) {
181
171
  }
182
172
 
183
173
  if (events) events.add({ files: readableFilepaths, injected_count: uniqueInjectedKeys(processedEnvs).size })
184
- let msg = `injected env (${uniqueInjectedKeys(processedEnvs).size})`
185
- if (readableFilepaths.length > 0) {
186
- msg += ` from ${readableFilepaths.join(', ')}`
187
- }
188
- logger.success(`⟐ ${msg}`)
174
+ logger.success(injectsummary(uniqueInjectedKeys(processedEnvs).size, readableFilepaths))
189
175
 
190
176
  if (lastError) {
191
177
  if (events) events.fail(lastError)
@@ -195,7 +181,7 @@ const config = function (options = {}, events) {
195
181
  }
196
182
  } catch (error) {
197
183
  if (events) events.fail(error)
198
- if (strict || fatal || error.code === 'MALFORMED_ENVSPEC') throw error
184
+ if (strict || fatal || error.code === 'MALFORMED_ENVFILE') throw error
199
185
 
200
186
  logger.error(redactOutput(error.messageWithHelp || error.message, sensitiveValues))
201
187
 
@@ -288,6 +274,7 @@ const set = async function (key, value, options = {}, events) {
288
274
  unchangedFilepaths
289
275
  } = await setTransform({
290
276
  envs,
277
+ profile: options.profile,
291
278
  key,
292
279
  value,
293
280
  fk: envKeysFilepath,
@@ -295,7 +282,6 @@ const set = async function (key, value, options = {}, events) {
295
282
  noNative,
296
283
  no1Password: options.no1Password,
297
284
  noBitwarden: options.noBitwarden,
298
- lockPassword: options.lockPassword,
299
285
  noCreate,
300
286
  encrypt
301
287
  })
@@ -372,16 +358,17 @@ const get = async function (key, options = {}, events) {
372
358
  const ignore = options.ignore || []
373
359
 
374
360
  const { parsed, errors } = await getResolver({
361
+ resolveDirectories: false,
375
362
  key,
376
363
  envs,
364
+ profile: options.profile,
377
365
  overload: options.overload,
378
366
  all: options.all,
379
367
  envKeysFile: options.envKeysFile,
380
368
  noArmor,
381
369
  noNative,
382
370
  no1Password: options.no1Password,
383
- noBitwarden: options.noBitwarden,
384
- lockPassword: options.lockPassword
371
+ noBitwarden: options.noBitwarden
385
372
  })
386
373
 
387
374
  if (options.mask !== undefined) {
@@ -1,66 +1,66 @@
1
- const custodians = require('../custodians')
2
-
3
- function hasKey (keyring, publicKeyHex) {
4
- return keyring && keyring[publicKeyHex]
5
- }
6
-
7
- function composeProviders (providerFns) {
8
- return async function provider (publicKeyHex) {
9
- for (const providerFn of providerFns) {
10
- const keyring = await providerFn(publicKeyHex)
11
- if (hasKey(keyring, publicKeyHex)) return keyring
1
+ const { provider } = require('@dotenvx/providers')
2
+ const bitwarden = require('../custodians/local/bitwarden')
3
+ const { version } = require('../helpers/packageJson')
4
+ const armoredKeyDisplay = require('../helpers/armoredKeyDisplay')
5
+ const listenForOpenKey = require('../helpers/listenForOpenKey')
6
+ const openUrl = require('../helpers/openUrl')
7
+
8
+ const nativeNames = { darwin: 'macosKeychain', win32: 'windowsCredentialManager', linux: 'linuxSecretService' }
9
+
10
+ function lookup (publicKey, options, sync) {
11
+ let source
12
+ let cleanup = () => {}
13
+ const keys = provider({
14
+ ...options,
15
+ // File keys are already resolved against the selected env file by callers.
16
+ fk: [],
17
+ processEnv: bitwarden.commandEnv(),
18
+ cliVersion: version,
19
+ // The async CLI fallback can interactively unlock Bitwarden. The shared
20
+ // synchronous path reads BW_SESSION without prompting.
21
+ noBitwarden: sync ? options.noBitwarden : true,
22
+ onLookup (name) { source = name },
23
+ onApprovalRequired: options.onStatus && (({ approvalUri, code }) => {
24
+ cleanup()
25
+ const display = armoredKeyDisplay(publicKey)
26
+ options.onStatus(`[${code}] press Enter to open [${approvalUri}] and approve${display ? ` (${display})` : ''}`)
27
+ cleanup = listenForOpenKey(() => openUrl(approvalUri))
28
+ })
29
+ })
30
+
31
+ function found (ring) {
32
+ if (ring[publicKey] && options.onProvider) {
33
+ options.onProvider(source === 'native' ? nativeNames[process.platform] || source : source, publicKey)
12
34
  }
13
-
14
- return {}
35
+ return ring
15
36
  }
16
- }
17
37
 
18
- function composeProvidersSync (providerFns) {
19
- return function providerSync (publicKeyHex) {
20
- for (const providerFn of providerFns) {
21
- const keyring = providerFn(publicKeyHex)
22
- if (hasKey(keyring, publicKeyHex)) return keyring
23
- }
24
-
25
- return {}
38
+ if (sync) {
39
+ try { return found(keys.getSync(publicKey)) } finally { cleanup() }
26
40
  }
27
- }
28
41
 
29
- function providerFrom (providerFns, compose) {
30
- if (providerFns.length === 0) return null
31
- if (providerFns.length === 1) return providerFns[0]
32
-
33
- return compose(providerFns)
42
+ return (async () => {
43
+ try {
44
+ let ring = await keys.get(publicKey)
45
+ if (!ring[publicKey] && bitwarden.enabled(options)) {
46
+ source = 'bitwarden'
47
+ ring = await bitwarden.get(publicKey)
48
+ }
49
+ return found(ring)
50
+ } finally {
51
+ cleanup()
52
+ }
53
+ })()
34
54
  }
35
55
 
36
56
  async function providers (options = {}) {
37
- if (Object.prototype.hasOwnProperty.call(options, 'provider')) {
38
- return options.provider
39
- }
40
-
41
- const providerFns = custodians.providers(options)
42
-
43
- const armor = custodians.get('armored')
44
- if (armor.enabled(options) && await armor.configured(options)) {
45
- providerFns.push(publicKey => armor.get(publicKey, options))
46
- }
47
-
48
- return providerFrom(providerFns, composeProviders)
57
+ if (Object.prototype.hasOwnProperty.call(options, 'provider')) return options.provider
58
+ return publicKey => lookup(publicKey, options, false)
49
59
  }
50
60
 
51
- providers.sync = function providersSync (options = {}) {
52
- if (Object.prototype.hasOwnProperty.call(options, 'provider')) {
53
- return options.provider
54
- }
55
-
56
- const providerFns = custodians.providers(options, true)
57
-
58
- const armor = custodians.get('armored')
59
- if (armor.enabled(options) && armor.configuredSync(options)) {
60
- providerFns.push(armor.getSync)
61
- }
62
-
63
- return providerFrom(providerFns, composeProvidersSync)
61
+ providers.sync = function (options = {}) {
62
+ if (Object.prototype.hasOwnProperty.call(options, 'provider')) return options.provider
63
+ return publicKey => lookup(publicKey, options, true)
64
64
  }
65
65
 
66
66
  module.exports = providers