emailengine-app 2.85.0 → 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 (128) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +74 -0
  4. package/Dockerfile +14 -1
  5. package/ENVIRONMENT.md +139 -0
  6. package/README.md +1 -1
  7. package/config/default.toml +2 -0
  8. package/copy-static-files.sh +4 -2
  9. package/data/google-crawlers.json +1 -1
  10. package/data/public_suffix_list.dat +4 -3
  11. package/lib/account-assignment.js +19 -0
  12. package/lib/account.js +194 -165
  13. package/lib/api-error-codes.js +49 -0
  14. package/lib/api-reference/model.js +6 -1
  15. package/lib/api-routes/account-routes.js +78 -26
  16. package/lib/api-routes/blocklist-routes.js +68 -2
  17. package/lib/api-routes/delivery-test-routes.js +1 -1
  18. package/lib/api-routes/gateway-routes.js +82 -10
  19. package/lib/api-routes/index.js +4 -0
  20. package/lib/api-routes/license-routes.js +2 -2
  21. package/lib/api-routes/mailbox-routes.js +3 -3
  22. package/lib/api-routes/message-routes.js +15 -7
  23. package/lib/api-routes/oauth2-app-routes.js +15 -8
  24. package/lib/api-routes/outbox-routes.js +77 -66
  25. package/lib/api-routes/permission-map.js +55 -6
  26. package/lib/api-routes/scoped-routes.js +74 -0
  27. package/lib/api-routes/settings-routes.js +11 -4
  28. package/lib/api-routes/stats-routes.js +5 -1
  29. package/lib/api-routes/submit-routes.js +4 -3
  30. package/lib/api-routes/template-routes.js +7 -6
  31. package/lib/api-routes/token-routes.js +11 -5
  32. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  33. package/lib/api-routes/webhook-route-routes.js +119 -4
  34. package/lib/calendar-event.js +81 -1
  35. package/lib/consts.js +38 -46
  36. package/lib/db.js +14 -6
  37. package/lib/delivery-error.js +6 -0
  38. package/lib/deprecations.js +270 -0
  39. package/lib/email-client/base-client.js +130 -156
  40. package/lib/email-client/fallback-poll.js +62 -0
  41. package/lib/email-client/gmail-client.js +51 -11
  42. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  43. package/lib/email-client/imap/adaptive-idle.js +278 -0
  44. package/lib/email-client/imap/connection-errors.js +14 -1
  45. package/lib/email-client/imap/idle-settings.js +31 -5
  46. package/lib/email-client/imap/listing-diff.js +37 -0
  47. package/lib/email-client/imap/mailbox.js +372 -226
  48. package/lib/email-client/imap/subconnection.js +7 -29
  49. package/lib/email-client/imap/sync-operations.js +220 -127
  50. package/lib/email-client/imap-client.js +227 -163
  51. package/lib/email-client/message-builder.js +14 -79
  52. package/lib/email-client/outlook-client.js +372 -338
  53. package/lib/email-client/smtp-pool-manager.js +16 -13
  54. package/lib/email-client/sync-state-fields.js +19 -0
  55. package/lib/encrypt.js +157 -41
  56. package/lib/enum-descriptions.js +3 -1
  57. package/lib/env-setting-overrides.js +288 -0
  58. package/lib/export-worker.js +751 -0
  59. package/lib/export.js +64 -15
  60. package/lib/gateway.js +17 -1
  61. package/lib/get-raw-email.js +25 -107
  62. package/lib/health.js +75 -0
  63. package/lib/lock-run.js +119 -0
  64. package/lib/logger-consts.js +48 -0
  65. package/lib/logger.js +1 -1
  66. package/lib/lua/z-head-scores.lua +28 -0
  67. package/lib/network-errors.js +1 -1
  68. package/lib/node-version.js +24 -0
  69. package/lib/notify-attachments.js +20 -1
  70. package/lib/oauth2-apps.js +630 -655
  71. package/lib/outbox.js +184 -54
  72. package/lib/parse-message.js +3 -3
  73. package/lib/privileged-settings.js +2 -2
  74. package/lib/queue-browser/definitions.js +11 -0
  75. package/lib/queue-browser/index.js +68 -19
  76. package/lib/queue-job-actions.js +18 -1
  77. package/lib/queue-retention.js +48 -12
  78. package/lib/queue-stats.js +11 -2
  79. package/lib/read-env-value.js +3 -0
  80. package/lib/redis-memory-warnings.js +99 -0
  81. package/lib/redis-reconnect.js +29 -0
  82. package/lib/request-timing.js +23 -0
  83. package/lib/respawn-backoff.js +35 -0
  84. package/lib/rewrite-text-nodes.js +19 -59
  85. package/lib/schemas.js +163 -39
  86. package/lib/settings.js +6 -2
  87. package/lib/smtp-auth.js +19 -1
  88. package/lib/thread-diagnostics.js +18 -1
  89. package/lib/tls/provision.js +6 -3
  90. package/lib/token-audit-log.js +19 -20
  91. package/lib/token-permission-view.js +4 -3
  92. package/lib/tools.js +8 -41
  93. package/lib/ui-routes/admin-config-routes.js +64 -90
  94. package/lib/ui-routes/admin-entities-routes.js +2 -14
  95. package/lib/ui-routes/imap-idle-field.js +1 -1
  96. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  97. package/lib/ui-routes/overridable-fields.js +84 -0
  98. package/lib/ui-routes/queue-routes.js +8 -5
  99. package/lib/ui-routes/settings-page.js +6 -0
  100. package/lib/utils/decode-headers.js +3 -12
  101. package/lib/utils/filter-empty.js +20 -0
  102. package/lib/utils/int-setting.js +48 -0
  103. package/lib/utils/tracking-settings.js +35 -0
  104. package/lib/web-safe-html.js +18 -105
  105. package/lib/webhook-delivery.js +461 -0
  106. package/lib/webhook-failures.js +132 -0
  107. package/lib/webhook-request.js +29 -1
  108. package/lib/webhook-routing.js +30 -1
  109. package/lib/webhook-test.js +88 -0
  110. package/lib/webhooks.js +54 -41
  111. package/lib/worker-rpc-error.js +2 -1
  112. package/package.json +21 -20
  113. package/sbom.json +304 -382
  114. package/server.js +149 -76
  115. package/static/js/ace/ace.js +1 -1
  116. package/static/licenses.html +21 -31
  117. package/translations/messages.pot +26 -26
  118. package/views/config/security.hbs +22 -0
  119. package/views/config/service.hbs +44 -0
  120. package/views/config/webhooks.hbs +36 -0
  121. package/views/partials/queue_retention_note.hbs +12 -8
  122. package/views/partials/ui/env-managed-alert.hbs +16 -7
  123. package/workers/api.js +102 -28
  124. package/workers/export.js +16 -631
  125. package/workers/imap.js +13 -0
  126. package/workers/smtp.js +9 -11
  127. package/workers/webhooks.js +18 -432
  128. package/lib/email-client/outlook-fallback-poll.js +0 -30
package/workers/api.js CHANGED
@@ -89,6 +89,7 @@ const { routeGrant, perRequestSurfaceAdmits, sessionTokenAdmits } = require('../
89
89
  const { mcpOptions } = require('../lib/api-routes/route-metadata');
90
90
 
91
91
  const { redis } = require('../lib/db');
92
+ const { createHealthChecks } = require('../lib/health');
92
93
  const { Account } = require('../lib/account');
93
94
  const settings = require('../lib/settings');
94
95
 
@@ -125,6 +126,9 @@ const {
125
126
 
126
127
  const registerApiRoutes = require('../lib/api-routes');
127
128
  const { securityHeadersExt, attachSecurityContext, isAdminPath, isMachineRoute, isSecureOrigin, CSP_MODES } = require('../lib/security-headers');
129
+ const { deprecationExt } = require('../lib/deprecations');
130
+ const { errorCodeExt } = require('../lib/api-error-codes');
131
+ const { apiCallDuration } = require('../lib/request-timing');
128
132
  const { registerHandlebarsHelpers } = require('../lib/handlebars-helpers');
129
133
 
130
134
  const {
@@ -237,6 +241,9 @@ const ADMIN_ACCESS_ADDRESSES = readEnvList('EENGINE_ADMIN_ACCESS_ADDRESSES');
237
241
  // the API proxy setting is on, which is the historical behavior; see resolveClientIp().
238
242
  const API_PROXY_ADDRESSES = readEnvList('EENGINE_API_PROXY_ADDRESSES');
239
243
 
244
+ // How long a shutdown waits for requests in flight, just below the main thread's WORKER_DRAIN_TIMEOUT
245
+ const API_DRAIN_TIMEOUT = 6000;
246
+
240
247
  const IMAP_WORKER_COUNT = getWorkerCount(readEnvValue('EENGINE_WORKERS') || (config.workers && config.workers.imap)) || 4;
241
248
 
242
249
  // Max POST body size for message uploads
@@ -391,12 +398,32 @@ async function onCommand(command) {
391
398
  // reconciler is a singleton but the HTTPS listeners are not, and a sibling worker that
392
399
  // kept its old context would go on serving the certificate that was just replaced.
393
400
  return refreshApiTls ? await refreshApiTls() : { updated: false };
401
+ case 'close':
402
+ return await drainApiServer();
394
403
  default:
395
404
  logger.debug({ msg: 'Unhandled command', command });
396
405
  return 999;
397
406
  }
398
407
  }
399
408
 
409
+ /**
410
+ * Stops taking new connections and waits for the requests in flight, so a shutdown no longer cuts
411
+ * them. Readiness turns 503 first, which tells a load balancer to stop sending traffic here. The
412
+ * main thread bounds the whole wait with its own drain timeout, this one is just below it.
413
+ */
414
+ async function drainApiServer() {
415
+ apiDraining = true;
416
+ if (!sessionAuthServer) {
417
+ return true;
418
+ }
419
+ try {
420
+ await sessionAuthServer.stop({ timeout: API_DRAIN_TIMEOUT });
421
+ } catch (err) {
422
+ logger.warn({ msg: 'Failed to stop the API server cleanly', err });
423
+ }
424
+ return true;
425
+ }
426
+
400
427
  function publishChangeEvent(data) {
401
428
  // Nothing to do (and no reason to compute the badge label) when no SSE client is
402
429
  // subscribed - the common case whenever no admin browser has the dashboard open.
@@ -430,7 +457,8 @@ function publishChangeEvent(data) {
430
457
 
431
458
  // The Hapi server, published by init() once the session strategy is registered and the boot-time
432
459
  // default has been decided, so the authData branch of the settings dispatcher below cannot set a
433
- // strategy that does not exist yet or race the boot-time server.auth.default() call
460
+ // strategy that does not exist yet or race the boot-time server.auth.default() call. Also what the
461
+ // shutdown drain stops
434
462
  let sessionAuthServer = null;
435
463
 
436
464
  // Installs a renewed certificate on this worker's own HTTPS listener. Published by init() when the
@@ -1586,11 +1614,19 @@ function registerRequestEvents(server) {
1586
1614
  // only log API calls
1587
1615
  return;
1588
1616
  }
1589
- metrics(logger, 'apiCall', 'inc', {
1590
- method: request.method,
1591
- route: request.route.path,
1592
- statusCode: request.response && request.response.statusCode
1593
- });
1617
+ // One message per request: the latency rides on the call counter's message and the main
1618
+ // thread observes it there, rather than costing a second postMessage on every request
1619
+ try {
1620
+ parentPort.postMessage({
1621
+ cmd: 'metrics',
1622
+ key: 'apiCall',
1623
+ method: 'inc',
1624
+ args: [{ method: request.method, route: request.route.path, statusCode: request.response && request.response.statusCode }],
1625
+ duration: apiCallDuration(request.info)
1626
+ });
1627
+ } catch (err) {
1628
+ logger.error({ msg: 'Failed to post metrics to parent', err });
1629
+ }
1594
1630
  });
1595
1631
  }
1596
1632
 
@@ -1771,32 +1807,64 @@ function registerStaticFilesRoute(server) {
1771
1807
  });
1772
1808
  }
1773
1809
 
1810
+ // Set by the close command: readiness answers 503 from then on while Hapi drains the requests in flight
1811
+ let apiDraining = false;
1812
+
1813
+ const healthChecks = createHealthChecks({
1814
+ call,
1815
+ redis,
1816
+ prefix: REDIS_PREFIX,
1817
+ expectedImapWorkers: IMAP_WORKER_COUNT,
1818
+ isDraining: () => apiDraining
1819
+ });
1820
+
1821
+ /**
1822
+ * Runs a readiness check and turns its failure into a 503 carrying a `code`
1823
+ * @param {Object} request - Hapi request
1824
+ * @returns {Promise<Object>} The check result
1825
+ */
1826
+ async function answerReadiness(request) {
1827
+ // Same rule as the license lookup: a header value the timer would mangle is ignored
1828
+ const { error: timeoutError, value: timeout } = headerTimeoutSchema.validate(request.headers['x-ee-timeout']);
1829
+ try {
1830
+ return await healthChecks.ready(timeoutError ? undefined : timeout);
1831
+ } catch (err) {
1832
+ if (err.statusCode !== 503) {
1833
+ throw err;
1834
+ }
1835
+ const error = Boom.boomify(err, { statusCode: err.statusCode });
1836
+ error.output.payload.code = err.code;
1837
+ throw error;
1838
+ }
1839
+ }
1840
+
1774
1841
  function registerHealthRoute(server) {
1842
+ const options = {
1843
+ auth: false,
1844
+ tags: ['static', 'health']
1845
+ };
1846
+
1847
+ // Kept with its historical meaning (everything needed to serve traffic), for the probes and
1848
+ // smoke tests already pointed at it
1775
1849
  server.route({
1776
1850
  method: 'GET',
1777
1851
  path: '/health',
1778
- async handler(request) {
1779
- const imapWorkerCount = await call({ cmd: 'imapWorkerCount', timeout: request.headers['x-ee-timeout'] });
1780
- if (imapWorkerCount < IMAP_WORKER_COUNT) {
1781
- let error = Boom.boomify(new Error('Not all IMAP workers available'), { statusCode: 500 });
1782
- throw error;
1783
- }
1852
+ handler: answerReadiness,
1853
+ options: Object.assign({ description: 'Health check' }, options)
1854
+ });
1784
1855
 
1785
- let checkKey = `${REDIS_PREFIX}test:${Date.now()}`;
1786
- let expected = crypto.randomBytes(8).toString('hex');
1787
- let res = await redis.multi().set(checkKey, expected).get(checkKey).del(checkKey).exec();
1788
- if (!(res[1] && res[1][1] === expected && res[2] && res[2][1] === 1)) {
1789
- let error = Boom.boomify(new Error('Database check failed'), { statusCode: 500 });
1790
- throw error;
1791
- }
1856
+ server.route({
1857
+ method: 'GET',
1858
+ path: '/health/ready',
1859
+ handler: answerReadiness,
1860
+ options: Object.assign({ description: 'Readiness check' }, options)
1861
+ });
1792
1862
 
1793
- return { success: true };
1794
- },
1795
- options: {
1796
- description: 'Health check',
1797
- auth: false,
1798
- tags: ['static', 'health']
1799
- }
1863
+ server.route({
1864
+ method: 'GET',
1865
+ path: '/health/live',
1866
+ handler: () => healthChecks.live(),
1867
+ options: Object.assign({ description: 'Liveness check' }, options)
1800
1868
  });
1801
1869
  }
1802
1870
 
@@ -3296,8 +3364,8 @@ function registerResponseExtensions(server) {
3296
3364
  const wantsJsonError = routeTags.includes('api') || routeTags.includes('external');
3297
3365
 
3298
3366
  if (request.errorInfo && wantsJsonError) {
3299
- // JSON response for API requests
3300
-
3367
+ // JSON response for API requests. A 404 thrown without a code already got NotFound
3368
+ // from errorCodeExt(), registered ahead of this handler
3301
3369
  let res = h.response(request.errorInfo);
3302
3370
  if (error.output.headers) {
3303
3371
  for (let key of Object.keys(error.output.headers)) {
@@ -3322,11 +3390,17 @@ function registerResponseExtensions(server) {
3322
3390
  .code(error.output.statusCode);
3323
3391
  };
3324
3392
 
3393
+ // First: fills in the default code of an error body before preResponse copies it
3394
+ server.ext('onPreResponse', errorCodeExt);
3325
3395
  server.ext('onPreResponse', preResponse);
3326
3396
 
3327
3397
  // After preResponse on purpose: it replaces an error response with the rendered error page
3328
3398
  // or a JSON body, and the headers have to land on whatever is actually sent
3329
3399
  server.ext('onPreResponse', securityHeadersExt({ cspMode: CSP_MODE }));
3400
+
3401
+ // Deprecation, Sunset and Link on the routes that declare plugins.deprecation, also after
3402
+ // preResponse for the same reason
3403
+ server.ext('onPreResponse', deprecationExt({ logger }));
3330
3404
  }
3331
3405
 
3332
3406
  function registerTotpExtension(server) {