@dotenvx/dotenvx 2.28.2 → 2.30.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 (82) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/README.md +47 -12
  3. package/package.json +3 -3
  4. package/src/cli/actions/armor/down.js +1 -1
  5. package/src/cli/actions/armor/move.js +1 -1
  6. package/src/cli/actions/armor/open.js +1 -1
  7. package/src/cli/actions/armor/pull.js +1 -1
  8. package/src/cli/actions/armor/push.js +1 -1
  9. package/src/cli/actions/armor/up.js +1 -1
  10. package/src/cli/actions/curl.js +2 -2
  11. package/src/cli/actions/decrypt.js +4 -10
  12. package/src/cli/actions/define.js +1 -1
  13. package/src/cli/actions/del.js +3 -5
  14. package/src/cli/actions/encrypt.js +4 -10
  15. package/src/cli/actions/ext/genexample.js +1 -1
  16. package/src/cli/actions/ext/gitignore.js +1 -0
  17. package/src/cli/actions/ext/prebuild.js +5 -28
  18. package/src/cli/actions/ext/precommit.js +8 -3
  19. package/src/cli/actions/ext/scan.js +2 -3
  20. package/src/cli/actions/get.js +4 -7
  21. package/src/cli/actions/keychain/down.js +1 -1
  22. package/src/cli/actions/keychain/pull.js +1 -1
  23. package/src/cli/actions/keychain/push.js +1 -1
  24. package/src/cli/actions/keychain/up.js +1 -1
  25. package/src/cli/actions/keypair.js +3 -3
  26. package/src/cli/actions/lock/down.js +2 -3
  27. package/src/cli/actions/lock/up.js +2 -3
  28. package/src/cli/actions/login.js +2 -2
  29. package/src/cli/actions/logout.js +1 -1
  30. package/src/cli/actions/ls.js +1 -1
  31. package/src/cli/actions/protect.js +75 -0
  32. package/src/cli/actions/protectDocker.js +30 -0
  33. package/src/cli/actions/protectProcess.js +126 -0
  34. package/src/cli/actions/protectStdin.js +64 -0
  35. package/src/cli/actions/run.js +5 -6
  36. package/src/cli/actions/set.js +5 -9
  37. package/src/cli/actions/settings/device.js +2 -2
  38. package/src/cli/actions/settings/hostname.js +2 -2
  39. package/src/cli/actions/settings/off.js +1 -1
  40. package/src/cli/actions/settings/on.js +1 -1
  41. package/src/cli/actions/settings/path.js +2 -2
  42. package/src/cli/actions/settings/token.js +2 -2
  43. package/src/cli/actions/settings/username.js +2 -2
  44. package/src/cli/actions/validate.js +2 -2
  45. package/src/cli/commandAction.js +16 -0
  46. package/src/cli/commands/armor.js +10 -9
  47. package/src/cli/commands/custody.js +6 -4
  48. package/src/cli/commands/ext.js +7 -7
  49. package/src/cli/commands/lock.js +3 -2
  50. package/src/cli/commands/native.js +5 -4
  51. package/src/cli/commands/settings.js +8 -7
  52. package/src/cli/dotenvx.js +31 -17
  53. package/src/cli/help.js +4 -3
  54. package/src/lib/events/backends/armor.js +31 -0
  55. package/src/lib/events/background.js +59 -0
  56. package/src/lib/events/catalog.js +14 -0
  57. package/src/lib/events/cli.js +40 -0
  58. package/src/lib/events/delivery.js +89 -0
  59. package/src/lib/events/index.js +73 -0
  60. package/src/lib/events/metadata.js +25 -0
  61. package/src/lib/events/sdk.js +44 -0
  62. package/src/lib/events/worker.js +29 -0
  63. package/src/lib/events/workerEnvironment.js +14 -0
  64. package/src/lib/helpers/checklist.js +50 -0
  65. package/src/lib/helpers/createProtectSpinner.js +13 -0
  66. package/src/lib/helpers/executeCommand.js +12 -1
  67. package/src/lib/helpers/hasPlaintextSecrets.js +7 -0
  68. package/src/lib/helpers/installPrecommitHook.js +1 -0
  69. package/src/lib/helpers/installProtectFilter.js +56 -0
  70. package/src/lib/helpers/installProtectIgnore.js +27 -0
  71. package/src/lib/helpers/logProtectedFiles.js +9 -0
  72. package/src/lib/helpers/precommitEnvPatterns.js +1 -0
  73. package/src/lib/helpers/prompts.js +24 -0
  74. package/src/lib/helpers/protectSettings.js +63 -0
  75. package/src/lib/helpers/removeLegacyProtectFilter.js +42 -0
  76. package/src/lib/helpers/uninstallPrecommitHook.js +66 -0
  77. package/src/lib/main.d.ts +14 -0
  78. package/src/lib/main.js +11 -3
  79. package/src/lib/services/prebuild.js +4 -5
  80. package/src/lib/services/precommit.js +2 -12
  81. package/src/cli/actions/ext/precommitClean.js +0 -21
  82. package/src/lib/helpers/installPrecommitFilter.js +0 -50
@@ -1,3 +1,4 @@
1
+ const commandAction = require('../commandAction')
1
2
  function configureLockCommand (lock) {
2
3
  lock.hook('preAction', async () => {
3
4
  const Session = require('./../../db/session')
@@ -17,7 +18,7 @@ function configureLockCommand (lock) {
17
18
  .option('-f, --env-file <path>', 'path to your env file')
18
19
  .option('-fk, --env-keys-file <path>', 'path to your .env.keys file', '.env.keys')
19
20
  .action(function (...args) {
20
- return require('./../actions/lock/up').apply(this, args)
21
+ return commandAction(require('./../actions/lock/up')).apply(this, args)
21
22
  })
22
23
 
23
24
  lock
@@ -26,7 +27,7 @@ function configureLockCommand (lock) {
26
27
  .option('-f, --env-file <path>', 'path to your env file')
27
28
  .option('-fk, --env-keys-file <path>', 'path to your .env.keys file', '.env.keys')
28
29
  .action(function (...args) {
29
- return require('./../actions/lock/down').apply(this, args)
30
+ return commandAction(require('./../actions/lock/down')).apply(this, args)
30
31
  })
31
32
 
32
33
  return lock
@@ -1,3 +1,4 @@
1
+ const commandAction = require('../commandAction')
1
2
  function configureNativeCommand (native) {
2
3
  native.hook('preAction', async () => {
3
4
  const Session = require('./../../db/session')
@@ -17,7 +18,7 @@ function configureNativeCommand (native) {
17
18
  .option('-f, --env-file <path>', 'path to your env file')
18
19
  .option('-fk, --env-keys-file <path>', 'path to your .env.keys file', '.env.keys')
19
20
  .action(function (...args) {
20
- return require('./../actions/keychain/up').apply(this, args)
21
+ return commandAction(require('./../actions/keychain/up')).apply(this, args)
21
22
  })
22
23
 
23
24
  native
@@ -26,7 +27,7 @@ function configureNativeCommand (native) {
26
27
  .option('-f, --env-file <path>', 'path to your env file')
27
28
  .option('-fk, --env-keys-file <path>', 'path to your .env.keys file', '.env.keys')
28
29
  .action(function (...args) {
29
- return require('./../actions/keychain/down').apply(this, args)
30
+ return commandAction(require('./../actions/keychain/down')).apply(this, args)
30
31
  })
31
32
 
32
33
  native
@@ -35,7 +36,7 @@ function configureNativeCommand (native) {
35
36
  .option('-f, --env-file <path>', 'path to your env file')
36
37
  .option('-fk, --env-keys-file <path>', 'path to your .env.keys file', '.env.keys')
37
38
  .action(function (...args) {
38
- return require('./../actions/keychain/push').apply(this, args)
39
+ return commandAction(require('./../actions/keychain/push')).apply(this, args)
39
40
  })
40
41
 
41
42
  native
@@ -44,7 +45,7 @@ function configureNativeCommand (native) {
44
45
  .option('-f, --env-file <path>', 'path to your env file')
45
46
  .option('-fk, --env-keys-file <path>', 'path to your .env.keys file', '.env.keys')
46
47
  .action(function (...args) {
47
- return require('./../actions/keychain/pull').apply(this, args)
48
+ return commandAction(require('./../actions/keychain/pull')).apply(this, args)
48
49
  })
49
50
 
50
51
  return native
@@ -1,3 +1,4 @@
1
+ const commandAction = require('../commandAction')
1
2
  function configureSettingsCommand (settings) {
2
3
  settings
3
4
  .description('settings')
@@ -9,7 +10,7 @@ function configureSettingsCommand (settings) {
9
10
  .command('username')
10
11
  .description('print your username')
11
12
  .action(function (...args) {
12
- return require('./../actions/settings/username').apply(this, args)
13
+ return commandAction(require('./../actions/settings/username')).apply(this, args)
13
14
  })
14
15
 
15
16
  settings
@@ -17,7 +18,7 @@ function configureSettingsCommand (settings) {
17
18
  .description('print your access token (--unmask)')
18
19
  .option('--unmask', 'unmask access token')
19
20
  .action(function (...args) {
20
- return require('./../actions/settings/token').apply(this, args)
21
+ return commandAction(require('./../actions/settings/token')).apply(this, args)
21
22
  })
22
23
 
23
24
  settings
@@ -25,35 +26,35 @@ function configureSettingsCommand (settings) {
25
26
  .description('print your device pubkey (--unmask)')
26
27
  .option('--unmask', 'unmask device pubkey')
27
28
  .action(function (...args) {
28
- return require('./../actions/settings/device').apply(this, args)
29
+ return commandAction(require('./../actions/settings/device')).apply(this, args)
29
30
  })
30
31
 
31
32
  settings
32
33
  .command('hostname')
33
34
  .description('print hostname')
34
35
  .action(function (...args) {
35
- return require('./../actions/settings/hostname').apply(this, args)
36
+ return commandAction(require('./../actions/settings/hostname')).apply(this, args)
36
37
  })
37
38
 
38
39
  settings
39
40
  .command('path')
40
41
  .description('print path to settings file')
41
42
  .action(function (...args) {
42
- return require('./../actions/settings/path').apply(this, args)
43
+ return commandAction(require('./../actions/settings/path')).apply(this, args)
43
44
  })
44
45
 
45
46
  settings
46
47
  .command('on')
47
48
  .description('turn armor on')
48
49
  .action(function (...args) {
49
- return require('./../actions/settings/on').apply(this, args)
50
+ return commandAction(require('./../actions/settings/on')).apply(this, args)
50
51
  })
51
52
 
52
53
  settings
53
54
  .command('off')
54
55
  .description('turn armor off')
55
56
  .action(function (...args) {
56
- return require('./../actions/settings/off').apply(this, args)
57
+ return commandAction(require('./../actions/settings/off')).apply(this, args)
57
58
  })
58
59
 
59
60
  return settings
@@ -3,6 +3,7 @@
3
3
  /* c8 ignore start */
4
4
  const { Command } = require('@dotenvx/tooling')
5
5
  const program = new Command()
6
+ const commandAction = require('./commandAction')
6
7
 
7
8
  const { setLogLevel } = require('../shared/logger')
8
9
  const help = require('./help')
@@ -220,7 +221,7 @@ program.command('ls', { hidden: true })
220
221
  .option('-ef, --exclude-env-file <excludeFilenames...>', 'path(s) to exclude from your env file(s) (default: none)')
221
222
  .option('--json', 'output a JSON array of absolute filepaths')
222
223
  .action(function (...args) {
223
- return require('./actions/ls').apply(this, args)
224
+ return commandAction(require('./actions/ls')).apply(this, args)
224
225
  })
225
226
 
226
227
  // dotenvx init
@@ -228,7 +229,7 @@ program.command('init', { hidden: true })
228
229
  .description('create an Envfile from .env.example and .env')
229
230
  .option('-f, --env-file <path>', 'file to read variable names from')
230
231
  .action(function () {
231
- return require('./actions/init').apply(this, arguments)
232
+ return commandAction(require('./actions/init')).apply(this, arguments)
232
233
  })
233
234
 
234
235
  // dotenvx define
@@ -236,7 +237,7 @@ program.command('define', { hidden: true })
236
237
  .description('define your environment in an Envfile')
237
238
  .option('-f, --env-file <path>', 'file to read variable names from')
238
239
  .action(function () {
239
- return require('./actions/define').apply(this, arguments)
240
+ return commandAction(require('./actions/define')).apply(this, arguments)
240
241
  })
241
242
 
242
243
  // dotenvx validate
@@ -256,12 +257,12 @@ program.command('validate', { hidden: true })
256
257
  .option('--no-bitwarden', 'disable Bitwarden secret reference resolution')
257
258
  .action(function (...args) {
258
259
  this.envs = envs
259
- return require('./actions/validate').apply(this, args)
260
+ return commandAction(require('./actions/validate')).apply(this, args)
260
261
  })
261
262
 
262
263
  // dotenvx gitignore
263
264
  program.command('gitignore', { hidden: true })
264
- .description('append to .gitignore')
265
+ .description('deprecated. use [dotenvx protect]')
265
266
  .addHelpText('after', help.gitignore)
266
267
  .option('--pattern <patterns...>', 'pattern(s) to gitignore', ['.env*'])
267
268
  .action(function (...args) {
@@ -274,24 +275,34 @@ program.command('genexample', { hidden: true })
274
275
  .argument('[directory]', 'directory to generate from', '.')
275
276
  .option('-f, --env-file <paths...>', 'path(s) to your env file(s)', '.env')
276
277
  .action(function (...args) {
277
- return require('./actions/ext/genexample').apply(this, args)
278
+ return commandAction(require('./actions/ext/genexample')).apply(this, args)
278
279
  })
279
280
 
280
281
  // dotenvx precommit
281
282
  program.command('precommit', { hidden: true })
282
- .description('prevent committing .env files to code')
283
+ .description('deprecated. use [dotenvx protect]')
283
284
  .addHelpText('after', help.precommit)
284
285
  .argument('[directory]', 'directory to prevent committing .env files from', '.')
285
- .option('-i, --install', 'install a pre-commit hook and required Git clean filter')
286
- .option('--global', 'with --install, install the clean filter for all repositories')
287
- .addOption(program.createOption('--clean <path>', 'validate Git filter input from stdin').hideHelp())
286
+ .option('-i, --install', 'install a pre-commit hook')
287
+ .option('--uninstall', 'remove the dotenvx pre-commit hook')
288
288
  .action(function (...args) {
289
289
  return require('./actions/ext/precommit').apply(this, args)
290
290
  })
291
291
 
292
+ // dotenvx protect
293
+ program.command('protect', { hidden: true })
294
+ .description('protect secrets and private keys from code commits')
295
+ .argument('[directory]', 'directory to check with --docker', '.')
296
+ .addOption(program.createOption('--docker', 'check env files are encrypted or dockerignored').conflicts(['gitFile', 'gitProcess']))
297
+ .addOption(program.createOption('--git-file <pathname>', 'check stdin contents for the given Git pathname').hideHelp())
298
+ .addOption(program.createOption('--git-process', 'run the Git protection filter protocol').hideHelp())
299
+ .action(function () {
300
+ return require('./actions/protect').apply(this, arguments)
301
+ })
302
+
292
303
  // dotenvx prebuild
293
304
  program.command('prebuild', { hidden: true })
294
- .description('prevent including .env files in docker')
305
+ .description('deprecated. use [dotenvx protect --docker]')
295
306
  .addHelpText('after', help.prebuild)
296
307
  .argument('[directory]', 'directory to prevent including .env files from', '.')
297
308
  .action(function (...args) {
@@ -303,21 +314,21 @@ program.command('doctor', { hidden: true })
303
314
  .description('scan for dotenv loaders')
304
315
  .argument('[directory]', 'directory to scan', '.')
305
316
  .action(function (...args) {
306
- return require('./actions/doctor').apply(this, args)
317
+ return commandAction(require('./actions/doctor')).apply(this, args)
307
318
  })
308
319
 
309
320
  // dotenvx hidden (a menu of top-level commands)
310
321
  program.command('hidden')
311
322
  .allowExcessArguments(false)
312
323
  .description('hidden features')
313
- .addHelpText('after', '\nHidden Commands:\n init create an Envfile from .env.example and .env\n define define your environment in an Envfile\n validate validate .env file(s) against Envfile\n genexample [directory] generate .env.example\n gitignore append to .gitignore\n ls [directory] print all .env files in a tree structure\n prebuild [directory] prevent including .env files in docker\n precommit [directory] prevent committing .env files to code\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\nRun directly: dotenvx <command>')
324
+ .addHelpText('after', '\nHidden Commands:\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.example and .env\n define define your environment in an Envfile\n validate validate .env file(s) against Envfile\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>')
314
325
  .action(function () { this.outputHelp() })
315
326
 
316
327
  // dotenvx update
317
328
  program.command('update')
318
329
  .description('update dotenvx')
319
330
  .action(function (...args) {
320
- return require('./actions/update').apply(this, args)
331
+ return commandAction(require('./actions/update')).apply(this, args)
321
332
  })
322
333
 
323
334
  // dotenvx login (compatibility alias for dotenvx armor login)
@@ -326,7 +337,7 @@ program.command('login', { hidden: true })
326
337
  .allowUnknownOption()
327
338
  .option('--hostname <hostname>', 'set Armor ⛨ hostname')
328
339
  .action(function (...args) {
329
- return require('./actions/login').apply(this, args)
340
+ return commandAction(require('./actions/login')).apply(this, args)
330
341
  })
331
342
 
332
343
  // dotenvx logout (compatibility alias for dotenvx armor logout)
@@ -335,7 +346,7 @@ program.command('logout', { hidden: true })
335
346
  .allowUnknownOption()
336
347
  .option('--hostname <hostname>', 'set Armor ⛨ hostname')
337
348
  .action(function (...args) {
338
- return require('./actions/logout').apply(this, args)
349
+ return commandAction(require('./actions/logout')).apply(this, args)
339
350
  })
340
351
 
341
352
  // dotenvx curl
@@ -352,7 +363,7 @@ program.command('curl', { hidden: true })
352
363
  return
353
364
  }
354
365
 
355
- return require('./actions/curl').apply(this, args)
366
+ return commandAction(require('./actions/curl')).apply(this, args)
356
367
  })
357
368
 
358
369
  // dotenvx help
@@ -405,6 +416,9 @@ program.helpInformation = function () {
405
416
  }
406
417
  /* c8 ignore stop */
407
418
 
419
+ program.command('_deliver-events', { hidden: true })
420
+ .action(() => require('../lib/events/worker')())
421
+
408
422
  require('./commands/fileOptions')(program)
409
423
 
410
424
  program.parse(process.argv)
package/src/cli/help.js CHANGED
@@ -42,17 +42,18 @@ Try it:
42
42
 
43
43
  const prebuild = function () {
44
44
  return `
45
+ Deprecated. Use [dotenvx protect --docker].
46
+
45
47
  Examples:
46
48
 
47
49
  \`\`\`
48
- $ dotenvx prebuild
50
+ $ dotenvx protect --docker
49
51
  \`\`\`
50
52
 
51
53
  Try it:
52
54
 
53
55
  \`\`\`
54
- $ dotenvx prebuild
55
- [dotenvx@0.10.0][prebuild] success
56
+ $ dotenvx protect --docker apps/backend
56
57
  \`\`\`
57
58
  `
58
59
  }
@@ -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
+ }
@@ -0,0 +1,73 @@
1
+ const { performance } = require('perf_hooks')
2
+ const safe = require('./metadata')
3
+ const catalog = require('./catalog')
4
+ const createDelivery = require('./delivery')
5
+ const createBackground = require('./background')
6
+ const armor = require('./backends/armor')
7
+ const { version } = require('../helpers/packageJson')
8
+
9
+ module.exports = function createEvents (name, options = {}, config = {}) {
10
+ let backend
11
+ let delivery
12
+ let selectedOptions
13
+ try {
14
+ selectedOptions = safe.options(config.eventOptions || options)
15
+ if (Object.prototype.hasOwnProperty.call(catalog, name)) {
16
+ if (config.background && !Object.prototype.hasOwnProperty.call(config, 'backend')) delivery = createBackground(options)
17
+ else backend = Object.prototype.hasOwnProperty.call(config, 'backend') ? config.backend : armor(options)
18
+ }
19
+ } catch {} // Missing credentials, keychain failures, and setup are optional.
20
+
21
+ delivery = delivery || createDelivery(backend, config.timeoutMs)
22
+ const started = performance.now()
23
+ const runtime = name.startsWith('sdk/') ? { sdk_version: version, sdk_language: 'javascript' } : { cli_version: version }
24
+ let completion
25
+ let failed = false
26
+ let details = {}
27
+
28
+ function record (metadata = {}, outcome = 'success', terminal = false) {
29
+ try {
30
+ if (completion) return
31
+ const eventOptions = safe.options(selectedOptions)
32
+ delivery.write({
33
+ name,
34
+ occurred_at: new Date().toISOString(),
35
+ outcome: outcome === 'success' ? 'success' : 'unsuccessful',
36
+ metadata: { ...safe.metadata(metadata), ...(Object.keys(eventOptions).length ? { options: eventOptions } : {}), ...runtime }
37
+ }, terminal)
38
+ } catch {}
39
+ }
40
+
41
+ return {
42
+ record,
43
+ file (row, metadata = {}) {
44
+ try {
45
+ if (completion) return
46
+ details.error_count = (details.error_count || 0) + (row.error ? 1 : 0)
47
+ if (row.error) failed = true
48
+ record({
49
+ output: options.stdout ? 'stdout' : 'file',
50
+ ...(details.key !== undefined ? { key: details.key } : {}),
51
+ ...metadata,
52
+ phase: 'file',
53
+ file: row.envFilepath,
54
+ changed: !row.error && !!row.changed,
55
+ ...(row.error ? { error_code: safe.errorCode(row.error) } : {})
56
+ }, row.error ? 'unsuccessful' : 'success')
57
+ } catch {}
58
+ },
59
+ add (metadata) { try { details = { ...details, ...safe.metadata(metadata) } } catch {} },
60
+ fail (error) {
61
+ failed = true
62
+ try { details.error_code = safe.errorCode(error) } catch {}
63
+ },
64
+ complete (outcome, metadata = {}) {
65
+ if (!completion) {
66
+ record({ ...details, ...metadata, phase: 'complete', duration_ms: Math.round(performance.now() - started) }, outcome || (failed ? 'unsuccessful' : 'success'), true)
67
+ completion = delivery.close()
68
+ }
69
+ return completion
70
+ },
71
+ flush: delivery.flush
72
+ }
73
+ }
@@ -0,0 +1,25 @@
1
+ // Event metadata is an allowlist, not a copy of command options or debug logs.
2
+ const fields = new Set(['key', 'file', 'files', 'changed', 'output', 'action', 'phase', 'decision', 'reason', 'error_code', 'error_count', 'warning_count', 'injected_count', 'proxied_count', 'exit_code', 'signal', 'duration_ms', 'filter', 'ignore', 'scope', 'executable'])
3
+ const optionFields = new Set(['envFile', 'envKeysFile', 'key', 'includeKey', 'excludeKey', 'stdout', 'plain', 'armor', 'native', '1password', 'bitwarden', 'create', 'overload', 'all', 'strict', 'convention', 'ignore', 'mask', 'redact', 'format', 'prettyPrint', 'pp', 'docker', 'gitFile', 'gitProcess', 'quiet', 'verbose', 'debug', 'logLevel', 'path', 'encoding', 'override', 'encrypt', 'noArmor', 'noNative', 'no1Password', 'noBitwarden'])
4
+
5
+ function value (input) {
6
+ if (input === null || typeof input === 'boolean') return input
7
+ if (typeof input === 'number' && Number.isFinite(input)) return input
8
+ if (typeof input === 'string') return input.slice(0, 1024)
9
+ if (Array.isArray(input)) return input.slice(0, 100).map(item => value(item)).filter(item => item !== undefined && !Array.isArray(item))
10
+ }
11
+
12
+ function select (input, allowed) {
13
+ const output = {}
14
+ for (const key of allowed) {
15
+ const selected = value(input[key])
16
+ if (selected !== undefined) output[key] = selected
17
+ }
18
+ return output
19
+ }
20
+
21
+ module.exports = {
22
+ metadata: input => select(input, fields),
23
+ options: input => select(input, optionFields),
24
+ errorCode: error => /^[A-Z][A-Z0-9_]{0,79}$/.test(error && error.code) ? error.code : 'COMMAND_FAILED'
25
+ }