emailengine-app 2.81.1 → 2.82.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 (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  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-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. package/workers/documents.js +0 -1128
@@ -2,21 +2,43 @@
2
2
 
3
3
  const { Writable, Readable, pipeline } = require('stream');
4
4
 
5
- // const { MessageChannel } = require('worker_threads');
6
- // const { port1, port2 } = new MessageChannel();
5
+ // Flow control. The writer may have this many bytes posted but not yet taken by the reader; the
6
+ // reader returns credit ({ ack: bytes }) as it hands chunks to its consumer, and the writer holds
7
+ // back the callback of the write that ran out of credit until some comes back. Without it the
8
+ // writer acknowledged every chunk at once, so the IMAP download ran at network speed whatever the
9
+ // HTTP client did, and a slow client left the whole message buffered in the API worker.
10
+ //
11
+ // The reader returns credit in batches of a quarter of the window rather than one ack per chunk,
12
+ // which doubled the cross-thread traffic of every transfer. Both sides have to agree on the
13
+ // window: a reader batching against a larger window than the writer holds would sit on the
14
+ // credit the writer is waiting for.
15
+ const DEFAULT_CREDIT_WINDOW = 1024 * 1024;
16
+ const ACK_BATCH_FRACTION = 4;
7
17
 
8
18
  class MessagePortWritable extends Writable {
9
- constructor(messagePort) {
19
+ constructor(messagePort, opts) {
10
20
  super();
11
21
  this.messagePort = messagePort;
12
22
  this.portClosed = false;
13
23
 
24
+ this.credit = (opts && opts.creditWindow) || DEFAULT_CREDIT_WINDOW;
25
+ this.pendingWrite = null;
26
+
14
27
  // The reader side posts { cancel: true } when it is torn down (e.g. the
15
28
  // HTTP client aborted the download). Stop the transfer so the upstream
16
29
  // source - and the IMAP lock it holds - is released.
17
30
  this.onPortMessage = message => {
18
31
  if (message && message.cancel) {
19
32
  this.destroy();
33
+ return;
34
+ }
35
+ if (message && typeof message.ack === 'number') {
36
+ this.credit += message.ack;
37
+ if (this.pendingWrite && this.credit > 0) {
38
+ let done = this.pendingWrite;
39
+ this.pendingWrite = null;
40
+ done();
41
+ }
20
42
  }
21
43
  };
22
44
 
@@ -81,7 +103,13 @@ class MessagePortWritable extends Writable {
81
103
  }
82
104
 
83
105
  this.postToPort({ value: chunk, done: false });
84
- done();
106
+ this.credit -= chunk.length;
107
+
108
+ if (this.credit > 0 || this.portClosed) {
109
+ return done();
110
+ }
111
+ // Out of credit: the next write waits until the reader has taken some of what was sent
112
+ this.pendingWrite = done;
85
113
  }
86
114
 
87
115
  _final(done) {
@@ -91,6 +119,9 @@ class MessagePortWritable extends Writable {
91
119
  }
92
120
 
93
121
  _destroy(err, done) {
122
+ // A write waiting for credit is abandoned with the stream; destroy() does not wait for it
123
+ this.pendingWrite = null;
124
+
94
125
  // Abnormal termination: tell the reader so a truncated transfer is not
95
126
  // mistaken for a complete message, then release the port.
96
127
  if (err) {
@@ -102,7 +133,7 @@ class MessagePortWritable extends Writable {
102
133
  }
103
134
 
104
135
  class MessagePortReadable extends Readable {
105
- constructor(messagePort) {
136
+ constructor(messagePort, opts) {
106
137
  super();
107
138
  this.messagePort = messagePort;
108
139
 
@@ -110,6 +141,10 @@ class MessagePortReadable extends Readable {
110
141
  this.portClosed = false;
111
142
  this.transferComplete = false;
112
143
 
144
+ // Credit taken from the writer but not yet returned; posted once it reaches the threshold
145
+ this.pendingAck = 0;
146
+ this.ackThreshold = Math.max(1, Math.ceil(((opts && opts.creditWindow) || DEFAULT_CREDIT_WINDOW) / ACK_BATCH_FRACTION));
147
+
113
148
  this.readableQueue = [];
114
149
  this.onPortMessage = message => {
115
150
  if (!message) {
@@ -150,9 +185,32 @@ class MessagePortReadable extends Readable {
150
185
  while (this.canRead && this.readableQueue.length) {
151
186
  let message = this.readableQueue.shift();
152
187
  if (message.done) {
188
+ this.flushAck();
153
189
  return this.push(null);
154
190
  }
155
- this.canRead = this.push(Buffer.from(message.value));
191
+ let chunk = Buffer.from(message.value);
192
+ this.canRead = this.push(chunk);
193
+ // The chunk has left the queue for the consumer, so the writer may send that much more.
194
+ // readableQueue therefore never holds more than the writer's credit window.
195
+ this.pendingAck += chunk.length;
196
+ if (this.pendingAck >= this.ackThreshold) {
197
+ this.flushAck();
198
+ }
199
+ }
200
+ }
201
+
202
+ // Returns the accumulated credit to the writer. Not called from _destroy(): the cancel posted
203
+ // there destroys the writer, so credit returned alongside it would never be spent.
204
+ flushAck() {
205
+ let bytes = this.pendingAck;
206
+ this.pendingAck = 0;
207
+ if (this.portClosed || !bytes) {
208
+ return;
209
+ }
210
+ try {
211
+ this.messagePort.postMessage({ ack: bytes });
212
+ } catch (err) {
213
+ // ignore - the producer may already be gone
156
214
  }
157
215
  }
158
216
 
package/lib/msgpack.js CHANGED
@@ -54,9 +54,4 @@ function decode(buf) {
54
54
  throw new Error('Unable to decode msgpack value');
55
55
  }
56
56
 
57
- // Decodes a byte stream of concatenated msgpack values (append-list hash fields)
58
- function decodeMulti(buf) {
59
- return Array.from(decoder.decodeMulti(buf), bufferize);
60
- }
61
-
62
- module.exports = { encode, decode, decodeMulti };
57
+ module.exports = { encode, decode };
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
3
  const fs = require('fs');
4
- const { fetch: undiciFetch } = require('undici');
4
+ const { fetch: undiciFetch, Agent } = require('undici');
5
5
  const packageData = require('../../package.json');
6
- const { httpAgent } = require('../tools');
6
+ const { httpAgent, parseRetryAfter } = require('../tools');
7
7
  const { makeError, validateConfig, extractFromFormat } = require('./external-account-config');
8
8
 
9
9
  const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';
@@ -15,6 +15,17 @@ const TOKEN_EXPIRY_SKEW_MS = 60 * 1000;
15
15
  const DEFAULT_FEDERATED_TOKEN_TTL_MS = 3600 * 1000;
16
16
  const USER_AGENT = `${packageData.name}/${packageData.version} (+${packageData.homepage})`;
17
17
 
18
+ // The URL credential source is a local identity endpoint (a cloud metadata server such as
19
+ // 169.254.169.254, a sidecar), reachable only from this host. It must never go through the
20
+ // configured HTTP or SOCKS proxy: the proxy cannot reach it, and the request headers and the
21
+ // returned identity token would be handed to the proxy. The STS and IAM calls are ordinary
22
+ // outbound traffic and keep the shared dispatcher
23
+ const credentialSourceAgent = new Agent({
24
+ connectTimeout: 30 * 1000,
25
+ headersTimeout: 60 * 1000,
26
+ bodyTimeout: 60 * 1000
27
+ });
28
+
18
29
  class ExternalAccountSigner {
19
30
  constructor(opts) {
20
31
  opts = opts || {};
@@ -81,7 +92,7 @@ class ExternalAccountSigner {
81
92
  res = await this._fetch(source.url, {
82
93
  method: 'GET',
83
94
  headers,
84
- dispatcher: httpAgent.retry
95
+ dispatcher: credentialSourceAgent
85
96
  });
86
97
  } catch (err) {
87
98
  throw makeError(`Failed to fetch subject token from ${source.url}: ${err.message}`, 'ESubjectTokenRead', null, { cause: err });
@@ -201,17 +212,9 @@ class ExternalAccountSigner {
201
212
  this._log('callSignJwt', 'POST', url, res.ok, res.status);
202
213
 
203
214
  if (!res.ok) {
204
- let retryAfter = null;
205
- if (res.status === 429) {
206
- let header = res.headers.get('retry-after');
207
- if (header) {
208
- let parsed = parseInt(header, 10);
209
- retryAfter = isNaN(parsed) ? null : parsed;
210
- }
211
- }
212
215
  throw makeError(`signJwt returned HTTP ${res.status}`, 'ESignJwt', res.status, {
213
216
  response: responseJson || null,
214
- retryAfter
217
+ retryAfter: res.status === 429 ? parseRetryAfter(res.headers) : null
215
218
  });
216
219
  }
217
220
 
@@ -258,4 +261,4 @@ class ExternalAccountSigner {
258
261
  }
259
262
 
260
263
  module.exports.ExternalAccountSigner = ExternalAccountSigner;
261
- module.exports.__test__ = { validateConfig, extractFromFormat, makeError };
264
+ module.exports.__test__ = { validateConfig, extractFromFormat, makeError, credentialSourceAgent };
@@ -1,7 +1,7 @@
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
  const crypto = require('crypto');
6
6
 
7
7
  const { fetch: fetchCmd } = require('undici');
@@ -262,11 +262,16 @@ class GmailOauth {
262
262
  // 3-legged OAuth has no serviceClient and never reaches generateServiceRequest.
263
263
  if (this.serviceClient) {
264
264
  if (this.authMethod === 'externalAccount') {
265
- this.signer = new ExternalAccountSigner({
266
- config: parseExternalAccountConfig(opts.externalAccount),
267
- logger: this.logger,
268
- logRaw: this.logRaw
269
- });
265
+ // The signer caches the federated token and deduplicates concurrent refreshes, which
266
+ // only pays off when it outlives this client: every token renewal builds a new
267
+ // GmailOauth, so the app handler passes in a signer it keeps per app
268
+ this.signer =
269
+ opts.externalAccountSigner ||
270
+ new ExternalAccountSigner({
271
+ config: parseExternalAccountConfig(opts.externalAccount),
272
+ logger: this.logger,
273
+ logRaw: this.logRaw
274
+ });
270
275
 
271
276
  // With Workload Identity Federation the JWT is signed by the
272
277
  // impersonated service account (derived from the external account
@@ -572,7 +577,11 @@ class GmailOauth {
572
577
  Authorization: `Bearer ${accessToken}`,
573
578
  'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
574
579
  },
575
- dispatcher: httpAgent.retry,
580
+ // Sent exactly once. Which failures are worth repeating depends on the method and on
581
+ // what Gmail answered, and that is decided by the request layer above this one
582
+ // (lib/email-client/api-retry.js); a transport that retried on its own replayed sends
583
+ // after a socket drop and multiplied throttled calls
584
+ dispatcher: httpAgent.fetch,
576
585
  signal: options.signal || undefined
577
586
  };
578
587
 
@@ -580,15 +589,10 @@ class GmailOauth {
580
589
  if (!Buffer.isBuffer(payload)) {
581
590
  reqData.headers.Accept = 'application/json';
582
591
  reqData.headers['Content-Type'] = options?.contentType || 'application/json';
583
- // Use string body instead of Buffer to avoid ArrayBuffer detachment on retry
584
592
  reqData.body = JSON.stringify(payload);
585
593
  } else {
586
594
  reqData.headers['Content-Type'] = options?.contentType || 'application/x-www-form-urlencoded';
587
595
  reqData.body = payload;
588
- if (payload.length > 0) {
589
- // Non-empty buffers use non-retry dispatcher to prevent ArrayBuffer detachment
590
- reqData.dispatcher = httpAgent.fetch;
591
- }
592
596
  }
593
597
  } else if (payload && method === 'get') {
594
598
  let parsedUrl = new URL(url);
@@ -626,14 +630,12 @@ class GmailOauth {
626
630
  reqTime
627
631
  };
628
632
 
629
- // Capture Retry-After header for rate limiting (429) responses
630
- if (res.status === 429) {
631
- let retryAfterHeader = res.headers.get('retry-after');
632
- if (retryAfterHeader) {
633
- let parsed = parseInt(retryAfterHeader, 10);
634
- err.retryAfter = isNaN(parsed) ? null : parsed;
635
- err.oauthRequest.retryAfter = err.retryAfter;
636
- }
633
+ // Capture Retry-After (sent with 429, and with rate-limit 403s and 503s) so the
634
+ // retry layer can honour it
635
+ let retryAfter = parseRetryAfter(res.headers);
636
+ if (retryAfter !== null) {
637
+ err.retryAfter = retryAfter;
638
+ err.oauthRequest.retryAfter = retryAfter;
637
639
  }
638
640
 
639
641
  try {
@@ -1,7 +1,7 @@
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
7
 
@@ -544,7 +544,12 @@ class OutlookOauth {
544
544
  Authorization: `Bearer ${accessToken}`,
545
545
  'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
546
546
  },
547
- dispatcher: httpAgent.retry
547
+ // Sent exactly once. Which failures are worth repeating depends on the method and on
548
+ // what Graph answered, and that is decided by the request layer above this one
549
+ // (lib/email-client/api-retry.js); a transport that retried on its own replayed sends
550
+ // after a socket drop (a repeated draft /send then failed with 404, reporting a sent
551
+ // message as failed) and multiplied throttled calls
552
+ dispatcher: httpAgent.fetch
548
553
  };
549
554
 
550
555
  if (options.headers) {
@@ -555,15 +560,10 @@ class OutlookOauth {
555
560
  if (!Buffer.isBuffer(payload)) {
556
561
  reqData.headers.Accept = 'application/json';
557
562
  reqData.headers['Content-Type'] = options?.contentType || 'application/json';
558
- // Use string body instead of Buffer to avoid ArrayBuffer detachment on retry
559
563
  reqData.body = JSON.stringify(payload);
560
564
  } else {
561
565
  reqData.headers['Content-Type'] = options?.contentType || 'application/x-www-form-urlencoded';
562
566
  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
567
  }
568
568
  } else if (payload && method === 'get') {
569
569
  let parsedUrl = new URL(url);
@@ -593,15 +593,12 @@ class OutlookOauth {
593
593
  reqTime
594
594
  };
595
595
 
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
- }
596
+ // Capture Retry-After (sent with 429, and with 503 while Graph is shedding load) so
597
+ // the retry layer can honour it
598
+ const retryAfter = parseRetryAfter(res.headers);
599
+ if (retryAfter !== null) {
600
+ err.retryAfter = retryAfter;
601
+ err.oauthRequest.retryAfter = retryAfter;
605
602
  }
606
603
 
607
604
  try {
@@ -648,6 +645,12 @@ class OutlookOauth {
648
645
  // clear potential auth flag
649
646
  await this.setFlag();
650
647
 
648
+ if (options.returnBuffer) {
649
+ // Raw MIME ($value endpoints) is bytes, not text: decoding it as UTF-8 would turn every
650
+ // 8-bit byte of a legacy charset into U+FFFD
651
+ return Buffer.from(await res.arrayBuffer());
652
+ }
653
+
651
654
  if (options.returnText) {
652
655
  return await res.text();
653
656
  }
@@ -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;
@@ -123,13 +123,10 @@ function checkAccountScopes(provider, scopes, logger) {
123
123
 
124
124
  if (provider === 'gmail') {
125
125
  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
- );
126
+ // gmail.labels is not a read scope: it manages labels but cannot read a message or the
127
+ // profile, so a send + labels account treated as full access armed the watch, got a 403
128
+ // and ended in authenticationError instead of running send-only
129
+ const hasReadScope = scopes.some(s => s.includes(GMAIL_API_SCOPES.modify) || s.includes(GMAIL_API_SCOPES.readonly) || s.includes('mail.google.com'));
133
130
  return { hasSendScope, hasReadScope };
134
131
  }
135
132
 
@@ -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,