@dotenvx/dotenvx 2.32.3 → 2.33.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 (61) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/README.md +43 -55
  3. package/package.json +3 -11
  4. package/src/cli/actions/check.js +7 -12
  5. package/src/cli/actions/encrypt.js +2 -2
  6. package/src/cli/actions/get.js +3 -3
  7. package/src/cli/actions/init.js +11 -11
  8. package/src/cli/actions/policy.js +14 -0
  9. package/src/cli/actions/primitivesCheck.js +32 -0
  10. package/src/cli/actions/primitivesProfile.js +15 -0
  11. package/src/cli/actions/primitivesRedact.js +19 -0
  12. package/src/cli/actions/protectStdin.js +2 -2
  13. package/src/cli/actions/run.js +6 -34
  14. package/src/cli/actions/set.js +1 -1
  15. package/src/cli/commands/primitives.js +28 -1
  16. package/src/cli/dotenvx.js +10 -5
  17. package/src/lib/custodians/local/onepassword.js +3 -5
  18. package/src/lib/{envspec → envfile}/discovery/discoverEnvFiles.js +1 -1
  19. package/src/lib/{envspec → envfile}/discovery/scanSource.js +1 -1
  20. package/src/lib/{envspec/parsing/formatEnvspecSyntaxError.js → envfile/parsing/formatEnvfileSyntaxError.js} +1 -1
  21. package/src/lib/envfile/parsing/readEnvfile.js +43 -0
  22. package/src/lib/envfile/parsing/resolveEnvfilePath.js +5 -0
  23. package/src/lib/{envspec/rendering/normalizeEnvspec.js → envfile/rendering/normalizeEnvfile.js} +1 -1
  24. package/src/lib/{envspec/rendering/previewEnvspec.js → envfile/rendering/previewEnvfile.js} +7 -15
  25. package/src/lib/{envspec/rendering/renderEnvspec.js → envfile/rendering/renderEnvfile.js} +4 -4
  26. package/src/lib/{envspec/validation/protectEnvspec.js → envfile/validation/protectEnvfile.js} +8 -10
  27. package/src/lib/envfile/validation/validateEnvfile.js +14 -0
  28. package/src/lib/helpers/errors.js +3 -12
  29. package/src/lib/helpers/executeCommand.js +1 -2
  30. package/src/lib/helpers/parseWithDecryptor.js +1 -9
  31. package/src/lib/helpers/redactOutput.js +30 -32
  32. package/src/lib/helpers/redactProcessOutput.js +58 -0
  33. package/src/lib/helpers/redactedValues.js +2 -2
  34. package/src/lib/helpers/selectEnvfileEnvs.js +29 -0
  35. package/src/lib/main.d.ts +14 -5
  36. package/src/lib/main.js +13 -19
  37. package/src/lib/resolvers/envs.js +5 -15
  38. package/src/lib/resolvers/get.js +2 -2
  39. package/src/lib/services/init.js +7 -7
  40. package/src/lib/services/validate.js +20 -31
  41. package/src/lib/transforms/encrypt.js +5 -5
  42. package/src/lib/transforms/set.js +5 -3
  43. package/src/lib/envspec/parsing/envspec.peggy +0 -105
  44. package/src/lib/envspec/parsing/envspecParser.js +0 -2851
  45. package/src/lib/envspec/parsing/readEnvspec.js +0 -151
  46. package/src/lib/envspec/parsing/resolveEnvspecPath.js +0 -12
  47. package/src/lib/envspec/validation/encryptedSources.js +0 -15
  48. package/src/lib/envspec/validation/validate.js +0 -109
  49. package/src/lib/envspec/validation/validateEnvspec.js +0 -57
  50. package/src/lib/helpers/isValidEmail.js +0 -11
  51. package/src/lib/helpers/isValidUrl.js +0 -9
  52. package/src/lib/proxy/configureProxy.js +0 -55
  53. package/src/lib/proxy/eligibleHeaders.js +0 -16
  54. package/src/lib/proxy/prepareProxy.js +0 -24
  55. package/src/lib/proxy/proxyCertificates.js +0 -44
  56. package/src/lib/proxy/proxyForward.js +0 -65
  57. package/src/lib/proxy/proxyPreload.js +0 -21
  58. package/src/lib/proxy/proxyPreloadSource.js +0 -3
  59. package/src/lib/proxy/proxyServer.js +0 -175
  60. /package/src/lib/{envspec → envfile}/discovery/extractEnvKeys.js +0 -0
  61. /package/src/lib/{envspec → envfile}/validation/diagnosticLocation.js +0 -0
@@ -1,151 +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 Dotenvspec 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 Dotenvspec 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 Dotenvspec 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 Dotenvspec 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 Dotenvspec 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 Dotenvspec 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 Dotenvspec 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 Dotenvspec 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 Dotenvspec 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'], processEnv = process.env) {
76
- let src
77
- if (filepath === undefined && processEnv.DOTENV_SPEC !== undefined) {
78
- // Inline policy replaces file discovery, even when the value is empty.
79
- // Use the working directory for file blocks and DOTENV_SPEC in diagnostics.
80
- filepath = path.resolve('DOTENV_SPEC')
81
- src = processEnv.DOTENV_SPEC
82
- } else {
83
- if (filepath === undefined) filepath = resolveEnvspecPath()
84
- try {
85
- src = fs.readFileSync(filepath, 'utf8')
86
- } catch (error) {
87
- if (error.code === 'ENOENT') {
88
- if (fs.lstatSync(filepath, { throwIfNoEntry: false })) throw new Error(`Cannot read ${path.basename(filepath)}: ${filepath}`)
89
- return { ...compileDeclarations([]), exists: false }
90
- }
91
- throw error
92
- }
93
- }
94
-
95
- let document
96
- try {
97
- document = parser.parse(src)
98
- } catch (error) {
99
- throw new Errors({ message: formatEnvspecSyntaxError(error, src, filepath) }).malformedEnvspec()
100
- }
101
-
102
- const defaults = { proxy: false, required: true, encrypted: true, redacted: true }
103
- const base = document.declarations.map(item => ({ ...defaults, ...item }))
104
- const strictByFile = new Map()
105
- const baseSchema = { ...compileDeclarations(base), encrypted: true, redacted: true, strict: document.strict ?? false, strictByFile }
106
- const selected = new Set(envFiles.map(file => path.resolve(file)))
107
- const seen = new Set()
108
- const active = []
109
- for (const block of document.files) {
110
- if (/[*?[\]]/.test(block.file)) {
111
- throw new Errors({ message: `File blocks require an exact filename: ${block.file}` }).malformedEnvspec()
112
- }
113
- const file = path.resolve(path.dirname(filepath), block.file)
114
- if (seen.has(file)) throw new Errors({ message: `Duplicate Dotenvspec file block: ${block.file}` }).malformedEnvspec()
115
- seen.add(file)
116
- const merged = new Map(base.map(item => [item.name, { ...item }]))
117
- const names = new Set()
118
- for (const item of block.declarations) {
119
- if (names.has(item.name)) throw new Errors({ message: `Duplicate Dotenvspec declaration in ${block.file}: ${item.name}` }).malformedEnvspec()
120
- names.add(item.name)
121
- merged.set(item.name, {
122
- ...defaults,
123
- ...merged.get(item.name),
124
- ...item
125
- })
126
- }
127
- const strict = block.strict ?? baseSchema.strict
128
- strictByFile.set(file, strict)
129
- const schema = { ...compileDeclarations([...merged.values()]), encrypted: true, redacted: true, strict }
130
- if (selected.has(file)) active.push(schema)
131
- }
132
- if (active.length === 0) return baseSchema
133
-
134
- // Each selected file policy must hold, regardless of file loading order.
135
- const proxyRules = new Map()
136
- for (const schema of active) {
137
- for (const [key, host] of schema.proxyRules) {
138
- if (proxyRules.has(key) && proxyRules.get(key) !== host) {
139
- throw new Errors({ message: `Conflicting Dotenvspec proxy domains for ${key} in selected file blocks` }).malformedEnvspec()
140
- }
141
- proxyRules.set(key, host)
142
- }
143
- }
144
- const redactionRules = new Map()
145
- for (const schema of active) {
146
- for (const [name, redacted] of schema.redactionRules) {
147
- redactionRules.set(name, redactionRules.get(name) === true || redacted)
148
- }
149
- }
150
- return { ...active[0], strict: baseSchema.strict, strictByFile, redactionRules, proxyRules, schemas: active }
151
- }
@@ -1,12 +0,0 @@
1
- const fs = require('node:fs')
2
- const path = require('node:path')
3
-
4
- // A present but broken Dotenvspec must fail, never fall back to a weaker policy.
5
- module.exports = function resolveEnvspecPath (directory = process.cwd()) {
6
- const preferred = path.resolve(directory, 'Dotenvspec')
7
- if (fs.lstatSync(preferred, { throwIfNoEntry: false })) return preferred
8
- const shorthand = path.resolve(directory, 'Envspec')
9
- if (fs.lstatSync(shorthand, { throwIfNoEntry: false })) return shorthand
10
- const alternate = path.resolve(directory, 'Dotenvxspec')
11
- return fs.lstatSync(alternate, { throwIfNoEntry: false }) ? alternate : preferred
12
- }
@@ -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,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
- }
@@ -1,65 +0,0 @@
1
- const eligibleHeaders = require('./eligibleHeaders')
2
-
3
- // Parent-only forwarding. Never load credential configuration into the application.
4
- function install (config, nativeFetch = globalThis.fetch) {
5
- if (typeof nativeFetch !== 'function') throw new Error('Credential proxy requires Node.js with built-in fetch.')
6
- return async function proxyFetch (input, init) {
7
- const url = new URL(input instanceof Request ? input.url : input)
8
- if (!config.credentials.some(item => item.host === url.hostname)) return nativeFetch(input, init)
9
- if (url.protocol !== 'https:' || (url.port && url.port !== '443') || url.username || url.password) {
10
- throw new Error('Credential proxy requests must use HTTPS on port 443.')
11
- }
12
- const request = new Request(input, init)
13
- const upstreamHeaders = Object.fromEntries([...request.headers].filter(([name]) => eligibleHeaders(name)))
14
- const values = Object.entries(upstreamHeaders).map(([name, value]) => {
15
- // Preserve existing Basic support: its placeholder is encoded on the wire.
16
- if (name === 'authorization' && value.startsWith('Basic ')) {
17
- const encoded = value.slice(6)
18
- const decoded = Buffer.from(encoded, 'base64')
19
- if (decoded.toString('base64') !== encoded) throw new Error('Invalid Basic authorization.')
20
- return decoded.toString('utf8')
21
- }
22
- return value
23
- })
24
- const active = config.credentials.filter(credential => {
25
- const occurrences = values.reduce((total, value) => total + value.split(credential.placeholder).length - 1, 0)
26
- if (occurrences && credential.host !== url.hostname) throw new Error('Proxy credential is not allowed at this destination.')
27
- if (occurrences > 1) throw new Error('Proxy credential must occur in only one eligible header, once.')
28
- return occurrences === 1
29
- })
30
- if (!active.length) throw new Error('Credential proxy requires a proxied environment variable in an eligible header.')
31
- if (active.length > 8 || active.some(item => item.publicKey !== active[0].publicKey)) {
32
- throw new Error('Proxy request requires at most eight credentials from the same keypair.')
33
- }
34
- const body = ['GET', 'HEAD'].includes(request.method) ? null : Buffer.from(await request.arrayBuffer())
35
- if (body && body.length > 256 * 1024) throw new Error('Proxy request body exceeds 256 KiB.')
36
- const credentials = active.map(({ publicKey, placeholder, ciphertext }) => ({ publicKey, placeholder, ciphertext }))
37
- const metadata = JSON.stringify({ headers: upstreamHeaders, credentials })
38
- if (Buffer.byteLength(metadata) > 64 * 1024) throw new Error('Proxy request metadata exceeds 64 KiB.')
39
- const payload = JSON.stringify({
40
- version: 1,
41
- request: {
42
- url: url.href,
43
- method: request.method,
44
- headers: upstreamHeaders,
45
- body: body === null ? null : { encoding: 'base64', data: body.toString('base64') }
46
- },
47
- credentials
48
- })
49
- if (Buffer.byteLength(payload) > 512 * 1024) throw new Error('Proxy request envelope exceeds 512 KiB.')
50
- const headers = new Headers({
51
- Authorization: `Bearer ${config.token}`,
52
- 'Content-Type': 'application/json'
53
- })
54
- if (config.devicePublicKey) headers.set('dotenvx-device-public-key', config.devicePublicKey)
55
- return nativeFetch(`${config.hostname}/api/proxy`, {
56
- method: 'POST',
57
- headers,
58
- body: payload,
59
- signal: request.signal,
60
- redirect: 'error'
61
- })
62
- }
63
- }
64
-
65
- module.exports = install
@@ -1,21 +0,0 @@
1
- // Other runtimes use standard proxy/CA variables. Node also needs a bridge for
2
- // older runtimes and core HTTP clients that do not read proxy variables.
3
- if (process.env.DOTENVX_PROXY_URL) {
4
- const http = require('node:http')
5
- if (typeof http.setGlobalProxyFromEnv === 'function') {
6
- http.setGlobalProxyFromEnv()
7
- } else {
8
- const { ProxyAgent, Agent, Dispatcher, setGlobalDispatcher } = require('undici')
9
- const proxy = new ProxyAgent(process.env.DOTENVX_PROXY_URL)
10
- const direct = new Agent()
11
- class ProxyDispatcher extends Dispatcher {
12
- dispatch (options, handler) {
13
- const host = new URL(options.origin).hostname
14
- return (['localhost', '127.0.0.1', '[::1]'].includes(host) ? direct : proxy).dispatch(options, handler)
15
- }
16
- }
17
- setGlobalDispatcher(new ProxyDispatcher())
18
- }
19
- const { createGlobalProxyAgent } = require('global-agent')
20
- createGlobalProxyAgent({ environmentVariableNamespace: '', forceGlobalAgent: true })
21
- }
@@ -1,3 +0,0 @@
1
- // Source installs can resolve dependencies beside the original preload. The
2
- // executable build replaces this module with the bundled, standalone script.
3
- module.exports = `require(${JSON.stringify(require.resolve('./proxyPreload'))})\n`