@dotenvx/dotenvx 2.33.0 → 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 (43) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/README.md +0 -1
  3. package/package.json +4 -4
  4. package/src/cli/actions/get.js +1 -2
  5. package/src/cli/actions/keypair.js +1 -0
  6. package/src/cli/actions/run.js +2 -12
  7. package/src/cli/dotenvx.js +1 -6
  8. package/src/db/session.js +1 -1
  9. package/src/lib/custodians/index.js +12 -10
  10. package/src/lib/custodians/local/bitwarden.js +5 -15
  11. package/src/lib/custodians/local/native/backend.js +4 -10
  12. package/src/lib/custodians/local/native/index.js +1 -1
  13. package/src/lib/custodians/local/onepassword.js +4 -24
  14. package/src/lib/custodians/managed/armor/index.js +0 -10
  15. package/src/lib/custodians/resolveLocalKey.js +3 -4
  16. package/src/lib/decryptors/armor/index.js +6 -7
  17. package/src/lib/helpers/errors.js +0 -13
  18. package/src/lib/helpers/matchesStoredKey.js +1 -12
  19. package/src/lib/helpers/parseWithDecryptor.js +27 -4
  20. package/src/lib/helpers/selectKeyStorage.js +1 -1
  21. package/src/lib/helpers/storeKeyStorage.js +0 -1
  22. package/src/lib/main.d.ts +0 -4
  23. package/src/lib/main.js +3 -10
  24. package/src/lib/providers/index.js +53 -53
  25. package/src/lib/resolvers/envs.js +5 -14
  26. package/src/lib/resolvers/get.js +0 -1
  27. package/src/lib/resolvers/keypair.js +39 -4
  28. package/src/lib/services/validate.js +0 -1
  29. package/src/cli/actions/lock/down.js +0 -54
  30. package/src/cli/actions/lock/up.js +0 -62
  31. package/src/cli/commands/lock.js +0 -36
  32. package/src/lib/api/postArmorDecrypt.js +0 -49
  33. package/src/lib/api/postArmorKeyring.js +0 -50
  34. package/src/lib/custodians/lock.js +0 -80
  35. package/src/lib/custodians/managed/armor/get.js +0 -44
  36. package/src/lib/helpers/lockedValue.js +0 -24
  37. package/src/lib/helpers/resolveLockPassword.js +0 -5
  38. package/src/lib/helpers/unlockedValue.js +0 -26
  39. package/src/lib/helpers/withLockedKeys.js +0 -41
  40. package/src/lib/providers/provider-worker.js +0 -6
  41. package/src/lib/services/armorKeyring.js +0 -119
  42. package/src/lib/services/lockDown.js +0 -157
  43. package/src/lib/services/lockUp.js +0 -150
@@ -1,66 +1,66 @@
1
- const custodians = require('../custodians')
2
-
3
- function hasKey (keyring, publicKeyHex) {
4
- return keyring && keyring[publicKeyHex]
5
- }
6
-
7
- function composeProviders (providerFns) {
8
- return async function provider (publicKeyHex) {
9
- for (const providerFn of providerFns) {
10
- const keyring = await providerFn(publicKeyHex)
11
- if (hasKey(keyring, publicKeyHex)) return keyring
1
+ const { provider } = require('@dotenvx/providers')
2
+ const bitwarden = require('../custodians/local/bitwarden')
3
+ const { version } = require('../helpers/packageJson')
4
+ const armoredKeyDisplay = require('../helpers/armoredKeyDisplay')
5
+ const listenForOpenKey = require('../helpers/listenForOpenKey')
6
+ const openUrl = require('../helpers/openUrl')
7
+
8
+ const nativeNames = { darwin: 'macosKeychain', win32: 'windowsCredentialManager', linux: 'linuxSecretService' }
9
+
10
+ function lookup (publicKey, options, sync) {
11
+ let source
12
+ let cleanup = () => {}
13
+ const keys = provider({
14
+ ...options,
15
+ // File keys are already resolved against the selected env file by callers.
16
+ fk: [],
17
+ processEnv: bitwarden.commandEnv(),
18
+ cliVersion: version,
19
+ // The async CLI fallback can interactively unlock Bitwarden. The shared
20
+ // synchronous path reads BW_SESSION without prompting.
21
+ noBitwarden: sync ? options.noBitwarden : true,
22
+ onLookup (name) { source = name },
23
+ onApprovalRequired: options.onStatus && (({ approvalUri, code }) => {
24
+ cleanup()
25
+ const display = armoredKeyDisplay(publicKey)
26
+ options.onStatus(`[${code}] press Enter to open [${approvalUri}] and approve${display ? ` (${display})` : ''}`)
27
+ cleanup = listenForOpenKey(() => openUrl(approvalUri))
28
+ })
29
+ })
30
+
31
+ function found (ring) {
32
+ if (ring[publicKey] && options.onProvider) {
33
+ options.onProvider(source === 'native' ? nativeNames[process.platform] || source : source, publicKey)
12
34
  }
13
-
14
- return {}
35
+ return ring
15
36
  }
16
- }
17
37
 
18
- function composeProvidersSync (providerFns) {
19
- return function providerSync (publicKeyHex) {
20
- for (const providerFn of providerFns) {
21
- const keyring = providerFn(publicKeyHex)
22
- if (hasKey(keyring, publicKeyHex)) return keyring
23
- }
24
-
25
- return {}
38
+ if (sync) {
39
+ try { return found(keys.getSync(publicKey)) } finally { cleanup() }
26
40
  }
27
- }
28
41
 
29
- function providerFrom (providerFns, compose) {
30
- if (providerFns.length === 0) return null
31
- if (providerFns.length === 1) return providerFns[0]
32
-
33
- return compose(providerFns)
42
+ return (async () => {
43
+ try {
44
+ let ring = await keys.get(publicKey)
45
+ if (!ring[publicKey] && bitwarden.enabled(options)) {
46
+ source = 'bitwarden'
47
+ ring = await bitwarden.get(publicKey)
48
+ }
49
+ return found(ring)
50
+ } finally {
51
+ cleanup()
52
+ }
53
+ })()
34
54
  }
35
55
 
36
56
  async function providers (options = {}) {
37
- if (Object.prototype.hasOwnProperty.call(options, 'provider')) {
38
- return options.provider
39
- }
40
-
41
- const providerFns = custodians.providers(options)
42
-
43
- const armor = custodians.get('armored')
44
- if (armor.enabled(options) && await armor.configured(options)) {
45
- providerFns.push(publicKey => armor.get(publicKey, options))
46
- }
47
-
48
- return providerFrom(providerFns, composeProviders)
57
+ if (Object.prototype.hasOwnProperty.call(options, 'provider')) return options.provider
58
+ return publicKey => lookup(publicKey, options, false)
49
59
  }
50
60
 
51
- providers.sync = function providersSync (options = {}) {
52
- if (Object.prototype.hasOwnProperty.call(options, 'provider')) {
53
- return options.provider
54
- }
55
-
56
- const providerFns = custodians.providers(options, true)
57
-
58
- const armor = custodians.get('armored')
59
- if (armor.enabled(options) && armor.configuredSync(options)) {
60
- providerFns.push(armor.getSync)
61
- }
62
-
63
- return providerFrom(providerFns, composeProvidersSync)
61
+ providers.sync = function (options = {}) {
62
+ if (Object.prototype.hasOwnProperty.call(options, 'provider')) return options.provider
63
+ return publicKey => lookup(publicKey, options, true)
64
64
  }
65
65
 
66
66
  module.exports = providers
@@ -54,9 +54,8 @@ function inject (processEnv, parsed) {
54
54
  }
55
55
  }
56
56
 
57
- function buildParseOptions ({ lockPassword, processEnv, overload, envKeysFilepath, provider, decryptor }) {
57
+ function buildParseOptions ({ processEnv, overload, envKeysFilepath, provider, decryptor }) {
58
58
  const options = {
59
- lockPassword,
60
59
  processEnv,
61
60
  overload,
62
61
  fk: envKeysFilepath
@@ -75,7 +74,7 @@ function buildParseOptions ({ lockPassword, processEnv, overload, envKeysFilepat
75
74
  return options
76
75
  }
77
76
 
78
- async function injectEnv ({ env, lockPassword, overload, processEnv, envKeysFilepath, provider, decryptor, no1Password, noBitwarden, onStatus }) {
77
+ async function injectEnv ({ env, overload, processEnv, envKeysFilepath, provider, decryptor, no1Password, noBitwarden, onStatus }) {
79
78
  const row = {}
80
79
  row.type = TYPE_ENV
81
80
  row.string = env.value
@@ -89,7 +88,6 @@ async function injectEnv ({ env, lockPassword, overload, processEnv, envKeysFile
89
88
  const parseOptions = buildParseOptions({
90
89
  processEnv: parseProcessEnv,
91
90
  overload,
92
- lockPassword,
93
91
  envKeysFilepath,
94
92
  provider,
95
93
  decryptor
@@ -129,7 +127,7 @@ async function injectEnv ({ env, lockPassword, overload, processEnv, envKeysFile
129
127
  return row
130
128
  }
131
129
 
132
- function injectEnvSync ({ env, lockPassword, overload, processEnv, envKeysFilepath, provider, decryptor, no1Password, noBitwarden }) {
130
+ function injectEnvSync ({ env, overload, processEnv, envKeysFilepath, provider, decryptor, no1Password, noBitwarden }) {
133
131
  const row = {}
134
132
  row.type = TYPE_ENV
135
133
  row.string = env.value
@@ -143,7 +141,6 @@ function injectEnvSync ({ env, lockPassword, overload, processEnv, envKeysFilepa
143
141
  const parseOptions = buildParseOptions({
144
142
  processEnv: parseProcessEnv,
145
143
  overload,
146
- lockPassword,
147
144
  envKeysFilepath,
148
145
  provider,
149
146
  decryptor
@@ -182,7 +179,7 @@ function injectEnvSync ({ env, lockPassword, overload, processEnv, envKeysFilepa
182
179
  return row
183
180
  }
184
181
 
185
- async function injectEnvFile ({ env, lockPassword, overload, processEnv, envKeysFilepath, provider, decryptor, readableFilepaths, no1Password, noBitwarden, onStatus }) {
182
+ async function injectEnvFile ({ env, overload, processEnv, envKeysFilepath, provider, decryptor, readableFilepaths, no1Password, noBitwarden, onStatus }) {
186
183
  const row = {}
187
184
  row.type = TYPE_ENV_FILE
188
185
  row.filepath = env.value
@@ -198,7 +195,6 @@ async function injectEnvFile ({ env, lockPassword, overload, processEnv, envKeys
198
195
  const parseOptions = buildParseOptions({
199
196
  processEnv,
200
197
  overload,
201
- lockPassword,
202
198
  envKeysFilepath: fk,
203
199
  provider,
204
200
  decryptor
@@ -243,7 +239,7 @@ async function injectEnvFile ({ env, lockPassword, overload, processEnv, envKeys
243
239
  return row
244
240
  }
245
241
 
246
- function injectEnvFileSync ({ env, lockPassword, overload, processEnv, envKeysFilepath, provider, decryptor, readableFilepaths, no1Password, noBitwarden }) {
242
+ function injectEnvFileSync ({ env, overload, processEnv, envKeysFilepath, provider, decryptor, readableFilepaths, no1Password, noBitwarden }) {
247
243
  const row = {}
248
244
  row.type = TYPE_ENV_FILE
249
245
  row.filepath = env.value
@@ -259,7 +255,6 @@ function injectEnvFileSync ({ env, lockPassword, overload, processEnv, envKeysFi
259
255
  const parseOptions = buildParseOptions({
260
256
  processEnv,
261
257
  overload,
262
- lockPassword,
263
258
  envKeysFilepath: fk,
264
259
  provider,
265
260
  decryptor
@@ -317,7 +312,6 @@ async function envs (options = {}) {
317
312
  processedEnvs.push(await injectEnvFile({
318
313
  env,
319
314
  overload: options.overload,
320
- lockPassword: options.lockPassword,
321
315
  processEnv,
322
316
  envKeysFilepath,
323
317
  provider,
@@ -331,7 +325,6 @@ async function envs (options = {}) {
331
325
  processedEnvs.push(await injectEnv({
332
326
  env,
333
327
  overload: options.overload,
334
- lockPassword: options.lockPassword,
335
328
  processEnv,
336
329
  envKeysFilepath,
337
330
  provider,
@@ -364,7 +357,6 @@ function envsSync (options = {}) {
364
357
  processedEnvs.push(injectEnvFileSync({
365
358
  env,
366
359
  overload: options.overload,
367
- lockPassword: options.lockPassword,
368
360
  processEnv,
369
361
  envKeysFilepath,
370
362
  provider,
@@ -377,7 +369,6 @@ function envsSync (options = {}) {
377
369
  processedEnvs.push(injectEnvSync({
378
370
  env,
379
371
  overload: options.overload,
380
- lockPassword: options.lockPassword,
381
372
  processEnv,
382
373
  envKeysFilepath,
383
374
  provider,
@@ -53,7 +53,6 @@ function buildOptions (options, processEnv) {
53
53
  noNative: options.noNative,
54
54
  no1Password: options.no1Password,
55
55
  noBitwarden: options.noBitwarden,
56
- lockPassword: options.lockPassword,
57
56
  onStatus: options.onStatus
58
57
  }
59
58
  }
@@ -1,3 +1,4 @@
1
+ const { file } = require('@dotenvx/providers')
1
2
  const fsx = require('./../helpers/fsx')
2
3
  const path = require('path')
3
4
  const keynames = require('./../conventions/keynames')
@@ -30,6 +31,7 @@ function outputKeypair ({ out, filepath, publicKey, ring }) {
30
31
 
31
32
  async function keypair (options = {}) {
32
33
  const out = {}
34
+ const origins = {}
33
35
  const processEnv = options.processEnv || process.env
34
36
 
35
37
  for (const filepath of filepaths(options.envFile)) {
@@ -42,19 +44,36 @@ async function keypair (options = {}) {
42
44
  fk: options.envKeysFilepath || options.envKeysFile || path.resolve(path.dirname(filepath), '.env.keys')
43
45
  })
44
46
 
45
- const provider = await providers(options)
46
- keyringOptions.provider = provider
47
+ let origin = 'environment'
48
+ const provider = await providers({ ...options, onProvider: name => { origin = name } })
49
+ const keys = file({ fk: keyringOptions.fk })
50
+ keyringOptions.provider = async publicKey => {
51
+ const ring = await keys.get(publicKey)
52
+ if (ring[publicKey]) {
53
+ origin = '.env.keys'
54
+ return ring
55
+ }
56
+ origin = 'custom'
57
+ return provider ? provider(publicKey) : {}
58
+ }
59
+ if (publicKey) keyringOptions.fk = []
47
60
 
48
61
  const ring = await keyring(keyringOptions)
49
62
 
50
63
  outputKeypair({ out, filepath, publicKey, ring })
64
+ origins[filepath] = publicKey && ring[publicKey] ? origin : null
51
65
  }
52
66
 
67
+ if (options.includeProvider) {
68
+ const names = Object.keys(origins)
69
+ out.provider = names.length === 1 ? origins[names[0]] : origins
70
+ }
53
71
  return out
54
72
  }
55
73
 
56
74
  function keypairSync (options = {}) {
57
75
  const out = {}
76
+ const origins = {}
58
77
  const processEnv = options.processEnv || process.env
59
78
 
60
79
  for (const filepath of filepaths(options.envFile)) {
@@ -66,14 +85,30 @@ function keypairSync (options = {}) {
66
85
  processEnv,
67
86
  fk: options.envKeysFilepath || options.envKeysFile || path.resolve(path.dirname(filepath), '.env.keys')
68
87
  })
69
- const provider = providers.sync(options)
70
- keyringOptions.provider = provider
88
+ let origin = 'environment'
89
+ const provider = providers.sync({ ...options, onProvider: name => { origin = name } })
90
+ const keys = file({ fk: keyringOptions.fk })
91
+ keyringOptions.provider = publicKey => {
92
+ const ring = keys.getSync(publicKey)
93
+ if (ring[publicKey]) {
94
+ origin = '.env.keys'
95
+ return ring
96
+ }
97
+ origin = 'custom'
98
+ return provider ? provider(publicKey) : {}
99
+ }
100
+ if (publicKey) keyringOptions.fk = []
71
101
 
72
102
  const ring = keyringSync(keyringOptions)
73
103
 
74
104
  outputKeypair({ out, filepath, publicKey, ring })
105
+ origins[filepath] = publicKey && ring[publicKey] ? origin : null
75
106
  }
76
107
 
108
+ if (options.includeProvider) {
109
+ const names = Object.keys(origins)
110
+ out.provider = names.length === 1 ? origins[names[0]] : origins
111
+ }
77
112
  return out
78
113
  }
79
114
 
@@ -32,7 +32,6 @@ module.exports = async function validate ({ envs = [], options = {}, processEnv
32
32
  noNative: options.native === false || options.noNative === true,
33
33
  no1Password: options['1password'] === false || options.no1Password === true,
34
34
  noBitwarden: options.bitwarden === false || options.noBitwarden === true,
35
- lockPassword: options.lockPassword,
36
35
  token: options.token,
37
36
  command,
38
37
  onStatus
@@ -1,54 +0,0 @@
1
- const unlockedValue = require('../../../lib/helpers/unlockedValue')
2
-
3
- const { logger } = require('../../../shared/logger')
4
- const LockDown = require('./../../../lib/services/lockDown')
5
- const armoredKeyDisplay = require('../../../lib/helpers/armoredKeyDisplay')
6
- const prompts = require('../../../lib/helpers/prompts')
7
- const resolveLockPassword = require('../../../lib/helpers/resolveLockPassword')
8
-
9
- async function down () {
10
- const options = this.opts()
11
- logger.debug(`options: ${JSON.stringify(options)}`)
12
-
13
- try {
14
- const lockDown = new LockDown(options.envFile, options.envKeysFile)
15
- const plan = lockDown.plan()
16
- let results = plan.alreadyUnlocked
17
-
18
- if (plan.locked.length > 0) {
19
- const preset = resolveLockPassword(options)
20
- const passphrase = preset !== undefined
21
- ? preset
22
- : await prompts.password({
23
- message: 'passphrase',
24
- prefix: '⊡',
25
- separator: '='
26
- }, {
27
- input: process.stdin,
28
- output: process.stderr
29
- })
30
-
31
- results = lockDown.run(lockedPrivateKey => unlockedValue(lockedPrivateKey, passphrase)).results
32
- }
33
-
34
- for (const result of results) {
35
- const keyDisplay = armoredKeyDisplay(result.publicKeyValue) || result.privateKeyName
36
-
37
- if (result.changed) {
38
- logger.success(`⊡ unlocked (${keyDisplay})`)
39
- } else {
40
- logger.info(`○ no change (${keyDisplay})`)
41
- }
42
- }
43
- } catch (error) {
44
- if (error.code === 'PROMPT_CANCELLED') {
45
- return { exitCode: 130, error }
46
- }
47
-
48
- logger.error(error.message)
49
- return { exitCode: 1, error }
50
- }
51
- }
52
-
53
- module.exports = down
54
- module.exports.unlockedValue = unlockedValue
@@ -1,62 +0,0 @@
1
- const lockedValue = require('../../../lib/helpers/lockedValue')
2
-
3
- const { logger } = require('../../../shared/logger')
4
- const LockUp = require('./../../../lib/services/lockUp')
5
- const armoredKeyDisplay = require('../../../lib/helpers/armoredKeyDisplay')
6
- const prompts = require('../../../lib/helpers/prompts')
7
- const resolveLockPassword = require('../../../lib/helpers/resolveLockPassword')
8
-
9
- async function up () {
10
- const options = this.opts()
11
- logger.debug(`options: ${JSON.stringify(options)}`)
12
-
13
- try {
14
- const lockUp = new LockUp(options.envFile, options.envKeysFile)
15
-
16
- const plan = lockUp.plan()
17
- let results = plan.alreadyLocked.map(lockedPrivateKey => ({
18
- changed: false,
19
- privateKeyName: lockedPrivateKey.privateKeyName,
20
- privateKeyValue: undefined,
21
- lockedPrivateKeyValue: lockedPrivateKey.lockedPrivateKeyValue,
22
- publicKeyValue: lockedPrivateKey.publicKeyValue,
23
- alreadyLocked: true
24
- }))
25
-
26
- if (plan.matches.length > 0) {
27
- const preset = resolveLockPassword(options)
28
- const passphrase = preset !== undefined
29
- ? preset
30
- : await prompts.password({
31
- message: 'passphrase',
32
- prefix: '⊡',
33
- separator: '='
34
- }, {
35
- input: process.stdin,
36
- output: process.stderr
37
- })
38
-
39
- results = lockUp.run((privateKey, publicKey) => lockedValue(privateKey, passphrase, publicKey)).results
40
- }
41
-
42
- for (const result of results) {
43
- const keyDisplay = armoredKeyDisplay(result.publicKeyValue) || result.privateKeyName
44
-
45
- if (result.changed) {
46
- logger.success(`⊡ locked (${keyDisplay})`)
47
- } else {
48
- logger.info(`○ no change (${keyDisplay})`)
49
- }
50
- }
51
- } catch (error) {
52
- if (error.code === 'PROMPT_CANCELLED') {
53
- return { exitCode: 130, error }
54
- }
55
-
56
- logger.error(error.message)
57
- return { exitCode: 1, error }
58
- }
59
- }
60
-
61
- module.exports = up
62
- module.exports.lockedValue = lockedValue
@@ -1,36 +0,0 @@
1
- const commandAction = require('../commandAction')
2
- function configureLockCommand (lock) {
3
- lock.hook('preAction', async () => {
4
- const Session = require('./../../db/session')
5
- const sesh = new Session()
6
- await sesh.notifyUpdate()
7
- })
8
-
9
- lock
10
- .description('lock private keys with a local passphrase')
11
- .action(function () {
12
- this.help()
13
- })
14
-
15
- lock
16
- .command('up')
17
- .description('lock key in .env.keys')
18
- .option('-f, --env-file <path>', 'path to your env file')
19
- .option('-fk, --env-keys-file <path>', 'path to your .env.keys file', '.env.keys')
20
- .action(function (...args) {
21
- return commandAction(require('./../actions/lock/up')).apply(this, args)
22
- })
23
-
24
- lock
25
- .command('down')
26
- .description('unlock key in .env.keys')
27
- .option('-f, --env-file <path>', 'path to your env file')
28
- .option('-fk, --env-keys-file <path>', 'path to your .env.keys file', '.env.keys')
29
- .action(function (...args) {
30
- return commandAction(require('./../actions/lock/down')).apply(this, args)
31
- })
32
-
33
- return lock
34
- }
35
-
36
- module.exports = configureLockCommand
@@ -1,49 +0,0 @@
1
- const { http } = require('../helpers/http')
2
- const buildApiError = require('../helpers/buildApiError')
3
- const packageJson = require('../helpers/packageJson')
4
- const normalizeToken = require('../helpers/normalizeToken')
5
-
6
- class PostArmorDecrypt {
7
- constructor (hostname, token, devicePublicKey, publicKey, src, grantToken) {
8
- this.hostname = hostname || 'https://armor.dotenvx.com'
9
- this.token = token
10
- this.devicePublicKey = devicePublicKey
11
- this.publicKey = publicKey
12
- this.src = src
13
- this.grantToken = grantToken
14
- }
15
-
16
- async run () {
17
- const token = normalizeToken(this.token)
18
- const url = `${this.hostname}/api/armor/decrypt`
19
- const body = {
20
- device_public_key: this.devicePublicKey,
21
- cli_version: packageJson.version,
22
- public_key: this.publicKey,
23
- src: this.src
24
- }
25
-
26
- if (this.grantToken) {
27
- body.grant_token = this.grantToken
28
- }
29
-
30
- const resp = await http(url, {
31
- method: 'POST',
32
- headers: {
33
- Authorization: `Bearer ${token}`,
34
- 'Content-Type': 'application/json'
35
- },
36
- body: JSON.stringify(body)
37
- })
38
-
39
- const json = await resp.body.json()
40
-
41
- if (resp.statusCode >= 400) {
42
- throw buildApiError(resp.statusCode, json)
43
- }
44
-
45
- return json
46
- }
47
- }
48
-
49
- module.exports = PostArmorDecrypt
@@ -1,50 +0,0 @@
1
- const { http } = require('../helpers/http')
2
- const buildApiError = require('../helpers/buildApiError')
3
- const packageJson = require('../helpers/packageJson')
4
- const normalizeToken = require('../helpers/normalizeToken')
5
-
6
- class PostArmorKeyring {
7
- constructor (hostname, token, devicePublicKey, publicKey, grantToken) {
8
- this.hostname = hostname || 'https://armor.dotenvx.com'
9
- this.token = token
10
- this.devicePublicKey = devicePublicKey
11
- this.publicKey = publicKey
12
- this.grantToken = grantToken
13
- }
14
-
15
- async run () {
16
- const token = normalizeToken(this.token)
17
- const url = `${this.hostname}/api/armor/keyring`
18
- const body = {
19
- device_public_key: this.devicePublicKey,
20
- cli_version: packageJson.version
21
- }
22
-
23
- if (this.publicKey) {
24
- body.public_key = this.publicKey
25
- }
26
-
27
- if (this.grantToken) {
28
- body.grant_token = this.grantToken
29
- }
30
-
31
- const resp = await http(url, {
32
- method: 'POST',
33
- headers: {
34
- Authorization: `Bearer ${token}`,
35
- 'Content-Type': 'application/json'
36
- },
37
- body: JSON.stringify(body)
38
- })
39
-
40
- const json = await resp.body.json()
41
-
42
- if (resp.statusCode >= 400) {
43
- throw buildApiError(resp.statusCode, json)
44
- }
45
-
46
- return json
47
- }
48
- }
49
-
50
- module.exports = PostArmorKeyring
@@ -1,80 +0,0 @@
1
- const { derive } = require('@dotenvx/primitives')
2
- const lockedValue = require('../helpers/lockedValue')
3
- const unlockedValue = require('../helpers/unlockedValue')
4
- const prompts = require('../helpers/prompts')
5
- const createSpinner = require('../helpers/createSpinner')
6
- const matchesKey = require('../helpers/matchesStoredKey')
7
- const Errors = require('../helpers/errors')
8
- const resolveLockPassword = require('../helpers/resolveLockPassword')
9
-
10
- // Context is shared only within a transform; never cache passphrases globally
11
- // by filename or return them alongside the staged keys.
12
- const passphrases = new WeakMap()
13
-
14
- async function promptPassphrase () {
15
- createSpinner.pause()
16
- try {
17
- const passphrase = await prompts.password({ message: 'passphrase', prefix: '⊡', separator: '=' }, {
18
- input: process.stdin,
19
- output: process.stderr
20
- })
21
- if (!passphrase) throw new Error('passphrase must not be empty')
22
- return passphrase
23
- } finally {
24
- createSpinner.resume()
25
- }
26
- }
27
-
28
- async function lock (publicKey, privateKey, context) {
29
- if (derive(privateKey) !== publicKey) throw new Error('private key does not match the .env public key')
30
- if (!passphrases.has(context)) {
31
- const password = resolveLockPassword(context)
32
- if (password === '') throw new Error('passphrase must not be empty')
33
- passphrases.set(context, password !== undefined ? password : promptPassphrase())
34
- }
35
- return lockedValue(privateKey, await passphrases.get(context), publicKey)
36
- }
37
-
38
- function isLocked (value) {
39
- return typeof value === 'string' && value.startsWith('locked:')
40
- }
41
-
42
- function unlockValue (publicKey, ring, passphrase) {
43
- try {
44
- const privateKey = unlockedValue(ring[publicKey], passphrase)
45
- if (derive(privateKey) !== publicKey) throw new Error('key mismatch')
46
- return { ...ring, [publicKey]: privateKey }
47
- } catch {
48
- throw new Errors().invalidPassphrase()
49
- }
50
- }
51
-
52
- function validateLocked (publicKey, ring) {
53
- const value = ring && ring[publicKey]
54
- if (!isLocked(value)) return false
55
- if (!matchesKey(publicKey, value)) throw new Error('invalid locked private key')
56
- return true
57
- }
58
-
59
- function passwordRequired () {
60
- const error = new Error('[LOCKED_PRIVATE_KEY] supply --lock-password, lockPassword, or DOTENVX_LOCK_PASSWORD to unlock the private key')
61
- error.code = 'LOCKED_PRIVATE_KEY'
62
- return error
63
- }
64
-
65
- async function unlock (publicKey, ring, options = {}) {
66
- if (!validateLocked(publicKey, ring)) return ring
67
- const password = resolveLockPassword(options)
68
- if (password !== undefined) return unlockValue(publicKey, ring, password)
69
- if (!process.stdin.isTTY || !process.stderr.isTTY || process.env.CI) throw passwordRequired()
70
- return unlockValue(publicKey, ring, await promptPassphrase())
71
- }
72
-
73
- function unlockSync (publicKey, ring, options = {}) {
74
- if (!validateLocked(publicKey, ring)) return ring
75
- const password = resolveLockPassword(options)
76
- if (password === undefined) throw passwordRequired()
77
- return unlockValue(publicKey, ring, password)
78
- }
79
-
80
- module.exports = { lock, unlock, unlockSync }