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
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()
@@ -1803,7 +1892,7 @@ const oauthCreateSchema = {
1803
1892
  then: Joi.required(),
1804
1893
  otherwise: Joi.optional().valid(false, null)
1805
1894
  })
1806
- .example('boT7Q~dUljnfFdVuqpC11g8nGMjO8kpRAv-ZB')
1895
+ .example('example-client-secret')
1807
1896
  .description('OAuth2 client secret from the provider'),
1808
1897
 
1809
1898
  baseScopes: Joi.string()
@@ -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 };
package/lib/sso.js CHANGED
@@ -35,7 +35,7 @@
35
35
  // dotted path (e.g. "realm_access.roles") for IdPs that nest it.
36
36
 
37
37
  const { fetch: fetchCmd } = require('undici');
38
- const { backOff } = require('exponential-backoff');
38
+ const { backOff } = require('./utils/back-off');
39
39
  const { readEnvValue, httpAgent, getBoolean } = require('./tools');
40
40
  const packageData = require('../package.json');
41
41
 
@@ -145,7 +145,7 @@ Full documentation: https://learn.emailengine.app/`
145
145
  description: 'Configure OAuth2 applications for Gmail, Outlook, and other providers. Manage client credentials and authentication flows',
146
146
  externalDocs: {
147
147
  description: 'OAuth2 Configuration Guide',
148
- url: 'https://learn.emailengine.app/docs/configuration/oauth2-configuration'
148
+ url: 'https://learn.emailengine.app/docs/accounts/oauth2-setup'
149
149
  }
150
150
  },
151
151
  {
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+
3
+ // What the main thread reports about its worker threads beyond their counts: the fields the
4
+ // heartbeat log lines carry and the per-thread event loop delay gauges. Kept free of server.js
5
+ // state so both can be tested without starting the process.
6
+
7
+ /**
8
+ * Fields for a heartbeat log line (unhealthy, restarting, recovered).
9
+ * @param {Object} args
10
+ * @param {number} args.now - Current time in milliseconds
11
+ * @param {number} [args.lastHeartbeat] - When the thread last reported in
12
+ * @param {number} [args.accounts] - Accounts assigned to the thread, for an account worker
13
+ * @param {Object} [args.threadInfo] - The thread's last resource reading. A thread that has gone quiet
14
+ * cannot answer, so this is the one taken before that, at most one collection interval earlier.
15
+ * @returns {Object} Fields to spread into the log entry
16
+ */
17
+ function heartbeatDiagnostics({ now, lastHeartbeat, accounts, threadInfo }) {
18
+ let details = {};
19
+ if (typeof lastHeartbeat === 'number') {
20
+ details.timeSinceHeartbeat = Math.round((now - lastHeartbeat) / 1000) + 's';
21
+ }
22
+ if (typeof accounts === 'number') {
23
+ details.accounts = accounts;
24
+ }
25
+ if (threadInfo?.eventLoopDelay) {
26
+ details.lastEventLoopDelay = Math.round(threadInfo.eventLoopDelay.max) + 'ms';
27
+ }
28
+ return details;
29
+ }
30
+
31
+ /**
32
+ * The per-thread event loop delay gauge values, in seconds, for every thread that has a reading.
33
+ * @param {Array<Object>} threadsInfo - Thread readings as the metrics collector returns them
34
+ * @returns {Array<{labels: Object, max: number, p99: number}>}
35
+ */
36
+ function eventLoopDelaySeries(threadsInfo) {
37
+ return (threadsInfo || [])
38
+ .filter(threadInfo => threadInfo.eventLoopDelay)
39
+ .map(threadInfo => ({
40
+ labels: { type: threadInfo.type, thread: String(threadInfo.threadId) },
41
+ max: threadInfo.eventLoopDelay.max / 1000,
42
+ p99: threadInfo.eventLoopDelay.p99 / 1000
43
+ }));
44
+ }
45
+
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 };
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+
3
+ // The timezone choices on the admin Service page, built from the runtime's own ICU data instead of
4
+ // a static package. Node (and the pkg binaries, which carry full ICU) list zones under their CLDR
5
+ // ids, and CLDR keeps the old spelling for zones IANA has since renamed: Intl answers
6
+ // "Europe/Kiev" and "Asia/Calcutta", never "Europe/Kyiv" or "Asia/Kolkata". Those are shown and
7
+ // stored under their IANA names, which is also what the replaced timezones-list package offered, so
8
+ // a value saved from the old list stays selected. Intl accepts both spellings as a timeZone.
9
+
10
+ // CLDR id -> current IANA name, for every id Intl.supportedValuesOf('timeZone') returns in its
11
+ // legacy form (checked on Node 20, 24 and 26, all ICU 78)
12
+ const IANA_NAMES = new Map([
13
+ ['Africa/Asmera', 'Africa/Asmara'],
14
+ ['America/Buenos_Aires', 'America/Argentina/Buenos_Aires'],
15
+ ['America/Catamarca', 'America/Argentina/Catamarca'],
16
+ ['America/Coral_Harbour', 'America/Atikokan'],
17
+ ['America/Cordoba', 'America/Argentina/Cordoba'],
18
+ ['America/Indianapolis', 'America/Indiana/Indianapolis'],
19
+ ['America/Jujuy', 'America/Argentina/Jujuy'],
20
+ ['America/Louisville', 'America/Kentucky/Louisville'],
21
+ ['America/Mendoza', 'America/Argentina/Mendoza'],
22
+ ['Asia/Calcutta', 'Asia/Kolkata'],
23
+ ['Asia/Katmandu', 'Asia/Kathmandu'],
24
+ ['Asia/Rangoon', 'Asia/Yangon'],
25
+ ['Asia/Saigon', 'Asia/Ho_Chi_Minh'],
26
+ ['Atlantic/Faeroe', 'Atlantic/Faroe'],
27
+ ['Europe/Kiev', 'Europe/Kyiv'],
28
+ ['Pacific/Ponape', 'Pacific/Pohnpei'],
29
+ ['Pacific/Truk', 'Pacific/Chuuk']
30
+ ]);
31
+
32
+ // Offsets are read on these dates so the label shows the standard offset all year round instead
33
+ // of moving with daylight saving time: the smaller of a January and a July offset is the standard
34
+ // one in both hemispheres
35
+ const SAMPLE_DATES = [new Date(Date.UTC(2026, 0, 1)), new Date(Date.UTC(2026, 6, 1))];
36
+
37
+ /**
38
+ * @param {string} timeZone
39
+ * @param {Date} date
40
+ * @returns {number|null} UTC offset in minutes, or null for an unknown zone
41
+ */
42
+ function getOffsetMinutes(timeZone, date) {
43
+ let name;
44
+ try {
45
+ name = new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' }).formatToParts(date).find(part => part.type === 'timeZoneName').value;
46
+ } catch {
47
+ return null;
48
+ }
49
+ // "GMT" alone is UTC, otherwise "GMT+05:30" / "GMT-03:00"
50
+ const match = name.match(/^GMT(?:([+-])(\d{2}):(\d{2}))?$/);
51
+ if (!match) {
52
+ return null;
53
+ }
54
+ return match[1] ? (match[1] === '-' ? -1 : 1) * (Number(match[2]) * 60 + Number(match[3])) : 0;
55
+ }
56
+
57
+ // The standard offset of a zone, null when the runtime does not know it
58
+ function getStandardOffset(timeZone) {
59
+ const offsets = SAMPLE_DATES.map(date => getOffsetMinutes(timeZone, date)).filter(offset => offset !== null);
60
+ return offsets.length ? Math.min(...offsets) : null;
61
+ }
62
+
63
+ function formatOffset(minutes) {
64
+ const sign = minutes < 0 ? '-' : '+';
65
+ const abs = Math.abs(minutes);
66
+ return `GMT${sign}${String(Math.floor(abs / 60)).padStart(2, '0')}:${String(abs % 60).padStart(2, '0')}`;
67
+ }
68
+
69
+ let cachedZones = null;
70
+
71
+ /**
72
+ * Every zone the runtime knows under its IANA name, ordered by standard offset and then by name.
73
+ *
74
+ * @returns {{ timezone: string, offset: number, label: string }[]}
75
+ */
76
+ function listTimezones() {
77
+ if (!cachedZones) {
78
+ const zones = new Map();
79
+ for (const id of Intl.supportedValuesOf('timeZone')) {
80
+ const timezone = IANA_NAMES.get(id) || id;
81
+ const offset = getStandardOffset(id);
82
+ if (offset === null || zones.has(timezone)) {
83
+ continue;
84
+ }
85
+ zones.set(timezone, { timezone, offset, label: `${timezone} (${formatOffset(offset)})` });
86
+ }
87
+ cachedZones = [...zones.values()].sort((a, b) => a.offset - b.offset || a.timezone.localeCompare(b.timezone));
88
+ }
89
+ return cachedZones;
90
+ }
91
+
92
+ /**
93
+ * Options for the timezone select. A stored value the runtime does not list (a zone IANA has
94
+ * since merged into another, like America/Yellowknife) is kept as an option of its own, so opening
95
+ * and saving the page never changes it.
96
+ *
97
+ * @param {string|false|null|undefined} selected The stored timezone
98
+ * @returns {{ name: string, timezone: string, selected: boolean }[]}
99
+ */
100
+ function timezoneOptions(selected) {
101
+ const options = listTimezones().map(zone => ({ name: zone.label, timezone: zone.timezone, selected: zone.timezone === selected }));
102
+ if (selected && !options.some(option => option.selected)) {
103
+ const offset = getStandardOffset(selected);
104
+ options.unshift({ name: offset === null ? selected : `${selected} (${formatOffset(offset)})`, timezone: selected, selected: true });
105
+ }
106
+ return options;
107
+ }
108
+
109
+ module.exports = { listTimezones, timezoneOptions, IANA_NAMES };
@@ -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 {