emailengine-app 2.79.1 → 2.79.3
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/.github/workflows/deploy.yml +92 -39
- package/.github/workflows/release.yaml +94 -34
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +85 -0
- package/bin/emailengine.js +8 -1
- package/config/default.toml +6 -0
- package/copy-static-files.sh +23 -2
- package/data/google-crawlers.json +1 -1
- package/lib/account.js +138 -18
- 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 +97 -1
- package/lib/api-routes/route-helpers.js +16 -4
- package/lib/api-routes/route-metadata.js +24 -4
- 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 +4 -2
- package/lib/consts.js +30 -1
- package/lib/email-client/base-client.js +235 -163
- package/lib/email-client/gmail-client.js +99 -22
- package/lib/email-client/imap/mailbox.js +140 -66
- package/lib/email-client/imap-client.js +74 -68
- package/lib/email-client/outlook-client.js +29 -14
- package/lib/enum-descriptions.js +2 -1
- package/lib/field-usage.js +17 -1
- package/lib/logger.js +43 -3
- 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/openapi/index.js +3 -1
- package/lib/response-stream.js +52 -21
- package/lib/routes-ui.js +4 -0
- package/lib/schemas.js +24 -3
- package/lib/token-permission-view.js +104 -8
- package/lib/tokens.js +34 -5
- package/lib/tools.js +96 -0
- package/lib/ui-routes/account-routes.js +43 -1
- package/lib/ui-routes/admin-config-routes.js +114 -1
- package/lib/ui-routes/admin-entities-routes.js +54 -5
- package/lib/ui-routes/auth-routes.js +13 -0
- package/lib/ui-routes/mcp-consent-routes.js +330 -0
- package/lib/ui-routes/route-helpers.js +116 -1
- package/lib/utils/network.js +9 -1
- package/lib/web-safe-html.js +61 -0
- package/lib/webhooks.js +3 -8
- package/package.json +15 -14
- package/sbom.json +1 -1
- package/scripts/README.md +25 -0
- package/scripts/build-icon.js +77 -0
- package/server.js +21 -9
- 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 +85 -135
- package/translations/messages.pot +103 -103
- package/views/config/mcp.hbs +361 -0
- package/views/config/oauth/index.hbs +7 -0
- package/views/layout/prompt.hbs +62 -0
- package/views/mcp/authorize.hbs +136 -0
- 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/templates/template.hbs +4 -3
- package/views/tokens/index.hbs +8 -2
- package/views/tokens/new.hbs +514 -243
- package/winconf.js +148 -48
- package/workers/api.js +198 -48
|
@@ -124,6 +124,47 @@ async function init(args) {
|
|
|
124
124
|
tags: ['api', 'Submit'],
|
|
125
125
|
|
|
126
126
|
plugins: {
|
|
127
|
+
mcp: {
|
|
128
|
+
name: 'send_message',
|
|
129
|
+
title: 'Send message',
|
|
130
|
+
description:
|
|
131
|
+
'Send an email from the account to real recipients - confirm with the user before calling this. Takes structured fields (to, subject, text, html). ' +
|
|
132
|
+
'To answer or pass on a message the user is looking at, set `reference.message` to its id and `reference.action` to reply, reply-all or forward, ' +
|
|
133
|
+
'and write only the new text: the subject, the recipients (for a reply) and the threading headers come from the referenced message. ' +
|
|
134
|
+
'Add `reference.inline` to quote the original under it, and `reference.forwardAttachments` to carry its attachments along when forwarding. ' +
|
|
135
|
+
'Delivery is queued; the response carries the queue id for get_outbox.',
|
|
136
|
+
// An allowlist, not a deny list. The submit payload is the widest one in the
|
|
137
|
+
// API and it grows; with `omit` a field added here later would join the
|
|
138
|
+
// agent-facing schema by default, which fails open on the one tool that
|
|
139
|
+
// reaches people outside the mailbox.
|
|
140
|
+
//
|
|
141
|
+
// What is kept is the message an agent composes: who it goes to, what it
|
|
142
|
+
// says, what it answers, what it carries and when it leaves. What is not is a
|
|
143
|
+
// decision the operator made when they connected the account - routing,
|
|
144
|
+
// tracking, bounce handling, whether the sent copy is filed - plus every way
|
|
145
|
+
// around the structured fields (`raw` replaces the whole message, `envelope`
|
|
146
|
+
// overrides the SMTP conversation, `headers`/`messageId` set headers
|
|
147
|
+
// EmailEngine derives) and `mailMerge`, which would turn one call into a bulk
|
|
148
|
+
// send to a recipient list - not what "confirm before sending" protects
|
|
149
|
+
// against. An agent that should mail several people calls the tool several
|
|
150
|
+
// times, where each send is visible as a send.
|
|
151
|
+
keep: [
|
|
152
|
+
'account',
|
|
153
|
+
'reference',
|
|
154
|
+
'from',
|
|
155
|
+
'replyTo',
|
|
156
|
+
'to',
|
|
157
|
+
'cc',
|
|
158
|
+
'bcc',
|
|
159
|
+
'subject',
|
|
160
|
+
'text',
|
|
161
|
+
'html',
|
|
162
|
+
'template',
|
|
163
|
+
'render',
|
|
164
|
+
'attachments',
|
|
165
|
+
'sendAt'
|
|
166
|
+
]
|
|
167
|
+
},
|
|
127
168
|
openapi: {
|
|
128
169
|
'x-ee-impact': IMPACT.SENDS,
|
|
129
170
|
'x-ee-behavior': [BEHAVIOR.QUEUED_DELIVERY, BEHAVIOR.SENT_FOLDER_UPLOAD],
|
|
@@ -10,6 +10,7 @@ const { handleError, throwNotFound } = require('./route-helpers');
|
|
|
10
10
|
|
|
11
11
|
const { templateSchemas, accountIdSchema, apiResponses } = require('../schemas');
|
|
12
12
|
const { IMPACT } = require('./operation-impact');
|
|
13
|
+
const { MCP_MAX_PAGE_SIZE } = require('../consts');
|
|
13
14
|
|
|
14
15
|
// Template owner field shared by all template response schemas
|
|
15
16
|
const templateAccountIdSchema = accountIdSchema.required().allow(null).description('Account ID. Null for public templates');
|
|
@@ -226,6 +227,12 @@ async function init(args) {
|
|
|
226
227
|
tags: ['api', 'Templates'],
|
|
227
228
|
|
|
228
229
|
plugins: {
|
|
230
|
+
mcp: {
|
|
231
|
+
name: 'list_templates',
|
|
232
|
+
title: 'List templates',
|
|
233
|
+
description: 'List stored email templates, paged. Pass an account id for account-specific templates or omit it for shared ones.',
|
|
234
|
+
bounds: { pageSize: MCP_MAX_PAGE_SIZE }
|
|
235
|
+
},
|
|
229
236
|
openapi: {
|
|
230
237
|
responses: apiResponses('Returns a page of stored templates for the account.', 400, 401, 403, 404, 429, 500)
|
|
231
238
|
}
|
|
@@ -123,11 +123,13 @@ async function init(args) {
|
|
|
123
123
|
description: Joi.string().empty('').trim().max(1024).required().example('Token description').description('Token description'),
|
|
124
124
|
|
|
125
125
|
scopes: Joi.array()
|
|
126
|
-
.items(Joi.string().valid('api', 'smtp', 'imap-proxy').meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenScope }).label('TokenScope'))
|
|
126
|
+
.items(Joi.string().valid('api', 'smtp', 'imap-proxy', 'mcp').meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenScope }).label('TokenScope'))
|
|
127
127
|
.single()
|
|
128
128
|
.default(['api'])
|
|
129
129
|
.required()
|
|
130
|
-
.description(
|
|
130
|
+
.description(
|
|
131
|
+
'Token permission scopes: "api" for REST API access, "smtp" for SMTP submission, "imap-proxy" for IMAP proxy authentication, "mcp" for the MCP endpoint only'
|
|
132
|
+
)
|
|
131
133
|
.label('Scopes'),
|
|
132
134
|
|
|
133
135
|
metadata: tokenMetadataSchema,
|
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
|
|
@@ -219,6 +227,15 @@ module.exports = {
|
|
|
219
227
|
COLLAPSE_CLASS: 'ee-collapsed-thread',
|
|
220
228
|
COLLAPSE_TOGGLE_CLASS: 'ee-collapsed-thread-toggle',
|
|
221
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
|
+
|
|
222
239
|
// We are using a legacy hash function in caching operations
|
|
223
240
|
// This is not insecure but it pops out in security scanners, so we need to mask the name of the hash
|
|
224
241
|
MAILBOX_HASH: Buffer.from('c2hhMQ', 'base64url').toString(),
|
|
@@ -287,7 +304,19 @@ module.exports = {
|
|
|
287
304
|
// each detail context, and `rawPacket` is a TLS-error field that can carry an unparsed
|
|
288
305
|
// credential frame - without these a failed validation writes plaintext passwords, OAuth2
|
|
289
306
|
// client secrets and access tokens into the log, the per-account log store and Sentry.
|
|
290
|
-
|
|
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
|
+
],
|
|
291
320
|
|
|
292
321
|
generateWebhookTable() {
|
|
293
322
|
let entries = [];
|
|
@@ -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
|
}
|
|
@@ -399,9 +486,14 @@ class BaseClient {
|
|
|
399
486
|
/**
|
|
400
487
|
* Sets error state and manages error tracking/notifications
|
|
401
488
|
* Implements logic to disable IMAP after repeated authentication failures
|
|
489
|
+
*
|
|
490
|
+
* The return value drives whether the caller sends a webhook. That is normally "is this a new
|
|
491
|
+
* error", so a run of identical failures is reported once - but it is also true when this call
|
|
492
|
+
* is the one that switches the account off, which is not a new error and still has to be heard.
|
|
493
|
+
*
|
|
402
494
|
* @param {string} event - Error event type
|
|
403
495
|
* @param {Object} data - Error details
|
|
404
|
-
* @returns {boolean} Whether
|
|
496
|
+
* @returns {boolean} Whether the caller should notify
|
|
405
497
|
*/
|
|
406
498
|
async setErrorState(event, data) {
|
|
407
499
|
// Retrieve previous error state for comparison
|
|
@@ -417,7 +509,7 @@ class BaseClient {
|
|
|
417
509
|
this.state = event;
|
|
418
510
|
await this.setStateVal();
|
|
419
511
|
|
|
420
|
-
let
|
|
512
|
+
let shouldNotify = true;
|
|
421
513
|
|
|
422
514
|
// Store current error state
|
|
423
515
|
await this.redis.hSetExists(this.getAccountKey(), 'lastErrorState', JSON.stringify(data));
|
|
@@ -429,12 +521,12 @@ class BaseClient {
|
|
|
429
521
|
|
|
430
522
|
if (data.serverResponseCode && data.serverResponseCode === prevLastErrorState.serverResponseCode) {
|
|
431
523
|
// error code did not change, assume it is the same error
|
|
432
|
-
|
|
524
|
+
shouldNotify = false;
|
|
433
525
|
} else {
|
|
434
526
|
try {
|
|
435
527
|
deepEqual(data, prevLastErrorState);
|
|
436
528
|
// nothing changed
|
|
437
|
-
|
|
529
|
+
shouldNotify = false;
|
|
438
530
|
} catch (err) {
|
|
439
531
|
// seems different
|
|
440
532
|
}
|
|
@@ -442,7 +534,7 @@ class BaseClient {
|
|
|
442
534
|
}
|
|
443
535
|
|
|
444
536
|
// Track error occurrences
|
|
445
|
-
if (
|
|
537
|
+
if (shouldNotify) {
|
|
446
538
|
const txn = createTransaction(this.redis, { logger: this.logger });
|
|
447
539
|
txn.add('hSetExists', this.getAccountKey(), 'lastError:errorCount', 1);
|
|
448
540
|
txn.add('hSetExists', this.getAccountKey(), 'lastError:first', new Date().toISOString());
|
|
@@ -473,53 +565,135 @@ class BaseClient {
|
|
|
473
565
|
switch (event) {
|
|
474
566
|
case 'authenticationError':
|
|
475
567
|
if (errorCount > 0 && firstError && Date.now() - firstError.getTime() > MAX_IMAP_AUTH_FAILURE_TIME) {
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
if (imapData && !imapData.disabled) {
|
|
487
|
-
imapData.disabled = true;
|
|
488
|
-
|
|
489
|
-
// Disable IMAP and reset error counters
|
|
490
|
-
const disableTxn = createTransaction(this.redis, { logger: this.logger });
|
|
491
|
-
disableTxn.add('hSetExists', this.getAccountKey(), 'imap', JSON.stringify(imapData));
|
|
492
|
-
disableTxn.add('hdel', this.getAccountKey(), 'lastError:errorCount', 'lastError:first');
|
|
493
|
-
disableTxn.add(
|
|
494
|
-
'hSetExists',
|
|
495
|
-
this.getAccountKey(),
|
|
496
|
-
'lastErrorState',
|
|
497
|
-
JSON.stringify({
|
|
498
|
-
description: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
|
|
499
|
-
response: data.response
|
|
500
|
-
})
|
|
501
|
-
);
|
|
502
|
-
await disableTxn.exec();
|
|
503
|
-
|
|
504
|
-
this.logger.warn({
|
|
505
|
-
msg: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
|
|
506
|
-
errorEvent: event,
|
|
507
|
-
firstError: firstError.toISOString(),
|
|
508
|
-
timeThreshold: MAX_IMAP_AUTH_FAILURE_TIME,
|
|
509
|
-
errorCount
|
|
510
|
-
});
|
|
511
|
-
|
|
512
|
-
// Close the connection after disabling
|
|
513
|
-
setImmediate(() => {
|
|
514
|
-
this.close();
|
|
515
|
-
});
|
|
568
|
+
const disabled = await this.disableAfterAuthFailures({ event, firstError, errorCount, data });
|
|
569
|
+
if (disabled) {
|
|
570
|
+
// Report it. This branch only runs for a repeat of an error the caller
|
|
571
|
+
// has already been told about, and would normally suppress the webhook
|
|
572
|
+
// as unchanged - but an account going offline until a human
|
|
573
|
+
// re-authenticates it is the one thing here an operator has to hear
|
|
574
|
+
// about, and until now it happened in silence.
|
|
575
|
+
shouldNotify = true;
|
|
516
576
|
}
|
|
517
577
|
}
|
|
518
578
|
break;
|
|
519
579
|
}
|
|
520
580
|
}
|
|
521
581
|
|
|
522
|
-
return
|
|
582
|
+
return shouldNotify;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Whether mail sync has been switched off for this account, by the operator or by the
|
|
587
|
+
* auth-failure safety net in setErrorState().
|
|
588
|
+
*
|
|
589
|
+
* Reads the flag straight out of Redis rather than through loadAccountData(), so a client can
|
|
590
|
+
* ask before it does any credential work. That ordering is the point: an account is switched
|
|
591
|
+
* off precisely because that work keeps failing, and for an OAuth2 account the failing work is
|
|
592
|
+
* a token refresh against the provider.
|
|
593
|
+
*
|
|
594
|
+
* @returns {Promise<Boolean>} True when the account must not connect
|
|
595
|
+
*/
|
|
596
|
+
async isSyncDisabled() {
|
|
597
|
+
const imapInfo = await this.redis.hget(this.getAccountKey(), 'imap');
|
|
598
|
+
if (!imapInfo) {
|
|
599
|
+
return false;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
try {
|
|
603
|
+
return !!JSON.parse(imapInfo).disabled;
|
|
604
|
+
} catch (err) {
|
|
605
|
+
// An unreadable blob is not a disable; stay noisy and let the connection proceed.
|
|
606
|
+
this.logger.error({ msg: 'Failed parsing IMAP data', err });
|
|
607
|
+
return false;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* Stops an account retrying after it has failed authentication for longer than
|
|
613
|
+
* MAX_IMAP_AUTH_FAILURE_TIME, until someone re-authenticates it.
|
|
614
|
+
*
|
|
615
|
+
* `imap.disabled` is the flag every gate in the codebase already reads, so an OAuth2 account -
|
|
616
|
+
* which has no `imap` configuration of its own, because getImapConfig() builds its connection
|
|
617
|
+
* from the provider table instead - gets one written holding nothing but the flag. Both kinds
|
|
618
|
+
* of account then take the identical path through the connection gates and the admin UI's
|
|
619
|
+
* disabled-account handling. Writing it cannot disturb an OAuth2 connection config:
|
|
620
|
+
* getImapConfig() branches on `oauth2` first and only reads `accountData.imap` for password
|
|
621
|
+
* accounts.
|
|
622
|
+
*
|
|
623
|
+
* Before this, the whole block was gated on an `imap` blob already being present. OAuth2
|
|
624
|
+
* accounts never have one, so on a deployment that is mostly Gmail and Microsoft the documented
|
|
625
|
+
* three-day safety net was a silent no-op: an account whose refresh token had been revoked kept
|
|
626
|
+
* asking for a new one forever.
|
|
627
|
+
*
|
|
628
|
+
* @param {Object} opts
|
|
629
|
+
* @param {String} opts.event - The error event that tripped the threshold
|
|
630
|
+
* @param {Date} opts.firstError - When the current run of failures started
|
|
631
|
+
* @param {Number} opts.errorCount - How many failures have been counted since
|
|
632
|
+
* @param {Object} opts.data - Error payload for the account's stored error state
|
|
633
|
+
* @returns {Promise<Boolean>} True when this call is what disabled the account
|
|
634
|
+
*/
|
|
635
|
+
async disableAfterAuthFailures({ event, firstError, errorCount, data }) {
|
|
636
|
+
const accountKey = this.getAccountKey();
|
|
637
|
+
|
|
638
|
+
let imapData;
|
|
639
|
+
const imapInfo = await this.redis.hget(accountKey, 'imap');
|
|
640
|
+
if (imapInfo) {
|
|
641
|
+
try {
|
|
642
|
+
imapData = JSON.parse(imapInfo);
|
|
643
|
+
} catch (err) {
|
|
644
|
+
// Rewriting a blob that does not parse would replace the account's IMAP
|
|
645
|
+
// configuration with a bare flag, so leave it alone and stay noisy instead.
|
|
646
|
+
this.logger.error({ msg: 'Failed parsing IMAP data', err });
|
|
647
|
+
return false;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
if (!imapData) {
|
|
652
|
+
// No IMAP configuration: an OAuth2 account. Only synthesize the flag when there is an
|
|
653
|
+
// OAuth2 credential for the failures to be about, so an account still being created
|
|
654
|
+
// cannot be marked disabled on its way in.
|
|
655
|
+
const hasOAuth2 = await this.redis.hexists(accountKey, 'oauth2');
|
|
656
|
+
if (!hasOAuth2) {
|
|
657
|
+
return false;
|
|
658
|
+
}
|
|
659
|
+
imapData = {};
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
if (imapData.disabled) {
|
|
663
|
+
return false;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
imapData.disabled = true;
|
|
667
|
+
|
|
668
|
+
// Disable IMAP and reset error counters
|
|
669
|
+
const disableTxn = createTransaction(this.redis, { logger: this.logger });
|
|
670
|
+
disableTxn.add('hSetExists', accountKey, 'imap', JSON.stringify(imapData));
|
|
671
|
+
disableTxn.add('hdel', accountKey, 'lastError:errorCount', 'lastError:first');
|
|
672
|
+
disableTxn.add(
|
|
673
|
+
'hSetExists',
|
|
674
|
+
accountKey,
|
|
675
|
+
'lastErrorState',
|
|
676
|
+
JSON.stringify({
|
|
677
|
+
description: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
|
|
678
|
+
response: data.response
|
|
679
|
+
})
|
|
680
|
+
);
|
|
681
|
+
await disableTxn.exec();
|
|
682
|
+
|
|
683
|
+
this.logger.warn({
|
|
684
|
+
msg: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
|
|
685
|
+
errorEvent: event,
|
|
686
|
+
firstError: firstError.toISOString(),
|
|
687
|
+
timeThreshold: MAX_IMAP_AUTH_FAILURE_TIME,
|
|
688
|
+
errorCount
|
|
689
|
+
});
|
|
690
|
+
|
|
691
|
+
// Close the connection after disabling
|
|
692
|
+
setImmediate(() => {
|
|
693
|
+
this.close();
|
|
694
|
+
});
|
|
695
|
+
|
|
696
|
+
return true;
|
|
523
697
|
}
|
|
524
698
|
|
|
525
699
|
/**
|
|
@@ -1304,14 +1478,7 @@ class BaseClient {
|
|
|
1304
1478
|
|
|
1305
1479
|
if (inlineMessageData.html) {
|
|
1306
1480
|
// 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
|
-
}
|
|
1481
|
+
cidAttachments = findReferencedCidAttachments(inlineMessageData.html, referencedMessage.attachments);
|
|
1315
1482
|
|
|
1316
1483
|
try {
|
|
1317
1484
|
let html = data.html;
|
|
@@ -1334,54 +1501,8 @@ class BaseClient {
|
|
|
1334
1501
|
}
|
|
1335
1502
|
}
|
|
1336
1503
|
|
|
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
|
-
}
|
|
1504
|
+
// Set the recipients of a reply or reply-all
|
|
1505
|
+
applyReferenceRecipients(data, referencedMessage);
|
|
1385
1506
|
|
|
1386
1507
|
// Determine which attachments to include
|
|
1387
1508
|
let attachmentsToDownload;
|
|
@@ -1807,14 +1928,7 @@ class BaseClient {
|
|
|
1807
1928
|
|
|
1808
1929
|
if (inlineMessageData.html) {
|
|
1809
1930
|
// 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
|
-
}
|
|
1931
|
+
cidAttachments = findReferencedCidAttachments(inlineMessageData.html, referencedMessage.attachments);
|
|
1818
1932
|
|
|
1819
1933
|
try {
|
|
1820
1934
|
let html = data.html;
|
|
@@ -1837,54 +1951,8 @@ class BaseClient {
|
|
|
1837
1951
|
}
|
|
1838
1952
|
}
|
|
1839
1953
|
|
|
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
|
-
}
|
|
1954
|
+
// Set the recipients of a reply or reply-all
|
|
1955
|
+
applyReferenceRecipients(data, referencedMessage);
|
|
1888
1956
|
|
|
1889
1957
|
// Determine which attachments to include
|
|
1890
1958
|
let attachmentsToDownload;
|
|
@@ -2579,13 +2647,14 @@ class BaseClient {
|
|
|
2579
2647
|
// Fetch inline attachments referenced in HTML
|
|
2580
2648
|
if (messageData.attachments && messageData.attachments.length && messageData.text && messageData.text.html) {
|
|
2581
2649
|
// fetch inline attachments
|
|
2650
|
+
let cidReferences = collectCidReferences(messageData.text.html);
|
|
2582
2651
|
for (let attachment of messageData.attachments) {
|
|
2583
2652
|
if (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE) {
|
|
2584
2653
|
// skip large attachments
|
|
2585
2654
|
continue;
|
|
2586
2655
|
}
|
|
2587
2656
|
|
|
2588
|
-
if (!attachment.content && attachment.contentId &&
|
|
2657
|
+
if (!attachment.content && attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
|
|
2589
2658
|
try {
|
|
2590
2659
|
attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
|
|
2591
2660
|
} catch (err) {
|
|
@@ -2826,11 +2895,12 @@ class BaseClient {
|
|
|
2826
2895
|
// embed inline images as data URIs
|
|
2827
2896
|
if (messageData.text.html && messageData.attachments) {
|
|
2828
2897
|
let attachmentList = new Map();
|
|
2898
|
+
let cidReferences = collectCidReferences(messageData.text.html);
|
|
2829
2899
|
|
|
2830
2900
|
// Find CID references in HTML
|
|
2831
2901
|
for (let attachment of messageData.attachments) {
|
|
2832
2902
|
let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
|
|
2833
|
-
if (contentId &&
|
|
2903
|
+
if (contentId && cidReferences.has(contentId)) {
|
|
2834
2904
|
if (attachment.content) {
|
|
2835
2905
|
// already downloaded in a previous step
|
|
2836
2906
|
continue;
|
|
@@ -2847,7 +2917,7 @@ class BaseClient {
|
|
|
2847
2917
|
|
|
2848
2918
|
// Replace CID references with data URIs
|
|
2849
2919
|
if (attachmentList.size) {
|
|
2850
|
-
messageData.text.html = messageData.text.html.replace(
|
|
2920
|
+
messageData.text.html = messageData.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
|
|
2851
2921
|
if (attachmentList.has(cidMatch)) {
|
|
2852
2922
|
let { attachment, content } = attachmentList.get(cidMatch);
|
|
2853
2923
|
if (content) {
|
|
@@ -3394,4 +3464,6 @@ class BaseClient {
|
|
|
3394
3464
|
}
|
|
3395
3465
|
|
|
3396
3466
|
// Re-export postMetrics from notification-handler for backward compatibility
|
|
3397
|
-
|
|
3467
|
+
// applyReferenceRecipients is exported for tests: the methods that call it need a live
|
|
3468
|
+
// account, a connection and a referenced message fetched from the server
|
|
3469
|
+
module.exports = { BaseClient, metricsMeta: postMetrics, applyReferenceRecipients };
|