emailengine-app 2.74.1 → 2.74.2

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.74.2](https://github.com/postalsys/emailengine/compare/v2.74.1...v2.74.2) (2026-07-26)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **api:** bring /v1/changes under the route-table guardrail ([d685ad8](https://github.com/postalsys/emailengine/commit/d685ad849fd46d0c15837278b9d30a7f195400a2))
9
+ * **auth:** normalize the rate-limit window and reject a negative cost ([4c58678](https://github.com/postalsys/emailengine/commit/4c586783b350c38e9dd016f334b00c3d7c29cfd4))
10
+ * **export:** correct the concurrency limits and the active-set ownership ([690934a](https://github.com/postalsys/emailengine/commit/690934a0ecf8cbaa5374f0d44ae6881f708ff914))
11
+ * **imap:** keep an error sink on abandoned IMAP connections ([a9ef9e3](https://github.com/postalsys/emailengine/commit/a9ef9e3fe380cd3752a1121a0741559fbd8229b7))
12
+ * **imap:** report account log write failures instead of crashing the worker ([e881e65](https://github.com/postalsys/emailengine/commit/e881e6593ffa0f4ace027e9287124b3bde3a3edb))
13
+ * **imap:** stop wiping the folder listing on an unusable LIST response ([f6229bb](https://github.com/postalsys/emailengine/commit/f6229bb72a8a6cd415a3c738740b9dc64dfbfb9d))
14
+ * **imap:** tolerate a FETCH response that omits FLAGS ([b78b314](https://github.com/postalsys/emailengine/commit/b78b314396ea6eec7e23d707044cf46d1f51899c))
15
+ * **smtp:** handle MIME parse errors and enforce the message size limit ([e70eb7d](https://github.com/postalsys/emailengine/commit/e70eb7df40245118752cf276cb70090647573216))
16
+ * **smtp:** reject an unparseable message permanently instead of with a 450 ([ef77542](https://github.com/postalsys/emailengine/commit/ef775420a15d94c6a46d6eefe6d37413b5330e6c))
17
+ * **ui:** flag recently restarted workers on the internals page ([435a932](https://github.com/postalsys/emailengine/commit/435a93233ca56c61c42f17d80fb2d4d39fb88381))
18
+
3
19
  ## [2.74.1](https://github.com/postalsys/emailengine/compare/v2.74.0...v2.74.1) (2026-07-24)
4
20
 
5
21
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-07-22T14:46:01.000000",
2
+ "creationTime": "2026-07-24T14:45:49.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
package/lib/account.js CHANGED
@@ -12,9 +12,9 @@ const {
12
12
  resolveCredentials,
13
13
  isEmail,
14
14
  resolveDelegatedAccount,
15
- escapeRedisGlob
15
+ escapeRedisGlob,
16
+ getMailboxStatusKey
16
17
  } = require('./tools');
17
- const crypto = require('crypto');
18
18
  const { MessageChannel } = require('worker_threads');
19
19
  const { MessagePortReadable } = require('./message-port-stream');
20
20
  const { deepStrictEqual, strictEqual } = require('assert');
@@ -27,10 +27,11 @@ const { customAlphabet } = require('nanoid');
27
27
  const Lock = require('ioredfour');
28
28
  const { redis } = require('./db');
29
29
  const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
30
- const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, MAILBOX_HASH } = require('./consts');
30
+ const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY } = require('./consts');
31
31
  const { mimeHtml } = require('@postalsys/email-text-tools');
32
32
  const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
33
33
  const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
34
+ const { decodeStoredMailboxEntry } = require('./email-client/imap/listing-diff');
34
35
 
35
36
  // Shared Lock instance to prevent Redis connection leak (one subscriber per Lock instance)
36
37
  // Previously, each Account created its own Lock, causing ~30k connections with 30k accounts
@@ -1331,15 +1332,25 @@ class Account {
1331
1332
  // Batch into a single round-trip to avoid per-mailbox latency with many folders
1332
1333
  let pipeline = this.redis.pipeline();
1333
1334
  for (let path of paths) {
1334
- let redisKey = BigInt('0x' + crypto.createHash(MAILBOX_HASH).update(normalizePath(path)).digest('hex')).toString(36);
1335
- pipeline.hgetall(`${REDIS_PREFIX}iam:${this.account}:h:${redisKey}`);
1335
+ pipeline.hgetall(getMailboxStatusKey(this.account, path));
1336
1336
  }
1337
1337
  let pipelineResults = await pipeline.exec();
1338
1338
 
1339
1339
  for (let i = 0; i < paths.length; i++) {
1340
1340
  let path = paths[i];
1341
1341
  try {
1342
- let decoded = msgpack.decode(storedListing[path]);
1342
+ // Returns false for a corrupt value. Skipping the folder (rather than pushing a
1343
+ // boxed primitive into the response) keeps the rest of the listing usable; the
1344
+ // IMAP sync purges the entry on its next pass (see getCurrentListing), which is
1345
+ // also where the corruption is escalated to the error tracker - once, with every
1346
+ // affected folder, instead of once per request from here. Until that pass runs
1347
+ // the folder is simply missing from a 200 response, which a client reconciling
1348
+ // its own state against this endpoint reads as a deletion.
1349
+ let decoded = decodeStoredMailboxEntry(storedListing[path]);
1350
+ if (!decoded) {
1351
+ this.logger.error({ msg: 'Skipping corrupt stored mailbox listing entry', path, account: this.account });
1352
+ continue;
1353
+ }
1343
1354
 
1344
1355
  if (decoded.path && decoded.delimiter && decoded.path.indexOf(decoded.delimiter) >= 0) {
1345
1356
  decoded.parentPath = decoded.path.substring(0, decoded.path.lastIndexOf(decoded.delimiter));
@@ -1809,17 +1820,8 @@ class Account {
1809
1820
 
1810
1821
  const { index, client } = this.esClient;
1811
1822
 
1812
- let inboxData = await this.redis.hgetBuffer(this.getMailboxListKey(), 'INBOX');
1813
- let delimiter;
1814
- if (inboxData) {
1815
- try {
1816
- inboxData = msgpack.decode(inboxData);
1817
- delimiter = inboxData.delimiter;
1818
- } catch (err) {
1819
- delimiter = '/'; // hope for the best
1820
- inboxData = false;
1821
- }
1822
- }
1823
+ let inboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), 'INBOX'));
1824
+ let delimiter = inboxData ? inboxData.delimiter : '/'; // hope for the best
1823
1825
 
1824
1826
  inboxData = inboxData || {
1825
1827
  path: 'INBOX',
@@ -1831,14 +1833,7 @@ class Account {
1831
1833
  let path = normalizePath(query.path, delimiter);
1832
1834
  let mailboxData = path === 'INBOX' ? inboxData : false;
1833
1835
  if (!mailboxData) {
1834
- mailboxData = await this.redis.hgetBuffer(this.getMailboxListKey(), path);
1835
- if (mailboxData) {
1836
- try {
1837
- mailboxData = msgpack.decode(mailboxData);
1838
- } catch (err) {
1839
- mailboxData = false;
1840
- }
1841
- }
1836
+ mailboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), path));
1842
1837
  }
1843
1838
 
1844
1839
  let searchQuery = {
@@ -1975,18 +1970,8 @@ class Account {
1975
1970
  }
1976
1971
 
1977
1972
  if (query.path) {
1978
- let inboxData = await this.redis.hgetBuffer(this.getMailboxListKey(), 'INBOX');
1979
- let delimiter;
1980
-
1981
- if (inboxData) {
1982
- try {
1983
- inboxData = msgpack.decode(inboxData);
1984
- delimiter = inboxData.delimiter;
1985
- } catch (err) {
1986
- delimiter = '/'; // hope for the best
1987
- inboxData = false;
1988
- }
1989
- }
1973
+ let inboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), 'INBOX'));
1974
+ let delimiter = inboxData ? inboxData.delimiter : '/'; // hope for the best
1990
1975
 
1991
1976
  inboxData = inboxData || {
1992
1977
  path: 'INBOX',
@@ -1998,14 +1983,7 @@ class Account {
1998
1983
  let path = normalizePath(query.path, delimiter);
1999
1984
  let mailboxData = path === 'INBOX' ? inboxData : false;
2000
1985
  if (!mailboxData) {
2001
- mailboxData = await this.redis.hgetBuffer(this.getMailboxListKey(), path);
2002
- if (mailboxData) {
2003
- try {
2004
- mailboxData = msgpack.decode(mailboxData);
2005
- } catch (err) {
2006
- mailboxData = false;
2007
- }
2008
- }
1986
+ mailboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), path));
2009
1987
  }
2010
1988
 
2011
1989
  searchQuery.bool.must.push({
@@ -0,0 +1,51 @@
1
+ 'use strict';
2
+
3
+ // Server-Sent Events feed of account state changes.
4
+ //
5
+ // Registered here rather than inline in workers/api.js so that it is part of the captured route
6
+ // table (test/api-routes-table-test.js): this endpoint streams every account's state transitions
7
+ // and error strings, and it was the one /v1 route no guardrail could see - a dropped auth block
8
+ // on it would have been invisible.
9
+
10
+ const { openChangeStream } = require('../response-stream');
11
+ const { errorResponses } = require('../schemas');
12
+
13
+ /**
14
+ * Registers the change-stream route.
15
+ *
16
+ * @param {Object} args
17
+ * @param {Object} args.server - Hapi server (or a route-recording mock)
18
+ * @param {Object|Boolean} args.CORS_CONFIG
19
+ */
20
+ async function init(args) {
21
+ const { server, CORS_CONFIG } = args;
22
+
23
+ server.route({
24
+ method: 'GET',
25
+ path: '/v1/changes',
26
+
27
+ // Shared with the admin feed (/admin/changes in workers/api.js)
28
+ handler: openChangeStream,
29
+
30
+ options: {
31
+ description: 'Stream state changes',
32
+ notes: 'Stream account state changes as an EventSource',
33
+ tags: ['api', 'Account'],
34
+
35
+ plugins: {
36
+ 'hapi-swagger': {
37
+ produces: ['text/event-stream'],
38
+ responses: errorResponses(401, 403, 429, 500)
39
+ }
40
+ },
41
+
42
+ auth: {
43
+ strategy: 'api-token',
44
+ mode: 'required'
45
+ },
46
+ cors: CORS_CONFIG
47
+ }
48
+ });
49
+ }
50
+
51
+ module.exports = init;
@@ -0,0 +1,160 @@
1
+ 'use strict';
2
+
3
+ // Single registration point for every REST API route module.
4
+ //
5
+ // workers/api.js used to inline this wiring, which meant nothing could enumerate the API surface
6
+ // without booting a Hapi server (the worker joins the worker-thread message port on require).
7
+ // The admin UI half already had this shape - lib/routes-ui.js is a plain module that
8
+ // test/helpers/capture-ui-routes.js can call against a mock server - and this brings the API half
9
+ // in line, so test/api-routes-table-test.js checks the REAL wiring instead of a hand-maintained
10
+ // mirror of it.
11
+ //
12
+ // Every module receives only the arguments it actually reads. Keep it that way: handing all of
13
+ // them the same bag hides which module depends on what, and hides it from the route-table test too.
14
+
15
+ const templateRoutes = require('./template-routes');
16
+ const chatRoutes = require('./chat-routes');
17
+ const accountRoutes = require('./account-routes');
18
+ const messageRoutes = require('./message-routes');
19
+ const exportRoutes = require('./export-routes');
20
+ const pubsubRoutes = require('./pubsub-routes');
21
+ const tokenRoutes = require('./token-routes');
22
+ const mailboxRoutes = require('./mailbox-routes');
23
+ const settingsRoutes = require('./settings-routes');
24
+ const statsRoutes = require('./stats-routes');
25
+ const licenseRoutes = require('./license-routes');
26
+ const outboxRoutes = require('./outbox-routes');
27
+ const webhookRouteRoutes = require('./webhook-route-routes');
28
+ const oauth2AppRoutes = require('./oauth2-app-routes');
29
+ const gatewayRoutes = require('./gateway-routes');
30
+ const deliveryTestRoutes = require('./delivery-test-routes');
31
+ const blocklistRoutes = require('./blocklist-routes');
32
+ const submitRoutes = require('./submit-routes');
33
+ const changesRoutes = require('./changes-routes');
34
+
35
+ /**
36
+ * Registers every /v1 route module on the supplied Hapi server.
37
+ *
38
+ * @param {Object} args
39
+ * @param {Object} args.server - Hapi server (or a route-recording mock)
40
+ * @param {Function} args.call - RPC helper for talking to the main thread
41
+ * @param {Object} args.notify - notify (webhooks) BullMQ queue
42
+ * @param {Object} args.documentsQueue - documents BullMQ queue
43
+ * @param {Object} args.metrics - Prometheus metrics registry
44
+ * @param {Object|Boolean} args.CORS_CONFIG
45
+ * @param {Array} args.FLAG_SORT_ORDER
46
+ * @param {String} args.SMTP_TEST_HOST
47
+ * @param {Number} args.MAX_ATTACHMENT_SIZE
48
+ * @param {Number} args.MAX_BODY_SIZE
49
+ * @param {Number} args.MAX_PAYLOAD_TIMEOUT
50
+ * @param {Boolean} args.documentStoreFeatureEnabled - gate for the deprecated Document Store
51
+ * @param {Object} args.oauth2Schema
52
+ * @param {Object} args.imapSchema
53
+ * @param {Object} args.smtpSchema
54
+ * @param {Object} args.AccountTypeSchema
55
+ * @param {Object} args.OAuth2ProviderSchema
56
+ */
57
+ async function registerApiRoutes(args) {
58
+ const {
59
+ server,
60
+ call,
61
+ notify,
62
+ documentsQueue,
63
+ metrics,
64
+ CORS_CONFIG,
65
+ FLAG_SORT_ORDER,
66
+ SMTP_TEST_HOST,
67
+ MAX_ATTACHMENT_SIZE,
68
+ MAX_BODY_SIZE,
69
+ MAX_PAYLOAD_TIMEOUT,
70
+ documentStoreFeatureEnabled,
71
+ oauth2Schema,
72
+ imapSchema,
73
+ smtpSchema,
74
+ AccountTypeSchema,
75
+ OAuth2ProviderSchema
76
+ } = args;
77
+
78
+ // setup template routes
79
+ await templateRoutes({ server, call, CORS_CONFIG });
80
+
81
+ // setup "chat with email" routes (deprecated Document Store feature; only when enabled)
82
+ if (documentStoreFeatureEnabled) {
83
+ await chatRoutes({ server, call, CORS_CONFIG });
84
+ }
85
+
86
+ // setup account CRUD routes
87
+ await accountRoutes({
88
+ server,
89
+ call,
90
+ documentsQueue,
91
+ oauth2Schema,
92
+ imapSchema,
93
+ smtpSchema,
94
+ CORS_CONFIG,
95
+ AccountTypeSchema,
96
+ OAuth2ProviderSchema,
97
+ metrics
98
+ });
99
+
100
+ // setup message routes
101
+ await messageRoutes({
102
+ server,
103
+ call,
104
+ CORS_CONFIG,
105
+ MAX_ATTACHMENT_SIZE,
106
+ MAX_BODY_SIZE,
107
+ MAX_PAYLOAD_TIMEOUT,
108
+ documentStoreFeatureEnabled
109
+ });
110
+
111
+ // setup export routes
112
+ await exportRoutes({
113
+ server,
114
+ CORS_CONFIG
115
+ });
116
+
117
+ // setup Pub/Sub status route
118
+ await pubsubRoutes({ server, CORS_CONFIG });
119
+
120
+ // setup access token routes
121
+ await tokenRoutes({ server, call, CORS_CONFIG });
122
+
123
+ // setup mailbox routes
124
+ await mailboxRoutes({ server, call, CORS_CONFIG, FLAG_SORT_ORDER });
125
+
126
+ // setup settings routes
127
+ await settingsRoutes({ server, notify, CORS_CONFIG });
128
+
129
+ // setup stats route
130
+ await statsRoutes({ server, call, CORS_CONFIG });
131
+
132
+ // setup license routes
133
+ await licenseRoutes({ server, call, CORS_CONFIG });
134
+
135
+ // setup outbox routes
136
+ await outboxRoutes({ server, CORS_CONFIG });
137
+
138
+ // setup webhook route management routes
139
+ await webhookRouteRoutes({ server, CORS_CONFIG });
140
+
141
+ // setup OAuth2 application routes
142
+ await oauth2AppRoutes({ server, call, CORS_CONFIG, OAuth2ProviderSchema });
143
+
144
+ // setup SMTP gateway routes
145
+ await gatewayRoutes({ server, call, CORS_CONFIG });
146
+
147
+ // setup delivery test routes
148
+ await deliveryTestRoutes({ server, call, CORS_CONFIG, SMTP_TEST_HOST });
149
+
150
+ // setup blocklist routes
151
+ await blocklistRoutes({ server, call, CORS_CONFIG });
152
+
153
+ // setup message submit route
154
+ await submitRoutes({ server, call, CORS_CONFIG, MAX_ATTACHMENT_SIZE, MAX_BODY_SIZE, MAX_PAYLOAD_TIMEOUT });
155
+
156
+ // setup the account state change stream (SSE)
157
+ await changesRoutes({ server, CORS_CONFIG });
158
+ }
159
+
160
+ module.exports = registerApiRoutes;
package/lib/consts.js CHANGED
@@ -204,6 +204,21 @@ module.exports = {
204
204
  // This is not insecure but it pops out in security scanners, so we need to mask the name of the hash
205
205
  MAILBOX_HASH: Buffer.from('c2hhMQ', 'base64url').toString(),
206
206
 
207
+ // The only fields persisted for each mailbox in the stored listing hash. Anything else
208
+ // ImapFlow reports (flags, status counters, ...) is derived state that lives elsewhere.
209
+ // Used by lib/email-client/imap/listing-diff.js, which also derives its comparison set from
210
+ // this list so that a newly persisted field is automatically compared too.
211
+ STORED_MAILBOX_FIELDS: ['path', 'specialUse', 'name', 'listed', 'subscribed', 'delimiter', 'specialUseSource', 'noInferiors'],
212
+
213
+ // The mailbox fields the /v1/verifyAccount response carries (lib/tools.js). Deliberately a
214
+ // separate list from STORED_MAILBOX_FIELDS even though the two happen to match today: this
215
+ // one is an API contract, declared as `mailboxBaseFields` in lib/schemas.js and validated
216
+ // against `shortMailboxesSchema`, while the other is a storage decision. Sharing one list
217
+ // means adding a persisted field silently publishes it in a documented response that its
218
+ // schema does not declare. `parentPath` is in the schema but not here - it is derived from
219
+ // the path and delimiter after the pick.
220
+ MAILBOX_RESPONSE_FIELDS: ['path', 'specialUse', 'name', 'listed', 'subscribed', 'delimiter', 'specialUseSource', 'noInferiors'],
221
+
207
222
  // nanoseconds
208
223
  ALLOWED_REDIS_LATENCY: 5 * 1000000,
209
224
 
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+
3
+ // Which Gmail send endpoint a message goes to, and how its body is encoded.
4
+ //
5
+ // Extracted from GmailClient.submitMessage() because it is a three-way branch on message size
6
+ // and threading that decides the endpoint, the content type AND the payload encoding, and it is
7
+ // unreachable from a test in place (submitMessage needs a live account, an OAuth app and a
8
+ // BullMQ job). Getting it wrong does not fail loudly: the message is simply rejected by Gmail,
9
+ // or silently loses its thread.
10
+
11
+ const crypto = require('crypto');
12
+
13
+ // The JSON endpoint accepts a 5MB request body, and base64url inflates the raw message by ~4/3,
14
+ // so anything above ~3.5MB raw has to go to the upload endpoint (which takes 35MB raw RFC822).
15
+ const JSON_SEND_LIMIT = 3.5 * 1024 * 1024;
16
+
17
+ /**
18
+ * Builds the Gmail send request for a raw RFC822 message.
19
+ *
20
+ * @param {Buffer} raw - Complete RFC822 message
21
+ * @param {String} [threadId] - Gmail thread to attach the message to
22
+ * @returns {Object} { targetEndpoint, contentType, payload } - endpoint is relative to GMAIL_API_BASE
23
+ */
24
+ function buildSendRequest(raw, threadId) {
25
+ if (raw.length <= JSON_SEND_LIMIT) {
26
+ // JSON endpoint with base64url encoding (retry-safe, no ArrayBuffer issues)
27
+ const payload = { raw: raw.toString('base64url') };
28
+ if (threadId) {
29
+ payload.threadId = threadId;
30
+ }
31
+ return {
32
+ targetEndpoint: `/gmail/v1/users/me/messages/send`,
33
+ contentType: 'application/json',
34
+ payload
35
+ };
36
+ }
37
+
38
+ if (threadId) {
39
+ // Large threaded reply: multipart upload preserves explicit threadId
40
+ // via JSON metadata alongside the raw RFC822 message body
41
+ const boundary = `ee_${crypto.randomBytes(16).toString('hex')}`;
42
+ const metadata = JSON.stringify({ threadId });
43
+ const preamble = Buffer.from(
44
+ `--${boundary}\r\n` +
45
+ `Content-Type: application/json; charset=UTF-8\r\n` +
46
+ `\r\n` +
47
+ `${metadata}\r\n` +
48
+ `--${boundary}\r\n` +
49
+ `Content-Type: message/rfc822\r\n` +
50
+ `\r\n`
51
+ );
52
+ const epilogue = Buffer.from(`\r\n--${boundary}--`);
53
+
54
+ return {
55
+ targetEndpoint: `/upload/gmail/v1/users/me/messages/send?uploadType=multipart`,
56
+ contentType: `multipart/related; boundary=${boundary}`,
57
+ payload: Buffer.concat([preamble, raw, epilogue])
58
+ };
59
+ }
60
+
61
+ // Large non-threaded message: simple upload with raw RFC822 Buffer
62
+ return {
63
+ targetEndpoint: `/upload/gmail/v1/users/me/messages/send`,
64
+ contentType: 'message/rfc822',
65
+ payload: raw
66
+ };
67
+ }
68
+
69
+ module.exports = { buildSendRequest, JSON_SEND_LIMIT };
@@ -11,7 +11,6 @@ const he = require('he');
11
11
  const { BaseClient, metricsMeta } = require('./base-client');
12
12
  const { mimeHtml } = require('@postalsys/email-text-tools');
13
13
  const { emitChangeEvent } = require('../tools');
14
- const crypto = require('crypto');
15
14
  const { Gateway } = require('../gateway');
16
15
 
17
16
  const {
@@ -28,6 +27,7 @@ const {
28
27
  const settings = require('../settings');
29
28
 
30
29
  const { GMAIL_API_BASE, LIST_BATCH_SIZE, request: gmailApiRequest, executeBatchRequests } = require('./gmail/gmail-api');
30
+ const { buildSendRequest } = require('./gmail/send-request');
31
31
 
32
32
  const MAX_GMAIL_BATCH_SIZE = 50;
33
33
 
@@ -1591,46 +1591,9 @@ class GmailClient extends BaseClient {
1591
1591
  return false;
1592
1592
  }
1593
1593
 
1594
- // Gmail JSON endpoint: 5MB body limit (~3.5MB raw before base64url overhead)
1595
- // Gmail upload endpoint: 35MB raw RFC822
1596
- let contentType;
1597
- let payload;
1598
- let targetEndpoint;
1599
- const JSON_SEND_LIMIT = 3.5 * 1024 * 1024;
1600
-
1601
- if (raw.length <= JSON_SEND_LIMIT) {
1602
- // JSON endpoint with base64url encoding (retry-safe, no ArrayBuffer issues)
1603
- contentType = 'application/json';
1604
- payload = { raw: raw.toString('base64url') };
1605
- targetEndpoint = `/gmail/v1/users/me/messages/send`;
1606
- if (data?.reference?.threadId) {
1607
- payload.threadId = data.reference.threadId;
1608
- }
1609
- } else if (data?.reference?.threadId) {
1610
- // Large threaded reply: multipart upload preserves explicit threadId
1611
- // via JSON metadata alongside the raw RFC822 message body
1612
- const boundary = `ee_${crypto.randomBytes(16).toString('hex')}`;
1613
- const metadata = JSON.stringify({ threadId: data.reference.threadId });
1614
- const preamble = Buffer.from(
1615
- `--${boundary}\r\n` +
1616
- `Content-Type: application/json; charset=UTF-8\r\n` +
1617
- `\r\n` +
1618
- `${metadata}\r\n` +
1619
- `--${boundary}\r\n` +
1620
- `Content-Type: message/rfc822\r\n` +
1621
- `\r\n`
1622
- );
1623
- const epilogue = Buffer.from(`\r\n--${boundary}--`);
1624
-
1625
- contentType = `multipart/related; boundary=${boundary}`;
1626
- payload = Buffer.concat([preamble, raw, epilogue]);
1627
- targetEndpoint = `/upload/gmail/v1/users/me/messages/send?uploadType=multipart`;
1628
- } else {
1629
- // Large non-threaded message: simple upload with raw RFC822 Buffer
1630
- contentType = 'message/rfc822';
1631
- payload = raw;
1632
- targetEndpoint = `/upload/gmail/v1/users/me/messages/send`;
1633
- }
1594
+ // Endpoint, content type and payload encoding all depend on the message size and on
1595
+ // whether it belongs to a thread - see lib/email-client/gmail/send-request.js
1596
+ const { targetEndpoint, contentType, payload } = buildSendRequest(raw, data?.reference?.threadId);
1634
1597
 
1635
1598
  // Send via Gmail API
1636
1599
  const submitInfo = await this.request(`${GMAIL_API_BASE}${targetEndpoint}`, 'post', payload, { contentType });
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Strips EmailEngine's handlers from an ImapFlow client that is being abandoned and
5
+ * leaves a permanent 'error' sink behind.
6
+ *
7
+ * ImapFlow reports connection failures with a bare `emit('error')`, so an instance
8
+ * left without an 'error' listener turns the next socket failure into an
9
+ * uncaughtException that takes the whole worker thread down with it. An abandoned
10
+ * client is closed but not yet dead: `close()` returns before the socket teardown
11
+ * finishes, so a reset can still surface a few ticks later. The sink therefore has
12
+ * to outlive `close()` - a `once()` handler only covers the first error and a
13
+ * handler removed right after `close()` covers none at all.
14
+ *
15
+ * @param {EventEmitter} imapClient - Client being abandoned
16
+ * @param {Object} logger - Logger the sink reports through
17
+ * @param {Object} [meta] - Extra fields to log with a sunk error
18
+ */
19
+ function detachImapClient(imapClient, logger, meta) {
20
+ imapClient.removeAllListeners();
21
+
22
+ imapClient.on('error', err => {
23
+ logger.warn({ msg: 'IMAP connection error', ...meta, err });
24
+ });
25
+ }
26
+
27
+ module.exports = { detachImapClient };