emailengine-app 2.84.2 → 2.86.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 (164) hide show
  1. package/.ncurc.js +29 -9
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +107 -0
  6. package/Dockerfile +20 -1
  7. package/ENVIRONMENT.md +139 -0
  8. package/README.md +2 -2
  9. package/bin/emailengine.js +434 -408
  10. package/config/default.toml +2 -0
  11. package/copy-static-files.sh +41 -14
  12. package/data/google-crawlers.json +1 -1
  13. package/data/public_suffix_list.dat +16563 -0
  14. package/eslint.config.js +81 -99
  15. package/lib/account-assignment.js +19 -0
  16. package/lib/account.js +230 -170
  17. package/lib/api-error-codes.js +49 -0
  18. package/lib/api-reference/format.js +4 -3
  19. package/lib/api-reference/model.js +6 -1
  20. package/lib/api-routes/account-routes.js +255 -38
  21. package/lib/api-routes/blocklist-routes.js +91 -4
  22. package/lib/api-routes/delivery-test-routes.js +27 -4
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +110 -12
  25. package/lib/api-routes/index.js +4 -0
  26. package/lib/api-routes/license-routes.js +2 -2
  27. package/lib/api-routes/mailbox-routes.js +44 -5
  28. package/lib/api-routes/message-routes.js +112 -10
  29. package/lib/api-routes/oauth2-app-routes.js +63 -23
  30. package/lib/api-routes/outbox-routes.js +97 -52
  31. package/lib/api-routes/permission-map.js +67 -7
  32. package/lib/api-routes/scoped-routes.js +74 -0
  33. package/lib/api-routes/settings-routes.js +34 -6
  34. package/lib/api-routes/stats-routes.js +5 -1
  35. package/lib/api-routes/submit-routes.js +337 -309
  36. package/lib/api-routes/template-routes.js +45 -8
  37. package/lib/api-routes/token-routes.js +152 -100
  38. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  39. package/lib/api-routes/webhook-route-routes.js +132 -6
  40. package/lib/bounce-detect.js +397 -205
  41. package/lib/calendar-event.js +81 -1
  42. package/lib/consts.js +38 -45
  43. package/lib/db.js +14 -6
  44. package/lib/delivery-error.js +6 -0
  45. package/lib/deprecations.js +270 -0
  46. package/lib/email-client/base-client.js +137 -184
  47. package/lib/email-client/fallback-poll.js +62 -0
  48. package/lib/email-client/gmail-client.js +60 -22
  49. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  50. package/lib/email-client/imap/adaptive-idle.js +278 -0
  51. package/lib/email-client/imap/connection-errors.js +14 -1
  52. package/lib/email-client/imap/idle-settings.js +31 -5
  53. package/lib/email-client/imap/listing-diff.js +37 -0
  54. package/lib/email-client/imap/mailbox.js +372 -242
  55. package/lib/email-client/imap/subconnection.js +8 -30
  56. package/lib/email-client/imap/sync-operations.js +220 -127
  57. package/lib/email-client/imap-client.js +228 -164
  58. package/lib/email-client/message-builder.js +14 -79
  59. package/lib/email-client/notification-handler.js +1 -2
  60. package/lib/email-client/outlook-client.js +372 -338
  61. package/lib/email-client/smtp-pool-manager.js +16 -13
  62. package/lib/email-client/sync-state-fields.js +19 -0
  63. package/lib/encrypt.js +157 -41
  64. package/lib/enum-descriptions.js +3 -1
  65. package/lib/env-setting-overrides.js +288 -0
  66. package/lib/export-worker.js +751 -0
  67. package/lib/export.js +64 -15
  68. package/lib/gateway.js +19 -4
  69. package/lib/get-raw-email.js +25 -107
  70. package/lib/hapi-request-logger.js +107 -0
  71. package/lib/health.js +75 -0
  72. package/lib/imapproxy/imap-core/README.md +6 -5
  73. package/lib/lock-run.js +119 -0
  74. package/lib/logger-consts.js +48 -0
  75. package/lib/logger.js +1 -1
  76. package/lib/lua/z-head-scores.lua +28 -0
  77. package/lib/mcp/tools.js +37 -8
  78. package/lib/network-errors.js +1 -1
  79. package/lib/node-version.js +24 -0
  80. package/lib/notify-attachments.js +36 -0
  81. package/lib/oauth/outlook-mailbox.js +35 -0
  82. package/lib/oauth/state.js +24 -0
  83. package/lib/oauth2-apps.js +631 -656
  84. package/lib/outbox.js +184 -54
  85. package/lib/parse-message.js +3 -3
  86. package/lib/pbkdf2-phc.js +1 -1
  87. package/lib/privileged-settings.js +2 -2
  88. package/lib/queue-browser/definitions.js +11 -0
  89. package/lib/queue-browser/index.js +68 -19
  90. package/lib/queue-job-actions.js +18 -1
  91. package/lib/queue-retention.js +48 -12
  92. package/lib/queue-stats.js +11 -2
  93. package/lib/read-env-value.js +3 -0
  94. package/lib/redis-memory-warnings.js +99 -0
  95. package/lib/redis-reconnect.js +29 -0
  96. package/lib/request-timing.js +23 -0
  97. package/lib/respawn-backoff.js +35 -0
  98. package/lib/rewrite-text-nodes.js +19 -59
  99. package/lib/schemas.js +164 -40
  100. package/lib/settings.js +6 -2
  101. package/lib/smtp-auth.js +19 -1
  102. package/lib/sso.js +1 -1
  103. package/lib/swagger-options.js +1 -1
  104. package/lib/thread-diagnostics.js +63 -0
  105. package/lib/timezones.js +109 -0
  106. package/lib/tls/provision.js +6 -3
  107. package/lib/token-audit-log.js +19 -20
  108. package/lib/token-permission-view.js +7 -6
  109. package/lib/tools.js +48 -51
  110. package/lib/totp.js +2 -5
  111. package/lib/translations.js +1 -2
  112. package/lib/ui-routes/account-routes.js +475 -454
  113. package/lib/ui-routes/account-setup.js +99 -0
  114. package/lib/ui-routes/admin-config-routes.js +152 -100
  115. package/lib/ui-routes/admin-entities-routes.js +93 -21
  116. package/lib/ui-routes/auth-routes.js +90 -38
  117. package/lib/ui-routes/imap-idle-field.js +1 -1
  118. package/lib/ui-routes/internals-routes.js +5 -0
  119. package/lib/ui-routes/oauth-config-routes.js +124 -82
  120. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  121. package/lib/ui-routes/overridable-fields.js +84 -0
  122. package/lib/ui-routes/queue-routes.js +8 -5
  123. package/lib/ui-routes/route-helpers.js +19 -3
  124. package/lib/ui-routes/settings-page.js +6 -0
  125. package/lib/ui-routes/tls-config-routes.js +58 -15
  126. package/lib/utils/back-off.js +82 -0
  127. package/lib/utils/decode-headers.js +3 -12
  128. package/lib/utils/filter-empty.js +20 -0
  129. package/lib/utils/int-setting.js +48 -0
  130. package/lib/utils/murmurhash3.js +66 -0
  131. package/lib/utils/public-suffix.js +122 -0
  132. package/lib/utils/random-id.js +26 -0
  133. package/lib/utils/tracking-settings.js +35 -0
  134. package/lib/utils/version.js +74 -0
  135. package/lib/web-safe-html.js +18 -105
  136. package/lib/webhook-delivery.js +461 -0
  137. package/lib/webhook-failures.js +132 -0
  138. package/lib/webhook-request.js +29 -1
  139. package/lib/webhook-routing.js +56 -0
  140. package/lib/webhook-test.js +88 -0
  141. package/lib/webhooks.js +93 -45
  142. package/lib/worker-rpc-error.js +2 -1
  143. package/package.json +37 -38
  144. package/sbom.json +7902 -1
  145. package/server.js +784 -518
  146. package/static/js/ace/ace.js +1 -1
  147. package/static/licenses.html +225 -1060
  148. package/translations/messages.pot +62 -63
  149. package/views/config/ai.hbs +1 -1
  150. package/views/config/security.hbs +24 -2
  151. package/views/config/service.hbs +47 -0
  152. package/views/config/webhooks.hbs +36 -0
  153. package/views/internals/index.hbs +8 -0
  154. package/views/partials/queue_retention_note.hbs +12 -8
  155. package/views/partials/ui/env-managed-alert.hbs +16 -7
  156. package/views/partials/webhook_form.hbs +1 -1
  157. package/views/suppression-lists/index.hbs +1 -1
  158. package/workers/api.js +840 -611
  159. package/workers/export.js +17 -632
  160. package/workers/imap.js +13 -0
  161. package/workers/smtp.js +9 -11
  162. package/workers/submit.js +1 -1
  163. package/workers/webhooks.js +18 -448
  164. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -366,443 +366,469 @@ function generateCommandHelp(cmdName) {
366
366
  return lines.join('\n');
367
367
  }
368
368
 
369
- function run() {
370
- let cmd = ((argv._ && argv._[0]) || '').toLowerCase();
371
- if (!cmd) {
372
- if (argv.version || argv.v) {
373
- cmd = 'version';
374
- }
369
+ function runEncrypt() {
370
+ process.title = 'emailengine-encrypt';
371
+ // encrypt account passwords
372
+ require('../encrypt');
373
+ }
375
374
 
376
- if (argv.help || argv.h) {
377
- cmd = 'help';
375
+ function runScan() {
376
+ process.title = 'emailengine-scan';
377
+ // Scan Redis keys
378
+ require('../scan');
379
+ }
380
+
381
+ function runPassword() {
382
+ // Update admin password
383
+ let password = argv.password || argv.p || crypto.randomBytes(16).toString('hex');
384
+
385
+ if (!password || typeof password !== 'string' || password.length < 8) {
386
+ console.error('Password must be at least 8 characters');
387
+ return process.exit(1);
388
+ }
389
+
390
+ let updatePassword = async () => {
391
+ let passwordHash = await pbkdf2.hash(password);
392
+
393
+ let authData = await settings.get('authData');
394
+
395
+ authData = authData || {};
396
+ authData.user = authData.user || 'admin';
397
+ authData.password = passwordHash;
398
+ authData.passwordVersion = Date.now();
399
+
400
+ await settings.set('authData', authData);
401
+ await settings.set('totpEnabled', false);
402
+ await settings.set('totpSeed', false);
403
+
404
+ let passkeys = require('../lib/passkeys');
405
+ await passkeys.deleteAllCredentials(authData.user);
406
+
407
+ return { password, passwordHash };
408
+ };
409
+
410
+ updatePassword()
411
+ .then(res => {
412
+ let returnValue = argv.hash || argv.r ? Buffer.from(res.passwordHash).toString('base64url') : res.password;
413
+ process.stdout.write(returnValue);
414
+ // The password is stored, and every existing session is ended by the
415
+ // version bump; the login requirement itself is installed by each API
416
+ // worker at startup, so an instance that was running without a password
417
+ // keeps serving the admin pages without one until it is restarted
418
+ process.stderr.write('\nRestart running EmailEngine instances for the new password to take effect\n');
419
+ return process.exit(0);
420
+ })
421
+ .catch(err => {
422
+ console.error('Failed to process account password');
423
+ console.error(err);
424
+ return process.exit(1);
425
+ });
426
+ }
427
+
428
+ function runHelp() {
429
+ // Show help for specific command or general help
430
+ let helpCmd = ((argv._ && argv._[1]) || '').toLowerCase();
431
+ if (helpCmd) {
432
+ let cmdHelp = generateCommandHelp(helpCmd);
433
+ if (cmdHelp) {
434
+ console.error(cmdHelp);
435
+ } else {
436
+ console.error(`Unknown command: ${helpCmd}`);
437
+ console.error('');
438
+ console.error('Run "emailengine help" to see available commands.');
439
+ process.exit(1);
378
440
  }
441
+ } else {
442
+ console.error(generateHelp());
379
443
  }
444
+ process.exit();
445
+ }
380
446
 
381
- switch (cmd) {
382
- case 'encrypt':
383
- process.title = 'emailengine-encrypt';
384
- // encrypt account passwords
385
- require('../encrypt');
386
- break;
387
-
388
- case 'scan':
389
- process.title = 'emailengine-scan';
390
- // Scan Redis keys
391
- require('../scan');
392
- break;
393
-
394
- case 'password':
395
- {
396
- // Update admin password
397
- let password = argv.password || argv.p || crypto.randomBytes(16).toString('hex');
398
-
399
- if (!password || typeof password !== 'string' || password.length < 8) {
400
- console.error('Password must be at least 8 characters');
401
- return process.exit(1);
402
- }
447
+ function runVersion() {
448
+ // Show version
449
+ console.log(`EmailEngine v${packageData.version} (${packageData.license})`);
450
+ return process.exit();
451
+ }
403
452
 
404
- let updatePassword = async () => {
405
- let passwordHash = await pbkdf2.hash(password);
406
-
407
- let authData = await settings.get('authData');
408
-
409
- authData = authData || {};
410
- authData.user = authData.user || 'admin';
411
- authData.password = passwordHash;
412
- authData.passwordVersion = Date.now();
413
-
414
- await settings.set('authData', authData);
415
- await settings.set('totpEnabled', false);
416
- await settings.set('totpSeed', false);
417
-
418
- let passkeys = require('../lib/passkeys');
419
- await passkeys.deleteAllCredentials(authData.user);
420
-
421
- return { password, passwordHash };
422
- };
423
-
424
- updatePassword()
425
- .then(res => {
426
- let returnValue = argv.hash || argv.r ? Buffer.from(res.passwordHash).toString('base64url') : res.password;
427
- process.stdout.write(returnValue);
428
- // The password is stored, and every existing session is ended by the
429
- // version bump; the login requirement itself is installed by each API
430
- // worker at startup, so an instance that was running without a password
431
- // keeps serving the admin pages without one until it is restarted
432
- process.stderr.write('\nRestart running EmailEngine instances for the new password to take effect\n');
433
- return process.exit(0);
434
- })
435
- .catch(err => {
436
- console.error('Failed to process account password');
437
- console.error(err);
438
- return process.exit(1);
439
- });
440
- }
441
- break;
442
-
443
- case 'help':
444
- {
445
- // Show help for specific command or general help
446
- let helpCmd = ((argv._ && argv._[1]) || '').toLowerCase();
447
- if (helpCmd) {
448
- let cmdHelp = generateCommandHelp(helpCmd);
449
- if (cmdHelp) {
450
- console.error(cmdHelp);
451
- } else {
452
- console.error(`Unknown command: ${helpCmd}`);
453
- console.error('');
454
- console.error('Run "emailengine help" to see available commands.');
455
- process.exit(1);
456
- }
457
- } else {
458
- console.error(generateHelp());
459
- }
460
- process.exit();
453
+ function runLicenseExport() {
454
+ return settings
455
+ .exportLicense()
456
+ .then(license => {
457
+ process.stdout.write(license);
458
+ return process.exit(0);
459
+ })
460
+ .catch(err => {
461
+ console.error('Failed to load license information');
462
+ console.error(err);
463
+ return process.exit(1);
464
+ });
465
+ }
466
+
467
+ function runLicenseImport() {
468
+ return settings
469
+ .importLicense((argv.license || argv.l || '').toString(), checkLicense)
470
+ .then(result => {
471
+ if (!result) {
472
+ console.error('License key was not imported');
473
+ } else {
474
+ console.error('License key was imported');
461
475
  }
462
- break;
463
-
464
- case 'version':
465
- // Show version
466
- console.log(`EmailEngine v${packageData.version} (${packageData.license})`);
467
- return process.exit();
468
-
469
- case 'license':
470
- {
471
- let licenseCmd = ((argv._ && argv._[1]) || '').toLowerCase();
472
- if (licenseCmd === 'export') {
473
- return settings
474
- .exportLicense()
475
- .then(license => {
476
- process.stdout.write(license);
477
- return process.exit(0);
478
- })
479
- .catch(err => {
480
- console.error('Failed to load license information');
481
- console.error(err);
482
- return process.exit(1);
483
- });
484
- }
476
+ return process.exit(0);
477
+ })
478
+ .catch(err => {
479
+ console.error(`Failed to import license information${err.code ? ` [${err.code}]` : ''}`);
480
+ console.error(err);
481
+ return process.exit(1);
482
+ });
483
+ }
485
484
 
486
- if (licenseCmd === 'import') {
487
- return settings
488
- .importLicense((argv.license || argv.l || '').toString(), checkLicense)
489
- .then(result => {
490
- if (!result) {
491
- console.error('License key was not imported');
492
- } else {
493
- console.error('License key was imported');
494
- }
495
- return process.exit(0);
496
- })
497
- .catch(err => {
498
- console.error(`Failed to import license information${err.code ? ` [${err.code}]` : ''}`);
499
- console.error(err);
500
- return process.exit(1);
501
- });
502
- }
485
+ function runLicenseShow() {
486
+ fs.readFile(pathlib.join(__dirname, '..', 'LICENSE_EMAILENGINE.txt'), (err, licenseComm) => {
487
+ if (err) {
488
+ console.error('Failed to load license information');
489
+ console.error(err);
490
+ return process.exit(1);
491
+ }
503
492
 
504
- fs.readFile(pathlib.join(__dirname, '..', 'LICENSE_EMAILENGINE.txt'), (err, licenseComm) => {
505
- if (err) {
506
- console.error('Failed to load license information');
507
- console.error(err);
508
- return process.exit(1);
509
- }
493
+ console.error('EmailEngine License');
494
+ console.error('===================');
510
495
 
511
- console.error('EmailEngine License');
512
- console.error('===================');
496
+ // if only stdout is read, only this line is is seen:
497
+ process.stdout.write(`EmailEngine v${packageData.version}`);
513
498
 
514
- // if only stdout is read, only this line is is seen:
515
- process.stdout.write(`EmailEngine v${packageData.version}`);
499
+ console.error(`\n(c) 2020-${new Date().getFullYear()} Postal Systems`);
500
+ console.error(`${packageData.license}, full text follows`);
501
+ console.error('');
516
502
 
517
- console.error(`\n(c) 2020-${new Date().getFullYear()} Postal Systems`);
518
- console.error(`${packageData.license}, full text follows`);
519
- console.error('');
503
+ console.error('-'.repeat(78));
504
+ console.error('');
520
505
 
521
- console.error('-'.repeat(78));
522
- console.error('');
506
+ console.error(licenseComm.toString().trim());
507
+ console.error('-'.repeat(78));
508
+ console.error('');
523
509
 
524
- console.error(licenseComm.toString().trim());
525
- console.error('-'.repeat(78));
526
- console.error('');
510
+ process.exit();
511
+ });
512
+ }
527
513
 
528
- process.exit();
529
- });
530
- }
531
- break;
532
-
533
- case 'tokens':
534
- {
535
- const tokens = require('../lib/tokens');
536
- let tokensCmd = ((argv._ && argv._[1]) || '').toLowerCase();
537
- switch (tokensCmd) {
538
- case 'issue':
539
- {
540
- const { MCP_SECTIONS, mcpGrantsFor, mcpLevel } = require('../lib/token-permission-view');
541
-
542
- // The two MCP scopes, by the name typed on the command line. A token
543
- // holding one of them always carries the pair list of a named access
544
- // level, exactly as the admin form and the consent prompt mint it: a
545
- // credential issued for the tools of today must not grow to include a
546
- // tool shipped next release. The level is appended to the scope with a
547
- // colon (`--scope mcp-manage:observe`) and is REQUIRED: there is no
548
- // consent prompt here to show what a level allows, and the one thing an
549
- // implicit default must not do is pick the widest one.
550
- const mcpScopes = new Map(Object.entries(MCP_SECTIONS).map(([key, section]) => [section.scope, { key, section }]));
551
-
552
- let allowedScopes = ['*', 'api', 'metrics', 'smtp', 'imap-proxy'].concat([...mcpScopes.keys()]);
553
- let requestedScopes = []
554
- .concat(argv.scope || [])
555
- .concat(argv.s || [])
556
- .map(entry => (entry || '').toString().toLowerCase());
557
-
558
- if (!requestedScopes.length) {
559
- requestedScopes = ['*'];
560
- }
561
-
562
- let scopes = [];
563
- let mcpChoice = {};
564
-
565
- for (let entry of requestedScopes) {
566
- let separator = entry.indexOf(':');
567
- let scope = separator < 0 ? entry : entry.slice(0, separator);
568
- let level = separator < 0 ? null : entry.slice(separator + 1);
569
-
570
- if (!allowedScopes.includes(scope)) {
571
- console.error(`Unknown scope: ${scope}`);
572
- console.error(`Allowed scopes: "${allowedScopes.join('", "')}"`);
573
- process.exit(1);
574
- }
575
-
576
- if (!mcpScopes.has(scope)) {
577
- if (level !== null) {
578
- console.error(`Scope "${scope}" does not take an access level`);
579
- process.exit(1);
580
- }
581
- scopes.push(scope);
582
- continue;
583
- }
584
-
585
- const { key, section } = mcpScopes.get(scope);
586
- // mcpLevel() is the shared vocabulary, and it answers null both for a
587
- // name the section does not have and for `none` - which is what makes
588
- // `--scope mcp:none`, asking for a scope and declining it in the same
589
- // breath, an error here rather than a token that grants nothing
590
- if (!mcpLevel(section, level)) {
591
- const levelNames = section.levels.map(sectionLevel => sectionLevel.value).join('", "');
592
- console.error(
593
- level === null
594
- ? `Scope "${scope}" needs an access level, as "${scope}:<level>"`
595
- : `Unknown ${scope} access level: ${level}`
596
- );
597
- console.error(`Allowed levels: "${levelNames}"`);
598
- process.exit(1);
599
- }
600
- mcpChoice[key] = level;
601
- }
602
-
603
- let permissions;
604
- if (Object.keys(mcpChoice).length) {
605
- // The admin form hides the level editor as soon as a non-MCP scope is
606
- // ticked, because one permissions record covers the whole token and a
607
- // level's pair list would narrow the REST API too. There is no way to
608
- // type a custom record here, so the combination is refused rather
609
- // than silently resolved one way or the other.
610
- if (scopes.length) {
611
- console.error(`An MCP scope cannot be combined with "${scopes.join('", "')}" on the command line`);
612
- console.error('Issue separate tokens, or use POST /v1/tokens to set an explicit permissions record');
613
- process.exit(1);
614
- }
615
- ({ scopes, permissions } = mcpGrantsFor(mcpChoice));
616
- }
617
-
618
- let description = (argv.description || argv.d || '').toString();
619
- if (!description) {
620
- description = `Generated at ${new Date().toISOString()}`;
621
- }
622
- let account = argv.account || argv.a || '';
623
- tokens
624
- .provision({
625
- account,
626
- description,
627
- scopes,
628
- permissions,
629
- nolog: true
630
- })
631
- .then(token => {
632
- process.stdout.write(token);
633
- process.exit();
634
- })
635
- .catch(err => {
636
- console.error(err);
637
- process.exit(1);
638
- });
639
- }
640
- break;
641
-
642
- case 'export':
643
- {
644
- let token = (argv.token || argv.t || '').toString();
645
- tokens
646
- .getRawData(token)
647
- .then(tokenData => {
648
- let encoded = msgpack.encode(tokenData);
649
- process.stdout.write(encoded.toString('base64url'));
650
- process.exit();
651
- })
652
- .catch(err => {
653
- console.error(err);
654
- process.exit(1);
655
- });
656
- }
657
- break;
658
-
659
- case 'import':
660
- {
661
- let rawToken = (argv.token || argv.t || '').toString();
662
- let tokenData;
663
- try {
664
- tokenData = msgpack.decode(Buffer.from(rawToken, 'base64url'));
665
- } catch (err) {
666
- console.error(`Unable to decode token data: ${err.message}`);
667
- return process.exit(1);
668
- }
669
- tokens
670
- .setRawData(tokenData)
671
- .then(result => {
672
- if (!result) {
673
- console.error('Token was not imported');
674
- } else {
675
- console.error('Token was imported');
676
- }
677
- process.exit();
678
- })
679
- .catch(err => {
680
- console.error(err);
681
- process.exit(1);
682
- });
683
- }
684
- break;
685
-
686
- default:
687
- // Nothing else would end the process: the Redis connection opened on load
688
- // kept it running with no output
689
- console.error(tokensCmd ? `Unknown tokens command: ${tokensCmd}` : 'A tokens command is required');
690
- console.error('');
691
- console.error(generateCommandHelp('tokens'));
692
- return process.exit(1);
693
- }
694
- }
695
- break;
514
+ function runLicense() {
515
+ let licenseCmd = ((argv._ && argv._[1]) || '').toLowerCase();
516
+ if (licenseCmd === 'export') {
517
+ return runLicenseExport();
518
+ }
519
+
520
+ if (licenseCmd === 'import') {
521
+ return runLicenseImport();
522
+ }
696
523
 
697
- case 'webhooks':
698
- generateWebhookTable();
524
+ runLicenseShow();
525
+ }
526
+
527
+ // Resolves the `--scope` arguments of `tokens issue` into the scopes and the permissions record the
528
+ // token is minted with, exiting the process on any value that cannot be issued
529
+ function resolveTokenIssueScopes() {
530
+ const { MCP_SECTIONS, mcpGrantsFor, mcpLevel } = require('../lib/token-permission-view');
531
+
532
+ // The two MCP scopes, by the name typed on the command line. A token
533
+ // holding one of them always carries the pair list of a named access
534
+ // level, exactly as the admin form and the consent prompt mint it: a
535
+ // credential issued for the tools of today must not grow to include a
536
+ // tool shipped next release. The level is appended to the scope with a
537
+ // colon (`--scope mcp-manage:observe`) and is REQUIRED: there is no
538
+ // consent prompt here to show what a level allows, and the one thing an
539
+ // implicit default must not do is pick the widest one.
540
+ const mcpScopes = new Map(Object.entries(MCP_SECTIONS).map(([key, section]) => [section.scope, { key, section }]));
541
+
542
+ let allowedScopes = ['*', 'api', 'metrics', 'smtp', 'imap-proxy'].concat([...mcpScopes.keys()]);
543
+ let requestedScopes = []
544
+ .concat(argv.scope || [])
545
+ .concat(argv.s || [])
546
+ .map(entry => (entry || '').toString().toLowerCase());
547
+
548
+ if (!requestedScopes.length) {
549
+ requestedScopes = ['*'];
550
+ }
551
+
552
+ let scopes = [];
553
+ let mcpChoice = {};
554
+
555
+ for (let entry of requestedScopes) {
556
+ let separator = entry.indexOf(':');
557
+ let scope = separator < 0 ? entry : entry.slice(0, separator);
558
+ let level = separator < 0 ? null : entry.slice(separator + 1);
559
+
560
+ if (!allowedScopes.includes(scope)) {
561
+ console.error(`Unknown scope: ${scope}`);
562
+ console.error(`Allowed scopes: "${allowedScopes.join('", "')}"`);
699
563
  process.exit(1);
700
- break;
701
-
702
- case 'export':
703
- {
704
- getSecret()
705
- .then(secret => {
706
- let account = (argv.account || argv.a || '').toString();
707
- let accountObject = new Account({
708
- redis,
709
- account,
710
- secret
711
- });
712
- return accountObject.loadAccountData(account, false);
713
- })
714
- .then(accountData => {
715
- process.stdout.write(JSON.stringify(accountData));
716
- process.exit(0);
717
- })
718
- .catch(err => {
719
- console.error(err);
720
- process.exit(1);
721
- });
564
+ }
565
+
566
+ if (!mcpScopes.has(scope)) {
567
+ if (level !== null) {
568
+ console.error(`Scope "${scope}" does not take an access level`);
569
+ process.exit(1);
722
570
  }
723
- break;
571
+ scopes.push(scope);
572
+ continue;
573
+ }
724
574
 
725
- case 'check-bounce':
726
- {
727
- process.title = 'emailengine-check-bounce';
728
- const { bounceDetect } = require('../lib/bounce-detect');
729
- const bounceClassifier = require('@postalsys/bounce-classifier');
575
+ const { key, section } = mcpScopes.get(scope);
576
+ // mcpLevel() is the shared vocabulary, and it answers null both for a
577
+ // name the section does not have and for `none` - which is what makes
578
+ // `--scope mcp:none`, asking for a scope and declining it in the same
579
+ // breath, an error here rather than a token that grants nothing
580
+ if (!mcpLevel(section, level)) {
581
+ const levelNames = section.levels.map(sectionLevel => sectionLevel.value).join('", "');
582
+ console.error(level === null ? `Scope "${scope}" needs an access level, as "${scope}:<level>"` : `Unknown ${scope} access level: ${level}`);
583
+ console.error(`Allowed levels: "${levelNames}"`);
584
+ process.exit(1);
585
+ }
586
+ mcpChoice[key] = level;
587
+ }
730
588
 
731
- let emlPath = argv._[1] || argv.file || argv.f;
589
+ let permissions;
590
+ if (Object.keys(mcpChoice).length) {
591
+ // The admin form hides the level editor as soon as a non-MCP scope is
592
+ // ticked, because one permissions record covers the whole token and a
593
+ // level's pair list would narrow the REST API too. There is no way to
594
+ // type a custom record here, so the combination is refused rather
595
+ // than silently resolved one way or the other.
596
+ if (scopes.length) {
597
+ console.error(`An MCP scope cannot be combined with "${scopes.join('", "')}" on the command line`);
598
+ console.error('Issue separate tokens, or use POST /v1/tokens to set an explicit permissions record');
599
+ process.exit(1);
600
+ }
601
+ ({ scopes, permissions } = mcpGrantsFor(mcpChoice));
602
+ }
732
603
 
733
- if (!emlPath) {
734
- console.error('Error: EML file path is required');
735
- console.error('Usage: emailengine check-bounce <path-to-eml-file>');
736
- console.error(' emailengine check-bounce --file <path-to-eml-file>');
737
- return process.exit(1);
738
- }
604
+ return { scopes, permissions };
605
+ }
739
606
 
740
- // Resolve the path
741
- emlPath = pathlib.resolve(emlPath);
607
+ function runTokensIssue(tokens) {
608
+ let { scopes, permissions } = resolveTokenIssueScopes();
742
609
 
743
- // Check if file exists
744
- if (!fs.existsSync(emlPath)) {
745
- console.error(`Error: File not found: ${emlPath}`);
746
- return process.exit(1);
747
- }
610
+ let description = (argv.description || argv.d || '').toString();
611
+ if (!description) {
612
+ description = `Generated at ${new Date().toISOString()}`;
613
+ }
614
+ let account = argv.account || argv.a || '';
615
+ tokens
616
+ .provision({
617
+ account,
618
+ description,
619
+ scopes,
620
+ permissions,
621
+ nolog: true
622
+ })
623
+ .then(token => {
624
+ process.stdout.write(token);
625
+ process.exit();
626
+ })
627
+ .catch(err => {
628
+ console.error(err);
629
+ process.exit(1);
630
+ });
631
+ }
748
632
 
749
- const checkBounce = async () => {
750
- // Initialize the bounce classifier
751
- await bounceClassifier.initialize();
752
-
753
- // Read the EML file
754
- const emlStream = fs.createReadStream(emlPath);
755
-
756
- // Detect bounce information
757
- const bounce = await bounceDetect(emlStream);
758
-
759
- // Classify the bounce if we have a response message
760
- if (bounce?.response?.message) {
761
- const classification = await bounceClassifier.classify(bounce.response.message);
762
-
763
- if (classification?.label) {
764
- bounce.response.category = classification.label;
765
- }
766
- if (classification?.action) {
767
- bounce.response.recommendedAction = classification.action;
768
- }
769
- if (classification?.blocklist) {
770
- bounce.response.blocklist = classification.blocklist;
771
- }
772
- if (classification?.retryAfter) {
773
- bounce.response.retryAfter = classification.retryAfter;
774
- }
775
- }
633
+ function runTokensExport(tokens) {
634
+ let token = (argv.token || argv.t || '').toString();
635
+ tokens
636
+ .getRawData(token)
637
+ .then(tokenData => {
638
+ let encoded = msgpack.encode(tokenData);
639
+ process.stdout.write(encoded.toString('base64url'));
640
+ process.exit();
641
+ })
642
+ .catch(err => {
643
+ console.error(err);
644
+ process.exit(1);
645
+ });
646
+ }
776
647
 
777
- return bounce;
778
- };
779
-
780
- checkBounce()
781
- .then(result => {
782
- process.stdout.write(JSON.stringify(result, null, 2));
783
- process.stdout.write('\n');
784
- return process.exit(0);
785
- })
786
- .catch(err => {
787
- console.error('Failed to analyze bounce email');
788
- console.error(err);
789
- return process.exit(1);
790
- });
648
+ function runTokensImport(tokens) {
649
+ let rawToken = (argv.token || argv.t || '').toString();
650
+ let tokenData;
651
+ try {
652
+ tokenData = msgpack.decode(Buffer.from(rawToken, 'base64url'));
653
+ } catch (err) {
654
+ console.error(`Unable to decode token data: ${err.message}`);
655
+ return process.exit(1);
656
+ }
657
+ tokens
658
+ .setRawData(tokenData)
659
+ .then(result => {
660
+ if (!result) {
661
+ console.error('Token was not imported');
662
+ } else {
663
+ console.error('Token was imported');
791
664
  }
792
- break;
665
+ process.exit();
666
+ })
667
+ .catch(err => {
668
+ console.error(err);
669
+ process.exit(1);
670
+ });
671
+ }
793
672
 
794
- case '':
795
- // run normally
796
- require('../server');
797
- break;
673
+ const TOKENS_COMMANDS = new Map([
674
+ ['issue', runTokensIssue],
675
+ ['export', runTokensExport],
676
+ ['import', runTokensImport]
677
+ ]);
798
678
 
799
- default:
800
- // A mistyped command used to start the server instead
801
- console.error(`Unknown command: ${cmd}`);
802
- console.error('');
803
- console.error('Run "emailengine help" to see available commands.');
679
+ function runTokens() {
680
+ const tokens = require('../lib/tokens');
681
+ let tokensCmd = ((argv._ && argv._[1]) || '').toLowerCase();
682
+
683
+ let handler = TOKENS_COMMANDS.get(tokensCmd);
684
+ if (handler) {
685
+ return handler(tokens);
686
+ }
687
+
688
+ // Nothing else would end the process: the Redis connection opened on load
689
+ // kept it running with no output
690
+ console.error(tokensCmd ? `Unknown tokens command: ${tokensCmd}` : 'A tokens command is required');
691
+ console.error('');
692
+ console.error(generateCommandHelp('tokens'));
693
+ return process.exit(1);
694
+ }
695
+
696
+ function runWebhooks() {
697
+ generateWebhookTable();
698
+ process.exit(1);
699
+ }
700
+
701
+ function runExport() {
702
+ getSecret()
703
+ .then(secret => {
704
+ let account = (argv.account || argv.a || '').toString();
705
+ let accountObject = new Account({
706
+ redis,
707
+ account,
708
+ secret
709
+ });
710
+ return accountObject.loadAccountData(account, false);
711
+ })
712
+ .then(accountData => {
713
+ process.stdout.write(JSON.stringify(accountData));
714
+ process.exit(0);
715
+ })
716
+ .catch(err => {
717
+ console.error(err);
718
+ process.exit(1);
719
+ });
720
+ }
721
+
722
+ function runCheckBounce() {
723
+ process.title = 'emailengine-check-bounce';
724
+ const { bounceDetect } = require('../lib/bounce-detect');
725
+ const bounceClassifier = require('@postalsys/bounce-classifier');
726
+
727
+ let emlPath = argv._[1] || argv.file || argv.f;
728
+
729
+ if (!emlPath) {
730
+ console.error('Error: EML file path is required');
731
+ console.error('Usage: emailengine check-bounce <path-to-eml-file>');
732
+ console.error(' emailengine check-bounce --file <path-to-eml-file>');
733
+ return process.exit(1);
734
+ }
735
+
736
+ // Resolve the path
737
+ emlPath = pathlib.resolve(emlPath);
738
+
739
+ // Check if file exists
740
+ if (!fs.existsSync(emlPath)) {
741
+ console.error(`Error: File not found: ${emlPath}`);
742
+ return process.exit(1);
743
+ }
744
+
745
+ const checkBounce = async () => {
746
+ // Initialize the bounce classifier
747
+ await bounceClassifier.initialize();
748
+
749
+ // Read the EML file
750
+ const emlStream = fs.createReadStream(emlPath);
751
+
752
+ // Detect bounce information
753
+ const bounce = await bounceDetect(emlStream);
754
+
755
+ // Classify the bounce if we have a response message
756
+ if (bounce?.response?.message) {
757
+ const classification = await bounceClassifier.classify(bounce.response.message);
758
+
759
+ if (classification?.label) {
760
+ bounce.response.category = classification.label;
761
+ }
762
+ if (classification?.action) {
763
+ bounce.response.recommendedAction = classification.action;
764
+ }
765
+ if (classification?.blocklist) {
766
+ bounce.response.blocklist = classification.blocklist;
767
+ }
768
+ if (classification?.retryAfter) {
769
+ bounce.response.retryAfter = classification.retryAfter;
770
+ }
771
+ }
772
+
773
+ return bounce;
774
+ };
775
+
776
+ checkBounce()
777
+ .then(result => {
778
+ process.stdout.write(JSON.stringify(result, null, 2));
779
+ process.stdout.write('\n');
780
+ return process.exit(0);
781
+ })
782
+ .catch(err => {
783
+ console.error('Failed to analyze bounce email');
784
+ console.error(err);
804
785
  return process.exit(1);
786
+ });
787
+ }
788
+
789
+ function runServer() {
790
+ // run normally
791
+ require('../server');
792
+ }
793
+
794
+ // A Map rather than an object literal, so a command typed as `constructor` or `__proto__` is an
795
+ // unknown command and not an inherited property
796
+ const COMMAND_HANDLERS = new Map([
797
+ ['encrypt', runEncrypt],
798
+ ['scan', runScan],
799
+ ['password', runPassword],
800
+ ['help', runHelp],
801
+ ['version', runVersion],
802
+ ['license', runLicense],
803
+ ['tokens', runTokens],
804
+ ['webhooks', runWebhooks],
805
+ ['export', runExport],
806
+ ['check-bounce', runCheckBounce],
807
+ ['', runServer]
808
+ ]);
809
+
810
+ function run() {
811
+ let cmd = ((argv._ && argv._[0]) || '').toLowerCase();
812
+ if (!cmd) {
813
+ if (argv.version || argv.v) {
814
+ cmd = 'version';
815
+ }
816
+
817
+ if (argv.help || argv.h) {
818
+ cmd = 'help';
819
+ }
805
820
  }
821
+
822
+ let handler = COMMAND_HANDLERS.get(cmd);
823
+ if (handler) {
824
+ return handler();
825
+ }
826
+
827
+ // A mistyped command used to start the server instead
828
+ console.error(`Unknown command: ${cmd}`);
829
+ console.error('');
830
+ console.error('Run "emailengine help" to see available commands.');
831
+ return process.exit(1);
806
832
  }
807
833
 
808
834
  run();