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
@@ -2,9 +2,11 @@
2
2
 
3
3
  const Joi = require('joi');
4
4
  const { webhooks: Webhooks } = require('../webhooks');
5
+ const settings = require('../settings');
6
+ const { sendTestWebhook, testEventBody } = require('../webhook-test');
5
7
  const { failAction } = require('../tools');
6
8
  const { handleError, throwNotFound, maskSecrets, MASK_NOTE } = require('./route-helpers');
7
- const { settingsSchema, apiResponses } = require('../schemas');
9
+ const { settingsSchema, apiResponses, listQuerySchema } = require('../schemas');
8
10
  const { MCP_MAX_PAGE_SIZE } = require('../consts');
9
11
 
10
12
  const webhookErrorFlagSchema = Joi.object({
@@ -28,7 +30,7 @@ function registerListWebhookRoutes(server, args) {
28
30
 
29
31
  async handler(request) {
30
32
  try {
31
- const listing = await Webhooks.list(request.query.page, request.query.pageSize);
33
+ const listing = await Webhooks.list(request.query.page, request.query.pageSize, request.query.query);
32
34
 
33
35
  // customHeaders and the target URL both carry credentials for the customer's own
34
36
  // receiver, so a reader of this listing could otherwise post forged, correctly
@@ -84,7 +86,8 @@ function registerListWebhookRoutes(server, args) {
84
86
  .example(0)
85
87
  .description('Page number (zero indexed, so use 0 for first page)')
86
88
  .label('PageNumber'),
87
- pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page').label('PageSize')
89
+ pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page').label('PageSize'),
90
+ query: listQuerySchema('ID, name, description or target URL', 'WebhookRoutesListQuery')
88
91
  }).label('WebhookRoutesListRequest')
89
92
  },
90
93
 
@@ -151,7 +154,8 @@ function registerGetWebhookRoute(server, args) {
151
154
  mcp: {
152
155
  name: 'get_webhook_route',
153
156
  title: 'Get webhook route',
154
- description: 'Get one webhook route: its target URL, the events it forwards, whether it is enabled, and its filter and mapping functions.'
157
+ description:
158
+ 'Get one webhook route: its target URL, whether it is enabled, its custom headers, and the filter and mapping functions that decide which events it forwards and in what shape.'
155
159
  },
156
160
  openapi: {
157
161
  responses: apiResponses('Returns the webhook route, including its filter and transform functions.', 400, 401, 403, 404, 429, 500)
@@ -205,11 +209,122 @@ function registerGetWebhookRoute(server, args) {
205
209
  });
206
210
  }
207
211
 
212
+ function registerTestWebhook(server, args) {
213
+ const { CORS_CONFIG } = args;
214
+
215
+ server.route({
216
+ method: 'POST',
217
+ path: '/v1/webhooks/test',
218
+
219
+ async handler(request) {
220
+ try {
221
+ const routeId = request.payload && request.payload.webhookRoute;
222
+
223
+ // Only ever a configured target: the global one, or a custom route's. The target
224
+ // URL and its headers are credentials of the receiver, so they are neither taken
225
+ // from the request nor echoed back in the result
226
+ let url, customHeaders;
227
+ if (routeId) {
228
+ const route = await Webhooks.getMeta(routeId);
229
+ if (!route || !route.id) {
230
+ throwNotFound('Requested webhook route was not found');
231
+ }
232
+ url = route.targetUrl;
233
+ customHeaders = route.customHeaders;
234
+ } else {
235
+ const stored = await settings.getMulti('webhooks', 'webhooksCustomHeaders');
236
+ url = stored.webhooks;
237
+ customHeaders = stored.webhooksCustomHeaders;
238
+ }
239
+
240
+ const target = routeId ? 'route' : 'global';
241
+ if (!url) {
242
+ return { success: false, target, error: 'Webhook URL is not set', code: 'NoWebhookTarget' };
243
+ }
244
+
245
+ const result = await sendTestWebhook({
246
+ url,
247
+ customHeaders,
248
+ body: testEventBody(await settings.get('serviceUrl')),
249
+ logger: request.logger
250
+ });
251
+
252
+ return Object.assign({ target }, result);
253
+ } catch (err) {
254
+ handleError(request, err);
255
+ }
256
+ },
257
+
258
+ options: {
259
+ description: 'Send a test webhook',
260
+ notes: 'Posts a `test` event to the global webhook target, or with `webhookRoute` set to the target of that custom route, with the custom headers configured for it and signed like a real delivery, and reports whether the receiver accepted it. The target is never taken from the request.',
261
+ tags: ['api', 'Webhooks'],
262
+
263
+ plugins: {
264
+ openapi: {
265
+ responses: apiResponses(
266
+ 'Returns the result of the test delivery. A failed delivery is reported in the result, not as an error status.',
267
+ 400,
268
+ 401,
269
+ 403,
270
+ 404,
271
+ 429,
272
+ 500
273
+ )
274
+ }
275
+ },
276
+
277
+ auth: {
278
+ strategy: 'api-token',
279
+ mode: 'required'
280
+ },
281
+ cors: CORS_CONFIG,
282
+
283
+ validate: {
284
+ options: {
285
+ stripUnknown: false,
286
+ abortEarly: false,
287
+ convert: true
288
+ },
289
+ failAction,
290
+ payload: Joi.object({
291
+ webhookRoute: Joi.string()
292
+ .max(256)
293
+ .example('AAABgS-UcAYAAAABAA')
294
+ .description('Custom webhook route to test. Omit to test the global webhook target')
295
+ })
296
+ .allow(null)
297
+ .label('TestWebhookRequest')
298
+ },
299
+
300
+ response: {
301
+ schema: Joi.object({
302
+ success: Joi.boolean().example(true).description('Did the receiver accept the test event with a 2xx response'),
303
+ target: Joi.string()
304
+ .valid('global', 'route')
305
+ .example('global')
306
+ .description('Which configured target was tested')
307
+ .label('TestWebhookTarget'),
308
+ duration: Joi.number().integer().example(182).description('How long the delivery took, in milliseconds'),
309
+ error: Joi.string().example('Request failed with status 503').description('Why the delivery failed. Only present if success=false'),
310
+ code: Joi.string().example('ECONNREFUSED').description('Error code. Only present if success=false'),
311
+ statusCode: Joi.number()
312
+ .integer()
313
+ .example(503)
314
+ .description('HTTP status the receiver answered with. Only present if it answered with an error')
315
+ }).label('TestWebhookResponse'),
316
+ failAction: 'log'
317
+ }
318
+ }
319
+ });
320
+ }
321
+
208
322
  async function init(args) {
209
323
  const { server } = args;
210
324
 
211
325
  registerListWebhookRoutes(server, args);
212
326
  registerGetWebhookRoute(server, args);
327
+ registerTestWebhook(server, args);
213
328
  }
214
329
 
215
330
  module.exports = init;
@@ -9,6 +9,7 @@
9
9
  // ISO timestamps are the instant the invite means wherever EmailEngine happens to run.
10
10
 
11
11
  const ical = require('ical.js');
12
+ const { filterEmptyObjectValues } = require('./utils/filter-empty');
12
13
 
13
14
  const CALENDAR_CONTENT_TYPES = ['text/calendar', 'application/ics'];
14
15
 
@@ -75,4 +76,83 @@ function parseCalendarEvent(content) {
75
76
  };
76
77
  }
77
78
 
78
- module.exports = { CALENDAR_CONTENT_TYPES, sortCalendarAttachments, parseCalendarEvent };
79
+ /**
80
+ * The calendar events of a new message, for the messageNew webhook (`notifyCalendarEvents`).
81
+ * Shared by the IMAP mailbox and the Gmail API and Graph clients, which differ only in how an
82
+ * attachment's content is loaded. text/calendar is read before application/ics, an event seen in
83
+ * both is listed once, and an event without a file name gets invite.ics or event.ics
84
+ * @param {Object[]} attachments - The message's attachments
85
+ * @param {Function} load - async (attachment) => void, sets attachment.content (base64) when it can
86
+ * @param {Object} logger
87
+ * @returns {Promise<Object[]|undefined>} The events, or undefined when there are none
88
+ */
89
+ async function collectCalendarEvents(attachments, load, logger) {
90
+ const events = new Map();
91
+
92
+ for (const attachment of [...(attachments || [])].sort(sortCalendarAttachments)) {
93
+ if (!CALENDAR_CONTENT_TYPES.includes(attachment.contentType)) {
94
+ continue;
95
+ }
96
+ if (!attachment.content) {
97
+ await load(attachment);
98
+ }
99
+ if (!attachment.content) {
100
+ continue;
101
+ }
102
+
103
+ const contentBuf = Buffer.from(attachment.content, 'base64');
104
+ let event;
105
+ try {
106
+ event = parseCalendarEvent(contentBuf);
107
+ } catch (err) {
108
+ logger.warn({ msg: 'Failed to parse calendar event', attachment: Object.assign({}, attachment, { content: `${contentBuf.length} bytes` }), err });
109
+ continue;
110
+ }
111
+ if (!event) {
112
+ continue;
113
+ }
114
+
115
+ if (events.has(event.eventId)) {
116
+ const existing = events.get(event.eventId);
117
+ if (attachment.filename && !existing.filename) {
118
+ existing.filename = attachment.filename;
119
+ }
120
+ continue;
121
+ }
122
+
123
+ events.set(
124
+ event.eventId,
125
+ filterEmptyObjectValues({
126
+ eventId: event.eventId,
127
+ attachment: attachment.id,
128
+ method: attachment.method || event.method || null,
129
+
130
+ summary: event.summary,
131
+ description: event.description,
132
+ timezone: event.timezone,
133
+ startDate: event.startDate,
134
+ endDate: event.endDate,
135
+ organizer: event.organizer,
136
+
137
+ filename: attachment.filename,
138
+ contentType: attachment.contentType,
139
+ encoding: 'base64',
140
+ content: attachment.content
141
+ })
142
+ );
143
+ }
144
+
145
+ if (!events.size) {
146
+ return undefined;
147
+ }
148
+
149
+ return Array.from(events.values()).map(calendarEvent => {
150
+ if (!calendarEvent.filename) {
151
+ const method = calendarEvent.method && calendarEvent.method.toUpperCase();
152
+ calendarEvent.filename = method === 'CANCEL' || method === 'REQUEST' ? 'invite.ics' : 'event.ics';
153
+ }
154
+ return calendarEvent;
155
+ });
156
+ }
157
+
158
+ module.exports = { CALENDAR_CONTENT_TYPES, sortCalendarAttachments, parseCalendarEvent, collectCalendarEvents };
package/lib/consts.js CHANGED
@@ -1,6 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  const dotenv = require('dotenv');
4
+ const { readEnvValue } = require('./read-env-value');
5
+ const { REDACTED_LOG_KEYS, TRANSIENT_NETWORK_CODES } = require('./logger-consts');
4
6
 
5
7
  if (!process.env.EE_ENV_LOADED) {
6
8
  dotenv.config({ quiet: true });
@@ -187,7 +189,7 @@ module.exports = {
187
189
  // separate constant from the live description rather than a reference to it.
188
190
  AUTH_FAILURE_DISABLED_LEGACY_DESCRIPTION: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
189
191
 
190
- REDIS_PREFIX: ((process.env.EENGINE_REDIS_PREFIX || '').toString().trim() + ':').replace(/^:/, ''),
192
+ REDIS_PREFIX: ((readEnvValue('EENGINE_REDIS_PREFIX') || '').toString().trim() + ':').replace(/^:/, ''),
191
193
 
192
194
  REDIS_BATCH_DELETE_SIZE: 1000,
193
195
 
@@ -207,15 +209,15 @@ module.exports = {
207
209
  // limits worth worrying about, and certificates signed by an untrusted root - which is also why
208
210
  // the default here has to stay production. A build that shipped staging by default would hand
209
211
  // every IMAP, SMTP and HTTPS client a certificate it refuses.
210
- ACME_ENVIRONMENT: (process.env.EENGINE_ACME_ENVIRONMENT || '').toString().trim() || 'emailengine',
211
- ACME_DIRECTORY_URL: (process.env.EENGINE_ACME_DIRECTORY_URL || '').toString().trim() || 'https://acme-v02.api.letsencrypt.org/directory',
212
+ ACME_ENVIRONMENT: (readEnvValue('EENGINE_ACME_ENVIRONMENT') || '').toString().trim() || 'emailengine',
213
+ ACME_DIRECTORY_URL: (readEnvValue('EENGINE_ACME_DIRECTORY_URL') || '').toString().trim() || 'https://acme-v02.api.letsencrypt.org/directory',
212
214
 
213
215
  // Exactly one of the two was overridden, which is the combination the paragraph above says
214
216
  // cannot work. Derived here, from the same reads the values themselves come from, so it can
215
217
  // never disagree with them; lib/cert-handler.js is what reports it, since nothing in the CA's
216
218
  // rejection says why every order failed.
217
219
  ACME_OVERRIDE_PARTIAL:
218
- !!(process.env.EENGINE_ACME_ENVIRONMENT || '').toString().trim() !== !!(process.env.EENGINE_ACME_DIRECTORY_URL || '').toString().trim(),
220
+ !!(readEnvValue('EENGINE_ACME_ENVIRONMENT') || '').toString().trim() !== !!(readEnvValue('EENGINE_ACME_DIRECTORY_URL') || '').toString().trim(),
219
221
 
220
222
  // do not attempt certificate renewal more often than once in 8 hours
221
223
  BLOCK_TLS_RENEW: 8 * 3600 * 1000,
@@ -283,6 +285,15 @@ module.exports = {
283
285
 
284
286
  // How many times to retry an email sending before it is considered as failing
285
287
  DEFAULT_DELIVERY_ATTEMPTS: 10,
288
+
289
+ // How many attempts a webhook delivery gets, and the first backoff delay between them in ms
290
+ // (it doubles with every attempt). The webhooksDeliveryAttempts and webhooksRetryDelay
291
+ // settings override them
292
+ DEFAULT_WEBHOOK_ATTEMPTS: 10,
293
+ MAX_WEBHOOK_ATTEMPTS: 100,
294
+ DEFAULT_WEBHOOK_RETRY_DELAY: 5000,
295
+ MIN_WEBHOOK_RETRY_DELAY: 1000,
296
+ MAX_WEBHOOK_RETRY_DELAY: 60 * 60 * 1000,
286
297
  // The most a caller may ask for, through the API or the X-EE-Delivery-Attempts header of a
287
298
  // stored draft or SMTP submission
288
299
  MAX_DELIVERY_ATTEMPTS: 100,
@@ -314,12 +325,12 @@ module.exports = {
314
325
 
315
326
  // while we do require a valid cert, the passing requirements are extremely low
316
327
  TLS_DEFAULTS: {
317
- minVersion: (process.env.EENGINE_TLS_MIN_VERSION || '').toString().trim() || 'TLSv1',
318
- minDHSize: Number((process.env.EENGINE_TLS_MIN_DH_SIZE || '').toString().trim()) || 1024,
319
- ciphers: (process.env.EENGINE_TLS_CIPHERS || '').toString().trim() || 'DEFAULT@SECLEVEL=0'
328
+ minVersion: (readEnvValue('EENGINE_TLS_MIN_VERSION') || '').toString().trim() || 'TLSv1',
329
+ minDHSize: Number((readEnvValue('EENGINE_TLS_MIN_DH_SIZE') || '').toString().trim()) || 1024,
330
+ ciphers: (readEnvValue('EENGINE_TLS_CIPHERS') || '').toString().trim() || 'DEFAULT@SECLEVEL=0'
320
331
  },
321
332
 
322
- URL_FETCH_TIMEOUT: Number((process.env.EENGINE_FETCH_TIMEOUT || '').toString().trim()) || 90 * 1000,
333
+ URL_FETCH_TIMEOUT: Number((readEnvValue('EENGINE_FETCH_TIMEOUT') || '').toString().trim()) || 90 * 1000,
323
334
 
324
335
  // hard limit for subscript execution (does not include waiting for promises)
325
336
  SUBSCRIPT_RUNTIME_TIMEOUT: 30 * 1000,
@@ -351,6 +362,11 @@ module.exports = {
351
362
  // length would store a string that names no account while claiming to name one.
352
363
  MAX_ACCOUNT_ID_LENGTH: 256,
353
364
 
365
+ // Token audit log bounds when neither the setting nor its environment variable is set
366
+ // (tokenLogEntries / EENGINE_TOKEN_LOG_ENTRIES, tokenLogAge / EENGINE_TOKEN_LOG_AGE)
367
+ TOKEN_LOG_ENTRIES_DEFAULT: 1000,
368
+ TOKEN_LOG_AGE_DEFAULT: 7 * 24 * 3600,
369
+
354
370
  // Class names on the collapse marker web-safe HTML wraps quoted thread history in. Part of the
355
371
  // output contract - consumers select on them to style or hide the block - so they are defined
356
372
  // once here and referenced by both the generator (lib/web-safe-html.js) and the API docs.
@@ -434,6 +450,16 @@ module.exports = {
434
450
  // How far back a manual sync of a Graph account may be asked to look (PUT /v1/account/{account}/sync `since`)
435
451
  OUTLOOK_SYNC_MAX_LOOKBACK: 30 * 24 * 60 * 60 * 1000, // ms
436
452
 
453
+ // Bounds for an IMAP IDLE restart interval (imap.maxIdleTime, and what lib/email-client/imap/adaptive-idle.js
454
+ // learns), in milliseconds. Anything shorter than the floor is polling rather than idling, and the
455
+ // RFC 3501 autologout timer is 30 minutes
456
+ IMAP_MAX_IDLE_TIME_MIN: 10 * 1000,
457
+ IMAP_MAX_IDLE_TIME_MAX: 30 * 60 * 1000,
458
+
459
+ // Settings a new message pass reads after the fetch, read together with settings.getMulti(): once
460
+ // per sync pass for IMAP, once per message for the API clients
461
+ NEW_MESSAGE_SETTINGS: ['notifyAttachments', 'notifyAttachmentSize', 'notifyCalendarEvents', 'notifyWebSafeHtml', 'resolveGmailCategories'],
462
+
437
463
  // Google Pub/Sub subscription defaults
438
464
  GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL: '2678400s', // 31 days in seconds (Google's default)
439
465
  GMAIL_PUBSUB_ACK_DEADLINE_SECONDS: 30,
@@ -441,22 +467,8 @@ module.exports = {
441
467
  // error (5xx, 408, 429, network) is retried after each of these delays (ms), about 3.5 hours in all
442
468
  CHANGE_EVENT_RETRY_DELAYS: [1, 4, 16, 60, 60, 60].map(minutes => minutes * 60 * 1000),
443
469
 
444
- // Transient network error codes that indicate a retry-worthy connection failure
445
- TRANSIENT_NETWORK_CODES: new Set([
446
- 'ENOTFOUND',
447
- 'EAI_AGAIN',
448
- 'ETIMEDOUT',
449
- 'ECONNRESET',
450
- 'ECONNREFUSED',
451
- // no route to the host, such as an IPv6 address on a host without IPv6 connectivity
452
- 'ENETUNREACH',
453
- 'EHOSTUNREACH',
454
- 'UND_ERR_SOCKET',
455
- 'UND_ERR_CONNECT_TIMEOUT',
456
- 'UND_ERR_HEADERS_TIMEOUT',
457
- // a response body that stalled mid-transfer
458
- 'UND_ERR_BODY_TIMEOUT'
459
- ]),
470
+ // Transient network error codes that indicate a retry-worthy connection failure (lib/logger-consts.js)
471
+ TRANSIENT_NETWORK_CODES,
460
472
 
461
473
  // Error codes meaning "the IMAP connection is gone", as opposed to the command itself failing
462
474
  CONNECTION_CLOSING_CODES: new Set(['IMAPConnectionClosing', 'EConnectionClosed', 'NoConnection']),
@@ -466,28 +478,8 @@ module.exports = {
466
478
  // `documentStoreEnabled` setting is still on
467
479
  LAST_DOCUMENT_STORE_VERSION: '2.81.2',
468
480
 
469
- // Applied by lib/logger.js to the root logger, so every worker inherits it. A logged joi
470
- // ValidationError carries the full submitted payload in `_original` and the offending value in
471
- // each detail context, and `rawPacket` is a TLS-error field that can carry an unparsed
472
- // credential frame - without these a failed validation writes plaintext passwords, OAuth2
473
- // client secrets and access tokens into the log, the per-account log store and Sentry.
474
- // `req.query.access_token` is here because the api-token scheme accepts the credential as a
475
- // query argument, and the request logger (lib/hapi-request-logger.js) logs the parsed query
476
- // object with every request - so a client using that form wrote a live token into this
477
- // instance's own request log. The serialized `req.url` is the pathname only
478
- // (pino-std-serializers reports `req.path`), so the credential reaches the log through the
479
- // query object and nowhere else.
480
- REDACTED_LOG_KEYS: [
481
- 'req.headers.authorization',
482
- 'req.headers.cookie',
483
- 'req.query.access_token',
484
- 'err.rawPacket',
485
- 'err._original',
486
- 'err.details[*].context.value',
487
- // the WHATWG URL parser attaches the string it rejected, and a stored proxy or webhook URL
488
- // carries its credentials inline
489
- 'err.input'
490
- ],
481
+ // Log paths pino redacts, see lib/logger-consts.js
482
+ REDACTED_LOG_KEYS,
491
483
 
492
484
  generateWebhookTable() {
493
485
  let entries = [];
package/lib/db.js CHANGED
@@ -9,6 +9,7 @@ const fs = require('fs');
9
9
  const config = require('@zone-eu/wild-config');
10
10
  const pathlib = require('path');
11
11
  const redisUrl = require('./redis-url');
12
+ const { reconnectOnErrorReply } = require('./redis-reconnect');
12
13
  const { threadId } = require('worker_threads');
13
14
  const logger = require('./logger');
14
15
  const { readEnvValue } = require('./read-env-value');
@@ -36,12 +37,13 @@ const REDIS_CONF = Object.assign(
36
37
  return delay;
37
38
  },
38
39
  reconnectOnError(err) {
39
- // Not fatal: this fires on every transient connection error and we always reconnect,
40
- // so logging it at fatal turned an ordinary Redis failover into a burst of top
41
- // severity alerts. The retryStrategy above reports the actual retry cadence.
42
- logger.warn({ msg: 'Redis connection error', isMainThread, threadId, err });
43
- // always try to reconnect
44
- return true;
40
+ // Runs for every error reply, see lib/redis-reconnect.js. Everything other than a
41
+ // failover is the caller's to handle, so only the reconnect itself is logged
42
+ let reconnect = reconnectOnErrorReply(err);
43
+ if (reconnect) {
44
+ logger.warn({ msg: 'Redis replied READONLY, reconnecting', isMainThread, threadId, err });
45
+ }
46
+ return reconnect;
45
47
  },
46
48
  offlineQueue: true
47
49
  },
@@ -122,6 +124,7 @@ const zExpungeScript = fs.readFileSync(pathlib.join(__dirname, '/lua/z-expunge.l
122
124
  const zSetScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-set.lua'), 'utf-8');
123
125
  const zGetScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-get.lua'), 'utf-8');
124
126
  const zGetByUidScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-get-by-uid.lua'), 'utf-8');
127
+ const zHeadScoresScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-head-scores.lua'), 'utf-8');
125
128
  const zGetMailboxIdScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-get-mailbox-id.lua'), 'utf-8');
126
129
  const zGetMailboxPathScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-get-mailbox-path.lua'), 'utf-8');
127
130
  const sListAccountsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/s-list-accounts.lua'), 'utf-8');
@@ -160,6 +163,11 @@ redis.defineCommand('zGetByUid', {
160
163
  lua: zGetByUidScript
161
164
  });
162
165
 
166
+ redis.defineCommand('zHeadScores', {
167
+ numberOfKeys: 1,
168
+ lua: zHeadScoresScript
169
+ });
170
+
163
171
  redis.defineCommand('zGetMailboxId', {
164
172
  numberOfKeys: 2,
165
173
  lua: zGetMailboxIdScript
@@ -52,6 +52,12 @@ function isPermanentDeliveryError(err) {
52
52
  return false;
53
53
  }
54
54
 
55
+ // nodemailer (10.2.0) decides it from the reply itself, which also covers a rejection of every
56
+ // recipient where only some were deferred: that one is transient although its first code is 5xx
57
+ if (typeof err.permanent === 'boolean') {
58
+ return err.permanent;
59
+ }
60
+
55
61
  const smtpResponseCode = Number(err.responseCode);
56
62
  if (smtpResponseCode) {
57
63
  // A real SMTP reply decides on its own: 5xx is permanent, everything else (transient 4xx, or