emailengine-app 2.78.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 (155) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +68 -0
  4. package/config/e2e.toml +2 -1
  5. package/config/test.toml +2 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +112 -36
  8. package/lib/api-reference/format.js +91 -4
  9. package/lib/api-reference/model.js +144 -19
  10. package/lib/api-reference/schema-tree.js +282 -28
  11. package/lib/api-routes/account-routes.js +80 -34
  12. package/lib/api-routes/blocklist-routes.js +21 -47
  13. package/lib/api-routes/chat-routes.js +10 -12
  14. package/lib/api-routes/delivery-test-routes.js +6 -26
  15. package/lib/api-routes/export-routes.js +2 -0
  16. package/lib/api-routes/gateway-routes.js +52 -11
  17. package/lib/api-routes/license-routes.js +2 -0
  18. package/lib/api-routes/mailbox-routes.js +29 -26
  19. package/lib/api-routes/message-routes.js +27 -21
  20. package/lib/api-routes/oauth2-app-routes.js +11 -29
  21. package/lib/api-routes/operation-impact.js +80 -0
  22. package/lib/api-routes/outbox-routes.js +15 -5
  23. package/lib/api-routes/permission-map.js +401 -0
  24. package/lib/api-routes/route-helpers.js +294 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +66 -38
  27. package/lib/api-routes/stats-routes.js +2 -2
  28. package/lib/api-routes/submit-routes.js +53 -31
  29. package/lib/api-routes/template-routes.js +3 -0
  30. package/lib/api-routes/token-routes.js +526 -72
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/arf-detect.js +17 -4
  33. package/lib/auth-token.js +80 -8
  34. package/lib/bounce-detect.js +28 -17
  35. package/lib/consts.js +16 -0
  36. package/lib/db.js +26 -2
  37. package/lib/delivery-error.js +30 -1
  38. package/lib/email-client/base-client.js +27 -41
  39. package/lib/email-client/gmail-client.js +23 -17
  40. package/lib/email-client/imap/mailbox.js +58 -59
  41. package/lib/email-client/imap/subconnection.js +10 -7
  42. package/lib/email-client/imap/sync-operations.js +46 -46
  43. package/lib/email-client/imap-client.js +85 -28
  44. package/lib/email-client/message-builder.js +3 -3
  45. package/lib/email-client/notification-handler.js +1 -1
  46. package/lib/email-client/outlook/graph-api.js +10 -4
  47. package/lib/email-client/outlook-client.js +56 -64
  48. package/lib/email-client/smtp-pool-manager.js +1 -1
  49. package/lib/enum-descriptions.js +92 -2
  50. package/lib/export.js +1 -1
  51. package/lib/field-usage.js +133 -0
  52. package/lib/gateway.js +1 -1
  53. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  54. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  55. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  56. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  57. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  58. package/lib/imapproxy/imap-server.js +27 -7
  59. package/lib/license-beacon.js +4 -9
  60. package/lib/lists.js +49 -1
  61. package/lib/llm-pre-process.js +5 -5
  62. package/lib/logger.js +5 -1
  63. package/lib/lua/h-set-new-mark.lua +36 -0
  64. package/lib/message-port-stream.js +84 -1
  65. package/lib/metrics-collector.js +2 -2
  66. package/lib/oauth/gmail.js +9 -12
  67. package/lib/oauth/mail-ru.js +5 -7
  68. package/lib/oauth/outlook.js +9 -9
  69. package/lib/oauth/pubsub/google.js +25 -10
  70. package/lib/oauth/scope-checker.js +1 -1
  71. package/lib/oauth2-apps.js +290 -292
  72. package/lib/openapi/build-document.js +20 -8
  73. package/lib/openapi/joi-schema.js +20 -0
  74. package/lib/outbox.js +85 -17
  75. package/lib/pre-process.js +8 -8
  76. package/lib/queue-stats.js +49 -0
  77. package/lib/read-env-value.js +1 -1
  78. package/lib/reconnection-manager.js +2 -2
  79. package/lib/rewrite-text-nodes.js +4 -3
  80. package/lib/routes-ui.js +4 -0
  81. package/lib/schemas.js +218 -162
  82. package/lib/settings.js +98 -5
  83. package/lib/sub-script.js +2 -1
  84. package/lib/swagger-options.js +2 -1
  85. package/lib/templates.js +4 -4
  86. package/lib/threads.js +2 -2
  87. package/lib/token-audit-log.js +231 -0
  88. package/lib/token-permission-view.js +219 -0
  89. package/lib/token-permissions.js +172 -0
  90. package/lib/tokens.js +247 -66
  91. package/lib/tools.js +142 -37
  92. package/lib/ui-routes/account-routes.js +42 -15
  93. package/lib/ui-routes/admin-config-routes.js +18 -10
  94. package/lib/ui-routes/admin-entities-routes.js +117 -38
  95. package/lib/ui-routes/auth-routes.js +30 -24
  96. package/lib/ui-routes/export-routes.js +10 -4
  97. package/lib/ui-routes/oauth-config-routes.js +12 -12
  98. package/lib/ui-routes/reference-routes.js +3 -3
  99. package/lib/ui-routes/route-helpers.js +78 -2
  100. package/lib/ui-routes/settings-page.js +1 -1
  101. package/lib/ui-routes/smtp-test-routes.js +1 -1
  102. package/lib/ui-routes/suppression-list-routes.js +299 -0
  103. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  104. package/lib/utils/decode-headers.js +42 -0
  105. package/lib/utils/header-map.js +48 -0
  106. package/lib/utils/network.js +2 -2
  107. package/lib/utils/unsafe-key.js +59 -0
  108. package/lib/web-safe-html.js +1 -1
  109. package/lib/webhook-routing.js +84 -0
  110. package/lib/webhooks.js +48 -14
  111. package/package.json +11 -10
  112. package/sbom.json +1 -1
  113. package/server.js +116 -55
  114. package/static/css/flyonui.css +1 -1
  115. package/static/css/src/app.tailwind.css +136 -9
  116. package/static/js/reference.js +456 -10
  117. package/static/js/ui.js +43 -0
  118. package/static/licenses.html +51 -41
  119. package/translations/messages.pot +59 -59
  120. package/views/accounts/account.hbs +75 -13
  121. package/views/accounts/browse.hbs +19 -36
  122. package/views/accounts/edit.hbs +2 -2
  123. package/views/config/logging.hbs +6 -0
  124. package/views/config/oauth/app.hbs +0 -2
  125. package/views/config/security.hbs +13 -0
  126. package/views/gateways/edit.hbs +1 -1
  127. package/views/gateways/gateway.hbs +2 -2
  128. package/views/gateways/index.hbs +7 -7
  129. package/views/partials/accounts_table.hbs +7 -7
  130. package/views/partials/oauth_form.hbs +0 -15
  131. package/views/partials/reference/disclosure.hbs +8 -2
  132. package/views/partials/reference/operation.hbs +47 -13
  133. package/views/partials/reference/params.hbs +17 -1
  134. package/views/partials/reference/schema-node.hbs +110 -52
  135. package/views/partials/reference/schema-tools.hbs +25 -0
  136. package/views/partials/reference/try-it.hbs +84 -11
  137. package/views/partials/side_menu.hbs +1 -0
  138. package/views/partials/ui/checkbox.hbs +2 -2
  139. package/views/partials/ui/tabs.hbs +7 -1
  140. package/views/reference/token.hbs +4 -0
  141. package/views/suppression-lists/index.hbs +85 -0
  142. package/views/suppression-lists/list.hbs +87 -0
  143. package/views/templates/index.hbs +10 -4
  144. package/views/templates/template.hbs +1 -1
  145. package/views/tokens/index.hbs +53 -6
  146. package/views/tokens/new.hbs +334 -5
  147. package/workers/api.js +185 -102
  148. package/workers/documents.js +46 -26
  149. package/workers/export.js +20 -8
  150. package/workers/imap-proxy.js +2 -2
  151. package/workers/imap.js +77 -78
  152. package/workers/smtp.js +13 -7
  153. package/workers/submit.js +40 -30
  154. package/workers/webhooks.js +80 -26
  155. package/lib/feature-flags.js +0 -48
@@ -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: {
@@ -549,9 +549,9 @@ function init(args) {
549
549
  },
550
550
 
551
551
  async failAction(request, h, err) {
552
- request.logger.error({ msg: 'Failed to register service account', err, app: request.params.app });
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({
@@ -590,7 +590,7 @@ function init(args) {
590
590
  },
591
591
 
592
592
  async failAction(request, h, err) {
593
- request.logger.error({ msg: 'Invalid verify request', err, app: request.params.app });
593
+ request.logger.debug({ msg: 'Invalid verify request', err, app: request.params.app });
594
594
  return h.response({ error: 'Invalid request' }).code(400).takeover();
595
595
  },
596
596
 
@@ -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 });
@@ -789,7 +789,7 @@ function init(args) {
789
789
  }
790
790
 
791
791
  await request.flash({ type: 'danger', message: `Couldn't register OAuth2 app. Try again.` });
792
- request.logger.error({ msg: 'Failed to register OAuth2 app', err });
792
+ request.logger.debug({ msg: 'Failed to register OAuth2 app', err });
793
793
 
794
794
  let { provider, baseScopes } = request.payload;
795
795
  if (!provider || !OAUTH_PROVIDERS.hasOwnProperty(provider)) {
@@ -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 });
@@ -1048,12 +1048,12 @@ function init(args) {
1048
1048
  let appData = await oauth2Apps.get(request.payload.app);
1049
1049
  if (!appData) {
1050
1050
  await request.flash({ type: 'danger', message: `Application not found` });
1051
- request.logger.error({ msg: 'Application was not found.', app: request.payload.app });
1051
+ request.logger.warn({ msg: 'OAuth2 application not found', app: request.payload.app });
1052
1052
  return h.redirect('/admin').takeover();
1053
1053
  }
1054
1054
 
1055
1055
  await request.flash({ type: 'danger', message: `Couldn't save OAuth2 app. Try again.` });
1056
- request.logger.error({ msg: 'Failed to update OAuth2 app', err });
1056
+ request.logger.debug({ msg: 'Failed to update OAuth2 app', err });
1057
1057
 
1058
1058
  let { provider } = request.payload;
1059
1059
  if (!provider || !OAUTH_PROVIDERS.hasOwnProperty(provider)) {
@@ -13,7 +13,7 @@ const Joi = require('joi');
13
13
  const Boom = require('@hapi/boom');
14
14
 
15
15
  const { failAction } = require('../tools');
16
- const { jsonErrorPayload } = require('./route-helpers');
16
+ const { jsonErrorPayload, authAwareLevel } = require('./route-helpers');
17
17
  const tokens = require('../tokens');
18
18
  const { getIndexView, getTagView, getNavView, getRedirectView } = require('../api-reference');
19
19
 
@@ -141,7 +141,7 @@ function init(args) {
141
141
 
142
142
  return { success: true, token, expires };
143
143
  } catch (err) {
144
- request.logger.error({ msg: 'Failed to mint a temporary reference token', err, remoteAddress: request.app.ip });
144
+ request.logger[authAwareLevel(err)]({ msg: 'Failed to mint a temporary reference token', err, remoteAddress: request.app.ip });
145
145
  return jsonErrorPayload(err);
146
146
  }
147
147
  }
@@ -178,7 +178,7 @@ function init(args) {
178
178
 
179
179
  return { success: true, deleted: true };
180
180
  } catch (err) {
181
- request.logger.error({ msg: 'Failed to revoke a temporary reference token', err, remoteAddress: request.app.ip });
181
+ request.logger[authAwareLevel(err)]({ msg: 'Failed to revoke a temporary reference token', err, remoteAddress: request.app.ip });
182
182
  return jsonErrorPayload(err);
183
183
  }
184
184
  },
@@ -18,7 +18,8 @@ const psl = require('psl');
18
18
 
19
19
  const settings = require('../settings');
20
20
  const { redis } = require('../db');
21
- const { REDIS_PREFIX } = require('../consts');
21
+ const { accountsExist } = require('../account');
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');
24
25
 
@@ -315,6 +316,19 @@ async function getServerStatus(type) {
315
316
  return { state, payload, label: formatServerState(state, payload) };
316
317
  }
317
318
 
319
+ // True for failures the client caused (a Boom 4xx, e.g. a stale tab polling a deleted entity).
320
+ // Used by catch blocks to skip or demote logging for them, so bot and stale-UI traffic does not
321
+ // land in the error stream.
322
+ function isClientError(err) {
323
+ return Boom.isBoom(err) && err.output.statusCode < 500;
324
+ }
325
+
326
+ // An unauthenticated attempt rejected with Boom.forbidden is an auth event worth auditing at
327
+ // warn, not a server failure. Returns the log level for a catch block that serves both cases.
328
+ function authAwareLevel(err) {
329
+ return Boom.isBoom(err) && err.output.statusCode === 403 ? 'warn' : 'error';
330
+ }
331
+
318
332
  function throwAsBoom(err) {
319
333
  if (Boom.isBoom(err)) {
320
334
  throw err;
@@ -363,8 +377,66 @@ function identityErrorView(request, h, { expectedEmail, actualEmail, retryUrl })
363
377
  .code(403);
364
378
  }
365
379
 
380
+ // View-model for the ui/pagination partial: prev/next URLs plus the numbered page links.
381
+ // basePath is the URL path without a query string (leading slash optional, matching the
382
+ // `new URL(path, base)` convention the route modules already use); data is a listing
383
+ // response carrying zero-based `page` and total `pages`; query is the validated request
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
+
393
+ function buildPagingView(basePath, data, query) {
394
+ const getPagingUrl = page => {
395
+ let url = new URL(basePath, 'http://localhost');
396
+
397
+ if (page) {
398
+ url.searchParams.append('page', page);
399
+ }
400
+
401
+ if (query.pageSize !== DEFAULT_PAGE_SIZE) {
402
+ url.searchParams.append('pageSize', query.pageSize);
403
+ }
404
+
405
+ return url.pathname + url.search;
406
+ };
407
+
408
+ return {
409
+ showPaging: data.pages > 1,
410
+ nextPage: data.pages > data.page + 1 ? getPagingUrl(data.page + 2) : false,
411
+ prevPage: data.page > 0 ? getPagingUrl(data.page) : false,
412
+ firstPage: data.page === 0,
413
+ pageLinks: new Array(data.pages || 1).fill(0).map((z, i) => ({
414
+ url: getPagingUrl(i + 1),
415
+ title: i + 1,
416
+ active: i === data.page
417
+ }))
418
+ };
419
+ }
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
+
366
437
  module.exports = {
367
438
  jsonErrorPayload,
439
+ resolveKnownAccounts,
368
440
  identityErrorView,
369
441
  OPEN_AI_MODELS,
370
442
  cachedTemplates,
@@ -375,5 +447,9 @@ module.exports = {
375
447
  formatAccountData,
376
448
  getExampleDocumentsPayloads,
377
449
  getServerStatus,
378
- throwAsBoom
450
+ throwAsBoom,
451
+ isClientError,
452
+ authAwareLevel,
453
+ buildPagingView,
454
+ adminUrl
379
455
  };
@@ -93,7 +93,7 @@ function registerSettingsPage(server, page) {
93
93
  }
94
94
 
95
95
  await request.flash({ type: 'danger', message: `Couldn't save settings. Try again.` });
96
- request.logger.error({ msg: 'Failed to update configuration', err });
96
+ request.logger.debug({ msg: 'Failed to update configuration', err });
97
97
 
98
98
  return (await renderError(request, h, errors)).takeover();
99
99
  },
@@ -146,7 +146,7 @@ ${now}`,
146
146
  let user = request.payload.user;
147
147
 
148
148
  try {
149
- request.logger.info({ msg: 'Request SMTP test response', user });
149
+ request.logger.debug({ msg: 'Request SMTP test response', user });
150
150
 
151
151
  let deliveryStatus = (await redis.hgetall(`${REDIS_PREFIX}test-send:${user}`)) || {};
152
152
  if (deliveryStatus.success === 'false') {
@@ -0,0 +1,299 @@
1
+ 'use strict';
2
+
3
+ // Admin UI for suppression lists (the store behind the Blocklists API and the public
4
+ // unsubscribe flow): /admin/suppression-lists (listing + add/delete) and
5
+ // /admin/suppression-lists/list/{listId} (entries + per-address removal). Lists are
6
+ // registered ad hoc, so adding an address to an unknown list ID creates that list, and
7
+ // removing the last address drops the list again (see lib/lua/ee-list-remove.lua).
8
+
9
+ const Joi = require('joi');
10
+ const { lists } = require('../lists');
11
+ const settings = require('../settings');
12
+ const { blocklistListIdSchema } = require('../schemas');
13
+ const { buildPagingView, resolveKnownAccounts, adminUrl } = require('./route-helpers');
14
+ const { buildUnsubscribeUrl, getServiceSecret } = require('../tools');
15
+ const consts = require('../consts');
16
+
17
+ const { DEFAULT_PAGE_SIZE } = consts;
18
+
19
+ const pagingQuerySchema = Joi.object({
20
+ page: Joi.number().integer().min(1).max(1000000).default(1),
21
+ pageSize: Joi.number().integer().min(1).max(250).default(DEFAULT_PAGE_SIZE)
22
+ });
23
+
24
+ function init(args) {
25
+ const { server } = args;
26
+
27
+ server.route({
28
+ method: 'GET',
29
+ path: '/admin/suppression-lists',
30
+ async handler(request, h) {
31
+ let data = await lists.list(request.query.page - 1, request.query.pageSize);
32
+
33
+ return h.view(
34
+ 'suppression-lists/index',
35
+ {
36
+ pageTitle: 'Suppression Lists',
37
+ menuSuppressionLists: true,
38
+
39
+ total: data.total,
40
+
41
+ ...buildPagingView('admin/suppression-lists', data, request.query),
42
+
43
+ suppressionLists: data.blocklists
44
+ },
45
+ {
46
+ layout: 'app'
47
+ }
48
+ );
49
+ },
50
+
51
+ options: {
52
+ validate: {
53
+ options: {
54
+ stripUnknown: true,
55
+ abortEarly: false,
56
+ convert: true
57
+ },
58
+
59
+ async failAction(request, h /*, err*/) {
60
+ return h.redirect('/admin/suppression-lists').takeover();
61
+ },
62
+
63
+ query: pagingQuerySchema
64
+ }
65
+ }
66
+ });
67
+
68
+ server.route({
69
+ method: 'GET',
70
+ path: '/admin/suppression-lists/list/{listId}',
71
+ async handler(request, h) {
72
+ let listId = request.params.listId;
73
+
74
+ let data;
75
+ try {
76
+ data = await lists.listContent(listId, request.query.page - 1, request.query.pageSize);
77
+ } catch (err) {
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
+ }
87
+ return h.redirect('/admin/suppression-lists');
88
+ }
89
+
90
+ // Link each entry to its public subscription management page - the same signed URL
91
+ // the List-Unsubscribe header carries - so the page can be previewed or the link
92
+ // sent to the recipient for self service re-subscription. The page loads the
93
+ // account, so entries without one (or whose account is gone) get no link.
94
+ let [serviceUrl, serviceSecret] = await Promise.all([settings.get('serviceUrl'), getServiceSecret()]);
95
+
96
+ let knownAccounts = await resolveKnownAccounts(data.addresses);
97
+
98
+ for (let entry of data.addresses) {
99
+ if (!entry.account || !knownAccounts.get(entry.account)) {
100
+ continue;
101
+ }
102
+ entry.unsubscribeUrl = buildUnsubscribeUrl(serviceSecret, serviceUrl, {
103
+ account: entry.account,
104
+ list: listId,
105
+ recipient: entry.recipient
106
+ });
107
+ }
108
+
109
+ return h.view(
110
+ 'suppression-lists/list',
111
+ {
112
+ pageTitle: `Suppression Lists - ${listId}`,
113
+ menuSuppressionLists: true,
114
+
115
+ listId,
116
+ total: data.total,
117
+
118
+ ...buildPagingView(`admin/suppression-lists/list/${listId}`, data, request.query),
119
+
120
+ addresses: data.addresses
121
+ },
122
+ {
123
+ layout: 'app'
124
+ }
125
+ );
126
+ },
127
+
128
+ options: {
129
+ validate: {
130
+ options: {
131
+ stripUnknown: true,
132
+ abortEarly: false,
133
+ convert: true
134
+ },
135
+
136
+ async failAction(request, h /*, err*/) {
137
+ return h.redirect('/admin/suppression-lists').takeover();
138
+ },
139
+
140
+ params: Joi.object({
141
+ listId: blocklistListIdSchema
142
+ }),
143
+
144
+ query: pagingQuerySchema
145
+ }
146
+ }
147
+ });
148
+
149
+ server.route({
150
+ method: 'POST',
151
+ path: '/admin/suppression-lists/add',
152
+ async handler(request, h) {
153
+ let { listId, recipient, reason } = request.payload;
154
+
155
+ try {
156
+ let added = await lists.add(listId, recipient, {
157
+ source: 'admin',
158
+ reason,
159
+ remoteAddress: request.app.ip,
160
+ userAgent: request.headers['user-agent']
161
+ });
162
+
163
+ if (added) {
164
+ await request.flash({ type: 'info', message: `Added ${recipient} to the suppression list` });
165
+ } else {
166
+ await request.flash({ type: 'info', message: `${recipient} was already listed; the entry was updated` });
167
+ }
168
+
169
+ return h.redirect(adminUrl`/admin/suppression-lists/list/${listId}`);
170
+ } catch (err) {
171
+ await request.flash({ type: 'danger', message: `Couldn't add the address. Try again.` });
172
+ request.logger.error({ msg: 'Failed to add suppression list entry', err, listId, remoteAddress: request.app.ip });
173
+ return h.redirect('/admin/suppression-lists');
174
+ }
175
+ },
176
+ options: {
177
+ validate: {
178
+ options: {
179
+ stripUnknown: true,
180
+ abortEarly: false,
181
+ convert: true
182
+ },
183
+
184
+ async failAction(request, h, err) {
185
+ await request.flash({ type: 'danger', message: `Couldn't add the address. Check the list ID and email address and try again.` });
186
+ request.logger.error({ msg: 'Failed to add suppression list entry', err });
187
+
188
+ return h.redirect('/admin/suppression-lists').takeover();
189
+ },
190
+
191
+ payload: Joi.object({
192
+ listId: blocklistListIdSchema,
193
+ recipient: Joi.string().empty('').email().required().description('Email address to suppress'),
194
+ reason: Joi.string().empty('').max(256).default('block').description('Identifier for the blocking reason')
195
+ })
196
+ }
197
+ }
198
+ });
199
+
200
+ server.route({
201
+ method: 'POST',
202
+ path: '/admin/suppression-lists/list/{listId}/remove',
203
+ async handler(request, h) {
204
+ let listId = request.params.listId;
205
+ let recipient = request.payload.recipient;
206
+
207
+ try {
208
+ let removed = await lists.remove(listId, recipient);
209
+
210
+ if (!removed) {
211
+ await request.flash({ type: 'danger', message: `${recipient} was not found on the list` });
212
+ } else if (!(await lists.exists(listId))) {
213
+ // removing the final address drops the list itself
214
+ await request.flash({ type: 'info', message: `Removed ${recipient}; the now empty list was deleted` });
215
+ return h.redirect('/admin/suppression-lists');
216
+ } else {
217
+ await request.flash({ type: 'info', message: `Removed ${recipient} from the suppression list` });
218
+ }
219
+
220
+ return h.redirect(adminUrl`/admin/suppression-lists/list/${listId}`);
221
+ } catch (err) {
222
+ await request.flash({ type: 'danger', message: `Couldn't remove the address. Try again.` });
223
+ request.logger.error({ msg: 'Failed to remove suppression list entry', err, listId, remoteAddress: request.app.ip });
224
+ return h.redirect(adminUrl`/admin/suppression-lists/list/${listId}`);
225
+ }
226
+ },
227
+ options: {
228
+ validate: {
229
+ options: {
230
+ stripUnknown: true,
231
+ abortEarly: false,
232
+ convert: true
233
+ },
234
+
235
+ async failAction(request, h, err) {
236
+ await request.flash({ type: 'danger', message: `Couldn't remove the address. Try again.` });
237
+ request.logger.error({ msg: 'Failed to remove suppression list entry', err });
238
+
239
+ return h.redirect('/admin/suppression-lists').takeover();
240
+ },
241
+
242
+ params: Joi.object({
243
+ listId: blocklistListIdSchema
244
+ }),
245
+
246
+ payload: Joi.object({
247
+ // entry keys are stored normalized, but accept whatever was displayed
248
+ recipient: Joi.string().max(1024).required().description('Listed address to remove')
249
+ })
250
+ }
251
+ }
252
+ });
253
+
254
+ server.route({
255
+ method: 'POST',
256
+ path: '/admin/suppression-lists/delete',
257
+ async handler(request, h) {
258
+ let listId = request.payload.listId;
259
+
260
+ try {
261
+ let deleted = await lists.deleteList(listId);
262
+
263
+ if (deleted) {
264
+ await request.flash({ type: 'info', message: `Suppression list deleted` });
265
+ } else {
266
+ await request.flash({ type: 'danger', message: `Requested suppression list was not found` });
267
+ }
268
+
269
+ return h.redirect('/admin/suppression-lists');
270
+ } catch (err) {
271
+ await request.flash({ type: 'danger', message: `Couldn't delete the suppression list. Try again.` });
272
+ request.logger.error({ msg: 'Failed to delete suppression list', err, listId, remoteAddress: request.app.ip });
273
+ return h.redirect('/admin/suppression-lists');
274
+ }
275
+ },
276
+ options: {
277
+ validate: {
278
+ options: {
279
+ stripUnknown: true,
280
+ abortEarly: false,
281
+ convert: true
282
+ },
283
+
284
+ async failAction(request, h, err) {
285
+ await request.flash({ type: 'danger', message: `Couldn't delete the suppression list. Try again.` });
286
+ request.logger.error({ msg: 'Failed to delete suppression list', err });
287
+
288
+ return h.redirect('/admin/suppression-lists').takeover();
289
+ },
290
+
291
+ payload: Joi.object({
292
+ listId: blocklistListIdSchema
293
+ })
294
+ }
295
+ }
296
+ });
297
+ }
298
+
299
+ module.exports = init;
@@ -9,8 +9,9 @@ const Joi = require('joi');
9
9
  const Boom = require('@hapi/boom');
10
10
  const { Account } = require('../account');
11
11
  const { redis } = require('../db');
12
- const { REDIS_PREFIX } = require('../consts');
12
+ const { lists } = require('../lists');
13
13
  const { parseSignedFormData } = require('../tools');
14
+ const { isClientError } = require('./route-helpers');
14
15
  const { signedFormBlobFields } = require('../schemas');
15
16
 
16
17
  function init(args) {
@@ -37,7 +38,7 @@ function init(args) {
37
38
  {
38
39
  pageTitleFull: request.app.gt.gettext('Subscription Management'),
39
40
 
40
- unsubscribed: await redis.hexists(`${REDIS_PREFIX}lists:unsub:entries:${data.list}`, data.rcpt),
41
+ unsubscribed: await lists.has(data.list, data.rcpt),
41
42
  values: {
42
43
  listId: data.list,
43
44
  account: data.acc,
@@ -64,7 +65,7 @@ function init(args) {
64
65
  },
65
66
 
66
67
  async failAction(request, h, err) {
67
- request.logger.error({ msg: 'Failed to validate request arguments', err });
68
+ request.logger.debug({ msg: 'Failed to validate request arguments', err });
68
69
  let error = Boom.boomify(new Error(request.app.gt.gettext('Invalid request. Check your input and try again.')), { statusCode: 400 });
69
70
  if (err.code) {
70
71
  error.output.payload.code = err.code;
@@ -121,28 +122,20 @@ function init(args) {
121
122
  }
122
123
  });
123
124
  } catch (err) {
124
- request.logger.error({ msg: `Failed to dispatch ${cmd} event`, account, listId, err });
125
+ request.logger.error({ msg: 'Failed to dispatch list event', event: cmd, account, listId, err });
125
126
  }
126
127
  };
127
128
 
128
129
  switch (request.payload.action) {
129
130
  case 'unsubscribe': {
130
- let isNew = await redis.eeListAdd(
131
- `${REDIS_PREFIX}lists:unsub:lists`,
132
- `${REDIS_PREFIX}lists:unsub:entries:${listId}`,
133
- listId,
134
- email.toLowerCase().trim(),
135
- JSON.stringify({
136
- recipient: email,
137
- account,
138
- source: 'form',
139
- reason: 'unsubscribe',
140
- messageId,
141
- remoteAddress: request.info.remoteAddress,
142
- userAgent: request.headers['user-agent'],
143
- created: new Date().toISOString()
144
- })
145
- );
131
+ let isNew = await lists.add(listId, email, {
132
+ account,
133
+ source: 'form',
134
+ reason: 'unsubscribe',
135
+ messageId,
136
+ remoteAddress: request.info.remoteAddress,
137
+ userAgent: request.headers['user-agent']
138
+ });
146
139
 
147
140
  if (isNew) {
148
141
  await dispatchListEvent('unsubscribe');
@@ -151,12 +144,7 @@ function init(args) {
151
144
  }
152
145
 
153
146
  case 'subscribe': {
154
- let removed = await redis.eeListRemove(
155
- `${REDIS_PREFIX}lists:unsub:lists`,
156
- `${REDIS_PREFIX}lists:unsub:entries:${listId}`,
157
- listId,
158
- email.toLowerCase().trim()
159
- );
147
+ let removed = await lists.remove(listId, email);
160
148
 
161
149
  if (removed) {
162
150
  await dispatchListEvent('subscribe');
@@ -172,7 +160,7 @@ function init(args) {
172
160
  {
173
161
  pageTitleFull: request.app.gt.gettext('Subscription Management'),
174
162
 
175
- unsubscribed: await redis.hexists(`${REDIS_PREFIX}lists:unsub:entries:${listId}`, email),
163
+ unsubscribed: await lists.has(listId, email),
176
164
  values: {
177
165
  listId,
178
166
  account,
@@ -190,7 +178,9 @@ function init(args) {
190
178
  );
191
179
  } catch (err) {
192
180
  await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't process request. Try again.") });
193
- request.logger.error({ msg: 'Failed to process subscription request', err });
181
+ // Boom 4xx (bad signature, unknown account) is client-caused traffic on a public
182
+ // endpoint, not a server failure
183
+ request.logger[isClientError(err) ? 'debug' : 'error']({ msg: 'Failed to process subscription request', err });
194
184
 
195
185
  return h.view(
196
186
  'unsubscribe',
@@ -224,7 +214,7 @@ function init(args) {
224
214
  }
225
215
 
226
216
  await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't process request. Try again.") });
227
- request.logger.error({ msg: 'Failed to process subscription request', err });
217
+ request.logger.debug({ msg: 'Failed to process subscription request', err });
228
218
 
229
219
  return h
230
220
  .view(