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