emailengine-app 2.79.0 → 2.79.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/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +79 -0
- package/bin/emailengine.js +8 -1
- package/config/default.toml +6 -0
- package/data/google-crawlers.json +1 -1
- package/lib/account.js +137 -19
- package/lib/api-routes/account-routes.js +13 -1
- package/lib/api-routes/index.js +12 -0
- package/lib/api-routes/mailbox-routes.js +6 -0
- package/lib/api-routes/mcp-oauth-routes.js +259 -0
- package/lib/api-routes/mcp-routes.js +172 -0
- package/lib/api-routes/message-routes.js +125 -4
- package/lib/api-routes/outbox-routes.js +7 -0
- package/lib/api-routes/permission-map.js +101 -1
- package/lib/api-routes/route-helpers.js +87 -4
- package/lib/api-routes/route-metadata.js +24 -4
- package/lib/api-routes/settings-routes.js +37 -14
- package/lib/api-routes/submit-routes.js +41 -0
- package/lib/api-routes/template-routes.js +7 -0
- package/lib/api-routes/token-routes.js +292 -122
- package/lib/arf-detect.js +17 -4
- package/lib/bounce-detect.js +28 -17
- package/lib/consts.js +36 -1
- package/lib/db.js +6 -0
- package/lib/email-client/base-client.js +102 -117
- package/lib/email-client/gmail-client.js +91 -29
- package/lib/email-client/imap/mailbox.js +175 -101
- package/lib/email-client/imap-client.js +49 -2
- package/lib/email-client/outlook-client.js +20 -24
- package/lib/enum-descriptions.js +2 -1
- package/lib/field-usage.js +17 -1
- package/lib/lua/h-set-new-mark.lua +36 -0
- package/lib/lua/s-list-accounts.lua +5 -2
- package/lib/mcp/index.js +29 -0
- package/lib/mcp/inject.js +70 -0
- package/lib/mcp/json-schema.js +120 -0
- package/lib/mcp/listen.js +171 -0
- package/lib/mcp/oauth.js +324 -0
- package/lib/mcp/protocol.js +489 -0
- package/lib/mcp/resources.js +139 -0
- package/lib/mcp/tools.js +655 -0
- package/lib/message-port-stream.js +84 -1
- package/lib/oauth2-apps.js +84 -15
- package/lib/openapi/build-document.js +5 -1
- package/lib/openapi/index.js +3 -1
- package/lib/response-stream.js +52 -21
- package/lib/routes-ui.js +4 -0
- package/lib/schemas.js +26 -5
- package/lib/settings.js +23 -9
- package/lib/token-audit-log.js +32 -9
- package/lib/token-permission-view.js +104 -8
- package/lib/tokens.js +194 -68
- package/lib/tools.js +96 -0
- package/lib/ui-routes/account-routes.js +55 -6
- package/lib/ui-routes/admin-config-routes.js +114 -1
- package/lib/ui-routes/admin-entities-routes.js +103 -19
- package/lib/ui-routes/auth-routes.js +13 -0
- package/lib/ui-routes/mcp-consent-routes.js +330 -0
- package/lib/ui-routes/oauth-config-routes.js +7 -7
- package/lib/ui-routes/route-helpers.js +143 -1
- package/lib/ui-routes/suppression-list-routes.js +14 -9
- package/lib/utils/decode-headers.js +42 -0
- package/lib/utils/header-map.js +48 -0
- package/lib/utils/network.js +9 -1
- package/lib/utils/unsafe-key.js +59 -0
- package/lib/web-safe-html.js +61 -0
- package/lib/webhook-routing.js +6 -2
- package/lib/webhooks.js +31 -8
- package/package.json +9 -8
- package/sbom.json +1 -1
- package/scripts/README.md +25 -0
- package/scripts/build-icon.js +77 -0
- package/server.js +39 -17
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +98 -0
- package/static/emailengine.ico +0 -0
- package/static/js/ui.js +465 -1
- package/static/licenses.html +42 -22
- package/translations/messages.pot +57 -57
- package/views/accounts/account.hbs +8 -8
- package/views/accounts/browse.hbs +1 -1
- package/views/accounts/edit.hbs +2 -2
- package/views/config/mcp.hbs +361 -0
- package/views/config/oauth/index.hbs +7 -0
- package/views/gateways/edit.hbs +1 -1
- package/views/gateways/gateway.hbs +2 -2
- package/views/gateways/index.hbs +7 -7
- package/views/layout/prompt.hbs +62 -0
- package/views/mcp/authorize.hbs +136 -0
- package/views/partials/accounts_table.hbs +7 -7
- package/views/partials/head_assets.hbs +3 -3
- package/views/partials/mcp_access_levels.hbs +13 -0
- package/views/partials/mcp_account_limit.hbs +14 -0
- package/views/partials/mcp_tool_count.hbs +19 -0
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/ui/account-picker.hbs +59 -0
- package/views/partials/ui/code-block.hbs +26 -0
- package/views/partials/ui/menu-item.hbs +5 -0
- package/views/partials/ui/radio.hbs +41 -0
- package/views/partials/ui/tab.hbs +15 -10
- package/views/partials/ui/tabs.hbs +8 -5
- package/views/suppression-lists/list.hbs +1 -1
- package/views/templates/index.hbs +2 -2
- package/views/templates/template.hbs +5 -4
- package/views/tokens/index.hbs +30 -4
- package/views/tokens/new.hbs +517 -239
- package/winconf.js +148 -48
- package/workers/api.js +239 -95
- package/workers/imap.js +65 -72
- package/workers/webhooks.js +21 -1
package/lib/consts.js
CHANGED
|
@@ -171,6 +171,14 @@ module.exports = {
|
|
|
171
171
|
|
|
172
172
|
MAX_INLINE_ATTACHMENT_SIZE: 2 * 1024 * 1024,
|
|
173
173
|
|
|
174
|
+
// How many times processing of the same Gmail history entry may start
|
|
175
|
+
// without finishing before the entry is skipped as poisonous. Only abrupt
|
|
176
|
+
// worker deaths reach this: a thrown error is caught and the cursor
|
|
177
|
+
// advances, a graceful close clears the marker, but an entry that kills the
|
|
178
|
+
// worker (OOM, heartbeat restart) is refetched on restart because the
|
|
179
|
+
// history cursor only moves after processing completes
|
|
180
|
+
GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS: 3,
|
|
181
|
+
|
|
174
182
|
TOTP_WINDOW_SIZE: 6,
|
|
175
183
|
|
|
176
184
|
WEBAUTHN_CHALLENGE_TTL: 300, // 5 minutes
|
|
@@ -207,12 +215,27 @@ module.exports = {
|
|
|
207
215
|
|
|
208
216
|
NONCE_BYTES: 16,
|
|
209
217
|
|
|
218
|
+
// Longest account id EmailEngine accepts. Defined here rather than only on `accountIdSchema`
|
|
219
|
+
// because the token audit log truncates to it while writing, before route validation has had a
|
|
220
|
+
// chance to reject a longer one, and the two have to agree: a log that trimmed at a different
|
|
221
|
+
// length would store a string that names no account while claiming to name one.
|
|
222
|
+
MAX_ACCOUNT_ID_LENGTH: 256,
|
|
223
|
+
|
|
210
224
|
// Class names on the collapse marker web-safe HTML wraps quoted thread history in. Part of the
|
|
211
225
|
// output contract - consumers select on them to style or hide the block - so they are defined
|
|
212
226
|
// once here and referenced by both the generator (lib/web-safe-html.js) and the API docs.
|
|
213
227
|
COLLAPSE_CLASS: 'ee-collapsed-thread',
|
|
214
228
|
COLLAPSE_TOGGLE_CLASS: 'ee-collapsed-thread-toggle',
|
|
215
229
|
|
|
230
|
+
// The largest page an MCP listing tool advertises and accepts, applied through the `bounds`
|
|
231
|
+
// option of a route's plugins.mcp block (lib/mcp/tools.js). The routes themselves keep taking
|
|
232
|
+
// 1000, which is right for a REST client writing the rows somewhere; a model asked to pick a
|
|
233
|
+
// page size picks the maximum it is shown, and 1000 message entries is a tool result large
|
|
234
|
+
// enough to crowd out the conversation it was fetched for. MAX_TOOL_RESULT_BYTES is still the
|
|
235
|
+
// backstop - this is what keeps a normal call from reaching it. Defined once so the five
|
|
236
|
+
// listing tools cannot drift apart on it.
|
|
237
|
+
MCP_MAX_PAGE_SIZE: 100,
|
|
238
|
+
|
|
216
239
|
// We are using a legacy hash function in caching operations
|
|
217
240
|
// This is not insecure but it pops out in security scanners, so we need to mask the name of the hash
|
|
218
241
|
MAILBOX_HASH: Buffer.from('c2hhMQ', 'base64url').toString(),
|
|
@@ -281,7 +304,19 @@ module.exports = {
|
|
|
281
304
|
// each detail context, and `rawPacket` is a TLS-error field that can carry an unparsed
|
|
282
305
|
// credential frame - without these a failed validation writes plaintext passwords, OAuth2
|
|
283
306
|
// client secrets and access tokens into the log, the per-account log store and Sentry.
|
|
284
|
-
|
|
307
|
+
// `req.query.access_token` is here because the api-token scheme accepts the credential as a
|
|
308
|
+
// query argument, and hapi-pino logs the parsed query object with every request - so a client
|
|
309
|
+
// using that form wrote a live token into this instance's own request log. The serialized
|
|
310
|
+
// `req.url` is the pathname only (pino-std-serializers reports `req.path`), so the credential
|
|
311
|
+
// reaches the log through the query object and nowhere else.
|
|
312
|
+
REDACTED_LOG_KEYS: [
|
|
313
|
+
'req.headers.authorization',
|
|
314
|
+
'req.headers.cookie',
|
|
315
|
+
'req.query.access_token',
|
|
316
|
+
'err.rawPacket',
|
|
317
|
+
'err._original',
|
|
318
|
+
'err.details[*].context.value'
|
|
319
|
+
],
|
|
285
320
|
|
|
286
321
|
generateWebhookTable() {
|
|
287
322
|
let entries = [];
|
package/lib/db.js
CHANGED
|
@@ -133,6 +133,7 @@ const hSetBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-bigg
|
|
|
133
133
|
const hUpdateBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-update-bigger.lua'), 'utf-8');
|
|
134
134
|
const hSetExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-exists.lua'), 'utf-8');
|
|
135
135
|
const hSetNewScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-new.lua'), 'utf-8');
|
|
136
|
+
const hSetNewMarkScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-new-mark.lua'), 'utf-8');
|
|
136
137
|
const hIncrbyExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-incrby-exists.lua'), 'utf-8');
|
|
137
138
|
const eeListAddScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-add.lua'), 'utf-8');
|
|
138
139
|
const eeListRemoveScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-remove.lua'), 'utf-8');
|
|
@@ -198,6 +199,11 @@ redis.defineCommand('hSetNew', {
|
|
|
198
199
|
lua: hSetNewScript
|
|
199
200
|
});
|
|
200
201
|
|
|
202
|
+
redis.defineCommand('hSetNewMark', {
|
|
203
|
+
numberOfKeys: 1,
|
|
204
|
+
lua: hSetNewMarkScript
|
|
205
|
+
});
|
|
206
|
+
|
|
201
207
|
redis.defineCommand('hIncrbyExists', {
|
|
202
208
|
numberOfKeys: 1,
|
|
203
209
|
lua: hIncrbyExistsScript
|
|
@@ -51,7 +51,9 @@ const {
|
|
|
51
51
|
filterEmptyObjectValues,
|
|
52
52
|
getDateBuckets,
|
|
53
53
|
resolveCredentials,
|
|
54
|
-
useAuthServerForOAuth2
|
|
54
|
+
useAuthServerForOAuth2,
|
|
55
|
+
collectCidReferences,
|
|
56
|
+
cidReferenceRegex
|
|
55
57
|
} = require('../tools');
|
|
56
58
|
|
|
57
59
|
// Import application constants
|
|
@@ -96,6 +98,91 @@ const TRANSIENT_CONNECT_CODES = new Set([
|
|
|
96
98
|
'UND_ERR_HEADERS_TIMEOUT'
|
|
97
99
|
]);
|
|
98
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Keeps only the address entries a message can actually be delivered to.
|
|
103
|
+
*
|
|
104
|
+
* An address entry may carry a display name and no address at all: RFC 9051 7.5.2 group
|
|
105
|
+
* markers look like that, and so does a server that answered FETCH ENVELOPE after failing
|
|
106
|
+
* to parse a malformed address header. A group name is not a mailbox, so such an entry has
|
|
107
|
+
* to be dropped here rather than travel on as a recipient with an empty address.
|
|
108
|
+
*
|
|
109
|
+
* @param {Object[]|Object} list - Address entries, or the single entry the `from` field holds
|
|
110
|
+
* @returns {Object[]} Entries carrying an address
|
|
111
|
+
*/
|
|
112
|
+
function addressableEntries(list) {
|
|
113
|
+
return [].concat(list || []).filter(entry => entry && entry.address);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Fills in the recipients of a reply or reply-all from the message being answered.
|
|
118
|
+
*
|
|
119
|
+
* Shared by prepareRawMessage() and queueMessageEntry(), which used to carry byte-identical
|
|
120
|
+
* copies of this. `data` is updated in place, and `data.to` is always a list. Falling back
|
|
121
|
+
* to the sender used to assign the bare `from` entry instead, and getRawEmail() maps over
|
|
122
|
+
* the address fields when building the envelope for a structured submission, so a reply to
|
|
123
|
+
* a message carrying no Reply-To threw "data[key]?.map is not a function" on that path.
|
|
124
|
+
*
|
|
125
|
+
* @param {Object} data - Submission payload, updated in place
|
|
126
|
+
* @param {Object} referencedMessage - The message being replied to
|
|
127
|
+
*/
|
|
128
|
+
function applyReferenceRecipients(data, referencedMessage) {
|
|
129
|
+
// Answer the address the message nominates, falling back to whoever sent it
|
|
130
|
+
let replyTo = addressableEntries(referencedMessage.replyTo);
|
|
131
|
+
let answerTo = replyTo.length ? replyTo : addressableEntries(referencedMessage.from);
|
|
132
|
+
|
|
133
|
+
if (!data.to && data.reference.action === 'reply') {
|
|
134
|
+
data.to = answerTo.length ? answerTo : false;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (data.reference.action !== 'reply-all') {
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// answerTo is already a fresh list, so the pushes below cannot reach referencedMessage
|
|
142
|
+
let envelope = {
|
|
143
|
+
to: answerTo,
|
|
144
|
+
cc: [],
|
|
145
|
+
bcc: []
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
// Deduplicate recipients
|
|
149
|
+
let addressesSeen = new Set([].concat(data.from?.address || []).concat(envelope.to.map(addr => addr.address)));
|
|
150
|
+
for (let rcpt of ['to', 'cc', 'bcc']) {
|
|
151
|
+
// A reply-all addresses the people visible on the conversation, so the referenced
|
|
152
|
+
// message contributes its To and Cc but never its Bcc. A Bcc header is normally
|
|
153
|
+
// stripped before transmission, so one that survived is either an artefact of how
|
|
154
|
+
// a copy was filed or, on a message someone else sent us, a header they chose to
|
|
155
|
+
// leave in. Either way nobody on the thread saw it. Copying it put a recipient of
|
|
156
|
+
// the sender's choosing into the reply envelope, and removeBcc() strips the header
|
|
157
|
+
// on the way out, so the sent copy recorded nothing about where the reply went.
|
|
158
|
+
let referenced = rcpt === 'bcc' ? [] : addressableEntries(referencedMessage[rcpt]);
|
|
159
|
+
|
|
160
|
+
for (let addr of referenced.concat(addressableEntries(data[rcpt]))) {
|
|
161
|
+
if (addressesSeen.has(addr.address)) {
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
addressesSeen.add(addr.address);
|
|
165
|
+
envelope[rcpt].push(addr);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (envelope[rcpt].length) {
|
|
169
|
+
data[rcpt] = envelope[rcpt];
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Finds the attachments of a referenced message whose content id the given HTML links to
|
|
175
|
+
function findReferencedCidAttachments(html, attachments) {
|
|
176
|
+
let cidAttachments = [];
|
|
177
|
+
let cidReferences = collectCidReferences(html);
|
|
178
|
+
for (let attachment of attachments || []) {
|
|
179
|
+
if (attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
|
|
180
|
+
cidAttachments.push(attachment);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return cidAttachments;
|
|
184
|
+
}
|
|
185
|
+
|
|
99
186
|
function isTransientNetworkError(err) {
|
|
100
187
|
return !!err && TRANSIENT_CONNECT_CODES.has(err.code);
|
|
101
188
|
}
|
|
@@ -1304,14 +1391,7 @@ class BaseClient {
|
|
|
1304
1391
|
|
|
1305
1392
|
if (inlineMessageData.html) {
|
|
1306
1393
|
// Find inline attachments referenced in HTML
|
|
1307
|
-
|
|
1308
|
-
// find all attachments that are referenced in the HTML
|
|
1309
|
-
for (let attachment of referencedMessage.attachments) {
|
|
1310
|
-
if (attachment.contentId && inlineMessageData.html.indexOf(`cid:${attachment.contentId.replace(/^<|>$/g, '')}`) >= 0) {
|
|
1311
|
-
cidAttachments.push(attachment);
|
|
1312
|
-
}
|
|
1313
|
-
}
|
|
1314
|
-
}
|
|
1394
|
+
cidAttachments = findReferencedCidAttachments(inlineMessageData.html, referencedMessage.attachments);
|
|
1315
1395
|
|
|
1316
1396
|
try {
|
|
1317
1397
|
let html = data.html;
|
|
@@ -1334,54 +1414,8 @@ class BaseClient {
|
|
|
1334
1414
|
}
|
|
1335
1415
|
}
|
|
1336
1416
|
|
|
1337
|
-
// Set
|
|
1338
|
-
|
|
1339
|
-
data.to =
|
|
1340
|
-
referencedMessage.replyTo && referencedMessage.replyTo.length
|
|
1341
|
-
? referencedMessage.replyTo
|
|
1342
|
-
: referencedMessage.from
|
|
1343
|
-
? referencedMessage.from
|
|
1344
|
-
: false;
|
|
1345
|
-
}
|
|
1346
|
-
|
|
1347
|
-
// Handle reply-all recipients
|
|
1348
|
-
if (data.reference.action === 'reply-all') {
|
|
1349
|
-
let envelope = {
|
|
1350
|
-
to: [].concat(
|
|
1351
|
-
referencedMessage.replyTo && referencedMessage.replyTo.length
|
|
1352
|
-
? referencedMessage.replyTo
|
|
1353
|
-
: referencedMessage.from
|
|
1354
|
-
? referencedMessage.from
|
|
1355
|
-
: []
|
|
1356
|
-
),
|
|
1357
|
-
cc: [],
|
|
1358
|
-
bcc: []
|
|
1359
|
-
};
|
|
1360
|
-
|
|
1361
|
-
// Deduplicate recipients
|
|
1362
|
-
let addressesSeen = new Set([].concat(data.from?.address || []).concat(envelope.to.map(addr => addr.address)));
|
|
1363
|
-
for (let rcpt of ['to', 'cc', 'bcc']) {
|
|
1364
|
-
for (let addr of referencedMessage[rcpt] || []) {
|
|
1365
|
-
if (addressesSeen.has(addr.address)) {
|
|
1366
|
-
continue;
|
|
1367
|
-
}
|
|
1368
|
-
addressesSeen.add(addr.address);
|
|
1369
|
-
envelope[rcpt].push(addr);
|
|
1370
|
-
}
|
|
1371
|
-
|
|
1372
|
-
for (let addr of data[rcpt] || []) {
|
|
1373
|
-
if (addressesSeen.has(addr.address)) {
|
|
1374
|
-
continue;
|
|
1375
|
-
}
|
|
1376
|
-
addressesSeen.add(addr.address);
|
|
1377
|
-
envelope[rcpt].push(addr);
|
|
1378
|
-
}
|
|
1379
|
-
|
|
1380
|
-
if (envelope[rcpt].length) {
|
|
1381
|
-
data[rcpt] = envelope[rcpt];
|
|
1382
|
-
}
|
|
1383
|
-
}
|
|
1384
|
-
}
|
|
1417
|
+
// Set the recipients of a reply or reply-all
|
|
1418
|
+
applyReferenceRecipients(data, referencedMessage);
|
|
1385
1419
|
|
|
1386
1420
|
// Determine which attachments to include
|
|
1387
1421
|
let attachmentsToDownload;
|
|
@@ -1807,14 +1841,7 @@ class BaseClient {
|
|
|
1807
1841
|
|
|
1808
1842
|
if (inlineMessageData.html) {
|
|
1809
1843
|
// Find inline attachments referenced in HTML
|
|
1810
|
-
|
|
1811
|
-
// find all attachments that are referenced in the HTML
|
|
1812
|
-
for (let attachment of referencedMessage.attachments) {
|
|
1813
|
-
if (attachment.contentId && inlineMessageData.html.indexOf(`cid:${attachment.contentId.replace(/^<|>$/g, '')}`) >= 0) {
|
|
1814
|
-
cidAttachments.push(attachment);
|
|
1815
|
-
}
|
|
1816
|
-
}
|
|
1817
|
-
}
|
|
1844
|
+
cidAttachments = findReferencedCidAttachments(inlineMessageData.html, referencedMessage.attachments);
|
|
1818
1845
|
|
|
1819
1846
|
try {
|
|
1820
1847
|
let html = data.html;
|
|
@@ -1837,54 +1864,8 @@ class BaseClient {
|
|
|
1837
1864
|
}
|
|
1838
1865
|
}
|
|
1839
1866
|
|
|
1840
|
-
// Set
|
|
1841
|
-
|
|
1842
|
-
data.to =
|
|
1843
|
-
referencedMessage.replyTo && referencedMessage.replyTo.length
|
|
1844
|
-
? referencedMessage.replyTo
|
|
1845
|
-
: referencedMessage.from
|
|
1846
|
-
? referencedMessage.from
|
|
1847
|
-
: false;
|
|
1848
|
-
}
|
|
1849
|
-
|
|
1850
|
-
// Handle reply-all recipients
|
|
1851
|
-
if (data.reference.action === 'reply-all') {
|
|
1852
|
-
let envelope = {
|
|
1853
|
-
to: [].concat(
|
|
1854
|
-
referencedMessage.replyTo && referencedMessage.replyTo.length
|
|
1855
|
-
? referencedMessage.replyTo
|
|
1856
|
-
: referencedMessage.from
|
|
1857
|
-
? referencedMessage.from
|
|
1858
|
-
: []
|
|
1859
|
-
),
|
|
1860
|
-
cc: [],
|
|
1861
|
-
bcc: []
|
|
1862
|
-
};
|
|
1863
|
-
|
|
1864
|
-
// Deduplicate recipients
|
|
1865
|
-
let addressesSeen = new Set([].concat(data.from?.address || []).concat(envelope.to.map(addr => addr.address)));
|
|
1866
|
-
for (let rcpt of ['to', 'cc', 'bcc']) {
|
|
1867
|
-
for (let addr of referencedMessage[rcpt] || []) {
|
|
1868
|
-
if (addressesSeen.has(addr.address)) {
|
|
1869
|
-
continue;
|
|
1870
|
-
}
|
|
1871
|
-
addressesSeen.add(addr.address);
|
|
1872
|
-
envelope[rcpt].push(addr);
|
|
1873
|
-
}
|
|
1874
|
-
|
|
1875
|
-
for (let addr of data[rcpt] || []) {
|
|
1876
|
-
if (addressesSeen.has(addr.address)) {
|
|
1877
|
-
continue;
|
|
1878
|
-
}
|
|
1879
|
-
addressesSeen.add(addr.address);
|
|
1880
|
-
envelope[rcpt].push(addr);
|
|
1881
|
-
}
|
|
1882
|
-
|
|
1883
|
-
if (envelope[rcpt].length) {
|
|
1884
|
-
data[rcpt] = envelope[rcpt];
|
|
1885
|
-
}
|
|
1886
|
-
}
|
|
1887
|
-
}
|
|
1867
|
+
// Set the recipients of a reply or reply-all
|
|
1868
|
+
applyReferenceRecipients(data, referencedMessage);
|
|
1888
1869
|
|
|
1889
1870
|
// Determine which attachments to include
|
|
1890
1871
|
let attachmentsToDownload;
|
|
@@ -2579,13 +2560,14 @@ class BaseClient {
|
|
|
2579
2560
|
// Fetch inline attachments referenced in HTML
|
|
2580
2561
|
if (messageData.attachments && messageData.attachments.length && messageData.text && messageData.text.html) {
|
|
2581
2562
|
// fetch inline attachments
|
|
2563
|
+
let cidReferences = collectCidReferences(messageData.text.html);
|
|
2582
2564
|
for (let attachment of messageData.attachments) {
|
|
2583
2565
|
if (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE) {
|
|
2584
2566
|
// skip large attachments
|
|
2585
2567
|
continue;
|
|
2586
2568
|
}
|
|
2587
2569
|
|
|
2588
|
-
if (!attachment.content && attachment.contentId &&
|
|
2570
|
+
if (!attachment.content && attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
|
|
2589
2571
|
try {
|
|
2590
2572
|
attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
|
|
2591
2573
|
} catch (err) {
|
|
@@ -2826,11 +2808,12 @@ class BaseClient {
|
|
|
2826
2808
|
// embed inline images as data URIs
|
|
2827
2809
|
if (messageData.text.html && messageData.attachments) {
|
|
2828
2810
|
let attachmentList = new Map();
|
|
2811
|
+
let cidReferences = collectCidReferences(messageData.text.html);
|
|
2829
2812
|
|
|
2830
2813
|
// Find CID references in HTML
|
|
2831
2814
|
for (let attachment of messageData.attachments) {
|
|
2832
2815
|
let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
|
|
2833
|
-
if (contentId &&
|
|
2816
|
+
if (contentId && cidReferences.has(contentId)) {
|
|
2834
2817
|
if (attachment.content) {
|
|
2835
2818
|
// already downloaded in a previous step
|
|
2836
2819
|
continue;
|
|
@@ -2847,7 +2830,7 @@ class BaseClient {
|
|
|
2847
2830
|
|
|
2848
2831
|
// Replace CID references with data URIs
|
|
2849
2832
|
if (attachmentList.size) {
|
|
2850
|
-
messageData.text.html = messageData.text.html.replace(
|
|
2833
|
+
messageData.text.html = messageData.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
|
|
2851
2834
|
if (attachmentList.has(cidMatch)) {
|
|
2852
2835
|
let { attachment, content } = attachmentList.get(cidMatch);
|
|
2853
2836
|
if (content) {
|
|
@@ -3394,4 +3377,6 @@ class BaseClient {
|
|
|
3394
3377
|
}
|
|
3395
3378
|
|
|
3396
3379
|
// Re-export postMetrics from notification-handler for backward compatibility
|
|
3397
|
-
|
|
3380
|
+
// applyReferenceRecipients is exported for tests: the methods that call it need a live
|
|
3381
|
+
// account, a connection and a referenced message fetched from the server
|
|
3382
|
+
module.exports = { BaseClient, metricsMeta: postMetrics, applyReferenceRecipients };
|
|
@@ -9,8 +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 { messageWebSafeHtml } = require('../web-safe-html');
|
|
13
|
-
const { emitChangeEvent, toCamelCase } = require('../tools');
|
|
12
|
+
const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
|
|
13
|
+
const { emitChangeEvent, toCamelCase, collectCidReferences, cidReferenceRegex, truncateTextContents } = require('../tools');
|
|
14
14
|
const { Gateway } = require('../gateway');
|
|
15
15
|
|
|
16
16
|
const {
|
|
@@ -21,13 +21,15 @@ const {
|
|
|
21
21
|
REDIS_PREFIX,
|
|
22
22
|
AUTH_ERROR_NOTIFY,
|
|
23
23
|
AUTH_SUCCESS_NOTIFY,
|
|
24
|
-
DEFAULT_GMAIL_EXPORT_BATCH_SIZE
|
|
24
|
+
DEFAULT_GMAIL_EXPORT_BATCH_SIZE,
|
|
25
|
+
GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS
|
|
25
26
|
} = require('../consts');
|
|
26
27
|
|
|
27
28
|
const settings = require('../settings');
|
|
28
29
|
|
|
29
30
|
const { GMAIL_API_BASE, LIST_BATCH_SIZE, request: gmailApiRequest, executeBatchRequests } = require('./gmail/gmail-api');
|
|
30
31
|
const { buildSendRequest, buildDraftSendRequest } = require('./gmail/send-request');
|
|
32
|
+
const { pushHeaderValue } = require('../utils/header-map');
|
|
31
33
|
|
|
32
34
|
const MAX_GMAIL_BATCH_SIZE = 50;
|
|
33
35
|
|
|
@@ -512,6 +514,16 @@ class GmailClient extends BaseClient {
|
|
|
512
514
|
clearTimeout(this.fallbackPollingTimer);
|
|
513
515
|
this.closed = true;
|
|
514
516
|
|
|
517
|
+
// A graceful close means the in-flight history entry did not kill this
|
|
518
|
+
// worker, so it must not keep the strike a deploy or a pause would
|
|
519
|
+
// otherwise leave behind. Guarded because the caller does not await
|
|
520
|
+
// close() - a rejection here would surface as an unhandled rejection
|
|
521
|
+
try {
|
|
522
|
+
await this.redis.hdel(this.getAccountKey(), 'googleHistoryProcessing');
|
|
523
|
+
} catch (err) {
|
|
524
|
+
this.logger.debug({ msg: 'Failed to clear history processing marker', account: this.account, err });
|
|
525
|
+
}
|
|
526
|
+
|
|
515
527
|
// Clean up cached data
|
|
516
528
|
this.cachedLabels = null;
|
|
517
529
|
this.cachedLabelsTime = null;
|
|
@@ -1285,18 +1297,14 @@ class GmailClient extends BaseClient {
|
|
|
1285
1297
|
await this.prepare();
|
|
1286
1298
|
|
|
1287
1299
|
// Enable all enhancements for web-safe HTML
|
|
1288
|
-
|
|
1289
|
-
options.textType = '*';
|
|
1290
|
-
options.embedAttachedImages = true;
|
|
1291
|
-
options.preProcessHtml = true;
|
|
1292
|
-
}
|
|
1300
|
+
applyWebSafeHtmlOptions(options);
|
|
1293
1301
|
|
|
1294
1302
|
const requestQuery = {
|
|
1295
1303
|
format: 'full'
|
|
1296
1304
|
};
|
|
1297
1305
|
const messageData = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${emailId}`, 'get', requestQuery);
|
|
1298
1306
|
|
|
1299
|
-
let formattedMessage = this.formatMessage(messageData, { extended: true, textType: options.textType });
|
|
1307
|
+
let formattedMessage = this.formatMessage(messageData, { extended: true, textType: options.textType, maxBytes: options.maxBytes });
|
|
1300
1308
|
|
|
1301
1309
|
// Resolve label IDs to human-readable names
|
|
1302
1310
|
await this.resolveLabels(formattedMessage);
|
|
@@ -1323,11 +1331,12 @@ class GmailClient extends BaseClient {
|
|
|
1323
1331
|
// Embed inline images as data URIs
|
|
1324
1332
|
if (options.embedAttachedImages && formattedMessage.text?.html && formattedMessage.attachments) {
|
|
1325
1333
|
let attachmentMap = new Map();
|
|
1334
|
+
let cidReferences = collectCidReferences(formattedMessage.text.html);
|
|
1326
1335
|
|
|
1327
1336
|
// Find CID references in HTML
|
|
1328
1337
|
for (let attachment of formattedMessage.attachments) {
|
|
1329
1338
|
let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
|
|
1330
|
-
if (contentId &&
|
|
1339
|
+
if (contentId && cidReferences.has(contentId)) {
|
|
1331
1340
|
attachmentMap.set(contentId, { attachment, content: null });
|
|
1332
1341
|
}
|
|
1333
1342
|
}
|
|
@@ -1340,7 +1349,7 @@ class GmailClient extends BaseClient {
|
|
|
1340
1349
|
}
|
|
1341
1350
|
|
|
1342
1351
|
// Replace CID references with data URIs
|
|
1343
|
-
formattedMessage.text.html = formattedMessage.text.html.replace(
|
|
1352
|
+
formattedMessage.text.html = formattedMessage.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
|
|
1344
1353
|
if (attachmentMap.has(cidMatch)) {
|
|
1345
1354
|
let { content } = attachmentMap.get(cidMatch);
|
|
1346
1355
|
if (content.content) {
|
|
@@ -1387,7 +1396,7 @@ class GmailClient extends BaseClient {
|
|
|
1387
1396
|
try {
|
|
1388
1397
|
const requestQuery = { format: 'full' };
|
|
1389
1398
|
const messageData = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${emailId}`, 'get', requestQuery);
|
|
1390
|
-
const formattedMessage = this.formatMessage(messageData, { extended: true, textType: options.textType });
|
|
1399
|
+
const formattedMessage = this.formatMessage(messageData, { extended: true, textType: options.textType, maxBytes: options.maxBytes });
|
|
1391
1400
|
|
|
1392
1401
|
await this.resolveLabels(formattedMessage, labelMap);
|
|
1393
1402
|
|
|
@@ -1472,7 +1481,7 @@ class GmailClient extends BaseClient {
|
|
|
1472
1481
|
response[key] = textContent[key].map(buf => buf.toString()).join('\n');
|
|
1473
1482
|
}
|
|
1474
1483
|
|
|
1475
|
-
response.hasMore =
|
|
1484
|
+
response.hasMore = truncateTextContents(response, options.maxBytes);
|
|
1476
1485
|
|
|
1477
1486
|
return response;
|
|
1478
1487
|
}
|
|
@@ -2490,7 +2499,7 @@ class GmailClient extends BaseClient {
|
|
|
2490
2499
|
* @returns {Object} Formatted message
|
|
2491
2500
|
*/
|
|
2492
2501
|
formatMessage(messageData, options) {
|
|
2493
|
-
let { extended, path, textType, minimalFields } = options || {};
|
|
2502
|
+
let { extended, path, textType, minimalFields, maxBytes } = options || {};
|
|
2494
2503
|
|
|
2495
2504
|
let date = messageData.internalDate && !isNaN(messageData.internalDate) ? new Date(Number(messageData.internalDate)) : undefined;
|
|
2496
2505
|
if (date?.toString() === 'Invalid Date') {
|
|
@@ -2529,19 +2538,21 @@ class GmailClient extends BaseClient {
|
|
|
2529
2538
|
|
|
2530
2539
|
let envelope = this.getEnvelope(messageData);
|
|
2531
2540
|
|
|
2532
|
-
// Extract all headers
|
|
2541
|
+
// Extract all headers. pushHeaderValue() guards against names that resolve to
|
|
2542
|
+
// Object.prototype members, which would otherwise throw for every fetch of that message
|
|
2533
2543
|
let headers = {};
|
|
2534
2544
|
for (let header of messageData.payload.headers) {
|
|
2535
|
-
|
|
2536
|
-
if (!headers[key]) {
|
|
2537
|
-
headers[key] = [header.value];
|
|
2538
|
-
} else {
|
|
2539
|
-
headers[key].push(header.value);
|
|
2540
|
-
}
|
|
2545
|
+
pushHeaderValue(headers, header.name.toLowerCase(), header.value);
|
|
2541
2546
|
}
|
|
2542
2547
|
|
|
2543
2548
|
const { attachments, textId, encodedTextSize, textContents } = this.getAttachmentList(messageData, { textType });
|
|
2544
2549
|
|
|
2550
|
+
const textValues = {
|
|
2551
|
+
plain: textContents?.[0]?.toString(),
|
|
2552
|
+
html: textContents?.[1]?.toString()
|
|
2553
|
+
};
|
|
2554
|
+
const textHasMore = truncateTextContents(textValues, maxBytes);
|
|
2555
|
+
|
|
2545
2556
|
// Decode snippet preview
|
|
2546
2557
|
let preview;
|
|
2547
2558
|
try {
|
|
@@ -2591,9 +2602,9 @@ class GmailClient extends BaseClient {
|
|
|
2591
2602
|
? {
|
|
2592
2603
|
id: textId,
|
|
2593
2604
|
encodedSize: encodedTextSize,
|
|
2594
|
-
plain:
|
|
2595
|
-
html:
|
|
2596
|
-
hasMore: textContents?.[0] || textContents?.[1] ?
|
|
2605
|
+
plain: textValues.plain,
|
|
2606
|
+
html: textValues.html,
|
|
2607
|
+
hasMore: textContents?.[0] || textContents?.[1] ? textHasMore : undefined
|
|
2597
2608
|
}
|
|
2598
2609
|
: undefined,
|
|
2599
2610
|
|
|
@@ -3033,6 +3044,26 @@ class GmailClient extends BaseClient {
|
|
|
3033
3044
|
let newestHistoryId = currentHistoryId;
|
|
3034
3045
|
let lastHistoryId = currentHistoryId;
|
|
3035
3046
|
|
|
3047
|
+
// The history cursor only advances after an entry is processed, so an
|
|
3048
|
+
// entry that kills the worker (OOM, heartbeat restart) is refetched by
|
|
3049
|
+
// the restarted worker and would loop forever. The in-flight marker
|
|
3050
|
+
// records which entry processing last started on and how many times;
|
|
3051
|
+
// once the limit is hit the entry is skipped with a syncWarning
|
|
3052
|
+
let processingMarker = null;
|
|
3053
|
+
try {
|
|
3054
|
+
processingMarker = JSON.parse(await this.redis.hget(this.getAccountKey(), 'googleHistoryProcessing'));
|
|
3055
|
+
} catch (err) {
|
|
3056
|
+
// no marker or an unreadable one, nothing to resume
|
|
3057
|
+
}
|
|
3058
|
+
|
|
3059
|
+
// advance the durable cursor once an entry is handled (processed or skipped)
|
|
3060
|
+
let advanceHistoryCursor = async historyEntryId => {
|
|
3061
|
+
if (historyEntryId && historyEntryId > lastHistoryId) {
|
|
3062
|
+
await this.redis.hset(this.getAccountKey(), 'googleHistoryId', historyEntryId.toString());
|
|
3063
|
+
lastHistoryId = historyEntryId;
|
|
3064
|
+
}
|
|
3065
|
+
};
|
|
3066
|
+
|
|
3036
3067
|
/**
|
|
3037
3068
|
* Fetches and processes a page of history
|
|
3038
3069
|
* @param {string} pageToken - Pagination token
|
|
@@ -3077,13 +3108,41 @@ class GmailClient extends BaseClient {
|
|
|
3077
3108
|
|
|
3078
3109
|
// Process each history entry
|
|
3079
3110
|
for (let entry of historyRes?.history || []) {
|
|
3111
|
+
let historyEntryId = Number(entry?.id) || null;
|
|
3112
|
+
|
|
3113
|
+
let attempts = processingMarker && entry?.id && String(processingMarker.id) === String(entry.id) ? Number(processingMarker.count) || 0 : 0;
|
|
3114
|
+
if (attempts >= GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS) {
|
|
3115
|
+
// Every attempt to process this entry has taken the worker
|
|
3116
|
+
// down with it. Skip it and advance the cursor so the
|
|
3117
|
+
// account can make progress; the warning names the messages
|
|
3118
|
+
// whose events were lost so they can be recovered manually
|
|
3119
|
+
let messageIds = (entry?.messagesAdded || []).map(added => added?.message?.id).filter(id => id);
|
|
3120
|
+
this.logger.error({
|
|
3121
|
+
msg: 'Skipping history entry that repeatedly killed the worker',
|
|
3122
|
+
account: this.account,
|
|
3123
|
+
entryId: entry?.id,
|
|
3124
|
+
attempts,
|
|
3125
|
+
messageIds
|
|
3126
|
+
});
|
|
3127
|
+
await emitChangeEvent(this.logger, this.account, 'syncWarning', {
|
|
3128
|
+
type: 'historyEntrySkipped',
|
|
3129
|
+
message: 'Processing a history entry repeatedly killed the sync worker, its changes were skipped',
|
|
3130
|
+
historyId: entry?.id,
|
|
3131
|
+
messageIds
|
|
3132
|
+
});
|
|
3133
|
+
await advanceHistoryCursor(historyEntryId);
|
|
3134
|
+
continue;
|
|
3135
|
+
}
|
|
3136
|
+
|
|
3137
|
+
if (entry?.id) {
|
|
3138
|
+
// mark the entry as in flight before touching it, so a
|
|
3139
|
+
// worker death mid-entry is attributable on restart
|
|
3140
|
+
await this.redis.hset(this.getAccountKey(), 'googleHistoryProcessing', JSON.stringify({ id: entry.id, count: attempts + 1 }));
|
|
3141
|
+
}
|
|
3142
|
+
|
|
3080
3143
|
try {
|
|
3081
3144
|
await this.processHistoryEntry(entry);
|
|
3082
|
-
|
|
3083
|
-
if (historyEntryId && historyEntryId > lastHistoryId) {
|
|
3084
|
-
await this.redis.hset(this.getAccountKey(), 'googleHistoryId', historyEntryId.toString());
|
|
3085
|
-
lastHistoryId = historyEntryId;
|
|
3086
|
-
}
|
|
3145
|
+
await advanceHistoryCursor(historyEntryId);
|
|
3087
3146
|
} catch (err) {
|
|
3088
3147
|
this.logger.error({
|
|
3089
3148
|
msg: 'Failed to process history entry',
|
|
@@ -3114,6 +3173,9 @@ class GmailClient extends BaseClient {
|
|
|
3114
3173
|
if (newestHistoryId && newestHistoryId > currentHistoryId) {
|
|
3115
3174
|
await this.redis.hset(this.getAccountKey(), 'googleHistoryId', newestHistoryId.toString());
|
|
3116
3175
|
}
|
|
3176
|
+
|
|
3177
|
+
// the run finished without dying, drop the in-flight marker
|
|
3178
|
+
await this.redis.hdel(this.getAccountKey(), 'googleHistoryProcessing');
|
|
3117
3179
|
}
|
|
3118
3180
|
|
|
3119
3181
|
/**
|