@dotenvx/dotenvx 2.30.0 → 2.31.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 +24 -2
- package/README.md +81 -749
- package/package.json +3 -3
- package/src/cli/actions/{validate.js → check.js} +3 -3
- package/src/cli/actions/feedback.js +42 -0
- package/src/cli/actions/init.js +56 -2
- package/src/cli/commands/armor.js +1 -1
- package/src/cli/commands/primitives.js +46 -0
- package/src/cli/dotenvx.js +33 -16
- package/src/lib/api/postFeedback.js +31 -0
- package/src/lib/custodians/resolveLocalKey.js +68 -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/helpers/checklist.js +1 -1
- package/src/lib/helpers/errors.js +1 -1
- package/src/lib/helpers/prompts.js +17 -0
- package/src/lib/main.js +5 -1
- package/src/lib/services/armorPush.js +3 -15
- package/src/lib/services/armorUp.js +5 -12
- 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
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "2.
|
|
2
|
+
"version": "2.31.1",
|
|
3
3
|
"name": "@dotenvx/dotenvx",
|
|
4
4
|
"description": "a secure dotenv–from the creator of `dotenv`",
|
|
5
5
|
"author": "@motdotla",
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"release:check": "npm test && npm run testshell",
|
|
51
51
|
"prerelease": "npm run release:check",
|
|
52
52
|
"release": "npm run release:check && standard-version",
|
|
53
|
-
"build:envfile": "peggy --format commonjs -o src/lib/
|
|
53
|
+
"build:envfile": "peggy --format commonjs -o src/lib/envfile/parsing/envfileParser.js src/lib/envfile/parsing/envfile.peggy"
|
|
54
54
|
},
|
|
55
55
|
"funding": "https://dotenvx.com",
|
|
56
56
|
"dependencies": {
|
|
@@ -82,7 +82,7 @@
|
|
|
82
82
|
},
|
|
83
83
|
"standard": {
|
|
84
84
|
"ignore": [
|
|
85
|
-
"src/lib/
|
|
85
|
+
"src/lib/envfile/parsing/envfileParser.js"
|
|
86
86
|
]
|
|
87
87
|
}
|
|
88
88
|
}
|
|
@@ -7,10 +7,10 @@ const normalizeDotenvConfigQuiet = require('../../lib/helpers/normalizeDotenvCon
|
|
|
7
7
|
const normalizeDotenvConfigConvention = require('../../lib/helpers/normalizeDotenvConfigConvention')
|
|
8
8
|
const normalizeDotenvConfigIgnore = require('../../lib/helpers/normalizeDotenvConfigIgnore')
|
|
9
9
|
|
|
10
|
-
async function
|
|
10
|
+
async function check () {
|
|
11
11
|
const options = normalizeDotenvConfigIgnore(normalizeDotenvConfigConvention(normalizeDotenvConfigQuiet(this.opts())))
|
|
12
12
|
const spinnerOptions = typeof this.optsWithGlobals === 'function' ? this.optsWithGlobals() : options
|
|
13
|
-
const spinner = await createSpinner({ ...spinnerOptions, ...options, text: '
|
|
13
|
+
const spinner = await createSpinner({ ...spinnerOptions, ...options, text: 'checking' })
|
|
14
14
|
const ignore = options.ignore || []
|
|
15
15
|
let errorCount = 0
|
|
16
16
|
|
|
@@ -72,4 +72,4 @@ async function validate () {
|
|
|
72
72
|
}
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
-
module.exports =
|
|
75
|
+
module.exports = check
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
const { logger } = require('../../shared/logger')
|
|
2
|
+
const Session = require('../../db/session')
|
|
3
|
+
const PostFeedback = require('../../lib/api/postFeedback')
|
|
4
|
+
const prompts = require('../../lib/helpers/prompts')
|
|
5
|
+
const createSpinner = require('../../lib/helpers/createSpinner')
|
|
6
|
+
|
|
7
|
+
async function feedback (body) {
|
|
8
|
+
let spinner
|
|
9
|
+
try {
|
|
10
|
+
if (body === undefined) {
|
|
11
|
+
if (!process.stdin.isTTY) {
|
|
12
|
+
throw new Error('provide a message: dotenvx feedback "Your feedback"')
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
body = await prompts.input({
|
|
16
|
+
message: 'Send feedback'
|
|
17
|
+
}, { input: process.stdin, output: process.stderr })
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (!body.trim()) {
|
|
21
|
+
throw new Error('feedback cannot be empty')
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const options = this.opts()
|
|
25
|
+
const spinnerOptions = typeof this.optsWithGlobals === 'function' ? this.optsWithGlobals() : options
|
|
26
|
+
const hostname = options.hostname || new Session().hostname()
|
|
27
|
+
spinner = await createSpinner({ ...spinnerOptions, ...options, text: 'sending' })
|
|
28
|
+
await new PostFeedback(hostname, body).run()
|
|
29
|
+
if (spinner) spinner.stop()
|
|
30
|
+
logger.success('✔ Feedback sent, thanks!')
|
|
31
|
+
} catch (error) {
|
|
32
|
+
if (spinner) spinner.stop()
|
|
33
|
+
if (error.code === 'PROMPT_CANCELLED') {
|
|
34
|
+
return { exitCode: 130, error }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
logger.error(error.message || error)
|
|
38
|
+
return { exitCode: 1, error }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
module.exports = feedback
|
package/src/cli/actions/init.js
CHANGED
|
@@ -1,3 +1,57 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
const fs = require('node:fs')
|
|
2
|
+
const process = require('node:process')
|
|
3
|
+
const prompts = require('../../lib/helpers/prompts')
|
|
4
|
+
const initEnvfile = require('../../lib/services/init')
|
|
5
|
+
const scanSource = require('../../lib/envfile/discovery/scanSource')
|
|
6
|
+
const discoverEnvFiles = require('../../lib/envfile/discovery/discoverEnvFiles')
|
|
7
|
+
const createSpinner = require('../../lib/helpers/createSpinner')
|
|
8
|
+
const { logger } = require('../../shared/logger')
|
|
9
|
+
const catchAndLog = require('../../lib/helpers/catchAndLog')
|
|
10
|
+
|
|
11
|
+
module.exports = async function init () {
|
|
12
|
+
const envFile = this.opts().envFile
|
|
13
|
+
const interactive = !process.env.CI && process.stdin.isTTY && process.stderr.isTTY
|
|
14
|
+
let spinner
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
if (fs.lstatSync('Envfile', { throwIfNoEntry: false })) {
|
|
18
|
+
logger.info('○ Envfile already exists (unchanged)')
|
|
19
|
+
return
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let envFiles
|
|
23
|
+
let sourceKeys = []
|
|
24
|
+
let scanCode = false
|
|
25
|
+
const onFile = filename => {
|
|
26
|
+
if (spinner) spinner.text = `scanning ${filename}`
|
|
27
|
+
}
|
|
28
|
+
if (interactive && !envFile) {
|
|
29
|
+
const candidates = discoverEnvFiles()
|
|
30
|
+
const selected = await prompts.multiselect({
|
|
31
|
+
message: 'Create Envfile from .env files and code',
|
|
32
|
+
submitLabel: 'Create Envfile',
|
|
33
|
+
choices: [...candidates, { name: 'code ./**/* (env references)', value: '__scan_source' }],
|
|
34
|
+
initial: [...candidates, '__scan_source']
|
|
35
|
+
})
|
|
36
|
+
envFiles = selected.filter(value => value !== '__scan_source')
|
|
37
|
+
scanCode = selected.includes('__scan_source')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const options = this.opts()
|
|
41
|
+
const spinnerOptions = typeof this.optsWithGlobals === 'function' ? this.optsWithGlobals() : options
|
|
42
|
+
spinner = await createSpinner({ ...spinnerOptions, ...options, text: 'scanning' })
|
|
43
|
+
if (scanCode) {
|
|
44
|
+
const { keys } = await scanSource({ onFile })
|
|
45
|
+
sourceKeys = keys
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const { created } = initEnvfile({ envFile, envFiles, sourceKeys, onFile })
|
|
49
|
+
if (spinner) spinner.stop()
|
|
50
|
+
if (created) logger.success('◈ created (Envfile)')
|
|
51
|
+
else logger.info('○ Envfile already exists (unchanged)')
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if (spinner) spinner.stop()
|
|
54
|
+
catchAndLog(error)
|
|
55
|
+
return { exitCode: 1, error }
|
|
56
|
+
}
|
|
3
57
|
}
|
|
@@ -43,7 +43,7 @@ function configureArmorCommand (armor) {
|
|
|
43
43
|
// dotenvx armor push
|
|
44
44
|
armor
|
|
45
45
|
.command('push')
|
|
46
|
-
.description('push armored key
|
|
46
|
+
.description('push armored key')
|
|
47
47
|
.option('-f, --env-file <path>', 'path to your env file')
|
|
48
48
|
.option('--token <token>', 'set token')
|
|
49
49
|
.option('--team <team>', 'team to push armored private key for')
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
const { derive, keypair } = require('@dotenvx/primitives')
|
|
2
|
+
const commandAction = require('../commandAction')
|
|
3
|
+
const catchAndLog = require('../../lib/helpers/catchAndLog')
|
|
4
|
+
|
|
5
|
+
function output (operation, required = false) {
|
|
6
|
+
return commandAction(async function (privateKey) {
|
|
7
|
+
try {
|
|
8
|
+
if (this.opts().stdin) {
|
|
9
|
+
if (privateKey !== undefined) throw new Error('Cannot combine a private key argument with --stdin')
|
|
10
|
+
process.stdin.setEncoding('utf8')
|
|
11
|
+
let input = ''
|
|
12
|
+
for await (const chunk of process.stdin) input += chunk
|
|
13
|
+
privateKey = input.trim()
|
|
14
|
+
if (!privateKey) throw new Error('Expected a private key on stdin')
|
|
15
|
+
}
|
|
16
|
+
if (required && privateKey === undefined) throw new Error('Provide a private key argument or use --stdin')
|
|
17
|
+
if (privateKey !== undefined && (privateKey.length !== 64 || !/^[a-f0-9]{64}$/i.test(privateKey))) throw new Error('Expected one 64-character hex private key')
|
|
18
|
+
const result = operation(privateKey)
|
|
19
|
+
console.log(typeof result === 'string' ? result : JSON.stringify(result))
|
|
20
|
+
return { exitCode: 0 }
|
|
21
|
+
} catch (error) {
|
|
22
|
+
catchAndLog(error)
|
|
23
|
+
return { exitCode: 1 }
|
|
24
|
+
}
|
|
25
|
+
})
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
module.exports = function primitives (command) {
|
|
29
|
+
command
|
|
30
|
+
.description('standalone primitives without env file reads or writes')
|
|
31
|
+
.action(function () { this.help() })
|
|
32
|
+
|
|
33
|
+
command.command('keypair')
|
|
34
|
+
.description('generate or restore a key pair and print JSON')
|
|
35
|
+
.argument('[privateKey]', 'hex-encoded private key to restore')
|
|
36
|
+
.option('--stdin', 'read the private key from stdin')
|
|
37
|
+
.allowExcessArguments(false)
|
|
38
|
+
.action(output(keypair))
|
|
39
|
+
|
|
40
|
+
command.command('derive')
|
|
41
|
+
.description('derive and print a public key from a private key')
|
|
42
|
+
.argument('[privateKey]', 'hex-encoded private key')
|
|
43
|
+
.option('--stdin', 'read the private key from stdin')
|
|
44
|
+
.allowExcessArguments(false)
|
|
45
|
+
.action(output(derive, true))
|
|
46
|
+
}
|
package/src/cli/dotenvx.js
CHANGED
|
@@ -226,23 +226,15 @@ program.command('ls', { hidden: true })
|
|
|
226
226
|
|
|
227
227
|
// dotenvx init
|
|
228
228
|
program.command('init', { hidden: true })
|
|
229
|
-
.description('
|
|
229
|
+
.description('select .env files to create an Envfile')
|
|
230
230
|
.option('-f, --env-file <path>', 'file to read variable names from')
|
|
231
231
|
.action(function () {
|
|
232
232
|
return commandAction(require('./actions/init')).apply(this, arguments)
|
|
233
233
|
})
|
|
234
234
|
|
|
235
|
-
// dotenvx
|
|
236
|
-
program.command('
|
|
237
|
-
.description('
|
|
238
|
-
.option('-f, --env-file <path>', 'file to read variable names from')
|
|
239
|
-
.action(function () {
|
|
240
|
-
return commandAction(require('./actions/define')).apply(this, arguments)
|
|
241
|
-
})
|
|
242
|
-
|
|
243
|
-
// dotenvx validate
|
|
244
|
-
program.command('validate', { hidden: true })
|
|
245
|
-
.description('validate .env file(s) against Envfile')
|
|
235
|
+
// dotenvx check
|
|
236
|
+
program.command('check', { hidden: true })
|
|
237
|
+
.description('check .env file(s) against Envfile')
|
|
246
238
|
.option('--strict', 'process.exit(1) on any errors, including missing env files', false)
|
|
247
239
|
.option('-e, --env <strings...>', 'environment variable(s) set as string (example: "HELLO=World")', collectEnvs('env'), [])
|
|
248
240
|
.option('-f, --env-file <path>', 'path(s) to your env file(s)', collectEnvs('envFile'), [])
|
|
@@ -257,7 +249,7 @@ program.command('validate', { hidden: true })
|
|
|
257
249
|
.option('--no-bitwarden', 'disable Bitwarden secret reference resolution')
|
|
258
250
|
.action(function (...args) {
|
|
259
251
|
this.envs = envs
|
|
260
|
-
return commandAction(require('./actions/
|
|
252
|
+
return commandAction(require('./actions/check')).apply(this, args)
|
|
261
253
|
})
|
|
262
254
|
|
|
263
255
|
// dotenvx gitignore
|
|
@@ -317,15 +309,37 @@ program.command('doctor', { hidden: true })
|
|
|
317
309
|
return commandAction(require('./actions/doctor')).apply(this, args)
|
|
318
310
|
})
|
|
319
311
|
|
|
320
|
-
// dotenvx
|
|
312
|
+
// dotenvx feedback
|
|
313
|
+
program.command('feedback', { hidden: true })
|
|
314
|
+
.description('send feedback to dotenvx')
|
|
315
|
+
.argument('[message]', 'feedback message')
|
|
316
|
+
.allowExcessArguments(false)
|
|
317
|
+
.option('--hostname <hostname>', 'set API hostname')
|
|
318
|
+
.action(function (...args) {
|
|
319
|
+
return commandAction(require('./actions/feedback')).apply(this, args)
|
|
320
|
+
})
|
|
321
|
+
|
|
322
|
+
// Build menu entries from the command definitions so new subcommands stay discoverable.
|
|
323
|
+
function hiddenSubcommands (name) {
|
|
324
|
+
const parent = program.commands.find(command => command.name() === name)
|
|
325
|
+
const formatter = parent.createHelp()
|
|
326
|
+
const entries = parent.commands.map(command => ({
|
|
327
|
+
term: `${name} ${formatter.subcommandTerm(command)}`,
|
|
328
|
+
description: command.description()
|
|
329
|
+
}))
|
|
330
|
+
const width = Math.max(...entries.map(entry => entry.term.length))
|
|
331
|
+
return entries.map(entry => ` ${entry.term.padEnd(width)} ${entry.description}`).join('\n')
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// dotenvx hidden (a menu of commands and subcommands)
|
|
321
335
|
program.command('hidden')
|
|
322
336
|
.allowExcessArguments(false)
|
|
323
337
|
.description('hidden features')
|
|
324
|
-
.addHelpText('after',
|
|
338
|
+
.addHelpText('after', () => `\nHidden Commands:\n update update dotenvx\n feedback [message] send feedback to dotenvx\n protect protect secrets and private keys from code commits\n ls [directory] print all .env files in a tree structure\n genexample [directory] generate .env.example\n lock ⊡ lock private keys with a local passphrase\n native ⌥ move private keys in/out of your OS secret store\n 1password □ move private keys in/out of 1Password\n bitwarden □ move private keys in/out of Bitwarden\n armor ⛨ move private keys in/out of Dotenvx Armor [www.dotenvx.com/armor]\n curl ⛨ call authenticated api Dotenvx Armor [www.dotenvx.com/armor]\n\nBeta Commands:\n init create an Envfile from .env files and source code\n check check .env file(s) against Envfile\n${hiddenSubcommands('primitives')}\n\nDeprecated Commands:\n gitignore deprecated. use [dotenvx protect]\n precommit [directory] deprecated. use [dotenvx protect]\n prebuild [directory] deprecated. use [dotenvx protect --docker]\n\nRun directly: dotenvx <command>`)
|
|
325
339
|
.action(function () { this.outputHelp() })
|
|
326
340
|
|
|
327
341
|
// dotenvx update
|
|
328
|
-
program.command('update')
|
|
342
|
+
program.command('update', { hidden: true })
|
|
329
343
|
.description('update dotenvx')
|
|
330
344
|
.action(function (...args) {
|
|
331
345
|
return commandAction(require('./actions/update')).apply(this, args)
|
|
@@ -394,6 +408,9 @@ require('./commands/lock')(program.command('lock', { hidden: true }))
|
|
|
394
408
|
// dotenvx armor
|
|
395
409
|
require('./commands/armor')(program.command('armor', { hidden: true }))
|
|
396
410
|
|
|
411
|
+
// dotenvx primitives
|
|
412
|
+
require('./commands/primitives')(program.command('primitives', { hidden: true }))
|
|
413
|
+
|
|
397
414
|
// dotenvx ext
|
|
398
415
|
program.addCommand(require('./commands/ext'))
|
|
399
416
|
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const { http } = require('../helpers/http')
|
|
2
|
+
const buildApiError = require('../helpers/buildApiError')
|
|
3
|
+
|
|
4
|
+
class PostFeedback {
|
|
5
|
+
constructor (hostname, body) {
|
|
6
|
+
this.hostname = hostname
|
|
7
|
+
this.body = body
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
async run () {
|
|
11
|
+
const url = `${this.hostname}/api/feedback`
|
|
12
|
+
|
|
13
|
+
const resp = await http(url, {
|
|
14
|
+
method: 'POST',
|
|
15
|
+
headers: {
|
|
16
|
+
'Content-Type': 'application/json'
|
|
17
|
+
},
|
|
18
|
+
body: JSON.stringify({ body: this.body })
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
const json = await resp.body.json()
|
|
22
|
+
|
|
23
|
+
if (resp.statusCode >= 400) {
|
|
24
|
+
throw buildApiError(resp.statusCode, json)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return json
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
module.exports = PostFeedback
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
const fs = require('node:fs')
|
|
2
|
+
const path = require('node:path')
|
|
3
|
+
const { scan, derive } = require('@dotenvx/primitives')
|
|
4
|
+
const custodians = require('./index')
|
|
5
|
+
const protection = require('./lock')
|
|
6
|
+
const keynames = require('../conventions/keynames')
|
|
7
|
+
const matchesStoredKey = require('../helpers/matchesStoredKey')
|
|
8
|
+
const removeEnvKey = require('../helpers/removeEnvKey')
|
|
9
|
+
const Errors = require('../helpers/errors')
|
|
10
|
+
|
|
11
|
+
function read (filename) {
|
|
12
|
+
try { return fs.readFileSync(filename, 'utf8') } catch (error) {
|
|
13
|
+
if (error.code === 'ENOENT') return undefined
|
|
14
|
+
throw error
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function value (src, name) {
|
|
19
|
+
return src === undefined ? undefined : scan(src).parsed[name]?.at(-1)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Return the originating store with the key, so a move only removes that source.
|
|
23
|
+
// Never look up Armor itself: these operations upload a locally held private key.
|
|
24
|
+
module.exports = async function resolveLocalKey (envFile = '.env', { allowMissing = false } = {}) {
|
|
25
|
+
const src = read(envFile)
|
|
26
|
+
const { publicKeyName, privateKeyName } = keynames(envFile, src || '')
|
|
27
|
+
let publicKey = value(src, publicKeyName)
|
|
28
|
+
if (allowMissing && !publicKey) {
|
|
29
|
+
if (src === undefined) throw new Errors({ envFilepath: envFile }).missingEnvFile()
|
|
30
|
+
throw new Errors({ key: publicKeyName }).missingKey()
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function result (stored, remove, reread) {
|
|
34
|
+
// A file-only push remains supported, including password-locked keys.
|
|
35
|
+
if (!publicKey) publicKey = stored.startsWith('locked:') ? stored.split(':')[1] : derive(stored)
|
|
36
|
+
if (!matchesStoredKey(publicKey, stored)) throw new Error('private key does not match the .env public key')
|
|
37
|
+
const privateKey = (await protection.unlock(publicKey, { [publicKey]: stored }))[publicKey]
|
|
38
|
+
return {
|
|
39
|
+
publicKey,
|
|
40
|
+
privateKey,
|
|
41
|
+
privateKeyName,
|
|
42
|
+
async remove () {
|
|
43
|
+
if (await reread() !== stored) throw new Error('private key changed during upload; original storage was not modified')
|
|
44
|
+
await remove()
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const files = [...new Set([path.resolve(path.dirname(envFile), '.env.keys'), path.resolve('.env.keys')])]
|
|
50
|
+
for (const filename of files) {
|
|
51
|
+
const stored = value(read(filename), privateKeyName)
|
|
52
|
+
if (stored) return result(stored, () => removeEnvKey(privateKeyName, filename), () => value(read(filename), privateKeyName))
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (publicKey) {
|
|
56
|
+
for (const id of ['native', 'onepassword', 'bitwarden']) {
|
|
57
|
+
const custodian = custodians.get(id)
|
|
58
|
+
if (!custodian.enabled() || (custodian.configured && !custodian.configured())) continue
|
|
59
|
+
const stored = (await custodian.get(publicKey))?.[publicKey]
|
|
60
|
+
if (stored) return result(stored, () => custodian.delete(publicKey), async () => (await custodian.get(publicKey))?.[publicKey])
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Up can be repeated for a key already held by Armor; the server verifies it.
|
|
65
|
+
if (allowMissing) return { publicKey, privateKeyName, remove: async () => {} }
|
|
66
|
+
if (!publicKey && src === undefined) throw new Errors({ envFilepath: '.env.keys' }).missingEnvFile()
|
|
67
|
+
throw new Error(`private key ${privateKeyName} not found in .env.keys, OS secret storage, 1Password, or Bitwarden`)
|
|
68
|
+
}
|
|
@@ -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
|
+
}
|