emailengine-app 2.87.2 → 2.88.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 (64) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +23 -0
  3. package/ENVIRONMENT.md +26 -23
  4. package/LICENSE_EMAILENGINE.txt +20 -12
  5. package/app.json +3 -3
  6. package/bin/emailengine.js +7 -11
  7. package/data/google-crawlers.json +1 -1
  8. package/data/public_suffix_list.dat +48 -10
  9. package/lib/account.js +69 -49
  10. package/lib/admin-password.js +85 -0
  11. package/lib/api-routes/license-routes.js +9 -0
  12. package/lib/api-token-auth.js +21 -5
  13. package/lib/calendar-event.js +15 -3
  14. package/lib/consts.js +5 -0
  15. package/lib/db.js +1 -0
  16. package/lib/email-client/base-client.js +36 -15
  17. package/lib/email-client/gmail-client.js +20 -6
  18. package/lib/email-client/imap/connection-errors.js +30 -1
  19. package/lib/email-client/imap/session-expiry.js +83 -0
  20. package/lib/email-client/imap-client.js +12 -2
  21. package/lib/email-client/smtp-pool-manager.js +66 -8
  22. package/lib/export.js +147 -22
  23. package/lib/graph-notifications.js +60 -0
  24. package/lib/imap-proxy-auth.js +52 -18
  25. package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
  26. package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
  27. package/lib/imapproxy/imap-server.js +10 -1
  28. package/lib/imapproxy/proxy-handoff.js +100 -5
  29. package/lib/license-subscription.js +238 -0
  30. package/lib/oauth/gmail.js +18 -0
  31. package/lib/oauth/outlook-identity.js +54 -12
  32. package/lib/prepared-password.js +38 -0
  33. package/lib/queue-browser/index.js +6 -6
  34. package/lib/queue-job-actions.js +59 -4
  35. package/lib/read-env-value.js +46 -21
  36. package/lib/redis-url.js +23 -0
  37. package/lib/response-stream.js +69 -1
  38. package/lib/revocation-events.js +79 -0
  39. package/lib/schemas.js +18 -2
  40. package/lib/settings.js +47 -24
  41. package/lib/sso.js +23 -0
  42. package/lib/submit-penalty.js +24 -0
  43. package/lib/submit-processor.js +10 -2
  44. package/lib/tokens.js +6 -0
  45. package/lib/tools.js +86 -15
  46. package/lib/ui-routes/admin-config-routes.js +3 -276
  47. package/lib/ui-routes/auth-routes.js +13 -64
  48. package/lib/ui-routes/license-routes.js +326 -0
  49. package/lib/web-safe-html.js +29 -0
  50. package/lib/webhook-delivery.js +21 -20
  51. package/lib/webhook-penalty.js +18 -17
  52. package/lib/webhooks.js +18 -0
  53. package/package.json +18 -18
  54. package/sbom.json +294 -294
  55. package/scan.js +2 -0
  56. package/server.js +253 -80
  57. package/static/css/flyonui.css +2 -2
  58. package/static/js/ui.js +11 -4
  59. package/static/licenses.html +27 -27
  60. package/translations/messages.pot +17 -17
  61. package/views/config/license.hbs +43 -16
  62. package/views/partials/side_menu.hbs +1 -1
  63. package/workers/api.js +108 -107
  64. package/workers/imap.js +4 -6
@@ -0,0 +1,326 @@
1
+ 'use strict';
2
+
3
+ // The admin UI's license page (/admin/config/license): showing the license and the subscription
4
+ // behind it, registering and removing a key, requesting a trial, and "Check subscription now"
5
+ // (lib/license-subscription.js decides what an answer of the license server does).
6
+
7
+ const Joi = require('joi');
8
+ const os = require('os');
9
+ const packageData = require('../../package.json');
10
+ const { fetch: fetchCmd } = require('undici');
11
+ const settings = require('../settings');
12
+ const { failAction, httpAgent } = require('../tools');
13
+ const { isSubscriptionLicense, isSuspended } = require('../license-subscription');
14
+
15
+ const LICENSE_HOST = 'https://postalsys.com';
16
+
17
+ // A date as the license page prints it, "10 December 2026", in UTC so every admin reads the same day
18
+ const dayLabel = value => new Date(value).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' });
19
+
20
+ /**
21
+ * The license page's view context: the GET and the error paths of the POST render the same page
22
+ * @param {Object|undefined} licenseInfo - the `license` command's answer
23
+ * @param {Object} [extra] - errors and the like
24
+ * @returns {Object}
25
+ */
26
+ function licensePageContext(licenseInfo, extra) {
27
+ let subscription = licenseInfo && licenseInfo.subscription;
28
+ return Object.assign(
29
+ {
30
+ pageTitle: 'License',
31
+ menuLicense: true,
32
+ hideLicenseWarning: true,
33
+
34
+ // what the license page says about the subscription behind the key
35
+ licenseInfo,
36
+ isSubscriptionLicense: !!(licenseInfo && isSubscriptionLicense(licenseInfo.details)),
37
+ isPaused: isSuspended(licenseInfo),
38
+ subscriptionSince: subscription && subscription.since ? dayLabel(subscription.since) : null,
39
+ subscriptionUntil: subscription && subscription.until ? dayLabel(subscription.until) : null,
40
+ expiresDays: subscription ? subscription.days : undefined,
41
+
42
+ // a paused license is still registered, so the form to add one stays closed
43
+ showLicenseText: !licenseInfo || !licenseInfo.details || !!licenseInfo.details.trial
44
+ },
45
+ extra
46
+ );
47
+ }
48
+
49
+ function registerGetConfigLicense(server, args) {
50
+ const { call } = args;
51
+
52
+ server.route({
53
+ method: 'GET',
54
+ path: '/admin/config/license',
55
+ async handler(request, h) {
56
+ // the answer reflects the check, which can have changed the state the request started with
57
+ let licenseInfo = (await call({ cmd: 'checkLicense' })) || request.app.licenseInfo;
58
+ request.app.licenseInfo = licenseInfo;
59
+
60
+ return h.view('config/license', licensePageContext(licenseInfo), {
61
+ layout: 'app'
62
+ });
63
+ }
64
+ });
65
+ }
66
+
67
+ function registerPostConfigLicense(server, args) {
68
+ const { call } = args;
69
+
70
+ server.route({
71
+ method: 'POST',
72
+ path: '/admin/config/license',
73
+ async handler(request, h) {
74
+ try {
75
+ // update license
76
+ const licenseInfo = await call({ cmd: 'updateLicense', license: request.payload.license });
77
+ if (!licenseInfo) {
78
+ let err = new Error('Failed to update license. Check license file contents.');
79
+ err.statusCode = 403;
80
+ err.details = { license: err.message };
81
+ throw err;
82
+ }
83
+
84
+ if (licenseInfo.active) {
85
+ await request.flash({ type: 'info', message: `License activated` });
86
+ }
87
+
88
+ return h.redirect('/admin/config/license');
89
+ } catch (err) {
90
+ await request.flash({ type: 'danger', message: `Couldn't register license. Check the key and try again.` });
91
+ request.logger.warn({ msg: 'Failed to register license key', err });
92
+
93
+ let context = licensePageContext(request.app.licenseInfo, { errors: err.details });
94
+ context.showLicenseText = context.showLicenseText || !!(err.details && err.details.license);
95
+ return h.view('config/license', context, {
96
+ layout: 'app'
97
+ });
98
+ }
99
+ },
100
+ options: {
101
+ validate: {
102
+ options: {
103
+ stripUnknown: true,
104
+ abortEarly: false,
105
+ convert: true
106
+ },
107
+
108
+ async failAction(request, h, err) {
109
+ let errors = {};
110
+
111
+ if (err.details) {
112
+ err.details.forEach(detail => {
113
+ if (!errors[detail.path]) {
114
+ errors[detail.path] = detail.message;
115
+ }
116
+ });
117
+ }
118
+
119
+ await request.flash({ type: 'danger', message: `Couldn't register license. Check the key and try again.` });
120
+ request.logger.warn({ msg: 'Failed to register license key', err });
121
+
122
+ let context = licensePageContext(request.app.licenseInfo, { errors });
123
+ context.showLicenseText = context.showLicenseText || !!errors.license;
124
+ return h
125
+ .view('config/license', context, {
126
+ layout: 'app'
127
+ })
128
+ .takeover();
129
+ },
130
+
131
+ payload: Joi.object({
132
+ license: Joi.string()
133
+ .max(10 * 1024)
134
+ .required()
135
+ .example('-----BEGIN LICENSE-----\r\n...')
136
+ .description('License file')
137
+ }).label('RegisterLicense')
138
+ }
139
+ }
140
+ });
141
+ }
142
+
143
+ function registerPostConfigLicenseDelete(server, args) {
144
+ const { call } = args;
145
+
146
+ server.route({
147
+ method: 'POST',
148
+ path: '/admin/config/license/delete',
149
+ async handler(request, h) {
150
+ try {
151
+ const licenseInfo = await call({ cmd: 'removeLicense' });
152
+ if (!licenseInfo) {
153
+ let err = new Error('Failed to clear license info');
154
+ err.statusCode = 403;
155
+ throw err;
156
+ } else {
157
+ await request.flash({ type: 'info', message: `License removed` });
158
+ }
159
+
160
+ return h.redirect('/admin/config/license');
161
+ } catch (err) {
162
+ await request.flash({ type: 'danger', message: `Couldn't remove license. Try again.` });
163
+ request.logger.error({ msg: 'Failed to unregister license key', err, remoteAddress: request.app.ip });
164
+ return h.redirect('/admin/config/license');
165
+ }
166
+ },
167
+ options: {
168
+ validate: {
169
+ options: {
170
+ stripUnknown: true,
171
+ abortEarly: false,
172
+ convert: true
173
+ },
174
+
175
+ async failAction(request, h, err) {
176
+ await request.flash({ type: 'danger', message: `Couldn't remove license. Try again.` });
177
+ request.logger.error({ msg: 'Failed to unregister license key', err });
178
+
179
+ return h.redirect('/admin/config/license').takeover();
180
+ },
181
+
182
+ payload: Joi.object({})
183
+ }
184
+ }
185
+ });
186
+ }
187
+
188
+ // The flash after "Check subscription now", by what the forced check reported
189
+ const RECHECK_MESSAGES = {
190
+ ok: { type: 'success', message: 'Subscription checked: it is in good standing' },
191
+ refused: { type: 'warning', message: 'Subscription checked: the payment is still overdue' },
192
+ unreachable: { type: 'danger', message: 'Could not reach postalsys.com. Try again in a minute.' },
193
+ error: { type: 'danger', message: 'postalsys.com could not check the subscription. Try again in a minute.' },
194
+ throttled: { type: 'info', message: 'The subscription was checked less than a minute ago. Try again shortly.' },
195
+ busy: { type: 'info', message: 'A subscription check is already running. Reload the page in a moment.' },
196
+ skipped: { type: 'info', message: 'This license does not depend on a subscription.' }
197
+ };
198
+
199
+ function registerPostConfigLicenseRecheck(server, args) {
200
+ const { call } = args;
201
+
202
+ server.route({
203
+ method: 'POST',
204
+ path: '/admin/config/license/recheck',
205
+ async handler(request, h) {
206
+ try {
207
+ let wasPaused = isSuspended(request.app.licenseInfo);
208
+ let result = await call({ cmd: 'checkLicense', force: true });
209
+ let flash = RECHECK_MESSAGES[result && result.checkOutcome] || RECHECK_MESSAGES.error;
210
+ if (result && result.checkOutcome === 'ok' && wasPaused) {
211
+ flash = { type: 'success', message: 'Subscription in good standing: EmailEngine has resumed' };
212
+ }
213
+ await request.flash(flash);
214
+ } catch (err) {
215
+ await request.flash({ type: 'danger', message: `Couldn't check the subscription. Try again.` });
216
+ request.logger.error({ msg: 'Failed to check the subscription', err });
217
+ }
218
+ return h.redirect('/admin/config/license');
219
+ },
220
+ options: {
221
+ validate: {
222
+ options: {
223
+ stripUnknown: true,
224
+ abortEarly: false,
225
+ convert: true
226
+ },
227
+
228
+ async failAction(request, h, err) {
229
+ await request.flash({ type: 'danger', message: `Couldn't check the subscription. Try again.` });
230
+ request.logger.error({ msg: 'Failed to check the subscription', err });
231
+
232
+ return h.redirect('/admin/config/license').takeover();
233
+ },
234
+
235
+ payload: Joi.object({})
236
+ }
237
+ }
238
+ });
239
+ }
240
+
241
+ function registerPostConfigLicenseTrial(server, args) {
242
+ const { call } = args;
243
+
244
+ server.route({
245
+ method: 'POST',
246
+ path: '/admin/config/license/trial',
247
+ async handler(request) {
248
+ try {
249
+ // provision new trial license
250
+
251
+ let headers = {
252
+ 'Content-Type': 'application/json',
253
+ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
254
+ };
255
+
256
+ let res = await fetchCmd(`${LICENSE_HOST}/licenses/trial`, {
257
+ method: 'post',
258
+ body: JSON.stringify({
259
+ version: packageData.version,
260
+ app: '@postalsys/emailengine-app',
261
+ hostname: os.hostname() || 'localhost',
262
+ url: (await settings.get('serviceUrl')) || ''
263
+ }),
264
+ headers,
265
+ dispatcher: httpAgent.retry
266
+ });
267
+
268
+ if (!res.ok) {
269
+ let err = new Error(res.statusText || `Invalid response: ${res.status} ${res.statusText}`);
270
+ err.statusCode = res.status;
271
+
272
+ try {
273
+ err.response = await res.json();
274
+ } catch (err) {
275
+ // ignore
276
+ }
277
+
278
+ throw err;
279
+ }
280
+
281
+ const data = await res.json();
282
+
283
+ let licenseFile = `-----BEGIN LICENSE-----
284
+ ${Buffer.from(data.content, 'base64url').toString('base64')}
285
+ -----END LICENSE-----`;
286
+
287
+ const licenseInfo = await call({ cmd: 'updateLicense', license: licenseFile });
288
+ if (!licenseInfo) {
289
+ let err = new Error('Failed to update license. Check license file contents.');
290
+ err.statusCode = 403;
291
+ err.details = { license: err.message };
292
+ throw err;
293
+ }
294
+
295
+ if (licenseInfo.active) {
296
+ await request.flash({ type: 'info', message: `Trial activated` });
297
+ return { success: true, message: `Trial activated` };
298
+ }
299
+
300
+ throw new Error('Failed to activate provisioned trial license');
301
+ } catch (err) {
302
+ request.logger.error({ msg: 'Failed to provision a trial license key', err, remoteAddress: request.app.ip });
303
+ return { success: false, error: (err.response && err.response.error) || err.message };
304
+ }
305
+ },
306
+ options: {
307
+ validate: {
308
+ options: {
309
+ stripUnknown: true,
310
+ abortEarly: false,
311
+ convert: true
312
+ },
313
+
314
+ failAction
315
+ }
316
+ }
317
+ });
318
+ }
319
+
320
+ module.exports = (server, args) => {
321
+ registerGetConfigLicense(server, args);
322
+ registerPostConfigLicense(server, args);
323
+ registerPostConfigLicenseDelete(server, args);
324
+ registerPostConfigLicenseRecheck(server, args);
325
+ registerPostConfigLicenseTrial(server, args);
326
+ };
@@ -348,6 +348,30 @@ function stripReservedClasses(html) {
348
348
  });
349
349
  }
350
350
 
351
+ // The largest message body (HTML and plain text together, in characters) parsed into web-safe HTML.
352
+ // The conversion parses the whole body into a DOM on a shared worker, and its cost grows with the
353
+ // input: about 2.4 s and 360 MB of heap for 2 MB. Any sender chooses the body, and it was bounded
354
+ // only by notifyTextSize for webhooks, which an operator can clear, and not at all for an API fetch;
355
+ // a body that killed the worker was converted again after every restart.
356
+ const WEB_SAFE_HTML_MAX_INPUT = 2 * 1024 * 1024;
357
+
358
+ /**
359
+ * Whether a message body is small enough to parse into web-safe HTML.
360
+ *
361
+ * @param {Object} text - `{ html, plain }`
362
+ * @returns {boolean}
363
+ */
364
+ function fitsWebSafeHtml(text) {
365
+ return ((text && text.html) || '').length + ((text && text.plain) || '').length <= WEB_SAFE_HTML_MAX_INPUT;
366
+ }
367
+
368
+ // What a body over the limit renders as: its plain text, escaped and cut at the limit, which costs
369
+ // nothing to produce and can not carry markup. A body with no plain part says so instead
370
+ function oversizedWebSafeHtml(text) {
371
+ const plain = typeof text.plain === 'string' ? text.plain.slice(0, WEB_SAFE_HTML_MAX_INPUT) : '';
372
+ return `<div style="white-space: pre-wrap">${he.escape(plain || 'This message is too large to display.')}</div>`;
373
+ }
374
+
351
375
  /**
352
376
  * Converts the bodies of a message object into sanitized, web-safe HTML.
353
377
  *
@@ -355,6 +379,10 @@ function stripReservedClasses(html) {
355
379
  * @returns {Promise<string>} Sanitized HTML
356
380
  */
357
381
  async function messageWebSafeHtml(messageData) {
382
+ if (!fitsWebSafeHtml(messageData.text)) {
383
+ return oversizedWebSafeHtml(messageData.text);
384
+ }
385
+
358
386
  let html = stripReservedClasses(messageData.text.html);
359
387
  if (html !== messageData.text.html) {
360
388
  messageData = Object.assign({}, messageData, { text: Object.assign({}, messageData.text, { html }) });
@@ -440,6 +468,7 @@ function applyWebSafeHtmlOptions(options) {
440
468
  }
441
469
 
442
470
  module.exports = {
471
+ WEB_SAFE_HTML_MAX_INPUT,
443
472
  messageWebSafeHtml,
444
473
  webSafeTextResponse,
445
474
  applyWebSafeHtmlOptions,
@@ -7,12 +7,13 @@
7
7
  // in, see createWebhookProcessor().
8
8
 
9
9
  const { accountDataKey } = require('./redis-keys');
10
- const { UnrecoverableError, DelayedError } = require('bullmq');
10
+ const { UnrecoverableError } = require('bullmq');
11
11
 
12
12
  const { redactUrlCredentials, splitUrlCredentials } = require('./tools');
13
13
  const { sendWebhookRequest, isUnrecoverableWebhookError, baseDeliveryHeaders, signDelivery } = require('./webhook-request');
14
14
  const { willBeFinalAttempt } = require('./delivery-error');
15
15
  const { penaltyKey, penaltyFor } = require('./webhook-penalty');
16
+ const { delayWhilePenalised, setPenalty } = require('./queue-job-actions');
16
17
  const {
17
18
  resolveTargetUrl,
18
19
  isDeliverableRoute,
@@ -121,7 +122,7 @@ function parseAccountHeaders(json, job, logger) {
121
122
  /**
122
123
  * Delays the job while its target is penalised; see lib/webhook-penalty.js. The attempt count is
123
124
  * not spent by the wait
124
- * @returns {Promise<string|null>} The target's penalty key, for recordFailure()
125
+ * @returns {Promise<string|null>} The target's penalty key, for penaliseTarget() after the attempt
125
126
  * @throws {DelayedError} When the job was moved to the delayed set
126
127
  */
127
128
  async function waitOutPenalty(job, token, webhooks, deps) {
@@ -129,18 +130,15 @@ async function waitOutPenalty(job, token, webhooks, deps) {
129
130
  if (!targetPenaltyKey) {
130
131
  return null;
131
132
  }
132
- let remaining = await deps.redis.pttl(targetPenaltyKey);
133
- if (remaining > 0) {
133
+ await delayWhilePenalised(job, token, deps.redis, targetPenaltyKey, delay =>
134
134
  deps.logger.debug({
135
135
  msg: 'Webhook target is penalised, delaying delivery',
136
136
  ...jobLogFields(job),
137
137
  code: 'target_penalised',
138
138
  webhooks: redactUrlCredentials(webhooks),
139
- delay: remaining
140
- });
141
- await job.moveToDelayed(Date.now() + remaining, token);
142
- throw new DelayedError();
143
- }
139
+ delay
140
+ })
141
+ );
144
142
  return targetPenaltyKey;
145
143
  }
146
144
 
@@ -293,26 +291,25 @@ async function writeErrorFlag(plan, flag, deps) {
293
291
  }
294
292
  }
295
293
 
294
+ async function penaliseTarget(plan, err, duration, deps) {
295
+ if (plan.targetPenaltyKey) {
296
+ await setPenalty(deps.redis, plan.targetPenaltyKey, penaltyFor(err, deps.timeout || DEFAULT_WEBHOOK_REQUEST_TIMEOUT, duration));
297
+ }
298
+ }
299
+
296
300
  /**
297
301
  * Records a failed attempt everywhere it is read back: the target penalty, the job's progress
298
302
  * field (for the queue browser), the log, the error flag and the metrics
299
303
  */
300
304
  async function recordFailure(job, plan, request, err, duration, deps) {
301
- const { redis, logger } = deps;
305
+ const { logger } = deps;
302
306
 
303
307
  // egress and redirect failures are thrown as UnrecoverableError, so they are final as well
304
308
  let isFinalAttempt = willBeFinalAttempt(job) || isUnrecoverableWebhookError(err);
305
309
 
306
- // A target that held the attempt until it timed out is penalised so the next deliveries to
307
- // it do not each cost the same wait
308
- let penalty = penaltyFor(err, deps.timeout || DEFAULT_WEBHOOK_REQUEST_TIMEOUT);
309
- if (penalty && plan.targetPenaltyKey) {
310
- try {
311
- await redis.set(plan.targetPenaltyKey, '1', 'PX', penalty);
312
- } catch (penaltyErr) {
313
- // a missed penalty costs the queue one more timeout, nothing else
314
- }
315
- }
310
+ // A target that held the attempt until it timed out, or for most of it, is penalised so the
311
+ // next deliveries to it do not each cost the same wait
312
+ await penaliseTarget(plan, err, duration, deps);
316
313
 
317
314
  // BullMQ keeps only the message of a failure on the job. The code and the HTTP status
318
315
  // are what explain it, so they are recorded the way the submit worker records its own
@@ -407,6 +404,10 @@ async function deliver(job, plan, deps) {
407
404
  await writeErrorFlag(plan, null, deps);
408
405
  deps.metrics('webhooks', 'inc', { event: job.name, status: 'success' });
409
406
 
407
+ // A delivery the receiver answered only after holding the worker for most of the attempt
408
+ // timeout costs the other accounts the same as a failed one
409
+ await penaliseTarget(plan, null, duration, deps);
410
+
410
411
  // Stored by BullMQ as the job's return value in the same write that completes it, so
411
412
  // a retained completed job shows what the endpoint answered and how long it took
412
413
  return { status: 'delivered', statusCode: status, duration };
@@ -6,18 +6,19 @@
6
6
  // that accepts the connection and never answers costs the whole attempt timeout (30 seconds by
7
7
  // default). One account pointing its own webhook URL at such a target, and generating a dozen
8
8
  // events a minute, kept the queue busy with timeouts and delayed every other account's
9
- // deliveries behind them, indefinitely. So a target whose attempt just ran into the timeout is
10
- // penalised: for a short while, deliveries to the same origin are moved back to the delayed set
9
+ // deliveries behind them, indefinitely. So a target whose attempt held the worker for most of the
10
+ // timeout is penalised: for a short while, deliveries to the same origin are moved back to the delayed set
11
11
  // instead of being attempted, and the queue spends its time on targets that answer. The
12
12
  // penalised delivery is not lost, it is tried again once the penalty is over, with its attempt
13
13
  // count unchanged.
14
14
  //
15
- // Only the slow failures count. A refused or reset connection and a name that does not resolve
16
- // fail in milliseconds, so they never hold the queue, and penalising them would defer every
17
- // delivery to a receiver for a minute because it was restarting when one attempt arrived. A
18
- // target answering with an HTTP status, any status, is not penalised either: it answered
19
- // quickly, and the retry schedule already spaces those out. Nor is an egress or redirect
20
- // refusal, which fails the job for good anyway.
15
+ // Only the slow attempts count: one that ran into a deadline, and one that held the worker for at
16
+ // least half the attempt timeout before it ended, whatever the receiver answered. The receiver
17
+ // chooses its answer, so keying on it let a target hold every attempt just short of the timeout
18
+ // and answer 500, or 200, and never be penalised. A refused or reset connection and a name that
19
+ // does not resolve fail in milliseconds, so they never hold the queue, and penalising them would
20
+ // defer every delivery to a receiver for a minute because it was restarting when one attempt
21
+ // arrived. Nor is an egress or redirect refusal penalised, which fails the job for good anyway.
21
22
 
22
23
  const { createHash } = require('crypto');
23
24
  const { REDIS_PREFIX } = require('./consts');
@@ -50,19 +51,19 @@ function penaltyKey(url) {
50
51
  }
51
52
 
52
53
  /**
53
- * How long a target is penalised after a failed attempt, in milliseconds; 0 when the failure is
54
- * not the kind that holds the queue.
54
+ * How long a target is penalised after an attempt, in milliseconds; 0 when the attempt is not the
55
+ * kind that holds the queue.
55
56
  *
56
- * @param {Error} err - the failure
57
+ * @param {Error|null} err - the failure, or null for a delivered attempt
57
58
  * @param {Number} attemptTimeout - the per-attempt wall clock cap, in milliseconds
59
+ * @param {Number} [duration] - how long the attempt took, in milliseconds
58
60
  * @returns {Number}
59
61
  */
60
- function penaltyFor(err, attemptTimeout) {
61
- if (!err || typeof err !== 'object') {
62
- return 0;
63
- }
64
- let code = err.code || (err.cause && err.cause.code);
65
- if (!code || !SLOW_FAILURE_CODES.has(code)) {
62
+ function penaltyFor(err, attemptTimeout, duration) {
63
+ let code = err && typeof err === 'object' && (err.code || (err.cause && err.cause.code));
64
+ let timedOut = !!code && SLOW_FAILURE_CODES.has(code);
65
+ let slow = Number(attemptTimeout) > 0 && Number(duration) >= Number(attemptTimeout) / 2;
66
+ if (!timedOut && !slow) {
66
67
  return 0;
67
68
  }
68
69
  // twice the attempt cap: long enough that a dozen events a minute to a dead target no
package/lib/webhooks.js CHANGED
@@ -631,6 +631,13 @@ class WebhooksHandler {
631
631
  } else if (data.text && truncateTextContents(data.text, notifyTextSize)) {
632
632
  data.text.hasMore = true;
633
633
  }
634
+
635
+ // The web-safe copy replaces the HTML below, after this limit was applied to the HTML,
636
+ // so it is held to the same limit: with inline images embedded it can be far larger
637
+ if (data.text && notifyText && notifyTextSize && typeof data.text._generatedHtml === 'string' && data.text._generatedHtml.length > notifyTextSize) {
638
+ data.text._generatedHtml = data.text._generatedHtml.substr(0, notifyTextSize);
639
+ data.text.hasMore = true;
640
+ }
634
641
  }
635
642
 
636
643
  if (data.headers) {
@@ -655,6 +662,17 @@ class WebhooksHandler {
655
662
  delete data.otp;
656
663
  }
657
664
 
665
+ // Calendar files are attachments too, and their description is message text: both used to
666
+ // be copied in whole whatever the two limits said
667
+ for (let calendarEvent of data.calendarEvents || []) {
668
+ if (calendarEvent.content && !withinNotifyAttachmentSize(calendarEvent, notifyAttachmentSize)) {
669
+ delete calendarEvent.content;
670
+ }
671
+ if (notifyTextSize && typeof calendarEvent.description === 'string' && calendarEvent.description.length > notifyTextSize) {
672
+ calendarEvent.description = calendarEvent.description.substr(0, notifyTextSize);
673
+ }
674
+ }
675
+
658
676
  // remove attachment contents
659
677
  if (data.attachments) {
660
678
  for (let attachment of data.attachments) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "emailengine-app",
3
- "version": "2.87.2",
3
+ "version": "2.88.0",
4
4
  "private": false,
5
5
  "productTitle": "EmailEngine",
6
6
  "description": "Email Sync Engine",
@@ -65,26 +65,26 @@
65
65
  "@hapi/vision": "7.0.3",
66
66
  "@msgpack/msgpack": "3.1.3",
67
67
  "@postalsys/bounce-classifier": "3.1.0",
68
- "@postalsys/certs": "2.0.4",
69
- "@postalsys/email-ai-tools": "2.4.2",
70
- "@postalsys/email-content": "0.1.20",
71
- "@postalsys/email-text-tools": "2.6.3",
68
+ "@postalsys/certs": "2.0.5",
69
+ "@postalsys/email-ai-tools": "2.4.3",
70
+ "@postalsys/email-content": "0.1.21",
71
+ "@postalsys/email-text-tools": "2.6.4",
72
72
  "@postalsys/gettext": "4.3.0",
73
73
  "@postalsys/joi-messages": "1.4.1",
74
74
  "@postalsys/templates": "2.1.1",
75
75
  "@sentry/node-core": "10.78.0",
76
- "@simplewebauthn/server": "14.0.3",
76
+ "@simplewebauthn/server": "14.1.0",
77
77
  "@zone-eu/mailsplit": "5.4.30",
78
78
  "@zone-eu/wild-config": "1.7.10",
79
- "bullmq": "6.7.0",
80
- "dotenv": "18.0.9",
79
+ "bullmq": "6.7.3",
80
+ "dotenv": "18.0.10",
81
81
  "fast-xml-parser": "5.12.0",
82
82
  "handlebars": "4.7.10",
83
83
  "he": "1.2.0",
84
84
  "html-to-text": "10.0.1",
85
85
  "ical.js": "2.2.1",
86
86
  "iconv-lite": "0.7.3",
87
- "imapflow": "2.10.2",
87
+ "imapflow": "2.11.0",
88
88
  "ioredfour": "2.2.0",
89
89
  "ioredis": "6.0.0",
90
90
  "ipaddr.js": "2.5.0",
@@ -92,27 +92,27 @@
92
92
  "libbase64": "1.4.1",
93
93
  "libmime": "5.6.4",
94
94
  "libqp": "3.0.1",
95
- "mailparser": "3.14.2",
95
+ "mailparser": "3.14.3",
96
96
  "marked": "15.0.12",
97
97
  "minimist": "1.2.8",
98
- "nodemailer": "10.3.1",
98
+ "nodemailer": "10.5.0",
99
99
  "pino": "10.3.1",
100
100
  "prom-client": "15.1.3",
101
101
  "pubface": "1.2.0",
102
102
  "punycode.js": "2.3.1",
103
103
  "qrcode-generator": "2.0.4",
104
- "smtp-server": "3.21.3",
104
+ "smtp-server": "3.21.4",
105
105
  "socks": "2.8.10",
106
- "undici": "7.30.1"
106
+ "undici": "7.30.2"
107
107
  },
108
108
  "devDependencies": {
109
109
  "@eslint/js": "10.0.1",
110
- "@iconify-json/tabler": "1.2.43",
110
+ "@iconify-json/tabler": "1.2.44",
111
111
  "@iconify/tailwind4": "1.2.3",
112
112
  "@playwright/test": "1.63.0",
113
113
  "@postalsys/ee-client": "1.10.0",
114
114
  "@simplewebauthn/browser": "14.0.0",
115
- "@tailwindcss/cli": "4.3.4",
115
+ "@tailwindcss/cli": "4.3.5",
116
116
  "ace-builds": "1.45.2",
117
117
  "acorn": "8.19.0",
118
118
  "acorn-walk": "8.3.5",
@@ -125,9 +125,9 @@
125
125
  "pino-pretty": "13.2.0",
126
126
  "prettier": "3.9.10",
127
127
  "resedit": "3.1.0",
128
- "spdx-satisfies": "6.0.0",
129
- "supertest": "7.3.1",
130
- "tailwindcss": "4.3.4",
128
+ "spdx-satisfies": "6.0.1",
129
+ "supertest": "7.3.2",
130
+ "tailwindcss": "4.3.5",
131
131
  "xgettext-template": "5.0.0"
132
132
  },
133
133
  "overrides": {