emailengine-app 2.78.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 (142) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +29 -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 +70 -35
  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 +397 -0
  24. package/lib/api-routes/route-helpers.js +223 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +30 -25
  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 +319 -33
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/auth-token.js +80 -8
  33. package/lib/consts.js +10 -0
  34. package/lib/db.js +20 -2
  35. package/lib/delivery-error.js +30 -1
  36. package/lib/email-client/base-client.js +27 -41
  37. package/lib/email-client/gmail-client.js +19 -10
  38. package/lib/email-client/imap/mailbox.js +23 -24
  39. package/lib/email-client/imap/subconnection.js +10 -7
  40. package/lib/email-client/imap/sync-operations.js +46 -46
  41. package/lib/email-client/imap-client.js +36 -26
  42. package/lib/email-client/message-builder.js +3 -3
  43. package/lib/email-client/notification-handler.js +1 -1
  44. package/lib/email-client/outlook/graph-api.js +10 -4
  45. package/lib/email-client/outlook-client.js +53 -54
  46. package/lib/email-client/smtp-pool-manager.js +1 -1
  47. package/lib/enum-descriptions.js +92 -2
  48. package/lib/export.js +1 -1
  49. package/lib/field-usage.js +133 -0
  50. package/lib/gateway.js +1 -1
  51. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  52. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  53. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  54. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  55. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  56. package/lib/imapproxy/imap-server.js +27 -7
  57. package/lib/license-beacon.js +4 -9
  58. package/lib/lists.js +49 -1
  59. package/lib/llm-pre-process.js +5 -5
  60. package/lib/logger.js +5 -1
  61. package/lib/metrics-collector.js +2 -2
  62. package/lib/oauth/gmail.js +9 -12
  63. package/lib/oauth/mail-ru.js +5 -7
  64. package/lib/oauth/outlook.js +9 -9
  65. package/lib/oauth/pubsub/google.js +25 -10
  66. package/lib/oauth/scope-checker.js +1 -1
  67. package/lib/oauth2-apps.js +223 -294
  68. package/lib/openapi/build-document.js +15 -7
  69. package/lib/openapi/joi-schema.js +20 -0
  70. package/lib/outbox.js +85 -17
  71. package/lib/pre-process.js +8 -8
  72. package/lib/queue-stats.js +49 -0
  73. package/lib/read-env-value.js +1 -1
  74. package/lib/reconnection-manager.js +2 -2
  75. package/lib/rewrite-text-nodes.js +4 -3
  76. package/lib/routes-ui.js +4 -0
  77. package/lib/schemas.js +216 -160
  78. package/lib/settings.js +84 -5
  79. package/lib/sub-script.js +2 -1
  80. package/lib/swagger-options.js +2 -1
  81. package/lib/templates.js +4 -4
  82. package/lib/threads.js +2 -2
  83. package/lib/token-audit-log.js +208 -0
  84. package/lib/token-permission-view.js +219 -0
  85. package/lib/token-permissions.js +172 -0
  86. package/lib/tokens.js +99 -15
  87. package/lib/tools.js +142 -37
  88. package/lib/ui-routes/account-routes.js +31 -11
  89. package/lib/ui-routes/admin-config-routes.js +18 -10
  90. package/lib/ui-routes/admin-entities-routes.js +66 -22
  91. package/lib/ui-routes/auth-routes.js +30 -24
  92. package/lib/ui-routes/export-routes.js +10 -4
  93. package/lib/ui-routes/oauth-config-routes.js +5 -5
  94. package/lib/ui-routes/reference-routes.js +3 -3
  95. package/lib/ui-routes/route-helpers.js +51 -2
  96. package/lib/ui-routes/settings-page.js +1 -1
  97. package/lib/ui-routes/smtp-test-routes.js +1 -1
  98. package/lib/ui-routes/suppression-list-routes.js +294 -0
  99. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  100. package/lib/utils/network.js +2 -2
  101. package/lib/web-safe-html.js +1 -1
  102. package/lib/webhook-routing.js +80 -0
  103. package/lib/webhooks.js +20 -14
  104. package/package.json +11 -10
  105. package/sbom.json +1 -1
  106. package/server.js +80 -41
  107. package/static/css/flyonui.css +1 -1
  108. package/static/css/src/app.tailwind.css +136 -9
  109. package/static/js/reference.js +456 -10
  110. package/static/js/ui.js +43 -0
  111. package/static/licenses.html +51 -41
  112. package/translations/messages.pot +59 -59
  113. package/views/accounts/account.hbs +69 -7
  114. package/views/accounts/browse.hbs +18 -35
  115. package/views/config/logging.hbs +6 -0
  116. package/views/config/oauth/app.hbs +0 -2
  117. package/views/config/security.hbs +13 -0
  118. package/views/partials/oauth_form.hbs +0 -15
  119. package/views/partials/reference/disclosure.hbs +8 -2
  120. package/views/partials/reference/operation.hbs +47 -13
  121. package/views/partials/reference/params.hbs +17 -1
  122. package/views/partials/reference/schema-node.hbs +110 -52
  123. package/views/partials/reference/schema-tools.hbs +25 -0
  124. package/views/partials/reference/try-it.hbs +84 -11
  125. package/views/partials/side_menu.hbs +1 -0
  126. package/views/partials/ui/checkbox.hbs +2 -2
  127. package/views/partials/ui/tabs.hbs +7 -1
  128. package/views/reference/token.hbs +4 -0
  129. package/views/suppression-lists/index.hbs +85 -0
  130. package/views/suppression-lists/list.hbs +87 -0
  131. package/views/templates/index.hbs +8 -2
  132. package/views/tokens/index.hbs +31 -4
  133. package/views/tokens/new.hbs +324 -2
  134. package/workers/api.js +146 -57
  135. package/workers/documents.js +46 -26
  136. package/workers/export.js +20 -8
  137. package/workers/imap-proxy.js +2 -2
  138. package/workers/imap.js +12 -6
  139. package/workers/smtp.js +13 -7
  140. package/workers/submit.js +40 -30
  141. package/workers/webhooks.js +59 -25
  142. 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
  }
@@ -485,13 +492,6 @@ const init = async () => {
485
492
 
486
493
  handlebars.registerHelper('ngettext', (msgid, plural, count) => util.format(gt.ngettext(msgid, plural, count), count));
487
494
 
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
495
  handlebars.registerHelper('equals', function (compareVal, baseVal, options) {
496
496
  if (baseVal === compareVal) {
497
497
  return options.fn(this);
@@ -912,9 +912,39 @@ const init = async () => {
912
912
  request.logger.setBindings({ tokenId: tokenData.id, tokenAccount: tokenData.account || null });
913
913
  }
914
914
 
915
+ const grant = routeGrant(request.route);
916
+
917
+ // This strategy runs before route validation, so `request.query` is whatever the client
918
+ // sent: a repeated `?account=` arrives as an array. Only a string can name an account,
919
+ // and this value is persisted into the audit log, so anything else is not one.
920
+ const queryAccount = request.query && typeof request.query.account === 'string' ? request.query.account : null;
921
+
922
+ // Shared by every audit entry below, so an allow and a deny describe the same request.
923
+ // Built before the first check that can refuse: a rejection is the strongest signal of
924
+ // credential misuse there is, and a trail that only held the calls that succeeded would
925
+ // be silent about exactly the ones worth looking at.
926
+ const auditEntry = {
927
+ tokenId: tokenData.id,
928
+ ip: request.app.ip,
929
+ method: request.route.method,
930
+ path: request.route.path,
931
+ action: grant.action,
932
+ group: grant.group,
933
+ // The account the REQUEST addressed, which is not always the one in the path: the
934
+ // routes that take it as a query argument are the ones a bound token gets refused
935
+ // on, and falling straight through to the token's own account recorded a
936
+ // cross-account attempt against the account it was entitled to reach - the opposite
937
+ // of what the entry exists to show. The token's account is still the answer for the
938
+ // routes that name no account at all.
939
+ //
940
+ // The refusals below log this field rather than re-deriving it, so the application
941
+ // log and the audit row cannot disagree about which account a denial concerned.
942
+ account: (request.params && request.params.account) || queryAccount || tokenData.account || null
943
+ };
944
+
915
945
  if (scope && tokenData.scopes && !tokenData.scopes.includes(scope) && !tokenData.scopes.includes('*')) {
916
946
  // failed scope validation
917
- logger.error({
947
+ logger.warn({
918
948
  msg: 'Trying to use invalid scope for a token',
919
949
  tokenAccount: tokenData.account,
920
950
  tokenId: tokenData.id,
@@ -922,11 +952,43 @@ const init = async () => {
922
952
  tokenScopes: tokenData.scopes
923
953
  });
924
954
 
955
+ tokenAuditLog.denied(auditEntry, 'scope');
956
+
925
957
  let error = Boom.forbidden('Unauthorized scope');
926
958
  error.output.payload.requestedScope = scope;
927
959
  throw error;
928
960
  }
929
961
 
962
+ // Narrowing below the scope. Runs after the scope check and before the account binding,
963
+ // so the order is: token resolved, scope, permissions, account, restrictions.
964
+ //
965
+ // Before the account switch on purpose - that switch reads the account from the query or
966
+ // from a Redis membership check for the three /v1/templates special cases, and none of
967
+ // that should happen for a request the permissions already refuse.
968
+ //
969
+ // Only subtracts: a token with no `permissions` field takes the allowed path, which is
970
+ // every token issued before this shipped.
971
+ const permissionCheck = tokenPermissions.check({ tokenData, operation: grant });
972
+ if (!permissionCheck.allowed) {
973
+ logger.warn({
974
+ msg: 'Token permissions do not allow this operation',
975
+ tokenAccount: tokenData.account,
976
+ tokenId: tokenData.id,
977
+ account: auditEntry.account,
978
+ reason: permissionCheck.reason,
979
+ required: permissionCheck.required
980
+ });
981
+
982
+ let error = Boom.forbidden('Unauthorized permission');
983
+ // Mirrors how the scope failure above attaches requestedScope: an agent that gets a
984
+ // 403 needs to know WHICH grant it lacked, not just that it lacked one.
985
+ // A refused call is the interesting record, so it is logged before the throw
986
+ tokenAuditLog.denied(auditEntry, permissionCheck.reason);
987
+
988
+ error.output.payload.requiredPermission = permissionCheck.required;
989
+ throw error;
990
+ }
991
+
930
992
  if (tokenData.account) {
931
993
  // account token
932
994
 
@@ -934,10 +996,19 @@ const init = async () => {
934
996
 
935
997
  // allow specific routes that have an account component but not in the URL params section
936
998
  switch (request.route.path) {
999
+ // The two listings that take the account as a query argument. `/v1/tokens` is
1000
+ // here because it replaced GET /v1/tokens/account/{account}, which carried the
1001
+ // account in the path and so reached a bound token's own tokens through the
1002
+ // default branch below - the replacement had nothing reading the argument, so
1003
+ // the capability disappeared with no alias and no error a caller could act on.
1004
+ // Both stay under the same rule as everything else: the argument has to name the
1005
+ // token's own account, and omitting it still refuses, because a bound credential
1006
+ // must not enumerate the instance.
937
1007
  case '/v1/templates':
1008
+ case '/v1/tokens':
938
1009
  switch (request.method) {
939
1010
  case 'get':
940
- accountIdSource = request.query && request.query.account;
1011
+ accountIdSource = queryAccount;
941
1012
  break;
942
1013
  }
943
1014
  break;
@@ -967,13 +1038,15 @@ const init = async () => {
967
1038
  }
968
1039
 
969
1040
  if (accountIdSource !== tokenData.account) {
970
- logger.error({
1041
+ logger.warn({
971
1042
  msg: 'Trying to use invalid account for a token',
972
1043
  tokenAccount: tokenData.account,
973
1044
  tokenId: tokenData.id,
974
- account: (request.params && request.params.account) || null
1045
+ account: auditEntry.account
975
1046
  });
976
1047
 
1048
+ tokenAuditLog.denied(auditEntry, 'account');
1049
+
977
1050
  let error = Boom.forbidden('Unauthorized account');
978
1051
  throw error;
979
1052
  }
@@ -981,15 +1054,17 @@ const init = async () => {
981
1054
 
982
1055
  if (tokenData.restrictions) {
983
1056
  if (tokenData.restrictions.addresses && !matchIp(request.app.ip, tokenData.restrictions.addresses)) {
984
- logger.error({
1057
+ logger.warn({
985
1058
  msg: 'Trying to use invalid IP for a token',
986
1059
  tokenAccount: tokenData.account,
987
1060
  tokenId: tokenData.id,
988
- account: (request.params && request.params.account) || null,
1061
+ account: auditEntry.account,
989
1062
  remoteAddress: request.app.ip,
990
1063
  addressAllowlist: tokenData.restrictions.addresses
991
1064
  });
992
1065
 
1066
+ tokenAuditLog.denied(auditEntry, 'address');
1067
+
993
1068
  let error = Boom.forbidden('Unauthorized address');
994
1069
  error.output.payload.remoteAddress = request.app.ip;
995
1070
  throw error;
@@ -1000,15 +1075,17 @@ const init = async () => {
1000
1075
  tokenData.restrictions.referrers.length &&
1001
1076
  !matcher(tokenData.restrictions.referrers, request.headers.referer)
1002
1077
  ) {
1003
- logger.error({
1078
+ logger.warn({
1004
1079
  msg: 'Trying to use invalid referer for a token',
1005
1080
  tokenAccount: tokenData.account,
1006
1081
  tokenId: tokenData.id,
1007
- account: (request.params && request.params.account) || null,
1082
+ account: auditEntry.account,
1008
1083
  referer: request.headers.referer,
1009
1084
  referrerAllowlist: tokenData.restrictions.referrers
1010
1085
  });
1011
1086
 
1087
+ tokenAuditLog.denied(auditEntry, 'referrer');
1088
+
1012
1089
  let error = Boom.forbidden('Unauthorized referrer');
1013
1090
  throw error;
1014
1091
  }
@@ -1022,7 +1099,9 @@ const init = async () => {
1022
1099
  );
1023
1100
 
1024
1101
  if (!rateLimit.success) {
1025
- logger.error({ msg: 'Rate limited', token: tokenData.id, rateLimit });
1102
+ logger.warn({ msg: 'Rate limited', token: tokenData.id, rateLimit });
1103
+ tokenAuditLog.denied(auditEntry, 'rateLimit');
1104
+
1026
1105
  let error = Boom.tooManyRequests('Rate limit exceeded');
1027
1106
  error.output.payload.ttl = Math.ceil(rateLimit.ttl);
1028
1107
  error.output.headers = {
@@ -1040,6 +1119,13 @@ const init = async () => {
1040
1119
  }
1041
1120
  }
1042
1121
 
1122
+ // The one point every accepted token request passes. "allowed" means the credential was
1123
+ // accepted, not that the request succeeded: this runs in the auth strategy, before
1124
+ // payload validation and the handler, so a call recorded here can still end in a 400 or
1125
+ // a 404. That is the right boundary for a credential trail - it answers what the token
1126
+ // was permitted to attempt.
1127
+ tokenAuditLog.allowed(auditEntry);
1128
+
1043
1129
  return { isValid: true, credentials: { token }, artifacts: tokenData };
1044
1130
  }
1045
1131
  });
@@ -1310,9 +1396,9 @@ const init = async () => {
1310
1396
  await server.register({
1311
1397
  plugin: hapiPino,
1312
1398
  options: {
1313
- instance: logger.child({ component: 'api' }, { redact: REDACTED_KEYS }),
1399
+ instance: logger.child({ component: 'api' }, { redact: consts.REDACTED_LOG_KEYS }),
1314
1400
  // Redact Authorization headers, see https://getpino.io/#/docs/redaction
1315
- redact: REDACTED_KEYS
1401
+ redact: consts.REDACTED_LOG_KEYS
1316
1402
  }
1317
1403
  });
1318
1404
 
@@ -1551,7 +1637,7 @@ const init = async () => {
1551
1637
  userAgent: request.headers['user-agent']
1552
1638
  });
1553
1639
  } else {
1554
- request.logger.info({
1640
+ request.logger.debug({
1555
1641
  msg: 'Detected automated request',
1556
1642
  account: data.acc,
1557
1643
  event: TRACK_CLICK_NOTIFY,
@@ -1615,7 +1701,7 @@ const init = async () => {
1615
1701
  userAgent: request.headers['user-agent']
1616
1702
  });
1617
1703
  } else {
1618
- request.logger.info({
1704
+ request.logger.debug({
1619
1705
  msg: 'Detected automated request',
1620
1706
  account: data.acc,
1621
1707
  event: TRACK_OPEN_NOTIFY,
@@ -1715,22 +1801,14 @@ const init = async () => {
1715
1801
 
1716
1802
  // Record the suppression. A transient backend failure here is intentionally NOT swallowed to
1717
1803
  // 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
- );
1804
+ let isNew = await lists.add(data.list, data.rcpt, {
1805
+ account: data.acc,
1806
+ source: 'one-click',
1807
+ reason: 'unsubscribe',
1808
+ messageId: data.msg,
1809
+ remoteAddress: request.app.ip,
1810
+ userAgent: request.headers['user-agent']
1811
+ });
1734
1812
 
1735
1813
  if (isNew) {
1736
1814
  // The suppression is already stored; a webhook delivery hiccup must not fail (and thus
@@ -1744,7 +1822,7 @@ const init = async () => {
1744
1822
  userAgent: request.headers['user-agent']
1745
1823
  });
1746
1824
  } catch (err) {
1747
- request.logger.error({ msg: 'Failed to send one-click unsubscribe webhook', err });
1825
+ request.logger.error({ msg: 'Failed to send one-click unsubscribe webhook', account: data.acc, listId: data.list, err });
1748
1826
  }
1749
1827
  }
1750
1828
 
@@ -1816,14 +1894,20 @@ const init = async () => {
1816
1894
  throw err;
1817
1895
  }
1818
1896
 
1897
+ const notificationEntries = graphNotificationEntries(request.payload);
1898
+
1819
1899
  if (!accountData.outlookSubscription) {
1820
- request.logger.error({ msg: 'Subscription not found for account', account: request.query.account, payload: request.payload });
1900
+ request.logger.warn({
1901
+ msg: 'Subscription not found for account',
1902
+ account: request.query.account,
1903
+ subscriptionIds: notificationEntries.map(entry => entry.subscriptionId)
1904
+ });
1821
1905
  return h.response(Buffer.alloc(0)).code(202);
1822
1906
  }
1823
1907
 
1824
1908
  const outlookSubscription = accountData.outlookSubscription;
1825
1909
 
1826
- for (let entry of (request.payload && request.payload.value) || []) {
1910
+ for (let entry of notificationEntries) {
1827
1911
  // enumerate and queue all entries
1828
1912
  const subscriptionIdMatch = entry.subscriptionId === outlookSubscription.id;
1829
1913
  const clientStateMatch = constantTimeEqual(entry.clientState, outlookSubscription.clientState);
@@ -1910,8 +1994,14 @@ const init = async () => {
1910
1994
  throw err;
1911
1995
  }
1912
1996
 
1997
+ const lifecycleEntries = graphNotificationEntries(request.payload);
1998
+
1913
1999
  if (!accountData.outlookSubscription) {
1914
- request.logger.error({ msg: 'Subscription not found for account', account: request.query.account, payload: request.payload });
2000
+ request.logger.warn({
2001
+ msg: 'Subscription not found for account',
2002
+ account: request.query.account,
2003
+ subscriptionIds: lifecycleEntries.map(entry => entry.subscriptionId)
2004
+ });
1915
2005
  return h.response(Buffer.alloc(0)).code(202);
1916
2006
  }
1917
2007
 
@@ -1921,7 +2011,7 @@ const init = async () => {
1921
2011
  // concurrent handlers racing (e.g., two subscriptionRemoved entries)
1922
2012
  const seenLifecycleEvents = new Set();
1923
2013
 
1924
- for (let entry of (request.payload && request.payload.value) || []) {
2014
+ for (let entry of lifecycleEntries) {
1925
2015
  request.logger.debug({
1926
2016
  msg: 'MS Graph subscription event',
1927
2017
  type: 'lifecycle',
@@ -2145,7 +2235,7 @@ const init = async () => {
2145
2235
 
2146
2236
  // Best-effort revocation of the partial token
2147
2237
  oAuth2Client.revokeToken(r.refresh_token || r.access_token).catch(err => {
2148
- request.logger.error({ msg: 'Failed to revoke partial OAuth2 token', err });
2238
+ request.logger.warn({ msg: 'Failed to revoke partial OAuth2 token', err });
2149
2239
  });
2150
2240
 
2151
2241
  const retryUrl = await startOAuthRetry(accountData.email);
@@ -2174,7 +2264,7 @@ const init = async () => {
2174
2264
  // This works for all account types including send-only accounts
2175
2265
  const idTokenPayload = decodeJwtPayload(r.id_token);
2176
2266
  if (r.id_token && !idTokenPayload) {
2177
- request.logger.error({ msg: 'Failed to decode Gmail ID token' });
2267
+ request.logger.warn({ msg: 'Failed to decode Gmail ID token' });
2178
2268
  }
2179
2269
  if (idTokenPayload && typeof idTokenPayload.email === 'string' && isEmail(idTokenPayload.email)) {
2180
2270
  userEmail = idTokenPayload.email;
@@ -2194,13 +2284,13 @@ const init = async () => {
2194
2284
 
2195
2285
  if (hasProfileScope) {
2196
2286
  try {
2197
- request.logger.info({ msg: 'Attempting Gmail profile endpoint as fallback' });
2287
+ request.logger.debug({ msg: 'Attempting Gmail profile endpoint as fallback' });
2198
2288
  profileRes = await oAuth2Client.request(r.access_token, 'https://gmail.googleapis.com/gmail/v1/users/me/profile');
2199
2289
  if (profileRes && profileRes.emailAddress) {
2200
2290
  userEmail = profileRes.emailAddress;
2201
2291
  }
2202
2292
  } catch (err) {
2203
- request.logger.error({ msg: 'Failed to fetch user info from Gmail API', err: err.message });
2293
+ request.logger.error({ msg: 'Failed to fetch user info from Gmail API', err });
2204
2294
  let response = err.oauthRequest && err.oauthRequest.response;
2205
2295
  if (response && response.error) {
2206
2296
  let message;
@@ -2284,7 +2374,7 @@ const init = async () => {
2284
2374
 
2285
2375
  const idTokenPayload = decodeJwtPayload(r.id_token);
2286
2376
  if (r.id_token && !idTokenPayload) {
2287
- request.logger.error({ msg: 'Failed to decode JWT payload' });
2377
+ request.logger.warn({ msg: 'Failed to decode Outlook ID token' });
2288
2378
  }
2289
2379
 
2290
2380
  userInfo = resolveOutlookUserInfo({ clientInfo, idTokenPayload });
@@ -2309,8 +2399,7 @@ const init = async () => {
2309
2399
  request.logger.info({
2310
2400
  msg: 'User profile returned by MS Graph API',
2311
2401
  user: userInfo.email,
2312
- provider: oauth2App.provider,
2313
- profile: profileRes
2402
+ provider: oauth2App.provider
2314
2403
  });
2315
2404
  }
2316
2405
 
@@ -2448,7 +2537,7 @@ const init = async () => {
2448
2537
  try {
2449
2538
  await oAuth2Client.revokeToken(grantToken);
2450
2539
  } catch (err) {
2451
- request.logger.error({ msg: 'Failed to revoke the OAuth2 grant after an identity mismatch', err });
2540
+ request.logger.warn({ msg: 'Failed to revoke the OAuth2 grant after an identity mismatch', err });
2452
2541
  }
2453
2542
  }
2454
2543
 
@@ -2948,7 +3037,7 @@ const init = async () => {
2948
3037
  return h.response(request.errorInfo).code(request.errorInfo.statusCode || 500);
2949
3038
  }
2950
3039
 
2951
- logger.error({ path: request.path, method: request.method, err: error });
3040
+ logger[isClientError(error) ? 'debug' : 'error']({ msg: 'Web request failed', path: request.path, method: request.method, err: error });
2952
3041
 
2953
3042
  return h
2954
3043
  .view('error', ctx, {
@@ -3096,7 +3185,7 @@ const init = async () => {
3096
3185
  await certHandler.acquireCert(serviceDomain);
3097
3186
  await call({ cmd: 'smtpReload' });
3098
3187
  } catch (err) {
3099
- logger.error({ err });
3188
+ logger.error({ msg: 'Failed to acquire TLS certificate', serviceDomain, err });
3100
3189
  } finally {
3101
3190
  try {
3102
3191
  await certHandler.setCertificateData(serviceDomain, { lastCheck: new Date() });
@@ -3114,7 +3203,7 @@ const init = async () => {
3114
3203
  // dynamic imports first, use a wrapper function or eslint parser will crash
3115
3204
  init()
3116
3205
  .then(() => {
3117
- logger.debug({
3206
+ logger.info({
3118
3207
  msg: 'Started API server thread',
3119
3208
  port: API_PORT,
3120
3209
  host: API_HOST,
@@ -3135,6 +3224,6 @@ init()
3135
3224
  }, 10 * 1000).unref();
3136
3225
  })
3137
3226
  .catch(err => {
3138
- logger.error({ msg: 'Failed to initialize API', err });
3227
+ logger.fatal({ msg: 'Failed to initialize API', err });
3139
3228
  logger.flush(() => process.exit(3));
3140
3229
  });
@@ -9,6 +9,7 @@ const settings = require('../lib/settings');
9
9
  const crypto = require('crypto');
10
10
 
11
11
  const { readEnvValue, threadStats, getDuration } = require('../lib/tools');
12
+ const { isFinalFailedAttempt } = require('../lib/delivery-error');
12
13
 
13
14
  const GB_COLLECT_DELAY = 6 * 3600 * 1000; // 6h
14
15
  const GB_FAILURE_DELAY = 3 * 1000;
@@ -189,7 +190,7 @@ const documentsWorker = new Worker(
189
190
  });
190
191
  deletedCount += deleteResult[indexName].deleted || 0;
191
192
  } catch (err) {
192
- logger.error({
193
+ logger.warn({
193
194
  msg: 'Failed to delete account emails from index',
194
195
  action: 'document',
195
196
  queue: job.queue.name,
@@ -254,7 +255,7 @@ const documentsWorker = new Worker(
254
255
  query: filterQuery
255
256
  });
256
257
  } catch (err) {
257
- logger.error({
258
+ logger.warn({
258
259
  msg: 'Failed to delete messages from a mailbox',
259
260
  action: 'document',
260
261
  queue: job.queue.name,
@@ -305,15 +306,15 @@ const documentsWorker = new Worker(
305
306
  .exec();
306
307
 
307
308
  if (err1) {
308
- logger.trace({ msg: 'Failed checking tombstone', key: tombstoneTdy, err: err1 });
309
+ logger.trace({ msg: 'Failed to check tombstone', key: tombstoneTdy, err: err1 });
309
310
  }
310
311
 
311
312
  if (err2) {
312
- logger.trace({ msg: 'Failed checking tombstone', key: tombstoneYdy, err: err2 });
313
+ logger.trace({ msg: 'Failed to check tombstone', key: tombstoneYdy, err: err2 });
313
314
  }
314
315
 
315
316
  if (isDeleted1 || isDeleted2) {
316
- logger.info({
317
+ logger.debug({
317
318
  msg: 'Skipped deleted email',
318
319
  action: 'document',
319
320
  queue: job.queue.name,
@@ -419,7 +420,7 @@ const documentsWorker = new Worker(
419
420
  throw new Error('Empty index response');
420
421
  }
421
422
  } catch (err) {
422
- logger.error({
423
+ logger.warn({
423
424
  msg: 'Failed to index new email',
424
425
  action: 'document',
425
426
  queue: job.queue.name,
@@ -428,7 +429,7 @@ const documentsWorker = new Worker(
428
429
  event: job.name,
429
430
  account: job.data.account,
430
431
  entryId: messageId,
431
- request: { index, id: `${job.data.account}:${messageId}`, document: messageData },
432
+ request: { index, id: `${job.data.account}:${messageId}` },
432
433
  err
433
434
  });
434
435
  throw err;
@@ -550,8 +551,9 @@ const documentsWorker = new Worker(
550
551
  });
551
552
  storedEmbeddings = false;
552
553
  } else {
553
- logger.info({
554
+ logger.debug({
554
555
  msg: 'Stored embeddings for a message',
556
+ account: job.data.account,
555
557
  messageId: messageData.messageId,
556
558
  items: bulkResponse.items?.length
557
559
  });
@@ -568,7 +570,7 @@ const documentsWorker = new Worker(
568
570
  }
569
571
  }
570
572
  } else {
571
- logger.info({ msg: 'Skipped embeddings, already exist', account: job.data.account, messageId: messageData.messageId });
573
+ logger.debug({ msg: 'Skipped embeddings, already exist', account: job.data.account, messageId: messageData.messageId });
572
574
  storedEmbeddings = false;
573
575
  }
574
576
  }
@@ -654,7 +656,7 @@ const documentsWorker = new Worker(
654
656
 
655
657
  break;
656
658
  default:
657
- logger.error({
659
+ logger.warn({
658
660
  msg: 'Failed to delete email',
659
661
  action: 'document',
660
662
  queue: job.queue.name,
@@ -753,7 +755,7 @@ ${Object.keys(params)
753
755
  updateResult = Object.assign({ failed: true }, err.meta.body);
754
756
  break;
755
757
  default:
756
- logger.error({
758
+ logger.warn({
757
759
  msg: 'Failed to update email',
758
760
  action: 'document',
759
761
  queue: job.queue.name,
@@ -856,7 +858,7 @@ if( ctx._source.bounces != null) {
856
858
  updateResult = Object.assign({ failed: true }, err.meta.body);
857
859
  break;
858
860
  default:
859
- logger.error({
861
+ logger.warn({
860
862
  msg: 'Failed to update email',
861
863
  action: 'document',
862
864
  queue: job.queue.name,
@@ -913,7 +915,7 @@ documentsWorker.on('completed', async job => {
913
915
  status: 'completed'
914
916
  });
915
917
 
916
- logger.info({
918
+ logger.debug({
917
919
  msg: 'Document queue entry completed',
918
920
  action: 'document',
919
921
  queue: job.queue.name,
@@ -923,19 +925,23 @@ documentsWorker.on('completed', async job => {
923
925
  });
924
926
  });
925
927
 
926
- documentsWorker.on('failed', async job => {
928
+ documentsWorker.on('failed', async (job, err) => {
927
929
  metrics(logger, 'queuesProcessed', 'inc', {
928
- queue: 'document',
930
+ queue: 'documents',
929
931
  status: 'failed'
930
932
  });
931
933
 
932
- logger.info({
934
+ let isFinal = isFinalFailedAttempt(job);
935
+
936
+ logger[isFinal ? 'error' : 'debug']({
933
937
  msg: 'Document queue entry failed',
934
938
  action: 'document',
935
939
  queue: job.queue.name,
936
940
  code: 'failed',
937
941
  job: job.id,
942
+ event: job.name,
938
943
  account: job.data.account,
944
+ err,
939
945
 
940
946
  failedReason: job.failedReason,
941
947
  stacktrace: job.stacktrace,
@@ -991,7 +997,12 @@ const clearExpungedEmbeddings = async () => {
991
997
 
992
998
  const { index, client } = await getESClient(logger);
993
999
  if (!client) {
994
- // Document store not enabled
1000
+ // Document store not enabled. Returning bare would spin, because the collector
1001
+ // re-invokes itself as soon as this resolves and the queue is not empty.
1002
+ await new Promise(resolve => {
1003
+ let timer = setTimeout(resolve, GB_EMPTY_DELAY);
1004
+ timer.unref();
1005
+ });
995
1006
  return;
996
1007
  }
997
1008
 
@@ -1005,12 +1016,6 @@ const clearExpungedEmbeddings = async () => {
1005
1016
  });
1006
1017
 
1007
1018
  if (!existingResult || !existingResult.hits) {
1008
- logger.error({
1009
- msg: 'Failed to run query to find emails by Message-ID. Empty result.',
1010
- account,
1011
- messageId,
1012
- existingResult
1013
- });
1014
1019
  throw new Error('Empty result');
1015
1020
  }
1016
1021
  } catch (err) {
@@ -1067,12 +1072,18 @@ const clearExpungedEmbeddings = async () => {
1067
1072
  messageId
1068
1073
  });
1069
1074
  } catch (err) {
1070
- logger.info({
1071
- msg: 'Dailed to delete embeddings for a missing email',
1075
+ // The zrem that retires this entry sits after the delete, so a failure
1076
+ // leaves it at the head of the queue. Push it back instead of retrying
1077
+ // straight away, otherwise a permanently failing entry (a missing
1078
+ // .embeddings index, say) blocks every other entry and re-logs on every
1079
+ // pass of the collector.
1080
+ logger.warn({
1081
+ msg: 'Failed to delete embeddings for a missing email',
1072
1082
  account,
1073
1083
  messageId,
1074
1084
  err
1075
1085
  });
1086
+ await redis.zadd(`${REDIS_PREFIX}expungequeue`, Date.now(), expungedEntry);
1076
1087
  }
1077
1088
  } else {
1078
1089
  // clear existing entry
@@ -1083,10 +1094,19 @@ const clearExpungedEmbeddings = async () => {
1083
1094
  messageId
1084
1095
  });
1085
1096
  }
1097
+ } else {
1098
+ // A member that does not split into both halves can never be processed. Retire it
1099
+ // rather than fall through, because the collector re-invokes itself immediately and
1100
+ // this entry would otherwise stay at the head of the queue and pin the loop.
1101
+ logger.warn({ msg: 'Removing malformed expunge queue entry', entry: expungedEntry });
1102
+ await redis.zrem(`${REDIS_PREFIX}expungequeue`, expungedEntry);
1086
1103
  }
1087
1104
  }
1088
1105
  } catch (err) {
1089
- logger.error({ msg: 'Failed to retrieve expunged entries', rangeStart: 0, rangeEnd, err });
1106
+ // The collector re-runs itself immediately, so this pass repeats every GB_FAILURE_DELAY for
1107
+ // as long as the failure lasts. Keep it visible: nothing else reports that embedding
1108
+ // cleanup has stopped making progress.
1109
+ logger.warn({ msg: 'Failed to retrieve expunged entries', rangeStart: 0, rangeEnd, err });
1090
1110
  await new Promise(resolve => {
1091
1111
  let timer = setTimeout(resolve, GB_FAILURE_DELAY);
1092
1112
  timer.unref();