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
@@ -0,0 +1,99 @@
1
+ 'use strict';
2
+
3
+ // The last step of the hosted account setup, shared by both arms of the form: the IMAP arm
4
+ // (POST /accounts/new/imap/server in ./account-routes.js) and the OAuth2 callback (GET /oauth in
5
+ // workers/api.js). Both claim the signed link's single-use nonce, create the account, give the
6
+ // nonce back when the create fails, and send the visitor on to the calling application or to the
7
+ // account page. The two copies this replaced had drifted apart: the OAuth2 one answered in
8
+ // untranslated English and built the account page link from the raw account ID.
9
+
10
+ const Boom = require('@hapi/boom');
11
+
12
+ const { redis } = require('../db');
13
+ const settings = require('../settings');
14
+ const { claimFormNonce, releaseFormNonce } = require('../tools');
15
+ const { adminUrl } = require('./route-helpers');
16
+
17
+ /**
18
+ * Where the visitor goes once the account exists: the calling application's redirect URL with the
19
+ * account ID and its state appended, or the account's admin page when the link named none.
20
+ *
21
+ * @param {string|undefined} redirectUrl - The redirect URL the signed link carried, resolved against `serviceUrl`
22
+ * @param {string|undefined} serviceUrl - The instance's Service URL
23
+ * @param {Object} result - What Account.create() returned (`account`, `state`)
24
+ * @returns {string}
25
+ */
26
+ function setupRedirectUrl(redirectUrl, serviceUrl, result) {
27
+ if (!redirectUrl) {
28
+ return adminUrl`/admin/accounts/${result.account}`;
29
+ }
30
+
31
+ const url = new URL(redirectUrl, serviceUrl);
32
+ url.searchParams.set('account', result.account);
33
+ url.searchParams.set('state', result.state);
34
+ return url.href;
35
+ }
36
+
37
+ /**
38
+ * Claims the link's nonce, creates the account and returns the URL to send the visitor to.
39
+ *
40
+ * The nonce is claimed BEFORE create (SET NX), so a concurrent double-submit, a replayed callback
41
+ * or one signed link spent on both arms (start OAuth2, then submit the same blob to the IMAP arm)
42
+ * cannot create a second account. A link with no nonce skips the claim: setup and re-auth links
43
+ * issued before nonces existed carry none, and the OAuth2 arm accepts them for that reason. When
44
+ * create() fails the nonce is released so the visitor can retry. Accepted residual: if Redis fails
45
+ * there too, the nonce stays consumed for its TTL and a fresh link is needed, the price of the
46
+ * claim-before-create ordering that makes the dedupe atomic.
47
+ *
48
+ * @param {Object} request - The Hapi request; its `app.gt` translates the refusals
49
+ * @param {Object} options
50
+ * @param {Object} options.accountObject - An Account instance to create the account with
51
+ * @param {Object} options.accountData - The account to create
52
+ * @param {Object} [options.nonce] - The signed link's nonce (`n`) and its timestamp (`t`)
53
+ * @param {string} [options.redirectUrl] - Where the calling application wants the visitor back
54
+ * @returns {Promise<string>} The URL to redirect the visitor to
55
+ */
56
+ async function completeAccountSetup(request, { accountObject, accountData, nonce, redirectUrl }) {
57
+ const gt = request.app.gt;
58
+
59
+ let nonceClaimed = false;
60
+ if (nonce && nonce.n) {
61
+ let claimed;
62
+ try {
63
+ claimed = await claimFormNonce(redis, nonce.n, nonce.t);
64
+ } catch (err) {
65
+ // A Redis failure is not a consumed nonce. Report it as a retryable server error
66
+ // instead of misdiagnosing a valid setup URL as invalid or expired.
67
+ request.logger.error({ msg: 'Failed to claim nonce for an account form request', err });
68
+ throw Boom.boomify(new Error(gt.gettext('Temporary error, please try again')), { statusCode: 500 });
69
+ }
70
+ if (!claimed) {
71
+ // SET NX returned null: the nonce key already exists, so this URL was already used.
72
+ //
73
+ // Reviewed, accepted (do not "fix" server-side): the LOSING side of a legitimate
74
+ // concurrent double-submit lands here and sees this 403 even though the winning request
75
+ // created the account. The client-side formSubmitting latch
76
+ // (views/accounts/register/imap-server.hbs) is the primary guard; the residual is a
77
+ // no-JS double-click, and even then this is strictly better than two duplicate
78
+ // accounts. Storing the created account ID under the nonce key and redirecting the
79
+ // loser to success is a possible future enhancement, not a bug.
80
+ throw Boom.boomify(new Error(gt.gettext('Invalid or expired account setup URL')), { statusCode: 403 });
81
+ }
82
+ nonceClaimed = true;
83
+ }
84
+
85
+ let result;
86
+ try {
87
+ result = await accountObject.create(accountData);
88
+ } catch (err) {
89
+ if (nonceClaimed) {
90
+ await releaseFormNonce(redis, nonce.n, request.logger);
91
+ }
92
+ throw err;
93
+ }
94
+
95
+ const serviceUrl = redirectUrl ? await settings.get('serviceUrl') : undefined;
96
+ return setupRedirectUrl(redirectUrl, serviceUrl, result);
97
+ }
98
+
99
+ module.exports = { completeAccountSetup, setupRedirectUrl };
@@ -6,7 +6,6 @@
6
6
  // getOpenAiError helper moved with the routes (only these config pages use them).
7
7
 
8
8
  const Joi = require('joi');
9
- const crypto = require('crypto');
10
9
  const config = require('@zone-eu/wild-config');
11
10
  const os = require('os');
12
11
  const packageData = require('../../package.json');
@@ -16,22 +15,11 @@ const { fetch: fetchCmd } = require('undici');
16
15
  const settings = require('../settings');
17
16
  const consts = require('../consts');
18
17
  const getSecret = require('../get-secret');
19
- const timezonesList = require('timezones-list').default;
18
+ const { timezoneOptions } = require('../timezones');
20
19
  const { Queue } = require('bullmq');
21
20
  const { redis, submitQueue, notifyQueue, queueConf, logBullErrors } = require('../db');
22
- const {
23
- getByteSize,
24
- formatByteSize,
25
- getDuration,
26
- failAction,
27
- readEnvValue,
28
- readEnvList,
29
- httpAgent,
30
- splitUrlCredentials,
31
- maybeReloadTlsCertificates
32
- } = require('../tools');
33
- const { validateWebhookTarget } = require('../webhook-egress');
34
- const { sendWebhookRequest } = require('../webhook-request');
21
+ const { getByteSize, formatByteSize, getDuration, failAction, readEnvValue, readEnvList, httpAgent, maybeReloadTlsCertificates } = require('../tools');
22
+ const { sendTestWebhook, testEventBody } = require('../webhook-test');
35
23
  const { llmPreProcess, buildSummaryInput, authenticationTrust } = require('../llm-pre-process');
36
24
  const { decodeHeaders } = require('../utils/decode-headers');
37
25
  const { mcpFeatureEnabled } = require('../mcp');
@@ -58,14 +46,19 @@ const { getOpenAiModels, reasoningEffortOptions, aiPageSchema, aiFieldSchema, ai
58
46
  const { DEFAULT_INSTRUCTIONS, DEFAULT_MODEL, DEFAULT_MAX_TOKENS } = require('@postalsys/email-ai-tools');
59
47
 
60
48
  const { registerSettingsPage } = require('./settings-page');
49
+ const { overridableFormValues, overridableSettingsFromForm, toFormValue, fromFormValue } = require('./overridable-fields');
50
+ const { writeOverridableSettings } = require('../env-setting-overrides');
61
51
 
62
52
  const {
63
53
  REDIS_PREFIX,
64
54
  DEFAULT_MAX_LOG_LINES,
65
55
  DEFAULT_DELIVERY_ATTEMPTS,
56
+ DEFAULT_WEBHOOK_ATTEMPTS,
57
+ DEFAULT_WEBHOOK_RETRY_DELAY,
58
+ MIN_WEBHOOK_RETRY_DELAY,
59
+ MAX_WEBHOOK_RETRY_DELAY,
66
60
  DEFAULT_MAX_BODY_SIZE,
67
61
  DEFAULT_MAX_PAYLOAD_TIMEOUT,
68
- NONCE_BYTES,
69
62
  DEFAULT_GMAIL_EXPORT_BATCH_SIZE,
70
63
  DEFAULT_OUTLOOK_EXPORT_BATCH_SIZE
71
64
  } = consts;
@@ -123,6 +116,7 @@ const configWebhooksSchema = {
123
116
  notifyHeaders: Joi.string().empty('').trim(),
124
117
  notifyText: formBoolean().default(false),
125
118
  notifyWebSafeHtml: formBoolean().default(false),
119
+ disableThreadCollapse: formBoolean().default(false),
126
120
 
127
121
  notifyTextSize: Joi.alternatives().try(
128
122
  Joi.number().empty('').integer().min(0),
@@ -158,7 +152,16 @@ const configWebhooksSchema = {
158
152
  .max(10 * 1024)
159
153
  .description('Custom request headers'),
160
154
 
161
- scriptEnv: settingsSchema.scriptEnv.default('')
155
+ scriptEnv: settingsSchema.scriptEnv.default(''),
156
+
157
+ webhooksDeliveryAttempts: settingsSchema.webhooksDeliveryAttempts,
158
+ // seconds on the form, milliseconds in the setting
159
+ webhooksRetryDelay: Joi.number()
160
+ .integer()
161
+ .empty('')
162
+ .allow(null)
163
+ .min(MIN_WEBHOOK_RETRY_DELAY / 1000)
164
+ .max(MAX_WEBHOOK_RETRY_DELAY / 1000)
162
165
  };
163
166
 
164
167
  for (let type of notificationTypes) {
@@ -203,9 +206,7 @@ async function getOpenAiError(gt) {
203
206
  return openAiError;
204
207
  }
205
208
 
206
- function init(args) {
207
- const { server, call } = args;
208
-
209
+ function registerConfigWebhooksPage(server) {
209
210
  registerSettingsPage(server, {
210
211
  path: '/admin/config/webhooks',
211
212
  view: 'config/webhooks',
@@ -226,6 +227,7 @@ function init(args) {
226
227
 
227
228
  const inboxNewOnly = (await settings.get('inboxNewOnly')) || false;
228
229
  const customHeaders = (await settings.get('webhooksCustomHeaders')) || [];
230
+ const { webhooksDeliveryAttempts, webhooksRetryDelay } = await settings.getMulti('webhooksDeliveryAttempts', 'webhooksRetryDelay');
229
231
 
230
232
  let webhooksEnabled = await settings.get('webhooksEnabled');
231
233
  let values = {
@@ -242,6 +244,7 @@ function init(args) {
242
244
  .join('\n'),
243
245
  notifyText,
244
246
  notifyWebSafeHtml,
247
+ ...(await overridableFormValues('disableThreadCollapse')),
245
248
  notifyTextSize: notifyTextSize ? formatByteSize(notifyTextSize) : '',
246
249
  notifyCalendarEvents,
247
250
 
@@ -253,7 +256,10 @@ function init(args) {
253
256
  .map(entry => `${entry.key}: ${entry.value}`.trim())
254
257
  .join('\n'),
255
258
 
256
- scriptEnv: (await settings.get('scriptEnv')) || ''
259
+ scriptEnv: (await settings.get('scriptEnv')) || '',
260
+
261
+ webhooksDeliveryAttempts: webhooksDeliveryAttempts || '',
262
+ webhooksRetryDelay: (Number(webhooksRetryDelay) && toFormValue('webhooksRetryDelay', Number(webhooksRetryDelay))) || ''
257
263
  };
258
264
 
259
265
  // per-event checkbox states under their form field names, so the GET render
@@ -267,6 +273,8 @@ function init(args) {
267
273
 
268
274
  async viewContext(request, values) {
269
275
  return {
276
+ defaultWebhookAttempts: DEFAULT_WEBHOOK_ATTEMPTS,
277
+ defaultWebhookRetryDelay: DEFAULT_WEBHOOK_RETRY_DELAY / 1000,
270
278
  notificationTypes: notificationTypes.map(type =>
271
279
  Object.assign({}, type, { checked: !!values[`notify_${type.name}`], isMessageNew: type.name === 'messageNew' })
272
280
  ),
@@ -281,6 +289,7 @@ function init(args) {
281
289
  webhooks: request.payload.webhooks,
282
290
  notifyText: request.payload.notifyText,
283
291
  notifyWebSafeHtml: request.payload.notifyWebSafeHtml,
292
+ ...overridableSettingsFromForm(request.payload, 'disableThreadCollapse'),
284
293
  notifyTextSize: request.payload.notifyTextSize || 0,
285
294
  notifyCalendarEvents: request.payload.notifyCalendarEvents,
286
295
 
@@ -291,6 +300,10 @@ function init(args) {
291
300
 
292
301
  scriptEnv: request.payload.scriptEnv,
293
302
 
303
+ // a cleared field falls back to the built-in policy
304
+ webhooksDeliveryAttempts: request.payload.webhooksDeliveryAttempts || null,
305
+ webhooksRetryDelay: request.payload.webhooksRetryDelay ? fromFormValue('webhooksRetryDelay', request.payload.webhooksRetryDelay) : null,
306
+
294
307
  webhookEvents: notificationTypes.filter(type => !!request.payload[`notify_${type.name}`]).map(type => type.name),
295
308
  notifyHeaders: (request.payload.notifyHeaders || '')
296
309
  .split(/\r?\n/)
@@ -311,7 +324,7 @@ function init(args) {
311
324
  data.notifyHeaders.push('*');
312
325
  }
313
326
 
314
- await settings.setMulti(data);
327
+ await writeOverridableSettings(data);
315
328
 
316
329
  if (!data.webhooksEnabled) {
317
330
  // clear error message (if exists)
@@ -319,6 +332,10 @@ function init(args) {
319
332
  }
320
333
  }
321
334
  });
335
+ }
336
+
337
+ function registerConfigServicePage(server, args) {
338
+ const { call } = args;
322
339
 
323
340
  registerSettingsPage(server, {
324
341
  path: '/admin/config/service',
@@ -328,6 +345,12 @@ function init(args) {
328
345
  schema: {
329
346
  serviceUrl: settingsSchema.serviceUrl,
330
347
  queueKeep: settingsSchema.queueKeep.default(0),
348
+ // Days and megabytes on the form, seconds and bytes in the settings; blank clears the
349
+ // setting, so the environment or the default applies again
350
+ queueKeepFailed: settingsSchema.queueKeepFailed.allow(null).default(null),
351
+ queueKeepFailedAge: Joi.number().empty('').positive().precision(2).allow(null).default(null),
352
+ queueKeepFailedContent: settingsSchema.queueKeepFailedContent.allow(null).default(null),
353
+ queueKeepFailedContentSize: Joi.number().empty('').min(0).precision(2).allow(null).default(null),
331
354
  enableApiProxy: settingsSchema.enableApiProxy.default(false),
332
355
 
333
356
  locale: settingsSchema.locale
@@ -344,6 +367,7 @@ function init(args) {
344
367
  return {
345
368
  serviceUrl: storedValues.serviceUrl || null,
346
369
  queueKeep: storedValues.queueKeep || 0,
370
+ ...(await overridableFormValues('queueKeepFailed', 'queueKeepFailedAge', 'queueKeepFailedContent', 'queueKeepFailedContentSize')),
347
371
  enableApiProxy: storedValues.enableApiProxy || false,
348
372
 
349
373
  locale: storedValues.locale || false,
@@ -355,17 +379,20 @@ function init(args) {
355
379
  return {
356
380
  locales: locales.map(locale => Object.assign({ selected: locale.locale === values.locale }, locale)),
357
381
 
358
- timezones: timezonesList.map(entry => ({
359
- name: entry.label,
360
- timezone: entry.tzCode,
361
- selected: entry.tzCode === values.timezone
362
- }))
382
+ timezones: timezoneOptions(values.timezone)
363
383
  };
364
384
  },
365
385
 
366
386
  async applySettings(request) {
367
387
  let data = {
368
388
  queueKeep: request.payload.queueKeep,
389
+ ...overridableSettingsFromForm(
390
+ request.payload,
391
+ 'queueKeepFailed',
392
+ 'queueKeepFailedAge',
393
+ 'queueKeepFailedContent',
394
+ 'queueKeepFailedContentSize'
395
+ ),
369
396
  enableApiProxy: request.payload.enableApiProxy,
370
397
  locale: request.payload.locale,
371
398
  timezone: request.payload.timezone
@@ -375,12 +402,20 @@ function init(args) {
375
402
  // write would leave the old URL in place after a save meant to clear it
376
403
  data.serviceUrl = request.payload.serviceUrl ? new URL(request.payload.serviceUrl).origin : null;
377
404
 
405
+ // While no timezone is stored the select starts on a blank "Not set" choice, and saving it
406
+ // leaves the setting alone: the next admin page load fills it in from the browser
407
+ // (/admin/config/browser). Without that choice the select started on the first zone in
408
+ // the list, and saving the page before the browser had reported stored Pacific/Midway
409
+ if (!data.timezone) {
410
+ delete data.timezone;
411
+ }
412
+
378
413
  // Compared before the write, and only for the reload: this form submits the service URL
379
414
  // on every save, so reloading on the write alone would hand three listeners a new
380
415
  // certificate every time somebody changed the timezone.
381
416
  const serviceUrlChanged = data.serviceUrl !== (await settings.get('serviceUrl'));
382
417
 
383
- await settings.setMulti(data);
418
+ await writeOverridableSettings(data);
384
419
 
385
420
  // The service URL names the first hostname EmailEngine serves TLS for, so changing it
386
421
  // here changes what the listeners have to offer exactly as the TLS page's own hostname
@@ -389,7 +424,9 @@ function init(args) {
389
424
  await maybeReloadTlsCertificates(call, request.logger, serviceUrlChanged ? ['serviceUrl'] : [], { action: 'settings' });
390
425
  }
391
426
  });
427
+ }
392
428
 
429
+ function registerConfigSecurityPage(server) {
393
430
  registerSettingsPage(server, {
394
431
  path: '/admin/config/security',
395
432
  view: 'config/security',
@@ -399,6 +436,9 @@ function init(args) {
399
436
  serviceSecret: settingsSchema.serviceSecret,
400
437
  ignoreMailCertErrors: settingsSchema.ignoreMailCertErrors.default(false),
401
438
  tokenAuditLog: settingsSchema.tokenAuditLog.default(false),
439
+ tokenLogEntries: settingsSchema.tokenLogEntries.allow(null).default(null),
440
+ // days on the form, seconds in the setting
441
+ tokenLogAge: Joi.number().empty('').positive().precision(2).allow(null).default(null),
402
442
 
403
443
  // Following options can only be changed via the UI
404
444
  enableOAuthTokensApi: formBoolean().description('If true, then allow using using the OAuth tokens API endpoint').default(false),
@@ -409,6 +449,7 @@ function init(args) {
409
449
  const storedValues = await settings.getMulti('serviceSecret', 'disableTokens', 'enableOAuthTokensApi', 'ignoreMailCertErrors', 'tokenAuditLog');
410
450
 
411
451
  return {
452
+ ...(await overridableFormValues('tokenLogEntries', 'tokenLogAge')),
412
453
  serviceSecret: storedValues.serviceSecret || null,
413
454
  enableTokens: !storedValues.disableTokens,
414
455
  enableOAuthTokensApi: storedValues.enableOAuthTokensApi || false,
@@ -429,7 +470,8 @@ function init(args) {
429
470
  disableTokens: !request.payload.enableTokens,
430
471
  enableOAuthTokensApi: request.payload.enableOAuthTokensApi,
431
472
  ignoreMailCertErrors: request.payload.ignoreMailCertErrors,
432
- tokenAuditLog: request.payload.tokenAuditLog
473
+ tokenAuditLog: request.payload.tokenAuditLog,
474
+ ...overridableSettingsFromForm(request.payload, 'tokenLogEntries', 'tokenLogAge')
433
475
  };
434
476
 
435
477
  // Only overwrite the service secret when a non-empty value is provided: an empty
@@ -443,10 +485,12 @@ function init(args) {
443
485
  await request.flash({ type: 'warning', message: `Service secret was left unchanged - type a new value to rotate it` });
444
486
  }
445
487
 
446
- await settings.setMulti(data);
488
+ await writeOverridableSettings(data);
447
489
  }
448
490
  });
491
+ }
449
492
 
493
+ function registerConfigEmailProcessingPage(server) {
450
494
  registerSettingsPage(server, {
451
495
  path: '/admin/config/email-processing',
452
496
  view: 'config/email-processing',
@@ -537,7 +581,9 @@ function init(args) {
537
581
  });
538
582
  }
539
583
  });
584
+ }
540
585
 
586
+ function registerConfigBrandingPage(server) {
541
587
  registerSettingsPage(server, {
542
588
  path: '/admin/config/branding',
543
589
  view: 'config/branding',
@@ -567,7 +613,9 @@ function init(args) {
567
613
  });
568
614
  }
569
615
  });
616
+ }
570
617
 
618
+ function registerConfigMcpPage(server) {
571
619
  registerSettingsPage(server, {
572
620
  path: '/admin/config/mcp',
573
621
  view: 'config/mcp',
@@ -684,7 +732,9 @@ function init(args) {
684
732
  });
685
733
  }
686
734
  });
735
+ }
687
736
 
737
+ function registerConfigAiPage(server) {
688
738
  registerSettingsPage(server, {
689
739
  path: '/admin/config/ai',
690
740
  view: 'config/ai',
@@ -773,6 +823,10 @@ function init(args) {
773
823
  }
774
824
  }
775
825
  });
826
+ }
827
+
828
+ function registerPostConfigAiTestPrompt(server, args) {
829
+ const { call } = args;
776
830
 
777
831
  server.route({
778
832
  method: 'POST',
@@ -839,6 +893,10 @@ function init(args) {
839
893
  }
840
894
  }
841
895
  });
896
+ }
897
+
898
+ function registerPostConfigAiReloadModels(server, args) {
899
+ const { call } = args;
842
900
 
843
901
  server.route({
844
902
  method: 'POST',
@@ -892,7 +950,9 @@ function init(args) {
892
950
  }
893
951
  }
894
952
  });
953
+ }
895
954
 
955
+ function registerPostConfigBrandingPreview(server) {
896
956
  server.route({
897
957
  method: 'POST',
898
958
  path: '/admin/config/branding/preview',
@@ -930,7 +990,9 @@ function init(args) {
930
990
  }
931
991
  }
932
992
  });
993
+ }
933
994
 
995
+ function registerPostConfigClearError(server) {
934
996
  server.route({
935
997
  method: 'POST',
936
998
  path: '/admin/config/clear-error',
@@ -989,7 +1051,9 @@ function init(args) {
989
1051
  }
990
1052
  }
991
1053
  });
1054
+ }
992
1055
 
1056
+ function registerPostConfigServiceClean(server) {
993
1057
  server.route({
994
1058
  method: 'POST',
995
1059
  path: '/admin/config/service/clean',
@@ -1024,7 +1088,9 @@ function init(args) {
1024
1088
  }
1025
1089
  }
1026
1090
  });
1091
+ }
1027
1092
 
1093
+ function registerConfigLoggingPage(server) {
1028
1094
  registerSettingsPage(server, {
1029
1095
  path: '/admin/config/logging',
1030
1096
  view: 'config/logging',
@@ -1077,6 +1143,10 @@ function init(args) {
1077
1143
  await settings.setMulti(data);
1078
1144
  }
1079
1145
  });
1146
+ }
1147
+
1148
+ function registerPostConfigLoggingReconnect(server, args) {
1149
+ const { call } = args;
1080
1150
 
1081
1151
  server.route({
1082
1152
  method: 'POST',
@@ -1124,16 +1194,13 @@ function init(args) {
1124
1194
  }
1125
1195
  }
1126
1196
  });
1197
+ }
1127
1198
 
1199
+ function registerPostConfigWebhooksTest(server) {
1128
1200
  server.route({
1129
1201
  method: 'POST',
1130
1202
  path: '/admin/config/webhooks/test',
1131
1203
  async handler(request) {
1132
- let headers = {
1133
- 'Content-Type': 'application/json',
1134
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
1135
- };
1136
-
1137
1204
  const webhooks = request.payload.webhooks;
1138
1205
  if (!webhooks) {
1139
1206
  return {
@@ -1143,72 +1210,17 @@ function init(args) {
1143
1210
  };
1144
1211
  }
1145
1212
 
1146
- let { url: parsed, authorization } = splitUrlCredentials(webhooks);
1147
- if (authorization) {
1148
- headers.Authorization = authorization;
1149
- }
1150
-
1151
- let customHeaders = parseCustomHeaders(request.payload.customHeaders);
1152
-
1153
- customHeaders.forEach(header => {
1154
- headers[header.key] = header.value;
1213
+ // The same request a delivery makes, through the same function and dispatcher, rather
1214
+ // than a lookalike: a probe that reimplements delivery can only prove that the
1215
+ // reimplementation works
1216
+ const result = await sendTestWebhook({
1217
+ url: webhooks,
1218
+ customHeaders: parseCustomHeaders(request.payload.customHeaders),
1219
+ body: request.payload.payload || testEventBody(await settings.get('serviceUrl')),
1220
+ logger: request.logger
1155
1221
  });
1156
1222
 
1157
- let start = Date.now();
1158
- let duration;
1159
- try {
1160
- let serviceUrl = await settings.get('serviceUrl');
1161
-
1162
- // The same call the notify worker makes, rather than a lookalike: a probe that
1163
- // reimplements delivery can only prove that the reimplementation works. It also
1164
- // inherits the delivery timeout and the response drain, both of which this route
1165
- // used to do without while running on the same keep-alive retry dispatcher.
1166
- try {
1167
- await sendWebhookRequest(fetchCmd, parsed.toString(), {
1168
- method: 'post',
1169
- body:
1170
- request.payload.payload ||
1171
- JSON.stringify({
1172
- serviceUrl,
1173
- account: null,
1174
- date: new Date().toISOString(),
1175
- event: 'test',
1176
- data: {
1177
- nonce: crypto.randomBytes(NONCE_BYTES).toString('base64url')
1178
- }
1179
- }),
1180
- headers,
1181
- dispatcher: httpAgent.webhook,
1182
- validateTarget: validateWebhookTarget
1183
- });
1184
- duration = Date.now() - start;
1185
- } catch (err) {
1186
- duration = Date.now() - start;
1187
- // undici wraps a connection failure in a generic "fetch failed"; the cause is
1188
- // the part worth reporting back to the operator
1189
- throw err.cause || err;
1190
- }
1191
-
1192
- return {
1193
- success: true,
1194
- target: webhooks,
1195
- duration
1196
- };
1197
- } catch (err) {
1198
- // log the parsed URL, not the raw payload value, so embedded basic-auth credentials
1199
- // stay out of the log
1200
- request.logger.warn({ msg: 'Failed to post test webhook', webhooks: parsed.toString(), event: 'test', err });
1201
- return {
1202
- success: false,
1203
- target: webhooks,
1204
- duration,
1205
- error: err.message,
1206
- code: err.code,
1207
- // Same field the stored webhookErrorFlag carries, so the probe and the error
1208
- // block on this page describe a failed delivery the same way
1209
- statusCode: err.statusCode
1210
- };
1211
- }
1223
+ return Object.assign({ target: webhooks }, result);
1212
1224
  },
1213
1225
  options: {
1214
1226
  tags: ['test'],
@@ -1245,8 +1257,12 @@ function init(args) {
1245
1257
  }
1246
1258
  }
1247
1259
  });
1260
+ }
1248
1261
 
1249
- // Webhook, template, gateway, and token routes are in admin-entities-routes.js
1262
+ // Webhook, template, gateway, and token routes are in admin-entities-routes.js
1263
+
1264
+ function registerGetConfigLicense(server, args) {
1265
+ const { call } = args;
1250
1266
 
1251
1267
  server.route({
1252
1268
  method: 'GET',
@@ -1282,6 +1298,10 @@ function init(args) {
1282
1298
  );
1283
1299
  }
1284
1300
  });
1301
+ }
1302
+
1303
+ function registerPostConfigLicense(server, args) {
1304
+ const { call } = args;
1285
1305
 
1286
1306
  server.route({
1287
1307
  method: 'POST',
@@ -1381,6 +1401,10 @@ function init(args) {
1381
1401
  }
1382
1402
  }
1383
1403
  });
1404
+ }
1405
+
1406
+ function registerPostConfigLicenseDelete(server, args) {
1407
+ const { call } = args;
1384
1408
 
1385
1409
  server.route({
1386
1410
  method: 'POST',
@@ -1422,6 +1446,10 @@ function init(args) {
1422
1446
  }
1423
1447
  }
1424
1448
  });
1449
+ }
1450
+
1451
+ function registerPostConfigLicenseTrial(server, args) {
1452
+ const { call } = args;
1425
1453
 
1426
1454
  server.route({
1427
1455
  method: 'POST',
@@ -1499,4 +1527,28 @@ ${Buffer.from(data.content, 'base64url').toString('base64')}
1499
1527
  });
1500
1528
  }
1501
1529
 
1530
+ function init(args) {
1531
+ const { server } = args;
1532
+
1533
+ registerConfigWebhooksPage(server);
1534
+ registerConfigServicePage(server, args);
1535
+ registerConfigSecurityPage(server);
1536
+ registerConfigEmailProcessingPage(server);
1537
+ registerConfigBrandingPage(server);
1538
+ registerConfigMcpPage(server);
1539
+ registerConfigAiPage(server);
1540
+ registerPostConfigAiTestPrompt(server, args);
1541
+ registerPostConfigAiReloadModels(server, args);
1542
+ registerPostConfigBrandingPreview(server);
1543
+ registerPostConfigClearError(server);
1544
+ registerPostConfigServiceClean(server);
1545
+ registerConfigLoggingPage(server);
1546
+ registerPostConfigLoggingReconnect(server, args);
1547
+ registerPostConfigWebhooksTest(server);
1548
+ registerGetConfigLicense(server, args);
1549
+ registerPostConfigLicense(server, args);
1550
+ registerPostConfigLicenseDelete(server, args);
1551
+ registerPostConfigLicenseTrial(server, args);
1552
+ }
1553
+
1502
1554
  module.exports = init;