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/lib/schemas.js CHANGED
@@ -33,8 +33,27 @@ function formBoolean() {
33
33
  }
34
34
  const config = require('@zone-eu/wild-config');
35
35
  const { getByteSize, readEnvValue } = require('./tools');
36
- const { COLLAPSE_CLASS, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
36
+ const {
37
+ COLLAPSE_CLASS,
38
+ MAX_ACCOUNT_ID_LENGTH,
39
+ DEFAULT_WEBHOOK_ATTEMPTS,
40
+ MAX_WEBHOOK_ATTEMPTS,
41
+ DEFAULT_WEBHOOK_RETRY_DELAY,
42
+ MIN_WEBHOOK_RETRY_DELAY,
43
+ MAX_WEBHOOK_RETRY_DELAY,
44
+ TOKEN_LOG_ENTRIES_DEFAULT,
45
+ TOKEN_LOG_AGE_DEFAULT,
46
+ IMAP_MAX_IDLE_TIME_MIN,
47
+ IMAP_MAX_IDLE_TIME_MAX
48
+ } = require('./consts');
49
+ const {
50
+ FAILED_JOB_RETENTION_AGE_DEFAULT,
51
+ FAILED_JOB_RETENTION_COUNT_DEFAULT,
52
+ DEFAULT_FAILED_CONTENT_RETENTION_COUNT,
53
+ DEFAULT_FAILED_CONTENT_RETENTION_SIZE
54
+ } = require('./queue-retention');
37
55
  const { PROVIDER_ID_SEGMENT } = require('./utils/provider-id');
56
+ const { deprecated } = require('./deprecations');
38
57
  const { locales } = require('./translations');
39
58
  const { OAUTH_PROVIDERS } = require('./oauth2-apps');
40
59
  const { ACCOUNT_STATES } = require('./account/account-state');
@@ -63,11 +82,6 @@ const externalAccountCustomValidator = (value, helpers) => {
63
82
 
64
83
  const RESYNC_DELAY = 15 * 60;
65
84
 
66
- // Bounds for the per-account IDLE restart interval, in milliseconds. Anything shorter than the
67
- // floor is polling rather than idling, and the RFC 3501 autologout timer is 30 minutes
68
- const IMAP_MAX_IDLE_TIME_MIN = 10 * 1000;
69
- const IMAP_MAX_IDLE_TIME_MAX = 30 * 60 * 1000;
70
-
71
85
  config.api = config.api || {
72
86
  port: 3000,
73
87
  host: '127.0.0.1',
@@ -175,6 +189,28 @@ const settingsSchema = {
175
189
  )
176
190
  .label('WebhooksCustomHeaders'),
177
191
 
192
+ webhooksDeliveryAttempts: Joi.number()
193
+ .integer()
194
+ .empty('')
195
+ .min(1)
196
+ .max(MAX_WEBHOOK_ATTEMPTS)
197
+ .allow(null)
198
+ .example(DEFAULT_WEBHOOK_ATTEMPTS)
199
+ .description(
200
+ `How many attempts a webhook delivery gets, including the first, before it is given up on. Applies to events queued after the change. Default ${DEFAULT_WEBHOOK_ATTEMPTS}`
201
+ ),
202
+
203
+ webhooksRetryDelay: Joi.number()
204
+ .integer()
205
+ .empty('')
206
+ .min(MIN_WEBHOOK_RETRY_DELAY)
207
+ .max(MAX_WEBHOOK_RETRY_DELAY)
208
+ .allow(null)
209
+ .example(DEFAULT_WEBHOOK_RETRY_DELAY)
210
+ .description(
211
+ `Delay in milliseconds before the first retry of a failed webhook delivery. It doubles with every attempt after that. Applies to events queued after the change. Default ${DEFAULT_WEBHOOK_RETRY_DELAY}`
212
+ ),
213
+
178
214
  notifyHeaders: Joi.array()
179
215
  .items(Joi.string().max(256).example('List-ID').label('NotifyHeaderEntry'))
180
216
  .description('Email headers to include in webhook payloads for additional context')
@@ -198,9 +234,7 @@ const settingsSchema = {
198
234
 
199
235
  /* ────────────── Tracking ────────────── */
200
236
 
201
- trackSentMessages: formBoolean()
202
- .description('Enable tracking features for outgoing messages (deprecated - use trackClicks and trackOpens instead)')
203
- .meta({ swaggerHidden: true }),
237
+ trackSentMessages: deprecated(formBoolean(), 'trackSentMessages'),
204
238
 
205
239
  trackClicks: formBoolean().description('Rewrite links in outgoing HTML emails to track click-through rates'),
206
240
 
@@ -231,7 +265,7 @@ const settingsSchema = {
231
265
 
232
266
  // The separate risk assessment call left in 2023. The key is still accepted and dropped so a
233
267
  // client that sends it keeps working
234
- generateRiskAssessment: Joi.any().strip().description('Deprecated - This feature has been removed').meta({ swaggerHidden: true }),
268
+ generateRiskAssessment: deprecated(Joi.any().strip(), 'generateRiskAssessment'),
235
269
 
236
270
  openAiAPIKey: Joi.string().allow('').example('sk-…').description('Your OpenAI API key for AI features').label('OpenAiAPIKey'),
237
271
  openAiModel: Joi.string()
@@ -294,7 +328,7 @@ const settingsSchema = {
294
328
  // Embeddings generation left with the Document Store in 2.82.0. The key is still accepted and
295
329
  // dropped so a client that sends it keeps working; storing it would only bump the AI settings
296
330
  // version for a value nothing reads
297
- openAiGenerateEmbeddings: Joi.any().strip().description('Deprecated - embeddings generation has been removed').meta({ swaggerHidden: true }),
331
+ openAiGenerateEmbeddings: deprecated(Joi.any().strip(), 'openAiGenerateEmbeddings'),
298
332
 
299
333
  /* ────────────── Webhook Filters ────────────── */
300
334
 
@@ -323,6 +357,27 @@ const settingsSchema = {
323
357
  'Record which requests each access token makes, readable at GET /v1/tokens/{token}/log. Disabled by default, and entries only exist from the point it is enabled'
324
358
  ),
325
359
 
360
+ tokenLogEntries: Joi.number()
361
+ .integer()
362
+ .empty('')
363
+ .min(1)
364
+ .max(1000000)
365
+ .allow(null)
366
+ .example(TOKEN_LOG_ENTRIES_DEFAULT)
367
+ .description(
368
+ `Requests retained per access token in the audit log (default ${TOKEN_LOG_ENTRIES_DEFAULT}). A full log of typical entries is roughly 170KB of Redis per token. EENGINE_TOKEN_LOG_ENTRIES overrides this setting when set; null clears it`
369
+ ),
370
+
371
+ tokenLogAge: Joi.number()
372
+ .integer()
373
+ .empty('')
374
+ .min(1)
375
+ .allow(null)
376
+ .example(TOKEN_LOG_AGE_DEFAULT)
377
+ .description(
378
+ `How long a token's audit log survives its last use, in seconds (default ${TOKEN_LOG_AGE_DEFAULT}, 7 days). EENGINE_TOKEN_LOG_AGE overrides this setting when set; null clears it`
379
+ ),
380
+
326
381
  /* ────────────── Proxy ────────────── */
327
382
 
328
383
  proxyEnabled: formBoolean().description(
@@ -361,6 +416,11 @@ const settingsSchema = {
361
416
  notifyWebSafeHtml: formBoolean().description(
362
417
  'Sanitize HTML content to remove potentially dangerous elements before including in webhooks, and fold quoted thread history into a collapsed block'
363
418
  ),
419
+ disableThreadCollapse: formBoolean()
420
+ .allow(null)
421
+ .description(
422
+ 'Stop web-safe HTML (in webhooks and in message responses that ask for it) from folding quoted thread history into a collapsed block. EENGINE_DISABLE_THREAD_COLLAPSE overrides this setting when set; null clears it'
423
+ ),
364
424
  notifyTextSize: Joi.number().integer().min(0).example(1048576).description('Maximum size (in bytes) of text content to include in webhook payloads'),
365
425
  notifyAttachments: formBoolean().description('Include attachment data in webhook payloads'),
366
426
  notifyAttachmentSize: Joi.number().integer().min(0).example(5242880).description('Maximum size (in bytes) per attachment to include in webhook payloads'),
@@ -385,7 +445,7 @@ const settingsSchema = {
385
445
  // The one Document Store setting still read after the removal: while it is on, the admin UI
386
446
  // and the startup log say where the feature went. Kept in the schema so an API-only
387
447
  // deployment can switch the notice off through POST /v1/settings
388
- documentStoreEnabled: formBoolean().description('Deprecated - Document Store feature has been removed').meta({ swaggerHidden: true }),
448
+ documentStoreEnabled: deprecated(formBoolean(), 'documentStoreEnabled'),
389
449
 
390
450
  /* ────────────── Logging ────────────── */
391
451
 
@@ -516,6 +576,46 @@ const settingsSchema = {
516
576
 
517
577
  queueKeep: Joi.number().integer().empty('').min(0).example(50).description('Number of completed and failed queue entries to retain for debugging'),
518
578
 
579
+ queueKeepFailed: Joi.number()
580
+ .integer()
581
+ .empty('')
582
+ .min(1)
583
+ .allow(null)
584
+ .example(FAILED_JOB_RETENTION_COUNT_DEFAULT)
585
+ .description(
586
+ `Failed queue entries retained per queue, at least (default ${FAILED_JOB_RETENTION_COUNT_DEFAULT}); a higher queueKeep raises it. EENGINE_QUEUE_KEEP_FAILED overrides this setting when set; null clears it`
587
+ ),
588
+
589
+ queueKeepFailedAge: Joi.number()
590
+ .integer()
591
+ .empty('')
592
+ .min(1)
593
+ .allow(null)
594
+ .example(FAILED_JOB_RETENTION_AGE_DEFAULT)
595
+ .description(
596
+ `How long failed queue entries are retained, in seconds (default ${FAILED_JOB_RETENTION_AGE_DEFAULT}, 7 days). EENGINE_QUEUE_KEEP_FAILED_AGE overrides this setting when set; null clears it`
597
+ ),
598
+
599
+ queueKeepFailedContent: Joi.number()
600
+ .integer()
601
+ .empty('')
602
+ .min(0)
603
+ .allow(null)
604
+ .example(DEFAULT_FAILED_CONTENT_RETENTION_COUNT)
605
+ .description(
606
+ `How many of the most recent failed messages keep their content so they can be retried (default ${DEFAULT_FAILED_CONTENT_RETENTION_COUNT}, 0 keeps none). EENGINE_QUEUE_KEEP_FAILED_CONTENT overrides this setting when set; null clears it`
607
+ ),
608
+
609
+ queueKeepFailedContentSize: Joi.number()
610
+ .integer()
611
+ .empty('')
612
+ .min(0)
613
+ .allow(null)
614
+ .example(DEFAULT_FAILED_CONTENT_RETENTION_SIZE)
615
+ .description(
616
+ `Total size of the retained failed-message content, in bytes (default ${DEFAULT_FAILED_CONTENT_RETENTION_SIZE}, 100MB, 0 keeps none). EENGINE_QUEUE_KEEP_FAILED_CONTENT_SIZE overrides this setting when set; null clears it`
617
+ ),
618
+
519
619
  deliveryAttempts: Joi.number()
520
620
  .integer()
521
621
  .empty('')
@@ -674,7 +774,9 @@ const isHiddenSetting = key => !!settingsSchema[key] && (settingsSchema[key].des
674
774
  // every removed feature whose setting is still accepted (documentStoreEnabled and two others).
675
775
  const settingsQuerySchema = Object.fromEntries(
676
776
  Object.keys(Object.assign({ eventTypes: true }, settingsSchema)).map(key => {
677
- const selector = apiBoolean().default(false);
777
+ const selector = apiBoolean()
778
+ .default(false)
779
+ .description(key === 'eventTypes' ? 'Include the list of webhook event types in the response' : `Include the \`${key}\` setting in the response`);
678
780
  return [key, isHiddenSetting(key) ? selector.meta({ swaggerHidden: true }) : selector];
679
781
  })
680
782
  );
@@ -731,7 +833,8 @@ function tlsOptionsSchema(label, opts) {
731
833
  ca: Joi.alternatives()
732
834
  .try(pemSchema.example(PEM_CERT_EXAMPLE), Joi.array().items(pemSchema.example(PEM_CERT_EXAMPLE)).max(32).example([PEM_CERT_EXAMPLE]))
733
835
  .example(PEM_CERT_EXAMPLE)
734
- .description('Trusted CA certificates in PEM format, replacing the default trust store'),
836
+ .description('Trusted CA certificates in PEM format, replacing the default trust store')
837
+ .label('TlsCaCertificates'),
735
838
  cert: pemSchema.example(PEM_CERT_EXAMPLE).description('Client certificate in PEM format, for servers that require one'),
736
839
  key: pemSchema.example(PEM_KEY_EXAMPLE).description('Private key of the client certificate in PEM format'),
737
840
  passphrase: Joi.string().max(1024).example('key passphrase').description('Passphrase of the client certificate private key'),
@@ -941,14 +1044,7 @@ const oauth2Schema = {
941
1044
  .example('1//09Ie3CtORQYm...')
942
1045
  .description('OAuth2 refresh token for obtaining new access tokens'),
943
1046
 
944
- authority: Joi.string()
945
- .trim()
946
- .empty('')
947
- .max(1024)
948
- .example('consumers')
949
- .description('Deprecated - Authority is set by the OAuth2 application configuration')
950
- .label('SupportedAccountTypes')
951
- .meta({ swaggerHidden: true }),
1047
+ authority: deprecated(Joi.string().trim().empty('').max(1024).example('consumers'), 'oauth2.authority').label('SupportedAccountTypes'),
952
1048
 
953
1049
  expires: Joi.date().iso().example('2021-03-22T13:13:31.000Z').description('Access token expiration timestamp')
954
1050
  };
@@ -1080,14 +1176,7 @@ const oauth2UpdateSchema = {
1080
1176
  .max(4 * 4096)
1081
1177
  .example('1//09Ie3CtORQYm...')
1082
1178
  .description('OAuth2 refresh token for obtaining new access tokens'),
1083
- authority: Joi.string()
1084
- .trim()
1085
- .empty('')
1086
- .max(1024)
1087
- .example('consumers')
1088
- .description('Deprecated - Authority is set by the OAuth2 application configuration')
1089
- .label('SupportedAccountTypes')
1090
- .meta({ swaggerHidden: true }),
1179
+ authority: deprecated(Joi.string().trim().empty('').max(1024).example('consumers'), 'oauth2.authority').label('SupportedAccountTypes'),
1091
1180
 
1092
1181
  expires: Joi.date().iso().example('2021-03-22T13:13:31.000Z').description('Access token expiration timestamp')
1093
1182
  };
@@ -1288,7 +1377,7 @@ const messageDetailsSchema = Joi.object({
1288
1377
  .valid('\\All', '\\Archive', '\\Drafts', '\\Flagged', '\\Junk', '\\Sent', '\\Trash', '\\Inbox')
1289
1378
  .description('Special folder type of the mailbox containing this message (IMAP accounts only)')
1290
1379
  .meta({ enumDescriptions: ENUM_DESCRIPTIONS.mailboxSpecialUse })
1291
- .label('MailboxSpecialUse'),
1380
+ .label('MessageMailboxSpecialUse'),
1292
1381
  messageSpecialUse: messageSpecialUseSchema
1293
1382
  }).label('MessageDetails');
1294
1383
 
@@ -1685,7 +1774,7 @@ const expectedEmailSchema = Joi.string()
1685
1774
  const accountSchemas = {
1686
1775
  // The Document Store sync start date. Accepted and dropped since the feature's removal, so an
1687
1776
  // integration written against an older release keeps working
1688
- syncFrom: Joi.any().strip().description('Deprecated - Document Store feature has been removed').meta({ swaggerHidden: true }),
1777
+ syncFrom: deprecated(Joi.any().strip(), 'syncFrom'),
1689
1778
 
1690
1779
  notifyFrom: Joi.date()
1691
1780
  .iso()
@@ -1915,7 +2004,8 @@ const oauthCreateSchema = {
1915
2004
  })
1916
2005
  .example('externalAccount')
1917
2006
  .description('How the Gmail service account authenticates')
1918
- .meta({ enumDescriptions: ENUM_DESCRIPTIONS.gmailAuthMethod }),
2007
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.gmailAuthMethod })
2008
+ .label('OAuth2AppAuthMethod'),
1919
2009
 
1920
2010
  externalAccount: Joi.string()
1921
2011
  .trim()
@@ -2104,7 +2194,8 @@ const oauthUpdateSchema = {
2104
2194
  otherwise: Joi.forbidden()
2105
2195
  })
2106
2196
  .description('How the Gmail service account authenticates')
2107
- .meta({ enumDescriptions: ENUM_DESCRIPTIONS.gmailAuthMethod }),
2197
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.gmailAuthMethod })
2198
+ .label('OAuth2AppUpdateAuthMethod'),
2108
2199
 
2109
2200
  externalAccount: Joi.string()
2110
2201
  .trim()
@@ -2321,6 +2412,38 @@ const defaultAccountTypeSchema = Joi.string()
2321
2412
  .description('Pre-select a specific account type (use "imap" or an OAuth2 app ID) instead of showing the selection screen')
2322
2413
  .label('DefaultAccountType');
2323
2414
 
2415
+ // Per-protocol result block of a connection check - the IMAP and SMTP results carry the same
2416
+ // fields built by verifyAccountInfo, only labels, wording, and the server response example
2417
+ // differ. Shared by the account verification and the gateway verification responses
2418
+ const verifyResultSchema = (proto, responseTextExample) =>
2419
+ Joi.object({
2420
+ success: Joi.boolean().example(true).description(`Was ${proto.toUpperCase()} account verified`).label(`Verify${proto}Success`),
2421
+ error: Joi.string()
2422
+ .example('Something went wrong')
2423
+ .description(`Error messages for ${proto.toUpperCase()} verification. Only present if success=false`)
2424
+ .label(`Verify${proto}Error`),
2425
+ code: Joi.string().example('ERR_SSL_WRONG_VERSION_NUMBER').description('Error code. Only present if success=false').label(`Verify${proto}Code`),
2426
+ statusCode: Joi.number()
2427
+ .integer()
2428
+ .example(500)
2429
+ .description('HTTP-style status code for the error. Only present if success=false')
2430
+ .label(`Verify${proto}StatusCode`),
2431
+ responseText: Joi.string()
2432
+ .example(responseTextExample)
2433
+ .description('Server response for the failed verification. Only present if success=false')
2434
+ .label(`Verify${proto}ResponseText`)
2435
+ }).label(`Verify${proto}Result`);
2436
+
2437
+ /**
2438
+ * The free-text filter of a list endpoint, the same case-insensitive substring match the admin
2439
+ * list pages apply
2440
+ * @param {string} fields - What the text is matched against, for the description
2441
+ * @param {string} label - Schema label, distinct per endpoint
2442
+ * @returns {Object} Joi schema
2443
+ */
2444
+ const listQuerySchema = (fields, label) =>
2445
+ Joi.string().trim().empty('').max(256).example('example').description(`List only entries whose ${fields} contains this text, ignoring case`).label(label);
2446
+
2324
2447
  const outboxEntrySchema = Joi.object({
2325
2448
  queueId: Joi.string().example('1869c5692565f756b33').description('Unique queue entry identifier'),
2326
2449
  account: accountIdSchema.required(),
@@ -2359,7 +2482,8 @@ const outboxEntrySchema = Joi.object({
2359
2482
  .example('2021-02-17T13:43:18.860Z')
2360
2483
  .description(
2361
2484
  'Next delivery attempt time (approximate, computed from the retry backoff without jitter). False when all delivery attempts have been used up'
2362
- ),
2485
+ )
2486
+ .label('OutboxNextAttempt'),
2363
2487
 
2364
2488
  attemptsMade: Joi.number().integer().example(3).description('Number of delivery attempts made'),
2365
2489
  attempts: Joi.number().integer().example(3).description('Maximum delivery attempts before marking as failed'),
@@ -2408,7 +2532,7 @@ const outboxEntrySchema = Joi.object({
2408
2532
  // The Document Store was removed in 2.82.0. The request fields that selected it are still
2409
2533
  // accepted and dropped, so an integration written against an older release keeps working and a
2410
2534
  // request that names them is answered from the live mailbox, as it already was with the feature off
2411
- const documentStoreSchema = Joi.any().strip().description('Deprecated - Document Store feature has been removed').meta({ swaggerHidden: true });
2535
+ const documentStoreSchema = deprecated(Joi.any().strip(), 'documentStore');
2412
2536
 
2413
2537
  const messageReferenceSchema = Joi.object({
2414
2538
  message: Joi.string()
@@ -2817,6 +2941,8 @@ module.exports = {
2817
2941
  threadIdSchema,
2818
2942
  signedFormBlobFields,
2819
2943
  outboxEntrySchema,
2944
+ verifyResultSchema,
2945
+ listQuerySchema,
2820
2946
  googleProjectIdSchema,
2821
2947
  googleTopicNameSchema,
2822
2948
  googleSubscriptionNameSchema,
@@ -2831,7 +2957,5 @@ module.exports = {
2831
2957
  exportIdSchema,
2832
2958
  pubSubErrorSchema,
2833
2959
  apiResponses,
2834
- ENUM_DESCRIPTIONS,
2835
- IMAP_MAX_IDLE_TIME_MIN,
2836
- IMAP_MAX_IDLE_TIME_MAX
2960
+ ENUM_DESCRIPTIONS
2837
2961
  };
package/lib/settings.js CHANGED
@@ -344,8 +344,12 @@ module.exports = {
344
344
  return await redis.hmset(`${REDIS_PREFIX}settings`, storeObj);
345
345
  },
346
346
 
347
- async clear(key) {
348
- return await redis.hdel(`${REDIS_PREFIX}settings`, key);
347
+ async clear(...keys) {
348
+ // several keys go in one HDEL; HDEL with no field at all is an error
349
+ if (!keys.length) {
350
+ return 0;
351
+ }
352
+ return await redis.hdel(`${REDIS_PREFIX}settings`, ...keys);
349
353
  },
350
354
 
351
355
  async getLoggingInfo(account, settingData) {
package/lib/smtp-auth.js CHANGED
@@ -174,4 +174,22 @@ function createSmtpAccountResolver({ accountCache, call }) {
174
174
  };
175
175
  }
176
176
 
177
- module.exports = { createSmtpAuthHandler, createSmtpAccountResolver };
177
+ /**
178
+ * The commands a submission session refuses: the server's own list, plus AUTH while the
179
+ * smtpServerAuthEnabled setting is off. Set on the session from onConnect, so it applies to that
180
+ * connection only (smtp-server reads session.disabledCommands in place of the server option)
181
+ * @param {string[]} serverDisabled - The server's disabledCommands option
182
+ * @param {boolean} authEnabled - The smtpServerAuthEnabled setting
183
+ * @returns {string[]}
184
+ */
185
+ function sessionDisabledCommands(serverDisabled, authEnabled) {
186
+ const commands = new Set((serverDisabled || []).map(command => command.toUpperCase()));
187
+ if (authEnabled) {
188
+ commands.delete('AUTH');
189
+ } else {
190
+ commands.add('AUTH');
191
+ }
192
+ return Array.from(commands);
193
+ }
194
+
195
+ module.exports = { createSmtpAuthHandler, createSmtpAccountResolver, sessionDisabledCommands };
@@ -43,4 +43,21 @@ function eventLoopDelaySeries(threadsInfo) {
43
43
  }));
44
44
  }
45
45
 
46
- module.exports = { heartbeatDiagnostics, eventLoopDelaySeries };
46
+ /**
47
+ * The per-thread heap gauge values, in bytes, for every thread that answered its resource reading.
48
+ * Heap is the one memory figure that belongs to a thread: rss and external are the process's, and
49
+ * every thread reports the same value for them.
50
+ * @param {Array<Object>} threadsInfo - Thread readings as the metrics collector returns them
51
+ * @returns {Array<{labels: Object, used: number, total: number}>}
52
+ */
53
+ function threadHeapSeries(threadsInfo) {
54
+ return (threadsInfo || [])
55
+ .filter(threadInfo => Number.isFinite(threadInfo.heapUsed) && Number.isFinite(threadInfo.heapTotal))
56
+ .map(threadInfo => ({
57
+ labels: { type: threadInfo.type, thread: String(threadInfo.threadId) },
58
+ used: threadInfo.heapUsed,
59
+ total: threadInfo.heapTotal
60
+ }));
61
+ }
62
+
63
+ module.exports = { heartbeatDiagnostics, eventLoopDelaySeries, threadHeapSeries };
@@ -326,9 +326,12 @@ async function provisionHostname(opts) {
326
326
  return { success: true, changed, hostname };
327
327
  }
328
328
 
329
- // acquireCert() answers a blocked or unvalidatable domain by returning what was already
330
- // stored, which for a first certificate is nothing. The reason it did not say is in the
331
- // record it wrote, so read it back rather than reporting "failed" and nothing else.
329
+ // A first order that failed validation or was blocked comes back as a `failed` record carrying
330
+ // the reason (@postalsys/certs 2.0.1). `false` only means another worker is on the same order;
331
+ // an older certs left the reason in the stored record instead, which is still read for that
332
+ if (!failure) {
333
+ failure = record && record.status === 'failed' && record.renewalError?.err;
334
+ }
332
335
  if (!failure) {
333
336
  let stored;
334
337
  try {
@@ -24,18 +24,7 @@ const msgpack = require('./msgpack');
24
24
  const settings = require('./settings');
25
25
  const { REDIS_PREFIX, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
26
26
  const { extractMultiError } = require('./redis-operations');
27
- const { readEnvValue } = require('./read-env-value');
28
-
29
- // Both overrides below are whole counts that have to be at least 1, and anything else falls back to
30
- // the default rather than being clamped towards it - "0" is not a request for the smallest possible
31
- // log, it is a value this module has no reading for. Each has its own way of going wrong: the entry
32
- // cap floors the log route's `pageSize` ceiling, so a value below 1 left `min(1).max(0)` on the
33
- // query schema and no request could satisfy it, and Redis DELETES a key given a non-positive
34
- // EXPIRE, so a negative age would drop each entry in the transaction that wrote it.
35
- function positiveInt(value, fallback) {
36
- const parsed = Math.floor(Number(value));
37
- return Number.isFinite(parsed) && parsed >= 1 ? parsed : fallback;
38
- }
27
+ const { getOverridableSettings, envOrDefault } = require('./env-setting-overrides');
39
28
 
40
29
  // How many entries to keep per token. The cap is a hard trim rather than a target, and it is what
41
30
  // bounds the whole feature: every write trims, so total storage is a function of how many tokens are
@@ -43,12 +32,20 @@ function positiveInt(value, fallback) {
43
32
  // per token, so a thousand active tokens cost about 170MB - entries carrying a maximum-length
44
33
  // account run some three times that. Raise it against those figures, and against the fact that a log
45
34
  // of who read whose mail carries the sensitivity of the mail itself.
46
- const LOG_ENTRIES = positiveInt(readEnvValue('EENGINE_TOKEN_LOG_ENTRIES'), 1000);
47
-
48
- // How long a token's log survives its last use, in seconds. Refreshed on every write, so this bounds
49
- // how long a log outlives the credential's activity rather than how long each entry lives - which is
50
- // the useful bound, because a token nobody has used is a log nobody needs.
51
- const LOG_AGE = positiveInt(readEnvValue('EENGINE_TOKEN_LOG_AGE'), 7 * 24 * 3600);
35
+ //
36
+ // The age is how long a token's log survives its last use. Refreshed on every write, so it bounds how
37
+ // long a log outlives the credential's activity rather than how long each entry lives - which is the
38
+ // useful bound, because a token nobody has used is a log nobody needs.
39
+ //
40
+ // Both are settings as well (tokenLogEntries, tokenLogAge), the environment winning, and each write
41
+ // reads the values in effect (lib/env-setting-overrides.js, which also parses both: a whole count of
42
+ // at least 1, anything else falling back to the default rather than being clamped towards it - "0"
43
+ // is not a request for the smallest possible log. Each has its own way of going wrong otherwise: the
44
+ // entry cap floors the log route's `pageSize` ceiling, so a value below 1 left `min(1).max(0)` on the
45
+ // query schema and no request could satisfy it, and Redis DELETES a key given a non-positive EXPIRE,
46
+ // so a negative age would drop each entry in the transaction that wrote it). The constant here is
47
+ // the environment-or-default entry cap, which the log route's page size bound below is fixed from.
48
+ const LOG_ENTRIES = envOrDefault('tokenLogEntries');
52
49
 
53
50
  // The largest page the log route will serve. Deliberately not the retention cap: one bounds a single
54
51
  // response, the other bounds stored data, and while they were the same constant raising retention
@@ -157,11 +154,13 @@ function record(entry) {
157
154
  reason: entry.reason || null
158
155
  };
159
156
 
157
+ const { tokenLogEntries, tokenLogAge } = await getOverridableSettings('tokenLogEntries', 'tokenLogAge');
158
+
160
159
  const results = await redis
161
160
  .multi()
162
161
  .lpushBuffer(key, msgpack.encode(stored))
163
- .ltrim(key, 0, LOG_ENTRIES - 1)
164
- .expire(key, LOG_AGE)
162
+ .ltrim(key, 0, tokenLogEntries - 1)
163
+ .expire(key, tokenLogAge)
165
164
  .exec();
166
165
 
167
166
  const err = extractMultiError(results);
@@ -40,7 +40,8 @@ const GROUP_LABELS = {
40
40
  [GROUP.OAUTH2]: 'OAuth2 applications',
41
41
  [GROUP.LICENSE]: 'License',
42
42
  [GROUP.TOKEN]: 'Access tokens',
43
- [GROUP.PROVISIONING]: 'Account and gateway setup'
43
+ [GROUP.PROVISIONING]: 'Account and gateway setup',
44
+ [GROUP.WEBHOOK_DELIVERIES]: 'Failed webhook deliveries'
44
45
  };
45
46
 
46
47
  // The one spelling of the slug-to-label lookup. Object.hasOwn rather than a bare lookup: a slug
@@ -62,7 +63,7 @@ const GROUP_CLUSTERS = [
62
63
  { label: 'Mail', groups: [GROUP.ACCOUNT, GROUP.MAILBOX, GROUP.MESSAGE, GROUP.SUBMIT, GROUP.OUTBOX, GROUP.EXPORT] },
63
64
  { label: 'Configuration', groups: [GROUP.TEMPLATE, GROUP.BLOCKLIST, GROUP.WEBHOOK, GROUP.GATEWAY] },
64
65
  { label: 'Monitoring', groups: [GROUP.EVENTS, GROUP.DIAGNOSTICS, GROUP.LOGS] },
65
- { label: 'Instance', groups: [GROUP.SETTINGS, GROUP.PROVISIONING, GROUP.OAUTH2, GROUP.TOKEN, GROUP.LICENSE] }
66
+ { label: 'Instance', groups: [GROUP.SETTINGS, GROUP.WEBHOOK_DELIVERIES, GROUP.PROVISIONING, GROUP.OAUTH2, GROUP.TOKEN, GROUP.LICENSE] }
66
67
  ];
67
68
 
68
69
  // How the token list names the sections an absent `groups` axis reaches (IMPLICIT_GROUPS): by
@@ -172,7 +173,7 @@ const MCP_SECTIONS = {
172
173
  {
173
174
  value: 'operate',
174
175
  label: 'Operate',
175
- hint: 'Also reconnect, add and test accounts, change settings, retry or expedite queued messages, and manage OAuth2 applications, gateways and templates.',
176
+ hint: 'Also reconnect, add and test accounts, change settings, retry or expedite queued messages and failed webhook deliveries, and manage OAuth2 applications, gateways and templates.',
176
177
  caveat: 'Settings changes take effect at once, and moving the webhook target sends future message notifications, message text included, elsewhere. Reconfiguring an account or gateway can send its stored credential to a new host, and reconfiguring an OAuth2 application can redirect where future sign-ins deliver their authorization codes. It cannot delete anything, create tokens or read stored credentials.',
177
178
  pairs: pairsOf(MCP_SCOPES.manage, grant => grant.action !== ACTION.DESTRUCTIVE)
178
179
  },
package/lib/tools.js CHANGED
@@ -2,8 +2,11 @@
2
2
 
3
3
  'use strict';
4
4
 
5
+ const { filterEmptyObjectValues } = require('./utils/filter-empty');
6
+
5
7
  const msgpack = require('./msgpack');
6
8
  const enumMessageFlags = require('./enum-message-flags');
9
+ const { redisMemoryWarnings } = require('./redis-memory-warnings');
7
10
  const Joi = require('joi');
8
11
  const packageData = require('../package.json');
9
12
  const { TLS_CERTIFICATE_SETTINGS } = require('./tls/listeners');
@@ -1834,7 +1837,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1834
1837
  });
1835
1838
  imapClient
1836
1839
  .connect()
1837
- .then(() => resolve(imapClient._mailboxList))
1840
+ .then(() => resolve(imapClient.mailboxList))
1838
1841
  .catch(reject);
1839
1842
  });
1840
1843
 
@@ -2270,37 +2273,8 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2270
2273
  });
2271
2274
  }
2272
2275
 
2273
- // EmailEngine uses Redis as a database, not a cache. Any eviction silently drops sync state,
2274
- // which makes already-synced messages look new and triggers duplicate webhooks.
2275
- let maxmemoryPolicy = typeof redisInfo.maxmemory_policy === 'string' ? redisInfo.maxmemory_policy : null;
2276
- let maxmemory = Number(redisInfo.maxmemory) || 0;
2277
- let evictedKeys = Number(redisInfo.evicted_keys) || 0;
2278
-
2279
- if (evictedKeys > 0) {
2280
- // Definitive: Redis has already evicted keys
2281
- redisWarnings.push({
2282
- key: 'evicted-keys',
2283
- color: 'danger',
2284
- title: 'Redis eviction detected',
2285
- details: [
2286
- `Redis has evicted ${evictedKeys.toLocaleString('en-US')} key${evictedKeys === 1 ? '' : 's'} after reaching its memory limit.`,
2287
- 'EmailEngine uses Redis as its primary database, not a cache. Evicted keys cause already-synced messages to be reprocessed - generating duplicate webhooks - and can lead to data loss.',
2288
- 'Set the Redis "maxmemory-policy" to "noeviction" and provision enough memory so Redis never reaches its limit.'
2289
- ]
2290
- });
2291
- } else if (maxmemoryPolicy && maxmemoryPolicy !== 'noeviction') {
2292
- // Latent risk: an eviction policy is configured but nothing has been evicted yet
2293
- redisWarnings.push({
2294
- key: 'maxmemory-policy',
2295
- color: maxmemory > 0 ? 'danger' : 'warning',
2296
- title: 'Unsafe Redis eviction policy',
2297
- details: [
2298
- `The Redis "maxmemory-policy" is set to "${maxmemoryPolicy}", but EmailEngine requires "noeviction".`,
2299
- 'With any other policy, Redis can delete EmailEngine sync state under memory pressure, causing already-synced messages to be reprocessed - generating duplicate webhooks - and possible data loss.',
2300
- 'Set "maxmemory-policy noeviction" and make sure Redis has enough memory for your workload.'
2301
- ]
2302
- });
2303
- }
2276
+ // Eviction and the maxmemory limit, see lib/redis-memory-warnings.js
2277
+ redisWarnings.push(...redisMemoryWarnings(redisInfo));
2304
2278
  } catch (err) {
2305
2279
  logger.error({ msg: 'Failed to get stats', err });
2306
2280
  redisVersion = err.message;
@@ -2601,15 +2575,8 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2601
2575
  return module.exports.getSignedFormDataSync(serviceSecret, opts);
2602
2576
  },
2603
2577
 
2604
- filterEmptyObjectValues(obj) {
2605
- let res = {};
2606
- for (let key of Object.keys(obj)) {
2607
- if (obj[key]) {
2608
- res[key] = obj[key];
2609
- }
2610
- }
2611
- return res;
2612
- },
2578
+ // lib/utils/filter-empty.js, kept here for the callers that take it from tools
2579
+ filterEmptyObjectValues,
2613
2580
 
2614
2581
  // Signs a hosted setup-form blob (the default purpose), a tracking blob or an unsubscribe
2615
2582
  // blob; the purpose picks the derived key the matching verifier checks against