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
package/workers/api.js CHANGED
@@ -8,10 +8,10 @@ const logger = require('../lib/logger');
8
8
  const Path = require('path');
9
9
  const Gettext = require('@postalsys/gettext');
10
10
  const { loadTranslations, gt, joiLocales, locales } = require('../lib/translations');
11
- const { accountStateLabel, formatServerState, identityErrorView } = require('../lib/ui-routes/route-helpers');
11
+ const { accountStateLabel, formatServerState, identityErrorView, isClientError } = require('../lib/ui-routes/route-helpers');
12
12
  const util = require('util');
13
13
  const { webhooks: Webhooks } = require('../lib/webhooks');
14
- const featureFlags = require('../lib/feature-flags');
14
+ const { lists } = require('../lib/lists');
15
15
  const Bell = require('@hapi/bell');
16
16
  const marked = require('marked');
17
17
 
@@ -71,6 +71,9 @@ const { matchesExpectedIdentity, pendingSetupExpectation, resolveExpectedIdentit
71
71
  const handlebars = require('handlebars');
72
72
  const AuthBearer = require('hapi-auth-bearer-token');
73
73
  const tokens = require('../lib/tokens');
74
+ const tokenPermissions = require('../lib/token-permissions');
75
+ const tokenAuditLog = require('../lib/token-audit-log');
76
+ const { routeGrant } = require('../lib/api-routes/permission-map');
74
77
 
75
78
  const { redis, documentsQueue } = require('../lib/db');
76
79
  const { Account } = require('../lib/account');
@@ -151,7 +154,11 @@ function formatScopeDescription(scope) {
151
154
  return shortName.replace(/\./g, ' ').replace(/\b\w/g, c => c.toUpperCase());
152
155
  }
153
156
 
154
- const REDACTED_KEYS = ['req.headers.authorization', 'req.headers.cookie', 'err.rawPacket'];
157
+ // The two MS Graph subscription routes are unauthenticated and deliberately carry no payload
158
+ // schema: they must answer 202 to anything, because a 400 would make Graph tear the subscription
159
+ // down, and the validation handshake posts an empty body. So the payload is arbitrary JSON and
160
+ // every read of it has to be defensive.
161
+ const graphNotificationEntries = payload => (Array.isArray(payload && payload.value) ? payload.value.filter(entry => entry && typeof entry === 'object') : []);
155
162
 
156
163
  const SMTP_TEST_HOST = 'https://api.nodemailer.com';
157
164
 
@@ -381,7 +388,7 @@ function publishChangeEvent(data) {
381
388
  try {
382
389
  stream.sendMessage({ account, type, key, payload, stateLabel });
383
390
  } catch (err) {
384
- logger.error({ msg: 'Failed to publish change event', err, account, type, key, payload });
391
+ logger.warn({ msg: 'Failed to publish change event', err, account, type, key, payload });
385
392
  }
386
393
  }
387
394
  }
@@ -474,6 +481,11 @@ const init = async () => {
474
481
  // keep using "danger" etc.
475
482
  handlebars.registerHelper('eeColor', value => (value === 'danger' ? 'error' : value || 'neutral'));
476
483
 
484
+ // Percent-encode a value for interpolation into a URL path segment. Handlebars escapes for
485
+ // HTML, which leaves "#", "/", "?" and "%" untouched - and an account ID is free text, so
486
+ // href="/admin/accounts/{{account}}" resolves somewhere else entirely for an ID carrying one.
487
+ handlebars.registerHelper('urlpart', value => encodeURIComponent(value === null || value === undefined ? '' : value));
488
+
477
489
  // Join string fragments in subexpressions, e.g. building composed partial
478
490
  // hash values: text=(concat "Up to " (formatInteger n locale) " lines")
479
491
  handlebars.registerHelper('concat', (...args) => args.slice(0, -1).join(''));
@@ -485,13 +497,6 @@ const init = async () => {
485
497
 
486
498
  handlebars.registerHelper('ngettext', (msgid, plural, count) => util.format(gt.ngettext(msgid, plural, count), count));
487
499
 
488
- handlebars.registerHelper('featureFlag', function (flag, options) {
489
- if (featureFlags.enabled(flag)) {
490
- return options.fn(this);
491
- }
492
- return options.inverse(this);
493
- });
494
-
495
500
  handlebars.registerHelper('equals', function (compareVal, baseVal, options) {
496
501
  if (baseVal === compareVal) {
497
502
  return options.fn(this);
@@ -912,9 +917,39 @@ const init = async () => {
912
917
  request.logger.setBindings({ tokenId: tokenData.id, tokenAccount: tokenData.account || null });
913
918
  }
914
919
 
920
+ const grant = routeGrant(request.route);
921
+
922
+ // This strategy runs before route validation, so `request.query` is whatever the client
923
+ // sent: a repeated `?account=` arrives as an array. Only a string can name an account,
924
+ // and this value is persisted into the audit log, so anything else is not one.
925
+ const queryAccount = request.query && typeof request.query.account === 'string' ? request.query.account : null;
926
+
927
+ // Shared by every audit entry below, so an allow and a deny describe the same request.
928
+ // Built before the first check that can refuse: a rejection is the strongest signal of
929
+ // credential misuse there is, and a trail that only held the calls that succeeded would
930
+ // be silent about exactly the ones worth looking at.
931
+ const auditEntry = {
932
+ tokenId: tokenData.id,
933
+ ip: request.app.ip,
934
+ method: request.route.method,
935
+ path: request.route.path,
936
+ action: grant.action,
937
+ group: grant.group,
938
+ // The account the REQUEST addressed, which is not always the one in the path: the
939
+ // routes that take it as a query argument are the ones a bound token gets refused
940
+ // on, and falling straight through to the token's own account recorded a
941
+ // cross-account attempt against the account it was entitled to reach - the opposite
942
+ // of what the entry exists to show. The token's account is still the answer for the
943
+ // routes that name no account at all.
944
+ //
945
+ // The refusals below log this field rather than re-deriving it, so the application
946
+ // log and the audit row cannot disagree about which account a denial concerned.
947
+ account: (request.params && request.params.account) || queryAccount || tokenData.account || null
948
+ };
949
+
915
950
  if (scope && tokenData.scopes && !tokenData.scopes.includes(scope) && !tokenData.scopes.includes('*')) {
916
951
  // failed scope validation
917
- logger.error({
952
+ logger.warn({
918
953
  msg: 'Trying to use invalid scope for a token',
919
954
  tokenAccount: tokenData.account,
920
955
  tokenId: tokenData.id,
@@ -922,11 +957,43 @@ const init = async () => {
922
957
  tokenScopes: tokenData.scopes
923
958
  });
924
959
 
960
+ tokenAuditLog.denied(auditEntry, 'scope');
961
+
925
962
  let error = Boom.forbidden('Unauthorized scope');
926
963
  error.output.payload.requestedScope = scope;
927
964
  throw error;
928
965
  }
929
966
 
967
+ // Narrowing below the scope. Runs after the scope check and before the account binding,
968
+ // so the order is: token resolved, scope, permissions, account, restrictions.
969
+ //
970
+ // Before the account switch on purpose - that switch reads the account from the query or
971
+ // from a Redis membership check for the three /v1/templates special cases, and none of
972
+ // that should happen for a request the permissions already refuse.
973
+ //
974
+ // Only subtracts: a token with no `permissions` field takes the allowed path, which is
975
+ // every token issued before this shipped.
976
+ const permissionCheck = tokenPermissions.check({ tokenData, operation: grant });
977
+ if (!permissionCheck.allowed) {
978
+ logger.warn({
979
+ msg: 'Token permissions do not allow this operation',
980
+ tokenAccount: tokenData.account,
981
+ tokenId: tokenData.id,
982
+ account: auditEntry.account,
983
+ reason: permissionCheck.reason,
984
+ required: permissionCheck.required
985
+ });
986
+
987
+ let error = Boom.forbidden('Unauthorized permission');
988
+ // Mirrors how the scope failure above attaches requestedScope: an agent that gets a
989
+ // 403 needs to know WHICH grant it lacked, not just that it lacked one.
990
+ // A refused call is the interesting record, so it is logged before the throw
991
+ tokenAuditLog.denied(auditEntry, permissionCheck.reason);
992
+
993
+ error.output.payload.requiredPermission = permissionCheck.required;
994
+ throw error;
995
+ }
996
+
930
997
  if (tokenData.account) {
931
998
  // account token
932
999
 
@@ -934,10 +1001,18 @@ const init = async () => {
934
1001
 
935
1002
  // allow specific routes that have an account component but not in the URL params section
936
1003
  switch (request.route.path) {
1004
+ // The two listings that take the account as a query argument. `/v1/tokens` is
1005
+ // here because it replaced GET /v1/tokens/account/{account}, which carried the
1006
+ // account in the path and so reached a bound token's own tokens through the
1007
+ // default branch below - as its deprecated alias registration still does.
1008
+ // Both stay under the same rule as everything else: the argument has to name the
1009
+ // token's own account, and omitting it still refuses, because a bound credential
1010
+ // must not enumerate the instance.
937
1011
  case '/v1/templates':
1012
+ case '/v1/tokens':
938
1013
  switch (request.method) {
939
1014
  case 'get':
940
- accountIdSource = request.query && request.query.account;
1015
+ accountIdSource = queryAccount;
941
1016
  break;
942
1017
  }
943
1018
  break;
@@ -967,13 +1042,15 @@ const init = async () => {
967
1042
  }
968
1043
 
969
1044
  if (accountIdSource !== tokenData.account) {
970
- logger.error({
1045
+ logger.warn({
971
1046
  msg: 'Trying to use invalid account for a token',
972
1047
  tokenAccount: tokenData.account,
973
1048
  tokenId: tokenData.id,
974
- account: (request.params && request.params.account) || null
1049
+ account: auditEntry.account
975
1050
  });
976
1051
 
1052
+ tokenAuditLog.denied(auditEntry, 'account');
1053
+
977
1054
  let error = Boom.forbidden('Unauthorized account');
978
1055
  throw error;
979
1056
  }
@@ -981,15 +1058,17 @@ const init = async () => {
981
1058
 
982
1059
  if (tokenData.restrictions) {
983
1060
  if (tokenData.restrictions.addresses && !matchIp(request.app.ip, tokenData.restrictions.addresses)) {
984
- logger.error({
1061
+ logger.warn({
985
1062
  msg: 'Trying to use invalid IP for a token',
986
1063
  tokenAccount: tokenData.account,
987
1064
  tokenId: tokenData.id,
988
- account: (request.params && request.params.account) || null,
1065
+ account: auditEntry.account,
989
1066
  remoteAddress: request.app.ip,
990
1067
  addressAllowlist: tokenData.restrictions.addresses
991
1068
  });
992
1069
 
1070
+ tokenAuditLog.denied(auditEntry, 'address');
1071
+
993
1072
  let error = Boom.forbidden('Unauthorized address');
994
1073
  error.output.payload.remoteAddress = request.app.ip;
995
1074
  throw error;
@@ -1000,15 +1079,17 @@ const init = async () => {
1000
1079
  tokenData.restrictions.referrers.length &&
1001
1080
  !matcher(tokenData.restrictions.referrers, request.headers.referer)
1002
1081
  ) {
1003
- logger.error({
1082
+ logger.warn({
1004
1083
  msg: 'Trying to use invalid referer for a token',
1005
1084
  tokenAccount: tokenData.account,
1006
1085
  tokenId: tokenData.id,
1007
- account: (request.params && request.params.account) || null,
1086
+ account: auditEntry.account,
1008
1087
  referer: request.headers.referer,
1009
1088
  referrerAllowlist: tokenData.restrictions.referrers
1010
1089
  });
1011
1090
 
1091
+ tokenAuditLog.denied(auditEntry, 'referrer');
1092
+
1012
1093
  let error = Boom.forbidden('Unauthorized referrer');
1013
1094
  throw error;
1014
1095
  }
@@ -1022,7 +1103,9 @@ const init = async () => {
1022
1103
  );
1023
1104
 
1024
1105
  if (!rateLimit.success) {
1025
- logger.error({ msg: 'Rate limited', token: tokenData.id, rateLimit });
1106
+ logger.warn({ msg: 'Rate limited', token: tokenData.id, rateLimit });
1107
+ tokenAuditLog.denied(auditEntry, 'rateLimit');
1108
+
1026
1109
  let error = Boom.tooManyRequests('Rate limit exceeded');
1027
1110
  error.output.payload.ttl = Math.ceil(rateLimit.ttl);
1028
1111
  error.output.headers = {
@@ -1040,6 +1123,13 @@ const init = async () => {
1040
1123
  }
1041
1124
  }
1042
1125
 
1126
+ // The one point every accepted token request passes. "allowed" means the credential was
1127
+ // accepted, not that the request succeeded: this runs in the auth strategy, before
1128
+ // payload validation and the handler, so a call recorded here can still end in a 400 or
1129
+ // a 404. That is the right boundary for a credential trail - it answers what the token
1130
+ // was permitted to attempt.
1131
+ tokenAuditLog.allowed(auditEntry);
1132
+
1043
1133
  return { isValid: true, credentials: { token }, artifacts: tokenData };
1044
1134
  }
1045
1135
  });
@@ -1310,9 +1400,9 @@ const init = async () => {
1310
1400
  await server.register({
1311
1401
  plugin: hapiPino,
1312
1402
  options: {
1313
- instance: logger.child({ component: 'api' }, { redact: REDACTED_KEYS }),
1403
+ instance: logger.child({ component: 'api' }, { redact: consts.REDACTED_LOG_KEYS }),
1314
1404
  // Redact Authorization headers, see https://getpino.io/#/docs/redaction
1315
- redact: REDACTED_KEYS
1405
+ redact: consts.REDACTED_LOG_KEYS
1316
1406
  }
1317
1407
  });
1318
1408
 
@@ -1551,7 +1641,7 @@ const init = async () => {
1551
1641
  userAgent: request.headers['user-agent']
1552
1642
  });
1553
1643
  } else {
1554
- request.logger.info({
1644
+ request.logger.debug({
1555
1645
  msg: 'Detected automated request',
1556
1646
  account: data.acc,
1557
1647
  event: TRACK_CLICK_NOTIFY,
@@ -1615,7 +1705,7 @@ const init = async () => {
1615
1705
  userAgent: request.headers['user-agent']
1616
1706
  });
1617
1707
  } else {
1618
- request.logger.info({
1708
+ request.logger.debug({
1619
1709
  msg: 'Detected automated request',
1620
1710
  account: data.acc,
1621
1711
  event: TRACK_OPEN_NOTIFY,
@@ -1715,22 +1805,14 @@ const init = async () => {
1715
1805
 
1716
1806
  // Record the suppression. A transient backend failure here is intentionally NOT swallowed to
1717
1807
  // a 2xx: it propagates as a 5xx so the client retries rather than dropping the unsubscribe.
1718
- let isNew = await redis.eeListAdd(
1719
- `${REDIS_PREFIX}lists:unsub:lists`,
1720
- `${REDIS_PREFIX}lists:unsub:entries:${data.list}`,
1721
- data.list,
1722
- data.rcpt.toLowerCase().trim(),
1723
- JSON.stringify({
1724
- recipient: data.rcpt,
1725
- account: data.acc,
1726
- source: 'one-click',
1727
- reason: 'unsubscribe',
1728
- messageId: data.msg,
1729
- remoteAddress: request.app.ip,
1730
- userAgent: request.headers['user-agent'],
1731
- created: new Date().toISOString()
1732
- })
1733
- );
1808
+ let isNew = await lists.add(data.list, data.rcpt, {
1809
+ account: data.acc,
1810
+ source: 'one-click',
1811
+ reason: 'unsubscribe',
1812
+ messageId: data.msg,
1813
+ remoteAddress: request.app.ip,
1814
+ userAgent: request.headers['user-agent']
1815
+ });
1734
1816
 
1735
1817
  if (isNew) {
1736
1818
  // The suppression is already stored; a webhook delivery hiccup must not fail (and thus
@@ -1744,7 +1826,7 @@ const init = async () => {
1744
1826
  userAgent: request.headers['user-agent']
1745
1827
  });
1746
1828
  } catch (err) {
1747
- request.logger.error({ msg: 'Failed to send one-click unsubscribe webhook', err });
1829
+ request.logger.error({ msg: 'Failed to send one-click unsubscribe webhook', account: data.acc, listId: data.list, err });
1748
1830
  }
1749
1831
  }
1750
1832
 
@@ -1816,14 +1898,20 @@ const init = async () => {
1816
1898
  throw err;
1817
1899
  }
1818
1900
 
1901
+ const notificationEntries = graphNotificationEntries(request.payload);
1902
+
1819
1903
  if (!accountData.outlookSubscription) {
1820
- request.logger.error({ msg: 'Subscription not found for account', account: request.query.account, payload: request.payload });
1904
+ request.logger.warn({
1905
+ msg: 'Subscription not found for account',
1906
+ account: request.query.account,
1907
+ subscriptionIds: notificationEntries.map(entry => entry.subscriptionId)
1908
+ });
1821
1909
  return h.response(Buffer.alloc(0)).code(202);
1822
1910
  }
1823
1911
 
1824
1912
  const outlookSubscription = accountData.outlookSubscription;
1825
1913
 
1826
- for (let entry of (request.payload && request.payload.value) || []) {
1914
+ for (let entry of notificationEntries) {
1827
1915
  // enumerate and queue all entries
1828
1916
  const subscriptionIdMatch = entry.subscriptionId === outlookSubscription.id;
1829
1917
  const clientStateMatch = constantTimeEqual(entry.clientState, outlookSubscription.clientState);
@@ -1910,8 +1998,14 @@ const init = async () => {
1910
1998
  throw err;
1911
1999
  }
1912
2000
 
2001
+ const lifecycleEntries = graphNotificationEntries(request.payload);
2002
+
1913
2003
  if (!accountData.outlookSubscription) {
1914
- request.logger.error({ msg: 'Subscription not found for account', account: request.query.account, payload: request.payload });
2004
+ request.logger.warn({
2005
+ msg: 'Subscription not found for account',
2006
+ account: request.query.account,
2007
+ subscriptionIds: lifecycleEntries.map(entry => entry.subscriptionId)
2008
+ });
1915
2009
  return h.response(Buffer.alloc(0)).code(202);
1916
2010
  }
1917
2011
 
@@ -1921,7 +2015,7 @@ const init = async () => {
1921
2015
  // concurrent handlers racing (e.g., two subscriptionRemoved entries)
1922
2016
  const seenLifecycleEvents = new Set();
1923
2017
 
1924
- for (let entry of (request.payload && request.payload.value) || []) {
2018
+ for (let entry of lifecycleEntries) {
1925
2019
  request.logger.debug({
1926
2020
  msg: 'MS Graph subscription event',
1927
2021
  type: 'lifecycle',
@@ -2145,7 +2239,7 @@ const init = async () => {
2145
2239
 
2146
2240
  // Best-effort revocation of the partial token
2147
2241
  oAuth2Client.revokeToken(r.refresh_token || r.access_token).catch(err => {
2148
- request.logger.error({ msg: 'Failed to revoke partial OAuth2 token', err });
2242
+ request.logger.warn({ msg: 'Failed to revoke partial OAuth2 token', err });
2149
2243
  });
2150
2244
 
2151
2245
  const retryUrl = await startOAuthRetry(accountData.email);
@@ -2174,7 +2268,7 @@ const init = async () => {
2174
2268
  // This works for all account types including send-only accounts
2175
2269
  const idTokenPayload = decodeJwtPayload(r.id_token);
2176
2270
  if (r.id_token && !idTokenPayload) {
2177
- request.logger.error({ msg: 'Failed to decode Gmail ID token' });
2271
+ request.logger.warn({ msg: 'Failed to decode Gmail ID token' });
2178
2272
  }
2179
2273
  if (idTokenPayload && typeof idTokenPayload.email === 'string' && isEmail(idTokenPayload.email)) {
2180
2274
  userEmail = idTokenPayload.email;
@@ -2194,13 +2288,13 @@ const init = async () => {
2194
2288
 
2195
2289
  if (hasProfileScope) {
2196
2290
  try {
2197
- request.logger.info({ msg: 'Attempting Gmail profile endpoint as fallback' });
2291
+ request.logger.debug({ msg: 'Attempting Gmail profile endpoint as fallback' });
2198
2292
  profileRes = await oAuth2Client.request(r.access_token, 'https://gmail.googleapis.com/gmail/v1/users/me/profile');
2199
2293
  if (profileRes && profileRes.emailAddress) {
2200
2294
  userEmail = profileRes.emailAddress;
2201
2295
  }
2202
2296
  } catch (err) {
2203
- request.logger.error({ msg: 'Failed to fetch user info from Gmail API', err: err.message });
2297
+ request.logger.error({ msg: 'Failed to fetch user info from Gmail API', err });
2204
2298
  let response = err.oauthRequest && err.oauthRequest.response;
2205
2299
  if (response && response.error) {
2206
2300
  let message;
@@ -2284,7 +2378,7 @@ const init = async () => {
2284
2378
 
2285
2379
  const idTokenPayload = decodeJwtPayload(r.id_token);
2286
2380
  if (r.id_token && !idTokenPayload) {
2287
- request.logger.error({ msg: 'Failed to decode JWT payload' });
2381
+ request.logger.warn({ msg: 'Failed to decode Outlook ID token' });
2288
2382
  }
2289
2383
 
2290
2384
  userInfo = resolveOutlookUserInfo({ clientInfo, idTokenPayload });
@@ -2309,8 +2403,7 @@ const init = async () => {
2309
2403
  request.logger.info({
2310
2404
  msg: 'User profile returned by MS Graph API',
2311
2405
  user: userInfo.email,
2312
- provider: oauth2App.provider,
2313
- profile: profileRes
2406
+ provider: oauth2App.provider
2314
2407
  });
2315
2408
  }
2316
2409
 
@@ -2448,7 +2541,7 @@ const init = async () => {
2448
2541
  try {
2449
2542
  await oAuth2Client.revokeToken(grantToken);
2450
2543
  } catch (err) {
2451
- request.logger.error({ msg: 'Failed to revoke the OAuth2 grant after an identity mismatch', err });
2544
+ request.logger.warn({ msg: 'Failed to revoke the OAuth2 grant after an identity mismatch', err });
2452
2545
  }
2453
2546
  }
2454
2547
 
@@ -2650,13 +2743,37 @@ const init = async () => {
2650
2743
  isCached: false,
2651
2744
 
2652
2745
  async context(request) {
2653
- const pendingMessages = await flash(redis, request);
2746
+ // The three reads are independent, and this runs on every admin page render. The
2747
+ // OAuth2 auth flags are best-effort - a failure to read them must not take the page
2748
+ // down with it.
2749
+ const [pendingMessages, settingsValues, oauthAuthFlags] = await Promise.all([
2750
+ flash(redis, request),
2751
+ settings.getMulti(
2752
+ 'upgrade',
2753
+ 'subexp',
2754
+ 'webhookErrorFlag',
2755
+ 'webhooksEnabled',
2756
+ 'disableTokens',
2757
+ 'tract',
2758
+ 'templateHeader',
2759
+ 'templateHtmlHead',
2760
+ 'documentStoreEnabled',
2761
+ 'serviceUrl',
2762
+ 'language',
2763
+ 'locale',
2764
+ 'timezone',
2765
+ 'pageBrandName',
2766
+ 'notificationBaseUrl'
2767
+ ),
2768
+ oauth2Apps.listAuthFlags().catch(err => {
2769
+ logger.error({ msg: 'Failed to list OAuth2 app auth flags', err });
2770
+ return [];
2771
+ })
2772
+ ]);
2773
+
2654
2774
  const {
2655
2775
  upgrade: upgradeInfo,
2656
2776
  subexp,
2657
- outlookAuthFlag,
2658
- gmailAuthFlag,
2659
- gmailServiceAuthFlag,
2660
2777
  webhookErrorFlag,
2661
2778
  webhooksEnabled,
2662
2779
  disableTokens,
@@ -2670,26 +2787,7 @@ const init = async () => {
2670
2787
  timezone,
2671
2788
  pageBrandName,
2672
2789
  notificationBaseUrl
2673
- } = await settings.getMulti(
2674
- 'upgrade',
2675
- 'subexp',
2676
- 'outlookAuthFlag',
2677
- 'gmailAuthFlag',
2678
- 'gmailServiceAuthFlag',
2679
- 'webhookErrorFlag',
2680
- 'webhooksEnabled',
2681
- 'disableTokens',
2682
- 'tract',
2683
- 'templateHeader',
2684
- 'templateHtmlHead',
2685
- 'documentStoreEnabled',
2686
- 'serviceUrl',
2687
- 'language',
2688
- 'locale',
2689
- 'timezone',
2690
- 'pageBrandName',
2691
- 'notificationBaseUrl'
2692
- );
2790
+ } = settingsValues;
2693
2791
 
2694
2792
  let systemAlerts = [];
2695
2793
  let authData;
@@ -2763,30 +2861,15 @@ const init = async () => {
2763
2861
  });
2764
2862
  }
2765
2863
 
2766
- if (outlookAuthFlag && outlookAuthFlag.message) {
2767
- systemAlerts.push({
2768
- url: outlookAuthFlag.url || '/admin/config/oauth/app/outlook',
2769
- level: 'danger',
2770
- icon: 'icon-[tabler--lock-open]',
2771
- message: outlookAuthFlag.message
2772
- });
2773
- }
2774
-
2775
- if (gmailAuthFlag && gmailAuthFlag.message) {
2776
- systemAlerts.push({
2777
- url: gmailAuthFlag.url || '/admin/config/oauth/app/gmail',
2778
- level: 'danger',
2779
- icon: 'icon-[tabler--lock-open]',
2780
- message: gmailAuthFlag.message
2781
- });
2782
- }
2783
-
2784
- if (gmailServiceAuthFlag && gmailServiceAuthFlag.message) {
2864
+ // OAuth2 apps whose token requests are being refused (setFlag() writes the failure
2865
+ // into app meta). Shown on every admin page: the accounts on such an app sit
2866
+ // disconnected until the operator acts, so the OAuth config page alone is not enough.
2867
+ for (let { app, authFlag } of oauthAuthFlags) {
2785
2868
  systemAlerts.push({
2786
- url: gmailServiceAuthFlag.url || '/admin/config/oauth/app/gmailService',
2869
+ url: authFlag.url || `/admin/config/oauth/app/${encodeURIComponent(app)}`,
2787
2870
  level: 'danger',
2788
2871
  icon: 'icon-[tabler--lock-open]',
2789
- message: gmailServiceAuthFlag.message
2872
+ message: authFlag.message
2790
2873
  });
2791
2874
  }
2792
2875
 
@@ -2948,7 +3031,7 @@ const init = async () => {
2948
3031
  return h.response(request.errorInfo).code(request.errorInfo.statusCode || 500);
2949
3032
  }
2950
3033
 
2951
- logger.error({ path: request.path, method: request.method, err: error });
3034
+ logger[isClientError(error) ? 'debug' : 'error']({ msg: 'Web request failed', path: request.path, method: request.method, err: error });
2952
3035
 
2953
3036
  return h
2954
3037
  .view('error', ctx, {
@@ -3096,7 +3179,7 @@ const init = async () => {
3096
3179
  await certHandler.acquireCert(serviceDomain);
3097
3180
  await call({ cmd: 'smtpReload' });
3098
3181
  } catch (err) {
3099
- logger.error({ err });
3182
+ logger.error({ msg: 'Failed to acquire TLS certificate', serviceDomain, err });
3100
3183
  } finally {
3101
3184
  try {
3102
3185
  await certHandler.setCertificateData(serviceDomain, { lastCheck: new Date() });
@@ -3114,7 +3197,7 @@ const init = async () => {
3114
3197
  // dynamic imports first, use a wrapper function or eslint parser will crash
3115
3198
  init()
3116
3199
  .then(() => {
3117
- logger.debug({
3200
+ logger.info({
3118
3201
  msg: 'Started API server thread',
3119
3202
  port: API_PORT,
3120
3203
  host: API_HOST,
@@ -3135,6 +3218,6 @@ init()
3135
3218
  }, 10 * 1000).unref();
3136
3219
  })
3137
3220
  .catch(err => {
3138
- logger.error({ msg: 'Failed to initialize API', err });
3221
+ logger.fatal({ msg: 'Failed to initialize API', err });
3139
3222
  logger.flush(() => process.exit(3));
3140
3223
  });