emailengine-app 2.81.2 → 2.82.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 (226) hide show
  1. package/.ncurc.js +33 -10
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +71 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/Dockerfile +2 -0
  6. package/bin/emailengine.js +105 -25
  7. package/config/default.toml +0 -5
  8. package/config/test.toml +0 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +70 -42
  11. package/getswagger.sh +0 -4
  12. package/lib/account/account-state.js +2 -110
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +138 -1
  15. package/lib/account.js +289 -869
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-binding.js +58 -0
  19. package/lib/api-routes/account-routes.js +65 -37
  20. package/lib/api-routes/behavior-notes.js +4 -0
  21. package/lib/api-routes/blocklist-routes.js +2 -2
  22. package/lib/api-routes/bull-board-routes.js +1 -6
  23. package/lib/api-routes/export-routes.js +2 -22
  24. package/lib/api-routes/gateway-routes.js +15 -16
  25. package/lib/api-routes/index.js +1 -13
  26. package/lib/api-routes/mailbox-routes.js +2 -7
  27. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  28. package/lib/api-routes/mcp-routes.js +7 -7
  29. package/lib/api-routes/message-routes.js +50 -238
  30. package/lib/api-routes/mint-bounds.js +110 -0
  31. package/lib/api-routes/oauth2-app-routes.js +23 -32
  32. package/lib/api-routes/operation-impact.js +1 -1
  33. package/lib/api-routes/outbox-routes.js +3 -3
  34. package/lib/api-routes/permission-map.js +1 -7
  35. package/lib/api-routes/route-helpers.js +11 -5
  36. package/lib/api-routes/settings-routes.js +20 -21
  37. package/lib/api-routes/stats-routes.js +1 -1
  38. package/lib/api-routes/submit-routes.js +17 -18
  39. package/lib/api-routes/template-routes.js +4 -9
  40. package/lib/api-routes/token-routes.js +28 -6
  41. package/lib/api-token-scheme.js +71 -0
  42. package/lib/arf-detect.js +33 -6
  43. package/lib/auth-token.js +44 -24
  44. package/lib/autodetect-imap-settings.js +305 -123
  45. package/lib/bounce-detect.js +25 -16
  46. package/lib/calendar-event.js +78 -0
  47. package/lib/consts.js +54 -5
  48. package/lib/create-imap-client.js +24 -0
  49. package/lib/db.js +77 -30
  50. package/lib/delivery-error.js +70 -2
  51. package/lib/egress-fetch.js +54 -3
  52. package/lib/egress-filter.js +11 -0
  53. package/lib/email-client/api-retry.js +147 -0
  54. package/lib/email-client/base-client.js +383 -536
  55. package/lib/email-client/credential-errors.js +21 -5
  56. package/lib/email-client/gmail/gmail-api.js +38 -125
  57. package/lib/email-client/gmail/send-request.js +1 -1
  58. package/lib/email-client/gmail-client.js +77 -51
  59. package/lib/email-client/imap/mailbox.js +158 -324
  60. package/lib/email-client/imap/stale-view.js +109 -0
  61. package/lib/email-client/imap/subconnection.js +46 -9
  62. package/lib/email-client/imap/sync-operations.js +5 -37
  63. package/lib/email-client/imap-client.js +190 -65
  64. package/lib/email-client/message-builder.js +50 -25
  65. package/lib/email-client/notification-handler.js +5 -219
  66. package/lib/email-client/outlook/graph-api.js +147 -126
  67. package/lib/email-client/outlook/send-request.js +10 -4
  68. package/lib/email-client/outlook-client.js +389 -463
  69. package/lib/email-client/smtp-pool-manager.js +3 -2
  70. package/lib/encrypt.js +184 -19
  71. package/lib/enum-descriptions.js +6 -3
  72. package/lib/export.js +141 -41
  73. package/lib/gateway.js +25 -6
  74. package/lib/get-raw-email.js +26 -44
  75. package/lib/get-secret.js +1 -21
  76. package/lib/handlebars-helpers.js +31 -10
  77. package/lib/imap-proxy-auth.js +13 -29
  78. package/lib/imapproxy/imap-core/README.md +1 -0
  79. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  80. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  81. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  82. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  83. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  84. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  85. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  86. package/lib/imapproxy/imap-server.js +17 -177
  87. package/lib/imapproxy/proxy-handoff.js +235 -0
  88. package/lib/imapproxy/response-error.js +33 -0
  89. package/lib/imapproxy/upstream-client.js +2 -2
  90. package/lib/license-beacon.js +3 -9
  91. package/lib/llm-pre-process.js +182 -43
  92. package/lib/logger.js +1 -1
  93. package/lib/lua/ee-export-queue-add.lua +39 -0
  94. package/lib/lua/ee-get-idempotency.lua +15 -3
  95. package/lib/lua/ee-release-attempts.lua +23 -0
  96. package/lib/lua/ee-reserve-attempts.lua +42 -0
  97. package/lib/lua/h-set-bigger.lua +12 -2
  98. package/lib/lua/s-list-accounts.lua +6 -3
  99. package/lib/mcp/index.js +1 -2
  100. package/lib/mcp/listen.js +221 -18
  101. package/lib/mcp/oauth.js +44 -5
  102. package/lib/mcp/resources.js +8 -2
  103. package/lib/mcp/tools.js +108 -36
  104. package/lib/message-port-stream.js +64 -6
  105. package/lib/oauth/external-account-signer.js +16 -13
  106. package/lib/oauth/gmail.js +64 -32
  107. package/lib/oauth/mail-ru.js +24 -17
  108. package/lib/oauth/outlook.js +53 -40
  109. package/lib/oauth/pubsub/google.js +38 -2
  110. package/lib/oauth/scope-checker.js +39 -8
  111. package/lib/oauth/scope-list.js +55 -0
  112. package/lib/oauth/token-fetch.js +47 -0
  113. package/lib/oauth/verify-app.js +2 -2
  114. package/lib/oauth2-apps.js +154 -90
  115. package/lib/openapi/build-document.js +1 -1
  116. package/lib/openapi/joi-schema.js +78 -9
  117. package/lib/outbox.js +2 -7
  118. package/lib/parse-message.js +21 -0
  119. package/lib/payload-examples-webhooks.json +4 -7
  120. package/lib/pbkdf2-phc.js +101 -0
  121. package/lib/privileged-settings.js +0 -14
  122. package/lib/queue-retention.js +4 -2
  123. package/lib/rate-limit.js +54 -15
  124. package/lib/read-env-value.js +33 -2
  125. package/lib/redis-scan-delete.js +56 -29
  126. package/lib/redis-url.js +3 -1
  127. package/lib/respawn-backoff.js +5 -4
  128. package/lib/response-stream.js +25 -4
  129. package/lib/rewrite-text-nodes.js +27 -40
  130. package/lib/routes-ui.js +0 -5
  131. package/lib/schemas.js +180 -253
  132. package/lib/sentry.js +21 -5
  133. package/lib/settings.js +58 -59
  134. package/lib/smtp-auth.js +6 -2
  135. package/lib/smtp-message-processor.js +28 -7
  136. package/lib/sso.js +7 -3
  137. package/lib/stream-encrypt.js +14 -13
  138. package/lib/swagger-options.js +3 -1
  139. package/lib/tls/provision.js +69 -3
  140. package/lib/tls/store.js +14 -1
  141. package/lib/token-audit-log.js +3 -2
  142. package/lib/tools.js +114 -53
  143. package/lib/totp.js +16 -1
  144. package/lib/ui-routes/account-routes.js +67 -70
  145. package/lib/ui-routes/admin-config-routes.js +111 -134
  146. package/lib/ui-routes/admin-entities-routes.js +101 -191
  147. package/lib/ui-routes/ai-options.js +104 -0
  148. package/lib/ui-routes/auth-routes.js +98 -18
  149. package/lib/ui-routes/export-routes.js +3 -23
  150. package/lib/ui-routes/internals-routes.js +12 -9
  151. package/lib/ui-routes/network-config-routes.js +8 -18
  152. package/lib/ui-routes/oauth-config-routes.js +83 -228
  153. package/lib/ui-routes/route-helpers.js +63 -67
  154. package/lib/ui-routes/special-use-paths.js +33 -0
  155. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  156. package/lib/utils/decode-headers.js +32 -5
  157. package/lib/utils/header-map.js +62 -1
  158. package/lib/utils/network.js +11 -17
  159. package/lib/web-safe-html.js +77 -4
  160. package/lib/webhook-request.js +9 -1
  161. package/lib/webhook-routing.js +27 -1
  162. package/lib/webhooks.js +120 -43
  163. package/lib/worker-rpc-error.js +43 -2
  164. package/list-generate.js +13 -2
  165. package/package.json +38 -46
  166. package/sbom.json +1 -1
  167. package/scripts/refresh-test-tokens.js +42 -14
  168. package/server.js +338 -292
  169. package/setup-production.sh +16 -7
  170. package/static/css/flyonui.css +1 -1
  171. package/static/css/src/app.tailwind.css +7 -8
  172. package/static/js/ee-client.js +145 -70
  173. package/static/js/ui.js +350 -154
  174. package/static/licenses.html +349 -1740
  175. package/translations/messages.pot +129 -111
  176. package/views/account-workspace-error.hbs +30 -0
  177. package/views/accounts/account.hbs +9 -4
  178. package/views/accounts/browse.hbs +10 -4
  179. package/views/accounts/edit.hbs +11 -2
  180. package/views/config/ai.hbs +49 -41
  181. package/views/config/oauth/app.hbs +2 -1
  182. package/views/dashboard.hbs +18 -16
  183. package/views/internals/index.hbs +1 -1
  184. package/views/layout/app.hbs +0 -22
  185. package/views/layout/login.hbs +2 -1
  186. package/views/partials/filter_editor_js.hbs +4 -3
  187. package/views/partials/gmail_api_scopes.hbs +16 -0
  188. package/views/partials/oauth_form.hbs +67 -94
  189. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  190. package/views/partials/scope_info.hbs +14 -23
  191. package/views/partials/side_menu.hbs +0 -4
  192. package/views/partials/ui/account-picker.hbs +6 -32
  193. package/views/partials/ui/model-picker.hbs +31 -0
  194. package/views/partials/ui/pagination.hbs +6 -1
  195. package/views/partials/ui/picker.hbs +47 -0
  196. package/views/unsubscribe.hbs +1 -1
  197. package/workers/api.js +82 -47
  198. package/workers/export.js +55 -60
  199. package/workers/imap.js +132 -49
  200. package/workers/submit.js +5 -6
  201. package/workers/webhooks.js +46 -27
  202. package/.githooks/pre-commit +0 -80
  203. package/.github/CODE_OF_CONDUCT.md +0 -76
  204. package/.github/contributing.md +0 -17
  205. package/.github/dependabot.yml +0 -22
  206. package/.github/docker-smoke-test.sh +0 -61
  207. package/.github/workflows/deploy.yml +0 -215
  208. package/.github/workflows/e2e.yml +0 -55
  209. package/.github/workflows/release.yaml +0 -217
  210. package/.github/workflows/test.yml +0 -307
  211. package/lib/api-routes/chat-routes.js +0 -535
  212. package/lib/document-store.js +0 -75
  213. package/lib/es.js +0 -757
  214. package/lib/generate-text-preview.js +0 -61
  215. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  216. package/lib/pre-process.js +0 -196
  217. package/lib/threads.js +0 -155
  218. package/lib/ui-routes/document-store-routes.js +0 -806
  219. package/playwright.config.js +0 -47
  220. package/views/config/document-store/chat.hbs +0 -286
  221. package/views/config/document-store/index.hbs +0 -146
  222. package/views/config/document-store/mappings/index.hbs +0 -108
  223. package/views/config/document-store/mappings/new.hbs +0 -68
  224. package/views/config/document-store/pre-processing/index.hbs +0 -103
  225. package/views/partials/document_store_header.hbs +0 -30
  226. package/workers/documents.js +0 -1128
@@ -2,6 +2,7 @@
2
2
 
3
3
  const packageData = require('../../package.json');
4
4
  const { fetch: fetchCmd } = require('undici');
5
+ const { fetchTokenRequest } = require('./token-fetch');
5
6
  const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError } = require('../tools');
6
7
 
7
8
  const MAIL_RU_SCOPES = ['userinfo', 'mail.imap'];
@@ -109,16 +110,19 @@ class MailRuOauth {
109
110
  let requestUrl = tokenRequest.url;
110
111
  let method = 'post';
111
112
 
112
- let res = await fetchCmd(tokenRequest.url, {
113
- method,
114
- headers: {
115
- 'Content-Type': 'application/x-www-form-urlencoded',
116
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`,
117
- Authorization: `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString('base64')}`
113
+ let res = await fetchTokenRequest(
114
+ tokenRequest.url,
115
+ {
116
+ method,
117
+ headers: {
118
+ 'Content-Type': 'application/x-www-form-urlencoded',
119
+ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`,
120
+ Authorization: `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString('base64')}`
121
+ },
122
+ body: tokenRequest.body
118
123
  },
119
- body: tokenRequest.body,
120
- dispatcher: httpAgent.retry
121
- });
124
+ { grant: 'authorization_code', provider: this.provider, clientId: this.clientId }
125
+ );
122
126
 
123
127
  let responseJson;
124
128
  try {
@@ -194,15 +198,18 @@ class MailRuOauth {
194
198
  let method = 'post';
195
199
 
196
200
  const bodyString = url.searchParams.toString();
197
- let res = await fetchCmd(requestUrl, {
198
- method,
199
- headers: {
200
- 'Content-Type': 'application/x-www-form-urlencoded',
201
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
201
+ let res = await fetchTokenRequest(
202
+ requestUrl,
203
+ {
204
+ method,
205
+ headers: {
206
+ 'Content-Type': 'application/x-www-form-urlencoded',
207
+ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
208
+ },
209
+ body: bodyString
202
210
  },
203
- body: bodyString,
204
- dispatcher: httpAgent.retry
205
- });
211
+ { grant: 'refresh_token', provider: this.provider, clientId: this.clientId }
212
+ );
206
213
 
207
214
  let responseJson;
208
215
  try {
@@ -1,9 +1,10 @@
1
1
  'use strict';
2
2
 
3
3
  const packageData = require('../../package.json');
4
- const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError } = require('../tools');
4
+ const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError, parseRetryAfter } = require('../tools');
5
5
 
6
6
  const { fetch: fetchCmd } = require('undici');
7
+ const { fetchTokenRequest } = require('./token-fetch');
7
8
 
8
9
  // Individual MS Graph API scope names for detection
9
10
  // These are the scope names extracted from full MS Graph API scope URLs
@@ -269,15 +270,18 @@ class OutlookOauth {
269
270
  let requestUrl = tokenRequest.url;
270
271
  let method = 'post';
271
272
 
272
- let res = await fetchCmd(tokenRequest.url, {
273
- method,
274
- headers: {
275
- 'Content-Type': 'application/x-www-form-urlencoded',
276
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
273
+ let res = await fetchTokenRequest(
274
+ tokenRequest.url,
275
+ {
276
+ method,
277
+ headers: {
278
+ 'Content-Type': 'application/x-www-form-urlencoded',
279
+ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
280
+ },
281
+ body: tokenRequest.body
277
282
  },
278
- body: tokenRequest.body,
279
- dispatcher: httpAgent.retry
280
- });
283
+ { grant: 'authorization_code', provider: this.provider, clientId: this.clientId, authority: this.authority }
284
+ );
281
285
 
282
286
  let responseJson;
283
287
  try {
@@ -370,15 +374,18 @@ class OutlookOauth {
370
374
  let method = 'post';
371
375
 
372
376
  const bodyString = url.searchParams.toString();
373
- let res = await fetchCmd(requestUrl, {
374
- method,
375
- headers: {
376
- 'Content-Type': 'application/x-www-form-urlencoded',
377
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
377
+ let res = await fetchTokenRequest(
378
+ requestUrl,
379
+ {
380
+ method,
381
+ headers: {
382
+ 'Content-Type': 'application/x-www-form-urlencoded',
383
+ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
384
+ },
385
+ body: bodyString
378
386
  },
379
- body: bodyString,
380
- dispatcher: httpAgent.retry
381
- });
387
+ { grant: 'refresh_token', provider: this.provider, clientId: this.clientId, authority: this.authority }
388
+ );
382
389
 
383
390
  let responseJson;
384
391
  try {
@@ -461,15 +468,18 @@ class OutlookOauth {
461
468
  let method = 'post';
462
469
 
463
470
  const bodyString = url.searchParams.toString();
464
- let res = await fetchCmd(requestUrl, {
465
- method,
466
- headers: {
467
- 'Content-Type': 'application/x-www-form-urlencoded',
468
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
471
+ let res = await fetchTokenRequest(
472
+ requestUrl,
473
+ {
474
+ method,
475
+ headers: {
476
+ 'Content-Type': 'application/x-www-form-urlencoded',
477
+ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
478
+ },
479
+ body: bodyString
469
480
  },
470
- body: bodyString,
471
- dispatcher: httpAgent.retry
472
- });
481
+ { grant: 'client_credentials', provider: this.provider, clientId: this.clientId, authority: this.authority }
482
+ );
473
483
 
474
484
  let responseJson;
475
485
  try {
@@ -544,7 +554,12 @@ class OutlookOauth {
544
554
  Authorization: `Bearer ${accessToken}`,
545
555
  'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
546
556
  },
547
- dispatcher: httpAgent.retry
557
+ // Sent exactly once. Which failures are worth repeating depends on the method and on
558
+ // what Graph answered, and that is decided by the request layer above this one
559
+ // (lib/email-client/api-retry.js); a transport that retried on its own replayed sends
560
+ // after a socket drop (a repeated draft /send then failed with 404, reporting a sent
561
+ // message as failed) and multiplied throttled calls
562
+ dispatcher: httpAgent.fetch
548
563
  };
549
564
 
550
565
  if (options.headers) {
@@ -555,15 +570,10 @@ class OutlookOauth {
555
570
  if (!Buffer.isBuffer(payload)) {
556
571
  reqData.headers.Accept = 'application/json';
557
572
  reqData.headers['Content-Type'] = options?.contentType || 'application/json';
558
- // Use string body instead of Buffer to avoid ArrayBuffer detachment on retry
559
573
  reqData.body = JSON.stringify(payload);
560
574
  } else {
561
575
  reqData.headers['Content-Type'] = options?.contentType || 'application/x-www-form-urlencoded';
562
576
  reqData.body = payload;
563
- if (payload.length > 0) {
564
- // Non-empty buffers use non-retry dispatcher to prevent ArrayBuffer detachment
565
- reqData.dispatcher = httpAgent.fetch;
566
- }
567
577
  }
568
578
  } else if (payload && method === 'get') {
569
579
  let parsedUrl = new URL(url);
@@ -593,15 +603,12 @@ class OutlookOauth {
593
603
  reqTime
594
604
  };
595
605
 
596
- // Capture Retry-After header for rate limiting (429) responses
597
- if (res.status === 429) {
598
- const retryAfterHeader = res.headers.get('retry-after');
599
- if (retryAfterHeader) {
600
- // Retry-After can be seconds or HTTP-date; parse as seconds
601
- const retryAfterSeconds = parseInt(retryAfterHeader, 10);
602
- err.retryAfter = !isNaN(retryAfterSeconds) ? retryAfterSeconds : null;
603
- err.oauthRequest.retryAfter = err.retryAfter;
604
- }
606
+ // Capture Retry-After (sent with 429, and with 503 while Graph is shedding load) so
607
+ // the retry layer can honour it
608
+ const retryAfter = parseRetryAfter(res.headers);
609
+ if (retryAfter !== null) {
610
+ err.retryAfter = retryAfter;
611
+ err.oauthRequest.retryAfter = retryAfter;
605
612
  }
606
613
 
607
614
  try {
@@ -648,6 +655,12 @@ class OutlookOauth {
648
655
  // clear potential auth flag
649
656
  await this.setFlag();
650
657
 
658
+ if (options.returnBuffer) {
659
+ // Raw MIME ($value endpoints) is bytes, not text: decoding it as UTF-8 would turn every
660
+ // 8-bit byte of a legacy charset into U+FFFD
661
+ return Buffer.from(await res.arrayBuffer());
662
+ }
663
+
651
664
  if (options.returnText) {
652
665
  return await res.text();
653
666
  }
@@ -9,6 +9,13 @@ const { oauth2Apps } = require('../../oauth2-apps');
9
9
 
10
10
  const { normalizeHashKeys } = require('../../tools');
11
11
 
12
+ // Recovery attempts made back to back (paced only by the loop's own backoff). Past this the next
13
+ // attempt waits RECOVERY_BACKOFF_STEP per extra attempt, up to RECOVERY_BACKOFF_MAX: an operator
14
+ // who fixes the IAM permissions after the fifth failure used to get nothing until a restart
15
+ const RECOVERY_FAST_ATTEMPTS = 5;
16
+ const RECOVERY_BACKOFF_STEP = 10 * 60 * 1000;
17
+ const RECOVERY_BACKOFF_MAX = 4 * 60 * 60 * 1000;
18
+
12
19
  class PubSubInstance {
13
20
  constructor(parent, opts) {
14
21
  this.parent = parent;
@@ -28,6 +35,7 @@ class PubSubInstance {
28
35
  this._lastLoopError = null;
29
36
  this._consecutiveErrors = 0;
30
37
  this._recoveryAttempts = 0;
38
+ this._nextRecoveryAt = 0;
31
39
 
32
40
  this.checkSchemaVersions()
33
41
  .catch(err => {
@@ -56,6 +64,7 @@ class PubSubInstance {
56
64
  this._lastLoopError = null;
57
65
  this._consecutiveErrors = 0;
58
66
  this._recoveryAttempts = 0;
67
+ this._nextRecoveryAt = 0;
59
68
  if (messageCount > 0) {
60
69
  this._immediateHandle = setImmediate(() => this.startLoop());
61
70
  } else {
@@ -313,6 +322,11 @@ class PubSubInstance {
313
322
  // 401: token refresh happens automatically via getServiceAccessToken() on next run().
314
323
  // 403: permanent until operator fixes IAM permissions; retrying ensurePubsub wastes API calls.
315
324
  if (err.statusCode === 401 || err.statusCode === 403) {
325
+ if (err.statusCode === 401) {
326
+ // The cached service token was refused. Left in place, every run would keep
327
+ // presenting it until its recorded expiry instead of fetching a new one
328
+ await this.invalidateAccessToken();
329
+ }
316
330
  logger.error({
317
331
  msg: 'Authentication/authorization error pulling subscription messages',
318
332
  app: this.app,
@@ -339,9 +353,18 @@ class PubSubInstance {
339
353
  }
340
354
 
341
355
  async attemptRecovery(reason) {
356
+ let now = Date.now();
357
+ if (this._recoveryAttempts >= RECOVERY_FAST_ATTEMPTS && now < this._nextRecoveryAt) {
358
+ let err = new Error(`Recovery attempted ${this._recoveryAttempts} times without a successful pull; backing off`);
359
+ // the loop sleeps until the next attempt is due instead of polling for it
360
+ err.retryDelay = this._nextRecoveryAt - now;
361
+ throw err;
362
+ }
363
+
342
364
  this._recoveryAttempts++;
343
- if (this._recoveryAttempts > 5) {
344
- throw new Error(`Recovery attempted ${this._recoveryAttempts} times without a successful pull; backing off`);
365
+ if (this._recoveryAttempts >= RECOVERY_FAST_ATTEMPTS) {
366
+ // reset by the loop after a run that completes
367
+ this._nextRecoveryAt = now + Math.min(RECOVERY_BACKOFF_STEP * (this._recoveryAttempts - RECOVERY_FAST_ATTEMPTS + 1), RECOVERY_BACKOFF_MAX);
345
368
  }
346
369
 
347
370
  logger.info({ msg: 'Attempting subscription recovery', app: this.app, reason, attempt: this._recoveryAttempts });
@@ -402,6 +425,19 @@ class PubSubInstance {
402
425
  return await oauth2Apps.getServiceAccessToken(this.appData, this.client);
403
426
  }
404
427
 
428
+ async invalidateAccessToken() {
429
+ try {
430
+ await oauth2Apps.invalidateServiceAccessToken(this.app);
431
+ } catch (err) {
432
+ logger.error({ msg: 'Failed to clear the cached service access token', app: this.app, err });
433
+ }
434
+ if (this.appData) {
435
+ // getServiceAccessToken() reads the token off this record first
436
+ this.appData.accessToken = null;
437
+ this.appData.accessTokenExpires = null;
438
+ }
439
+ }
440
+
405
441
  _setPubSubFlag(flag) {
406
442
  this._hadPubSubFlag = true;
407
443
  this._pubSubFlagSetThisSession = true;
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const { GMAIL_API_SCOPES } = require('./gmail');
3
+ const { GMAIL_API_SCOPES, GMAIL_SCOPES, GMAIL_PROVIDERS, GMAIL_SCOPE_PREFIX } = require('./gmail');
4
+ const { formatExtraScopes } = require('./scope-list');
4
5
  const { OUTLOOK_API_SCOPES } = require('./outlook');
5
6
 
6
7
  // Known Microsoft Graph API endpoints across different cloud environments
@@ -123,13 +124,10 @@ function checkAccountScopes(provider, scopes, logger) {
123
124
 
124
125
  if (provider === 'gmail') {
125
126
  const hasSendScope = scopes.some(s => s.includes(GMAIL_API_SCOPES.send));
126
- const hasReadScope = scopes.some(
127
- s =>
128
- s.includes(GMAIL_API_SCOPES.modify) ||
129
- s.includes(GMAIL_API_SCOPES.readonly) ||
130
- s.includes(GMAIL_API_SCOPES.labels) ||
131
- s.includes('mail.google.com')
132
- );
127
+ // gmail.labels is not a read scope: it manages labels but cannot read a message or the
128
+ // profile, so a send + labels account treated as full access armed the watch, got a 403
129
+ // and ended in authenticationError instead of running send-only
130
+ const hasReadScope = scopes.some(s => s.includes(GMAIL_API_SCOPES.modify) || s.includes(GMAIL_API_SCOPES.readonly) || s.includes('mail.google.com'));
133
131
  return { hasSendScope, hasReadScope };
134
132
  }
135
133
 
@@ -176,6 +174,38 @@ function checkOutlookScopes(accountData, logger) {
176
174
  return checkAccountScopes('outlook', scopes, logger);
177
175
  }
178
176
 
177
+ /**
178
+ * Whether an OAuth2 APPLICATION is configured for sending only, as the app page presents it.
179
+ *
180
+ * Only an API-based Gmail app can be: `baseScopes: 'api'` is what makes one reach the Gmail HTTP API
181
+ * rather than IMAP XOAUTH2, and it is not a property of the provider - a service account delegated
182
+ * gmail.send alone is as send-only as an interactive app, which the admin route used to miss by keying
183
+ * on `provider === 'gmail'`.
184
+ *
185
+ * Judged on the scopes the app really requests, which is the list the authentication URL is built from:
186
+ * the api-mode default it does not have to repeat, its own extras, minus what skipScopes removes.
187
+ * Reading extraScopes alone called an app send-only while it still requested gmail.modify. A scope may
188
+ * be stored under its short name, which Google's own scope URLs are not, so the list is expanded first.
189
+ *
190
+ * Pure: extracted out of lib/ui-routes/oauth-config-routes.js, which built an Account instance and
191
+ * resolved the encryption secret only to reach checkAccountScopes() above.
192
+ *
193
+ * @param {Object} app - A stored OAuth2 application record
194
+ * @returns {boolean} True when the app grants sending but not reading
195
+ */
196
+ function isSendOnlyGmailApp(app) {
197
+ if (!app || !GMAIL_PROVIDERS.has(app.provider) || app.baseScopes !== 'api') {
198
+ return false;
199
+ }
200
+
201
+ const scopes = formatExtraScopes(app.extraScopes, app.baseScopes, GMAIL_SCOPES, app.skipScopes, GMAIL_SCOPE_PREFIX).map(scope =>
202
+ scope.startsWith('https://') ? scope : `${GMAIL_SCOPE_PREFIX}/${scope}`
203
+ );
204
+ const { hasSendScope, hasReadScope } = checkAccountScopes('gmail', scopes);
205
+
206
+ return hasSendScope && !hasReadScope;
207
+ }
208
+
179
209
  /**
180
210
  * Determines if an account is in send-only mode based on its scopes.
181
211
  *
@@ -192,6 +222,7 @@ function isSendOnlyByScopes(provider, accountData, logger) {
192
222
 
193
223
  module.exports = {
194
224
  checkAccountScopes,
225
+ isSendOnlyGmailApp,
195
226
  checkGmailScopes,
196
227
  checkOutlookScopes,
197
228
  isSendOnlyByScopes,
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+
3
+ // The scope list an OAuth2 application actually requests, derived from what is stored on it. Kept in a
4
+ // leaf module because two callers need it from opposite ends of the dependency graph: lib/oauth2-apps.js
5
+ // builds the authentication URL from it, and lib/oauth/scope-checker.js decides from it what an
6
+ // application can do - the latter must not pull the Redis chain in to ask.
7
+
8
+ // The last path segment of a scope URL, which is the short name the scope presets on the OAuth2 app
9
+ // form write into skipScopes ("Mail.ReadWrite", "gmail.modify"). Derived from the scope's own prefix
10
+ // rather than compared against a list of hosts: the Outlook defaults are requested under
11
+ // graph.microsoft.com on the global cloud but under graph.microsoft.us, dod-graph.microsoft.us or
12
+ // microsoftgraph.chinacloudapi.cn on GCC High, DoD and China, and a host list that named only the
13
+ // global one left every default scope of such an application in place.
14
+ function shortScopeName(scope) {
15
+ const separator = scope.lastIndexOf('/');
16
+ return separator < 0 ? scope : scope.slice(separator + 1);
17
+ }
18
+
19
+ function formatExtraScopes(extraScopes, baseScopes, defaultScopesList, skipScopes, scopePrefix) {
20
+ let defaultScopes;
21
+
22
+ // An empty entry would match the short name of a scope URL ending in a slash
23
+ skipScopes = [].concat(skipScopes || []).filter(entry => entry);
24
+
25
+ if (Array.isArray(defaultScopesList)) {
26
+ defaultScopes = defaultScopesList;
27
+ } else {
28
+ defaultScopes = (baseScopes && defaultScopesList[baseScopes]) || defaultScopesList.imap;
29
+ }
30
+
31
+ if (!extraScopes && !skipScopes.length) {
32
+ return defaultScopes;
33
+ }
34
+
35
+ extraScopes = extraScopes || [];
36
+
37
+ let extras = [];
38
+ for (let extraScope of extraScopes) {
39
+ if (defaultScopes.includes(extraScope) || (scopePrefix && defaultScopes.includes(`${scopePrefix}/${extraScope}`))) {
40
+ // skip existing
41
+ continue;
42
+ }
43
+ extras.push(extraScope);
44
+ }
45
+
46
+ let result = extras.length ? extras.concat(defaultScopes) : defaultScopes;
47
+
48
+ if (skipScopes.length) {
49
+ result = result.filter(scope => !skipScopes.some(skipScope => scope === skipScope || shortScopeName(scope) === skipScope));
50
+ }
51
+
52
+ return result;
53
+ }
54
+
55
+ module.exports = { shortScopeName, formatExtraScopes };
@@ -0,0 +1,47 @@
1
+ 'use strict';
2
+
3
+ const { fetch: fetchCmd } = require('undici');
4
+ const { httpAgent } = require('../tools');
5
+
6
+ /**
7
+ * Performs a token-endpoint request, and says which endpoint failed when the request never got there.
8
+ *
9
+ * A rejected response is already described in detail by each provider client (`ETokenRefresh`, the
10
+ * status, the parsed body). A request that never reaches the endpoint is not: undici rejects a failed
11
+ * fetch with a bare `fetch failed` whose own `code` is unset, the reason (ENOTFOUND, ECONNREFUSED,
12
+ * UND_ERR_CONNECT_TIMEOUT, a TLS failure) sitting on `err.cause`. Such a failure is correctly treated
13
+ * as transient - the account reports a connectError and keeps retrying rather than being parked - but
14
+ * the webhook then carried "fetch failed" and no serverResponseCode, which is indistinguishable from
15
+ * the mail server itself being unreachable. That is the one thing it is not.
16
+ *
17
+ * The error is ANNOTATED rather than replaced. Its code and cause are what isTransientNetworkError()
18
+ * reads (lib/email-client/credential-errors.js), and a token endpoint that could not be reached has
19
+ * not refused the refresh token: a replacement error carrying a code of its own would be read as an
20
+ * authentication failure and would park the account.
21
+ *
22
+ * @param {String} url - the token endpoint
23
+ * @param {Object} options - fetch options; the retrying dispatcher is applied here and cannot be overridden
24
+ * @param {Object} context - what to record about the attempt, as the rejected-response path records it.
25
+ * The method is read from `options`, so the two cannot disagree
26
+ * @returns {Promise<Response>} the response, whatever its status
27
+ */
28
+ async function fetchTokenRequest(url, options, context) {
29
+ try {
30
+ // The dispatcher is applied last, so this helper really is the one place that decides it -
31
+ // with the default first, a caller that passed one would silently lose the retrying agent
32
+ return await fetchCmd(url, Object.assign({}, options, { dispatcher: httpAgent.retry }));
33
+ } catch (err) {
34
+ // The cause carries the actionable code. Promoted onto the error itself so the connectError
35
+ // webhook has something to report - the transient check consults both, so no verdict changes.
36
+ if (!err.code && err.cause && err.cause.code) {
37
+ err.code = err.cause.code;
38
+ }
39
+
40
+ err.tokenRequest = Object.assign({ url, method: (options && options.method) || 'get', error: err.message, errorCode: err.code }, context);
41
+ err.message = `Token request to ${url} failed${err.code ? ` [${err.code}]` : ''}: ${(err.cause && err.cause.message) || err.message}`;
42
+
43
+ throw err;
44
+ }
45
+ }
46
+
47
+ module.exports = { fetchTokenRequest };
@@ -6,7 +6,7 @@
6
6
  // existing OAuth clients and the coded errors they already throw - no provider logic
7
7
  // is reimplemented here.
8
8
 
9
- const { ImapFlow } = require('imapflow');
9
+ const { createImapClient } = require('../create-imap-client');
10
10
  const { oauth2Apps, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
11
11
  const packageData = require('../../package.json');
12
12
 
@@ -134,7 +134,7 @@ function mapTokenError(err, account, appData, steps) {
134
134
  // Live, read-only IMAP XOAUTH2 login. No mailbox changes, no mail sent.
135
135
  async function imapProbe(appData, account, accessToken, steps) {
136
136
  let imapCfg = oauth2ProviderData(appData.provider, appData.cloud).imap;
137
- let client = new ImapFlow({
137
+ let client = createImapClient({
138
138
  host: imapCfg.host,
139
139
  port: imapCfg.port,
140
140
  secure: imapCfg.secure,