@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
@@ -1,144 +0,0 @@
1
- const fs = require('node:fs')
2
- const path = require('node:path')
3
- const { isIP } = require('node:net')
4
- const parser = require('./envspecParser')
5
- const Errors = require('../../helpers/errors')
6
- const isValidUrl = require('../../helpers/isValidUrl')
7
- const isValidEmail = require('../../helpers/isValidEmail')
8
- const formatEnvspecSyntaxError = require('./formatEnvspecSyntaxError')
9
- const resolveEnvspecPath = require('./resolveEnvspecPath')
10
-
11
- function compileDeclarations (declarations) {
12
- const proxyRules = new Map()
13
- const requiredKeys = []
14
- const types = new Map()
15
- const declaredTypes = new Map()
16
- const enums = new Map()
17
- const ranges = new Map()
18
- const encryptedKeys = []
19
- const redactionRules = new Map()
20
- const encryptionRules = new Map()
21
- const names = new Set()
22
- for (const input of declarations) {
23
- const declaration = { ...input }
24
- if (input.type) declaredTypes.set(input.name, input.type)
25
- if (names.has(declaration.name)) throw new Errors({ message: `Duplicate Envfile declaration: ${declaration.name}` }).malformedEnvspec()
26
- names.add(declaration.name)
27
- redactionRules.set(declaration.name, declaration.redacted !== false)
28
- encryptionRules.set(declaration.name, declaration.encrypted !== false)
29
- if (declaration.encrypted !== false) encryptedKeys.push(declaration.name)
30
- if (declaration.type === 'port') {
31
- declaration.type = 'integer'
32
- if (declaration.min === undefined || BigInt(declaration.min) < 0n) declaration.min = '0'
33
- if (declaration.max === undefined || BigInt(declaration.max) > 65535n) declaration.max = '65535'
34
- }
35
- if (declaration.required) requiredKeys.push(declaration.name)
36
- if (declaration.type) types.set(declaration.name, declaration.type)
37
- if (declaration.min !== undefined || declaration.max !== undefined) {
38
- if (declaration.type !== 'integer') {
39
- throw new Errors({ message: `Invalid Envfile range for ${declaration.name}: min and max require type: "integer" or "port".` }).malformedEnvspec()
40
- }
41
- if (declaration.min !== undefined && declaration.max !== undefined && BigInt(declaration.min) > BigInt(declaration.max)) {
42
- throw new Errors({ message: `Invalid Envfile range for ${declaration.name}: min must be less than or equal to max.` }).malformedEnvspec()
43
- }
44
- ranges.set(declaration.name, { min: declaration.min, max: declaration.max })
45
- }
46
- if (declaration.enum) {
47
- if (declaration.type === 'integer' && declaration.enum.some(value => !/^[+-]?\d+$/.test(value.trim()))) {
48
- throw new Errors({ message: `Invalid Envfile enum for ${declaration.name}: expected integer choices.` }).malformedEnvspec()
49
- }
50
- if (declaration.type === 'boolean' && declaration.enum.some(value => !['true', 'false', '1', '0'].includes(value))) {
51
- throw new Errors({ message: `Invalid Envfile enum for ${declaration.name}: expected true, false, 1, or 0 choices.` }).malformedEnvspec()
52
- }
53
- if (declaration.type === 'url' && declaration.enum.some(value => !isValidUrl(value))) {
54
- throw new Errors({ message: `Invalid Envfile enum for ${declaration.name}: expected URL choices.` }).malformedEnvspec()
55
- }
56
- if (declaration.type === 'email' && declaration.enum.some(value => !isValidEmail(value))) {
57
- throw new Errors({ message: `Invalid Envfile enum for ${declaration.name}: expected email choices.` }).malformedEnvspec()
58
- }
59
- if (declaration.type === 'ip' && declaration.enum.some(value => isIP(value) === 0)) {
60
- throw new Errors({ message: `Invalid Envfile enum for ${declaration.name}: expected IPv4 or IPv6 choices.` }).malformedEnvspec()
61
- }
62
- enums.set(declaration.name, declaration.enum)
63
- }
64
- if (declaration.proxy) {
65
- const host = declaration.proxy.domain.toLowerCase()
66
- if (host.length > 253 || isIP(host) || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(host)) {
67
- throw new Errors({ message: `Invalid Envfile proxy host for ${declaration.name}: expected a DNS hostname without a scheme, port, path or wildcard.` }).malformedEnvspec()
68
- }
69
- proxyRules.set(declaration.name, host)
70
- }
71
- }
72
- return { exists: true, proxyRules, requiredKeys, types, declaredTypes, enums, ranges, encryptedKeys, redactionRules, encryptionRules }
73
- }
74
-
75
- module.exports = function readEnvspec (filepath, envFiles = ['.env']) {
76
- if (filepath === undefined) filepath = resolveEnvspecPath()
77
- let src
78
- try {
79
- src = fs.readFileSync(filepath, 'utf8')
80
- } catch (error) {
81
- if (error.code === 'ENOENT') {
82
- if (fs.lstatSync(filepath, { throwIfNoEntry: false })) throw new Error(`Cannot read ${path.basename(filepath)}: ${filepath}`)
83
- return { ...compileDeclarations([]), exists: false }
84
- }
85
- throw error
86
- }
87
-
88
- let document
89
- try {
90
- document = parser.parse(src)
91
- } catch (error) {
92
- throw new Errors({ message: formatEnvspecSyntaxError(error, src, filepath) }).malformedEnvspec()
93
- }
94
-
95
- const defaults = { proxy: false, required: true, encrypted: true, redacted: true }
96
- const base = document.declarations.map(item => ({ ...defaults, ...item }))
97
- const strictByFile = new Map()
98
- const baseSchema = { ...compileDeclarations(base), encrypted: true, redacted: true, strict: document.strict ?? false, strictByFile }
99
- const selected = new Set(envFiles.map(file => path.resolve(file)))
100
- const seen = new Set()
101
- const active = []
102
- for (const block of document.files) {
103
- if (/[*?[\]]/.test(block.file)) {
104
- throw new Errors({ message: `File blocks require an exact filename: ${block.file}` }).malformedEnvspec()
105
- }
106
- const file = path.resolve(path.dirname(filepath), block.file)
107
- if (seen.has(file)) throw new Errors({ message: `Duplicate Envfile file block: ${block.file}` }).malformedEnvspec()
108
- seen.add(file)
109
- const merged = new Map(base.map(item => [item.name, { ...item }]))
110
- const names = new Set()
111
- for (const item of block.declarations) {
112
- if (names.has(item.name)) throw new Errors({ message: `Duplicate Envfile declaration in ${block.file}: ${item.name}` }).malformedEnvspec()
113
- names.add(item.name)
114
- merged.set(item.name, {
115
- ...defaults,
116
- ...merged.get(item.name),
117
- ...item
118
- })
119
- }
120
- const strict = block.strict ?? baseSchema.strict
121
- strictByFile.set(file, strict)
122
- const schema = { ...compileDeclarations([...merged.values()]), encrypted: true, redacted: true, strict }
123
- if (selected.has(file)) active.push(schema)
124
- }
125
- if (active.length === 0) return baseSchema
126
-
127
- // Each selected file policy must hold, regardless of file loading order.
128
- const proxyRules = new Map()
129
- for (const schema of active) {
130
- for (const [key, host] of schema.proxyRules) {
131
- if (proxyRules.has(key) && proxyRules.get(key) !== host) {
132
- throw new Errors({ message: `Conflicting Envfile proxy domains for ${key} in selected file blocks` }).malformedEnvspec()
133
- }
134
- proxyRules.set(key, host)
135
- }
136
- }
137
- const redactionRules = new Map()
138
- for (const schema of active) {
139
- for (const [name, redacted] of schema.redactionRules) {
140
- redactionRules.set(name, redactionRules.get(name) === true || redacted)
141
- }
142
- }
143
- return { ...active[0], strict: baseSchema.strict, strictByFile, redactionRules, proxyRules, schemas: active }
144
- }
@@ -1,11 +0,0 @@
1
- const fs = require('node:fs')
2
- const path = require('node:path')
3
-
4
- // A present but broken policy must fail, never fall back to a weaker policy.
5
- module.exports = function resolveEnvspecPath (directory = process.cwd()) {
6
- for (const filename of ['Envfile', 'Envspec', 'Dotenvspec']) {
7
- const candidate = path.resolve(directory, filename)
8
- if (fs.lstatSync(candidate, { throwIfNoEntry: false })) return candidate
9
- }
10
- return path.resolve(directory, 'Envfile')
11
- }
@@ -1,15 +0,0 @@
1
- const { scan, encrypted } = require('@dotenvx/primitives')
2
-
3
- // Follow actual injection order, so shell overrides and --overload retain their semantics.
4
- module.exports = function encryptedSources (processedEnvs) {
5
- const keys = new Set()
6
- for (const row of processedEnvs || []) {
7
- const { parsed } = scan(row.src || row.string || '')
8
- for (const [key, value] of Object.entries(row.injected || {})) {
9
- const original = parsed[key]?.at(-1)
10
- if (encrypted(original) && !encrypted(value)) keys.add(key)
11
- else keys.delete(key)
12
- }
13
- }
14
- return keys
15
- }
@@ -1,109 +0,0 @@
1
- const isValidUrl = require('../../helpers/isValidUrl')
2
- const isValidEmail = require('../../helpers/isValidEmail')
3
- const { isIP } = require('node:net')
4
-
5
- function validate (example = {}, env = {}, options = {}) {
6
- const errors = []
7
- const missingRequired = []
8
-
9
- for (const key of Object.keys(example)) {
10
- const value = env[key]
11
- const missing = !Object.prototype.hasOwnProperty.call(env, key) || value.trim() === ''
12
- if (missing) {
13
- missingRequired.push(key)
14
- }
15
- }
16
-
17
- if (missingRequired.length > 0) {
18
- errors.push({
19
- code: 'MISSING_REQUIRED',
20
- keys: missingRequired,
21
- message: missingRequired.map(key => `${key} is required`).join('; ')
22
- })
23
- }
24
-
25
- const invalidIntegers = []
26
- const invalidBooleans = []
27
- const invalidUrls = []
28
- const invalidEmails = []
29
- const invalidIps = []
30
- for (const [key, type] of options.types || []) {
31
- if (!Object.prototype.hasOwnProperty.call(env, key)) continue
32
- const value = env[key].trim()
33
- if (value === '') continue // required checks handle blank values
34
- if (type === 'integer' && !/^[+-]?\d+$/.test(value)) invalidIntegers.push(key)
35
- if (type === 'boolean' && !['true', 'false', '1', '0'].includes(env[key])) invalidBooleans.push(key)
36
- if (type === 'url' && !isValidUrl(env[key])) invalidUrls.push(key)
37
- if (type === 'email' && !isValidEmail(env[key])) invalidEmails.push(key)
38
- if (type === 'ip' && isIP(env[key]) === 0) invalidIps.push(key)
39
- }
40
- if (invalidIntegers.length > 0) {
41
- errors.push({
42
- code: 'INVALID_INTEGER',
43
- keys: invalidIntegers,
44
- message: invalidIntegers.map(key => `${key} must be an integer`).join('; ')
45
- })
46
- }
47
-
48
- if (invalidBooleans.length > 0) {
49
- errors.push({
50
- code: 'INVALID_BOOLEAN',
51
- keys: invalidBooleans,
52
- message: invalidBooleans.map(key => `${key} must be true, false, 1, or 0`).join('; ')
53
- })
54
- }
55
- if (invalidUrls.length > 0) {
56
- errors.push({ code: 'INVALID_URL', keys: invalidUrls, message: invalidUrls.map(key => `${key} must be a valid URL`).join('; ') })
57
- }
58
- if (invalidEmails.length > 0) {
59
- errors.push({ code: 'INVALID_EMAIL', keys: invalidEmails, message: invalidEmails.map(key => `${key} must be a valid email address`).join('; ') })
60
- }
61
- if (invalidIps.length > 0) {
62
- errors.push({ code: 'INVALID_IP', keys: invalidIps, message: invalidIps.map(key => `${key} must be a valid IPv4 or IPv6 address`).join('; ') })
63
- }
64
- const invalidEnums = []
65
- for (const [key, choices] of options.enums || []) {
66
- if (!Object.prototype.hasOwnProperty.call(env, key) || env[key].trim() === '') continue
67
- if (invalidIntegers.includes(key) || invalidBooleans.includes(key) || invalidUrls.includes(key) || invalidEmails.includes(key) || invalidIps.includes(key)) continue
68
- const value = env[key]
69
- const matches = options.types?.get(key) === 'integer'
70
- ? choices.some(choice => BigInt(choice.trim()) === BigInt(value.trim()))
71
- : choices.includes(value)
72
- if (!matches) invalidEnums.push(key)
73
- }
74
- if (invalidEnums.length > 0) {
75
- errors.push({
76
- code: 'INVALID_ENUM',
77
- keys: invalidEnums,
78
- message: invalidEnums.map(key => `${key} is not an allowed value`).join('; ')
79
- })
80
- }
81
-
82
- for (const [key, { min, max }] of options.ranges || []) {
83
- if (!Object.prototype.hasOwnProperty.call(env, key) || env[key].trim() === '') continue
84
- if (invalidIntegers.includes(key)) continue
85
- const value = BigInt(env[key].trim())
86
- if (min !== undefined && value < BigInt(min)) {
87
- errors.push({ code: 'BELOW_MIN', keys: [key], message: `${key} must be at least ${min}` })
88
- }
89
- if (max !== undefined && value > BigInt(max)) {
90
- errors.push({ code: 'ABOVE_MAX', keys: [key], message: `${key} must be at most ${max}` })
91
- }
92
- }
93
-
94
- const unencrypted = []
95
- for (const key of options.encryptedKeys || []) {
96
- if (!Object.prototype.hasOwnProperty.call(env, key) || env[key].trim() === '') continue
97
- if (!options.encryptedSources?.has(key)) unencrypted.push(key)
98
- }
99
- if (unencrypted.length > 0) {
100
- errors.push({ code: 'EXPECTED_ENCRYPTED', keys: unencrypted, message: unencrypted.map(key => `${key} is not encrypted`).join('; ') })
101
- }
102
-
103
- return {
104
- valid: errors.length === 0,
105
- errors
106
- }
107
- }
108
-
109
- module.exports = validate
@@ -1,57 +0,0 @@
1
- const validate = require('./validate')
2
- const encryptedSources = require('./encryptedSources')
3
- const Errors = require('../../helpers/errors')
4
-
5
- module.exports = function validateEnvspec (schema, env, processedEnvs, onKey, { validateEncryption = true } = {}) {
6
- if (!schema.exists) return
7
- const diagnostics = new Map()
8
- const schemas = schema.schemas || [schema]
9
- const sources = validateEncryption ? encryptedSources(processedEnvs) : undefined
10
- // Include loaded keys and their shell overrides, not unrelated host variables.
11
- const loadedKeys = new Set((processedEnvs || []).flatMap(row => [...Object.keys(row.injected || {}), ...Object.keys(row.existed || {})]))
12
- const declaredKeys = new Set(schemas.flatMap(rules => [...rules.encryptionRules.keys()]))
13
- // Defaults apply only to keys absent from every active policy. An unrelated
14
- // file block must not undo another block's explicit plaintext exception.
15
- const undeclaredKeys = [...loadedKeys].filter(key => !declaredKeys.has(key))
16
- for (const rules of schemas) {
17
- const { requiredKeys, types, enums, ranges } = rules
18
- const encryptedKeys = new Set(validateEncryption
19
- ? [...rules.encryptedKeys, ...undeclaredKeys].filter(key =>
20
- !key.startsWith('DOTENV_PUBLIC_KEY') && (rules.encryptionRules.get(key) ?? true)
21
- )
22
- : [])
23
- const keys = new Set([...requiredKeys, ...types.keys(), ...enums.keys(), ...ranges.keys(), ...encryptedKeys, ...(rules.redactionRules?.keys() || [])])
24
- for (const key of keys) {
25
- if (onKey) onKey(key)
26
- const validation = validate(requiredKeys.includes(key) ? { [key]: '' } : {}, env, {
27
- types: types.has(key) ? new Map([[key, types.get(key)]]) : undefined,
28
- enums: enums.has(key) ? new Map([[key, enums.get(key)]]) : undefined,
29
- ranges: ranges.has(key) ? new Map([[key, ranges.get(key)]]) : undefined,
30
- encryptedKeys: encryptedKeys.has(key) ? [key] : [],
31
- encryptedSources: sources
32
- })
33
- for (const error of validation.errors) {
34
- const strict = rules.strict === true || diagnostics.get(error.message)?.strict === true
35
- const type = rules.declaredTypes?.get(key) || types.get(key)
36
- const rule = {
37
- MISSING_REQUIRED: 'required',
38
- EXPECTED_ENCRYPTED: 'encrypted',
39
- INVALID_INTEGER: type,
40
- INVALID_BOOLEAN: 'boolean',
41
- INVALID_URL: 'url',
42
- INVALID_EMAIL: 'email',
43
- INVALID_IP: 'ip',
44
- INVALID_ENUM: 'enum',
45
- BELOW_MIN: type === 'port' ? 'port' : 'min',
46
- ABOVE_MAX: type === 'port' ? 'port' : 'max'
47
- }[error.code]
48
- diagnostics.set(error.message, { key, code: error.code, message: error.message, strict, rule })
49
- }
50
- }
51
- }
52
- if (diagnostics.size > 0) {
53
- const error = new Errors({ message: [...diagnostics.keys()].join('; ') }).invalidEnv()
54
- error.diagnostics = [...diagnostics.values()]
55
- return error
56
- }
57
- }
@@ -1,11 +0,0 @@
1
- module.exports = function isValidEmail (value) {
2
- if (value.length > 254 || /\s/.test(value)) return false
3
- const parts = value.split('@')
4
- if (parts.length !== 2) return false
5
- const [local, domain] = parts
6
- if (local.length > 64 || !/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/i.test(local)) return false
7
- const labels = domain.split('.')
8
- return labels.length > 1 &&
9
- labels.every(label => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label)) &&
10
- /^(?:[a-z]{2,63}|xn--[a-z0-9-]+)$/i.test(labels[labels.length - 1])
11
- }
@@ -1,9 +0,0 @@
1
- const { URL } = require('node:url')
2
-
3
- module.exports = function isValidUrl (value) {
4
- try {
5
- return new URL(value).protocol !== ''
6
- } catch {
7
- return false
8
- }
9
- }
@@ -1,24 +0,0 @@
1
- const crypto = require('crypto')
2
-
3
- function lockedValue (privateKey, passphrase, publicKey) {
4
- const salt = crypto.randomBytes(16)
5
- const iv = crypto.randomBytes(12)
6
- const key = crypto.scryptSync(passphrase, salt, 32)
7
- const cipher = crypto.createCipheriv('aes-256-gcm', key, iv)
8
- const ciphertext = Buffer.concat([
9
- cipher.update(privateKey, 'utf8'),
10
- cipher.final()
11
- ])
12
- const tag = cipher.getAuthTag()
13
- const payload = Buffer.concat([
14
- Buffer.from([1]),
15
- salt,
16
- iv,
17
- tag,
18
- ciphertext
19
- ]).toString('base64url')
20
-
21
- return `locked:${publicKey}:${payload}`
22
- }
23
-
24
- module.exports = lockedValue
@@ -1,5 +0,0 @@
1
- function resolveLockPassword (options = {}) {
2
- return options.lockPassword !== undefined ? options.lockPassword : process.env.DOTENVX_LOCK_PASSWORD
3
- }
4
-
5
- module.exports = resolveLockPassword
@@ -1,26 +0,0 @@
1
- const crypto = require('crypto')
2
-
3
- function unlockedValue (lockedPrivateKey, passphrase) {
4
- const parts = lockedPrivateKey.split(':')
5
- const payload = Buffer.from(parts.slice(2).join(':'), 'base64url')
6
- const version = payload.subarray(0, 1)[0]
7
- const salt = payload.subarray(1, 17)
8
- const iv = payload.subarray(17, 29)
9
- const tag = payload.subarray(29, 45)
10
- const ciphertext = payload.subarray(45)
11
- const key = crypto.scryptSync(passphrase, salt, 32)
12
- const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv)
13
-
14
- if (version !== 1) {
15
- throw new Error('unsupported locked private key version')
16
- }
17
-
18
- decipher.setAuthTag(tag)
19
-
20
- return Buffer.concat([
21
- decipher.update(ciphertext),
22
- decipher.final()
23
- ]).toString('utf8')
24
- }
25
-
26
- module.exports = unlockedValue
@@ -1,41 +0,0 @@
1
- const fs = require('fs')
2
- const { scan } = require('@dotenvx/primitives')
3
- const protection = require('../custodians/lock')
4
-
5
- // Primitives already resolve raw file/environment keys first. This provider
6
- // supplies locked keys only when the requested private key is still missing.
7
- function withLockedKeys (options, sync = false) {
8
- const candidates = []
9
- const paths = Array.isArray(options.fk) ? options.fk : [options.fk || '.env.keys']
10
- for (const filepath of paths) {
11
- let src
12
- try { src = fs.readFileSync(filepath, 'utf8') } catch { continue }
13
- for (const [name, values] of Object.entries(scan(src).parsed)) {
14
- if (name.startsWith('DOTENV_PRIVATE_KEY')) candidates.push(...values.flatMap(value => value.split(',')))
15
- }
16
- }
17
- // Environment assignments take precedence over key files.
18
- for (const [name, value] of Object.entries(options.processEnv || process.env)) {
19
- if (name.startsWith('DOTENV_PRIVATE_KEY') && typeof value === 'string') candidates.push(...value.split(','))
20
- }
21
- if (!candidates.some(value => value.startsWith('locked:'))) return options
22
- candidates.reverse()
23
- function find (publicKey) {
24
- return candidates.find(value => value.startsWith(`locked:${publicKey}:`))
25
- }
26
- const provider = options.provider
27
- return {
28
- ...options,
29
- provider: sync
30
- ? publicKey => {
31
- const value = find(publicKey)
32
- return value ? protection.unlockSync(publicKey, { [publicKey]: value }, options) : (provider ? provider(publicKey) : {})
33
- }
34
- : async publicKey => {
35
- const value = find(publicKey)
36
- return value ? protection.unlock(publicKey, { [publicKey]: value }, options) : (provider ? provider(publicKey) : {})
37
- }
38
- }
39
- }
40
-
41
- module.exports = withLockedKeys
@@ -1,6 +0,0 @@
1
- const { runAsWorker } = require('@dotenvx/tooling')
2
- const provider = require('../custodians/managed/armor').get
3
-
4
- runAsWorker(async (publicKeyHex) => {
5
- return provider(publicKeyHex)
6
- })
@@ -1,55 +0,0 @@
1
- const path = require('node:path')
2
- const fs = require('node:fs')
3
- const startProxy = require('./proxyServer')
4
-
5
- module.exports = async function configureProxy (commandArgs, env, credentials = [], session, explicitToken) {
6
- const active = credentials.filter(credential => env[credential.name] === credential.placeholder)
7
- if (active.length === 0) return { commandArgs, env }
8
- const token = explicitToken || session.token()
9
- if (!token || token.startsWith('encrypted:')) throw new Error('Credential proxy requires Armor login. Run [dotenvx armor login].')
10
- const hostname = session.hostname()
11
- const url = new URL(hostname)
12
- if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
13
- throw new Error('Credential proxy requires an HTTPS Armor hostname.')
14
- }
15
- const server = await startProxy({ credentials: active, token, hostname: url.href.replace(/\/$/, ''), devicePublicKey: session.devicePublicKey(), env })
16
- const preload = path.join(path.dirname(server.caPath), 'proxy-preload.cjs')
17
- try {
18
- fs.writeFileSync(preload, require('./proxyPreloadSource'), { mode: 0o600 })
19
- } catch (error) {
20
- await server.close()
21
- throw error
22
- }
23
- const nodeOptions = `${env.NODE_OPTIONS || ''} --require ${JSON.stringify(preload)}`.trim()
24
- const args = /\.(mjs|cjs|js)$/.test(commandArgs[0])
25
- ? [process.pkg ? 'node' : process.execPath, path.resolve(commandArgs[0]), ...commandArgs.slice(1)]
26
- : commandArgs
27
- return {
28
- commandArgs: args,
29
- close: server.close,
30
- env: {
31
- ...env,
32
- NODE_OPTIONS: nodeOptions,
33
- HTTP_PROXY: server.proxyUrl,
34
- HTTPS_PROXY: server.proxyUrl,
35
- ALL_PROXY: server.proxyUrl,
36
- http_proxy: server.proxyUrl,
37
- https_proxy: server.proxyUrl,
38
- all_proxy: server.proxyUrl,
39
- NO_PROXY: 'localhost,127.0.0.1,::1',
40
- no_proxy: 'localhost,127.0.0.1,::1',
41
- NODE_EXTRA_CA_CERTS: server.caPath,
42
- SSL_CERT_FILE: server.caPath,
43
- REQUESTS_CA_BUNDLE: server.caPath,
44
- CURL_CA_BUNDLE: server.caPath,
45
- GIT_SSL_CAINFO: server.caPath,
46
- CARGO_HTTP_CAINFO: server.caPath,
47
- DENO_CERT: server.caPath,
48
- DOTENVX_PROXY_URL: server.proxyUrl,
49
- DOTENVX_PROXY_SOCKET: undefined,
50
- DOTENVX_PROXY_CONFIG: undefined,
51
- DOTENVX_TOKEN: undefined,
52
- DOTENVX_ARMOR_TOKEN: undefined
53
- }
54
- }
55
- }
@@ -1,16 +0,0 @@
1
- // Keep this policy in sync with Radar's GatewayService::EligibleHeaders.
2
- // Authentication headers (Authorization, X-Api-Key, etc.) are eligible. Routing,
3
- // transport, browser context, cookies and proxy control metadata are not.
4
- const EXCLUDED = new Set([
5
- 'host', 'connection', 'keep-alive', 'transfer-encoding', 'content-length',
6
- 'te', 'trailer', 'upgrade', 'expect', 'accept-encoding',
7
- 'cookie', 'set-cookie', 'forwarded', 'via', 'referer', 'origin', 'user-agent',
8
- 'x-real-ip', 'x-original-url', 'x-rewrite-url', 'x-http-method-override'
9
- ])
10
- const PREFIXES = ['proxy-', 'dotenvx-', 'x-forwarded-', 'sec-']
11
-
12
- module.exports = function eligibleHeaders (name) {
13
- const lower = name.toLowerCase()
14
- return /^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(lower) &&
15
- !EXCLUDED.has(lower) && !PREFIXES.some(prefix => lower.startsWith(prefix))
16
- }
@@ -1,24 +0,0 @@
1
- const { randomBytes } = require('node:crypto')
2
- const { scan, upsert, encrypted } = require('@dotenvx/primitives')
3
-
4
- // Remove proxy credentials before any local or Armor decryption is attempted.
5
- module.exports = function prepareProxy (src, credentials, processEnv = {}, proxyRules = new Map()) {
6
- const { parsed } = scan(src)
7
- const publicKeys = Object.entries(parsed).filter(([name]) => name.startsWith('DOTENV_PUBLIC_KEY'))
8
- for (const [name, values] of Object.entries(parsed)) {
9
- if (!proxyRules.has(name)) continue
10
- const replaced = values.map(value => {
11
- if (!encrypted(value)) return value
12
- if (publicKeys.length > 1) throw new Error('Credential proxy requires an unambiguous DOTENV_PUBLIC_KEY in its env file.')
13
- const publicKey = publicKeys.length === 1 ? publicKeys[0][1].at(-1) : processEnv.DOTENV_PUBLIC_KEY
14
- if (!publicKey || !/^(02|03)[0-9a-f]{64}$/i.test(publicKey)) {
15
- throw new Error('Credential proxy requires DOTENV_PUBLIC_KEY alongside the encrypted credential.')
16
- }
17
- const placeholder = `dotenvx_proxy_${randomBytes(24).toString('hex')}`
18
- credentials.push({ name, host: proxyRules.get(name), placeholder, ciphertext: value, publicKey })
19
- return placeholder
20
- })
21
- src = upsert(src, name, replaced)
22
- }
23
- return src
24
- }
@@ -1,44 +0,0 @@
1
- const { generateKeyPair, randomBytes } = require('node:crypto')
2
- const { promisify } = require('node:util')
3
- const forge = require('node-forge')
4
-
5
- // Only public certificates are persisted. Both signing keys stay in this process.
6
- module.exports = async function proxyCertificates (hosts = ['localhost']) {
7
- const generate = () => promisify(generateKeyPair)('rsa', {
8
- modulusLength: 2048,
9
- publicKeyEncoding: { type: 'spki', format: 'pem' },
10
- privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
11
- })
12
- const [caKeys, leafKeys] = await Promise.all([generate(), generate()])
13
- const issuer = [{ name: 'commonName', value: 'dotenvx temporary proxy' }]
14
- const certificate = (keys, subject) => {
15
- const cert = forge.pki.createCertificate()
16
- cert.publicKey = forge.pki.publicKeyFromPem(keys.publicKey)
17
- cert.serialNumber = '01' + randomBytes(16).toString('hex')
18
- cert.validity.notBefore = new Date(Date.now() - 60000)
19
- cert.validity.notAfter = new Date(Date.now() + 24 * 60 * 60 * 1000)
20
- cert.setSubject(subject)
21
- cert.setIssuer(issuer)
22
- return cert
23
- }
24
- const ca = certificate(caKeys, issuer)
25
- ca.setExtensions([
26
- { name: 'basicConstraints', cA: true, critical: true },
27
- { name: 'subjectKeyIdentifier' },
28
- { name: 'authorityKeyIdentifier', keyIdentifier: true },
29
- { name: 'keyUsage', keyCertSign: true, cRLSign: true, critical: true }
30
- ])
31
- const signingKey = forge.pki.privateKeyFromPem(caKeys.privateKey)
32
- ca.sign(signingKey, forge.md.sha256.create())
33
- const leaf = certificate(leafKeys, [{ name: 'commonName', value: hosts[0] || 'localhost' }])
34
- leaf.setExtensions([
35
- { name: 'basicConstraints', cA: false, critical: true },
36
- { name: 'subjectKeyIdentifier' },
37
- { name: 'authorityKeyIdentifier', keyIdentifier: ca.generateSubjectKeyIdentifier().getBytes() },
38
- { name: 'keyUsage', digitalSignature: true, keyEncipherment: true, critical: true },
39
- { name: 'extKeyUsage', serverAuth: true },
40
- { name: 'subjectAltName', altNames: hosts.map(value => ({ type: 2, value })) }
41
- ])
42
- leaf.sign(signingKey, forge.md.sha256.create())
43
- return { ca: forge.pki.certificateToPem(ca), cert: forge.pki.certificateToPem(leaf), key: leafKeys.privateKey }
44
- }