emailengine-app 2.87.2 → 2.89.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 (71) hide show
  1. package/.ncurc.js +24 -44
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +37 -0
  4. package/ENVIRONMENT.md +26 -23
  5. package/LICENSE_EMAILENGINE.txt +20 -12
  6. package/app.json +3 -3
  7. package/bin/emailengine.js +7 -11
  8. package/data/google-crawlers.json +1 -1
  9. package/data/public_suffix_list.dat +155 -16
  10. package/lib/account.js +69 -49
  11. package/lib/admin-password.js +85 -0
  12. package/lib/api-routes/license-routes.js +9 -0
  13. package/lib/api-token-auth.js +21 -5
  14. package/lib/calendar-event.js +15 -3
  15. package/lib/consts.js +5 -0
  16. package/lib/db.js +1 -0
  17. package/lib/email-client/base-client.js +36 -15
  18. package/lib/email-client/gmail-client.js +20 -6
  19. package/lib/email-client/imap/connection-errors.js +30 -1
  20. package/lib/email-client/imap/session-expiry.js +83 -0
  21. package/lib/email-client/imap-client.js +12 -2
  22. package/lib/email-client/smtp-pool-manager.js +66 -8
  23. package/lib/export.js +147 -22
  24. package/lib/graph-notifications.js +60 -0
  25. package/lib/imap-proxy-auth.js +52 -18
  26. package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
  27. package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
  28. package/lib/imapproxy/imap-server.js +10 -1
  29. package/lib/imapproxy/proxy-handoff.js +100 -5
  30. package/lib/license-subscription.js +244 -0
  31. package/lib/node-version.js +99 -12
  32. package/lib/oauth/gmail.js +18 -0
  33. package/lib/oauth/outlook-identity.js +54 -12
  34. package/lib/prepared-password.js +38 -0
  35. package/lib/queue-browser/index.js +6 -6
  36. package/lib/queue-job-actions.js +59 -4
  37. package/lib/read-env-value.js +46 -21
  38. package/lib/redis-url.js +23 -0
  39. package/lib/response-stream.js +69 -1
  40. package/lib/revocation-events.js +79 -0
  41. package/lib/schemas.js +18 -2
  42. package/lib/settings.js +50 -24
  43. package/lib/sso.js +23 -0
  44. package/lib/submit-penalty.js +24 -0
  45. package/lib/submit-processor.js +10 -2
  46. package/lib/tokens.js +6 -0
  47. package/lib/tools.js +90 -18
  48. package/lib/ui-routes/admin-config-routes.js +3 -276
  49. package/lib/ui-routes/auth-routes.js +13 -64
  50. package/lib/ui-routes/dashboard-routes.js +4 -0
  51. package/lib/ui-routes/license-routes.js +326 -0
  52. package/lib/web-safe-html.js +74 -1
  53. package/lib/webhook-delivery.js +21 -20
  54. package/lib/webhook-penalty.js +18 -17
  55. package/lib/webhooks.js +18 -0
  56. package/list-generate.js +56 -19
  57. package/package.json +28 -31
  58. package/sbom.json +373 -964
  59. package/scan.js +2 -0
  60. package/server.js +273 -100
  61. package/static/css/flyonui.css +2 -2
  62. package/static/js/ui.js +11 -4
  63. package/static/licenses.html +1108 -504
  64. package/translations/messages.pot +18 -18
  65. package/views/config/license.hbs +43 -16
  66. package/views/dashboard.hbs +9 -0
  67. package/views/partials/side_menu.hbs +1 -1
  68. package/views/upgrade.hbs +25 -0
  69. package/workers/api.js +108 -107
  70. package/workers/imap.js +4 -6
  71. package/lib/net-tos-guard.js +0 -42
@@ -13,6 +13,7 @@ const { formBoolean } = require('../schemas');
13
13
  const crypto = require('crypto');
14
14
  const { parentPort } = require('worker_threads');
15
15
  const pbkdf2 = require('../pbkdf2-phc');
16
+ const { verifyAdminPassword, verifyCurrentPassword, setAdminPassword } = require('../admin-password');
16
17
  const { generateTotpSeed, verifyTotp, generateTotpUrl, generateTotpQrDataUrl } = require('../totp');
17
18
  const {
18
19
  generateRegistrationOptions,
@@ -115,46 +116,6 @@ function passkeyTimestamp(value) {
115
116
  return date && !isNaN(date.getTime()) ? date.toISOString() : null;
116
117
  }
117
118
 
118
- // Single place that knows how a failed password check is interpreted: an absent password and a
119
- // verify() that throws (which happens only on a malformed stored hash, never on a wrong password)
120
- // are both failures, never a pass. Sign-in, the password change and both passkey registration
121
- // steps all come through here, so a change to how the account password is checked - a KDF swap,
122
- // a dummy verify to flatten timing - lands in one place.
123
- async function verifyAdminPassword(hash, password, logger) {
124
- if (!password) {
125
- return false;
126
- }
127
- try {
128
- return await pbkdf2.verify(hash, password);
129
- } catch (err) {
130
- logger.error({ msg: 'Failed to verify password hash', err });
131
- return false;
132
- }
133
- }
134
-
135
- // The current-password check behind the security page's step-down actions (the password change
136
- // and switching the second factor off). A live session alone is not supposed to reveal the
137
- // password, and unthrottled the field let a hijacked session guess it at full speed, so the
138
- // check is rate limited the way the login form is: keyed on the account rather than the address
139
- // because the caller is already authenticated as it, and with the login form's per-username
140
- // budget. Owns the limiter and the warn logs; the caller decides how to report the failure.
141
- //
142
- // @returns {Promise<{ ok: true } | { ok: false, reason: 'rateLimited' | 'invalid', message: String }>}
143
- async function verifyCurrentPassword(request, h, authData, password) {
144
- let rateLimit = await h.checkRateLimit(`password:verify:${authData.user || 'admin'}`, 1, 10, 60);
145
- if (!rateLimit.success) {
146
- request.logger.warn({ msg: 'Rate limited', rateLimit, remoteAddress: request.app.ip });
147
- return { ok: false, reason: 'rateLimited', message: 'Rate limited, please wait and try again' };
148
- }
149
-
150
- if (!(await verifyAdminPassword(authData.password, password, request.logger))) {
151
- request.logger.warn({ msg: 'Invalid current password', remoteAddress: request.app.ip });
152
- return { ok: false, reason: 'invalid', message: 'Invalid password' };
153
- }
154
-
155
- return { ok: true };
156
- }
157
-
158
119
  // Sends a refused step-down action on the security page back to the page with the reason
159
120
  async function refuseSecurityAction(request, h, verified) {
160
121
  await request.flash({ type: 'danger', message: verified.message });
@@ -1136,9 +1097,12 @@ function registerPostAccountPasskeysRegisterOptions(server) {
1136
1097
  }
1137
1098
 
1138
1099
  // Last, because it is the expensive check: the request is refused for a missing
1139
- // Service URL or a full list without paying for a PBKDF2 verification first
1140
- if (!(await verifyAdminPassword(authData.password, request.payload.password, request.logger))) {
1141
- return h.response({ error: 'Invalid password' }).code(403);
1100
+ // Service URL or a full list without paying for a PBKDF2 verification first.
1101
+ // Through the per-account budget the other step-down checks use: the per-address
1102
+ // limit above alone let a hijacked session guess the password from many addresses
1103
+ let verified = await verifyCurrentPassword(request, h, authData, request.payload.password);
1104
+ if (!verified.ok) {
1105
+ return h.response({ error: verified.message }).code(verified.statusCode);
1142
1106
  }
1143
1107
 
1144
1108
  let options = await generateRegistrationOptions({
@@ -1213,7 +1177,7 @@ function registerPostAccountPasskeysRegisterVerify(server) {
1213
1177
  // change, so a hijacked session gets no second password-guessing surface here
1214
1178
  let verified = await verifyCurrentPassword(request, h, authData, request.payload.password);
1215
1179
  if (!verified.ok) {
1216
- return h.response({ error: verified.message }).code(verified.reason === 'rateLimited' ? 429 : 403);
1180
+ return h.response({ error: verified.message }).code(verified.statusCode);
1217
1181
  }
1218
1182
 
1219
1183
  let challenge = await passkeys.consumeChallenge(request.payload.challengeId, passkeys.CHALLENGE_REGISTER);
@@ -1573,26 +1537,11 @@ function registerPostAccountPassword(server) {
1573
1537
  }
1574
1538
  }
1575
1539
 
1576
- const passwordHash = await pbkdf2.hash(request.payload.password);
1577
-
1578
- authData = authData || {};
1579
- authData.user = authData.user || 'admin';
1580
- authData.password = passwordHash;
1581
- authData.passwordVersion = Date.now();
1582
-
1583
- await settings.set('authData', authData);
1584
-
1585
- // Every passkey goes with the old password: registering one takes the password,
1586
- // so a passkey that outlived a password change could be one registered by whoever
1587
- // had the old password. The form warns about this while passkeys exist, and the
1588
- // flash below says how many went.
1589
- let clearedPasskeys = 0;
1590
- try {
1591
- clearedPasskeys = await passkeys.deleteAllCredentials(authData.user || 'admin');
1592
- request.logger.info({ msg: 'All passkeys cleared after password change', user: authData.user || 'admin', cleared: clearedPasskeys });
1593
- } catch (passkeyErr) {
1594
- request.logger.error({ msg: 'Failed to clear passkeys after password change', err: passkeyErr });
1595
- }
1540
+ // Every passkey goes with the old password (see setAdminPassword()). The form
1541
+ // warns about this while passkeys exist, and the flash below says how many went.
1542
+ const changed = await setAdminPassword(await pbkdf2.hash(request.payload.password), { settings, passkeys, logger: request.logger }, authData);
1543
+ authData = changed.authData;
1544
+ const clearedPasskeys = changed.clearedPasskeys;
1596
1545
 
1597
1546
  if (!server.auth.settings.default) {
1598
1547
  server.auth.default('session');
@@ -11,6 +11,8 @@ const { redis } = require('../db');
11
11
  const { ALLOWED_REDIS_LATENCY } = require('../consts');
12
12
  const { ACCOUNT_STATE_DISPLAY } = require('./route-helpers');
13
13
  const { ERROR_STATES } = require('../account/account-state');
14
+ // The release a process runs on does not change, so neither does what the pages say about it
15
+ const NODE_RUNTIME = require('../node-version').nodeRuntimeView(process.versions.node, !!process.pkg);
14
16
 
15
17
  function init(args) {
16
18
  const { server, call } = args;
@@ -91,6 +93,7 @@ function init(args) {
91
93
  activityWindows,
92
94
 
93
95
  redisWarnings: stats.redisWarnings || [],
96
+ nodeRuntime: NODE_RUNTIME,
94
97
 
95
98
  redisPing: {
96
99
  key: 'redisPing',
@@ -159,6 +162,7 @@ function init(args) {
159
162
  'upgrade',
160
163
  {
161
164
  pageTitle: 'Upgrade',
165
+ nodeRuntime: NODE_RUNTIME,
162
166
  isDO,
163
167
  isRender,
164
168
  isScriptInstalled,
@@ -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,68 @@ 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 renders as when it is not converted: its plain text, escaped and cut at the limit,
369
+ // which costs nothing to produce and can not carry markup. A body with no plain part says why instead
370
+ function plainWebSafeHtml(text, reason) {
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 || reason)}</div>`;
373
+ }
374
+
375
+ /**
376
+ * Returns a function that hands out mimeHtml(), or null once loading it has failed.
377
+ *
378
+ * mimeHtml loads jsdom and juice from the bundles in @postalsys/email-text-tools, which need a
379
+ * newer Node.js than EmailEngine can start on (the undici inside jsdom throws when it is loaded on a
380
+ * release below 22.19, and the range jsdom declares starts at 22.22.2, see lib/node-version.js).
381
+ * A failed require() is not cached, so trying again would parse the whole bundle for every
382
+ * message: the first failure is logged and remembered, and web-safe HTML falls back to escaped
383
+ * plain text for the life of the process.
384
+ *
385
+ * @param {Function} load - Returns mimeHtml, throws when it can not be loaded
386
+ * @returns {Function} Returns mimeHtml or null
387
+ */
388
+ function createMimeHtmlLoader(load) {
389
+ let failed = false;
390
+ let mimeHtml = null;
391
+ return () => {
392
+ if (mimeHtml || failed) {
393
+ return mimeHtml;
394
+ }
395
+ try {
396
+ mimeHtml = load();
397
+ return mimeHtml;
398
+ } catch (err) {
399
+ failed = true;
400
+ logger.error({
401
+ msg: 'Failed to load the HTML sanitizer, web-safe HTML falls back to plain text',
402
+ nodeVersion: process.versions.node,
403
+ err
404
+ });
405
+ return null;
406
+ }
407
+ };
408
+ }
409
+
410
+ // Resolved at call time: touching textTools.mimeHtml is what loads jsdom
411
+ const getMimeHtml = createMimeHtmlLoader(() => textTools.mimeHtml);
412
+
351
413
  /**
352
414
  * Converts the bodies of a message object into sanitized, web-safe HTML.
353
415
  *
@@ -355,6 +417,15 @@ function stripReservedClasses(html) {
355
417
  * @returns {Promise<string>} Sanitized HTML
356
418
  */
357
419
  async function messageWebSafeHtml(messageData) {
420
+ if (!fitsWebSafeHtml(messageData.text)) {
421
+ return plainWebSafeHtml(messageData.text, 'This message is too large to display.');
422
+ }
423
+
424
+ const mimeHtml = getMimeHtml();
425
+ if (!mimeHtml) {
426
+ return plainWebSafeHtml(messageData.text, 'This message can not be displayed: the HTML sanitizer failed to load.');
427
+ }
428
+
358
429
  let html = stripReservedClasses(messageData.text.html);
359
430
  if (html !== messageData.text.html) {
360
431
  messageData = Object.assign({}, messageData, { text: Object.assign({}, messageData.text, { html }) });
@@ -377,7 +448,7 @@ async function messageWebSafeHtml(messageData) {
377
448
 
378
449
  // mimeHtml() does not throw: on hostile input (thousands of nested elements or quote levels)
379
450
  // it falls back to escaped text itself, which is what the catch that used to be here did
380
- return textTools.mimeHtml(source);
451
+ return mimeHtml(source);
381
452
  }
382
453
 
383
454
  /**
@@ -440,6 +511,8 @@ function applyWebSafeHtmlOptions(options) {
440
511
  }
441
512
 
442
513
  module.exports = {
514
+ WEB_SAFE_HTML_MAX_INPUT,
515
+ createMimeHtmlLoader,
443
516
  messageWebSafeHtml,
444
517
  webSafeTextResponse,
445
518
  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 };