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
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+
3
+ // Maximum size of the encoded payload segment we are willing to decode. Real id_tokens are a few
4
+ // hundred bytes of claims; anything larger is malformed or hostile, and the segment reaches us from a
5
+ // provider response we do not otherwise bound.
6
+ const MAX_PAYLOAD_LENGTH = 16 * 1024;
7
+
8
+ // Decode the claims of a JWT WITHOUT verifying its signature, returning null for anything that does not
9
+ // parse. Never throws - callers treat a null payload as "no claims available" and fall back.
10
+ //
11
+ // Not verifying is deliberate and only safe at the sites that use it: every caller obtained the token
12
+ // from the provider's token endpoint over a direct TLS back-channel POST (lib/oauth/*.js getToken), so
13
+ // authenticity comes from the transport, not from the token. The claims are trustworthy for that reason
14
+ // alone. Do NOT reuse this for a token that arrived through the browser or any other front channel -
15
+ // there the signature is the only thing standing between you and attacker-authored claims.
16
+ function decodeJwtPayload(token) {
17
+ if (!token || typeof token !== 'string') {
18
+ return null;
19
+ }
20
+
21
+ const [, encodedPayload] = token.split('.');
22
+ if (!encodedPayload || encodedPayload.length > MAX_PAYLOAD_LENGTH) {
23
+ return null;
24
+ }
25
+
26
+ try {
27
+ const payload = JSON.parse(Buffer.from(encodedPayload, 'base64url').toString());
28
+ // A JWT payload is a JSON object. Anything else (a bare string, a number, null, an array) is not
29
+ // a claims set, and returning it would hand callers a value that fails on property access.
30
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
31
+ return null;
32
+ }
33
+ return payload;
34
+ } catch (err) {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ module.exports = { decodeJwtPayload, MAX_PAYLOAD_LENGTH };
@@ -176,7 +176,7 @@ const formatFetchBody = (searchParams, logRaw) => {
176
176
  return data;
177
177
  }
178
178
 
179
- for (let key of ['refresh_token', 'client_secret']) {
179
+ for (let key of ['refresh_token', 'client_secret', 'code']) {
180
180
  if (data[key]) {
181
181
  data[key] = formatPartialSecretKey(data[key]);
182
182
  }
@@ -196,7 +196,7 @@ const formatFetchResponse = (responseObj, logRaw) => {
196
196
  }
197
197
 
198
198
  let data = structuredClone(responseObj);
199
- for (let key of ['access_token', 'refresh_token']) {
199
+ for (let key of ['access_token', 'refresh_token', 'id_token']) {
200
200
  if (data[key]) {
201
201
  data[key] = logRaw ? data[key] : formatPartialSecretKey(data[key]);
202
202
  }
@@ -379,7 +379,7 @@ class GmailOauth {
379
379
  responseJson = await res.json();
380
380
  } catch (err) {
381
381
  if (this.logger) {
382
- this.logger.error({ msg: 'Failed to retrieve JSON', err });
382
+ this.logger.error({ msg: 'Failed to parse JSON response', url: requestUrl, status: res.status, err });
383
383
  }
384
384
  }
385
385
 
@@ -413,7 +413,7 @@ class GmailOauth {
413
413
  googleProjectId: this.googleProjectId,
414
414
  serviceClientEmail: this.serviceClientEmail,
415
415
  scopes: this.scopes,
416
- code
416
+ code: formatPartialSecretKey(code)
417
417
  };
418
418
  try {
419
419
  err.tokenRequest.response = responseJson || { error: 'Failed to parse response' };
@@ -494,7 +494,7 @@ class GmailOauth {
494
494
  responseJson = await res.json();
495
495
  } catch (err) {
496
496
  if (this.logger) {
497
- this.logger.error({ msg: 'Failed to retrieve JSON', err });
497
+ this.logger.error({ msg: 'Failed to parse JSON response', url: requestUrl, status: res.status, err });
498
498
  }
499
499
  }
500
500
 
@@ -613,7 +613,6 @@ class GmailOauth {
613
613
  let err = new Error('OAuth2 request failed');
614
614
  err.statusCode = res.status;
615
615
  err.oauthRequest = {
616
- o: 1,
617
616
  url,
618
617
  method,
619
618
  provider: this.provider,
@@ -657,7 +656,7 @@ class GmailOauth {
657
656
  // ignore
658
657
  } finally {
659
658
  if (this.logger) {
660
- this.logger.error(Object.assign({ msg: 'API request failed' }, err.oauthRequest));
659
+ this.logger.warn(Object.assign({ msg: 'API request failed' }, err.oauthRequest));
661
660
  }
662
661
  }
663
662
 
@@ -665,11 +664,10 @@ class GmailOauth {
665
664
  }
666
665
 
667
666
  if (this.logger) {
668
- this.logger.info(
667
+ this.logger.debug(
669
668
  Object.assign(
670
669
  { msg: 'External API request completed' },
671
670
  {
672
- o: 2,
673
671
  url,
674
672
  method,
675
673
  provider: this.provider,
@@ -695,7 +693,6 @@ class GmailOauth {
695
693
  if (!['application/json', 'text/json'].includes(contentType)) {
696
694
  let error = new Error('Expected JSON response for OAuth2 request');
697
695
  error.oauthRequest = {
698
- o: 3,
699
696
  url,
700
697
  method,
701
698
  provider: this.provider,
@@ -717,7 +714,7 @@ class GmailOauth {
717
714
  }
718
715
 
719
716
  error.oauthRequest.response = {
720
- lentgh: responseText.length,
717
+ length: responseText.length,
721
718
  text: responseText.toString().substring(0, 5 * 1024)
722
719
  };
723
720
  throw error;
@@ -817,7 +814,7 @@ class GmailOauth {
817
814
  }
818
815
  } catch (err) {
819
816
  if (this.logger) {
820
- this.logger.error({ msg: 'OAuth2 token revocation error', err });
817
+ this.logger.warn({ msg: 'OAuth2 token revocation error', err });
821
818
  }
822
819
  }
823
820
  }
@@ -25,7 +25,7 @@ const formatFetchBody = (searchParams, logRaw) => {
25
25
  return data;
26
26
  }
27
27
 
28
- for (let key of ['refresh_token', 'client_secret']) {
28
+ for (let key of ['refresh_token', 'client_secret', 'code']) {
29
29
  if (data[key]) {
30
30
  data[key] = formatPartialSecretKey(data[key]);
31
31
  }
@@ -40,7 +40,7 @@ const formatFetchResponse = (responseObj, logRaw) => {
40
40
  }
41
41
 
42
42
  let data = structuredClone(responseObj);
43
- for (let key of ['access_token', 'refresh_token']) {
43
+ for (let key of ['access_token', 'refresh_token', 'id_token']) {
44
44
  if (data[key]) {
45
45
  data[key] = logRaw ? data[key] : formatPartialSecretKey(data[key]);
46
46
  }
@@ -125,7 +125,7 @@ class MailRuOauth {
125
125
  responseJson = await res.json();
126
126
  } catch (err) {
127
127
  if (this.logger) {
128
- this.logger.error({ msg: 'Failed to retrieve JSON', err });
128
+ this.logger.error({ msg: 'Failed to parse JSON response', url: requestUrl, status: res.status, err });
129
129
  }
130
130
  }
131
131
 
@@ -150,13 +150,12 @@ class MailRuOauth {
150
150
  err.tokenRequest = {
151
151
  url: requestUrl,
152
152
  method,
153
- authority: this.authority,
154
153
  grant: 'authorization_code',
155
154
  provider: this.provider,
156
155
  status: res.status,
157
156
  clientId: this.clientId,
158
157
  scopes: this.scopes,
159
- code
158
+ code: formatPartialSecretKey(code)
160
159
  };
161
160
  try {
162
161
  err.tokenRequest.response = responseJson || { error: 'Failed to parse response' };
@@ -210,7 +209,7 @@ class MailRuOauth {
210
209
  responseJson = await res.json();
211
210
  } catch (err) {
212
211
  if (this.logger) {
213
- this.logger.error({ msg: 'Failed to retrieve JSON', err });
212
+ this.logger.error({ msg: 'Failed to parse JSON response', url: requestUrl, status: res.status, err });
214
213
  }
215
214
  }
216
215
 
@@ -235,7 +234,6 @@ class MailRuOauth {
235
234
  err.tokenRequest = {
236
235
  url: requestUrl,
237
236
  method,
238
- authority: this.authority,
239
237
  grant: 'refresh_token',
240
238
  provider: this.provider,
241
239
  status: res.status,
@@ -0,0 +1,61 @@
1
+ 'use strict';
2
+
3
+ const { isEmail } = require('../utils/is-email');
4
+
5
+ // Resolves the Microsoft account identity from the sources the OAuth2 callback can have. Split out of
6
+ // workers/api.js because this is a TRUST BOUNDARY, and a trust boundary that exists only as an ordering
7
+ // of assignments inside a 300-line switch is one nobody can test or review.
8
+ //
9
+ // The sources are not equal:
10
+ //
11
+ // clientInfo - Microsoft's `client_info` blob. EmailEngine asks for it (lib/oauth/outlook.js sets
12
+ // client_info=1) and it comes back as a query parameter on the FRONT channel, i.e.
13
+ // through the user's browser. It is not signed and nothing verifies it, so whoever
14
+ // drives the callback URL chooses its contents.
15
+ // idTokenPayload - claims from the id_token returned by the token endpoint. Unverified as a token, but
16
+ // fetched over a direct TLS POST (see lib/oauth/decode-jwt-payload.js).
17
+ // profile - the MS Graph /v1.0/me response, also a back-channel request.
18
+ //
19
+ // Callers pass only the sources their branch actually has: the legacy IMAP-scope branch has clientInfo
20
+ // and the id_token, the Graph branch has the profile.
21
+ //
22
+ // `verifiedIdentities` therefore NEVER contains a clientInfo value. It is the only field callers may use
23
+ // to decide whether an authenticated identity satisfies an expected identity. Both the mailbox address
24
+ // and the user principal name are offered, because either can be the stable identity for a tenant and
25
+ // they routinely differ (user@contoso.com vs user@contoso.onmicrosoft.com).
26
+ //
27
+ // `email` prefers a verified value and falls back to clientInfo only when no back-channel source produced
28
+ // one. That fallback exists for OAuth2 apps predating the User.Read scope; it is rarely reached now, since
29
+ // the id_token carries preferred_username whenever `openid profile` is granted. The precedence matters
30
+ // beyond the identity check: accountData.email is persisted, shown in the admin UI, and used as the
31
+ // default From address, so a spoofable value winning there is a bug in its own right.
32
+ //
33
+ // `username` is the credential EmailEngine authenticates with (XOAUTH2), so it is verified-only with no
34
+ // clientInfo fallback. The profile's userPrincipalName is taken as-is rather than filtered as an address,
35
+ // matching the previous behavior - a tenant whose UPN is not email-shaped must still be able to log in.
36
+ function resolveOutlookUserInfo(sources) {
37
+ const { clientInfo, idTokenPayload, profile } = sources || {};
38
+
39
+ // isEmail already rejects non-strings, so these only normalize a miss to null.
40
+ const asEmail = value => isEmail(value) || null;
41
+ const asString = value => (typeof value === 'string' && value ? value : null);
42
+
43
+ const profileUpn = asString(profile && profile.userPrincipalName);
44
+ const idTokenUpn = asEmail(idTokenPayload && idTokenPayload.preferred_username);
45
+
46
+ // One list in preference order does both jobs: membership answers "did the provider return this
47
+ // address", and the first entry is the best address to show. Keeping two orderings in sync by hand
48
+ // would be a silent bug the moment they drifted.
49
+ const verifiedIdentities = [
50
+ ...new Set([asEmail(profile && profile.mail), asEmail(idTokenPayload && idTokenPayload.email), idTokenUpn, asEmail(profileUpn)].filter(Boolean))
51
+ ];
52
+
53
+ return {
54
+ name: asString(idTokenPayload && idTokenPayload.name) || asString(profile && profile.displayName) || asString(clientInfo && clientInfo.name),
55
+ email: verifiedIdentities[0] || asEmail(clientInfo && clientInfo.preferred_username),
56
+ username: idTokenUpn || profileUpn,
57
+ verifiedIdentities
58
+ };
59
+ }
60
+
61
+ module.exports = { resolveOutlookUserInfo };
@@ -134,7 +134,7 @@ const formatFetchBody = (searchParams, logRaw) => {
134
134
  return data;
135
135
  }
136
136
 
137
- for (let key of ['refresh_token', 'client_secret']) {
137
+ for (let key of ['refresh_token', 'client_secret', 'code']) {
138
138
  if (data[key]) {
139
139
  data[key] = formatPartialSecretKey(data[key]);
140
140
  }
@@ -149,7 +149,7 @@ const formatFetchResponse = (responseObj, logRaw) => {
149
149
  }
150
150
 
151
151
  let data = structuredClone(responseObj);
152
- for (let key of ['access_token', 'refresh_token']) {
152
+ for (let key of ['access_token', 'refresh_token', 'id_token']) {
153
153
  if (data[key]) {
154
154
  data[key] = logRaw ? data[key] : formatPartialSecretKey(data[key]);
155
155
  }
@@ -284,7 +284,7 @@ class OutlookOauth {
284
284
  responseJson = await res.json();
285
285
  } catch (err) {
286
286
  if (this.logger) {
287
- this.logger.error({ msg: 'Failed to retrieve JSON', err });
287
+ this.logger.error({ msg: 'Failed to parse JSON response', url: requestUrl, status: res.status, err });
288
288
  }
289
289
  }
290
290
 
@@ -316,7 +316,7 @@ class OutlookOauth {
316
316
  status: res.status,
317
317
  clientId: this.clientId,
318
318
  scopes: this.scopes,
319
- code
319
+ code: formatPartialSecretKey(code)
320
320
  };
321
321
  try {
322
322
  err.tokenRequest.response = responseJson || { error: 'Failed to parse response' };
@@ -385,7 +385,7 @@ class OutlookOauth {
385
385
  responseJson = await res.json();
386
386
  } catch (err) {
387
387
  if (this.logger) {
388
- this.logger.error({ msg: 'Failed to retrieve JSON', err });
388
+ this.logger.error({ msg: 'Failed to parse JSON response', url: requestUrl, status: res.status, err });
389
389
  }
390
390
  }
391
391
 
@@ -476,7 +476,7 @@ class OutlookOauth {
476
476
  responseJson = await res.json();
477
477
  } catch (err) {
478
478
  if (this.logger) {
479
- this.logger.error({ msg: 'Failed to retrieve JSON', err });
479
+ this.logger.error({ msg: 'Failed to parse JSON response', url: requestUrl, status: res.status, err });
480
480
  }
481
481
  }
482
482
 
@@ -623,14 +623,14 @@ class OutlookOauth {
623
623
  // ignore
624
624
  } finally {
625
625
  if (this.logger) {
626
- this.logger.error(Object.assign({ msg: 'API request failed' }, err.oauthRequest));
626
+ this.logger.warn(Object.assign({ msg: 'API request failed' }, err.oauthRequest));
627
627
  }
628
628
  }
629
629
  throw err;
630
630
  }
631
631
 
632
632
  if (this.logger) {
633
- this.logger.info(
633
+ this.logger.debug(
634
634
  Object.assign(
635
635
  { msg: 'External API request completed' },
636
636
  {
@@ -691,7 +691,7 @@ class OutlookOauth {
691
691
  responseEnd: responseText.length > 200 ? responseText.slice(-200) : undefined
692
692
  };
693
693
  if (this.logger) {
694
- this.logger.error(Object.assign({ msg: 'API returned invalid JSON' }, err.oauthRequest, { parseError: parseErr.message }));
694
+ this.logger.error(Object.assign({ msg: 'API returned invalid JSON' }, err.oauthRequest, { err: parseErr }));
695
695
  }
696
696
  throw err;
697
697
  }
@@ -31,7 +31,7 @@ class PubSubInstance {
31
31
 
32
32
  this.checkSchemaVersions()
33
33
  .catch(err => {
34
- logger.error({ msg: 'Failed to process schema versions', err });
34
+ logger.error({ msg: 'Failed to process schema versions', app: this.app, err });
35
35
  })
36
36
  .finally(() => {
37
37
  if (!this.stopped) {
@@ -70,7 +70,12 @@ class PubSubInstance {
70
70
  }
71
71
  let errKey = [err.message, err.code, err.statusCode].filter(val => val).join('|');
72
72
  if (this._lastLoopError !== errKey) {
73
- logger.error({ msg: 'Failed to process subscription loop', app: this.app, err });
73
+ if (err.eeLogged) {
74
+ // already logged with full context where it happened; keep only a trace of the loop retry
75
+ logger.debug({ msg: 'Failed to process subscription loop', app: this.app, err });
76
+ } else {
77
+ logger.error({ msg: 'Failed to process subscription loop', app: this.app, err });
78
+ }
74
79
  this._lastLoopError = errKey;
75
80
 
76
81
  this._setPubSubFlag({
@@ -100,29 +105,35 @@ class PubSubInstance {
100
105
  // normalization passed
101
106
  await redis.hset(`${REDIS_PREFIX}oapp:h:${subscriberApp}`, '__schemaVersion', currentSchemaId.toString(10));
102
107
 
103
- logger.info({ msg: 'Normalized hash keys', source: 'google', app: subscriberApp, schemaVersion, currentSchemaId, normalizationResults });
108
+ logger.info({ msg: 'Normalized hash keys', app: subscriberApp, schemaVersion, currentSchemaId, normalizationResults });
104
109
  } catch (err) {
105
- logger.error({ msg: 'Failed to normalize hash keys', source: 'google', app: subscriberApp, schemaVersion, currentSchemaId, err });
110
+ logger.error({ msg: 'Failed to normalize hash keys', app: subscriberApp, schemaVersion, currentSchemaId, err });
106
111
  }
107
112
  }
108
113
  }
109
114
  }
110
115
 
111
116
  async processPulledMessage(messageId, data) {
112
- logger.debug({ msg: 'Processing subscription message', source: 'google', app: this.app, messageId, data });
117
+ logger.debug({ msg: 'Processing subscription message', app: this.app, messageId, data });
113
118
 
114
119
  let payload;
115
120
  try {
116
121
  payload = JSON.parse(data);
117
122
  } catch (err) {
118
- logger.error({ msg: 'Failed to process subscription message', source: 'google', app: this.app, messageId, data, err });
123
+ logger.error({
124
+ msg: 'Failed to process subscription message',
125
+ app: this.app,
126
+ messageId,
127
+ dataLength: (data || '').length,
128
+ dataPreview: (data || '').toString().slice(0, 256),
129
+ err
130
+ });
119
131
  return;
120
132
  }
121
133
 
122
134
  if (!payload?.emailAddress || !payload?.historyId) {
123
135
  logger.warn({
124
136
  msg: 'Ignoring Pub/Sub message with missing required fields',
125
- source: 'google',
126
137
  app: this.app,
127
138
  messageId,
128
139
  hasPayload: !!payload,
@@ -142,7 +153,7 @@ class PubSubInstance {
142
153
  }
143
154
 
144
155
  if (!accountIds.size) {
145
- logger.info({ msg: 'Failed to match email address with account ID', app: this.app, subscriberApps, messageId, emailAddress: payload.emailAddress });
156
+ logger.debug({ msg: 'No account matched for Pub/Sub notification', app: this.app, subscriberApps, messageId, emailAddress: payload.emailAddress });
146
157
  return;
147
158
  }
148
159
 
@@ -172,7 +183,7 @@ class PubSubInstance {
172
183
 
173
184
  let accessToken = await this.getAccessToken();
174
185
  if (!accessToken) {
175
- logger.error({ msg: 'Failed to retrieve access token', app: this.app });
186
+ // not logged here: the thrown error is logged by the startLoop catch
176
187
  throw new Error('Failed to retrieve access token');
177
188
  }
178
189
 
@@ -205,7 +216,6 @@ class PubSubInstance {
205
216
 
206
217
  logger.debug({
207
218
  msg: 'Pulled subscription messages',
208
- source: 'google',
209
219
  app: this.app,
210
220
  messages: pullRes?.receivedMessages?.length || 0,
211
221
  reqTime
@@ -282,6 +292,7 @@ class PubSubInstance {
282
292
  if (TRANSIENT_NETWORK_CODES.has(err.code)) {
283
293
  logger.warn({ msg: 'Transient error pulling subscription messages', app: this.app, code: err.code });
284
294
  err.retryDelay = 5000;
295
+ err.eeLogged = true;
285
296
  throw err;
286
297
  }
287
298
  // Rate limited by Google API - respect Retry-After header
@@ -289,6 +300,7 @@ class PubSubInstance {
289
300
  let retryDelay = (err.retryAfter ? err.retryAfter * 1000 : null) || 30000;
290
301
  logger.warn({ msg: 'Rate limited by Google Pub/Sub API', app: this.app, retryAfterSec: err.retryAfter });
291
302
  err.retryDelay = retryDelay;
303
+ err.eeLogged = true;
292
304
  throw err;
293
305
  }
294
306
  // Detect deleted subscription (expired after 31 days of inactivity) and try to recreate
@@ -307,6 +319,7 @@ class PubSubInstance {
307
319
  statusCode: err.statusCode,
308
320
  err
309
321
  });
322
+ err.eeLogged = true;
310
323
  if (!this._pubSubFlagSetThisSession) {
311
324
  await this._setPubSubFlag({
312
325
  message:
@@ -320,6 +333,7 @@ class PubSubInstance {
320
333
  }
321
334
 
322
335
  logger.error({ msg: 'Failed to pull subscription messages', app: this.app, err });
336
+ err.eeLogged = true;
323
337
  throw err;
324
338
  }
325
339
  }
@@ -354,6 +368,7 @@ class PubSubInstance {
354
368
  logger.info({ msg: 'Successfully recovered Pub/Sub subscription', app: this.app, reason });
355
369
  } catch (recoveryErr) {
356
370
  logger.warn({ msg: 'Subscription recovery failed', app: this.app, reason, err: recoveryErr });
371
+ recoveryErr.eeLogged = true;
357
372
  throw recoveryErr;
358
373
  }
359
374
  }
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+
3
+ // Builds the pending-setup record for a retry after an OAuth2 attempt the user can correct themselves -
4
+ // a consent screen with permissions unchecked, or signing in as an account the setup link is not pinned
5
+ // to. The retry is a fresh single-use setup, so it needs a record of its own.
6
+ //
7
+ // The subtlety is which parts of the rejected attempt to carry over. By the time either failure is
8
+ // detected, the provider branches have already rewritten accountData from whoever actually signed in:
9
+ // `email` holds the authenticated address, `name` may hold their display name, and `oauth2` holds their
10
+ // tokens. Copying that wholesale would let a rejected identity leak into the account the retry creates,
11
+ // while rebuilding from scratch would drop what the caller actually asked for.
12
+ //
13
+ // So the tokens go, and the caller's own intent comes back:
14
+ //
15
+ // oauth2.auth.delegatedUser - names the MAILBOX TO BIND, not a credential. Dropping it silently turns a
16
+ // shared-mailbox setup into a personal one, so the retry would bind the
17
+ // principal's own mailbox while reporting success.
18
+ // email - for a delegated setup this is the shared mailbox, and both delegation
19
+ // paths in the Outlook branch key on it. Overwriting it with the address
20
+ // the user is being steered towards breaks them.
21
+ // name - filled in from the signed-in profile when the caller supplied none, and
22
+ // kept by `name || profile.name` on the retry, so the rejected user's
23
+ // display name would stick to the account and become its From name.
24
+ //
25
+ // `_meta` rides along unchanged: it carries the redirect URL, the expected identity and the single-use
26
+ // form nonce, which is claimed only on success and so is still unspent here.
27
+ function buildRetrySetup(accountData, requestedSetup, provider, accountMeta) {
28
+ const { email, name, delegatedUser } = requestedSetup || {};
29
+
30
+ return Object.assign({}, accountData, {
31
+ oauth2: delegatedUser ? { provider, auth: { delegatedUser } } : { provider },
32
+ email,
33
+ name,
34
+ _meta: accountMeta
35
+ });
36
+ }
37
+
38
+ module.exports = { buildRetrySetup };
@@ -74,7 +74,7 @@ function normalizeMsGraphScope(scope, logger) {
74
74
  logger.warn({
75
75
  msg: 'Failed to parse MS Graph scope URL',
76
76
  scope,
77
- err: err.message
77
+ err
78
78
  });
79
79
  }
80
80
  }