emailengine-app 2.74.1 → 2.75.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 (60) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/data/google-crawlers.json +1 -1
  3. package/lib/account.js +117 -63
  4. package/lib/api-routes/changes-routes.js +51 -0
  5. package/lib/api-routes/index.js +160 -0
  6. package/lib/api-routes/message-routes.js +3 -1
  7. package/lib/consts.js +21 -0
  8. package/lib/db.js +4 -1
  9. package/lib/egress-filter.js +220 -0
  10. package/lib/email-client/base-client.js +5 -8
  11. package/lib/email-client/gmail/send-request.js +69 -0
  12. package/lib/email-client/gmail-client.js +6 -46
  13. package/lib/email-client/imap/detach-client.js +27 -0
  14. package/lib/email-client/imap/listing-diff.js +165 -0
  15. package/lib/email-client/imap/mailbox.js +35 -22
  16. package/lib/email-client/imap/subconnection.js +2 -4
  17. package/lib/email-client/imap/sync-operations.js +5 -3
  18. package/lib/email-client/imap-client.js +50 -84
  19. package/lib/email-client/notification-handler.js +11 -12
  20. package/lib/email-client/outlook/send-request.js +48 -0
  21. package/lib/email-client/outlook-client.js +7 -19
  22. package/lib/export.js +97 -21
  23. package/lib/imapproxy/imap-core/README.md +69 -0
  24. package/lib/imapproxy/imap-core/lib/imap-connection.js +1 -1
  25. package/lib/logger.js +14 -6
  26. package/lib/oauth/external-account-config.js +41 -1
  27. package/lib/oauth/external-account-signer.js +7 -2
  28. package/lib/oauth/verify-app.js +18 -3
  29. package/lib/queue-retention.js +56 -0
  30. package/lib/rate-limit.js +33 -11
  31. package/lib/respawn-backoff.js +95 -0
  32. package/lib/response-stream.js +138 -0
  33. package/lib/schemas.js +9 -2
  34. package/lib/sentry.js +8 -0
  35. package/lib/settings.js +4 -1
  36. package/lib/smtp-message-processor.js +131 -0
  37. package/lib/tools.js +48 -5
  38. package/lib/ui-routes/admin-config-routes.js +22 -18
  39. package/lib/ui-routes/internals-routes.js +32 -0
  40. package/lib/utils/network.js +122 -3
  41. package/lib/web-safe-html.js +401 -0
  42. package/lib/webhook-request.js +40 -2
  43. package/lib/webhooks.js +2 -3
  44. package/package.json +15 -13
  45. package/sbom.json +1 -1
  46. package/server.js +33 -8
  47. package/static/js/ee-client.js +55 -6
  48. package/static/js/ui.js +13 -0
  49. package/static/licenses.html +336 -286
  50. package/translations/messages.pot +12 -12
  51. package/views/config/webhooks.hbs +2 -2
  52. package/views/internals/index.hbs +8 -0
  53. package/views/partials/webhooks_editor_functions.hbs +1 -1
  54. package/workers/api.js +52 -233
  55. package/workers/documents.js +6 -0
  56. package/workers/export.js +37 -16
  57. package/workers/imap.js +64 -29
  58. package/workers/smtp.js +50 -91
  59. package/workers/submit.js +10 -0
  60. package/workers/webhooks.js +23 -2
@@ -0,0 +1,220 @@
1
+ 'use strict';
2
+
3
+ const net = require('net');
4
+ const dns = require('dns').promises;
5
+ const ipaddr = require('ipaddr.js');
6
+
7
+ // Egress policies for operator-supplied outbound URLs (webhook targets), least to most
8
+ // restrictive. EmailEngine is usually self-hosted alongside the services it notifies, so
9
+ // blocking private ranges outright would break ordinary deployments - the default therefore only
10
+ // blocks the link-local range, which is where every cloud provider parks its instance metadata
11
+ // service and which no real webhook receiver lives on.
12
+ const POLICY_OFF = 'off';
13
+ const POLICY_LINK_LOCAL = 'link-local';
14
+ const POLICY_PRIVATE = 'private';
15
+
16
+ const VALID_POLICIES = new Set([POLICY_OFF, POLICY_LINK_LOCAL, POLICY_PRIVATE]);
17
+
18
+ // Range names come from ipaddr.js `range()`
19
+ const LINK_LOCAL_BLOCKED_RANGES = new Set(['linkLocal']);
20
+
21
+ const PRIVATE_BLOCKED_RANGES = new Set([
22
+ 'linkLocal',
23
+ 'loopback',
24
+ 'private',
25
+ 'uniqueLocal',
26
+ 'carrierGradeNat',
27
+ 'reserved',
28
+ 'unspecified',
29
+ 'broadcast',
30
+ 'multicast'
31
+ ]);
32
+
33
+ // Metadata endpoints that range classification alone does not catch under the default policy:
34
+ // AWS serves IMDS over IPv6 from a unique-local address, and Alibaba Cloud parks its IMDS in the
35
+ // carrier-grade NAT range. Normalized forms, compared against a normalized subject.
36
+ const ALWAYS_BLOCKED_ADDRESSES = new Set(['fd00:ec2:0:0:0:0:0:254', '100.100.100.200']);
37
+
38
+ /**
39
+ * Resolves the configured egress policy, falling back to the default for unknown values.
40
+ * @param {string} [value] - Raw configured value
41
+ * @returns {string} One of the POLICY_* constants
42
+ */
43
+ function normalizePolicy(value) {
44
+ let policy = (value || '').toString().trim().toLowerCase();
45
+ return VALID_POLICIES.has(policy) ? policy : POLICY_LINK_LOCAL;
46
+ }
47
+
48
+ /**
49
+ * Checks a single IP address against an egress policy.
50
+ *
51
+ * IPv4-mapped IPv6 addresses are unwrapped first, otherwise `::ffff:169.254.169.254` would be
52
+ * classified as a plain IPv6 unicast address and sail through.
53
+ *
54
+ * @param {string} ip - IP address to classify
55
+ * @param {string} policy - One of the POLICY_* constants
56
+ * @returns {boolean} True when the address must not be contacted
57
+ */
58
+ function isBlockedAddress(ip, policy) {
59
+ if (policy === POLICY_OFF) {
60
+ return false;
61
+ }
62
+
63
+ let parsed;
64
+ try {
65
+ parsed = ipaddr.parse(ip);
66
+ } catch (err) {
67
+ // Fail closed: an address we can not classify is not one we should connect to
68
+ return true;
69
+ }
70
+
71
+ if (parsed.kind() === 'ipv6' && parsed.isIPv4MappedAddress()) {
72
+ parsed = parsed.toIPv4Address();
73
+ }
74
+
75
+ if (ALWAYS_BLOCKED_ADDRESSES.has(parsed.toNormalizedString())) {
76
+ return true;
77
+ }
78
+
79
+ const blockedRanges = policy === POLICY_PRIVATE ? PRIVATE_BLOCKED_RANGES : LINK_LOCAL_BLOCKED_RANGES;
80
+
81
+ return blockedRanges.has(parsed.range());
82
+ }
83
+
84
+ /**
85
+ * Builds the error thrown for a blocked destination. Carries `code` so callers can recognize a
86
+ * policy rejection and stop retrying: a blocked target is a configuration problem, and burning
87
+ * ten attempts on it only delays the operator seeing the real reason.
88
+ * @param {string} reason - Human readable explanation
89
+ * @returns {Error} Error tagged with code EEGRESSBLOCKED
90
+ */
91
+ function blockedError(reason) {
92
+ let err = new Error(reason);
93
+ err.code = 'EEGRESSBLOCKED';
94
+ return err;
95
+ }
96
+
97
+ // An operator who does not know this policy exists otherwise has nothing to search for: the
98
+ // message would describe a refusal without naming what is refusing. It also reaches operators who
99
+ // only ever see the log line, which no amount of UI help would.
100
+ const POLICY_HINT = 'See EENGINE_WEBHOOK_EGRESS_POLICY if this destination is intended.';
101
+
102
+ // A destination the policy refuses, as opposed to one we could not parse - the hint belongs on the
103
+ // former only, since the setting cannot help with a malformed URL
104
+ const policyBlockedError = reason => blockedError(`${reason}. ${POLICY_HINT}`);
105
+
106
+ // Verdict cache for resolved hostnames. Node's dns.lookup has no cache of its own and glibc has
107
+ // none either without nscd, so without this every webhook delivery pays a resolver round trip -
108
+ // and the notify worker runs at concurrency 1 by default, so that cost is fully serialized ahead
109
+ // of each POST. Caching the verdict rather than the addresses keeps entries tiny.
110
+ //
111
+ // This gives up nothing: undici resolves the name again independently when it connects, so the
112
+ // check is inherently time-of-check/time-of-use racy and a short TTL introduces no hole that was
113
+ // not already there. Distinct webhook targets are few, so the hit rate is effectively total.
114
+ const VERDICT_TTL = 60 * 1000;
115
+ const VERDICT_CACHE_LIMIT = 1000;
116
+ const verdictCache = new Map();
117
+
118
+ function readCachedVerdict(key) {
119
+ const hit = verdictCache.get(key);
120
+ if (!hit) {
121
+ return null;
122
+ }
123
+
124
+ if (hit.expires <= Date.now()) {
125
+ verdictCache.delete(key);
126
+ return null;
127
+ }
128
+
129
+ return hit;
130
+ }
131
+
132
+ function cacheVerdict(key, blockedBy) {
133
+ // Bounded: drop the oldest entry once full. Map preserves insertion order.
134
+ if (verdictCache.size >= VERDICT_CACHE_LIMIT) {
135
+ verdictCache.delete(verdictCache.keys().next().value);
136
+ }
137
+
138
+ verdictCache.set(key, { blockedBy, expires: Date.now() + VERDICT_TTL });
139
+ }
140
+
141
+ /**
142
+ * Verifies that a URL may be contacted under the given egress policy.
143
+ *
144
+ * Hostnames are resolved and every returned address is checked, so a name that points at a
145
+ * blocked address is rejected just like a literal would be.
146
+ *
147
+ * @param {string} url - Destination URL
148
+ * @param {Object} [opts]
149
+ * @param {string} [opts.policy] - One of the POLICY_* constants, defaults to the link-local policy
150
+ * @param {Function} [opts.resolve] - Injectable resolver returning [{address}], defaults to dns.lookup
151
+ * @returns {Promise<void>} Resolves when the destination is allowed
152
+ * @throws {Error} Tagged with code EEGRESSBLOCKED when the destination is not allowed
153
+ */
154
+ async function assertAllowedUrl(url, opts) {
155
+ const { policy = POLICY_LINK_LOCAL, resolve } = opts || {};
156
+
157
+ if (policy === POLICY_OFF) {
158
+ return;
159
+ }
160
+
161
+ let hostname;
162
+ try {
163
+ hostname = new URL(url).hostname;
164
+ } catch (err) {
165
+ throw blockedError(`Invalid webhook URL: ${url}`);
166
+ }
167
+
168
+ // URL keeps IPv6 literals in brackets, ipaddr.js does not want them
169
+ if (hostname.startsWith('[') && hostname.endsWith(']')) {
170
+ hostname = hostname.slice(1, -1);
171
+ }
172
+
173
+ // A literal needs no resolution, so it is both the cheapest path and never cached
174
+ if (net.isIP(hostname)) {
175
+ if (isBlockedAddress(hostname, policy)) {
176
+ throw policyBlockedError(`Refusing to deliver to a blocked address (${hostname})`);
177
+ }
178
+ return;
179
+ }
180
+
181
+ const cacheKey = `${policy}:${hostname}`;
182
+ const cached = readCachedVerdict(cacheKey);
183
+ if (cached) {
184
+ if (cached.blockedBy) {
185
+ throw policyBlockedError(`Refusing to deliver to ${hostname}, it resolves to a blocked address (${cached.blockedBy})`);
186
+ }
187
+ return;
188
+ }
189
+
190
+ let addresses;
191
+ try {
192
+ addresses = resolve ? await resolve(hostname) : await dns.lookup(hostname, { all: true });
193
+ } catch (err) {
194
+ // A name that does not resolve is a delivery problem, not a policy one. Let the request
195
+ // proceed and fail with the transport's own error so it retries like any other DNS blip.
196
+ // Deliberately not cached, so a resolver blip cannot pin a verdict for a whole minute.
197
+ return;
198
+ }
199
+
200
+ for (let { address } of addresses) {
201
+ if (isBlockedAddress(address, policy)) {
202
+ cacheVerdict(cacheKey, address);
203
+ throw policyBlockedError(`Refusing to deliver to ${hostname}, it resolves to a blocked address (${address})`);
204
+ }
205
+ }
206
+
207
+ cacheVerdict(cacheKey, null);
208
+ }
209
+
210
+ module.exports = {
211
+ assertAllowedUrl,
212
+ isBlockedAddress,
213
+ normalizePolicy,
214
+ // Exported so tests can start from a known state; nothing in production clears the cache,
215
+ // entries simply expire.
216
+ clearVerdictCache: () => verdictCache.clear(),
217
+ POLICY_OFF,
218
+ POLICY_LINK_LOCAL,
219
+ POLICY_PRIVATE
220
+ };
@@ -10,7 +10,8 @@ const { templates } = require('../templates');
10
10
  const { Gateway } = require('../gateway');
11
11
  const os = require('os');
12
12
  const punycode = require('punycode.js');
13
- const { inlineHtml, inlineText, htmlToText, textToHtml, mimeHtml } = require('@postalsys/email-text-tools');
13
+ const { inlineHtml, inlineText, htmlToText, textToHtml } = require('@postalsys/email-text-tools');
14
+ const { messageWebSafeHtml } = require('../web-safe-html');
14
15
  const { randomUUID: uuid } = require('crypto');
15
16
  const { addTrackers } = require('../add-trackers');
16
17
  const { getRawEmail } = require('../get-raw-email');
@@ -67,6 +68,7 @@ const {
67
68
  EMAIL_DELIVERY_ERROR_NOTIFY,
68
69
  EMAIL_SENT_NOTIFY
69
70
  } = require('../consts');
71
+ const { buildRetentionPolicy } = require('../queue-retention');
70
72
 
71
73
  // Configure download chunk size from environment or use default
72
74
  const DOWNLOAD_CHUNK_SIZE = getByteSize(readEnvValue('EENGINE_CHUNK_SIZE')) || DEFAULT_DOWNLOAD_CHUNK_SIZE;
@@ -2060,11 +2062,9 @@ class BaseClient {
2060
2062
 
2061
2063
  // Configure queue job options
2062
2064
  let queueName = 'queued';
2063
- let retention = typeof queueKeep === 'number' ? { age: 24 * 3600, count: queueKeep } : queueKeep;
2064
2065
  let jobOpts = {
2065
2066
  jobId: queueId,
2066
- removeOnComplete: retention,
2067
- removeOnFail: retention,
2067
+ ...buildRetentionPolicy(queueKeep),
2068
2068
  attempts: typeof deliveryAttempts === 'number' ? deliveryAttempts : defaultDeliveryAttempts,
2069
2069
  backoff: {
2070
2070
  type: 'exponential',
@@ -2736,10 +2736,7 @@ class BaseClient {
2736
2736
  let notifyWebSafeHtml = await settings.get('notifyWebSafeHtml');
2737
2737
  if (notifyWebSafeHtml && messageData.text && (messageData.text.html || messageData.text.plain)) {
2738
2738
  // convert to web safe
2739
- messageData.text._generatedHtml = mimeHtml({
2740
- html: messageData.text.html,
2741
- text: messageData.text.plain
2742
- });
2739
+ messageData.text._generatedHtml = await messageWebSafeHtml(messageData);
2743
2740
 
2744
2741
  // embed inline images as data URIs
2745
2742
  if (messageData.text.html && messageData.attachments) {
@@ -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 };
@@ -9,9 +9,8 @@ const addressparser = require('nodemailer/lib/addressparser');
9
9
  const libmime = require('libmime');
10
10
  const he = require('he');
11
11
  const { BaseClient, metricsMeta } = require('./base-client');
12
- const { mimeHtml } = require('@postalsys/email-text-tools');
12
+ const { messageWebSafeHtml } = require('../web-safe-html');
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
 
@@ -1300,10 +1300,7 @@ class GmailClient extends BaseClient {
1300
1300
 
1301
1301
  // Generate web-safe HTML if requested
1302
1302
  if (options.preProcessHtml && formattedMessage.text && (formattedMessage.text.html || formattedMessage.text.plain)) {
1303
- formattedMessage.text.html = mimeHtml({
1304
- html: formattedMessage.text.html,
1305
- text: formattedMessage.text.plain
1306
- });
1303
+ formattedMessage.text.html = await messageWebSafeHtml(formattedMessage);
1307
1304
  formattedMessage.text.webSafe = true;
1308
1305
  }
1309
1306
 
@@ -1591,46 +1588,9 @@ class GmailClient extends BaseClient {
1591
1588
  return false;
1592
1589
  }
1593
1590
 
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
- }
1591
+ // Endpoint, content type and payload encoding all depend on the message size and on
1592
+ // whether it belongs to a thread - see lib/email-client/gmail/send-request.js
1593
+ const { targetEndpoint, contentType, payload } = buildSendRequest(raw, data?.reference?.threadId);
1634
1594
 
1635
1595
  // Send via Gmail API
1636
1596
  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 };
@@ -0,0 +1,165 @@
1
+ 'use strict';
2
+
3
+ // Pure helpers behind IMAPClient.getCurrentListing().
4
+ //
5
+ // Every IMAP sync pass re-runs LIST and has to work out which folders are new, which changed
6
+ // shape, and which disappeared, then persist the result. That comparison is the part worth
7
+ // testing on its own: it is pure, it runs on every sync for every account, and getting it wrong
8
+ // either floods operators with spurious mailboxNew notifications or silently drops folders.
9
+ // The surrounding IO (the LIST call, clearing a deleted folder's index, the Redis write) stays
10
+ // in imap-client.js.
11
+ //
12
+ // Folder paths are compared through normalizePath(), which case-folds INBOX so a server that
13
+ // reports "Inbox" one pass and "INBOX" the next does not look like a delete plus an add.
14
+
15
+ const msgpack = require('msgpack5')();
16
+ const { normalizePath } = require('../../tools');
17
+ const { STORED_MAILBOX_FIELDS } = require('../../consts');
18
+
19
+ // The fields diffMailboxListing() compares, i.e. everything buildStoredListingObject() persists
20
+ // except the path, which is the hash key and therefore equal by construction. Derived from the
21
+ // stored field list so that persisting a new field can not silently leave it uncompared.
22
+ const COMPARED_MAILBOX_FIELDS = STORED_MAILBOX_FIELDS.filter(field => field !== 'path');
23
+
24
+ /**
25
+ * Decodes one msgpack-encoded entry of the stored mailbox listing hash, or returns false if the
26
+ * value is unusable. Callers drop a false entry rather than failing: a single corrupt value must
27
+ * not take down the sync (or the mailboxes API response) for every other folder in the account.
28
+ *
29
+ * The shape check is not redundant with the try/catch. msgpack5 only throws on input it can not
30
+ * parse at all - a corrupt buffer whose first byte happens to be a valid type marker decodes to
31
+ * a plain number or string instead. Such an entry has no `path`, so downstream it would register
32
+ * as a phantom mailbox keyed `undefined` and (via Object.assign onto a primitive) surface as a
33
+ * boxed Number in the mailboxes API response.
34
+ *
35
+ * @param {Buffer} value - msgpack-encoded hash value
36
+ * @returns {Object|false} Decoded mailbox entry, or false when the value is missing or corrupt
37
+ */
38
+ function decodeStoredMailboxEntry(value) {
39
+ let entry;
40
+ try {
41
+ entry = msgpack.decode(value);
42
+ } catch (err) {
43
+ // should not happen
44
+ return false;
45
+ }
46
+ return entry && typeof entry === 'object' && typeof entry.path === 'string' ? entry : false;
47
+ }
48
+
49
+ /**
50
+ * Decodes the msgpack-encoded mailbox listing hash read back from Redis, separating out the
51
+ * entries that did not decode.
52
+ *
53
+ * The corrupt paths are reported rather than just dropped because a dropped entry is invisible to
54
+ * every later step: it is not in the decoded listing, so it can never be matched against a server
55
+ * folder, so it can never register as deleted either. Without an explicit rewrite the bad field
56
+ * survives every sync pass forever while the mailboxes API keeps skipping that folder.
57
+ *
58
+ * @param {Object} storedListing - Redis hash (path -> msgpack Buffer), possibly null
59
+ * @returns {Object} { entries, corruptPaths } - decoded mailbox entries and the unusable fields
60
+ */
61
+ function decodeStoredListing(storedListing) {
62
+ const entries = [];
63
+ const corruptPaths = [];
64
+
65
+ for (let path of Object.keys(storedListing || {})) {
66
+ let entry = decodeStoredMailboxEntry(storedListing[path]);
67
+ if (entry) {
68
+ entries.push(entry);
69
+ } else {
70
+ corruptPaths.push(path);
71
+ }
72
+ }
73
+
74
+ return { entries, corruptPaths };
75
+ }
76
+
77
+ /**
78
+ * Compares a fresh server listing against the stored one.
79
+ *
80
+ * Mutates the entries of `listing`: a folder with no stored counterpart is flagged `isNew`.
81
+ * That flag is the one-shot carrier that makes processListing() emit mailboxNew, so it has to
82
+ * ride on the returned listing rather than being reported separately.
83
+ *
84
+ * @param {Array} listing - Mailbox entries from the server (already filtered of \Noselect)
85
+ * @param {Array} storedListing - Decoded entries previously persisted for this account
86
+ * @returns {Object} { hasChanges, deletedEntries } - deletedEntries are stored folders the
87
+ * server no longer lists, whose message index the caller must clear
88
+ */
89
+ function diffMailboxListing(listing, storedListing) {
90
+ let hasChanges = false;
91
+
92
+ // Map for O(1) lookups - a linear scan per folder is quadratic on accounts with thousands
93
+ // of folders, which is common on shared/public namespaces.
94
+ const storedListingMap = new Map();
95
+ for (const entry of storedListing) {
96
+ storedListingMap.set(normalizePath(entry.path), entry);
97
+ }
98
+
99
+ for (let mailbox of listing) {
100
+ let existingMailbox = storedListingMap.get(normalizePath(mailbox.path));
101
+ if (!existingMailbox) {
102
+ // found new!
103
+ mailbox.isNew = true;
104
+ hasChanges = true;
105
+ } else {
106
+ // Every persisted field has to be compared, not just the structural ones. The
107
+ // mailboxes API answers from the stored hash (Account.getMailboxListing merges only
108
+ // the live status counters onto it), so a field that changed without setting
109
+ // hasChanges is never written back and the stale value is served until some
110
+ // unrelated folder happens to be created or deleted. Unsubscribing a folder moves
111
+ // `subscribed` alone, and modifyMailbox() explicitly refreshes the listing right
112
+ // afterwards expecting exactly that to be picked up.
113
+ for (let field of COMPARED_MAILBOX_FIELDS) {
114
+ if (existingMailbox[field] !== mailbox[field]) {
115
+ hasChanges = true;
116
+ break;
117
+ }
118
+ }
119
+ }
120
+ }
121
+
122
+ // Check for deleted mailboxes
123
+ const listingPathSet = new Set(listing.map(mailbox => normalizePath(mailbox.path)));
124
+ const deletedEntries = storedListing.filter(entry => !listingPathSet.has(normalizePath(entry.path)));
125
+ if (deletedEntries.length) {
126
+ hasChanges = true;
127
+ }
128
+
129
+ return { hasChanges, deletedEntries };
130
+ }
131
+
132
+ /**
133
+ * Builds the Redis hash written back when the listing changed: normalized path -> msgpack of
134
+ * the persisted field subset.
135
+ *
136
+ * The accumulator has a null prototype because folder names are attacker-influenced strings and
137
+ * one of them is special on a plain object: assigning `listingObject['__proto__']` would invoke
138
+ * the Object.prototype setter instead of creating an own property, so Object.keys() (which is
139
+ * how ioredis serializes the hash) would silently omit that folder. It would then look unseen on
140
+ * every following sync: a fresh mailboxNew notification plus a full initial sync of the folder,
141
+ * every pass, forever.
142
+ *
143
+ * @param {Array} listing - Mailbox entries from the server
144
+ * @returns {Object} Hash suitable for HMSET
145
+ */
146
+ function buildStoredListingObject(listing) {
147
+ const listingObject = Object.create(null);
148
+ listing.forEach(entry => {
149
+ let mailbox = {};
150
+ Object.keys(entry).forEach(key => {
151
+ if (STORED_MAILBOX_FIELDS.includes(key)) {
152
+ mailbox[key] = entry[key];
153
+ }
154
+ });
155
+ listingObject[normalizePath(entry.path)] = msgpack.encode(mailbox);
156
+ });
157
+ return listingObject;
158
+ }
159
+
160
+ module.exports = {
161
+ decodeStoredMailboxEntry,
162
+ decodeStoredListing,
163
+ diffMailboxListing,
164
+ buildStoredListingObject
165
+ };