@dotenvx/dotenvx 2.32.4 → 2.34.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 (90) hide show
  1. package/CHANGELOG.md +22 -1
  2. package/README.md +24 -26
  3. package/package.json +5 -13
  4. package/src/cli/actions/check.js +6 -11
  5. package/src/cli/actions/encrypt.js +2 -2
  6. package/src/cli/actions/get.js +4 -5
  7. package/src/cli/actions/init.js +4 -4
  8. package/src/cli/actions/keypair.js +1 -0
  9. package/src/cli/actions/policy.js +14 -0
  10. package/src/cli/actions/primitivesCheck.js +32 -0
  11. package/src/cli/actions/primitivesProfile.js +15 -0
  12. package/src/cli/actions/primitivesRedact.js +19 -0
  13. package/src/cli/actions/protectStdin.js +2 -2
  14. package/src/cli/actions/run.js +8 -46
  15. package/src/cli/actions/set.js +1 -1
  16. package/src/cli/commands/primitives.js +28 -1
  17. package/src/cli/dotenvx.js +6 -6
  18. package/src/db/session.js +1 -1
  19. package/src/lib/custodians/index.js +12 -10
  20. package/src/lib/custodians/local/bitwarden.js +5 -15
  21. package/src/lib/custodians/local/native/backend.js +4 -10
  22. package/src/lib/custodians/local/native/index.js +1 -1
  23. package/src/lib/custodians/local/onepassword.js +7 -29
  24. package/src/lib/custodians/managed/armor/index.js +0 -10
  25. package/src/lib/custodians/resolveLocalKey.js +3 -4
  26. package/src/lib/decryptors/armor/index.js +6 -7
  27. package/src/lib/{envspec → envfile}/discovery/discoverEnvFiles.js +1 -1
  28. package/src/lib/{envspec → envfile}/discovery/scanSource.js +1 -1
  29. package/src/lib/{envspec/parsing/formatEnvspecSyntaxError.js → envfile/parsing/formatEnvfileSyntaxError.js} +1 -1
  30. package/src/lib/envfile/parsing/readEnvfile.js +43 -0
  31. package/src/lib/envfile/parsing/resolveEnvfilePath.js +5 -0
  32. package/src/lib/{envspec/rendering/normalizeEnvspec.js → envfile/rendering/normalizeEnvfile.js} +1 -1
  33. package/src/lib/{envspec/rendering/previewEnvspec.js → envfile/rendering/previewEnvfile.js} +7 -15
  34. package/src/lib/{envspec/rendering/renderEnvspec.js → envfile/rendering/renderEnvfile.js} +3 -3
  35. package/src/lib/{envspec/validation/protectEnvspec.js → envfile/validation/protectEnvfile.js} +7 -7
  36. package/src/lib/envfile/validation/validateEnvfile.js +14 -0
  37. package/src/lib/helpers/errors.js +3 -25
  38. package/src/lib/helpers/executeCommand.js +1 -2
  39. package/src/lib/helpers/matchesStoredKey.js +1 -12
  40. package/src/lib/helpers/parseWithDecryptor.js +27 -12
  41. package/src/lib/helpers/redactOutput.js +30 -32
  42. package/src/lib/helpers/redactProcessOutput.js +58 -0
  43. package/src/lib/helpers/redactedValues.js +2 -2
  44. package/src/lib/helpers/selectEnvfileEnvs.js +29 -0
  45. package/src/lib/helpers/selectKeyStorage.js +1 -1
  46. package/src/lib/helpers/storeKeyStorage.js +0 -1
  47. package/src/lib/main.d.ts +12 -6
  48. package/src/lib/main.js +16 -29
  49. package/src/lib/providers/index.js +53 -53
  50. package/src/lib/resolvers/envs.js +7 -26
  51. package/src/lib/resolvers/get.js +2 -3
  52. package/src/lib/resolvers/keypair.js +39 -4
  53. package/src/lib/services/init.js +4 -4
  54. package/src/lib/services/validate.js +20 -32
  55. package/src/lib/transforms/encrypt.js +5 -5
  56. package/src/lib/transforms/set.js +5 -3
  57. package/src/cli/actions/lock/down.js +0 -54
  58. package/src/cli/actions/lock/up.js +0 -62
  59. package/src/cli/commands/lock.js +0 -36
  60. package/src/lib/api/postArmorDecrypt.js +0 -49
  61. package/src/lib/api/postArmorKeyring.js +0 -50
  62. package/src/lib/custodians/lock.js +0 -80
  63. package/src/lib/custodians/managed/armor/get.js +0 -44
  64. package/src/lib/envspec/parsing/envspec.peggy +0 -105
  65. package/src/lib/envspec/parsing/envspecParser.js +0 -2851
  66. package/src/lib/envspec/parsing/readEnvspec.js +0 -144
  67. package/src/lib/envspec/parsing/resolveEnvspecPath.js +0 -11
  68. package/src/lib/envspec/validation/encryptedSources.js +0 -15
  69. package/src/lib/envspec/validation/validate.js +0 -109
  70. package/src/lib/envspec/validation/validateEnvspec.js +0 -57
  71. package/src/lib/helpers/isValidEmail.js +0 -11
  72. package/src/lib/helpers/isValidUrl.js +0 -9
  73. package/src/lib/helpers/lockedValue.js +0 -24
  74. package/src/lib/helpers/resolveLockPassword.js +0 -5
  75. package/src/lib/helpers/unlockedValue.js +0 -26
  76. package/src/lib/helpers/withLockedKeys.js +0 -41
  77. package/src/lib/providers/provider-worker.js +0 -6
  78. package/src/lib/proxy/configureProxy.js +0 -55
  79. package/src/lib/proxy/eligibleHeaders.js +0 -16
  80. package/src/lib/proxy/prepareProxy.js +0 -24
  81. package/src/lib/proxy/proxyCertificates.js +0 -44
  82. package/src/lib/proxy/proxyForward.js +0 -65
  83. package/src/lib/proxy/proxyPreload.js +0 -21
  84. package/src/lib/proxy/proxyPreloadSource.js +0 -3
  85. package/src/lib/proxy/proxyServer.js +0 -175
  86. package/src/lib/services/armorKeyring.js +0 -119
  87. package/src/lib/services/lockDown.js +0 -157
  88. package/src/lib/services/lockUp.js +0 -150
  89. /package/src/lib/{envspec → envfile}/discovery/extractEnvKeys.js +0 -0
  90. /package/src/lib/{envspec → envfile}/validation/diagnosticLocation.js +0 -0
@@ -1,65 +0,0 @@
1
- const eligibleHeaders = require('./eligibleHeaders')
2
-
3
- // Parent-only forwarding. Never load credential configuration into the application.
4
- function install (config, nativeFetch = globalThis.fetch) {
5
- if (typeof nativeFetch !== 'function') throw new Error('Credential proxy requires Node.js with built-in fetch.')
6
- return async function proxyFetch (input, init) {
7
- const url = new URL(input instanceof Request ? input.url : input)
8
- if (!config.credentials.some(item => item.host === url.hostname)) return nativeFetch(input, init)
9
- if (url.protocol !== 'https:' || (url.port && url.port !== '443') || url.username || url.password) {
10
- throw new Error('Credential proxy requests must use HTTPS on port 443.')
11
- }
12
- const request = new Request(input, init)
13
- const upstreamHeaders = Object.fromEntries([...request.headers].filter(([name]) => eligibleHeaders(name)))
14
- const values = Object.entries(upstreamHeaders).map(([name, value]) => {
15
- // Preserve existing Basic support: its placeholder is encoded on the wire.
16
- if (name === 'authorization' && value.startsWith('Basic ')) {
17
- const encoded = value.slice(6)
18
- const decoded = Buffer.from(encoded, 'base64')
19
- if (decoded.toString('base64') !== encoded) throw new Error('Invalid Basic authorization.')
20
- return decoded.toString('utf8')
21
- }
22
- return value
23
- })
24
- const active = config.credentials.filter(credential => {
25
- const occurrences = values.reduce((total, value) => total + value.split(credential.placeholder).length - 1, 0)
26
- if (occurrences && credential.host !== url.hostname) throw new Error('Proxy credential is not allowed at this destination.')
27
- if (occurrences > 1) throw new Error('Proxy credential must occur in only one eligible header, once.')
28
- return occurrences === 1
29
- })
30
- if (!active.length) throw new Error('Credential proxy requires a proxied environment variable in an eligible header.')
31
- if (active.length > 8 || active.some(item => item.publicKey !== active[0].publicKey)) {
32
- throw new Error('Proxy request requires at most eight credentials from the same keypair.')
33
- }
34
- const body = ['GET', 'HEAD'].includes(request.method) ? null : Buffer.from(await request.arrayBuffer())
35
- if (body && body.length > 256 * 1024) throw new Error('Proxy request body exceeds 256 KiB.')
36
- const credentials = active.map(({ publicKey, placeholder, ciphertext }) => ({ publicKey, placeholder, ciphertext }))
37
- const metadata = JSON.stringify({ headers: upstreamHeaders, credentials })
38
- if (Buffer.byteLength(metadata) > 64 * 1024) throw new Error('Proxy request metadata exceeds 64 KiB.')
39
- const payload = JSON.stringify({
40
- version: 1,
41
- request: {
42
- url: url.href,
43
- method: request.method,
44
- headers: upstreamHeaders,
45
- body: body === null ? null : { encoding: 'base64', data: body.toString('base64') }
46
- },
47
- credentials
48
- })
49
- if (Buffer.byteLength(payload) > 512 * 1024) throw new Error('Proxy request envelope exceeds 512 KiB.')
50
- const headers = new Headers({
51
- Authorization: `Bearer ${config.token}`,
52
- 'Content-Type': 'application/json'
53
- })
54
- if (config.devicePublicKey) headers.set('dotenvx-device-public-key', config.devicePublicKey)
55
- return nativeFetch(`${config.hostname}/api/proxy`, {
56
- method: 'POST',
57
- headers,
58
- body: payload,
59
- signal: request.signal,
60
- redirect: 'error'
61
- })
62
- }
63
- }
64
-
65
- module.exports = install
@@ -1,21 +0,0 @@
1
- // Other runtimes use standard proxy/CA variables. Node also needs a bridge for
2
- // older runtimes and core HTTP clients that do not read proxy variables.
3
- if (process.env.DOTENVX_PROXY_URL) {
4
- const http = require('node:http')
5
- if (typeof http.setGlobalProxyFromEnv === 'function') {
6
- http.setGlobalProxyFromEnv()
7
- } else {
8
- const { ProxyAgent, Agent, Dispatcher, setGlobalDispatcher } = require('undici')
9
- const proxy = new ProxyAgent(process.env.DOTENVX_PROXY_URL)
10
- const direct = new Agent()
11
- class ProxyDispatcher extends Dispatcher {
12
- dispatch (options, handler) {
13
- const host = new URL(options.origin).hostname
14
- return (['localhost', '127.0.0.1', '[::1]'].includes(host) ? direct : proxy).dispatch(options, handler)
15
- }
16
- }
17
- setGlobalDispatcher(new ProxyDispatcher())
18
- }
19
- const { createGlobalProxyAgent } = require('global-agent')
20
- createGlobalProxyAgent({ environmentVariableNamespace: '', forceGlobalAgent: true })
21
- }
@@ -1,3 +0,0 @@
1
- // Source installs can resolve dependencies beside the original preload. The
2
- // executable build replaces this module with the bundled, standalone script.
3
- module.exports = `require(${JSON.stringify(require.resolve('./proxyPreload'))})\n`
@@ -1,175 +0,0 @@
1
- const http = require('node:http')
2
- const https = require('node:https')
3
- const net = require('node:net')
4
- const tls = require('node:tls')
5
- const fs = require('node:fs')
6
- const os = require('node:os')
7
- const path = require('node:path')
8
- const certificates = require('./proxyCertificates')
9
- const forward = require('./proxyForward')
10
- const eligibleHeaders = require('./eligibleHeaders')
11
-
12
- const REQUEST_LIMIT = 256 * 1024
13
- const RESPONSE_LIMIT = 2 * 1024 * 1024
14
- const RESPONSE_HEADERS = ['content-type', 'request-id', 'retry-after', 'stripe-version']
15
-
16
- module.exports = async function startProxy (config, nativeFetch) {
17
- const fetch = forward(config, nativeFetch)
18
- const hosts = new Set(config.credentials.map(item => item.host))
19
- const identity = await certificates(hosts.size ? [...hosts] : ['localhost'])
20
- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'dxp-'))
21
- fs.chmodSync(directory, 0o700)
22
- const caPath = path.join(directory, 'ca.pem')
23
- const sockets = new Set()
24
- const track = socket => {
25
- sockets.add(socket)
26
- socket.on('close', () => sockets.delete(socket))
27
- socket.on('error', () => {})
28
- socket.setTimeout(30000, () => socket.destroy())
29
- return socket
30
- }
31
- const reject = socket => socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n')
32
- const servers = new Map()
33
- for (const host of hosts) {
34
- const secure = https.createServer({ key: identity.key, cert: identity.cert, ALPNProtocols: ['http/1.1'] }, async (req, res) => {
35
- const controller = new AbortController()
36
- res.on('close', () => { if (!res.writableEnded) controller.abort() })
37
- try {
38
- const url = new URL(req.url, `https://${host}`)
39
- if (![host, `${host}:443`].includes(req.headers.host?.toLowerCase()) ||
40
- url.origin !== `https://${host}` || url.username || url.password || url.hash ||
41
- !req.url.startsWith('/') || req.url.startsWith('//') ||
42
- !['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {
43
- res.writeHead(403).end('Proxy request is not allowed.')
44
- return
45
- }
46
- const chunks = []
47
- let size = 0
48
- for await (const chunk of req) {
49
- size += chunk.length
50
- if (size > REQUEST_LIMIT) {
51
- res.writeHead(413).end('Proxy request exceeds 256 KiB.')
52
- return
53
- }
54
- chunks.push(chunk)
55
- }
56
- const headers = new Headers()
57
- for (const [name, value] of Object.entries(req.headers)) {
58
- if (eligibleHeaders(name)) headers.set(name, Array.isArray(value) ? value.join(', ') : value)
59
- }
60
- const response = await fetch(url.href, {
61
- method: req.method,
62
- headers,
63
- body: ['GET', 'HEAD'].includes(req.method) ? undefined : Buffer.concat(chunks),
64
- signal: controller.signal
65
- })
66
- const output = []
67
- let bytes = 0
68
- if (response.body) {
69
- for await (const chunk of response.body) {
70
- bytes += chunk.length
71
- if (bytes > RESPONSE_LIMIT) throw new Error('response too large')
72
- output.push(Buffer.from(chunk))
73
- }
74
- }
75
- for (const name of RESPONSE_HEADERS) {
76
- if (response.headers.has(name)) res.setHeader(name, response.headers.get(name))
77
- }
78
- res.writeHead(response.status).end(Buffer.concat(output))
79
- } catch {
80
- if (!res.headersSent) res.writeHead(502)
81
- res.end('Proxy request failed.')
82
- }
83
- })
84
- secure.on('secureConnection', track)
85
- secure.on('tlsClientError', (_error, socket) => socket.destroy())
86
- secure.on('upgrade', (_req, socket) => reject(socket))
87
- secure.requestTimeout = 30000
88
- secure.headersTimeout = 10000
89
- servers.set(host, secure)
90
- }
91
-
92
- const server = http.createServer((req, res) => {
93
- // Ordinary HTTP is forwarded without injecting any proxy credential.
94
- let url
95
- try { url = new URL(req.url) } catch { res.writeHead(400).end(); return }
96
- if (url.protocol !== 'http:' || url.username || url.password || hosts.has(url.hostname) || self(url)) {
97
- res.writeHead(403).end('Proxy request is not allowed.')
98
- return
99
- }
100
- const headers = { ...req.headers, host: url.host }
101
- for (const name of ['proxy-authorization', 'proxy-connection', 'connection']) delete headers[name]
102
- const upstream = http.request(url, { method: req.method, headers, agent: false }, response => {
103
- const responseHeaders = { ...response.headers }
104
- delete responseHeaders['proxy-authenticate']
105
- res.writeHead(response.statusCode, responseHeaders)
106
- response.pipe(res)
107
- response.on('error', () => res.destroy())
108
- })
109
- upstream.on('socket', track)
110
- upstream.on('error', () => { if (!res.headersSent) res.writeHead(502); res.end('Proxy request failed.') })
111
- res.on('close', () => upstream.destroy())
112
- req.pipe(upstream)
113
- })
114
- function self (url) {
115
- return ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname) && Number(url.port) === server.address()?.port
116
- }
117
- server.on('connection', track)
118
- server.on('upgrade', (_req, socket) => reject(socket))
119
- server.on('connect', (req, socket, head) => {
120
- let target
121
- try {
122
- if (!/^(\[[\da-f:]+\]|[a-z\d.-]+):\d+$/i.test(req.url)) throw new Error('invalid authority')
123
- target = new URL(`https://${req.url}`)
124
- if (self(target)) throw new Error('proxy loop')
125
- } catch { reject(socket); return }
126
- if (hosts.has(target.hostname)) {
127
- if (target.port && target.port !== '443') { reject(socket); return }
128
- socket.write('HTTP/1.1 200 Connection Established\r\n\r\n')
129
- if (head.length) socket.unshift(head)
130
- servers.get(target.hostname).emit('connection', socket)
131
- return
132
- }
133
- // Unmanaged HTTPS remains end-to-end encrypted through a standard CONNECT tunnel.
134
- const upstream = track(net.connect(Number(target.port) || 443, target.hostname.replace(/^\[|\]$/g, '')))
135
- upstream.on('connect', () => {
136
- socket.write('HTTP/1.1 200 Connection Established\r\n\r\n')
137
- if (head.length) upstream.write(head)
138
- socket.pipe(upstream).pipe(socket)
139
- })
140
- upstream.on('error', () => socket.destroy())
141
- socket.on('close', () => upstream.destroy())
142
- upstream.on('close', () => socket.destroy())
143
- })
144
- server.requestTimeout = 30000
145
- server.headersTimeout = 10000
146
- let closed
147
- const close = () => {
148
- if (!closed) {
149
- closed = (async () => {
150
- for (const socket of sockets) socket.destroy()
151
- await new Promise(resolve => server.close(resolve))
152
- fs.rmSync(directory, { recursive: true, force: true })
153
- })()
154
- }
155
- return closed
156
- }
157
- try {
158
- const roots = typeof tls.getCACertificates === 'function' ? tls.getCACertificates('default') : tls.rootCertificates
159
- const trust = new Set(roots)
160
- const env = config.env || {}
161
- for (const name of ['NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'GIT_SSL_CAINFO', 'CARGO_HTTP_CAINFO', 'DENO_CERT']) {
162
- if (env[name]) trust.add(fs.readFileSync(env[name], 'utf8'))
163
- }
164
- trust.add(identity.ca)
165
- fs.writeFileSync(caPath, [...trust].join('\n'), { mode: 0o600 })
166
- await new Promise((resolve, reject) => {
167
- server.once('error', reject)
168
- server.listen(0, '127.0.0.1', () => { server.removeListener('error', reject); resolve() })
169
- })
170
- } catch (error) {
171
- await close()
172
- throw error
173
- }
174
- return { proxyUrl: `http://127.0.0.1:${server.address().port}`, caPath, close }
175
- }
@@ -1,119 +0,0 @@
1
- const PostArmorKeyring = require('../api/postArmorKeyring')
2
-
3
- const ACCESS_APPROVAL_REQUIRED = 'ACCESS_APPROVAL_REQUIRED'
4
- const ACCESS_APPROVAL_PENDING = 'ACCESS_APPROVAL_PENDING'
5
- const ACCESS_PENDING = 'ACCESS_PENDING'
6
- const POLL_INTERVAL = 1000
7
- const POLL_TIMEOUT = 5 * 60 * 1000
8
-
9
- function grantTokenFromError (error) {
10
- return error.meta && error.meta.grant_token
11
- }
12
-
13
- function isAccessApprovalRequired (error) {
14
- return error.code === ACCESS_APPROVAL_REQUIRED
15
- }
16
-
17
- function isAccessPending (error) {
18
- return error.code === ACCESS_PENDING || error.code === ACCESS_APPROVAL_PENDING
19
- }
20
-
21
- function approvalUriFromError (error) {
22
- if (error.meta) {
23
- return error.meta.approval_uri
24
- }
25
-
26
- return error.json && error.json.error && error.json.error.approval_uri
27
- }
28
-
29
- async function sleep (ms) {
30
- await new Promise(resolve => setTimeout(resolve, ms))
31
- }
32
-
33
- function approvalTimeoutError () {
34
- const code = 'ACCESS_APPROVAL_TIMEOUT'
35
- const error = new Error(`[${code}] approval timed out after 5 minutes`)
36
- error.code = code
37
- return error
38
- }
39
-
40
- class ArmorKeyring {
41
- constructor (hostname, token, devicePublicKey, publicKey) {
42
- this.hostname = hostname
43
- this.token = token
44
- this.devicePublicKey = devicePublicKey
45
- this.publicKey = publicKey
46
- this.onApprovalRequired = null
47
- }
48
-
49
- async request (grantToken) {
50
- if (grantToken !== undefined) {
51
- return await new PostArmorKeyring(
52
- this.hostname,
53
- this.token,
54
- this.devicePublicKey,
55
- this.publicKey,
56
- grantToken
57
- ).run()
58
- }
59
-
60
- return await new PostArmorKeyring(
61
- this.hostname,
62
- this.token,
63
- this.devicePublicKey,
64
- this.publicKey
65
- ).run()
66
- }
67
-
68
- async requestWithApprovalPolling () {
69
- try {
70
- return await this.request()
71
- } catch (error) {
72
- if (!isAccessApprovalRequired(error)) {
73
- throw error
74
- }
75
-
76
- const grantToken = grantTokenFromError(error)
77
- if (!grantToken) {
78
- throw error
79
- }
80
-
81
- const approvalUri = approvalUriFromError(error)
82
- if (!approvalUri) {
83
- throw error
84
- }
85
-
86
- if (this.onApprovalRequired) {
87
- this.onApprovalRequired({ approvalUri, code: error.code })
88
- }
89
-
90
- return await this.poll(grantToken)
91
- }
92
- }
93
-
94
- async poll (grantToken) {
95
- const startedAt = Date.now()
96
-
97
- while (true) {
98
- try {
99
- return await this.request(grantToken)
100
- } catch (error) {
101
- if (!isAccessPending(error)) {
102
- throw error
103
- }
104
-
105
- if (Date.now() - startedAt >= POLL_TIMEOUT) {
106
- throw approvalTimeoutError()
107
- }
108
-
109
- await sleep(POLL_INTERVAL)
110
- }
111
- }
112
- }
113
-
114
- async run () {
115
- return await this.requestWithApprovalPolling()
116
- }
117
- }
118
-
119
- module.exports = ArmorKeyring
@@ -1,157 +0,0 @@
1
- const fs = require('fs')
2
- const { derive, publickeys, scan } = require('@dotenvx/primitives')
3
-
4
- const Errors = require('../helpers/errors')
5
- const upsertEnvKey = require('../helpers/upsertEnvKey')
6
-
7
- function latestValues (parsed) {
8
- const result = {}
9
-
10
- for (const [key, values] of Object.entries(parsed)) {
11
- result[key] = values[values.length - 1]
12
- }
13
-
14
- return result
15
- }
16
-
17
- function lockedCandidates (keysSrc) {
18
- const { parsed } = scan(keysSrc)
19
- const values = latestValues(parsed)
20
- const candidates = []
21
-
22
- for (const [privateKeyName, privateKey] of Object.entries(values)) {
23
- if (!privateKeyName.startsWith('DOTENV_PRIVATE_KEY')) continue
24
- if (!privateKey.startsWith('locked:')) continue
25
-
26
- const parts = privateKey.split(':')
27
- if (parts.length < 3) continue
28
-
29
- candidates.push({
30
- privateKeyName,
31
- lockedPrivateKeyValue: privateKey,
32
- publicKeyValue: parts[1]
33
- })
34
- }
35
-
36
- return candidates
37
- }
38
-
39
- function privateKeyring (keysSrc) {
40
- const { parsed } = scan(keysSrc)
41
- const values = latestValues(parsed)
42
- const keyring = {}
43
-
44
- for (const [privateKeyName, privateKey] of Object.entries(values)) {
45
- if (!privateKeyName.startsWith('DOTENV_PRIVATE_KEY')) continue
46
- if (privateKey.startsWith('locked:')) continue
47
-
48
- try {
49
- const publicKey = derive(privateKey)
50
- keyring[publicKey] = { privateKeyName, privateKeyValue: privateKey }
51
- } catch {}
52
- }
53
-
54
- return keyring
55
- }
56
-
57
- class LockDown {
58
- constructor (envFile = '.env', envKeysFile = '.env.keys') {
59
- this.envFile = envFile
60
- this.envKeysFile = envKeysFile
61
- }
62
-
63
- lockedCandidates () {
64
- const keysSrc = fs.readFileSync(this.envKeysFile, 'utf8')
65
- const candidates = lockedCandidates(keysSrc)
66
-
67
- if (candidates.length < 1) {
68
- throw new Errors({ key: 'DOTENV_PRIVATE_KEY' }).missingKey()
69
- }
70
-
71
- return candidates
72
- }
73
-
74
- plan () {
75
- const envSrc = fs.readFileSync(this.envFile, 'utf8')
76
- const keysSrc = fs.readFileSync(this.envKeysFile, 'utf8')
77
- const publicKeyValues = publickeys(envSrc)
78
- const lockedByPublicKey = {}
79
- const plaintextByPublicKey = privateKeyring(keysSrc)
80
- const locked = []
81
- const alreadyUnlocked = []
82
-
83
- for (const lockedPrivateKey of lockedCandidates(keysSrc)) {
84
- lockedByPublicKey[lockedPrivateKey.publicKeyValue] = lockedPrivateKey
85
- }
86
-
87
- for (const publicKey of publicKeyValues) {
88
- const lockedPrivateKey = lockedByPublicKey[publicKey]
89
- if (lockedPrivateKey) {
90
- locked.push(lockedPrivateKey)
91
- continue
92
- }
93
-
94
- const privateKey = plaintextByPublicKey[publicKey]
95
- if (privateKey) {
96
- alreadyUnlocked.push({
97
- changed: false,
98
- privateKeyName: privateKey.privateKeyName,
99
- privateKeyValue: privateKey.privateKeyValue,
100
- lockedPrivateKeyValue: undefined,
101
- publicKeyValue: publicKey
102
- })
103
- }
104
- }
105
-
106
- if (locked.length < 1 && alreadyUnlocked.length < 1) {
107
- throw new Errors({ key: 'DOTENV_PRIVATE_KEY' }).missingKey()
108
- }
109
-
110
- return { locked, alreadyUnlocked }
111
- }
112
-
113
- run (unlockPrivateKey) {
114
- const { locked, alreadyUnlocked } = this.plan()
115
- const results = [...alreadyUnlocked]
116
-
117
- if (locked.length > 0 && !unlockPrivateKey) {
118
- throw new Error('missing unlock private key function')
119
- }
120
-
121
- for (const lockedPrivateKey of locked) {
122
- let privateKeyValue
123
-
124
- try {
125
- privateKeyValue = unlockPrivateKey(lockedPrivateKey.lockedPrivateKeyValue)
126
- } catch (error) {
127
- throw new Errors({ privateKeyName: lockedPrivateKey.privateKeyName }).invalidPassphrase()
128
- }
129
-
130
- const publicKeyValue = derive(privateKeyValue)
131
-
132
- if (publicKeyValue !== lockedPrivateKey.publicKeyValue) continue
133
-
134
- const result = upsertEnvKey(lockedPrivateKey.privateKeyName, privateKeyValue, this.envKeysFile)
135
-
136
- results.push({
137
- changed: result.changed,
138
- privateKeyName: lockedPrivateKey.privateKeyName,
139
- privateKeyValue,
140
- lockedPrivateKeyValue: lockedPrivateKey.lockedPrivateKeyValue,
141
- publicKeyValue
142
- })
143
- }
144
-
145
- if (results.length < 1) {
146
- throw new Errors({ key: 'DOTENV_PRIVATE_KEY' }).missingKey()
147
- }
148
-
149
- return {
150
- changed: results.some(result => result.changed),
151
- results
152
- }
153
- }
154
- }
155
-
156
- module.exports = LockDown
157
- module.exports.lockedCandidates = lockedCandidates
@@ -1,150 +0,0 @@
1
- const fs = require('fs')
2
- const { derive, publickeys, scan } = require('@dotenvx/primitives')
3
-
4
- const Errors = require('../helpers/errors')
5
- const upsertEnvKey = require('../helpers/upsertEnvKey')
6
-
7
- function latestValues (parsed) {
8
- const result = {}
9
-
10
- for (const [key, values] of Object.entries(parsed)) {
11
- result[key] = values[values.length - 1]
12
- }
13
-
14
- return result
15
- }
16
-
17
- function privateKeyring (keysSrc) {
18
- const { parsed } = scan(keysSrc)
19
- const values = latestValues(parsed)
20
- const keyring = {}
21
-
22
- for (const [privateKeyName, privateKey] of Object.entries(values)) {
23
- if (!privateKeyName.startsWith('DOTENV_PRIVATE_KEY')) continue
24
-
25
- try {
26
- const publicKey = derive(privateKey)
27
- keyring[publicKey] = { privateKeyName, privateKeyValue: privateKey }
28
- } catch {}
29
- }
30
-
31
- return keyring
32
- }
33
-
34
- function lockedKeyring (keysSrc) {
35
- const { parsed } = scan(keysSrc)
36
- const values = latestValues(parsed)
37
- const keyring = {}
38
-
39
- for (const [privateKeyName, privateKey] of Object.entries(values)) {
40
- if (!privateKeyName.startsWith('DOTENV_PRIVATE_KEY')) continue
41
- if (!privateKey.startsWith('locked:')) continue
42
-
43
- const parts = privateKey.split(':')
44
- if (parts.length < 3) continue
45
-
46
- const publicKey = parts[1]
47
- keyring[publicKey] = {
48
- privateKeyName,
49
- lockedPrivateKeyValue: privateKey,
50
- publicKeyValue: publicKey
51
- }
52
- }
53
-
54
- return keyring
55
- }
56
-
57
- class LockUp {
58
- constructor (envFile = '.env', envKeysFile = '.env.keys') {
59
- this.envFile = envFile
60
- this.envKeysFile = envKeysFile
61
- }
62
-
63
- plan () {
64
- const envFile = this.envFile
65
- const envKeysFile = this.envKeysFile
66
-
67
- const envSrc = fs.readFileSync(envFile, 'utf8')
68
- const keysSrc = fs.readFileSync(envKeysFile, 'utf8')
69
- const ring = privateKeyring(keysSrc)
70
- const lockedRing = lockedKeyring(keysSrc)
71
- const matches = []
72
- const alreadyLocked = []
73
-
74
- for (const publicKey of publickeys(envSrc)) {
75
- const privateKey = ring[publicKey]
76
- if (privateKey) {
77
- matches.push({
78
- privateKeyName: privateKey.privateKeyName,
79
- privateKeyValue: privateKey.privateKeyValue,
80
- publicKeyValue: publicKey
81
- })
82
- continue
83
- }
84
-
85
- const lockedPrivateKey = lockedRing[publicKey]
86
- if (lockedPrivateKey) {
87
- alreadyLocked.push(lockedPrivateKey)
88
- }
89
- }
90
-
91
- if (matches.length < 1 && alreadyLocked.length < 1) {
92
- throw new Errors({ key: 'DOTENV_PRIVATE_KEY' }).missingKey()
93
- }
94
-
95
- return { matches, alreadyLocked }
96
- }
97
-
98
- matches () {
99
- const { matches } = this.plan()
100
-
101
- if (matches.length < 1) {
102
- throw new Errors({ key: 'DOTENV_PRIVATE_KEY' }).missingKey()
103
- }
104
-
105
- return matches
106
- }
107
-
108
- run (lockPrivateKey) {
109
- if (!lockPrivateKey) {
110
- throw new Error('missing lock private key function')
111
- }
112
-
113
- const envKeysFile = this.envKeysFile
114
- const results = []
115
-
116
- const { matches, alreadyLocked } = this.plan()
117
-
118
- for (const privateKey of matches) {
119
- const lockedPrivateKey = lockPrivateKey(privateKey.privateKeyValue, privateKey.publicKeyValue)
120
- const result = upsertEnvKey(privateKey.privateKeyName, lockedPrivateKey, envKeysFile)
121
-
122
- results.push({
123
- changed: result.changed,
124
- privateKeyName: privateKey.privateKeyName,
125
- privateKeyValue: privateKey.privateKeyValue,
126
- lockedPrivateKeyValue: lockedPrivateKey,
127
- publicKeyValue: privateKey.publicKeyValue
128
- })
129
- }
130
-
131
- for (const lockedPrivateKey of alreadyLocked) {
132
- results.push({
133
- changed: false,
134
- privateKeyName: lockedPrivateKey.privateKeyName,
135
- privateKeyValue: undefined,
136
- lockedPrivateKeyValue: lockedPrivateKey.lockedPrivateKeyValue,
137
- publicKeyValue: lockedPrivateKey.publicKeyValue,
138
- alreadyLocked: true
139
- })
140
- }
141
-
142
- return {
143
- changed: results.some(result => result.changed),
144
- results
145
- }
146
- }
147
- }
148
-
149
- module.exports = LockUp
150
- module.exports.privateKeyring = privateKeyring