emailengine-app 2.85.0 → 2.86.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +74 -0
  4. package/Dockerfile +14 -1
  5. package/ENVIRONMENT.md +139 -0
  6. package/README.md +1 -1
  7. package/config/default.toml +2 -0
  8. package/copy-static-files.sh +4 -2
  9. package/data/google-crawlers.json +1 -1
  10. package/data/public_suffix_list.dat +4 -3
  11. package/lib/account-assignment.js +19 -0
  12. package/lib/account.js +194 -165
  13. package/lib/api-error-codes.js +49 -0
  14. package/lib/api-reference/model.js +6 -1
  15. package/lib/api-routes/account-routes.js +78 -26
  16. package/lib/api-routes/blocklist-routes.js +68 -2
  17. package/lib/api-routes/delivery-test-routes.js +1 -1
  18. package/lib/api-routes/gateway-routes.js +82 -10
  19. package/lib/api-routes/index.js +4 -0
  20. package/lib/api-routes/license-routes.js +2 -2
  21. package/lib/api-routes/mailbox-routes.js +3 -3
  22. package/lib/api-routes/message-routes.js +15 -7
  23. package/lib/api-routes/oauth2-app-routes.js +15 -8
  24. package/lib/api-routes/outbox-routes.js +77 -66
  25. package/lib/api-routes/permission-map.js +55 -6
  26. package/lib/api-routes/scoped-routes.js +74 -0
  27. package/lib/api-routes/settings-routes.js +11 -4
  28. package/lib/api-routes/stats-routes.js +5 -1
  29. package/lib/api-routes/submit-routes.js +4 -3
  30. package/lib/api-routes/template-routes.js +7 -6
  31. package/lib/api-routes/token-routes.js +11 -5
  32. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  33. package/lib/api-routes/webhook-route-routes.js +119 -4
  34. package/lib/calendar-event.js +81 -1
  35. package/lib/consts.js +38 -46
  36. package/lib/db.js +14 -6
  37. package/lib/delivery-error.js +6 -0
  38. package/lib/deprecations.js +270 -0
  39. package/lib/email-client/base-client.js +130 -156
  40. package/lib/email-client/fallback-poll.js +62 -0
  41. package/lib/email-client/gmail-client.js +51 -11
  42. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  43. package/lib/email-client/imap/adaptive-idle.js +278 -0
  44. package/lib/email-client/imap/connection-errors.js +14 -1
  45. package/lib/email-client/imap/idle-settings.js +31 -5
  46. package/lib/email-client/imap/listing-diff.js +37 -0
  47. package/lib/email-client/imap/mailbox.js +372 -226
  48. package/lib/email-client/imap/subconnection.js +7 -29
  49. package/lib/email-client/imap/sync-operations.js +220 -127
  50. package/lib/email-client/imap-client.js +227 -163
  51. package/lib/email-client/message-builder.js +14 -79
  52. package/lib/email-client/outlook-client.js +372 -338
  53. package/lib/email-client/smtp-pool-manager.js +16 -13
  54. package/lib/email-client/sync-state-fields.js +19 -0
  55. package/lib/encrypt.js +157 -41
  56. package/lib/enum-descriptions.js +3 -1
  57. package/lib/env-setting-overrides.js +288 -0
  58. package/lib/export-worker.js +751 -0
  59. package/lib/export.js +64 -15
  60. package/lib/gateway.js +17 -1
  61. package/lib/get-raw-email.js +25 -107
  62. package/lib/health.js +75 -0
  63. package/lib/lock-run.js +119 -0
  64. package/lib/logger-consts.js +48 -0
  65. package/lib/logger.js +1 -1
  66. package/lib/lua/z-head-scores.lua +28 -0
  67. package/lib/network-errors.js +1 -1
  68. package/lib/node-version.js +24 -0
  69. package/lib/notify-attachments.js +20 -1
  70. package/lib/oauth2-apps.js +630 -655
  71. package/lib/outbox.js +184 -54
  72. package/lib/parse-message.js +3 -3
  73. package/lib/privileged-settings.js +2 -2
  74. package/lib/queue-browser/definitions.js +11 -0
  75. package/lib/queue-browser/index.js +68 -19
  76. package/lib/queue-job-actions.js +18 -1
  77. package/lib/queue-retention.js +48 -12
  78. package/lib/queue-stats.js +11 -2
  79. package/lib/read-env-value.js +3 -0
  80. package/lib/redis-memory-warnings.js +99 -0
  81. package/lib/redis-reconnect.js +29 -0
  82. package/lib/request-timing.js +23 -0
  83. package/lib/respawn-backoff.js +35 -0
  84. package/lib/rewrite-text-nodes.js +19 -59
  85. package/lib/schemas.js +163 -39
  86. package/lib/settings.js +6 -2
  87. package/lib/smtp-auth.js +19 -1
  88. package/lib/thread-diagnostics.js +18 -1
  89. package/lib/tls/provision.js +6 -3
  90. package/lib/token-audit-log.js +19 -20
  91. package/lib/token-permission-view.js +4 -3
  92. package/lib/tools.js +8 -41
  93. package/lib/ui-routes/admin-config-routes.js +64 -90
  94. package/lib/ui-routes/admin-entities-routes.js +2 -14
  95. package/lib/ui-routes/imap-idle-field.js +1 -1
  96. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  97. package/lib/ui-routes/overridable-fields.js +84 -0
  98. package/lib/ui-routes/queue-routes.js +8 -5
  99. package/lib/ui-routes/settings-page.js +6 -0
  100. package/lib/utils/decode-headers.js +3 -12
  101. package/lib/utils/filter-empty.js +20 -0
  102. package/lib/utils/int-setting.js +48 -0
  103. package/lib/utils/tracking-settings.js +35 -0
  104. package/lib/web-safe-html.js +18 -105
  105. package/lib/webhook-delivery.js +461 -0
  106. package/lib/webhook-failures.js +132 -0
  107. package/lib/webhook-request.js +29 -1
  108. package/lib/webhook-routing.js +30 -1
  109. package/lib/webhook-test.js +88 -0
  110. package/lib/webhooks.js +54 -41
  111. package/lib/worker-rpc-error.js +2 -1
  112. package/package.json +21 -20
  113. package/sbom.json +304 -382
  114. package/server.js +149 -76
  115. package/static/js/ace/ace.js +1 -1
  116. package/static/licenses.html +21 -31
  117. package/translations/messages.pot +26 -26
  118. package/views/config/security.hbs +22 -0
  119. package/views/config/service.hbs +44 -0
  120. package/views/config/webhooks.hbs +36 -0
  121. package/views/partials/queue_retention_note.hbs +12 -8
  122. package/views/partials/ui/env-managed-alert.hbs +16 -7
  123. package/workers/api.js +102 -28
  124. package/workers/export.js +16 -631
  125. package/workers/imap.js +13 -0
  126. package/workers/smtp.js +9 -11
  127. package/workers/webhooks.js +18 -432
  128. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -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');
@@ -19,19 +18,8 @@ const getSecret = require('../get-secret');
19
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) {
@@ -224,6 +227,7 @@ function registerConfigWebhooksPage(server) {
224
227
 
225
228
  const inboxNewOnly = (await settings.get('inboxNewOnly')) || false;
226
229
  const customHeaders = (await settings.get('webhooksCustomHeaders')) || [];
230
+ const { webhooksDeliveryAttempts, webhooksRetryDelay } = await settings.getMulti('webhooksDeliveryAttempts', 'webhooksRetryDelay');
227
231
 
228
232
  let webhooksEnabled = await settings.get('webhooksEnabled');
229
233
  let values = {
@@ -240,6 +244,7 @@ function registerConfigWebhooksPage(server) {
240
244
  .join('\n'),
241
245
  notifyText,
242
246
  notifyWebSafeHtml,
247
+ ...(await overridableFormValues('disableThreadCollapse')),
243
248
  notifyTextSize: notifyTextSize ? formatByteSize(notifyTextSize) : '',
244
249
  notifyCalendarEvents,
245
250
 
@@ -251,7 +256,10 @@ function registerConfigWebhooksPage(server) {
251
256
  .map(entry => `${entry.key}: ${entry.value}`.trim())
252
257
  .join('\n'),
253
258
 
254
- scriptEnv: (await settings.get('scriptEnv')) || ''
259
+ scriptEnv: (await settings.get('scriptEnv')) || '',
260
+
261
+ webhooksDeliveryAttempts: webhooksDeliveryAttempts || '',
262
+ webhooksRetryDelay: (Number(webhooksRetryDelay) && toFormValue('webhooksRetryDelay', Number(webhooksRetryDelay))) || ''
255
263
  };
256
264
 
257
265
  // per-event checkbox states under their form field names, so the GET render
@@ -265,6 +273,8 @@ function registerConfigWebhooksPage(server) {
265
273
 
266
274
  async viewContext(request, values) {
267
275
  return {
276
+ defaultWebhookAttempts: DEFAULT_WEBHOOK_ATTEMPTS,
277
+ defaultWebhookRetryDelay: DEFAULT_WEBHOOK_RETRY_DELAY / 1000,
268
278
  notificationTypes: notificationTypes.map(type =>
269
279
  Object.assign({}, type, { checked: !!values[`notify_${type.name}`], isMessageNew: type.name === 'messageNew' })
270
280
  ),
@@ -279,6 +289,7 @@ function registerConfigWebhooksPage(server) {
279
289
  webhooks: request.payload.webhooks,
280
290
  notifyText: request.payload.notifyText,
281
291
  notifyWebSafeHtml: request.payload.notifyWebSafeHtml,
292
+ ...overridableSettingsFromForm(request.payload, 'disableThreadCollapse'),
282
293
  notifyTextSize: request.payload.notifyTextSize || 0,
283
294
  notifyCalendarEvents: request.payload.notifyCalendarEvents,
284
295
 
@@ -289,6 +300,10 @@ function registerConfigWebhooksPage(server) {
289
300
 
290
301
  scriptEnv: request.payload.scriptEnv,
291
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
+
292
307
  webhookEvents: notificationTypes.filter(type => !!request.payload[`notify_${type.name}`]).map(type => type.name),
293
308
  notifyHeaders: (request.payload.notifyHeaders || '')
294
309
  .split(/\r?\n/)
@@ -309,7 +324,7 @@ function registerConfigWebhooksPage(server) {
309
324
  data.notifyHeaders.push('*');
310
325
  }
311
326
 
312
- await settings.setMulti(data);
327
+ await writeOverridableSettings(data);
313
328
 
314
329
  if (!data.webhooksEnabled) {
315
330
  // clear error message (if exists)
@@ -330,6 +345,12 @@ function registerConfigServicePage(server, args) {
330
345
  schema: {
331
346
  serviceUrl: settingsSchema.serviceUrl,
332
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),
333
354
  enableApiProxy: settingsSchema.enableApiProxy.default(false),
334
355
 
335
356
  locale: settingsSchema.locale
@@ -346,6 +367,7 @@ function registerConfigServicePage(server, args) {
346
367
  return {
347
368
  serviceUrl: storedValues.serviceUrl || null,
348
369
  queueKeep: storedValues.queueKeep || 0,
370
+ ...(await overridableFormValues('queueKeepFailed', 'queueKeepFailedAge', 'queueKeepFailedContent', 'queueKeepFailedContentSize')),
349
371
  enableApiProxy: storedValues.enableApiProxy || false,
350
372
 
351
373
  locale: storedValues.locale || false,
@@ -364,6 +386,13 @@ function registerConfigServicePage(server, args) {
364
386
  async applySettings(request) {
365
387
  let data = {
366
388
  queueKeep: request.payload.queueKeep,
389
+ ...overridableSettingsFromForm(
390
+ request.payload,
391
+ 'queueKeepFailed',
392
+ 'queueKeepFailedAge',
393
+ 'queueKeepFailedContent',
394
+ 'queueKeepFailedContentSize'
395
+ ),
367
396
  enableApiProxy: request.payload.enableApiProxy,
368
397
  locale: request.payload.locale,
369
398
  timezone: request.payload.timezone
@@ -386,7 +415,7 @@ function registerConfigServicePage(server, args) {
386
415
  // certificate every time somebody changed the timezone.
387
416
  const serviceUrlChanged = data.serviceUrl !== (await settings.get('serviceUrl'));
388
417
 
389
- await settings.setMulti(data);
418
+ await writeOverridableSettings(data);
390
419
 
391
420
  // The service URL names the first hostname EmailEngine serves TLS for, so changing it
392
421
  // here changes what the listeners have to offer exactly as the TLS page's own hostname
@@ -407,6 +436,9 @@ function registerConfigSecurityPage(server) {
407
436
  serviceSecret: settingsSchema.serviceSecret,
408
437
  ignoreMailCertErrors: settingsSchema.ignoreMailCertErrors.default(false),
409
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),
410
442
 
411
443
  // Following options can only be changed via the UI
412
444
  enableOAuthTokensApi: formBoolean().description('If true, then allow using using the OAuth tokens API endpoint').default(false),
@@ -417,6 +449,7 @@ function registerConfigSecurityPage(server) {
417
449
  const storedValues = await settings.getMulti('serviceSecret', 'disableTokens', 'enableOAuthTokensApi', 'ignoreMailCertErrors', 'tokenAuditLog');
418
450
 
419
451
  return {
452
+ ...(await overridableFormValues('tokenLogEntries', 'tokenLogAge')),
420
453
  serviceSecret: storedValues.serviceSecret || null,
421
454
  enableTokens: !storedValues.disableTokens,
422
455
  enableOAuthTokensApi: storedValues.enableOAuthTokensApi || false,
@@ -437,7 +470,8 @@ function registerConfigSecurityPage(server) {
437
470
  disableTokens: !request.payload.enableTokens,
438
471
  enableOAuthTokensApi: request.payload.enableOAuthTokensApi,
439
472
  ignoreMailCertErrors: request.payload.ignoreMailCertErrors,
440
- tokenAuditLog: request.payload.tokenAuditLog
473
+ tokenAuditLog: request.payload.tokenAuditLog,
474
+ ...overridableSettingsFromForm(request.payload, 'tokenLogEntries', 'tokenLogAge')
441
475
  };
442
476
 
443
477
  // Only overwrite the service secret when a non-empty value is provided: an empty
@@ -451,7 +485,7 @@ function registerConfigSecurityPage(server) {
451
485
  await request.flash({ type: 'warning', message: `Service secret was left unchanged - type a new value to rotate it` });
452
486
  }
453
487
 
454
- await settings.setMulti(data);
488
+ await writeOverridableSettings(data);
455
489
  }
456
490
  });
457
491
  }
@@ -1167,11 +1201,6 @@ function registerPostConfigWebhooksTest(server) {
1167
1201
  method: 'POST',
1168
1202
  path: '/admin/config/webhooks/test',
1169
1203
  async handler(request) {
1170
- let headers = {
1171
- 'Content-Type': 'application/json',
1172
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
1173
- };
1174
-
1175
1204
  const webhooks = request.payload.webhooks;
1176
1205
  if (!webhooks) {
1177
1206
  return {
@@ -1181,72 +1210,17 @@ function registerPostConfigWebhooksTest(server) {
1181
1210
  };
1182
1211
  }
1183
1212
 
1184
- let { url: parsed, authorization } = splitUrlCredentials(webhooks);
1185
- if (authorization) {
1186
- headers.Authorization = authorization;
1187
- }
1188
-
1189
- let customHeaders = parseCustomHeaders(request.payload.customHeaders);
1190
-
1191
- customHeaders.forEach(header => {
1192
- 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
1193
1221
  });
1194
1222
 
1195
- let start = Date.now();
1196
- let duration;
1197
- try {
1198
- let serviceUrl = await settings.get('serviceUrl');
1199
-
1200
- // The same call the notify worker makes, rather than a lookalike: a probe that
1201
- // reimplements delivery can only prove that the reimplementation works. It also
1202
- // inherits the delivery timeout and the response drain, both of which this route
1203
- // used to do without while running on the same keep-alive retry dispatcher.
1204
- try {
1205
- await sendWebhookRequest(fetchCmd, parsed.toString(), {
1206
- method: 'post',
1207
- body:
1208
- request.payload.payload ||
1209
- JSON.stringify({
1210
- serviceUrl,
1211
- account: null,
1212
- date: new Date().toISOString(),
1213
- event: 'test',
1214
- data: {
1215
- nonce: crypto.randomBytes(NONCE_BYTES).toString('base64url')
1216
- }
1217
- }),
1218
- headers,
1219
- dispatcher: httpAgent.webhook,
1220
- validateTarget: validateWebhookTarget
1221
- });
1222
- duration = Date.now() - start;
1223
- } catch (err) {
1224
- duration = Date.now() - start;
1225
- // undici wraps a connection failure in a generic "fetch failed"; the cause is
1226
- // the part worth reporting back to the operator
1227
- throw err.cause || err;
1228
- }
1229
-
1230
- return {
1231
- success: true,
1232
- target: webhooks,
1233
- duration
1234
- };
1235
- } catch (err) {
1236
- // log the parsed URL, not the raw payload value, so embedded basic-auth credentials
1237
- // stay out of the log
1238
- request.logger.warn({ msg: 'Failed to post test webhook', webhooks: parsed.toString(), event: 'test', err });
1239
- return {
1240
- success: false,
1241
- target: webhooks,
1242
- duration,
1243
- error: err.message,
1244
- code: err.code,
1245
- // Same field the stored webhookErrorFlag carries, so the probe and the error
1246
- // block on this page describe a failed delivery the same way
1247
- statusCode: err.statusCode
1248
- };
1249
- }
1223
+ return Object.assign({ target: webhooks }, result);
1250
1224
  },
1251
1225
  options: {
1252
1226
  tags: ['test'],
@@ -14,7 +14,7 @@ const tokenPermissionView = require('../token-permission-view');
14
14
  const { PRIVILEGED_SETTINGS_SUMMARY } = require('../privileged-settings');
15
15
  const { Account, accountExists, accountSummary } = require('../account');
16
16
  const { isMcpEnabled } = require('../mcp');
17
- const { Gateway } = require('../gateway');
17
+ const { Gateway, gatewaySmtpConfig } = require('../gateway');
18
18
  const { templates } = require('../templates');
19
19
  const { webhooks } = require('../webhooks');
20
20
  const consts = require('../consts');
@@ -1972,19 +1972,7 @@ function registerPostGatewaysTest(server) {
1972
1972
  }
1973
1973
 
1974
1974
  let accountData = {
1975
- smtp: {
1976
- host,
1977
- port,
1978
- secure,
1979
- requireTLS,
1980
- auth:
1981
- user || pass
1982
- ? {
1983
- user,
1984
- pass: pass || ''
1985
- }
1986
- : false
1987
- }
1975
+ smtp: gatewaySmtpConfig({ host, port, secure, requireTLS, user, pass })
1988
1976
  };
1989
1977
 
1990
1978
  let verifyResult = await verifyAccountInfo(redis, accountData, request.logger.child({ gateway, action: 'verify-gateway' }));
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const Joi = require('joi');
4
- const { IMAP_MAX_IDLE_TIME_MIN, IMAP_MAX_IDLE_TIME_MAX } = require('../schemas');
4
+ const { IMAP_MAX_IDLE_TIME_MIN, IMAP_MAX_IDLE_TIME_MAX } = require('../consts');
5
5
 
6
6
  // The IDLE restart interval on the account edit form. The form takes seconds, like the resync
7
7
  // interval next to it, while the account stores milliseconds, the unit of the ImapFlow option it
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const { FALLBACK_POLL_INTERVAL } = require('../email-client/outlook-fallback-poll');
3
+ const { OUTLOOK_FALLBACK_POLL_INTERVAL: FALLBACK_POLL_INTERVAL } = require('../email-client/fallback-poll');
4
4
 
5
5
  /**
6
6
  * Adds the fields the account page renders for a Graph change subscription, in place
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+
3
+ // Form fields for the settings that an environment variable can override
4
+ // (lib/env-setting-overrides.js). Some are shown in a friendlier unit than the one stored - days
5
+ // for a setting kept in seconds, megabytes for one kept in bytes - so the conversion lives here,
6
+ // next to the values the pages read and write. A blank field arrives as null and stays null,
7
+ // which writeOverridableSettings() reads as "clear this setting".
8
+
9
+ const { getOverridableSettings } = require('../env-setting-overrides');
10
+
11
+ const DAY = 24 * 3600;
12
+ const MEGABYTE = 1024 * 1024;
13
+
14
+ const isNumber = value => typeof value === 'number' && Number.isFinite(value);
15
+
16
+ // Rounded to two decimals so an age set through the API in odd seconds still shows something a
17
+ // form can submit back unchanged in meaning
18
+ const secondsToDays = seconds => (isNumber(seconds) ? Math.round((seconds / DAY) * 100) / 100 : null);
19
+ const daysToSeconds = days => (isNumber(days) ? Math.round(days * DAY) : null);
20
+
21
+ const bytesToMegabytes = bytes => (isNumber(bytes) ? Math.round((bytes / MEGABYTE) * 100) / 100 : null);
22
+ const megabytesToBytes = megabytes => (isNumber(megabytes) ? Math.round(megabytes * MEGABYTE) : null);
23
+
24
+ const msToSeconds = ms => (isNumber(ms) ? Math.round(ms / 10) / 100 : null);
25
+ const secondsToMs = seconds => (isNumber(seconds) ? Math.round(seconds * 1000) : null);
26
+
27
+ // key -> [stored to form, form to stored]; keys not listed are shown as stored. Not limited to the
28
+ // overridable settings: any settings form field kept in a unit other than the one it shows is here
29
+ const FORM_UNITS = {
30
+ queueKeepFailedAge: [secondsToDays, daysToSeconds],
31
+ queueKeepFailedContentSize: [bytesToMegabytes, megabytesToBytes],
32
+ tokenLogAge: [secondsToDays, daysToSeconds],
33
+ webhooksRetryDelay: [msToSeconds, secondsToMs]
34
+ };
35
+
36
+ /**
37
+ * A stored value in the unit its form field shows
38
+ * @param {string} key - Setting key
39
+ * @param {*} value - Stored value
40
+ * @returns {*}
41
+ */
42
+ const toFormValue = (key, value) => (FORM_UNITS[key] ? FORM_UNITS[key][0](value) : value);
43
+
44
+ /**
45
+ * A form value in the unit the setting is stored in
46
+ * @param {string} key - Setting key
47
+ * @param {*} value - Validated form value, null for a blank field
48
+ * @returns {*}
49
+ */
50
+ const fromFormValue = (key, value) => (FORM_UNITS[key] ? FORM_UNITS[key][1](value) : value);
51
+
52
+ /**
53
+ * The values in effect for the given keys, in the units their form fields show. The page shows
54
+ * what applies whichever source set it, the environment included.
55
+ * @param {...string} keys - Overridable setting keys
56
+ * @returns {Promise<Object>} field name -> value
57
+ */
58
+ async function overridableFormValues(...keys) {
59
+ const values = await getOverridableSettings(...keys);
60
+ return Object.fromEntries(keys.map(key => [key, toFormValue(key, values[key])]));
61
+ }
62
+
63
+ /**
64
+ * The settings to write for the given keys from a validated form payload, in stored units.
65
+ * @param {Object} payload - Validated request payload
66
+ * @param {...string} keys - Overridable setting keys
67
+ * @returns {Object} key -> value (null to clear)
68
+ */
69
+ function overridableSettingsFromForm(payload, ...keys) {
70
+ return Object.fromEntries(keys.map(key => [key, fromFormValue(key, payload[key] === undefined ? null : payload[key])]));
71
+ }
72
+
73
+ module.exports = {
74
+ overridableFormValues,
75
+ overridableSettingsFromForm,
76
+ toFormValue,
77
+ fromFormValue,
78
+ secondsToDays,
79
+ daysToSeconds,
80
+ bytesToMegabytes,
81
+ megabytesToBytes,
82
+ msToSeconds,
83
+ secondsToMs
84
+ };
@@ -12,7 +12,7 @@ const Boom = require('@hapi/boom');
12
12
 
13
13
  const { buildPagingView } = require('./route-helpers');
14
14
  const queueBrowser = require('../queue-browser');
15
- const { QUEUE_NAMES, STATE_NAMES, DEFAULT_STATE, SCAN_LIMIT } = require('../queue-browser/definitions');
15
+ const { QUEUE_NAMES, STATE_NAMES, DEFAULT_STATE, SCAN_LIMIT, BULL_BOARD_DEPRECATION } = require('../queue-browser/definitions');
16
16
  const { DEFAULT_PAGE_SIZE } = require('../consts');
17
17
 
18
18
  const QUEUE_PARAM = Joi.string()
@@ -194,7 +194,7 @@ function init(args) {
194
194
  listing,
195
195
  scanLimit: SCAN_LIMIT,
196
196
  retention,
197
- failedContent: { limits: queueBrowser.failedContentLimits() },
197
+ failedContent: { limits: await queueBrowser.failedContentLimits() },
198
198
 
199
199
  filter: Object.assign({ active: listing.filtered, label: filterLabel }, filterParams),
200
200
  clearHref: listUrl(queueDef.name, { state }),
@@ -348,13 +348,15 @@ function init(args) {
348
348
 
349
349
  // Compatibility for the retired bull-board page: its own URL and the queue deep links
350
350
  // written against it (the docs, the dashboard of older releases, bookmarks) land on the
351
- // matching page here.
351
+ // matching page here. Deprecated, removed after REMOVAL_DATE (lib/deprecations.js)
352
+
352
353
  server.route({
353
354
  method: 'GET',
354
355
  path: '/admin/bull-board',
355
356
  handler(request, h) {
356
357
  return h.redirect('/admin/queues');
357
- }
358
+ },
359
+ options: { plugins: { deprecation: BULL_BOARD_DEPRECATION } }
358
360
  });
359
361
 
360
362
  server.route({
@@ -364,7 +366,8 @@ function init(args) {
364
366
  const path = decodeURIComponent(request.params.path || '');
365
367
  const queueName = QUEUE_NAMES.find(name => path.includes(name));
366
368
  return h.redirect(queueName ? `/admin/queues/${queueName}` : '/admin/queues');
367
- }
369
+ },
370
+ options: { plugins: { deprecation: BULL_BOARD_DEPRECATION } }
368
371
  });
369
372
  }
370
373
 
@@ -29,9 +29,14 @@
29
29
  // so - the way the logging page flags the SENTRY_DSN pinned fields. Field names are matched to
30
30
  // settings keys as-is, which holds for every page except the logging form, whose
31
31
  // `all`/`maxLogLines` fields fold into the `logs` setting.
32
+ //
33
+ // Renders also carry `envOverriddenSettings`, the fields whose own environment variable is set
34
+ // (lib/env-setting-overrides.js): the variable wins over the setting, so the page shows the value
35
+ // in effect and a value typed into such a field is not saved.
32
36
 
33
37
  const Joi = require('joi');
34
38
  const settings = require('../settings');
39
+ const { envOverriddenSettings } = require('../env-setting-overrides');
35
40
 
36
41
  function registerSettingsPage(server, page) {
37
42
  const { path, view, pageTitle, menuKey, schema, loadValues, applySettings, errorValues, viewContext } = page;
@@ -45,6 +50,7 @@ function registerSettingsPage(server, page) {
45
50
  }
46
51
  const preparedKeys = (await settings.get('preparedSettingsKeys')) || [];
47
52
  context.envManagedKeys = preparedKeys.filter(key => Object.hasOwn(schema, key));
53
+ context.envOverriddenSettings = envOverriddenSettings(Object.keys(schema));
48
54
  return context;
49
55
  };
50
56
 
@@ -1,7 +1,6 @@
1
1
  'use strict';
2
2
 
3
3
  const libmime = require('libmime');
4
- const { UNSAFE_KEYS } = require('./unsafe-key');
5
4
 
6
5
  // Largest header block handed to libmime. Its line unfolding used to be quadratic in the line
7
6
  // count, and the bounce and complaint detectors decode blocks taken from attachments any sender
@@ -53,17 +52,9 @@ function capHeaderBlock(content) {
53
52
  * @returns {Object} Map of lowercased header name to array of values
54
53
  */
55
54
  function decodeHeaders(headers) {
56
- let parsed = libmime.decodeHeaders(capHeaderBlock(headers));
57
-
58
- for (let name of UNSAFE_KEYS) {
59
- // Probing first is not needed for correctness, deleting a missing key is a no-op, but it is
60
- // the cheaper no-op and almost every message takes this path
61
- if (Object.hasOwn(parsed, name)) {
62
- delete parsed[name];
63
- }
64
- }
65
-
66
- return parsed;
55
+ // libmime drops the names that exist on Object.prototype itself; as header names are lowercased
56
+ // those are exactly __proto__ and constructor, the UNSAFE_KEYS this module used to delete
57
+ return libmime.decodeHeaders(capHeaderBlock(headers), { skipPrototypeKeys: true });
67
58
  }
68
59
 
69
60
  module.exports = { decodeHeaders, capHeaderBlock, MAX_HEADER_BLOCK_SIZE };
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+
3
+ // Dependency-free, so pure modules can use it without the Redis connection lib/tools.js opens
4
+
5
+ /**
6
+ * A copy of an object with only the keys whose value is set (truthy)
7
+ * @param {Object} obj
8
+ * @returns {Object}
9
+ */
10
+ function filterEmptyObjectValues(obj) {
11
+ let res = {};
12
+ for (let key of Object.keys(obj)) {
13
+ if (obj[key]) {
14
+ res[key] = obj[key];
15
+ }
16
+ }
17
+ return res;
18
+ }
19
+
20
+ module.exports = { filterEmptyObjectValues };
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ // Readers for whole-number settings and environment values. Dependency-free, so pure modules can
4
+ // share them: the overridable settings, the token audit log and the webhook retry policy each had
5
+ // a parser of their own, and they disagreed on blank values, zero and fractions.
6
+
7
+ /**
8
+ * A whole number of at least 1, or undefined for anything else. Fractions are floored.
9
+ * @param {*} value
10
+ * @returns {number|undefined}
11
+ */
12
+ function asPositiveInt(value) {
13
+ const parsed = Math.floor(Number(value));
14
+ return Number.isFinite(parsed) && parsed >= 1 ? parsed : undefined;
15
+ }
16
+
17
+ /**
18
+ * A whole number of at least 0, or undefined for anything else, blank values included (Number('')
19
+ * would read as 0). Fractions are floored.
20
+ * @param {*} value
21
+ * @returns {number|undefined}
22
+ */
23
+ function asNonNegativeInt(value) {
24
+ if (value === '' || value === null || value === undefined) {
25
+ return undefined;
26
+ }
27
+ const parsed = Math.floor(Number(value));
28
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
29
+ }
30
+
31
+ /**
32
+ * A whole number clamped into [min, max], or the default for anything that is not one: a setting
33
+ * that is unset, cleared, or written by an older version without validation
34
+ * @param {*} value
35
+ * @param {number} defaultValue
36
+ * @param {number} min
37
+ * @param {number} max
38
+ * @returns {number}
39
+ */
40
+ function boundedInt(value, defaultValue, min, max) {
41
+ const number = Number(value);
42
+ if (value === null || value === undefined || value === '' || !Number.isInteger(number)) {
43
+ return defaultValue;
44
+ }
45
+ return Math.min(Math.max(number, min), max);
46
+ }
47
+
48
+ module.exports = { asPositiveInt, asNonNegativeInt, boundedInt };
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ // Which kinds of tracking a sent message gets. The message's own flags win, the instance
4
+ // settings fill in what it leaves open, and open and click tracking follow trackSentMessages
5
+ // unless set on their own.
6
+
7
+ const TRACKING_SETTINGS = ['trackSentMessages', 'trackClicks', 'trackOpens'];
8
+
9
+ const isBoolean = value => typeof value === 'boolean';
10
+
11
+ /**
12
+ * Whether the message leaves anything to the instance settings, so the caller can skip the read
13
+ * @param {Object} message - trackingEnabled, trackClicks, trackOpens as the message set them
14
+ * @returns {boolean}
15
+ */
16
+ function needsTrackingSettings(message) {
17
+ return !isBoolean(message.trackingEnabled) || !isBoolean(message.trackClicks) || !isBoolean(message.trackOpens);
18
+ }
19
+
20
+ /**
21
+ * @param {Object} message - trackingEnabled, trackClicks, trackOpens as the message set them
22
+ * @param {Object} [stored] - The TRACKING_SETTINGS values; needed only when needsTrackingSettings()
23
+ * @returns {{trackingEnabled: *, trackClicks: boolean, trackOpens: boolean}}
24
+ */
25
+ function resolveTracking(message, stored = {}) {
26
+ const trackingEnabled = isBoolean(message.trackingEnabled) ? message.trackingEnabled : stored.trackSentMessages || false;
27
+ const pick = (own, setting) => [own, setting].find(isBoolean) ?? trackingEnabled;
28
+ return {
29
+ trackingEnabled,
30
+ trackClicks: pick(message.trackClicks, stored.trackClicks),
31
+ trackOpens: pick(message.trackOpens, stored.trackOpens)
32
+ };
33
+ }
34
+
35
+ module.exports = { TRACKING_SETTINGS, needsTrackingSettings, resolveTracking };