emailengine-app 2.85.0 → 2.87.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 (137) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +97 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +16 -3
  6. package/ENVIRONMENT.md +139 -0
  7. package/README.md +5 -1
  8. package/config/default.toml +2 -0
  9. package/copy-static-files.sh +4 -2
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +4 -3
  12. package/lib/account-assignment.js +19 -0
  13. package/lib/account.js +285 -195
  14. package/lib/api-error-codes.js +49 -0
  15. package/lib/api-reference/model.js +6 -1
  16. package/lib/api-routes/account-routes.js +91 -32
  17. package/lib/api-routes/blocklist-routes.js +68 -2
  18. package/lib/api-routes/delivery-test-routes.js +1 -1
  19. package/lib/api-routes/gateway-routes.js +82 -10
  20. package/lib/api-routes/index.js +4 -0
  21. package/lib/api-routes/license-routes.js +2 -2
  22. package/lib/api-routes/mailbox-routes.js +3 -3
  23. package/lib/api-routes/message-routes.js +15 -7
  24. package/lib/api-routes/oauth2-app-routes.js +15 -8
  25. package/lib/api-routes/outbox-routes.js +77 -66
  26. package/lib/api-routes/permission-map.js +55 -6
  27. package/lib/api-routes/scoped-routes.js +74 -0
  28. package/lib/api-routes/settings-routes.js +11 -4
  29. package/lib/api-routes/stats-routes.js +5 -1
  30. package/lib/api-routes/submit-routes.js +25 -5
  31. package/lib/api-routes/template-routes.js +7 -6
  32. package/lib/api-routes/token-routes.js +11 -5
  33. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  34. package/lib/api-routes/webhook-route-routes.js +119 -4
  35. package/lib/calendar-event.js +81 -1
  36. package/lib/consts.js +38 -46
  37. package/lib/db.js +14 -6
  38. package/lib/delivery-error.js +6 -0
  39. package/lib/deprecations.js +270 -0
  40. package/lib/email-client/base-client.js +134 -158
  41. package/lib/email-client/fallback-poll.js +62 -0
  42. package/lib/email-client/gmail-client.js +59 -11
  43. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  44. package/lib/email-client/imap/adaptive-idle.js +278 -0
  45. package/lib/email-client/imap/connection-errors.js +14 -1
  46. package/lib/email-client/imap/idle-settings.js +31 -5
  47. package/lib/email-client/imap/listing-diff.js +37 -0
  48. package/lib/email-client/imap/mailbox.js +380 -227
  49. package/lib/email-client/imap/subconnection.js +7 -29
  50. package/lib/email-client/imap/sync-operations.js +220 -127
  51. package/lib/email-client/imap-client.js +227 -163
  52. package/lib/email-client/message-builder.js +14 -79
  53. package/lib/email-client/outlook-client.js +378 -338
  54. package/lib/email-client/smtp-pool-manager.js +16 -13
  55. package/lib/email-client/sync-state-fields.js +19 -0
  56. package/lib/encrypt.js +157 -41
  57. package/lib/enum-descriptions.js +3 -1
  58. package/lib/env-setting-overrides.js +288 -0
  59. package/lib/export-worker.js +751 -0
  60. package/lib/export.js +64 -15
  61. package/lib/field-usage.js +1 -1
  62. package/lib/gateway.js +17 -1
  63. package/lib/get-raw-email.js +35 -108
  64. package/lib/health.js +75 -0
  65. package/lib/lock-run.js +119 -0
  66. package/lib/logger-consts.js +48 -0
  67. package/lib/logger.js +1 -1
  68. package/lib/lua/z-head-scores.lua +28 -0
  69. package/lib/network-errors.js +1 -1
  70. package/lib/node-version.js +24 -0
  71. package/lib/notify-attachments.js +20 -1
  72. package/lib/oauth/gmail.js +54 -29
  73. package/lib/oauth2-apps.js +630 -655
  74. package/lib/otp.js +66 -0
  75. package/lib/outbox.js +184 -54
  76. package/lib/parse-message.js +3 -3
  77. package/lib/privileged-settings.js +2 -2
  78. package/lib/queue-browser/definitions.js +11 -0
  79. package/lib/queue-browser/index.js +68 -19
  80. package/lib/queue-job-actions.js +18 -1
  81. package/lib/queue-retention.js +48 -12
  82. package/lib/queue-stats.js +11 -2
  83. package/lib/read-env-value.js +3 -0
  84. package/lib/redis-memory-warnings.js +99 -0
  85. package/lib/redis-reconnect.js +29 -0
  86. package/lib/request-timing.js +23 -0
  87. package/lib/respawn-backoff.js +35 -0
  88. package/lib/rewrite-text-nodes.js +19 -59
  89. package/lib/schemas.js +225 -41
  90. package/lib/settings.js +6 -2
  91. package/lib/smtp-auth.js +19 -1
  92. package/lib/swagger-options.js +2 -2
  93. package/lib/thread-diagnostics.js +18 -1
  94. package/lib/tls/provision.js +6 -3
  95. package/lib/token-audit-log.js +19 -20
  96. package/lib/token-permission-view.js +4 -3
  97. package/lib/tools.js +8 -41
  98. package/lib/ui-routes/admin-config-routes.js +64 -90
  99. package/lib/ui-routes/admin-entities-routes.js +2 -14
  100. package/lib/ui-routes/imap-idle-field.js +1 -1
  101. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  102. package/lib/ui-routes/overridable-fields.js +84 -0
  103. package/lib/ui-routes/queue-routes.js +8 -5
  104. package/lib/ui-routes/settings-page.js +6 -0
  105. package/lib/utils/decode-headers.js +3 -12
  106. package/lib/utils/filter-empty.js +20 -0
  107. package/lib/utils/int-setting.js +48 -0
  108. package/lib/utils/tracking-settings.js +35 -0
  109. package/lib/web-safe-html.js +18 -105
  110. package/lib/webhook-delivery.js +461 -0
  111. package/lib/webhook-failures.js +132 -0
  112. package/lib/webhook-request.js +29 -1
  113. package/lib/webhook-routing.js +30 -1
  114. package/lib/webhook-test.js +88 -0
  115. package/lib/webhooks.js +59 -41
  116. package/lib/worker-rpc-error.js +2 -1
  117. package/package.json +28 -26
  118. package/sbom.json +600 -678
  119. package/server.js +149 -76
  120. package/static/css/flyonui.css +1 -1
  121. package/static/js/ace/ace.js +1 -1
  122. package/static/js/ee-client.js +650 -196
  123. package/static/licenses.html +49 -59
  124. package/translations/messages.pot +26 -26
  125. package/views/config/security.hbs +22 -0
  126. package/views/config/service.hbs +44 -0
  127. package/views/config/webhooks.hbs +36 -0
  128. package/views/layout/app.hbs +9 -6
  129. package/views/legal.hbs +8 -0
  130. package/views/partials/queue_retention_note.hbs +12 -8
  131. package/views/partials/ui/env-managed-alert.hbs +16 -7
  132. package/workers/api.js +112 -37
  133. package/workers/export.js +16 -631
  134. package/workers/imap.js +13 -0
  135. package/workers/smtp.js +9 -11
  136. package/workers/webhooks.js +18 -432
  137. 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,9 +189,33 @@ 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
- .description('Email headers to include in webhook payloads for additional context')
216
+ .description(
217
+ 'Email headers to include in webhook payloads for additional context. Listing OTP-Token also adds the otp field (the one-time passcode) to messageNew payloads'
218
+ )
181
219
  .label('NotifyHeaders'),
182
220
 
183
221
  /* ────────────── URLs ────────────── */
@@ -198,9 +236,7 @@ const settingsSchema = {
198
236
 
199
237
  /* ────────────── Tracking ────────────── */
200
238
 
201
- trackSentMessages: formBoolean()
202
- .description('Enable tracking features for outgoing messages (deprecated - use trackClicks and trackOpens instead)')
203
- .meta({ swaggerHidden: true }),
239
+ trackSentMessages: deprecated(formBoolean(), 'trackSentMessages'),
204
240
 
205
241
  trackClicks: formBoolean().description('Rewrite links in outgoing HTML emails to track click-through rates'),
206
242
 
@@ -231,7 +267,7 @@ const settingsSchema = {
231
267
 
232
268
  // The separate risk assessment call left in 2023. The key is still accepted and dropped so a
233
269
  // client that sends it keeps working
234
- generateRiskAssessment: Joi.any().strip().description('Deprecated - This feature has been removed').meta({ swaggerHidden: true }),
270
+ generateRiskAssessment: deprecated(Joi.any().strip(), 'generateRiskAssessment'),
235
271
 
236
272
  openAiAPIKey: Joi.string().allow('').example('sk-…').description('Your OpenAI API key for AI features').label('OpenAiAPIKey'),
237
273
  openAiModel: Joi.string()
@@ -294,7 +330,7 @@ const settingsSchema = {
294
330
  // Embeddings generation left with the Document Store in 2.82.0. The key is still accepted and
295
331
  // dropped so a client that sends it keeps working; storing it would only bump the AI settings
296
332
  // version for a value nothing reads
297
- openAiGenerateEmbeddings: Joi.any().strip().description('Deprecated - embeddings generation has been removed').meta({ swaggerHidden: true }),
333
+ openAiGenerateEmbeddings: deprecated(Joi.any().strip(), 'openAiGenerateEmbeddings'),
298
334
 
299
335
  /* ────────────── Webhook Filters ────────────── */
300
336
 
@@ -323,6 +359,27 @@ const settingsSchema = {
323
359
  '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
360
  ),
325
361
 
362
+ tokenLogEntries: Joi.number()
363
+ .integer()
364
+ .empty('')
365
+ .min(1)
366
+ .max(1000000)
367
+ .allow(null)
368
+ .example(TOKEN_LOG_ENTRIES_DEFAULT)
369
+ .description(
370
+ `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`
371
+ ),
372
+
373
+ tokenLogAge: Joi.number()
374
+ .integer()
375
+ .empty('')
376
+ .min(1)
377
+ .allow(null)
378
+ .example(TOKEN_LOG_AGE_DEFAULT)
379
+ .description(
380
+ `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`
381
+ ),
382
+
326
383
  /* ────────────── Proxy ────────────── */
327
384
 
328
385
  proxyEnabled: formBoolean().description(
@@ -361,6 +418,11 @@ const settingsSchema = {
361
418
  notifyWebSafeHtml: formBoolean().description(
362
419
  'Sanitize HTML content to remove potentially dangerous elements before including in webhooks, and fold quoted thread history into a collapsed block'
363
420
  ),
421
+ disableThreadCollapse: formBoolean()
422
+ .allow(null)
423
+ .description(
424
+ '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'
425
+ ),
364
426
  notifyTextSize: Joi.number().integer().min(0).example(1048576).description('Maximum size (in bytes) of text content to include in webhook payloads'),
365
427
  notifyAttachments: formBoolean().description('Include attachment data in webhook payloads'),
366
428
  notifyAttachmentSize: Joi.number().integer().min(0).example(5242880).description('Maximum size (in bytes) per attachment to include in webhook payloads'),
@@ -385,7 +447,7 @@ const settingsSchema = {
385
447
  // The one Document Store setting still read after the removal: while it is on, the admin UI
386
448
  // and the startup log say where the feature went. Kept in the schema so an API-only
387
449
  // deployment can switch the notice off through POST /v1/settings
388
- documentStoreEnabled: formBoolean().description('Deprecated - Document Store feature has been removed').meta({ swaggerHidden: true }),
450
+ documentStoreEnabled: deprecated(formBoolean(), 'documentStoreEnabled'),
389
451
 
390
452
  /* ────────────── Logging ────────────── */
391
453
 
@@ -516,6 +578,46 @@ const settingsSchema = {
516
578
 
517
579
  queueKeep: Joi.number().integer().empty('').min(0).example(50).description('Number of completed and failed queue entries to retain for debugging'),
518
580
 
581
+ queueKeepFailed: Joi.number()
582
+ .integer()
583
+ .empty('')
584
+ .min(1)
585
+ .allow(null)
586
+ .example(FAILED_JOB_RETENTION_COUNT_DEFAULT)
587
+ .description(
588
+ `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`
589
+ ),
590
+
591
+ queueKeepFailedAge: Joi.number()
592
+ .integer()
593
+ .empty('')
594
+ .min(1)
595
+ .allow(null)
596
+ .example(FAILED_JOB_RETENTION_AGE_DEFAULT)
597
+ .description(
598
+ `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`
599
+ ),
600
+
601
+ queueKeepFailedContent: Joi.number()
602
+ .integer()
603
+ .empty('')
604
+ .min(0)
605
+ .allow(null)
606
+ .example(DEFAULT_FAILED_CONTENT_RETENTION_COUNT)
607
+ .description(
608
+ `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`
609
+ ),
610
+
611
+ queueKeepFailedContentSize: Joi.number()
612
+ .integer()
613
+ .empty('')
614
+ .min(0)
615
+ .allow(null)
616
+ .example(DEFAULT_FAILED_CONTENT_RETENTION_SIZE)
617
+ .description(
618
+ `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`
619
+ ),
620
+
519
621
  deliveryAttempts: Joi.number()
520
622
  .integer()
521
623
  .empty('')
@@ -598,7 +700,7 @@ const settingsSchema = {
598
700
  imapClientSupportUrl: Joi.string()
599
701
  .allow('')
600
702
  .uri({ scheme: ['http', 'https', 'mailto'], allowRelative: false })
601
- .example('https://github.com/postalsys/emailengine/issues')
703
+ .example('https://emailengine.app/support')
602
704
  .description('Support URL advertised via IMAP ID extension'),
603
705
 
604
706
  /* ────────────── Export ────────────── */
@@ -674,7 +776,9 @@ const isHiddenSetting = key => !!settingsSchema[key] && (settingsSchema[key].des
674
776
  // every removed feature whose setting is still accepted (documentStoreEnabled and two others).
675
777
  const settingsQuerySchema = Object.fromEntries(
676
778
  Object.keys(Object.assign({ eventTypes: true }, settingsSchema)).map(key => {
677
- const selector = apiBoolean().default(false);
779
+ const selector = apiBoolean()
780
+ .default(false)
781
+ .description(key === 'eventTypes' ? 'Include the list of webhook event types in the response' : `Include the \`${key}\` setting in the response`);
678
782
  return [key, isHiddenSetting(key) ? selector.meta({ swaggerHidden: true }) : selector];
679
783
  })
680
784
  );
@@ -731,7 +835,8 @@ function tlsOptionsSchema(label, opts) {
731
835
  ca: Joi.alternatives()
732
836
  .try(pemSchema.example(PEM_CERT_EXAMPLE), Joi.array().items(pemSchema.example(PEM_CERT_EXAMPLE)).max(32).example([PEM_CERT_EXAMPLE]))
733
837
  .example(PEM_CERT_EXAMPLE)
734
- .description('Trusted CA certificates in PEM format, replacing the default trust store'),
838
+ .description('Trusted CA certificates in PEM format, replacing the default trust store')
839
+ .label('TlsCaCertificates'),
735
840
  cert: pemSchema.example(PEM_CERT_EXAMPLE).description('Client certificate in PEM format, for servers that require one'),
736
841
  key: pemSchema.example(PEM_KEY_EXAMPLE).description('Private key of the client certificate in PEM format'),
737
842
  passphrase: Joi.string().max(1024).example('key passphrase').description('Passphrase of the client certificate private key'),
@@ -941,14 +1046,7 @@ const oauth2Schema = {
941
1046
  .example('1//09Ie3CtORQYm...')
942
1047
  .description('OAuth2 refresh token for obtaining new access tokens'),
943
1048
 
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 }),
1049
+ authority: deprecated(Joi.string().trim().empty('').max(1024).example('consumers'), 'oauth2.authority').label('SupportedAccountTypes'),
952
1050
 
953
1051
  expires: Joi.date().iso().example('2021-03-22T13:13:31.000Z').description('Access token expiration timestamp')
954
1052
  };
@@ -1080,14 +1178,7 @@ const oauth2UpdateSchema = {
1080
1178
  .max(4 * 4096)
1081
1179
  .example('1//09Ie3CtORQYm...')
1082
1180
  .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 }),
1181
+ authority: deprecated(Joi.string().trim().empty('').max(1024).example('consumers'), 'oauth2.authority').label('SupportedAccountTypes'),
1091
1182
 
1092
1183
  expires: Joi.date().iso().example('2021-03-22T13:13:31.000Z').description('Access token expiration timestamp')
1093
1184
  };
@@ -1210,6 +1301,42 @@ const messageEntrySchema = Joi.object({
1210
1301
  isAutoReply: Joi.boolean().example(false).description('Whether this message appears to be an automatic reply (out of office, vacation responder, etc.)')
1211
1302
  }).label('MessageListEntry');
1212
1303
 
1304
+ // One-time passcode of the OTP-Token header (draft-goto-otp-token). Experimental: the draft is a
1305
+ // work in progress, the field follows it
1306
+ const messageOtpSchema = Joi.object({
1307
+ code: Joi.string().example('123456').description('The passcode'),
1308
+ origin: Joi.string().example('https://example.com').description('The origin the passcode is bound to'),
1309
+ authenticated: Joi.boolean()
1310
+ .example(true)
1311
+ .description(
1312
+ "Whether the receiving server vouches for the origin: its Authentication-Results header records a passing DKIM signature from the origin's organizational domain. Only Gmail and Microsoft 365 mailboxes can report true, for other servers this is always false"
1313
+ )
1314
+ })
1315
+ .description(
1316
+ 'One-time passcode from the OTP-Token header (draft-goto-otp-token), present when the message carries exactly one valid header. Experimental, follows the Internet-Draft. The header is not authenticated by itself, so name the origin to a user only when authenticated is true'
1317
+ )
1318
+ .label('MessageOtp');
1319
+
1320
+ // Optional one-time passcode for the OTP-Token header of an outgoing message
1321
+ const submitOtpSchema = Joi.object({
1322
+ code: Joi.string()
1323
+ .pattern(/^[\x20-\x7e]+$/, 'printable ASCII')
1324
+ .max(256)
1325
+ .required()
1326
+ .example('123456')
1327
+ .description('The passcode, printable ASCII. It should also appear in the message body'),
1328
+ origin: Joi.string()
1329
+ .uri({ scheme: ['https', 'http'], allowRelative: false })
1330
+ .max(2048)
1331
+ .required()
1332
+ .example('https://example.com')
1333
+ .description('The site the passcode is for, https (or http on a loopback host). A full URL is reduced to its origin')
1334
+ })
1335
+ .description(
1336
+ 'Adds an OTP-Token header (draft-goto-otp-token) so that mail clients and browsers can offer the passcode. Experimental, follows the Internet-Draft. Cannot be combined with useStructuredFormat'
1337
+ )
1338
+ .label('SubmitOtp');
1339
+
1213
1340
  const messageDetailsSchema = Joi.object({
1214
1341
  id: Joi.string().example('AAAAAgAACrI').description('EmailEngine message identifier').label('MessageEntryId'),
1215
1342
  uid: Joi.number().integer().example(12345).description('IMAP UID (unique identifier within the mailbox). IMAP accounts only').label('MessageUid'),
@@ -1277,6 +1404,7 @@ const messageDetailsSchema = Joi.object({
1277
1404
  'Whether this message is a bounce (a delivery failure report). Checked for messages in the Inbox only; a delivery or delay notification is not one'
1278
1405
  ),
1279
1406
  relatedMessageId: Joi.string().example('<original@example.com>').description('Message-ID of the message that bounced. Set together with isBounce'),
1407
+ otp: messageOtpSchema,
1280
1408
 
1281
1409
  preview: Joi.string()
1282
1410
  .example('Hello, here is the report you asked for')
@@ -1288,7 +1416,7 @@ const messageDetailsSchema = Joi.object({
1288
1416
  .valid('\\All', '\\Archive', '\\Drafts', '\\Flagged', '\\Junk', '\\Sent', '\\Trash', '\\Inbox')
1289
1417
  .description('Special folder type of the mailbox containing this message (IMAP accounts only)')
1290
1418
  .meta({ enumDescriptions: ENUM_DESCRIPTIONS.mailboxSpecialUse })
1291
- .label('MailboxSpecialUse'),
1419
+ .label('MessageMailboxSpecialUse'),
1292
1420
  messageSpecialUse: messageSpecialUseSchema
1293
1421
  }).label('MessageDetails');
1294
1422
 
@@ -1685,7 +1813,7 @@ const expectedEmailSchema = Joi.string()
1685
1813
  const accountSchemas = {
1686
1814
  // The Document Store sync start date. Accepted and dropped since the feature's removal, so an
1687
1815
  // integration written against an older release keeps working
1688
- syncFrom: Joi.any().strip().description('Deprecated - Document Store feature has been removed').meta({ swaggerHidden: true }),
1816
+ syncFrom: deprecated(Joi.any().strip(), 'syncFrom'),
1689
1817
 
1690
1818
  notifyFrom: Joi.date()
1691
1819
  .iso()
@@ -1915,7 +2043,8 @@ const oauthCreateSchema = {
1915
2043
  })
1916
2044
  .example('externalAccount')
1917
2045
  .description('How the Gmail service account authenticates')
1918
- .meta({ enumDescriptions: ENUM_DESCRIPTIONS.gmailAuthMethod }),
2046
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.gmailAuthMethod })
2047
+ .label('OAuth2AppAuthMethod'),
1919
2048
 
1920
2049
  externalAccount: Joi.string()
1921
2050
  .trim()
@@ -2104,7 +2233,8 @@ const oauthUpdateSchema = {
2104
2233
  otherwise: Joi.forbidden()
2105
2234
  })
2106
2235
  .description('How the Gmail service account authenticates')
2107
- .meta({ enumDescriptions: ENUM_DESCRIPTIONS.gmailAuthMethod }),
2236
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.gmailAuthMethod })
2237
+ .label('OAuth2AppUpdateAuthMethod'),
2108
2238
 
2109
2239
  externalAccount: Joi.string()
2110
2240
  .trim()
@@ -2321,6 +2451,38 @@ const defaultAccountTypeSchema = Joi.string()
2321
2451
  .description('Pre-select a specific account type (use "imap" or an OAuth2 app ID) instead of showing the selection screen')
2322
2452
  .label('DefaultAccountType');
2323
2453
 
2454
+ // Per-protocol result block of a connection check - the IMAP and SMTP results carry the same
2455
+ // fields built by verifyAccountInfo, only labels, wording, and the server response example
2456
+ // differ. Shared by the account verification and the gateway verification responses
2457
+ const verifyResultSchema = (proto, responseTextExample) =>
2458
+ Joi.object({
2459
+ success: Joi.boolean().example(true).description(`Was ${proto.toUpperCase()} account verified`).label(`Verify${proto}Success`),
2460
+ error: Joi.string()
2461
+ .example('Something went wrong')
2462
+ .description(`Error messages for ${proto.toUpperCase()} verification. Only present if success=false`)
2463
+ .label(`Verify${proto}Error`),
2464
+ code: Joi.string().example('ERR_SSL_WRONG_VERSION_NUMBER').description('Error code. Only present if success=false').label(`Verify${proto}Code`),
2465
+ statusCode: Joi.number()
2466
+ .integer()
2467
+ .example(500)
2468
+ .description('HTTP-style status code for the error. Only present if success=false')
2469
+ .label(`Verify${proto}StatusCode`),
2470
+ responseText: Joi.string()
2471
+ .example(responseTextExample)
2472
+ .description('Server response for the failed verification. Only present if success=false')
2473
+ .label(`Verify${proto}ResponseText`)
2474
+ }).label(`Verify${proto}Result`);
2475
+
2476
+ /**
2477
+ * The free-text filter of a list endpoint, the same case-insensitive substring match the admin
2478
+ * list pages apply
2479
+ * @param {string} fields - What the text is matched against, for the description
2480
+ * @param {string} label - Schema label, distinct per endpoint
2481
+ * @returns {Object} Joi schema
2482
+ */
2483
+ const listQuerySchema = (fields, label) =>
2484
+ Joi.string().trim().empty('').max(256).example('example').description(`List only entries whose ${fields} contains this text, ignoring case`).label(label);
2485
+
2324
2486
  const outboxEntrySchema = Joi.object({
2325
2487
  queueId: Joi.string().example('1869c5692565f756b33').description('Unique queue entry identifier'),
2326
2488
  account: accountIdSchema.required(),
@@ -2359,7 +2521,8 @@ const outboxEntrySchema = Joi.object({
2359
2521
  .example('2021-02-17T13:43:18.860Z')
2360
2522
  .description(
2361
2523
  'Next delivery attempt time (approximate, computed from the retry backoff without jitter). False when all delivery attempts have been used up'
2362
- ),
2524
+ )
2525
+ .label('OutboxNextAttempt'),
2363
2526
 
2364
2527
  attemptsMade: Joi.number().integer().example(3).description('Number of delivery attempts made'),
2365
2528
  attempts: Joi.number().integer().example(3).description('Maximum delivery attempts before marking as failed'),
@@ -2408,7 +2571,7 @@ const outboxEntrySchema = Joi.object({
2408
2571
  // The Document Store was removed in 2.82.0. The request fields that selected it are still
2409
2572
  // accepted and dropped, so an integration written against an older release keeps working and a
2410
2573
  // 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 });
2574
+ const documentStoreSchema = deprecated(Joi.any().strip(), 'documentStore');
2412
2575
 
2413
2576
  const messageReferenceSchema = Joi.object({
2414
2577
  message: Joi.string()
@@ -2761,8 +2924,29 @@ function apiResponses(description, ...statusCodes) {
2761
2924
  return Object.assign({ 200: { description } }, errorResponses(...statusCodes));
2762
2925
  }
2763
2926
 
2927
+ // What DELETE /v1/account/{account} reports about revoking the OAuth2 grant, present only when
2928
+ // revoke was requested. Also the `info.revocation` of a revoke=required refusal
2929
+ const accountRevocationSchema = Joi.object({
2930
+ attempted: Joi.boolean().example(true).description('Whether the provider was asked to revoke the grant'),
2931
+ revoked: Joi.boolean().example(true).description('Whether the provider confirmed the revocation'),
2932
+ status: Joi.number().integer().example(200).description('HTTP status of the provider response, when one arrived'),
2933
+ reason: Joi.string()
2934
+ .valid('NotOAuth2', 'NoToken', 'AppNotFound', 'AppError', 'ServiceAccount', 'Unsupported', 'TokenInvalid', 'ProviderRefused', 'RequestFailed')
2935
+ .example('ProviderRefused')
2936
+ .label('AccountRevocationReason')
2937
+ .description(
2938
+ 'Why the grant was not revoked. NotOAuth2: not an OAuth2 account. NoToken: no stored token to revoke with. AppNotFound / AppError: the OAuth2 application is missing or could not be loaded. ServiceAccount: a Workspace service account, which has no per-user grant. Unsupported: the provider offers no revocation endpoint (Microsoft). TokenInvalid: the provider reports the token as already revoked or expired. ProviderRefused: the provider answered with an error. RequestFailed: no answer from the provider'
2939
+ ),
2940
+ error: Joi.string().example('invalid_request').description('OAuth2 error code the provider returned, or the network error code')
2941
+ })
2942
+ .description('Outcome of the OAuth2 grant revocation, included when revoke was requested')
2943
+ .label('AccountRevocation');
2944
+
2764
2945
  module.exports = {
2765
2946
  requireTlsSchema,
2947
+ messageOtpSchema,
2948
+ submitOtpSchema,
2949
+ accountRevocationSchema,
2766
2950
  apiBoolean,
2767
2951
  formBoolean,
2768
2952
  MAX_MESSAGE_ATTACHMENTS,
@@ -2817,6 +3001,8 @@ module.exports = {
2817
3001
  threadIdSchema,
2818
3002
  signedFormBlobFields,
2819
3003
  outboxEntrySchema,
3004
+ verifyResultSchema,
3005
+ listQuerySchema,
2820
3006
  googleProjectIdSchema,
2821
3007
  googleTopicNameSchema,
2822
3008
  googleSubscriptionNameSchema,
@@ -2831,7 +3017,5 @@ module.exports = {
2831
3017
  exportIdSchema,
2832
3018
  pubSubErrorSchema,
2833
3019
  apiResponses,
2834
- ENUM_DESCRIPTIONS,
2835
- IMAP_MAX_IDLE_TIME_MIN,
2836
- IMAP_MAX_IDLE_TIME_MAX
3020
+ ENUM_DESCRIPTIONS
2837
3021
  };
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 };
@@ -32,8 +32,8 @@ module.exports = {
32
32
 
33
33
  contact: {
34
34
  name: 'EmailEngine Support',
35
- url: 'https://learn.emailengine.app/docs/support',
36
- email: 'support@emailengine.app'
35
+ url: 'https://emailengine.app/support',
36
+ email: 'support@postalsys.com'
37
37
  },
38
38
 
39
39
  license: {
@@ -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
  },