@dotenvx/dotenvx 2.31.1 → 2.32.1
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.
- package/CHANGELOG.md +25 -1
- package/README.md +100 -28
- package/package.json +3 -3
- package/src/cli/actions/check.js +45 -38
- package/src/cli/actions/encrypt.js +3 -5
- package/src/cli/actions/init.js +23 -13
- package/src/cli/actions/protectStdin.js +19 -3
- package/src/cli/actions/run.js +15 -11
- package/src/cli/actions/set.js +2 -4
- package/src/cli/commands/primitives.js +1 -1
- package/src/cli/dotenvx.js +8 -7
- package/src/lib/custodians/managed/armor/index.js +1 -1
- package/src/lib/custodians/managed/armor/store.js +11 -3
- package/src/lib/{envfile → envspec}/discovery/discoverEnvFiles.js +1 -1
- package/src/lib/{envfile → envspec}/discovery/scanSource.js +1 -1
- package/src/lib/{envfile/parsing/envfile.peggy → envspec/parsing/envspec.peggy} +17 -10
- package/src/lib/{envfile/parsing/envfileParser.js → envspec/parsing/envspecParser.js} +575 -455
- package/src/lib/{envfile/parsing/formatEnvfileSyntaxError.js → envspec/parsing/formatEnvspecSyntaxError.js} +1 -1
- package/src/lib/{envfile/parsing/readEnvfile.js → envspec/parsing/readEnvspec.js} +38 -27
- package/src/lib/{envfile/rendering/normalizeEnvfile.js → envspec/rendering/normalizeEnvspec.js} +7 -10
- package/src/lib/envspec/rendering/previewEnvspec.js +51 -0
- package/src/lib/envspec/rendering/renderEnvspec.js +30 -0
- package/src/lib/envspec/validation/diagnosticLocation.js +29 -0
- package/src/lib/envspec/validation/protectEnvspec.js +39 -0
- package/src/lib/envspec/validation/validateEnvspec.js +57 -0
- package/src/lib/helpers/custodySelect.js +25 -0
- package/src/lib/helpers/errors.js +7 -6
- package/src/lib/helpers/isPublicKey.js +3 -0
- package/src/lib/helpers/plaintextKeys.js +9 -0
- package/src/lib/helpers/prompts.js +7 -1
- package/src/lib/helpers/redactedValues.js +10 -4
- package/src/lib/helpers/selectKeyStorage.js +62 -17
- package/src/lib/helpers/storeKeyStorage.js +19 -0
- package/src/lib/services/armorDown.js +1 -0
- package/src/lib/services/armorMove.js +1 -0
- package/src/lib/services/armorPull.js +1 -0
- package/src/lib/services/armorPush.js +1 -0
- package/src/lib/services/armorUp.js +1 -0
- package/src/lib/services/init.js +27 -22
- package/src/lib/services/validate.js +20 -10
- package/src/lib/transforms/encrypt.js +28 -14
- package/src/lib/transforms/set.js +5 -6
- package/src/lib/envfile/rendering/renderEnvfile.js +0 -26
- package/src/lib/envfile/validation/validateEnvfile.js +0 -24
- /package/src/lib/{envfile → envspec}/discovery/extractEnvKeys.js +0 -0
- /package/src/lib/{envfile → envspec}/validation/encryptedSources.js +0 -0
- /package/src/lib/{envfile → envspec}/validation/validate.js +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const path = require('node:path')
|
|
2
2
|
|
|
3
|
-
module.exports = function
|
|
3
|
+
module.exports = function formatEnvspecSyntaxError (error, src, filepath) {
|
|
4
4
|
const location = error.location?.start
|
|
5
5
|
if (!location) return error.message
|
|
6
6
|
|
|
@@ -1,25 +1,31 @@
|
|
|
1
1
|
const fs = require('node:fs')
|
|
2
2
|
const path = require('node:path')
|
|
3
3
|
const { isIP } = require('node:net')
|
|
4
|
-
const parser = require('./
|
|
4
|
+
const parser = require('./envspecParser')
|
|
5
5
|
const Errors = require('../../helpers/errors')
|
|
6
6
|
const isValidUrl = require('../../helpers/isValidUrl')
|
|
7
7
|
const isValidEmail = require('../../helpers/isValidEmail')
|
|
8
|
-
const
|
|
8
|
+
const formatEnvspecSyntaxError = require('./formatEnvspecSyntaxError')
|
|
9
9
|
|
|
10
10
|
function compileDeclarations (declarations) {
|
|
11
11
|
const proxyRules = new Map()
|
|
12
12
|
const requiredKeys = []
|
|
13
13
|
const types = new Map()
|
|
14
|
+
const declaredTypes = new Map()
|
|
14
15
|
const enums = new Map()
|
|
15
16
|
const ranges = new Map()
|
|
16
17
|
const encryptedKeys = []
|
|
18
|
+
const redactionRules = new Map()
|
|
19
|
+
const encryptionRules = new Map()
|
|
17
20
|
const names = new Set()
|
|
18
21
|
for (const input of declarations) {
|
|
19
22
|
const declaration = { ...input }
|
|
20
|
-
if (
|
|
23
|
+
if (input.type) declaredTypes.set(input.name, input.type)
|
|
24
|
+
if (names.has(declaration.name)) throw new Errors({ message: `Duplicate Envspec declaration: ${declaration.name}` }).malformedEnvspec()
|
|
21
25
|
names.add(declaration.name)
|
|
22
|
-
|
|
26
|
+
redactionRules.set(declaration.name, declaration.redacted !== false)
|
|
27
|
+
encryptionRules.set(declaration.name, declaration.encrypted !== false)
|
|
28
|
+
if (declaration.encrypted !== false) encryptedKeys.push(declaration.name)
|
|
23
29
|
if (declaration.type === 'port') {
|
|
24
30
|
declaration.type = 'integer'
|
|
25
31
|
if (declaration.min === undefined || BigInt(declaration.min) < 0n) declaration.min = '0'
|
|
@@ -29,43 +35,43 @@ function compileDeclarations (declarations) {
|
|
|
29
35
|
if (declaration.type) types.set(declaration.name, declaration.type)
|
|
30
36
|
if (declaration.min !== undefined || declaration.max !== undefined) {
|
|
31
37
|
if (declaration.type !== 'integer') {
|
|
32
|
-
throw new Errors({ message: `Invalid
|
|
38
|
+
throw new Errors({ message: `Invalid Envspec range for ${declaration.name}: min and max require type: "integer" or "port".` }).malformedEnvspec()
|
|
33
39
|
}
|
|
34
40
|
if (declaration.min !== undefined && declaration.max !== undefined && BigInt(declaration.min) > BigInt(declaration.max)) {
|
|
35
|
-
throw new Errors({ message: `Invalid
|
|
41
|
+
throw new Errors({ message: `Invalid Envspec range for ${declaration.name}: min must be less than or equal to max.` }).malformedEnvspec()
|
|
36
42
|
}
|
|
37
43
|
ranges.set(declaration.name, { min: declaration.min, max: declaration.max })
|
|
38
44
|
}
|
|
39
45
|
if (declaration.enum) {
|
|
40
46
|
if (declaration.type === 'integer' && declaration.enum.some(value => !/^[+-]?\d+$/.test(value.trim()))) {
|
|
41
|
-
throw new Errors({ message: `Invalid
|
|
47
|
+
throw new Errors({ message: `Invalid Envspec enum for ${declaration.name}: expected integer choices.` }).malformedEnvspec()
|
|
42
48
|
}
|
|
43
49
|
if (declaration.type === 'boolean' && declaration.enum.some(value => !['true', 'false', '1', '0'].includes(value))) {
|
|
44
|
-
throw new Errors({ message: `Invalid
|
|
50
|
+
throw new Errors({ message: `Invalid Envspec enum for ${declaration.name}: expected true, false, 1, or 0 choices.` }).malformedEnvspec()
|
|
45
51
|
}
|
|
46
52
|
if (declaration.type === 'url' && declaration.enum.some(value => !isValidUrl(value))) {
|
|
47
|
-
throw new Errors({ message: `Invalid
|
|
53
|
+
throw new Errors({ message: `Invalid Envspec enum for ${declaration.name}: expected URL choices.` }).malformedEnvspec()
|
|
48
54
|
}
|
|
49
55
|
if (declaration.type === 'email' && declaration.enum.some(value => !isValidEmail(value))) {
|
|
50
|
-
throw new Errors({ message: `Invalid
|
|
56
|
+
throw new Errors({ message: `Invalid Envspec enum for ${declaration.name}: expected email choices.` }).malformedEnvspec()
|
|
51
57
|
}
|
|
52
58
|
if (declaration.type === 'ip' && declaration.enum.some(value => isIP(value) === 0)) {
|
|
53
|
-
throw new Errors({ message: `Invalid
|
|
59
|
+
throw new Errors({ message: `Invalid Envspec enum for ${declaration.name}: expected IPv4 or IPv6 choices.` }).malformedEnvspec()
|
|
54
60
|
}
|
|
55
61
|
enums.set(declaration.name, declaration.enum)
|
|
56
62
|
}
|
|
57
63
|
if (declaration.proxy) {
|
|
58
64
|
const host = declaration.proxy.domain.toLowerCase()
|
|
59
65
|
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)) {
|
|
60
|
-
throw new Errors({ message: `Invalid
|
|
66
|
+
throw new Errors({ message: `Invalid Envspec proxy host for ${declaration.name}: expected a DNS hostname without a scheme, port, path or wildcard.` }).malformedEnvspec()
|
|
61
67
|
}
|
|
62
68
|
proxyRules.set(declaration.name, host)
|
|
63
69
|
}
|
|
64
70
|
}
|
|
65
|
-
return { exists: true, proxyRules, requiredKeys, types, enums, ranges, encryptedKeys }
|
|
71
|
+
return { exists: true, proxyRules, requiredKeys, types, declaredTypes, enums, ranges, encryptedKeys, redactionRules, encryptionRules }
|
|
66
72
|
}
|
|
67
73
|
|
|
68
|
-
module.exports = function
|
|
74
|
+
module.exports = function readEnvspec (filepath = path.resolve('Envspec'), envFiles = ['.env']) {
|
|
69
75
|
let src
|
|
70
76
|
try {
|
|
71
77
|
src = fs.readFileSync(filepath, 'utf8')
|
|
@@ -78,38 +84,37 @@ module.exports = function readEnvfile (filepath = path.resolve('Envfile'), envFi
|
|
|
78
84
|
try {
|
|
79
85
|
document = parser.parse(src)
|
|
80
86
|
} catch (error) {
|
|
81
|
-
throw new Errors({ message:
|
|
87
|
+
throw new Errors({ message: formatEnvspecSyntaxError(error, src, filepath) }).malformedEnvspec()
|
|
82
88
|
}
|
|
83
89
|
|
|
84
|
-
const defaults = { proxy: false, required: true, encrypted:
|
|
90
|
+
const defaults = { proxy: false, required: true, encrypted: true, redacted: true }
|
|
85
91
|
const base = document.declarations.map(item => ({ ...defaults, ...item }))
|
|
86
|
-
const
|
|
92
|
+
const strictByFile = new Map()
|
|
93
|
+
const baseSchema = { ...compileDeclarations(base), encrypted: true, redacted: true, strict: document.strict ?? false, strictByFile }
|
|
87
94
|
const selected = new Set(envFiles.map(file => path.resolve(file)))
|
|
88
95
|
const seen = new Set()
|
|
89
96
|
const active = []
|
|
90
97
|
for (const block of document.files) {
|
|
91
98
|
if (/[*?[\]]/.test(block.file)) {
|
|
92
|
-
throw new Errors({ message: `File blocks require an exact filename: ${block.file}` }).
|
|
99
|
+
throw new Errors({ message: `File blocks require an exact filename: ${block.file}` }).malformedEnvspec()
|
|
93
100
|
}
|
|
94
101
|
const file = path.resolve(path.dirname(filepath), block.file)
|
|
95
|
-
if (seen.has(file)) throw new Errors({ message: `Duplicate
|
|
102
|
+
if (seen.has(file)) throw new Errors({ message: `Duplicate Envspec file block: ${block.file}` }).malformedEnvspec()
|
|
96
103
|
seen.add(file)
|
|
97
104
|
const merged = new Map(base.map(item => [item.name, { ...item }]))
|
|
98
|
-
if (block.encrypted !== null && block.encrypted !== undefined) {
|
|
99
|
-
for (const item of merged.values()) item.encrypted = block.encrypted
|
|
100
|
-
}
|
|
101
105
|
const names = new Set()
|
|
102
106
|
for (const item of block.declarations) {
|
|
103
|
-
if (names.has(item.name)) throw new Errors({ message: `Duplicate
|
|
107
|
+
if (names.has(item.name)) throw new Errors({ message: `Duplicate Envspec declaration in ${block.file}: ${item.name}` }).malformedEnvspec()
|
|
104
108
|
names.add(item.name)
|
|
105
109
|
merged.set(item.name, {
|
|
106
110
|
...defaults,
|
|
107
|
-
...(block.encrypted === null || block.encrypted === undefined ? {} : { encrypted: block.encrypted }),
|
|
108
111
|
...merged.get(item.name),
|
|
109
112
|
...item
|
|
110
113
|
})
|
|
111
114
|
}
|
|
112
|
-
const
|
|
115
|
+
const strict = block.strict ?? baseSchema.strict
|
|
116
|
+
strictByFile.set(file, strict)
|
|
117
|
+
const schema = { ...compileDeclarations([...merged.values()]), encrypted: true, redacted: true, strict }
|
|
113
118
|
if (selected.has(file)) active.push(schema)
|
|
114
119
|
}
|
|
115
120
|
if (active.length === 0) return baseSchema
|
|
@@ -119,10 +124,16 @@ module.exports = function readEnvfile (filepath = path.resolve('Envfile'), envFi
|
|
|
119
124
|
for (const schema of active) {
|
|
120
125
|
for (const [key, host] of schema.proxyRules) {
|
|
121
126
|
if (proxyRules.has(key) && proxyRules.get(key) !== host) {
|
|
122
|
-
throw new Errors({ message: `Conflicting
|
|
127
|
+
throw new Errors({ message: `Conflicting Envspec proxy domains for ${key} in selected file blocks` }).malformedEnvspec()
|
|
123
128
|
}
|
|
124
129
|
proxyRules.set(key, host)
|
|
125
130
|
}
|
|
126
131
|
}
|
|
127
|
-
|
|
132
|
+
const redactionRules = new Map()
|
|
133
|
+
for (const schema of active) {
|
|
134
|
+
for (const [name, redacted] of schema.redactionRules) {
|
|
135
|
+
redactionRules.set(name, redactionRules.get(name) === true || redacted)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return { ...active[0], strict: baseSchema.strict, strictByFile, redactionRules, proxyRules, schemas: active }
|
|
128
139
|
}
|
package/src/lib/{envfile/rendering/normalizeEnvfile.js → envspec/rendering/normalizeEnvspec.js}
RENAMED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// Pure final pass over independently inferred file rules. Never mutates inputs.
|
|
2
|
-
module.exports = function
|
|
2
|
+
module.exports = function normalizeEnvspec ({ files, codeDeclarations = [] }) {
|
|
3
3
|
const hasNamedEnvironment = files.some(file => !['.env', '.env.example'].includes(file.filename))
|
|
4
4
|
const rootFiles = []
|
|
5
5
|
const environments = []
|
|
6
6
|
for (const file of files) {
|
|
7
|
-
if (file.filename === '.env.example' || (file.filename === '.env' && !hasNamedEnvironment)) rootFiles.push(file)
|
|
7
|
+
if ((file.filename === '.env.example' || (file.filename === '.env' && !hasNamedEnvironment))) rootFiles.push(file)
|
|
8
8
|
else environments.push(file)
|
|
9
9
|
}
|
|
10
10
|
|
|
11
|
-
const encrypted =
|
|
11
|
+
const encrypted = true
|
|
12
12
|
const root = new Map()
|
|
13
13
|
for (const file of rootFiles) {
|
|
14
14
|
for (const item of file.declarations) {
|
|
@@ -22,22 +22,19 @@ module.exports = function normalizeEnvfile ({ files, codeDeclarations = [] }) {
|
|
|
22
22
|
const matches = environments.map(file => file.declarations.find(other => other.name === item.name))
|
|
23
23
|
if (!root.has(item.name) && matches.every(other => other && other.type === item.type && other.optional === item.optional)) {
|
|
24
24
|
// Keep encryption differences in their file scopes, not the shared declaration.
|
|
25
|
-
root.set(item.name, { ...item, encrypted })
|
|
25
|
+
root.set(item.name, { ...item, encrypted: matches.some(other => other.encrypted !== false) })
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
const blocks = environments.map(file => {
|
|
31
|
-
const overridesEncryption = file.encrypted !== encrypted
|
|
32
31
|
const declarations = file.declarations.flatMap(item => {
|
|
33
32
|
const inherited = root.get(item.name)
|
|
34
|
-
const defaults = inherited
|
|
35
|
-
? { ...inherited, encrypted: overridesEncryption ? file.encrypted : inherited.encrypted }
|
|
36
|
-
: { encrypted: file.encrypted }
|
|
33
|
+
const defaults = inherited || { encrypted: true }
|
|
37
34
|
const overrides = Object.fromEntries(Object.entries(item).filter(([key, value]) => key !== 'name' && value !== defaults[key]))
|
|
38
35
|
return inherited && !Object.keys(overrides).length ? [] : [{ name: item.name, ...overrides }]
|
|
39
36
|
})
|
|
40
|
-
return { filename: file.filename,
|
|
37
|
+
return { filename: file.filename, declarations }
|
|
41
38
|
})
|
|
42
39
|
|
|
43
40
|
const names = new Set(files.flatMap(file => file.declarations.map(item => item.name)))
|
|
@@ -52,5 +49,5 @@ module.exports = function normalizeEnvfile ({ files, codeDeclarations = [] }) {
|
|
|
52
49
|
if (result.encrypted === encrypted) delete result.encrypted
|
|
53
50
|
return result
|
|
54
51
|
})
|
|
55
|
-
return {
|
|
52
|
+
return { declarations, files: blocks, codeDeclarations: code }
|
|
56
53
|
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const { encrypted } = require('@dotenvx/primitives')
|
|
2
|
+
const diagnosticLocations = require('../validation/diagnosticLocation')
|
|
3
|
+
const { getColor } = require('../../../shared/colors')
|
|
4
|
+
|
|
5
|
+
function displayValue (value) {
|
|
6
|
+
const hasControl = Array.from(value).some(char => char.charCodeAt(0) < 32)
|
|
7
|
+
if (value && !hasControl && !/[\s#"'`\\\x7f-\x9f]/.test(value)) return value
|
|
8
|
+
return JSON.stringify(value).replace(/[\x7f-\x9f\u2028\u2029]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`)
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// Show final resolved values once, not source contents or unrelated shell variables.
|
|
12
|
+
module.exports = function previewEnvspec (processedEnvs, schema, processEnv, proxyCredentials = [], diagnostics = []) {
|
|
13
|
+
const keys = new Set((processedEnvs || []).flatMap(row => [...Object.keys(row.parsed || {}), ...Object.keys(row.injected || {}), ...Object.keys(row.existed || {})]))
|
|
14
|
+
for (const key of schema.redactionRules.keys()) keys.add(key)
|
|
15
|
+
const proxyKeys = new Set(proxyCredentials.map(credential => credential.name))
|
|
16
|
+
const location = diagnosticLocations(processedEnvs || [], 'process.env', { environmentLabel: 'process.env' })
|
|
17
|
+
const rows = []
|
|
18
|
+
const errors = new Map()
|
|
19
|
+
for (const diagnostic of diagnostics) {
|
|
20
|
+
keys.add(diagnostic.key)
|
|
21
|
+
const message = diagnostic.rule
|
|
22
|
+
? `!${diagnostic.rule}`
|
|
23
|
+
: diagnostic.code === 'EXPECTED_ENCRYPTED'
|
|
24
|
+
? '!encrypted'
|
|
25
|
+
: diagnostic.code === 'MISSING_REQUIRED'
|
|
26
|
+
? '!required'
|
|
27
|
+
: `! ${diagnostic.message.slice(diagnostic.key.length + 1).replace(/^is /, '')}`
|
|
28
|
+
errors.set(diagnostic.key, [...new Set([...(errors.get(diagnostic.key) || []), message])])
|
|
29
|
+
}
|
|
30
|
+
for (const key of keys) {
|
|
31
|
+
const missing = processEnv[key] === undefined
|
|
32
|
+
if (/^DOTENV_(?:PUBLIC|PRIVATE)_KEY/.test(key) || (missing && !errors.has(key))) continue
|
|
33
|
+
const value = String(processEnv[key])
|
|
34
|
+
const redacted = schema.redactionRules.get(key) ?? true
|
|
35
|
+
const display = missing ? '[MISSING]' : redacted || encrypted(value) || proxyKeys.has(key) ? '[REDACTED]' : displayValue(value)
|
|
36
|
+
const source = missing ? '' : displayValue(location(key))
|
|
37
|
+
const error = errors.has(key) ? errors.get(key).join(', ') : ''
|
|
38
|
+
const unspecced = !schema.redactionRules.has(key)
|
|
39
|
+
const status = [unspecced ? '!declared' : '', error].filter(Boolean).join(', ')
|
|
40
|
+
rows.push({ assignment: `${key}=${display}`, comment: [source, status].filter(Boolean).join(' '), error, unspecced })
|
|
41
|
+
}
|
|
42
|
+
const width = Math.max(0, ...rows.map(row => row.assignment.length))
|
|
43
|
+
return rows.map(({ assignment, comment, error, unspecced }) => {
|
|
44
|
+
const line = `${assignment.padEnd(width)} # ${comment}`
|
|
45
|
+
return error
|
|
46
|
+
? getColor('red', process.stdout)(`☠ ${line}`)
|
|
47
|
+
: unspecced
|
|
48
|
+
? getColor('orangered', process.stdout)(`⚠ ${line}`)
|
|
49
|
+
: `${getColor('green', process.stdout)('✔')} ${getColor('gray', process.stdout)(line)}`
|
|
50
|
+
}).join('\n')
|
|
51
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
function declaration (item) {
|
|
2
|
+
let line = `env "${item.name}"`
|
|
3
|
+
if (item.type) line += `, type: "${item.type}"`
|
|
4
|
+
if (item.encrypted !== undefined) line += `, encrypted: ${item.encrypted}`
|
|
5
|
+
if (item.redacted !== undefined) line += `, redacted: ${item.redacted}`
|
|
6
|
+
if (item.optional !== undefined) line += `, optional: ${item.optional}`
|
|
7
|
+
return line
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function renderFile (file) {
|
|
11
|
+
const quote = file.filename.includes('"') ? "'" : '"'
|
|
12
|
+
if (file.filename.includes(quote) || /[\r\n\0*?[\]{}]/.test(file.filename)) {
|
|
13
|
+
throw new Error(`Unsupported Envspec filename: ${file.filename}`)
|
|
14
|
+
}
|
|
15
|
+
const lines = [`file ${quote}${file.filename}${quote} do`]
|
|
16
|
+
lines.push(...file.declarations.map(item => ` ${declaration(item)}`), 'end')
|
|
17
|
+
return lines.join('\n')
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
module.exports = function renderEnvspec (document) {
|
|
21
|
+
const sections = []
|
|
22
|
+
if (document.declarations.length) sections.push(document.declarations.map(declaration).join('\n'))
|
|
23
|
+
for (const file of document.files) {
|
|
24
|
+
sections.push(renderFile(file))
|
|
25
|
+
}
|
|
26
|
+
if (document.codeDeclarations.length) {
|
|
27
|
+
sections.push('# additionally found in code\n' + document.codeDeclarations.map(declaration).join('\n'))
|
|
28
|
+
}
|
|
29
|
+
return '# Envspec (safe to commit)\n# ------------------------\n\n' + sections.join('\n\n') + (sections.length ? '\n' : '')
|
|
30
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const path = require('node:path')
|
|
2
|
+
|
|
3
|
+
// Match the assignment grammar used by primitives.scan, including multiline values.
|
|
4
|
+
function assignmentLines (src) {
|
|
5
|
+
const text = (src || '').toString().replace(/\r\n?/g, '\n')
|
|
6
|
+
const assignment = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#(.*))?$/mg
|
|
7
|
+
const result = new Map()
|
|
8
|
+
for (const match of text.matchAll(assignment)) {
|
|
9
|
+
const start = match.index + match[0].search(/\S/)
|
|
10
|
+
result.set(match[1], text.slice(0, start).split('\n').length)
|
|
11
|
+
}
|
|
12
|
+
return result
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
module.exports = function diagnosticLocations (processedEnvs, fallback, { environmentLabel } = {}) {
|
|
16
|
+
const locations = new Map()
|
|
17
|
+
for (const row of processedEnvs) {
|
|
18
|
+
const filename = row.type === 'envFile' ? path.relative(process.cwd(), path.resolve(row.filepath)) : (environmentLabel || '--env')
|
|
19
|
+
const lines = assignmentLines(row.src || row.string)
|
|
20
|
+
for (const key of Object.keys(row.injected || {})) {
|
|
21
|
+
const line = row.type === 'envFile' || !environmentLabel ? lines.get(key) : undefined
|
|
22
|
+
locations.set(key, line ? `${filename}:${line}` : filename)
|
|
23
|
+
}
|
|
24
|
+
for (const key of Object.keys(row.existed || {})) {
|
|
25
|
+
if (!locations.has(key)) locations.set(key, environmentLabel || 'shell environment')
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return key => locations.get(key) || fallback
|
|
29
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
const fs = require('node:fs')
|
|
2
|
+
const path = require('node:path')
|
|
3
|
+
const { execFileSync } = require('node:child_process')
|
|
4
|
+
const readEnvspec = require('../parsing/readEnvspec')
|
|
5
|
+
const plaintextKeys = require('../../helpers/plaintextKeys')
|
|
6
|
+
|
|
7
|
+
function readPolicy (policyPath, file) {
|
|
8
|
+
const schema = readEnvspec(policyPath, [file])
|
|
9
|
+
if (!schema.exists) {
|
|
10
|
+
// A dangling policy symlink is a broken policy, not an absent policy.
|
|
11
|
+
if (fs.lstatSync(policyPath, { throwIfNoEntry: false })) throw new Error(`Cannot read Envspec: ${policyPath}`)
|
|
12
|
+
return null
|
|
13
|
+
}
|
|
14
|
+
return schema
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Inspect Git's incoming blob, never the working-tree env values or shell overrides.
|
|
18
|
+
module.exports = function protectEnvspec (filepath, content) {
|
|
19
|
+
const file = path.resolve(filepath)
|
|
20
|
+
const directory = path.dirname(file)
|
|
21
|
+
let schema = readPolicy(path.join(directory, 'Envspec'), file)
|
|
22
|
+
if (!schema) {
|
|
23
|
+
let root
|
|
24
|
+
try {
|
|
25
|
+
root = execFileSync('git', ['rev-parse', '--show-toplevel'], {
|
|
26
|
+
cwd: directory,
|
|
27
|
+
encoding: 'utf8',
|
|
28
|
+
stdio: ['ignore', 'pipe', 'ignore']
|
|
29
|
+
}).trim()
|
|
30
|
+
} catch {
|
|
31
|
+
// Outside a Git working tree, only an adjacent policy can apply.
|
|
32
|
+
return null
|
|
33
|
+
}
|
|
34
|
+
if (path.resolve(root) !== directory) schema = readPolicy(path.join(root, 'Envspec'), file)
|
|
35
|
+
}
|
|
36
|
+
if (!schema) return null
|
|
37
|
+
|
|
38
|
+
return plaintextKeys(content).filter(key => /^DOTENV_PRIVATE_KEY(?:_|$)/.test(key) || (schema.encryptionRules.get(key) ?? true))
|
|
39
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
const { Enquirer } = require('@dotenvx/tooling')
|
|
2
|
+
|
|
3
|
+
class CustodySelect extends Enquirer.prompts.Select {
|
|
4
|
+
keypress (input, key = {}) {
|
|
5
|
+
if (key.name === 'escape') return this.cancel(new Error('Cancelled'))
|
|
6
|
+
if (key.name === 'left' && this.options.backValue) {
|
|
7
|
+
this.index = this.choices.findIndex(choice => choice.name === this.options.backValue)
|
|
8
|
+
return this.submit()
|
|
9
|
+
}
|
|
10
|
+
return super.keypress(input, key)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async render () {
|
|
14
|
+
// Replace the previous step instead of leaving a trail of completed menus.
|
|
15
|
+
if (this.state.submitted) {
|
|
16
|
+
this.clear(this.state.size)
|
|
17
|
+
this.state.prompt = ''
|
|
18
|
+
this.state.size = 0
|
|
19
|
+
return
|
|
20
|
+
}
|
|
21
|
+
return super.render()
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
module.exports = CustodySelect
|
|
@@ -233,10 +233,11 @@ class Errors {
|
|
|
233
233
|
return e
|
|
234
234
|
}
|
|
235
235
|
|
|
236
|
-
|
|
237
|
-
const e = new Error('[
|
|
238
|
-
e.code = '
|
|
239
|
-
e.
|
|
236
|
+
envspecRequired () {
|
|
237
|
+
const e = new Error('[ENVSPEC_REQUIRED] check requires an Envspec')
|
|
238
|
+
e.code = 'ENVSPEC_REQUIRED'
|
|
239
|
+
e.help = 'fix: run [dotenvx spec]'
|
|
240
|
+
e.messageWithHelp = `${e.message}. ${e.help}`
|
|
240
241
|
return e
|
|
241
242
|
}
|
|
242
243
|
|
|
@@ -338,8 +339,8 @@ class Errors {
|
|
|
338
339
|
return e
|
|
339
340
|
}
|
|
340
341
|
|
|
341
|
-
|
|
342
|
-
const code = '
|
|
342
|
+
malformedEnvspec () {
|
|
343
|
+
const code = 'MALFORMED_ENVSPEC'
|
|
343
344
|
const message = `[${code}] ${this.message}`
|
|
344
345
|
const e = new Error(message)
|
|
345
346
|
e.code = code
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
const { scan, encrypted } = require('@dotenvx/primitives')
|
|
2
|
+
|
|
3
|
+
module.exports = function plaintextKeys (content) {
|
|
4
|
+
return Object.entries(scan(content).parsed)
|
|
5
|
+
.filter(([key, values]) => !key.startsWith('DOTENV_PUBLIC_KEY') && values.some(value =>
|
|
6
|
+
value.trim() !== '' && !encrypted(value) && !value.startsWith('op://') && !value.startsWith('bw://')
|
|
7
|
+
))
|
|
8
|
+
.map(([key]) => key)
|
|
9
|
+
}
|
|
@@ -9,6 +9,7 @@ function choicesForSelect (choices) {
|
|
|
9
9
|
return {
|
|
10
10
|
name: choice.value,
|
|
11
11
|
message: choice.name || choice.value,
|
|
12
|
+
...(choice.role ? { role: choice.role } : {}),
|
|
12
13
|
...(choice.disabled !== undefined ? { disabled: choice.disabled === true ? '(unavailable)' : choice.disabled } : {})
|
|
13
14
|
}
|
|
14
15
|
})
|
|
@@ -39,10 +40,15 @@ function clearLastLine (stream) {
|
|
|
39
40
|
}
|
|
40
41
|
}
|
|
41
42
|
|
|
42
|
-
async function select ({ message, choices }, context) {
|
|
43
|
+
async function select ({ message, choices, navigation, backValue, initial, prefix }, context) {
|
|
44
|
+
if (navigation) {
|
|
45
|
+
const CustodySelect = require('./custodySelect')
|
|
46
|
+
return new CustodySelect({ message, choices: choicesForSelect(choices), backValue, initial, ...(prefix ? { symbols: { prefix: { pending: prefix } } } : {}), ...enquirerOptions(context) }).run()
|
|
47
|
+
}
|
|
43
48
|
const answer = await enquirer.prompt({
|
|
44
49
|
type: 'select',
|
|
45
50
|
name: 'value',
|
|
51
|
+
...(prefix ? { symbols: { prefix: { pending: prefix } } } : {}),
|
|
46
52
|
message,
|
|
47
53
|
choices: choicesForSelect(choices),
|
|
48
54
|
...enquirerOptions(context)
|
|
@@ -1,16 +1,22 @@
|
|
|
1
|
-
const
|
|
1
|
+
const isPublicKey = require('./isPublicKey')
|
|
2
2
|
|
|
3
|
-
function redactedValues (processedEnvs) {
|
|
3
|
+
function redactedValues (processedEnvs, schema, processEnv = {}, legacyRedact = false) {
|
|
4
|
+
if (!schema?.exists && !legacyRedact) return []
|
|
4
5
|
const result = new Set()
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
const rows = [...(processedEnvs || [])]
|
|
8
|
+
if (schema?.exists) {
|
|
9
|
+
rows.push({ injected: Object.fromEntries([...schema.redactionRules.keys()].map(key => [key, processEnv[key]])) })
|
|
10
|
+
}
|
|
11
|
+
for (const processedEnv of rows) {
|
|
7
12
|
const values = {
|
|
8
13
|
...(processedEnv.injected || {}),
|
|
9
14
|
...(processedEnv.existed || {})
|
|
10
15
|
}
|
|
11
16
|
|
|
12
17
|
for (const [key, value] of Object.entries(values)) {
|
|
13
|
-
|
|
18
|
+
const redacted = schema?.exists ? (schema.redactionRules.get(key) ?? schema.redacted) : !isPublicKey(key)
|
|
19
|
+
if (!redacted) continue
|
|
14
20
|
if (value === undefined || value === null || value === '') continue
|
|
15
21
|
|
|
16
22
|
result.add(`${value}`)
|
|
@@ -1,28 +1,73 @@
|
|
|
1
1
|
const prompts = require('./prompts')
|
|
2
2
|
const custodians = require('../custodians')
|
|
3
|
+
const createSpinner = require('./createSpinner')
|
|
4
|
+
|
|
5
|
+
const nativeNames = { darwin: 'macOS Keychain', win32: 'Windows Credential Manager', linux: 'Linux Secret Service' }
|
|
3
6
|
|
|
4
7
|
async function selectKeyStorage (options = {}) {
|
|
5
8
|
const defaultStorage = custodians.get('native').enabled(options) ? 'native' : 'file'
|
|
6
9
|
if (process.env.CI || options.noCreate || !process.stdin.isTTY || !process.stderr.isTTY) return defaultStorage
|
|
7
10
|
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
11
|
+
const groups = new Map()
|
|
12
|
+
const setup = new Map()
|
|
13
|
+
const definitions = [
|
|
14
|
+
['local', ['file', 'native']],
|
|
15
|
+
['passwords', ['onepassword', 'bitwarden']],
|
|
16
|
+
['armored', ['armored']]
|
|
17
|
+
]
|
|
18
|
+
for (const [group, ids] of definitions) {
|
|
19
|
+
const entries = []
|
|
20
|
+
for (const id of ids) {
|
|
21
|
+
const custodian = custodians.get(id)
|
|
22
|
+
if (!custodian.enabled(options)) continue
|
|
23
|
+
let name = id === 'native' ? nativeNames[process.platform] : id === 'file' ? `File ${options.fk || '.env.keys'}` : id === 'armored' ? '⛨ Dotenvx Armor' : custodian.name
|
|
24
|
+
if (!await custodian.available()) {
|
|
25
|
+
const command = id === 'onepassword' ? 'op' : 'bw'
|
|
26
|
+
name += ' (install CLI)'
|
|
27
|
+
setup.set(id, `Install the ${custodian.name} CLI (${command}), then retry this command.`)
|
|
28
|
+
} else if (id === 'armored' && !await custodian.configured(options)) {
|
|
29
|
+
name += ' (sign in)'
|
|
30
|
+
setup.set(id, 'Sign in with [dotenvx armor login], then retry this command.')
|
|
31
|
+
}
|
|
32
|
+
entries.push({ name, value: id })
|
|
33
|
+
}
|
|
34
|
+
if (entries.length) groups.set(group, entries)
|
|
35
|
+
}
|
|
24
36
|
|
|
25
|
-
|
|
37
|
+
createSpinner.pause()
|
|
38
|
+
try {
|
|
39
|
+
const context = { input: process.stdin, output: process.stderr }
|
|
40
|
+
const choices = [
|
|
41
|
+
{ name: '⛉ Local', value: 'local' },
|
|
42
|
+
...(groups.get('armored') || []),
|
|
43
|
+
...(groups.has('passwords') ? [{ name: '⛊ Password Managers', value: 'passwords' }] : [])
|
|
44
|
+
]
|
|
45
|
+
let initial = 'local'
|
|
46
|
+
while (true) {
|
|
47
|
+
const category = await prompts.select({ message: 'Choose private key custody', choices, navigation: true, initial }, context)
|
|
48
|
+
if (!choices.some(choice => choice.value === category)) throw new Error('Invalid private key storage selection')
|
|
49
|
+
let storage = category
|
|
50
|
+
if (category !== 'armored') {
|
|
51
|
+
const entries = groups.get(category)
|
|
52
|
+
storage = await prompts.select({
|
|
53
|
+
message: category === 'local' ? 'Choose local custody' : 'Choose password manager',
|
|
54
|
+
prefix: category === 'local' ? '⛉' : '⛊',
|
|
55
|
+
choices: [...entries, { name: '← back', value: '__back' }],
|
|
56
|
+
navigation: true,
|
|
57
|
+
backValue: '__back'
|
|
58
|
+
}, context)
|
|
59
|
+
if (storage === '__back') {
|
|
60
|
+
initial = category
|
|
61
|
+
continue
|
|
62
|
+
}
|
|
63
|
+
if (!entries.some(choice => choice.value === storage)) throw new Error('Invalid private key storage selection')
|
|
64
|
+
}
|
|
65
|
+
if (setup.has(storage)) throw new Error(setup.get(storage))
|
|
66
|
+
return storage
|
|
67
|
+
}
|
|
68
|
+
} finally {
|
|
69
|
+
createSpinner.resume()
|
|
70
|
+
}
|
|
26
71
|
}
|
|
27
72
|
|
|
28
73
|
module.exports = selectKeyStorage
|