@dotenvx/dotenvx 2.29.0 → 2.31.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.
- package/CHANGELOG.md +24 -1
- package/README.md +81 -749
- package/package.json +5 -5
- package/src/cli/actions/armor/down.js +1 -1
- package/src/cli/actions/armor/move.js +1 -1
- package/src/cli/actions/armor/open.js +1 -1
- package/src/cli/actions/armor/pull.js +1 -1
- package/src/cli/actions/armor/push.js +1 -1
- package/src/cli/actions/armor/up.js +1 -1
- package/src/cli/actions/{validate.js → check.js} +5 -5
- package/src/cli/actions/curl.js +2 -2
- package/src/cli/actions/decrypt.js +4 -10
- package/src/cli/actions/del.js +3 -5
- package/src/cli/actions/encrypt.js +4 -10
- package/src/cli/actions/ext/genexample.js +1 -1
- package/src/cli/actions/ext/prebuild.js +1 -1
- package/src/cli/actions/ext/scan.js +2 -3
- package/src/cli/actions/feedback.js +42 -0
- package/src/cli/actions/get.js +4 -7
- package/src/cli/actions/init.js +56 -2
- package/src/cli/actions/keychain/down.js +1 -1
- package/src/cli/actions/keychain/pull.js +1 -1
- package/src/cli/actions/keychain/push.js +1 -1
- package/src/cli/actions/keychain/up.js +1 -1
- package/src/cli/actions/keypair.js +3 -3
- package/src/cli/actions/lock/down.js +2 -3
- package/src/cli/actions/lock/up.js +2 -3
- package/src/cli/actions/login.js +2 -2
- package/src/cli/actions/logout.js +1 -1
- package/src/cli/actions/ls.js +1 -1
- package/src/cli/actions/protect.js +4 -1
- package/src/cli/actions/protectDocker.js +2 -2
- package/src/cli/actions/protectProcess.js +4 -1
- package/src/cli/actions/protectStdin.js +1 -0
- package/src/cli/actions/run.js +5 -6
- package/src/cli/actions/set.js +5 -9
- package/src/cli/actions/settings/device.js +2 -2
- package/src/cli/actions/settings/hostname.js +2 -2
- package/src/cli/actions/settings/off.js +1 -1
- package/src/cli/actions/settings/on.js +1 -1
- package/src/cli/actions/settings/path.js +2 -2
- package/src/cli/actions/settings/token.js +2 -2
- package/src/cli/actions/settings/username.js +2 -2
- package/src/cli/commandAction.js +16 -0
- package/src/cli/commands/armor.js +10 -9
- package/src/cli/commands/custody.js +6 -4
- package/src/cli/commands/ext.js +4 -3
- package/src/cli/commands/lock.js +3 -2
- package/src/cli/commands/native.js +5 -4
- package/src/cli/commands/primitives.js +46 -0
- package/src/cli/commands/settings.js +8 -7
- package/src/cli/dotenvx.js +45 -24
- package/src/lib/api/postFeedback.js +31 -0
- package/src/lib/envfile/discovery/discoverEnvFiles.js +29 -0
- package/src/lib/envfile/discovery/extractEnvKeys.js +173 -0
- package/src/lib/envfile/discovery/scanSource.js +79 -0
- package/src/lib/{helpers → envfile/parsing}/readEnvfile.js +3 -3
- package/src/lib/envfile/rendering/normalizeEnvfile.js +56 -0
- package/src/lib/envfile/rendering/renderEnvfile.js +26 -0
- package/src/lib/{helpers → envfile/validation}/validate.js +2 -2
- package/src/lib/{helpers → envfile/validation}/validateEnvfile.js +1 -1
- package/src/lib/events/backends/armor.js +31 -0
- package/src/lib/events/background.js +59 -0
- package/src/lib/events/catalog.js +14 -0
- package/src/lib/events/cli.js +40 -0
- package/src/lib/events/delivery.js +89 -0
- package/src/lib/events/index.js +73 -0
- package/src/lib/events/metadata.js +25 -0
- package/src/lib/events/sdk.js +44 -0
- package/src/lib/events/worker.js +29 -0
- package/src/lib/events/workerEnvironment.js +14 -0
- package/src/lib/helpers/checklist.js +9 -4
- package/src/lib/helpers/errors.js +1 -1
- package/src/lib/helpers/executeCommand.js +12 -1
- package/src/lib/helpers/hasPlaintextSecrets.js +2 -6
- package/src/lib/helpers/prompts.js +17 -0
- package/src/lib/main.d.ts +14 -0
- package/src/lib/main.js +15 -3
- package/src/lib/services/init.js +34 -12
- package/src/lib/services/validate.js +2 -2
- package/src/cli/actions/define.js +0 -17
- /package/src/lib/{grammars → envfile/parsing}/envfile.peggy +0 -0
- /package/src/lib/{helpers → envfile/parsing}/envfileParser.js +0 -0
- /package/src/lib/{helpers → envfile/parsing}/formatEnvfileSyntaxError.js +0 -0
- /package/src/lib/{helpers → envfile/validation}/encryptedSources.js +0 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const fs = require('node:fs')
|
|
2
|
+
const path = require('node:path')
|
|
3
|
+
|
|
4
|
+
const ignoredDirectories = new Set(['.git', 'node_modules', 'dist', 'build', '.next', 'vendor', '.venv', 'coverage', '__pycache__'])
|
|
5
|
+
|
|
6
|
+
// Discover selectable inputs without reading their values. Env files are often
|
|
7
|
+
// gitignored, so .gitignore must not hide them from this checklist.
|
|
8
|
+
module.exports = function discoverEnvFiles ({ directory = process.cwd() } = {}) {
|
|
9
|
+
const root = path.resolve(directory)
|
|
10
|
+
const files = []
|
|
11
|
+
function walk (current) {
|
|
12
|
+
const entries = fs.readdirSync(current, { withFileTypes: true })
|
|
13
|
+
// Stop at nested packages and initialized projects, including symlinked markers.
|
|
14
|
+
if (current !== root && entries.some(entry => entry.name === 'Envfile' || entry.name === 'package.json')) return
|
|
15
|
+
for (const entry of entries) {
|
|
16
|
+
const filename = path.join(current, entry.name)
|
|
17
|
+
if (entry.isDirectory()) {
|
|
18
|
+
if (!ignoredDirectories.has(entry.name) && !entry.name.startsWith('.env')) walk(filename)
|
|
19
|
+
continue
|
|
20
|
+
}
|
|
21
|
+
if (entry.name !== '.env' && !entry.name.startsWith('.env.')) continue
|
|
22
|
+
if (/^\.env\.(schema|x)$/.test(entry.name) || /^\.env\.(keys|vault)(\.|$)/.test(entry.name)) continue
|
|
23
|
+
if (!entry.isFile() && !(entry.isSymbolicLink() && fs.statSync(filename, { throwIfNoEntry: false })?.isFile())) continue
|
|
24
|
+
files.push(path.relative(root, filename).split(path.sep).join('/'))
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
walk(root)
|
|
28
|
+
return files.sort()
|
|
29
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// Best-effort static syntax extraction, independent of traversal and filesystem I/O.
|
|
2
|
+
// Deliberately does not evaluate expressions or follow runtime-computed key names.
|
|
3
|
+
const identifier = '[A-Za-z_][A-Za-z0-9_]*'
|
|
4
|
+
const literal = `(['"\x60])(${identifier})\\1`
|
|
5
|
+
const member = '\\s*(?:\\?\\.|\\.)\\s*'
|
|
6
|
+
const envMember = `(?:${member}env|\\s*(?:\\?\\.\\s*)?\\[\\s*(?:'env'|"env")\\s*\\])`
|
|
7
|
+
const jsEnv = `(?:process${envMember}|import${member}meta${envMember})`
|
|
8
|
+
const boundary = '(?<![\\w$.])'
|
|
9
|
+
|
|
10
|
+
function escapeRegex (value) {
|
|
11
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Match braces without counting braces inside quoted defaults or comments.
|
|
15
|
+
function openingBraces (source) {
|
|
16
|
+
const openings = new Map()
|
|
17
|
+
const stack = []
|
|
18
|
+
let quote
|
|
19
|
+
for (let i = 0; i < source.length; i++) {
|
|
20
|
+
const char = source[i]
|
|
21
|
+
if (quote) {
|
|
22
|
+
if (char === '\\') i++
|
|
23
|
+
else if (char === quote) quote = undefined
|
|
24
|
+
} else if ('\'"`'.includes(char)) quote = char
|
|
25
|
+
else if (source.startsWith('//', i)) {
|
|
26
|
+
const end = source.indexOf('\n', i + 2)
|
|
27
|
+
i = end === -1 ? source.length : end
|
|
28
|
+
} else if (source.startsWith('/*', i)) {
|
|
29
|
+
const end = source.indexOf('*/', i + 2)
|
|
30
|
+
i = end === -1 ? source.length : end + 1
|
|
31
|
+
} else if (char === '{') stack.push(i)
|
|
32
|
+
else if (char === '}') openings.set(i, stack.pop())
|
|
33
|
+
}
|
|
34
|
+
return openings
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Split destructuring properties without treating commas in defaults or nested
|
|
38
|
+
// patterns as new properties. This also lets us ignore rest and computed names.
|
|
39
|
+
function properties (body) {
|
|
40
|
+
const parts = []
|
|
41
|
+
let start = 0
|
|
42
|
+
let depth = 0
|
|
43
|
+
let quote
|
|
44
|
+
for (let i = 0; i < body.length; i++) {
|
|
45
|
+
const char = body[i]
|
|
46
|
+
if (quote) {
|
|
47
|
+
if (char === '\\') i++
|
|
48
|
+
else if (char === quote) quote = undefined
|
|
49
|
+
} else if ('\'"`'.includes(char)) quote = char
|
|
50
|
+
else if ('([{'.includes(char)) depth++
|
|
51
|
+
else if (')]}'.includes(char)) depth--
|
|
52
|
+
else if (char === ',' && depth === 0) {
|
|
53
|
+
parts.push(body.slice(start, i))
|
|
54
|
+
start = i + 1
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
parts.push(body.slice(start))
|
|
58
|
+
return parts
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
module.exports = function extractEnvKeys (content, language) {
|
|
62
|
+
// Preserve line breaks for import detection. Full parsing of every language is
|
|
63
|
+
// intentionally outside this helper; inline comments/strings can still match.
|
|
64
|
+
const source = content.split('\n').map(line => {
|
|
65
|
+
const text = line.trimStart()
|
|
66
|
+
if (['python', 'ruby', 'php'].includes(language) && text.startsWith('#')) return ''
|
|
67
|
+
if (!['python', 'ruby'].includes(language) && /^(\/\/|\/\*|\*(?:\s|\/|$))/.test(text)) return ''
|
|
68
|
+
return line
|
|
69
|
+
}).join('\n')
|
|
70
|
+
const keys = new Set()
|
|
71
|
+
function collect (pattern, group = 2, input = source) {
|
|
72
|
+
for (const match of input.matchAll(new RegExp(pattern, 'g'))) keys.add(match[group])
|
|
73
|
+
}
|
|
74
|
+
function call (base) {
|
|
75
|
+
collect(`${boundary}(?:${base})\\s*\\(\\s*${literal}\\s*(?=[,)])`)
|
|
76
|
+
}
|
|
77
|
+
function bracket (base) {
|
|
78
|
+
collect(`${boundary}(?:${base})\\s*\\[\\s*${literal}\\s*\\]`)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (language === 'js') {
|
|
82
|
+
const bases = [{ base: jsEnv, start: 0 }]
|
|
83
|
+
// Only immutable, direct bindings: no evaluation or guessed dynamic aliases.
|
|
84
|
+
const binding = /\bconst\s+([A-Za-z_$][\w$]*)\s*=\s*([^;\n]+)/g
|
|
85
|
+
for (const match of source.matchAll(binding)) {
|
|
86
|
+
const value = match[2].trim()
|
|
87
|
+
if (!bases.some(({ base }) => new RegExp(`^(?:${base})$`).test(value))) continue
|
|
88
|
+
bases.push({ base: escapeRegex(match[1]), start: match.index + match[0].length })
|
|
89
|
+
}
|
|
90
|
+
for (const { base, start } of bases) {
|
|
91
|
+
const input = source.slice(start)
|
|
92
|
+
collect(`${boundary}(?:${base})${member}(${identifier})\\b`, 1, input)
|
|
93
|
+
collect(`${boundary}(?:${base})\\s*(?:\\?\\.\\s*)?\\[\\s*${literal}\\s*\\]`, 2, input)
|
|
94
|
+
const openings = openingBraces(input)
|
|
95
|
+
for (const match of input.matchAll(new RegExp(`}\\s*=\\s*(?:${base})(?![\\w$]|\\s*(?:\\?\\.|\\.|\\[))`, 'g'))) {
|
|
96
|
+
const opening = openings.get(match.index)
|
|
97
|
+
if (opening === undefined) continue
|
|
98
|
+
for (const property of properties(input.slice(opening + 1, match.index))) {
|
|
99
|
+
const key = property.trim().match(new RegExp(`^(?:(${identifier})|['"](${identifier})['"]|\\[\\s*['"](${identifier})['"]\\s*\\])\\s*(?=[:,=]|$)`))
|
|
100
|
+
if (key) keys.add(key[1] || key[2] || key[3])
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
} else if (language === 'python') {
|
|
105
|
+
const modules = new Set(['os'])
|
|
106
|
+
const getters = new Set()
|
|
107
|
+
const environs = new Set()
|
|
108
|
+
for (const match of source.matchAll(/^\s*import\s+([^\n;]+)/gm)) {
|
|
109
|
+
for (const item of match[1].split(',')) {
|
|
110
|
+
const imported = item.trim().match(/^os(?:\s+as\s+([A-Za-z_]\w*))?\s*(?:#.*)?$/)
|
|
111
|
+
if (imported) modules.add(imported[1] || 'os')
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
for (const match of source.matchAll(/^\s*from\s+os\s+import\s+(?:\(([^)]*)\)|([^\n;]+))/gm)) {
|
|
115
|
+
for (const item of (match[1] || match[2]).split(',')) {
|
|
116
|
+
const imported = item.replace(/#[^\n]*/g, '').trim().match(/^(getenv|environ)(?:\s+as\s+([A-Za-z_]\w*))?$/)
|
|
117
|
+
if (!imported) continue
|
|
118
|
+
const aliases = imported[1] === 'getenv' ? getters : environs
|
|
119
|
+
aliases.add(imported[2] || imported[1])
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
for (const name of modules) {
|
|
123
|
+
call(`${escapeRegex(name)}\\s*\\.\\s*getenv`)
|
|
124
|
+
environs.add(`${name}.environ`)
|
|
125
|
+
}
|
|
126
|
+
for (const name of getters) call(escapeRegex(name))
|
|
127
|
+
for (const name of environs) {
|
|
128
|
+
const base = name.split('.').map(escapeRegex).join('\\s*\\.\\s*')
|
|
129
|
+
bracket(base)
|
|
130
|
+
call(`${base}\\s*\\.\\s*get`)
|
|
131
|
+
}
|
|
132
|
+
} else if (language === 'go') {
|
|
133
|
+
call('os\\s*\\.\\s*(?:Getenv|LookupEnv)')
|
|
134
|
+
for (const match of source.matchAll(/\bimport\s+(?:\(([^)]*)\)|([^\n;]+))/g)) {
|
|
135
|
+
for (const imported of (match[1] || match[2]).matchAll(/(?:^|[;\n])\s*([A-Za-z_]\w*|\.)\s+["`]os["`]\s*(?=$|[;\n]|\/\/)/g)) {
|
|
136
|
+
const alias = imported[1]
|
|
137
|
+
if (alias === '_') continue
|
|
138
|
+
call(alias === '.' ? '(?:Getenv|LookupEnv)' : `${escapeRegex(alias)}\\s*\\.\\s*(?:Getenv|LookupEnv)`)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
} else if (language === 'ruby') {
|
|
142
|
+
bracket('ENV')
|
|
143
|
+
call('ENV\\s*\\.\\s*fetch')
|
|
144
|
+
collect(`${boundary}ENV\\s*\\.\\s*fetch\\s+${literal}\\s*(?=,|$|[;\\r\\n])`)
|
|
145
|
+
} else if (language === 'php') {
|
|
146
|
+
call('getenv')
|
|
147
|
+
bracket('\\$_(?:ENV|SERVER)')
|
|
148
|
+
} else if (language === 'rust') {
|
|
149
|
+
call('(?:std\\s*::\\s*)?env\\s*::\\s*(?:var|var_os)')
|
|
150
|
+
// Expand Rust use trees, including grouped and renamed imports.
|
|
151
|
+
function imports (tree, prefix = '') {
|
|
152
|
+
for (const item of properties(tree)) {
|
|
153
|
+
const value = item.trim()
|
|
154
|
+
const group = value.indexOf('{')
|
|
155
|
+
if (group !== -1 && value.endsWith('}')) {
|
|
156
|
+
imports(value.slice(group + 1, -1), prefix + value.slice(0, group))
|
|
157
|
+
continue
|
|
158
|
+
}
|
|
159
|
+
const [original, alias] = (prefix + value).split(/\s+as\s+/)
|
|
160
|
+
const path = original.replace(/\s/g, '').replace(/::self$/, '')
|
|
161
|
+
if (alias === '_') continue
|
|
162
|
+
if (path === 'std::env') call(`${escapeRegex(alias || 'env')}\\s*::\\s*(?:var|var_os)`)
|
|
163
|
+
if (/^std::env::(?:var|var_os)$/.test(path)) call(escapeRegex(alias || path.split('::').pop()))
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
for (const match of source.matchAll(/\buse\s+([^;]+);/g)) imports(match[1])
|
|
167
|
+
} else if (language === 'java') {
|
|
168
|
+
call('(?:java\\s*\\.\\s*lang\\s*\\.\\s*)?System\\s*\\.\\s*getenv')
|
|
169
|
+
} else if (language === 'csharp') {
|
|
170
|
+
call('(?:System\\s*\\.\\s*)?Environment\\s*\\.\\s*GetEnvironmentVariable')
|
|
171
|
+
}
|
|
172
|
+
return [...keys].sort()
|
|
173
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
const fs = require('node:fs/promises')
|
|
2
|
+
const path = require('node:path')
|
|
3
|
+
const { ignore } = require('@dotenvx/tooling')
|
|
4
|
+
const extractEnvKeys = require('./extractEnvKeys')
|
|
5
|
+
|
|
6
|
+
const ignoredDirectories = new Set(['.git', 'node_modules', 'dist', 'build', '.next', 'vendor', '.venv', 'coverage', '__pycache__'])
|
|
7
|
+
const projectMarkers = new Set(['package.json', 'Envfile', '.env.schema'])
|
|
8
|
+
const languages = {
|
|
9
|
+
js: 'js',
|
|
10
|
+
mjs: 'js',
|
|
11
|
+
cjs: 'js',
|
|
12
|
+
jsx: 'js',
|
|
13
|
+
ts: 'js',
|
|
14
|
+
mts: 'js',
|
|
15
|
+
cts: 'js',
|
|
16
|
+
tsx: 'js',
|
|
17
|
+
vue: 'js',
|
|
18
|
+
svelte: 'js',
|
|
19
|
+
astro: 'js',
|
|
20
|
+
py: 'python',
|
|
21
|
+
go: 'go',
|
|
22
|
+
rb: 'ruby',
|
|
23
|
+
php: 'php',
|
|
24
|
+
rs: 'rust',
|
|
25
|
+
java: 'java',
|
|
26
|
+
cs: 'csharp'
|
|
27
|
+
}
|
|
28
|
+
module.exports = async function scanSource ({ directory = process.cwd(), onFile = () => {} } = {}) {
|
|
29
|
+
const root = path.resolve(directory)
|
|
30
|
+
const keys = new Set()
|
|
31
|
+
let scannedFiles = 0
|
|
32
|
+
const files = []
|
|
33
|
+
|
|
34
|
+
async function walk (directory, parents) {
|
|
35
|
+
const entries = (await fs.readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))
|
|
36
|
+
if (directory !== root && entries.some(entry => entry.isFile() && projectMarkers.has(entry.name))) return
|
|
37
|
+
const rules = [...parents]
|
|
38
|
+
if (entries.some(entry => entry.name === '.gitignore' && entry.isFile())) {
|
|
39
|
+
rules.push({ directory, matcher: ignore().add(await fs.readFile(path.join(directory, '.gitignore'), 'utf8')) })
|
|
40
|
+
}
|
|
41
|
+
for (const entry of entries) {
|
|
42
|
+
if (entry.name.startsWith('.env') || entry.isSymbolicLink()) continue
|
|
43
|
+
if (entry.isDirectory() && ignoredDirectories.has(entry.name)) continue
|
|
44
|
+
const filename = path.join(directory, entry.name)
|
|
45
|
+
let ignored = false
|
|
46
|
+
for (const rule of rules) {
|
|
47
|
+
const relative = path.relative(rule.directory, filename).split(path.sep).join('/') + (entry.isDirectory() ? '/' : '')
|
|
48
|
+
const result = rule.matcher.test(relative)
|
|
49
|
+
if (result.ignored) ignored = true
|
|
50
|
+
else if (result.unignored) ignored = false
|
|
51
|
+
}
|
|
52
|
+
if (ignored) continue
|
|
53
|
+
if (entry.isDirectory()) {
|
|
54
|
+
await walk(filename, rules)
|
|
55
|
+
} else if (entry.isFile()) {
|
|
56
|
+
const language = languages[path.extname(entry.name).slice(1).toLowerCase()]
|
|
57
|
+
if (language) files.push({ filename, language })
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
await walk(root, [])
|
|
63
|
+
let nextFile = 0
|
|
64
|
+
async function worker () {
|
|
65
|
+
while (nextFile < files.length) {
|
|
66
|
+
const { filename, language } = files[nextFile++]
|
|
67
|
+
if ((await fs.stat(filename)).size > 1024 * 1024) continue
|
|
68
|
+
const content = await fs.readFile(filename, 'utf8')
|
|
69
|
+
if (content.includes('\0')) continue
|
|
70
|
+
onFile(path.relative(root, filename))
|
|
71
|
+
scannedFiles++
|
|
72
|
+
for (const key of extractEnvKeys(content, language)) {
|
|
73
|
+
if (!/^DOTENV_(?:PUBLIC|PRIVATE)_KEY(?:_|$)/.test(key)) keys.add(key)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
await Promise.all(Array.from({ length: Math.min(50, files.length) }, worker))
|
|
78
|
+
return { keys: [...keys].sort(), scannedFiles }
|
|
79
|
+
}
|
|
@@ -2,9 +2,9 @@ const fs = require('node:fs')
|
|
|
2
2
|
const path = require('node:path')
|
|
3
3
|
const { isIP } = require('node:net')
|
|
4
4
|
const parser = require('./envfileParser')
|
|
5
|
-
const Errors = require('
|
|
6
|
-
const isValidUrl = require('
|
|
7
|
-
const isValidEmail = require('
|
|
5
|
+
const Errors = require('../../helpers/errors')
|
|
6
|
+
const isValidUrl = require('../../helpers/isValidUrl')
|
|
7
|
+
const isValidEmail = require('../../helpers/isValidEmail')
|
|
8
8
|
const formatEnvfileSyntaxError = require('./formatEnvfileSyntaxError')
|
|
9
9
|
|
|
10
10
|
function compileDeclarations (declarations) {
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Pure final pass over independently inferred file rules. Never mutates inputs.
|
|
2
|
+
module.exports = function normalizeEnvfile ({ files, codeDeclarations = [] }) {
|
|
3
|
+
const hasNamedEnvironment = files.some(file => !['.env', '.env.example'].includes(file.filename))
|
|
4
|
+
const rootFiles = []
|
|
5
|
+
const environments = []
|
|
6
|
+
for (const file of files) {
|
|
7
|
+
if (file.filename === '.env.example' || (file.filename === '.env' && !hasNamedEnvironment)) rootFiles.push(file)
|
|
8
|
+
else environments.push(file)
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const encrypted = rootFiles.some(file => file.hasValues) && rootFiles.every(file => !file.hasValues || file.encrypted)
|
|
12
|
+
const root = new Map()
|
|
13
|
+
for (const file of rootFiles) {
|
|
14
|
+
for (const item of file.declarations) {
|
|
15
|
+
const previous = root.get(item.name)
|
|
16
|
+
root.set(item.name, { ...item, encrypted: Boolean(previous?.encrypted || item.encrypted) })
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (environments.length > 1) {
|
|
21
|
+
for (const item of environments[0].declarations) {
|
|
22
|
+
const matches = environments.map(file => file.declarations.find(other => other.name === item.name))
|
|
23
|
+
if (!root.has(item.name) && matches.every(other => other && other.type === item.type && other.optional === item.optional)) {
|
|
24
|
+
// Keep encryption differences in their file scopes, not the shared declaration.
|
|
25
|
+
root.set(item.name, { ...item, encrypted })
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const blocks = environments.map(file => {
|
|
31
|
+
const overridesEncryption = file.encrypted !== encrypted
|
|
32
|
+
const declarations = file.declarations.flatMap(item => {
|
|
33
|
+
const inherited = root.get(item.name)
|
|
34
|
+
const defaults = inherited
|
|
35
|
+
? { ...inherited, encrypted: overridesEncryption ? file.encrypted : inherited.encrypted }
|
|
36
|
+
: { encrypted: file.encrypted }
|
|
37
|
+
const overrides = Object.fromEntries(Object.entries(item).filter(([key, value]) => key !== 'name' && value !== defaults[key]))
|
|
38
|
+
return inherited && !Object.keys(overrides).length ? [] : [{ name: item.name, ...overrides }]
|
|
39
|
+
})
|
|
40
|
+
return { filename: file.filename, ...(overridesEncryption ? { encrypted: file.encrypted } : {}), declarations }
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
const names = new Set(files.flatMap(file => file.declarations.map(item => item.name)))
|
|
44
|
+
const code = []
|
|
45
|
+
for (const item of codeDeclarations) {
|
|
46
|
+
if (names.has(item.name)) continue
|
|
47
|
+
names.add(item.name)
|
|
48
|
+
code.push({ ...item, optional: true })
|
|
49
|
+
}
|
|
50
|
+
const declarations = [...root.values()].map(item => {
|
|
51
|
+
const result = { ...item }
|
|
52
|
+
if (result.encrypted === encrypted) delete result.encrypted
|
|
53
|
+
return result
|
|
54
|
+
})
|
|
55
|
+
return { encrypted, declarations, files: blocks, codeDeclarations: code }
|
|
56
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
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.optional !== undefined) line += `, optional: ${item.optional}`
|
|
6
|
+
return line
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
module.exports = function renderEnvfile (document) {
|
|
10
|
+
const sections = [`encrypted ${document.encrypted}`]
|
|
11
|
+
if (document.declarations.length) sections.push(document.declarations.map(declaration).join('\n'))
|
|
12
|
+
for (const file of document.files) {
|
|
13
|
+
const quote = file.filename.includes('"') ? "'" : '"'
|
|
14
|
+
if (file.filename.includes(quote) || /[\r\n\0*?[\]{}]/.test(file.filename)) {
|
|
15
|
+
throw new Error(`Unsupported Envfile filename: ${file.filename}`)
|
|
16
|
+
}
|
|
17
|
+
const lines = [`file ${quote}${file.filename}${quote} do`]
|
|
18
|
+
if (file.encrypted !== undefined) lines.push(` encrypted ${file.encrypted}`)
|
|
19
|
+
lines.push(...file.declarations.map(item => ` ${declaration(item)}`), 'end')
|
|
20
|
+
sections.push(lines.join('\n'))
|
|
21
|
+
}
|
|
22
|
+
if (document.codeDeclarations.length) {
|
|
23
|
+
sections.push('# additionally found in code\n' + document.codeDeclarations.map(declaration).join('\n'))
|
|
24
|
+
}
|
|
25
|
+
return sections.join('\n\n') + '\n'
|
|
26
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const isValidUrl = require('
|
|
2
|
-
const isValidEmail = require('
|
|
1
|
+
const isValidUrl = require('../../helpers/isValidUrl')
|
|
2
|
+
const isValidEmail = require('../../helpers/isValidEmail')
|
|
3
3
|
const { isIP } = require('node:net')
|
|
4
4
|
|
|
5
5
|
function validate (example = {}, env = {}, options = {}) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const validate = require('./validate')
|
|
2
2
|
const encryptedSources = require('./encryptedSources')
|
|
3
|
-
const Errors = require('
|
|
3
|
+
const Errors = require('../../helpers/errors')
|
|
4
4
|
|
|
5
5
|
module.exports = function validateEnvfile (schema, env, processedEnvs) {
|
|
6
6
|
const messages = new Set()
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const Session = require('../../../db/session')
|
|
2
|
+
const { http } = require('../../helpers/http')
|
|
3
|
+
|
|
4
|
+
// Radar ingests client-reported activity at POST /api/events.
|
|
5
|
+
// Authentication is captured before `run` loads application environment values.
|
|
6
|
+
module.exports = function armor (options = {}) {
|
|
7
|
+
if (process.env.DOTENVX_NO_ARMOR === 'true' || options.armor === false || options.noArmor === true) return
|
|
8
|
+
const session = new Session()
|
|
9
|
+
if (!options.token && (!session.on() || !session.username())) return
|
|
10
|
+
const token = options.token || session.token()
|
|
11
|
+
if (!token) return
|
|
12
|
+
const hostname = session.hostname()
|
|
13
|
+
|
|
14
|
+
return {
|
|
15
|
+
id: 'armor',
|
|
16
|
+
async send (events, { signal }) {
|
|
17
|
+
const response = await http(`${hostname}/api/events`, {
|
|
18
|
+
method: 'POST',
|
|
19
|
+
signal,
|
|
20
|
+
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
21
|
+
body: JSON.stringify({ events })
|
|
22
|
+
})
|
|
23
|
+
// No response data belongs in console output (including errors).
|
|
24
|
+
// Undici can emit an asynchronous AbortError when its body is destroyed,
|
|
25
|
+
// even after the request promise resolves. Handle it before cleanup.
|
|
26
|
+
response.body.on('error', () => {})
|
|
27
|
+
response.body.destroy()
|
|
28
|
+
if (response.statusCode >= 400) throw new Error('Event delivery failed')
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const { spawn } = require('child_process')
|
|
2
|
+
const Session = require('../../db/session')
|
|
3
|
+
const workerEnvironment = require('./workerEnvironment')
|
|
4
|
+
|
|
5
|
+
// CLI delivery owns no network handles. Credentials are read by the worker.
|
|
6
|
+
module.exports = function createBackground (options = {}) {
|
|
7
|
+
if (process.env.DOTENVX_NO_ARMOR === 'true' || options.armor === false || options.noArmor === true) return
|
|
8
|
+
const session = new Session()
|
|
9
|
+
if (!options.token && (!session.on() || !session.username())) return
|
|
10
|
+
// Capture before run loads application environment values.
|
|
11
|
+
const env = workerEnvironment()
|
|
12
|
+
// pkg otherwise treats the first child argument as a JavaScript entrypoint.
|
|
13
|
+
// Relaunch the embedded CLI so _deliver-events remains a command.
|
|
14
|
+
if (process.pkg) env.PKG_EXECPATH = ''
|
|
15
|
+
const cwd = process.cwd()
|
|
16
|
+
const args = process.pkg ? [] : [process.argv[1]]
|
|
17
|
+
const token = options.token
|
|
18
|
+
let queue = []
|
|
19
|
+
let closing
|
|
20
|
+
|
|
21
|
+
function flush () {
|
|
22
|
+
if (!queue.length) return Promise.resolve()
|
|
23
|
+
const events = queue
|
|
24
|
+
queue = []
|
|
25
|
+
return new Promise(resolve => {
|
|
26
|
+
let child
|
|
27
|
+
let timer
|
|
28
|
+
const done = () => { clearTimeout(timer); resolve() }
|
|
29
|
+
try {
|
|
30
|
+
child = spawn(process.execPath, [...args, '_deliver-events'], {
|
|
31
|
+
cwd, env, detached: true, windowsHide: true, stdio: ['pipe', 'ignore', 'ignore']
|
|
32
|
+
})
|
|
33
|
+
child.on('error', done)
|
|
34
|
+
child.stdin.on('error', done)
|
|
35
|
+
child.unref()
|
|
36
|
+
child.stdin.unref()
|
|
37
|
+
// Only wait for the local pipe write, never worker startup or HTTP.
|
|
38
|
+
timer = setTimeout(() => { child.stdin.destroy(); done() }, 25)
|
|
39
|
+
child.stdin.end(JSON.stringify({ options: { token }, events }), done)
|
|
40
|
+
} catch { done() }
|
|
41
|
+
})
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
write (event, terminal = false) {
|
|
46
|
+
if (closing) return
|
|
47
|
+
if (queue.length >= 256) {
|
|
48
|
+
if (terminal) queue.pop()
|
|
49
|
+
else return
|
|
50
|
+
}
|
|
51
|
+
queue.push(event)
|
|
52
|
+
},
|
|
53
|
+
flush,
|
|
54
|
+
close () {
|
|
55
|
+
if (!closing) closing = flush()
|
|
56
|
+
return closing
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Register public operations here. Internal helpers keep the caller's recorder.
|
|
2
|
+
module.exports = {
|
|
3
|
+
'cli/run': {},
|
|
4
|
+
'cli/get': { keyArgument: true },
|
|
5
|
+
'cli/set': { keyArgument: true },
|
|
6
|
+
'cli/del': { keyArgument: true },
|
|
7
|
+
'cli/encrypt': {},
|
|
8
|
+
'cli/decrypt': {},
|
|
9
|
+
'cli/keypair': { keyArgument: true },
|
|
10
|
+
'cli/protect': {},
|
|
11
|
+
'sdk/config': {},
|
|
12
|
+
'sdk/get': { keyArgument: true },
|
|
13
|
+
'sdk/set': { keyArgument: true }
|
|
14
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
const commandAction = require('../../cli/commandAction')
|
|
2
|
+
const createEvents = require('./index')
|
|
3
|
+
const catalog = require('./catalog')
|
|
4
|
+
|
|
5
|
+
module.exports = function trackCli (command, action) {
|
|
6
|
+
return commandAction(async function (...args) {
|
|
7
|
+
const options = typeof this.optsWithGlobals === 'function' ? this.optsWithGlobals() : this.opts()
|
|
8
|
+
const context = this
|
|
9
|
+
const name = `cli/${command}`
|
|
10
|
+
const eventOptions = {}
|
|
11
|
+
for (const [key, value] of Object.entries(options)) {
|
|
12
|
+
const source = typeof this.getOptionValueSourceWithGlobals === 'function'
|
|
13
|
+
? this.getOptionValueSourceWithGlobals(key)
|
|
14
|
+
: this.getOptionValueSource?.(key)
|
|
15
|
+
if (source === 'cli' || source === 'env') eventOptions[key] = value
|
|
16
|
+
}
|
|
17
|
+
const events = createEvents(name, options, { eventOptions, background: true })
|
|
18
|
+
if (catalog[name]?.keyArgument) events.add({ key: args[0] })
|
|
19
|
+
let code
|
|
20
|
+
let result
|
|
21
|
+
try {
|
|
22
|
+
result = await action.apply(context, args)
|
|
23
|
+
if (Number.isInteger(result?.exitCode)) code = result.exitCode
|
|
24
|
+
if (result?.error) {
|
|
25
|
+
events.fail(result.error)
|
|
26
|
+
code = code ?? 1
|
|
27
|
+
}
|
|
28
|
+
if (Number.isInteger(result?.errorCount)) events.add({ error_count: result.errorCount })
|
|
29
|
+
if (result?.signal) events.add({ signal: result.signal })
|
|
30
|
+
return result
|
|
31
|
+
} catch (error) {
|
|
32
|
+
code = 1
|
|
33
|
+
events.fail(error)
|
|
34
|
+
throw error
|
|
35
|
+
} finally {
|
|
36
|
+
const exitCode = code ?? process.exitCode ?? 0
|
|
37
|
+
await events.complete(exitCode === 0 && !(result?.errorCount > 0) ? 'success' : 'unsuccessful', { exit_code: exitCode })
|
|
38
|
+
}
|
|
39
|
+
})
|
|
40
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
const BATCH_SIZE = 50
|
|
2
|
+
const QUEUE_LIMIT = 256
|
|
3
|
+
|
|
4
|
+
// Transport only. Backend failures cannot escape this boundary.
|
|
5
|
+
module.exports = function createDelivery (backend, timeoutMs = 500) {
|
|
6
|
+
const timeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.min(timeoutMs, 500) : 500
|
|
7
|
+
const queue = []
|
|
8
|
+
let running
|
|
9
|
+
let controller
|
|
10
|
+
let closing
|
|
11
|
+
let sendBatch
|
|
12
|
+
try {
|
|
13
|
+
if (backend && typeof backend.send === 'function') sendBatch = backend.send.bind(backend)
|
|
14
|
+
} catch {} // Treat an invalid backend as disabled, including throwing getters.
|
|
15
|
+
let closed = !sendBatch
|
|
16
|
+
|
|
17
|
+
function stop () {
|
|
18
|
+
closed = true
|
|
19
|
+
queue.length = 0
|
|
20
|
+
if (controller) controller.abort()
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function send (batch) {
|
|
24
|
+
let timer
|
|
25
|
+
controller = new AbortController()
|
|
26
|
+
try {
|
|
27
|
+
await Promise.race([
|
|
28
|
+
Promise.resolve().then(() => sendBatch(batch, { signal: controller.signal })),
|
|
29
|
+
new Promise(resolve => { timer = setTimeout(() => { stop(); resolve() }, timeout) })
|
|
30
|
+
])
|
|
31
|
+
} catch {
|
|
32
|
+
stop()
|
|
33
|
+
} finally {
|
|
34
|
+
clearTimeout(timer)
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function pump () {
|
|
39
|
+
if (closed || running || !queue.length) return
|
|
40
|
+
running = (async () => {
|
|
41
|
+
while (queue.length) {
|
|
42
|
+
if (closed) break
|
|
43
|
+
await send(queue.splice(0, BATCH_SIZE))
|
|
44
|
+
}
|
|
45
|
+
})().finally(() => {
|
|
46
|
+
running = undefined
|
|
47
|
+
pump()
|
|
48
|
+
})
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function flush () {
|
|
52
|
+
let timer
|
|
53
|
+
try {
|
|
54
|
+
// Overall flush deadline is separate from each batch's deadline.
|
|
55
|
+
await Promise.race([
|
|
56
|
+
(async () => {
|
|
57
|
+
pump()
|
|
58
|
+
let current = running
|
|
59
|
+
while (current) {
|
|
60
|
+
await current
|
|
61
|
+
current = running
|
|
62
|
+
}
|
|
63
|
+
})(),
|
|
64
|
+
new Promise(resolve => { timer = setTimeout(() => { stop(); resolve() }, timeout) })
|
|
65
|
+
])
|
|
66
|
+
} catch {
|
|
67
|
+
stop()
|
|
68
|
+
} finally {
|
|
69
|
+
clearTimeout(timer)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
write (event, terminal = false) {
|
|
75
|
+
if (closed || closing) return
|
|
76
|
+
if (queue.length >= QUEUE_LIMIT) {
|
|
77
|
+
if (!terminal) return
|
|
78
|
+
queue.pop() // Reserve room for the final result.
|
|
79
|
+
}
|
|
80
|
+
queue.push(event)
|
|
81
|
+
pump()
|
|
82
|
+
},
|
|
83
|
+
flush,
|
|
84
|
+
close () {
|
|
85
|
+
if (!closing) closing = flush().finally(stop)
|
|
86
|
+
return closing
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|