emailengine-app 2.79.0 → 2.79.1

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 (50) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +39 -0
  3. package/lib/account.js +43 -2
  4. package/lib/api-routes/permission-map.js +4 -0
  5. package/lib/api-routes/route-helpers.js +71 -0
  6. package/lib/api-routes/settings-routes.js +37 -14
  7. package/lib/api-routes/token-routes.js +290 -122
  8. package/lib/arf-detect.js +17 -4
  9. package/lib/bounce-detect.js +28 -17
  10. package/lib/consts.js +6 -0
  11. package/lib/db.js +6 -0
  12. package/lib/email-client/gmail-client.js +4 -7
  13. package/lib/email-client/imap/mailbox.js +35 -35
  14. package/lib/email-client/imap-client.js +49 -2
  15. package/lib/email-client/outlook-client.js +3 -10
  16. package/lib/lua/h-set-new-mark.lua +36 -0
  17. package/lib/message-port-stream.js +84 -1
  18. package/lib/oauth2-apps.js +84 -15
  19. package/lib/openapi/build-document.js +5 -1
  20. package/lib/schemas.js +2 -2
  21. package/lib/settings.js +23 -9
  22. package/lib/token-audit-log.js +32 -9
  23. package/lib/tokens.js +163 -66
  24. package/lib/ui-routes/account-routes.js +13 -6
  25. package/lib/ui-routes/admin-entities-routes.js +52 -17
  26. package/lib/ui-routes/oauth-config-routes.js +7 -7
  27. package/lib/ui-routes/route-helpers.js +28 -1
  28. package/lib/ui-routes/suppression-list-routes.js +14 -9
  29. package/lib/utils/decode-headers.js +42 -0
  30. package/lib/utils/header-map.js +48 -0
  31. package/lib/utils/unsafe-key.js +59 -0
  32. package/lib/webhook-routing.js +6 -2
  33. package/lib/webhooks.js +28 -0
  34. package/package.json +1 -1
  35. package/server.js +39 -17
  36. package/views/accounts/account.hbs +8 -8
  37. package/views/accounts/browse.hbs +1 -1
  38. package/views/accounts/edit.hbs +2 -2
  39. package/views/gateways/edit.hbs +1 -1
  40. package/views/gateways/gateway.hbs +2 -2
  41. package/views/gateways/index.hbs +7 -7
  42. package/views/partials/accounts_table.hbs +7 -7
  43. package/views/suppression-lists/list.hbs +1 -1
  44. package/views/templates/index.hbs +2 -2
  45. package/views/templates/template.hbs +1 -1
  46. package/views/tokens/index.hbs +22 -2
  47. package/views/tokens/new.hbs +10 -3
  48. package/workers/api.js +41 -47
  49. package/workers/imap.js +65 -72
  50. package/workers/webhooks.js +21 -1
@@ -10,13 +10,13 @@ const getSecret = require('../get-secret');
10
10
  const { failAction, verifyAccountInfo, formatPartialSecretKey } = require('../tools');
11
11
  const { templateSchemas, accountIdSchema, tokenPermissionsSchema } = require('../schemas');
12
12
  const tokenPermissionView = require('../token-permission-view');
13
- const { Account } = require('../account');
13
+ const { Account, accountExists } = require('../account');
14
14
  const { Gateway } = require('../gateway');
15
15
  const { templates } = require('../templates');
16
16
  const { webhooks } = require('../webhooks');
17
17
  const consts = require('../consts');
18
18
  const wellKnownServices = require('nodemailer/lib/well-known/services.json');
19
- const { authAwareLevel } = require('./route-helpers');
19
+ const { authAwareLevel, resolveKnownAccounts, adminUrl } = require('./route-helpers');
20
20
  const exampleWebhookPayloads = require('../payload-examples-webhooks.json');
21
21
 
22
22
  const { DEFAULT_PAGE_SIZE } = consts;
@@ -300,7 +300,7 @@ return payload;`)
300
300
  );
301
301
 
302
302
  await request.flash({ type: 'info', message: `Webhook created` });
303
- return h.redirect(`/admin/webhooks/webhook/${createRequest.id}`);
303
+ return h.redirect(adminUrl`/admin/webhooks/webhook/${createRequest.id}`);
304
304
  } catch (err) {
305
305
  await request.flash({ type: 'danger', message: `Couldn't create webhook. Try again.` });
306
306
  request.logger.error({ msg: 'Failed to create webhook route', err });
@@ -612,7 +612,7 @@ return payload;`)
612
612
  );
613
613
 
614
614
  await request.flash({ type: 'info', message: `Webhook saved` });
615
- return h.redirect(`/admin/webhooks/webhook/${request.payload.webhook}`);
615
+ return h.redirect(adminUrl`/admin/webhooks/webhook/${request.payload.webhook}`);
616
616
  } catch (err) {
617
617
  await request.flash({ type: 'danger', message: `Couldn't save webhook. Try again.` });
618
618
  request.logger.error({ msg: 'Failed to update webhook route', err });
@@ -760,7 +760,7 @@ return payload;`)
760
760
  } catch (err) {
761
761
  await request.flash({ type: 'danger', message: `Couldn't delete webhook. Try again.` });
762
762
  request.logger.error({ msg: 'Failed to delete webhook route', err, webhook: request.payload.webhook, remoteAddress: request.app.ip });
763
- return h.redirect(`/admin/webhooks/webhook/${request.payload.webhook}`);
763
+ return h.redirect(adminUrl`/admin/webhooks/webhook/${request.payload.webhook}`);
764
764
  }
765
765
  },
766
766
  options: {
@@ -1058,7 +1058,7 @@ return payload;`)
1058
1058
  );
1059
1059
 
1060
1060
  await request.flash({ type: 'info', message: `Template saved` });
1061
- return h.redirect(`/admin/templates/template/${request.payload.template}`);
1061
+ return h.redirect(adminUrl`/admin/templates/template/${request.payload.template}`);
1062
1062
  } catch (err) {
1063
1063
  await request.flash({ type: 'danger', message: `Couldn't save template. Try again.` });
1064
1064
  request.logger.error({ msg: 'Failed to update template', err });
@@ -1285,7 +1285,7 @@ return payload;`)
1285
1285
  );
1286
1286
 
1287
1287
  await request.flash({ type: 'info', message: `Template created` });
1288
- return h.redirect(`/admin/templates/template/${createRequest.id}`);
1288
+ return h.redirect(adminUrl`/admin/templates/template/${createRequest.id}`);
1289
1289
  } catch (err) {
1290
1290
  await request.flash({ type: 'danger', message: `Couldn't create template. Try again.` });
1291
1291
  request.logger.error({ msg: 'Failed to create template', err });
@@ -1420,7 +1420,7 @@ return payload;`)
1420
1420
  } catch (err) {
1421
1421
  await request.flash({ type: 'danger', message: `Couldn't delete template. Try again.` });
1422
1422
  request.logger.error({ msg: 'Failed to delete the template', err, template: request.payload.template, remoteAddress: request.app.ip });
1423
- return h.redirect(`/admin/templates/template/${request.payload.template}`);
1423
+ return h.redirect(adminUrl`/admin/templates/template/${request.payload.template}`);
1424
1424
  }
1425
1425
  },
1426
1426
  options: {
@@ -1792,7 +1792,7 @@ return payload;`)
1792
1792
  await request.flash({ type: 'success', message: `Updated SMTP gateway`, result });
1793
1793
  }
1794
1794
 
1795
- return h.redirect(`/admin/gateways/gateway/${encodeURIComponent(result.gateway)}?state=${result.state}`);
1795
+ return h.redirect(adminUrl`/admin/gateways/gateway/${result.gateway}?state=${result.state}`);
1796
1796
  } catch (err) {
1797
1797
  await request.flash({ type: 'danger', message: `Couldn't add gateway. Try again.` });
1798
1798
  request.logger.error({ msg: 'Failed to add new gateway', err });
@@ -1907,7 +1907,7 @@ return payload;`)
1907
1907
 
1908
1908
  await request.flash({ type: 'success', message: `Updated SMTP gateway`, result });
1909
1909
 
1910
- return h.redirect(`/admin/gateways/gateway/${encodeURIComponent(result.gateway)}`);
1910
+ return h.redirect(adminUrl`/admin/gateways/gateway/${result.gateway}`);
1911
1911
  } catch (err) {
1912
1912
  await request.flash({ type: 'danger', message: `Couldn't save gateway. Try again.` });
1913
1913
  request.logger.error({ msg: 'Failed to update gateway', err });
@@ -2141,7 +2141,7 @@ return payload;`)
2141
2141
  } catch (err) {
2142
2142
  await request.flash({ type: 'danger', message: `Couldn't delete gateway. Try again.` });
2143
2143
  request.logger.error({ msg: 'Failed to delete the gateway', err, gateway: request.params.gateway, remoteAddress: request.app.ip });
2144
- return h.redirect(`/admin/gateways/${request.params.gateway}`);
2144
+ return h.redirect(adminUrl`/admin/gateways/gateway/${request.params.gateway}`);
2145
2145
  }
2146
2146
  },
2147
2147
  options: {
@@ -2178,9 +2178,26 @@ return payload;`)
2178
2178
  accountData = await accountObject.loadAccountData();
2179
2179
  }
2180
2180
 
2181
- const data = await tokens.list(request.query.account, request.query.page - 1, request.query.pageSize, request.query.query);
2181
+ const data = await tokens.list(request.query.account, request.query.page - 1, request.query.pageSize, request.query.query, {
2182
+ // Every token on the instance, not just the unbound ones. A bound token lives in its
2183
+ // account's index, so without this the page that manages access tokens was the one
2184
+ // place a bound token could not be seen - and the form can now issue one directly.
2185
+ all: !request.query.account
2186
+ });
2187
+
2188
+ // A token outlives the account it was bound to: deleting an account drops that account's
2189
+ // token index but not the token records, and such a token still authenticates. So the
2190
+ // binding column has to tell a live account from a gone one rather than link every row
2191
+ // and let some of them lead to a 404.
2192
+ //
2193
+ // That column is the only reader of accountKnown, so the probe follows the same flag the
2194
+ // view renders on: an account-filtered page names one account, already loaded above, and
2195
+ // shows no column to put the answer in.
2196
+ const showAccountColumn = !accountData;
2197
+ const knownAccounts = showAccountColumn ? await resolveKnownAccounts(data.tokens) : new Map();
2182
2198
 
2183
2199
  data.tokens.forEach(entry => {
2200
+ entry.accountKnown = knownAccounts.get(entry.account);
2184
2201
  entry.access = entry.access || {};
2185
2202
  entry.access.timeStr =
2186
2203
  entry.access && entry.access.time && typeof entry.access.time.toISOString === 'function' ? entry.access.time.toISOString() : null;
@@ -2244,6 +2261,10 @@ return payload;`)
2244
2261
  menuTokens: true,
2245
2262
  data,
2246
2263
 
2264
+ // Redundant in the account-filtered listing, where the card header above the
2265
+ // table already names the one account every row belongs to
2266
+ showAccountColumn,
2267
+
2247
2268
  searchTarget: '/admin/tokens',
2248
2269
  searchPlaceholder: 'Search for access tokens…',
2249
2270
  query: request.query.query,
@@ -2288,7 +2309,10 @@ return payload;`)
2288
2309
  account: accountIdSchema.default(null),
2289
2310
  page: Joi.number().integer().min(1).max(1000000).default(1),
2290
2311
  pageSize: Joi.number().integer().min(1).max(250).default(DEFAULT_PAGE_SIZE),
2291
- query: Joi.string().empty('').example('prometheus').description('Filter by search term')
2312
+ // Trimmed like the /v1/tokens listing: an untrimmed whitespace-only value is a
2313
+ // query to the route and no query at all to the filter, so the listing would
2314
+ // read every record on the instance and then match all of them
2315
+ query: Joi.string().empty('').trim().example('prometheus').description('Filter by search term')
2292
2316
  })
2293
2317
  }
2294
2318
  }
@@ -2316,7 +2340,6 @@ return payload;`)
2316
2340
  menuTokens: true,
2317
2341
  values: {
2318
2342
  scopesAll: true,
2319
- allAccounts: !request.query.account,
2320
2343
  account: request.query.account
2321
2344
  },
2322
2345
  // Same expression the POST gate uses, so the form and the thing it submits to
@@ -2389,8 +2412,13 @@ return payload;`)
2389
2412
  }
2390
2413
 
2391
2414
  if (request.payload.account) {
2392
- let accountObject = new Account({ redis, account: request.payload.account });
2393
- await accountObject.loadAccountData();
2415
+ // Existence probe rather than a full account load: nothing here reads the record,
2416
+ // only whether the ID names one. The ID is typed into the form now rather than
2417
+ // carried over from an account page, so a typo is the likely cause and the answer
2418
+ // has to name the value that was not found.
2419
+ if (!(await accountExists(redis, request.payload.account))) {
2420
+ throw Boom.badRequest(`No account found with ID "${request.payload.account}"`);
2421
+ }
2394
2422
  data.account = request.payload.account;
2395
2423
  }
2396
2424
 
@@ -2477,7 +2505,14 @@ return payload;`)
2477
2505
  return h.redirect('/admin/tokens').takeover();
2478
2506
  },
2479
2507
 
2480
- payload: Joi.object({ token: Joi.string().length(64).hex().required().example('123456').description('Access token') })
2508
+ payload: Joi.object({
2509
+ token: Joi.string()
2510
+ .length(64)
2511
+ .hex()
2512
+ .required()
2513
+ .example('1bc12baf7f0d5e51fe0a4e0eda06e1be5b8d6cc2c66b95dc0fbe4d2e9f5d5e1a')
2514
+ .description('Access token')
2515
+ })
2481
2516
  }
2482
2517
  }
2483
2518
  });
@@ -18,7 +18,7 @@ const { Account } = require('../account');
18
18
  const { oauth2Apps, OAUTH_PROVIDERS, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
19
19
  const { verifyOAuth2App } = require('../oauth/verify-app');
20
20
  const { oauthCreateSchema, oauthUpdateSchema, accountIdSchema } = require('../schemas');
21
- const { throwAsBoom } = require('./route-helpers');
21
+ const { throwAsBoom, adminUrl } = require('./route-helpers');
22
22
 
23
23
  const { DEFAULT_PAGE_SIZE } = consts;
24
24
 
@@ -469,7 +469,7 @@ function init(args) {
469
469
  } catch (err) {
470
470
  await request.flash({ type: 'danger', message: `Couldn't delete OAuth2 app. Try again.` });
471
471
  request.logger.error({ msg: 'Failed to delete OAuth2 application', err, app: request.payload.app, remoteAddress: request.app.ip });
472
- return h.redirect(`/admin/config/oauth/app/${request.payload.app}`);
472
+ return h.redirect(adminUrl`/admin/config/oauth/app/${request.payload.app}`);
473
473
  }
474
474
  },
475
475
  options: {
@@ -533,11 +533,11 @@ function init(args) {
533
533
 
534
534
  await request.flash({ type: 'info', message: `Account ${result.state === 'existing' ? 'updated' : 'added'}` });
535
535
 
536
- return h.redirect(`/admin/accounts/${result.account}`);
536
+ return h.redirect(adminUrl`/admin/accounts/${result.account}`);
537
537
  } catch (err) {
538
538
  request.logger.error({ msg: 'Failed to register service account', err, app: appId, remoteAddress: request.app.ip });
539
539
  await request.flash({ type: 'danger', message: `Failed to add account${err.message ? `: ${err.message}` : ''}` });
540
- return h.redirect(`/admin/config/oauth/app/${appId}`);
540
+ return h.redirect(adminUrl`/admin/config/oauth/app/${appId}`);
541
541
  }
542
542
  },
543
543
  options: {
@@ -551,7 +551,7 @@ function init(args) {
551
551
  async failAction(request, h, err) {
552
552
  request.logger.debug({ msg: 'Failed to register service account', err, app: request.params.app });
553
553
  await request.flash({ type: 'danger', message: `Failed to add account. Provide a valid email address.` });
554
- return h.redirect(`/admin/config/oauth/app/${request.params.app}`).takeover();
554
+ return h.redirect(adminUrl`/admin/config/oauth/app/${request.params.app}`).takeover();
555
555
  },
556
556
 
557
557
  params: Joi.object({
@@ -715,7 +715,7 @@ function init(args) {
715
715
  }
716
716
 
717
717
  await request.flash({ type: 'success', message: `OAuth2 app created` });
718
- return h.redirect(`/admin/config/oauth/app/${oauth2App.id}`);
718
+ return h.redirect(adminUrl`/admin/config/oauth/app/${oauth2App.id}`);
719
719
  } catch (err) {
720
720
  await request.flash({ type: 'danger', message: `Couldn't register OAuth2 app. Try again.` });
721
721
  request.logger.error({ msg: 'Failed to register OAuth2 app', err });
@@ -974,7 +974,7 @@ function init(args) {
974
974
  }
975
975
 
976
976
  await request.flash({ type: 'success', message: `OAuth2 app saved` });
977
- return h.redirect(`/admin/config/oauth/app/${oauth2App.id}`);
977
+ return h.redirect(adminUrl`/admin/config/oauth/app/${oauth2App.id}`);
978
978
  } catch (err) {
979
979
  await request.flash({ type: 'danger', message: `Couldn't save OAuth2 app. Try again.` });
980
980
  request.logger.error({ msg: 'Failed to update OAuth2 app', app: request.payload.app, err });
@@ -18,6 +18,7 @@ const psl = require('psl');
18
18
 
19
19
  const settings = require('../settings');
20
20
  const { redis } = require('../db');
21
+ const { accountsExist } = require('../account');
21
22
  const { REDIS_PREFIX, DEFAULT_PAGE_SIZE } = require('../consts');
22
23
  const { oauth2ProviderData } = require('../oauth2-apps');
23
24
  const exampleDocumentsPayloads = require('../payload-examples-documents.json');
@@ -381,6 +382,14 @@ function identityErrorView(request, h, { expectedEmail, actualEmail, retryUrl })
381
382
  // `new URL(path, base)` convention the route modules already use); data is a listing
382
383
  // response carrying zero-based `page` and total `pages`; query is the validated request
383
384
  // query whose `pageSize` is appended to the URLs only when it differs from the default.
385
+ // Tagged template for redirect paths that interpolate an identifier: percent-encodes every
386
+ // interpolated value, so a raw ID cannot break the path or turn into a URL fragment whichever
387
+ // call site forgets. The JS-layer counterpart of the `urlpart` Handlebars helper that closed
388
+ // the same bug class in the templates - use this instead of hand-placing encodeURIComponent.
389
+ function adminUrl(strings, ...values) {
390
+ return strings.reduce((url, part, i) => url + part + (i < values.length ? encodeURIComponent(values[i]) : ''), '');
391
+ }
392
+
384
393
  function buildPagingView(basePath, data, query) {
385
394
  const getPagingUrl = page => {
386
395
  let url = new URL(basePath, 'http://localhost');
@@ -409,8 +418,25 @@ function buildPagingView(basePath, data, query) {
409
418
  };
410
419
  }
411
420
 
421
+ /**
422
+ * Resolves which of the accounts a listing refers to still exist.
423
+ *
424
+ * Rows outlive the account they name: deleting an account leaves its suppression-list entries in
425
+ * place and leaves its access tokens valid. A row naming a dead account must not be rendered as a
426
+ * link to a page that 404s, so the listings ask this before rendering. One probe per distinct
427
+ * account rather than per row, all of them in one round trip, and each is a single HEXISTS - no
428
+ * account load, nothing decrypted.
429
+ *
430
+ * @param {Array} entries - listing rows, each optionally carrying an `account`
431
+ * @returns {Promise<Map<String, Boolean>>} keyed by account ID; rows without one are absent
432
+ */
433
+ async function resolveKnownAccounts(entries) {
434
+ return accountsExist(redis, Array.from(new Set(entries.map(entry => entry.account).filter(Boolean))));
435
+ }
436
+
412
437
  module.exports = {
413
438
  jsonErrorPayload,
439
+ resolveKnownAccounts,
414
440
  identityErrorView,
415
441
  OPEN_AI_MODELS,
416
442
  cachedTemplates,
@@ -424,5 +450,6 @@ module.exports = {
424
450
  throwAsBoom,
425
451
  isClientError,
426
452
  authAwareLevel,
427
- buildPagingView
453
+ buildPagingView,
454
+ adminUrl
428
455
  };
@@ -7,12 +7,10 @@
7
7
  // removing the last address drops the list again (see lib/lua/ee-list-remove.lua).
8
8
 
9
9
  const Joi = require('joi');
10
- const { redis } = require('../db');
11
10
  const { lists } = require('../lists');
12
11
  const settings = require('../settings');
13
- const { accountExists } = require('../account');
14
12
  const { blocklistListIdSchema } = require('../schemas');
15
- const { buildPagingView } = require('./route-helpers');
13
+ const { buildPagingView, resolveKnownAccounts, adminUrl } = require('./route-helpers');
16
14
  const { buildUnsubscribeUrl, getServiceSecret } = require('../tools');
17
15
  const consts = require('../consts');
18
16
 
@@ -77,7 +75,15 @@ function init(args) {
77
75
  try {
78
76
  data = await lists.listContent(listId, request.query.page - 1, request.query.pageSize);
79
77
  } catch (err) {
80
- await request.flash({ type: 'danger', message: `Requested suppression list was not found` });
78
+ // Only a missing list reads as one. Anything else (say, a dropped Redis
79
+ // connection) is a transient failure of an intact list - reporting it as
80
+ // "not found" tells the operator their unsubscribe data is gone when it is not.
81
+ if (err.output && err.output.statusCode === 404) {
82
+ await request.flash({ type: 'danger', message: `Requested suppression list was not found` });
83
+ } else {
84
+ request.logger.error({ msg: 'Failed to load suppression list', listId, err });
85
+ await request.flash({ type: 'danger', message: `Failed to load the suppression list. Try again.` });
86
+ }
81
87
  return h.redirect('/admin/suppression-lists');
82
88
  }
83
89
 
@@ -87,8 +93,7 @@ function init(args) {
87
93
  // account, so entries without one (or whose account is gone) get no link.
88
94
  let [serviceUrl, serviceSecret] = await Promise.all([settings.get('serviceUrl'), getServiceSecret()]);
89
95
 
90
- let uniqueAccounts = Array.from(new Set(data.addresses.map(entry => entry.account).filter(Boolean)));
91
- let knownAccounts = new Map(await Promise.all(uniqueAccounts.map(async account => [account, await accountExists(redis, account)])));
96
+ let knownAccounts = await resolveKnownAccounts(data.addresses);
92
97
 
93
98
  for (let entry of data.addresses) {
94
99
  if (!entry.account || !knownAccounts.get(entry.account)) {
@@ -161,7 +166,7 @@ function init(args) {
161
166
  await request.flash({ type: 'info', message: `${recipient} was already listed; the entry was updated` });
162
167
  }
163
168
 
164
- return h.redirect(`/admin/suppression-lists/list/${listId}`);
169
+ return h.redirect(adminUrl`/admin/suppression-lists/list/${listId}`);
165
170
  } catch (err) {
166
171
  await request.flash({ type: 'danger', message: `Couldn't add the address. Try again.` });
167
172
  request.logger.error({ msg: 'Failed to add suppression list entry', err, listId, remoteAddress: request.app.ip });
@@ -212,11 +217,11 @@ function init(args) {
212
217
  await request.flash({ type: 'info', message: `Removed ${recipient} from the suppression list` });
213
218
  }
214
219
 
215
- return h.redirect(`/admin/suppression-lists/list/${listId}`);
220
+ return h.redirect(adminUrl`/admin/suppression-lists/list/${listId}`);
216
221
  } catch (err) {
217
222
  await request.flash({ type: 'danger', message: `Couldn't remove the address. Try again.` });
218
223
  request.logger.error({ msg: 'Failed to remove suppression list entry', err, listId, remoteAddress: request.app.ip });
219
- return h.redirect(`/admin/suppression-lists/list/${listId}`);
224
+ return h.redirect(adminUrl`/admin/suppression-lists/list/${listId}`);
220
225
  }
221
226
  },
222
227
  options: {
@@ -0,0 +1,42 @@
1
+ 'use strict';
2
+
3
+ const libmime = require('libmime');
4
+ const { UNSAFE_KEYS } = require('./unsafe-key');
5
+
6
+ /**
7
+ * Parses a header block into a map of lowercased header name to array of values.
8
+ *
9
+ * Wraps libmime.decodeHeaders() to drop names that collide with Object.prototype. Header names
10
+ * come from the message, so any sender can use one, and libmime returns them as real own
11
+ * properties. Neither names a real header, so there is nothing to preserve by keeping them:
12
+ *
13
+ * - an own "__proto__" key is the one thing lib/msgpack.js refuses to decode, so a map carrying it
14
+ * encodes into webhook logs and message payloads that can never be read back, and it hands
15
+ * anything that later copies the map with `obj[key] =` or Object.assign a prototype swap
16
+ * - "constructor" is inert on its own, but lib/utils/header-map.js cannot represent it, so keeping
17
+ * it would describe the same message differently depending on the transport that fetched it
18
+ *
19
+ * Dropping them here rather than at each consumer keeps every parsed header block on one
20
+ * contract: lib/email-client/imap/mailbox.js and lib/bounce-detect.js return these maps to callers
21
+ * verbatim, and lib/arf-detect.js copies them key by key into a published report. It is not the
22
+ * last word on either name though - a consumer that rebuilds a key from the name has to check
23
+ * again, see isUnsafeKey() in lib/utils/unsafe-key.js.
24
+ *
25
+ * @param {String|Buffer} headers - Raw header block
26
+ * @returns {Object} Map of lowercased header name to array of values
27
+ */
28
+ function decodeHeaders(headers) {
29
+ let parsed = libmime.decodeHeaders(headers);
30
+
31
+ for (let name of UNSAFE_KEYS) {
32
+ // Probing first is not needed for correctness, deleting a missing key is a no-op, but it is
33
+ // the cheaper no-op and almost every message takes this path
34
+ if (Object.hasOwn(parsed, name)) {
35
+ delete parsed[name];
36
+ }
37
+ }
38
+
39
+ return parsed;
40
+ }
41
+
42
+ module.exports = { decodeHeaders };
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ // Lives here rather than in lib/tools.js so that pure modules and tests can use it: tools.js
4
+ // opens Redis, which drags a connection into anything that only wants to collect header values.
5
+
6
+ /**
7
+ * Appends one value to a header map keyed by lowercased header name.
8
+ *
9
+ * Header names come from the remote server, so any sender can pick one that names an
10
+ * Object.prototype member. On a plain object `headers['__proto__']` reads back the prototype
11
+ * instead of an array, and assigning to it hands the value to the prototype setter rather than
12
+ * storing a key - so a bare `!headers[key]` probe pushes onto something that is not an array and
13
+ * throws. Lowercasing leaves exactly two such names, "__proto__" and "constructor", and both are
14
+ * dropped rather than collected: storing them would need an own "__proto__" key, which msgpack
15
+ * refuses to decode (test/msgpack-compat-test.js) and which hands webhook consumers a prototype
16
+ * pollution gadget of their own.
17
+ *
18
+ * Only the accumulate-by-assignment shape is guarded here. A header block parsed by libmime
19
+ * arrives with these names already set as own properties, which this cannot detect, so
20
+ * lib/utils/decode-headers.js drops them after the fact for the IMAP and bounce paths.
21
+ *
22
+ * The array is read before the `in` probe on purpose. `in` walks the prototype chain and has no
23
+ * fast path for the freshly lowercased (non-internalized) key, which made it roughly twice the
24
+ * cost of the whole loop; reading first keeps `in` on the miss path only.
25
+ *
26
+ * @param {Object} headers - Map of lowercased header name to array of values
27
+ * @param {String} key - Lowercased header name
28
+ * @param {String} value - Value to append
29
+ * @returns {Boolean} True when the value was stored, false when the name was skipped
30
+ */
31
+ function pushHeaderValue(headers, key, value) {
32
+ let values = headers[key];
33
+
34
+ if (Array.isArray(values)) {
35
+ values.push(value);
36
+ return true;
37
+ }
38
+
39
+ // Not an array: either the name is unused, or it resolves to a prototype member
40
+ if (key in headers) {
41
+ return false;
42
+ }
43
+
44
+ headers[key] = [value];
45
+ return true;
46
+ }
47
+
48
+ module.exports = { pushHeaderValue };
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+
3
+ // Lives here rather than in lib/tools.js so that pure modules and tests can use it: tools.js opens
4
+ // Redis, which drags a connection into anything that only wants to parse a message.
5
+
6
+ // Names that resolve to an Object.prototype member. Header names come from the message, so any
7
+ // sender can pick one, and the maps built from them are plain objects:
8
+ //
9
+ // - assigning "__proto__" hands the value to the prototype setter and swaps the map's prototype
10
+ // instead of storing a key, and defining it as an own property instead leaves a key
11
+ // lib/msgpack.js refuses to decode - so a map carrying one encodes into webhook logs and message
12
+ // payloads that can never be read back
13
+ // - "constructor" is inert on its own, but lib/utils/header-map.js cannot represent it, so keeping
14
+ // it would describe the same message differently depending on the transport that fetched it
15
+ //
16
+ // The names a message supplies arrive lowercased, which leaves exactly these two. Kept as an
17
+ // explicit list rather than an `in {}` probe so that what gets dropped is readable at a glance, and
18
+ // so that names like "toString" - which cannot collide with a lowercased key, and which no real
19
+ // header or subtype uses either - are not dropped as a side effect.
20
+ const UNSAFE_KEYS = ['__proto__', 'constructor'];
21
+
22
+ /**
23
+ * Tells whether a key is one a plain-object map built from a message must not carry - header names,
24
+ * but also anything else the message names, such as the MIME subtype lib/email-client/imap/mailbox.js
25
+ * groups text parts by.
26
+ *
27
+ * Applied at the parse boundary (lib/utils/decode-headers.js), and again after any transform that
28
+ * rebuilds a key from a name. A transform can manufacture one of these out of an input the parse
29
+ * boundary had no reason to drop: toCamelCase() turns "_-_proto__" into "__proto__", so a guard
30
+ * that only ran before it never saw the name it exists to catch.
31
+ *
32
+ * @param {String} key - Key to test
33
+ * @returns {Boolean} True when the key must be dropped
34
+ */
35
+ function isUnsafeKey(key) {
36
+ return UNSAFE_KEYS.includes(key);
37
+ }
38
+
39
+ /**
40
+ * The stricter test for a key REBUILT from a name by a case-changing transform. After
41
+ * toCamelCase() a key is no longer lowercase-only: "to-string" camelCases into "toString" and
42
+ * "has-own-property" into "hasOwnProperty", so the transform can manufacture any Object.prototype
43
+ * member name out of an input the parse boundary had no reason to drop. Assigning one creates an
44
+ * own property that shadows the method on the published object, and the first consumer that
45
+ * string-coerces the report - or calls hasOwnProperty() on it - throws.
46
+ *
47
+ * Probed with `in` against Object.prototype itself (whose own chain ends at null, so this reads
48
+ * exactly its member set, __proto__ and constructor included) rather than extending the list
49
+ * above: the set tracks the runtime, and the parse-boundary check deliberately stays narrower -
50
+ * see the note on UNSAFE_KEYS about not dropping names a lowercased key cannot collide with.
51
+ *
52
+ * @param {String} key - Key to test, after the transform that rebuilt it
53
+ * @returns {Boolean} True when the key must be dropped
54
+ */
55
+ function isUnsafeTransformedKey(key) {
56
+ return key in Object.prototype;
57
+ }
58
+
59
+ module.exports = { UNSAFE_KEYS, isUnsafeKey, isUnsafeTransformedKey };
@@ -65,14 +65,18 @@ function describeEffectiveRouting(opts) {
65
65
  },
66
66
 
67
67
  // Enabled custom routes deliver independently of the default route, each gated by its
68
- // own filter function instead of the webhookEvents allowlist
68
+ // own filter function instead of the webhookEvents allowlist. The worker requires that
69
+ // filter to exist (lib/webhooks.js pushToQueue skips a route without a compiled
70
+ // function), so a route whose `hasFilter` marker is false is flagged rather than
71
+ // presented as delivering - it never fires anything.
69
72
  customRoutes: []
70
73
  .concat(opts.routes || [])
71
74
  .filter(isDeliverableRoute)
72
75
  .map(route => ({
73
76
  id: route.id,
74
77
  name: route.name,
75
- targetUrl: route.targetUrl
78
+ targetUrl: route.targetUrl,
79
+ missingFilter: route.hasFilter === false
76
80
  }))
77
81
  };
78
82
  }
package/lib/webhooks.js CHANGED
@@ -349,6 +349,34 @@ class WebhooksHandler {
349
349
  }
350
350
  }
351
351
 
352
+ // Filter-presence markers for the routes asked about, as a Map of id -> boolean. The
353
+ // delivery gate in pushToQueue() requires a compiled filter function, so anything
354
+ // describing routes to an operator (the account page's routing card) has to know which
355
+ // routes carry a script at all. Reads only the content entries of the given ids.
356
+ async getFilterInfo(ids) {
357
+ let result = new Map();
358
+ if (!ids || !ids.length) {
359
+ return result;
360
+ }
361
+
362
+ let entries = await this.redis.hmgetBuffer(
363
+ this.getWebhooksContentKey(),
364
+ ids.map(id => `${id}:content`)
365
+ );
366
+
367
+ for (let i = 0; i < ids.length; i++) {
368
+ let content = null;
369
+ try {
370
+ content = entries[i] ? msgpack.decode(entries[i]) : null;
371
+ } catch (err) {
372
+ logger.error({ msg: 'Failed to process webhook', webhook: ids[i], entry: entries[i] && entries[i].toString('base64'), err });
373
+ }
374
+ result.set(ids[i], !!(content && content.fn));
375
+ }
376
+
377
+ return result;
378
+ }
379
+
352
380
  async getHandler(id) {
353
381
  let webhookData = await this.get(id);
354
382
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "emailengine-app",
3
- "version": "2.79.0",
3
+ "version": "2.79.1",
4
4
  "private": false,
5
5
  "productTitle": "EmailEngine",
6
6
  "description": "Email Sync Engine",