@dotenvx/dotenvx 2.31.0 → 2.32.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 (37) hide show
  1. package/CHANGELOG.md +18 -1
  2. package/README.md +100 -28
  3. package/package.json +3 -3
  4. package/src/cli/actions/check.js +45 -38
  5. package/src/cli/actions/init.js +23 -13
  6. package/src/cli/actions/protectStdin.js +19 -3
  7. package/src/cli/actions/run.js +15 -11
  8. package/src/cli/commands/armor.js +1 -1
  9. package/src/cli/commands/primitives.js +1 -1
  10. package/src/cli/dotenvx.js +8 -7
  11. package/src/lib/custodians/resolveLocalKey.js +68 -0
  12. package/src/lib/{envfile → envspec}/discovery/discoverEnvFiles.js +1 -1
  13. package/src/lib/{envfile → envspec}/discovery/scanSource.js +1 -1
  14. package/src/lib/{envfile/parsing/envfile.peggy → envspec/parsing/envspec.peggy} +17 -10
  15. package/src/lib/{envfile/parsing/envfileParser.js → envspec/parsing/envspecParser.js} +575 -455
  16. package/src/lib/{envfile/parsing/formatEnvfileSyntaxError.js → envspec/parsing/formatEnvspecSyntaxError.js} +1 -1
  17. package/src/lib/{envfile/parsing/readEnvfile.js → envspec/parsing/readEnvspec.js} +38 -27
  18. package/src/lib/{envfile/rendering/normalizeEnvfile.js → envspec/rendering/normalizeEnvspec.js} +7 -10
  19. package/src/lib/envspec/rendering/previewEnvspec.js +51 -0
  20. package/src/lib/envspec/rendering/renderEnvspec.js +30 -0
  21. package/src/lib/envspec/validation/diagnosticLocation.js +29 -0
  22. package/src/lib/envspec/validation/protectEnvspec.js +39 -0
  23. package/src/lib/envspec/validation/validateEnvspec.js +57 -0
  24. package/src/lib/helpers/errors.js +7 -6
  25. package/src/lib/helpers/isPublicKey.js +3 -0
  26. package/src/lib/helpers/plaintextKeys.js +9 -0
  27. package/src/lib/helpers/redactedValues.js +10 -4
  28. package/src/lib/services/armorPush.js +3 -15
  29. package/src/lib/services/armorUp.js +5 -12
  30. package/src/lib/services/init.js +27 -22
  31. package/src/lib/services/validate.js +20 -10
  32. package/src/lib/transforms/encrypt.js +21 -8
  33. package/src/lib/envfile/rendering/renderEnvfile.js +0 -26
  34. package/src/lib/envfile/validation/validateEnvfile.js +0 -24
  35. /package/src/lib/{envfile → envspec}/discovery/extractEnvKeys.js +0 -0
  36. /package/src/lib/{envfile → envspec}/validation/encryptedSources.js +0 -0
  37. /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 formatEnvfileSyntaxError (error, src, filepath) {
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('./envfileParser')
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 formatEnvfileSyntaxError = require('./formatEnvfileSyntaxError')
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 (names.has(declaration.name)) throw new Errors({ message: `Duplicate Envfile declaration: ${declaration.name}` }).malformedEnvfile()
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
- if (declaration.encrypted) encryptedKeys.push(declaration.name)
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 Envfile range for ${declaration.name}: min and max require type: "integer" or "port".` }).malformedEnvfile()
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 Envfile range for ${declaration.name}: min must be less than or equal to max.` }).malformedEnvfile()
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 Envfile enum for ${declaration.name}: expected integer choices.` }).malformedEnvfile()
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 Envfile enum for ${declaration.name}: expected true, false, 1, or 0 choices.` }).malformedEnvfile()
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 Envfile enum for ${declaration.name}: expected URL choices.` }).malformedEnvfile()
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 Envfile enum for ${declaration.name}: expected email choices.` }).malformedEnvfile()
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 Envfile enum for ${declaration.name}: expected IPv4 or IPv6 choices.` }).malformedEnvfile()
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 Envfile proxy host for ${declaration.name}: expected a DNS hostname without a scheme, port, path or wildcard.` }).malformedEnvfile()
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 readEnvfile (filepath = path.resolve('Envfile'), envFiles = ['.env']) {
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: formatEnvfileSyntaxError(error, src, filepath) }).malformedEnvfile()
87
+ throw new Errors({ message: formatEnvspecSyntaxError(error, src, filepath) }).malformedEnvspec()
82
88
  }
83
89
 
84
- const defaults = { proxy: false, required: true, encrypted: document.encrypted }
90
+ const defaults = { proxy: false, required: true, encrypted: true, redacted: true }
85
91
  const base = document.declarations.map(item => ({ ...defaults, ...item }))
86
- const baseSchema = compileDeclarations(base)
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}` }).malformedEnvfile()
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 Envfile file block: ${block.file}` }).malformedEnvfile()
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 Envfile declaration in ${block.file}: ${item.name}` }).malformedEnvfile()
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 schema = compileDeclarations([...merged.values()])
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 Envfile proxy domains for ${key} in selected file blocks` }).malformedEnvfile()
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
- return { ...active[0], proxyRules, schemas: active }
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
  }
@@ -1,14 +1,14 @@
1
1
  // Pure final pass over independently inferred file rules. Never mutates inputs.
2
- module.exports = function normalizeEnvfile ({ files, codeDeclarations = [] }) {
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 = rootFiles.some(file => file.hasValues) && rootFiles.every(file => !file.hasValues || file.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, ...(overridesEncryption ? { encrypted: file.encrypted } : {}), declarations }
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 { encrypted, declarations, files: blocks, codeDeclarations: code }
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
+ }
@@ -233,10 +233,11 @@ class Errors {
233
233
  return e
234
234
  }
235
235
 
236
- envfileRequired () {
237
- const e = new Error('[ENVFILE_REQUIRED] check requires an Envfile')
238
- e.code = 'ENVFILE_REQUIRED'
239
- e.messageWithHelp = e.message
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
- malformedEnvfile () {
342
- const code = 'MALFORMED_ENVFILE'
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,3 @@
1
+ module.exports = function isPublicKey (name) {
2
+ return name.includes('PUBLIC') || name.startsWith('VITE')
3
+ }
@@ -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
+ }
@@ -1,16 +1,22 @@
1
- const isPlainKey = require('./cryptography/isPlainKey')
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
- for (const processedEnv of processedEnvs || []) {
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
- if (isPlainKey(key)) continue
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,19 +1,9 @@
1
- const { derive } = require('@dotenvx/primitives')
2
1
  const prompts = require('../helpers/prompts')
2
+ const resolveLocalKey = require('../custodians/resolveLocalKey')
3
3
  const PostArmorPush = require('../api/postArmorPush')
4
- const keynames = require('../conventions/keynames')
5
- const readEnvKey = require('../helpers/readEnvKey')
6
4
  const teamChoicesFromMeta = require('../helpers/teamChoicesFromMeta')
7
5
  const isTeamRequiredError = require('../helpers/isTeamRequiredError')
8
6
 
9
- function publicKeyFromPrivateKey (privateKey) {
10
- try {
11
- return derive(privateKey)
12
- } catch {
13
- return ''
14
- }
15
- }
16
-
17
7
  class ArmorPush {
18
8
  constructor (hostname, token, devicePublicKey, envFile = '.env', team = undefined) {
19
9
  this.hostname = hostname
@@ -30,10 +20,8 @@ class ArmorPush {
30
20
  const envFile = this.envFile
31
21
  const team = this.team
32
22
 
33
- const { privateKeyName } = keynames(envFile)
34
-
35
- const privateKey = readEnvKey(privateKeyName, '.env.keys', { strict: true })
36
- const publicKey = publicKeyFromPrivateKey(privateKey)
23
+ const source = await resolveLocalKey(envFile)
24
+ const { publicKey, privateKey, privateKeyName } = source
37
25
 
38
26
  let json
39
27
 
@@ -1,8 +1,6 @@
1
1
  const prompts = require('../helpers/prompts')
2
+ const resolveLocalKey = require('../custodians/resolveLocalKey')
2
3
  const PostArmorUp = require('../api/postArmorUp')
3
- const keynames = require('../conventions/keynames')
4
- const removeEnvKey = require('../helpers/removeEnvKey')
5
- const readEnvKey = require('../helpers/readEnvKey')
6
4
  const teamChoicesFromMeta = require('../helpers/teamChoicesFromMeta')
7
5
  const isTeamRequiredError = require('../helpers/isTeamRequiredError')
8
6
 
@@ -22,13 +20,8 @@ class ArmorUp {
22
20
  const envFile = this.envFile
23
21
  const team = this.team
24
22
 
25
- const {
26
- publicKeyName,
27
- privateKeyName
28
- } = keynames(envFile)
29
-
30
- const publicKey = readEnvKey(publicKeyName, envFile, { strict: true, ignore: ['MISSING_PRIVATE_KEY'] })
31
- const privateKey = readEnvKey(privateKeyName, '.env.keys', { strict: true, ignore: ['MISSING_KEY'] })
23
+ const source = await resolveLocalKey(envFile, { allowMissing: true })
24
+ const { publicKey, privateKey, privateKeyName } = source
32
25
 
33
26
  let json
34
27
 
@@ -59,11 +52,11 @@ class ArmorUp {
59
52
  }
60
53
  }
61
54
 
62
- removeEnvKey(privateKeyName)
55
+ await source.remove()
63
56
 
64
57
  return {
65
58
  ...json,
66
- changed: json.changed,
59
+ changed: Boolean(json.changed || privateKey),
67
60
  privateKeyName,
68
61
  privateKeyValue: json.private_key,
69
62
  publicKeyValue: publicKey