emailengine-app 2.87.1 → 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 (73) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +31 -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/dbsc/index.js +292 -0
  17. package/lib/dbsc/jwt.js +157 -0
  18. package/lib/dbsc/protocol.js +132 -0
  19. package/lib/dbsc/store.js +136 -0
  20. package/lib/email-client/base-client.js +36 -15
  21. package/lib/email-client/gmail-client.js +20 -6
  22. package/lib/email-client/imap/connection-errors.js +30 -1
  23. package/lib/email-client/imap/session-expiry.js +83 -0
  24. package/lib/email-client/imap-client.js +12 -2
  25. package/lib/email-client/smtp-pool-manager.js +66 -8
  26. package/lib/export.js +147 -22
  27. package/lib/graph-notifications.js +60 -0
  28. package/lib/imap-proxy-auth.js +52 -18
  29. package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
  30. package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
  31. package/lib/imapproxy/imap-server.js +10 -1
  32. package/lib/imapproxy/proxy-handoff.js +100 -5
  33. package/lib/license-subscription.js +238 -0
  34. package/lib/oauth/gmail.js +18 -0
  35. package/lib/oauth/outlook-identity.js +54 -12
  36. package/lib/prepared-password.js +38 -0
  37. package/lib/privileged-settings.js +6 -0
  38. package/lib/queue-browser/index.js +6 -6
  39. package/lib/queue-job-actions.js +59 -4
  40. package/lib/read-env-value.js +46 -21
  41. package/lib/redis-url.js +23 -0
  42. package/lib/response-stream.js +69 -1
  43. package/lib/revocation-events.js +79 -0
  44. package/lib/routes-ui.js +4 -1
  45. package/lib/schemas.js +26 -2
  46. package/lib/session-default.js +13 -3
  47. package/lib/settings.js +47 -24
  48. package/lib/sso.js +23 -0
  49. package/lib/submit-penalty.js +24 -0
  50. package/lib/submit-processor.js +10 -2
  51. package/lib/tokens.js +6 -0
  52. package/lib/tools.js +86 -15
  53. package/lib/ui-routes/admin-config-routes.js +30 -281
  54. package/lib/ui-routes/auth-routes.js +17 -64
  55. package/lib/ui-routes/dbsc-routes.js +43 -0
  56. package/lib/ui-routes/license-routes.js +326 -0
  57. package/lib/web-safe-html.js +29 -0
  58. package/lib/webhook-delivery.js +21 -20
  59. package/lib/webhook-penalty.js +18 -17
  60. package/lib/webhooks.js +18 -0
  61. package/package.json +18 -18
  62. package/sbom.json +294 -294
  63. package/scan.js +2 -0
  64. package/server.js +253 -80
  65. package/static/css/flyonui.css +2 -2
  66. package/static/js/ui.js +11 -4
  67. package/static/licenses.html +27 -27
  68. package/translations/messages.pot +17 -17
  69. package/views/config/license.hbs +43 -16
  70. package/views/config/security.hbs +37 -0
  71. package/views/partials/side_menu.hbs +1 -1
  72. package/workers/api.js +128 -109
  73. package/workers/imap.js +4 -6
@@ -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,
@@ -30,6 +31,7 @@ const PASSKEY_ALGORITHMS = [-7, -257];
30
31
  const settings = require('../settings');
31
32
  const consts = require('../consts');
32
33
  const { readEnvValue, setAdminSession } = require('../tools');
34
+ const { endDeviceBinding } = require('../dbsc');
33
35
  const passkeys = require('../passkeys');
34
36
  const sso = require('../sso');
35
37
  const { redis } = require('../db');
@@ -114,46 +116,6 @@ function passkeyTimestamp(value) {
114
116
  return date && !isNaN(date.getTime()) ? date.toISOString() : null;
115
117
  }
116
118
 
117
- // Single place that knows how a failed password check is interpreted: an absent password and a
118
- // verify() that throws (which happens only on a malformed stored hash, never on a wrong password)
119
- // are both failures, never a pass. Sign-in, the password change and both passkey registration
120
- // steps all come through here, so a change to how the account password is checked - a KDF swap,
121
- // a dummy verify to flatten timing - lands in one place.
122
- async function verifyAdminPassword(hash, password, logger) {
123
- if (!password) {
124
- return false;
125
- }
126
- try {
127
- return await pbkdf2.verify(hash, password);
128
- } catch (err) {
129
- logger.error({ msg: 'Failed to verify password hash', err });
130
- return false;
131
- }
132
- }
133
-
134
- // The current-password check behind the security page's step-down actions (the password change
135
- // and switching the second factor off). A live session alone is not supposed to reveal the
136
- // password, and unthrottled the field let a hijacked session guess it at full speed, so the
137
- // check is rate limited the way the login form is: keyed on the account rather than the address
138
- // because the caller is already authenticated as it, and with the login form's per-username
139
- // budget. Owns the limiter and the warn logs; the caller decides how to report the failure.
140
- //
141
- // @returns {Promise<{ ok: true } | { ok: false, reason: 'rateLimited' | 'invalid', message: String }>}
142
- async function verifyCurrentPassword(request, h, authData, password) {
143
- let rateLimit = await h.checkRateLimit(`password:verify:${authData.user || 'admin'}`, 1, 10, 60);
144
- if (!rateLimit.success) {
145
- request.logger.warn({ msg: 'Rate limited', rateLimit, remoteAddress: request.app.ip });
146
- return { ok: false, reason: 'rateLimited', message: 'Rate limited, please wait and try again' };
147
- }
148
-
149
- if (!(await verifyAdminPassword(authData.password, password, request.logger))) {
150
- request.logger.warn({ msg: 'Invalid current password', remoteAddress: request.app.ip });
151
- return { ok: false, reason: 'invalid', message: 'Invalid password' };
152
- }
153
-
154
- return { ok: true };
155
- }
156
-
157
119
  // Sends a refused step-down action on the security page back to the page with the reason
158
120
  async function refuseSecurityAction(request, h, verified) {
159
121
  await request.flash({ type: 'danger', message: verified.message });
@@ -333,6 +295,9 @@ function registerGetLogout(server) {
333
295
  logoutUrl = await h.oidcLogoutUrl(artifacts.idToken);
334
296
  }
335
297
 
298
+ // Before the cookie is cleared: the binding is found by the session's sid
299
+ await endDeviceBinding(request, h);
300
+
336
301
  if (request.cookieAuth) {
337
302
  request.cookieAuth.clear();
338
303
  }
@@ -1132,9 +1097,12 @@ function registerPostAccountPasskeysRegisterOptions(server) {
1132
1097
  }
1133
1098
 
1134
1099
  // Last, because it is the expensive check: the request is refused for a missing
1135
- // Service URL or a full list without paying for a PBKDF2 verification first
1136
- if (!(await verifyAdminPassword(authData.password, request.payload.password, request.logger))) {
1137
- 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);
1138
1106
  }
1139
1107
 
1140
1108
  let options = await generateRegistrationOptions({
@@ -1209,7 +1177,7 @@ function registerPostAccountPasskeysRegisterVerify(server) {
1209
1177
  // change, so a hijacked session gets no second password-guessing surface here
1210
1178
  let verified = await verifyCurrentPassword(request, h, authData, request.payload.password);
1211
1179
  if (!verified.ok) {
1212
- return h.response({ error: verified.message }).code(verified.reason === 'rateLimited' ? 429 : 403);
1180
+ return h.response({ error: verified.message }).code(verified.statusCode);
1213
1181
  }
1214
1182
 
1215
1183
  let challenge = await passkeys.consumeChallenge(request.payload.challengeId, passkeys.CHALLENGE_REGISTER);
@@ -1569,26 +1537,11 @@ function registerPostAccountPassword(server) {
1569
1537
  }
1570
1538
  }
1571
1539
 
1572
- const passwordHash = await pbkdf2.hash(request.payload.password);
1573
-
1574
- authData = authData || {};
1575
- authData.user = authData.user || 'admin';
1576
- authData.password = passwordHash;
1577
- authData.passwordVersion = Date.now();
1578
-
1579
- await settings.set('authData', authData);
1580
-
1581
- // Every passkey goes with the old password: registering one takes the password,
1582
- // so a passkey that outlived a password change could be one registered by whoever
1583
- // had the old password. The form warns about this while passkeys exist, and the
1584
- // flash below says how many went.
1585
- let clearedPasskeys = 0;
1586
- try {
1587
- clearedPasskeys = await passkeys.deleteAllCredentials(authData.user || 'admin');
1588
- request.logger.info({ msg: 'All passkeys cleared after password change', user: authData.user || 'admin', cleared: clearedPasskeys });
1589
- } catch (passkeyErr) {
1590
- request.logger.error({ msg: 'Failed to clear passkeys after password change', err: passkeyErr });
1591
- }
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;
1592
1545
 
1593
1546
  if (!server.auth.settings.default) {
1594
1547
  server.auth.default('session');
@@ -0,0 +1,43 @@
1
+ 'use strict';
2
+
3
+ // The two endpoints of device-bound admin sessions (lib/dbsc/). The browser calls both on its own,
4
+ // not a page, which is why neither carries a crumb: what stands in for one is a signature over a
5
+ // challenge only this server issued, to this session, minutes ago.
6
+
7
+ const { REGISTRATION_PATH, REFRESH_PATH } = require('../dbsc/protocol');
8
+
9
+ /**
10
+ * The handlers find the DBSC instance on server.app, where workers/api.js publishes it with the
11
+ * session strategy (setupDbsc() in lib/dbsc), so registration needs nothing but the server
12
+ * @param {Object} args
13
+ * @param {Object} args.server - hapi server
14
+ */
15
+ function init(args) {
16
+ const { server } = args;
17
+
18
+ server.route({
19
+ method: 'POST',
20
+ path: REGISTRATION_PATH,
21
+ // The default session strategy: only a signed-in admin session can bind itself
22
+ handler: (request, h) => request.server.app.dbsc.register(request, h),
23
+ options: {
24
+ plugins: { crumb: false }
25
+ }
26
+ });
27
+
28
+ server.route({
29
+ method: 'POST',
30
+ path: REFRESH_PATH,
31
+ // Reads the session without requiring it. The browser acts on the status of this answer, and
32
+ // the redirect to the login page a required session would produce is one it ignores, so an
33
+ // ended session has to be told so in a body it understands instead
34
+ handler: (request, h) => request.server.app.dbsc.refresh(request, h),
35
+ options: {
36
+ auth: { strategy: 'session', mode: 'try' },
37
+ // dbsc.enforce: false - a missing bound cookie is what this route renews
38
+ plugins: { crumb: false, dbsc: { enforce: false } }
39
+ }
40
+ });
41
+ }
42
+
43
+ module.exports = init;
@@ -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 };