emailengine-app 2.77.0 → 2.79.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 (189) hide show
  1. package/.github/workflows/test.yml +80 -0
  2. package/.ncurc.js +23 -13
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +60 -0
  5. package/bin/emailengine.js +1 -1
  6. package/config/e2e.toml +2 -1
  7. package/config/test.toml +2 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +1 -1
  10. package/lib/account/expected-identity.js +88 -0
  11. package/lib/account.js +145 -61
  12. package/lib/api-reference/format.js +105 -4
  13. package/lib/api-reference/index.js +24 -7
  14. package/lib/api-reference/model.js +148 -21
  15. package/lib/api-reference/schema-tree.js +282 -28
  16. package/lib/api-routes/account-routes.js +99 -36
  17. package/lib/api-routes/behavior-notes.js +3 -0
  18. package/lib/api-routes/blocklist-routes.js +21 -47
  19. package/lib/api-routes/chat-routes.js +10 -12
  20. package/lib/api-routes/delivery-test-routes.js +6 -26
  21. package/lib/api-routes/export-routes.js +2 -0
  22. package/lib/api-routes/gateway-routes.js +52 -11
  23. package/lib/api-routes/license-routes.js +2 -0
  24. package/lib/api-routes/mailbox-routes.js +29 -26
  25. package/lib/api-routes/message-routes.js +27 -21
  26. package/lib/api-routes/oauth2-app-routes.js +11 -29
  27. package/lib/api-routes/operation-impact.js +80 -0
  28. package/lib/api-routes/outbox-routes.js +15 -5
  29. package/lib/api-routes/permission-map.js +397 -0
  30. package/lib/api-routes/route-helpers.js +223 -9
  31. package/lib/api-routes/route-metadata.js +28 -0
  32. package/lib/api-routes/settings-routes.js +30 -25
  33. package/lib/api-routes/stats-routes.js +2 -2
  34. package/lib/api-routes/submit-routes.js +53 -31
  35. package/lib/api-routes/template-routes.js +3 -0
  36. package/lib/api-routes/token-routes.js +319 -33
  37. package/lib/api-routes/webhook-route-routes.js +14 -4
  38. package/lib/append-list.js +3 -14
  39. package/lib/arf-detect.js +23 -1
  40. package/lib/auth-token.js +80 -8
  41. package/lib/autodetect-imap-settings.js +40 -16
  42. package/lib/base32.js +30 -0
  43. package/lib/bounce-detect.js +182 -62
  44. package/lib/consts.js +10 -0
  45. package/lib/db.js +20 -2
  46. package/lib/delivery-error.js +30 -1
  47. package/lib/egress-filter.js +89 -8
  48. package/lib/email-client/base-client.js +35 -113
  49. package/lib/email-client/gmail-client.js +22 -13
  50. package/lib/email-client/imap/listing-diff.js +3 -3
  51. package/lib/email-client/imap/mailbox.js +28 -93
  52. package/lib/email-client/imap/subconnection.js +10 -7
  53. package/lib/email-client/imap/sync-operations.js +46 -46
  54. package/lib/email-client/imap-client.js +39 -28
  55. package/lib/email-client/message-builder.js +15 -15
  56. package/lib/email-client/notification-handler.js +1 -1
  57. package/lib/email-client/outlook/graph-api.js +10 -4
  58. package/lib/email-client/outlook-client.js +54 -55
  59. package/lib/email-client/smtp-pool-manager.js +1 -1
  60. package/lib/enum-descriptions.js +92 -2
  61. package/lib/export.js +2 -2
  62. package/lib/field-usage.js +133 -0
  63. package/lib/gateway.js +2 -2
  64. package/lib/get-raw-email.js +1 -1
  65. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  66. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  67. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  68. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  69. package/lib/imapproxy/imap-core/lib/imap-connection.js +17 -7
  70. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  71. package/lib/imapproxy/imap-server.js +40 -10
  72. package/lib/license-beacon.js +5 -10
  73. package/lib/lists.js +49 -1
  74. package/lib/llm-pre-process.js +6 -6
  75. package/lib/logger.js +5 -1
  76. package/lib/metrics-collector.js +2 -2
  77. package/lib/msgpack.js +62 -0
  78. package/lib/oauth/decode-jwt-payload.js +39 -0
  79. package/lib/oauth/gmail.js +9 -12
  80. package/lib/oauth/mail-ru.js +5 -7
  81. package/lib/oauth/outlook-identity.js +61 -0
  82. package/lib/oauth/outlook.js +9 -9
  83. package/lib/oauth/pubsub/google.js +25 -10
  84. package/lib/oauth/retry-setup.js +38 -0
  85. package/lib/oauth/scope-checker.js +1 -1
  86. package/lib/oauth2-apps.js +224 -295
  87. package/lib/openapi/build-document.js +15 -7
  88. package/lib/openapi/joi-schema.js +20 -0
  89. package/lib/outbox.js +145 -14
  90. package/lib/pre-process.js +9 -9
  91. package/lib/queue-stats.js +49 -0
  92. package/lib/read-env-value.js +37 -0
  93. package/lib/reconnection-manager.js +2 -2
  94. package/lib/rewrite-text-nodes.js +4 -3
  95. package/lib/routes-ui.js +4 -0
  96. package/lib/schemas.js +223 -155
  97. package/lib/settings.js +84 -5
  98. package/lib/sub-script.js +2 -1
  99. package/lib/swagger-options.js +2 -1
  100. package/lib/templates.js +5 -5
  101. package/lib/threads.js +2 -2
  102. package/lib/token-audit-log.js +208 -0
  103. package/lib/token-permission-view.js +219 -0
  104. package/lib/token-permissions.js +172 -0
  105. package/lib/tokens.js +100 -16
  106. package/lib/tools.js +259 -85
  107. package/lib/totp.js +67 -0
  108. package/lib/ui-routes/account-routes.js +122 -26
  109. package/lib/ui-routes/admin-config-routes.js +20 -17
  110. package/lib/ui-routes/admin-entities-routes.js +66 -22
  111. package/lib/ui-routes/auth-routes.js +36 -48
  112. package/lib/ui-routes/export-routes.js +10 -4
  113. package/lib/ui-routes/oauth-config-routes.js +5 -5
  114. package/lib/ui-routes/reference-routes.js +11 -8
  115. package/lib/ui-routes/route-helpers.js +79 -2
  116. package/lib/ui-routes/settings-page.js +1 -1
  117. package/lib/ui-routes/smtp-test-routes.js +1 -1
  118. package/lib/ui-routes/suppression-list-routes.js +294 -0
  119. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  120. package/lib/utils/is-email.js +34 -0
  121. package/lib/utils/network.js +2 -2
  122. package/lib/utils/to-camel-case.js +17 -0
  123. package/lib/web-safe-html.js +1 -1
  124. package/lib/webhook-egress.js +37 -0
  125. package/lib/webhook-routing.js +80 -0
  126. package/lib/webhooks.js +21 -15
  127. package/package.json +26 -27
  128. package/sbom.json +1 -0
  129. package/server.js +81 -42
  130. package/static/css/flyonui.css +1 -1
  131. package/static/css/public.css +3 -0
  132. package/static/css/src/app.tailwind.css +159 -9
  133. package/static/js/app.js +69 -0
  134. package/static/js/reference.js +741 -10
  135. package/static/js/ui.js +43 -0
  136. package/static/licenses.html +698 -1590
  137. package/translations/README.md +64 -0
  138. package/translations/de.mo +0 -0
  139. package/translations/de.po +164 -120
  140. package/translations/en.po +200 -161
  141. package/translations/et.mo +0 -0
  142. package/translations/et.po +163 -120
  143. package/translations/fr.mo +0 -0
  144. package/translations/fr.po +163 -120
  145. package/translations/ja.mo +0 -0
  146. package/translations/ja.po +163 -120
  147. package/translations/messages.pot +94 -64
  148. package/translations/nl.mo +0 -0
  149. package/translations/nl.po +164 -120
  150. package/translations/pl.mo +0 -0
  151. package/translations/pl.po +163 -120
  152. package/views/account-identity-error.hbs +34 -0
  153. package/views/accounts/account.hbs +69 -7
  154. package/views/accounts/browse.hbs +18 -35
  155. package/views/accounts/edit.hbs +1 -0
  156. package/views/accounts/register/imap.hbs +12 -2
  157. package/views/config/logging.hbs +6 -0
  158. package/views/config/oauth/app.hbs +0 -2
  159. package/views/config/security.hbs +13 -0
  160. package/views/layout/app.hbs +29 -5
  161. package/views/oauth-scope-error.hbs +1 -1
  162. package/views/partials/oauth_form.hbs +0 -15
  163. package/views/partials/reference/disclosure.hbs +8 -2
  164. package/views/partials/reference/nav.hbs +36 -9
  165. package/views/partials/reference/operation.hbs +48 -14
  166. package/views/partials/reference/params.hbs +17 -1
  167. package/views/partials/reference/schema-node.hbs +112 -54
  168. package/views/partials/reference/schema-tools.hbs +25 -0
  169. package/views/partials/reference/token-alert.hbs +35 -10
  170. package/views/partials/reference/try-it.hbs +84 -11
  171. package/views/partials/side_menu.hbs +1 -0
  172. package/views/partials/ui/checkbox.hbs +2 -2
  173. package/views/partials/ui/tabs.hbs +7 -1
  174. package/views/reference/index.hbs +1 -1
  175. package/views/reference/token.hbs +4 -0
  176. package/views/suppression-lists/index.hbs +85 -0
  177. package/views/suppression-lists/list.hbs +87 -0
  178. package/views/templates/index.hbs +8 -2
  179. package/views/tokens/index.hbs +31 -4
  180. package/views/tokens/new.hbs +324 -2
  181. package/workers/api.js +299 -140
  182. package/workers/documents.js +46 -26
  183. package/workers/export.js +20 -8
  184. package/workers/imap-proxy.js +2 -2
  185. package/workers/imap.js +13 -7
  186. package/workers/smtp.js +13 -7
  187. package/workers/submit.js +41 -31
  188. package/workers/webhooks.js +60 -37
  189. package/lib/feature-flags.js +0 -48
@@ -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
 
@@ -27,6 +27,11 @@ const TEMP_TOKEN_TTL = 60 * 60 * 1000;
27
27
  // can never be deleted by clearing the field.
28
28
  const TEMP_TOKEN_DESCRIPTION = 'Temporary token for the API reference';
29
29
 
30
+ // Opts every reference page into the layout's second navigation column, rendered flush
31
+ // against the main sidebar (views/layout/app.hbs). The label names it where the column
32
+ // cannot be shown as a column - below lg it collapses to a single row carrying this text.
33
+ const SECONDARY_NAV = { secondaryNav: 'reference/nav', secondaryNavLabel: 'Endpoints' };
34
+
30
35
  function init(args) {
31
36
  const { server } = args;
32
37
 
@@ -36,9 +41,7 @@ function init(args) {
36
41
  async handler(request, h) {
37
42
  const view = await getIndexView(request);
38
43
 
39
- // secondaryNav opts this page into the layout's second navigation column,
40
- // rendered flush against the main sidebar (views/layout/app.hbs)
41
- return h.view('reference/index', Object.assign({ pageTitle: 'API Reference', menuReference: true, secondaryNav: 'reference/nav' }, view), {
44
+ return h.view('reference/index', Object.assign({ pageTitle: 'API Reference', menuReference: true, ...SECONDARY_NAV }, view), {
42
45
  layout: 'app'
43
46
  });
44
47
  }
@@ -53,7 +56,7 @@ function init(args) {
53
56
  async handler(request, h) {
54
57
  const view = await getNavView(request);
55
58
 
56
- return h.view('reference/token', Object.assign({ pageTitle: 'Access token', menuReference: true, secondaryNav: 'reference/nav' }, view), {
59
+ return h.view('reference/token', Object.assign({ pageTitle: 'Access token', menuReference: true, ...SECONDARY_NAV }, view), {
57
60
  layout: 'app'
58
61
  });
59
62
  }
@@ -69,7 +72,7 @@ function init(args) {
69
72
  throw Boom.notFound('Unknown endpoint group');
70
73
  }
71
74
 
72
- return h.view('reference/tag', Object.assign({ pageTitle: `${view.tag.name} API`, menuReference: true, secondaryNav: 'reference/nav' }, view), {
75
+ return h.view('reference/tag', Object.assign({ pageTitle: `${view.tag.name} API`, menuReference: true, ...SECONDARY_NAV }, view), {
73
76
  layout: 'app'
74
77
  });
75
78
  },
@@ -138,7 +141,7 @@ function init(args) {
138
141
 
139
142
  return { success: true, token, expires };
140
143
  } catch (err) {
141
- 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 });
142
145
  return jsonErrorPayload(err);
143
146
  }
144
147
  }
@@ -175,7 +178,7 @@ function init(args) {
175
178
 
176
179
  return { success: true, deleted: true };
177
180
  } catch (err) {
178
- 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 });
179
182
  return jsonErrorPayload(err);
180
183
  }
181
184
  },
@@ -18,7 +18,7 @@ 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 { REDIS_PREFIX, DEFAULT_PAGE_SIZE } = require('../consts');
22
22
  const { oauth2ProviderData } = require('../oauth2-apps');
23
23
  const exampleDocumentsPayloads = require('../payload-examples-documents.json');
24
24
 
@@ -315,6 +315,19 @@ async function getServerStatus(type) {
315
315
  return { state, payload, label: formatServerState(state, payload) };
316
316
  }
317
317
 
318
+ // True for failures the client caused (a Boom 4xx, e.g. a stale tab polling a deleted entity).
319
+ // Used by catch blocks to skip or demote logging for them, so bot and stale-UI traffic does not
320
+ // land in the error stream.
321
+ function isClientError(err) {
322
+ return Boom.isBoom(err) && err.output.statusCode < 500;
323
+ }
324
+
325
+ // An unauthenticated attempt rejected with Boom.forbidden is an auth event worth auditing at
326
+ // warn, not a server failure. Returns the log level for a catch block that serves both cases.
327
+ function authAwareLevel(err) {
328
+ return Boom.isBoom(err) && err.output.statusCode === 403 ? 'warn' : 'error';
329
+ }
330
+
318
331
  function throwAsBoom(err) {
319
332
  if (Boom.isBoom(err)) {
320
333
  throw err;
@@ -336,8 +349,69 @@ function jsonErrorPayload(err) {
336
349
  return { success: false, error: err.code || 'Error', message: err.message };
337
350
  }
338
351
 
352
+ // The "wrong account" page, shown when a setup link pinned to one address is completed as another.
353
+ // Rendered from both arms of the hosted form - the OAuth2 callback in workers/api.js and the IMAP arm in
354
+ // ./account-routes.js - which live in different workers, so the view name, the layout and the refusal
355
+ // status are kept here rather than written out twice. Only `retryUrl` is arm-specific: the OAuth arm
356
+ // sends the user back to the provider, the IMAP arm back to the form.
357
+ //
358
+ // 403 rather than the 200 that the sibling views/oauth-scope-error.hbs returns: this is a refused
359
+ // request, the surrounding refusals in the same flow already answer 403, and both call sites are plain
360
+ // form navigations, so the browser still renders the page.
361
+ function identityErrorView(request, h, { expectedEmail, actualEmail, retryUrl }) {
362
+ return h
363
+ .view(
364
+ 'account-identity-error',
365
+ {
366
+ pageTitleFull: request.app.gt.gettext('Email Account Setup'),
367
+ templateLocale: request.app.locale,
368
+ expectedEmail,
369
+ actualEmail,
370
+ retryUrl
371
+ },
372
+ {
373
+ layout: 'public'
374
+ }
375
+ )
376
+ .code(403);
377
+ }
378
+
379
+ // View-model for the ui/pagination partial: prev/next URLs plus the numbered page links.
380
+ // basePath is the URL path without a query string (leading slash optional, matching the
381
+ // `new URL(path, base)` convention the route modules already use); data is a listing
382
+ // response carrying zero-based `page` and total `pages`; query is the validated request
383
+ // query whose `pageSize` is appended to the URLs only when it differs from the default.
384
+ function buildPagingView(basePath, data, query) {
385
+ const getPagingUrl = page => {
386
+ let url = new URL(basePath, 'http://localhost');
387
+
388
+ if (page) {
389
+ url.searchParams.append('page', page);
390
+ }
391
+
392
+ if (query.pageSize !== DEFAULT_PAGE_SIZE) {
393
+ url.searchParams.append('pageSize', query.pageSize);
394
+ }
395
+
396
+ return url.pathname + url.search;
397
+ };
398
+
399
+ return {
400
+ showPaging: data.pages > 1,
401
+ nextPage: data.pages > data.page + 1 ? getPagingUrl(data.page + 2) : false,
402
+ prevPage: data.page > 0 ? getPagingUrl(data.page) : false,
403
+ firstPage: data.page === 0,
404
+ pageLinks: new Array(data.pages || 1).fill(0).map((z, i) => ({
405
+ url: getPagingUrl(i + 1),
406
+ title: i + 1,
407
+ active: i === data.page
408
+ }))
409
+ };
410
+ }
411
+
339
412
  module.exports = {
340
413
  jsonErrorPayload,
414
+ identityErrorView,
341
415
  OPEN_AI_MODELS,
342
416
  cachedTemplates,
343
417
  getOpenAiModels,
@@ -347,5 +421,8 @@ module.exports = {
347
421
  formatAccountData,
348
422
  getExampleDocumentsPayloads,
349
423
  getServerStatus,
350
- throwAsBoom
424
+ throwAsBoom,
425
+ isClientError,
426
+ authAwareLevel,
427
+ buildPagingView
351
428
  };
@@ -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,294 @@
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 { redis } = require('../db');
11
+ const { lists } = require('../lists');
12
+ const settings = require('../settings');
13
+ const { accountExists } = require('../account');
14
+ const { blocklistListIdSchema } = require('../schemas');
15
+ const { buildPagingView } = require('./route-helpers');
16
+ const { buildUnsubscribeUrl, getServiceSecret } = require('../tools');
17
+ const consts = require('../consts');
18
+
19
+ const { DEFAULT_PAGE_SIZE } = consts;
20
+
21
+ const pagingQuerySchema = Joi.object({
22
+ page: Joi.number().integer().min(1).max(1000000).default(1),
23
+ pageSize: Joi.number().integer().min(1).max(250).default(DEFAULT_PAGE_SIZE)
24
+ });
25
+
26
+ function init(args) {
27
+ const { server } = args;
28
+
29
+ server.route({
30
+ method: 'GET',
31
+ path: '/admin/suppression-lists',
32
+ async handler(request, h) {
33
+ let data = await lists.list(request.query.page - 1, request.query.pageSize);
34
+
35
+ return h.view(
36
+ 'suppression-lists/index',
37
+ {
38
+ pageTitle: 'Suppression Lists',
39
+ menuSuppressionLists: true,
40
+
41
+ total: data.total,
42
+
43
+ ...buildPagingView('admin/suppression-lists', data, request.query),
44
+
45
+ suppressionLists: data.blocklists
46
+ },
47
+ {
48
+ layout: 'app'
49
+ }
50
+ );
51
+ },
52
+
53
+ options: {
54
+ validate: {
55
+ options: {
56
+ stripUnknown: true,
57
+ abortEarly: false,
58
+ convert: true
59
+ },
60
+
61
+ async failAction(request, h /*, err*/) {
62
+ return h.redirect('/admin/suppression-lists').takeover();
63
+ },
64
+
65
+ query: pagingQuerySchema
66
+ }
67
+ }
68
+ });
69
+
70
+ server.route({
71
+ method: 'GET',
72
+ path: '/admin/suppression-lists/list/{listId}',
73
+ async handler(request, h) {
74
+ let listId = request.params.listId;
75
+
76
+ let data;
77
+ try {
78
+ data = await lists.listContent(listId, request.query.page - 1, request.query.pageSize);
79
+ } catch (err) {
80
+ await request.flash({ type: 'danger', message: `Requested suppression list was not found` });
81
+ return h.redirect('/admin/suppression-lists');
82
+ }
83
+
84
+ // Link each entry to its public subscription management page - the same signed URL
85
+ // the List-Unsubscribe header carries - so the page can be previewed or the link
86
+ // sent to the recipient for self service re-subscription. The page loads the
87
+ // account, so entries without one (or whose account is gone) get no link.
88
+ let [serviceUrl, serviceSecret] = await Promise.all([settings.get('serviceUrl'), getServiceSecret()]);
89
+
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)])));
92
+
93
+ for (let entry of data.addresses) {
94
+ if (!entry.account || !knownAccounts.get(entry.account)) {
95
+ continue;
96
+ }
97
+ entry.unsubscribeUrl = buildUnsubscribeUrl(serviceSecret, serviceUrl, {
98
+ account: entry.account,
99
+ list: listId,
100
+ recipient: entry.recipient
101
+ });
102
+ }
103
+
104
+ return h.view(
105
+ 'suppression-lists/list',
106
+ {
107
+ pageTitle: `Suppression Lists - ${listId}`,
108
+ menuSuppressionLists: true,
109
+
110
+ listId,
111
+ total: data.total,
112
+
113
+ ...buildPagingView(`admin/suppression-lists/list/${listId}`, data, request.query),
114
+
115
+ addresses: data.addresses
116
+ },
117
+ {
118
+ layout: 'app'
119
+ }
120
+ );
121
+ },
122
+
123
+ options: {
124
+ validate: {
125
+ options: {
126
+ stripUnknown: true,
127
+ abortEarly: false,
128
+ convert: true
129
+ },
130
+
131
+ async failAction(request, h /*, err*/) {
132
+ return h.redirect('/admin/suppression-lists').takeover();
133
+ },
134
+
135
+ params: Joi.object({
136
+ listId: blocklistListIdSchema
137
+ }),
138
+
139
+ query: pagingQuerySchema
140
+ }
141
+ }
142
+ });
143
+
144
+ server.route({
145
+ method: 'POST',
146
+ path: '/admin/suppression-lists/add',
147
+ async handler(request, h) {
148
+ let { listId, recipient, reason } = request.payload;
149
+
150
+ try {
151
+ let added = await lists.add(listId, recipient, {
152
+ source: 'admin',
153
+ reason,
154
+ remoteAddress: request.app.ip,
155
+ userAgent: request.headers['user-agent']
156
+ });
157
+
158
+ if (added) {
159
+ await request.flash({ type: 'info', message: `Added ${recipient} to the suppression list` });
160
+ } else {
161
+ await request.flash({ type: 'info', message: `${recipient} was already listed; the entry was updated` });
162
+ }
163
+
164
+ return h.redirect(`/admin/suppression-lists/list/${listId}`);
165
+ } catch (err) {
166
+ await request.flash({ type: 'danger', message: `Couldn't add the address. Try again.` });
167
+ request.logger.error({ msg: 'Failed to add suppression list entry', err, listId, remoteAddress: request.app.ip });
168
+ return h.redirect('/admin/suppression-lists');
169
+ }
170
+ },
171
+ options: {
172
+ validate: {
173
+ options: {
174
+ stripUnknown: true,
175
+ abortEarly: false,
176
+ convert: true
177
+ },
178
+
179
+ async failAction(request, h, err) {
180
+ await request.flash({ type: 'danger', message: `Couldn't add the address. Check the list ID and email address and try again.` });
181
+ request.logger.error({ msg: 'Failed to add suppression list entry', err });
182
+
183
+ return h.redirect('/admin/suppression-lists').takeover();
184
+ },
185
+
186
+ payload: Joi.object({
187
+ listId: blocklistListIdSchema,
188
+ recipient: Joi.string().empty('').email().required().description('Email address to suppress'),
189
+ reason: Joi.string().empty('').max(256).default('block').description('Identifier for the blocking reason')
190
+ })
191
+ }
192
+ }
193
+ });
194
+
195
+ server.route({
196
+ method: 'POST',
197
+ path: '/admin/suppression-lists/list/{listId}/remove',
198
+ async handler(request, h) {
199
+ let listId = request.params.listId;
200
+ let recipient = request.payload.recipient;
201
+
202
+ try {
203
+ let removed = await lists.remove(listId, recipient);
204
+
205
+ if (!removed) {
206
+ await request.flash({ type: 'danger', message: `${recipient} was not found on the list` });
207
+ } else if (!(await lists.exists(listId))) {
208
+ // removing the final address drops the list itself
209
+ await request.flash({ type: 'info', message: `Removed ${recipient}; the now empty list was deleted` });
210
+ return h.redirect('/admin/suppression-lists');
211
+ } else {
212
+ await request.flash({ type: 'info', message: `Removed ${recipient} from the suppression list` });
213
+ }
214
+
215
+ return h.redirect(`/admin/suppression-lists/list/${listId}`);
216
+ } catch (err) {
217
+ await request.flash({ type: 'danger', message: `Couldn't remove the address. Try again.` });
218
+ 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}`);
220
+ }
221
+ },
222
+ options: {
223
+ validate: {
224
+ options: {
225
+ stripUnknown: true,
226
+ abortEarly: false,
227
+ convert: true
228
+ },
229
+
230
+ async failAction(request, h, err) {
231
+ await request.flash({ type: 'danger', message: `Couldn't remove the address. Try again.` });
232
+ request.logger.error({ msg: 'Failed to remove suppression list entry', err });
233
+
234
+ return h.redirect('/admin/suppression-lists').takeover();
235
+ },
236
+
237
+ params: Joi.object({
238
+ listId: blocklistListIdSchema
239
+ }),
240
+
241
+ payload: Joi.object({
242
+ // entry keys are stored normalized, but accept whatever was displayed
243
+ recipient: Joi.string().max(1024).required().description('Listed address to remove')
244
+ })
245
+ }
246
+ }
247
+ });
248
+
249
+ server.route({
250
+ method: 'POST',
251
+ path: '/admin/suppression-lists/delete',
252
+ async handler(request, h) {
253
+ let listId = request.payload.listId;
254
+
255
+ try {
256
+ let deleted = await lists.deleteList(listId);
257
+
258
+ if (deleted) {
259
+ await request.flash({ type: 'info', message: `Suppression list deleted` });
260
+ } else {
261
+ await request.flash({ type: 'danger', message: `Requested suppression list was not found` });
262
+ }
263
+
264
+ return h.redirect('/admin/suppression-lists');
265
+ } catch (err) {
266
+ await request.flash({ type: 'danger', message: `Couldn't delete the suppression list. Try again.` });
267
+ request.logger.error({ msg: 'Failed to delete suppression list', err, listId, remoteAddress: request.app.ip });
268
+ return h.redirect('/admin/suppression-lists');
269
+ }
270
+ },
271
+ options: {
272
+ validate: {
273
+ options: {
274
+ stripUnknown: true,
275
+ abortEarly: false,
276
+ convert: true
277
+ },
278
+
279
+ async failAction(request, h, err) {
280
+ await request.flash({ type: 'danger', message: `Couldn't delete the suppression list. Try again.` });
281
+ request.logger.error({ msg: 'Failed to delete suppression list', err });
282
+
283
+ return h.redirect('/admin/suppression-lists').takeover();
284
+ },
285
+
286
+ payload: Joi.object({
287
+ listId: blocklistListIdSchema
288
+ })
289
+ }
290
+ }
291
+ });
292
+ }
293
+
294
+ 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(
@@ -0,0 +1,34 @@
1
+ 'use strict';
2
+
3
+ const Joi = require('joi');
4
+
5
+ // Built once. joi schemas are immutable and meant to be reused, and compiling this per call measured
6
+ // ~5x slower - which matters because unserializeAccountData() calls isEmail() for every OAuth2 account
7
+ // that has no stored email, and the account listing maps that over every row of a page.
8
+ const emailSchema = Joi.object({
9
+ email: Joi.string().email().required()
10
+ });
11
+
12
+ const validateOptions = {
13
+ abortEarly: false,
14
+ stripUnknown: true,
15
+ convert: true
16
+ };
17
+
18
+ // Syntactic check only - it says the string is shaped like an address, never that the address is real
19
+ // or that whoever supplied it controls it. Trust decisions belong to the caller.
20
+ //
21
+ // Lives here rather than in lib/tools.js so the pure modules that need it (lib/oauth/outlook-identity.js)
22
+ // do not have to require tools, which pulls in settings and a Redis connection. lib/tools.js re-exports
23
+ // this function, so every existing caller is unaffected.
24
+ function isEmail(str) {
25
+ const { error, value } = emailSchema.validate({ email: str }, validateOptions);
26
+
27
+ if (error) {
28
+ return false;
29
+ }
30
+
31
+ return value.email;
32
+ }
33
+
34
+ module.exports = { isEmail };
@@ -102,7 +102,7 @@ function matchIp(ip, addresses) {
102
102
  return true;
103
103
  }
104
104
  } catch (err) {
105
- logger.error({ msg: 'Failed to parse IP address', ip, addr, err });
105
+ logger.error({ msg: 'Failed to parse allowlist address', ip, addr, err });
106
106
  }
107
107
  }
108
108
 
@@ -339,7 +339,7 @@ async function getLocalAddress(redis, protocol, account, hint) {
339
339
  addressData.addressSelector = addressSelector;
340
340
  return addressData;
341
341
  } catch (err) {
342
- logger.error({ msg: 'Failed to load address data', localAddress, err });
342
+ logger.warn({ msg: 'Failed to load address data', localAddress, err });
343
343
  addressSelector = 'error';
344
344
  return { address: false, name: hostname, addressSelector };
345
345
  }
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+
3
+ // Lives here rather than in lib/tools.js so that pure modules can use it: tools.js opens Redis,
4
+ // which hangs a unit test that only wants to parse a message. tools.js re-exports it, so the
5
+ // existing `require('../tools')` consumers are unaffected.
6
+
7
+ /**
8
+ * Converts a kebab-case header name into the camelCase key used in payloads,
9
+ * eg. "final-recipient" into "finalRecipient"
10
+ * @param {String} key Header name
11
+ * @returns {String} camelCased key
12
+ */
13
+ function toCamelCase(key) {
14
+ return key.replace(/-(.)/g, (m, c) => c.toUpperCase());
15
+ }
16
+
17
+ module.exports = { toCamelCase };