emailengine-app 2.79.7 → 2.79.8
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 +17 -0
- package/DOCKER_DEPLOYMENT.md +2 -0
- package/bin/emailengine.js +29 -13
- package/config/default.toml +13 -3
- package/data/google-crawlers.json +7 -1
- package/docker-compose.yml +12 -3
- package/install.sh +2 -0
- package/lib/api-routes/account-routes.js +14 -3
- package/lib/api-routes/mailbox-routes.js +4 -1
- package/lib/api-routes/message-routes.js +6 -5
- package/lib/api-routes/outbox-routes.js +7 -4
- package/lib/api-routes/settings-routes.js +34 -25
- package/lib/api-routes/stats-routes.js +8 -1
- package/lib/api-routes/submit-routes.js +2 -1
- package/lib/api-routes/template-routes.js +3 -2
- package/lib/bounce-detect.js +45 -0
- package/lib/consts.js +5 -1
- package/lib/egress-filter.js +39 -4
- package/lib/email-client/base-client.js +274 -24
- package/lib/email-client/gmail/gmail-api.js +15 -7
- package/lib/email-client/gmail-client.js +121 -64
- package/lib/email-client/imap/mailbox.js +18 -59
- package/lib/email-client/imap-client.js +53 -29
- package/lib/email-client/notification-handler.js +11 -2
- package/lib/email-client/outlook/graph-api.js +106 -90
- package/lib/email-client/outlook-client.js +222 -106
- package/lib/generate-text-preview.js +10 -5
- package/lib/headers-rewriter.js +1 -1
- package/lib/llm-pre-process.js +4 -1
- package/lib/mcp/json-schema.js +50 -2
- package/lib/outbox.js +22 -5
- package/lib/pre-process.js +4 -1
- package/lib/rewrite-text-nodes.js +12 -1
- package/lib/schemas.js +27 -5
- package/lib/settings.js +19 -1
- package/lib/sso.js +13 -3
- package/lib/submit-progress.js +29 -0
- package/lib/templates.js +11 -0
- package/lib/tools.js +96 -53
- package/lib/ui-routes/account-routes.js +70 -11
- package/lib/ui-routes/admin-config-routes.js +7 -21
- package/lib/ui-routes/admin-entities-routes.js +42 -12
- package/lib/ui-routes/auth-routes.js +87 -28
- package/lib/ui-routes/dashboard-routes.js +1 -1
- package/lib/ui-routes/internals-routes.js +2 -0
- package/lib/ui-routes/mcp-consent-routes.js +5 -2
- package/lib/ui-routes/network-config-routes.js +2 -2
- package/lib/ui-routes/oauth-config-routes.js +12 -1
- package/lib/ui-routes/route-helpers.js +41 -6
- package/lib/ui-routes/settings-page.js +10 -0
- package/lib/ui-routes/suppression-list-routes.js +16 -5
- package/lib/ui-routes/unsubscribe-routes.js +22 -3
- package/lib/webhooks.js +14 -2
- package/package.json +11 -11
- package/sbom.json +1 -1
- package/server.js +63 -35
- package/static/css/flyonui.css +1 -1
- package/static/licenses.html +17 -17
- package/translations/messages.pot +49 -49
- package/views/account/passkeys.hbs +8 -0
- package/views/account/password.hbs +11 -0
- package/views/account/security.hbs +18 -7
- package/views/accounts/account.hbs +6 -1
- package/views/accounts/register/imap-server.hbs +10 -2
- package/views/config/ai.hbs +2 -0
- package/views/config/branding.hbs +2 -0
- package/views/config/email-processing.hbs +2 -0
- package/views/config/imap-proxy.hbs +2 -0
- package/views/config/logging.hbs +3 -1
- package/views/config/mcp.hbs +2 -0
- package/views/config/network.hbs +2 -0
- package/views/config/oauth/app.hbs +2 -2
- package/views/config/security.hbs +2 -0
- package/views/config/service.hbs +2 -0
- package/views/config/smtp.hbs +2 -0
- package/views/config/webhooks.hbs +2 -0
- package/views/error.hbs +6 -0
- package/views/layout/app.hbs +6 -3
- package/views/layout/login.hbs +1 -1
- package/views/layout/prompt.hbs +1 -1
- package/views/layout/public.hbs +1 -1
- package/views/legal.hbs +1 -1
- package/views/partials/filter_editor_js.hbs +1 -1
- package/views/partials/oauth_form.hbs +5 -5
- package/views/partials/ui/env-managed-alert.hbs +19 -0
- package/views/partials/webhook_form.hbs +1 -1
- package/views/unsubscribe.hbs +6 -0
- package/workers/api.js +137 -63
- package/workers/imap.js +32 -3
- package/workers/smtp.js +7 -0
- package/workers/submit.js +25 -1
- package/workers/webhooks.js +13 -17
- package/lib/reconnection-manager.js +0 -106
package/lib/egress-filter.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/* eslint no-bitwise: 0 */
|
|
2
|
+
|
|
1
3
|
'use strict';
|
|
2
4
|
|
|
3
5
|
const net = require('net');
|
|
@@ -50,11 +52,44 @@ function normalizePolicy(value) {
|
|
|
50
52
|
return VALID_POLICIES.has(policy) ? policy : POLICY_LINK_LOCAL;
|
|
51
53
|
}
|
|
52
54
|
|
|
55
|
+
const ipv4FromHextets = (hi, lo) => new ipaddr.IPv4([hi >> 8, hi & 0xff, lo >> 8, lo & 0xff]);
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Extracts the IPv4 address an IPv6 transition address carries, if it is one.
|
|
59
|
+
*
|
|
60
|
+
* It is the embedded address the policy has to judge: `::ffff:169.254.169.254` (IPv4-mapped),
|
|
61
|
+
* `64:ff9b::169.254.169.254` (NAT64) and `2002:a9fe:a9fe::1` (6to4) all lead to the metadata
|
|
62
|
+
* service while classifying as plain unicast or as a transition range the policy does not list.
|
|
63
|
+
* Unwrapping rather than blocking the ranges outright keeps a NAT64-only host working: there,
|
|
64
|
+
* every IPv4-only receiver resolves into 64:ff9b::/96.
|
|
65
|
+
*
|
|
66
|
+
* @param {Object} parsed - An ipaddr.js IPv6 address
|
|
67
|
+
* @returns {Object|null} The embedded ipaddr.js IPv4 address, or null for a native IPv6 address
|
|
68
|
+
*/
|
|
69
|
+
function embeddedIPv4(parsed) {
|
|
70
|
+
if (parsed.isIPv4MappedAddress()) {
|
|
71
|
+
return parsed.toIPv4Address();
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const parts = parsed.parts;
|
|
75
|
+
switch (parsed.range()) {
|
|
76
|
+
case 'rfc6052': // 64:ff9b::/96 and 64:ff9b:1::/48, NAT64: the IPv4 is the low 32 bits
|
|
77
|
+
case 'rfc6145': // ::ffff:0:0:0/96, IPv4-translated: same layout
|
|
78
|
+
return ipv4FromHextets(parts[6], parts[7]);
|
|
79
|
+
case '6to4': // 2002:AABB:CCDD::/48, the IPv4 follows the 16-bit prefix
|
|
80
|
+
return ipv4FromHextets(parts[1], parts[2]);
|
|
81
|
+
case 'teredo': // 2001::/32, the client's IPv4 is the low 32 bits, bit-inverted
|
|
82
|
+
return ipv4FromHextets(parts[6] ^ 0xffff, parts[7] ^ 0xffff);
|
|
83
|
+
default:
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
53
88
|
/**
|
|
54
89
|
* Checks a single IP address against an egress policy.
|
|
55
90
|
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
91
|
+
* IPv6 transition addresses are unwrapped to the IPv4 address they carry first, see
|
|
92
|
+
* embeddedIPv4().
|
|
58
93
|
*
|
|
59
94
|
* @param {string} ip - IP address to classify
|
|
60
95
|
* @param {string} policy - One of the POLICY_* constants
|
|
@@ -73,8 +108,8 @@ function isBlockedAddress(ip, policy) {
|
|
|
73
108
|
return true;
|
|
74
109
|
}
|
|
75
110
|
|
|
76
|
-
if (parsed.kind() === 'ipv6'
|
|
77
|
-
parsed = parsed
|
|
111
|
+
if (parsed.kind() === 'ipv6') {
|
|
112
|
+
parsed = embeddedIPv4(parsed) || parsed;
|
|
78
113
|
}
|
|
79
114
|
|
|
80
115
|
if (ALWAYS_BLOCKED_ADDRESSES.has(parsed.toNormalizedString())) {
|
|
@@ -6,6 +6,7 @@ const logger = require('../logger');
|
|
|
6
6
|
const settings = require('../settings');
|
|
7
7
|
const { isDocumentStoreEnabled } = require('../document-store');
|
|
8
8
|
const msgpack = require('../msgpack');
|
|
9
|
+
const appendList = require('../append-list');
|
|
9
10
|
const { templates } = require('../templates');
|
|
10
11
|
const { Gateway } = require('../gateway');
|
|
11
12
|
const os = require('os');
|
|
@@ -72,10 +73,12 @@ const {
|
|
|
72
73
|
AUTH_FAILURE_DISABLED_FIELD,
|
|
73
74
|
AUTH_FAILURE_DISABLED_DESCRIPTION,
|
|
74
75
|
EMAIL_DELIVERY_ERROR_NOTIFY,
|
|
75
|
-
EMAIL_SENT_NOTIFY
|
|
76
|
+
EMAIL_SENT_NOTIFY,
|
|
77
|
+
TRANSIENT_NETWORK_CODES
|
|
76
78
|
} = require('../consts');
|
|
77
79
|
const { buildRetentionPolicy } = require('../queue-retention');
|
|
78
80
|
const { readImapData } = require('../account/imap-data');
|
|
81
|
+
const { ReconnectBackoff } = require('./reconnect-backoff');
|
|
79
82
|
|
|
80
83
|
// Configure download chunk size from environment or use default
|
|
81
84
|
const DOWNLOAD_CHUNK_SIZE = getByteSize(readEnvValue('EENGINE_CHUNK_SIZE')) || DEFAULT_DOWNLOAD_CHUNK_SIZE;
|
|
@@ -86,21 +89,6 @@ const MAX_IMAP_AUTH_FAILURE_TIME = getDuration(readEnvValue('EENGINE_MAX_IMAP_AU
|
|
|
86
89
|
// Map to track pending idempotency operations to prevent duplicate processing
|
|
87
90
|
const pendingIdempotencyOperations = new Map();
|
|
88
91
|
|
|
89
|
-
// Failing to reach a remote endpoint is a connection problem, not a rejected credential. Both
|
|
90
|
-
// OAuth2 credential sources (EmailEngine's own token refresh and an external authentication server)
|
|
91
|
-
// use this to avoid reporting an unreachable host as an authentication error, which would webhook
|
|
92
|
-
// and park every account on the instance over a brief outage.
|
|
93
|
-
const TRANSIENT_CONNECT_CODES = new Set([
|
|
94
|
-
'ENOTFOUND',
|
|
95
|
-
'ETIMEDOUT',
|
|
96
|
-
'ECONNREFUSED',
|
|
97
|
-
'ECONNRESET',
|
|
98
|
-
'EAI_AGAIN',
|
|
99
|
-
'UND_ERR_CONNECT_TIMEOUT',
|
|
100
|
-
'UND_ERR_SOCKET',
|
|
101
|
-
'UND_ERR_HEADERS_TIMEOUT'
|
|
102
|
-
]);
|
|
103
|
-
|
|
104
92
|
/**
|
|
105
93
|
* Keeps only the address entries a message can actually be delivered to.
|
|
106
94
|
*
|
|
@@ -186,8 +174,55 @@ function findReferencedCidAttachments(html, attachments) {
|
|
|
186
174
|
return cidAttachments;
|
|
187
175
|
}
|
|
188
176
|
|
|
177
|
+
/**
|
|
178
|
+
* A 401 that survives renewing the access token is the provider refusing the account's
|
|
179
|
+
* credential. Left as it is it reaches the API caller as a 401, which reads as their own
|
|
180
|
+
* EmailEngine token being rejected, so it is reported as a coded 403 the way a failed token
|
|
181
|
+
* renewal (OauthRenewError) is. The raw exchange stays on err.oauthRequest for the logs
|
|
182
|
+
* @param {Error} err - Error raised by the OAuth2 request layer
|
|
183
|
+
* @returns {Error} The same error, marked when it was a 401
|
|
184
|
+
*/
|
|
185
|
+
function markRejectedAccessToken(err) {
|
|
186
|
+
if (err && err.oauthRequest && err.oauthRequest.status === 401) {
|
|
187
|
+
err.code = 'OAuthTokenRejected';
|
|
188
|
+
err.statusCode = 403;
|
|
189
|
+
}
|
|
190
|
+
return err;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* A cached token the provider now rejects (revoked or invalidated on their side) is renewed
|
|
195
|
+
* so the caller can repeat the request once. A token fresh from the token endpoint is not
|
|
196
|
+
* renewed again - the rejection is then about the grant, not about a stale copy. Shared by
|
|
197
|
+
* the retry loops of the Gmail API and Graph transports
|
|
198
|
+
* @param {Object} context - Client the request was made for (logger, account, invalidateAccessToken)
|
|
199
|
+
* @param {Error} err - Error raised by the OAuth2 request layer
|
|
200
|
+
* @param {Object} tokenData - Token the failed request used ({ accessToken, cached })
|
|
201
|
+
* @param {boolean} tokenRenewed - Whether the request already renewed its token once
|
|
202
|
+
* @returns {Promise<boolean>} True when the token was invalidated and the request should be repeated
|
|
203
|
+
*/
|
|
204
|
+
async function renewRejectedAccessToken(context, err, tokenData, tokenRenewed) {
|
|
205
|
+
if (err.oauthRequest?.status !== 401 || !tokenData.cached || tokenRenewed) {
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
context.logger.warn({ msg: 'Cached access token was rejected, renewing it', account: context.account });
|
|
209
|
+
await context.invalidateAccessToken();
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Failing to reach a remote endpoint is a connection problem, not a rejected credential. Both
|
|
215
|
+
* OAuth2 credential sources (EmailEngine's own token refresh and an external authentication
|
|
216
|
+
* server) use this to avoid reporting an unreachable host as an authentication error, which
|
|
217
|
+
* would webhook and park every account on the instance over a brief outage, and the API
|
|
218
|
+
* transports use it to decide which failed requests to repeat. undici reports a connection
|
|
219
|
+
* failure as a generic TypeError ("fetch failed") with the real DNS/socket error attached as
|
|
220
|
+
* err.cause, so the code is looked up there as well
|
|
221
|
+
* @param {Error} err - The error to check
|
|
222
|
+
* @returns {boolean} True if the error is a transient network failure
|
|
223
|
+
*/
|
|
189
224
|
function isTransientNetworkError(err) {
|
|
190
|
-
return !!err &&
|
|
225
|
+
return !!err && (TRANSIENT_NETWORK_CODES.has(err.code) || (!!err.cause && TRANSIENT_NETWORK_CODES.has(err.cause.code)));
|
|
191
226
|
}
|
|
192
227
|
|
|
193
228
|
/**
|
|
@@ -297,6 +332,10 @@ class BaseClient {
|
|
|
297
332
|
// Track sub-connections (e.g., for IMAP IDLE)
|
|
298
333
|
this.subconnections = [];
|
|
299
334
|
|
|
335
|
+
// Set by the API clients: a failed init() is scheduled again by the worker through
|
|
336
|
+
// scheduleInitRetry(). IMAPClient reconnects with its own backoff instead
|
|
337
|
+
this.retriesInit = false;
|
|
338
|
+
|
|
300
339
|
// Initialize notification handler for webhook and event delivery
|
|
301
340
|
this.notificationHandler = new NotificationHandler({
|
|
302
341
|
account: this.account,
|
|
@@ -340,6 +379,56 @@ class BaseClient {
|
|
|
340
379
|
return false;
|
|
341
380
|
}
|
|
342
381
|
|
|
382
|
+
/**
|
|
383
|
+
* Schedules another init() attempt after one failed on something other than a refused
|
|
384
|
+
* credential. IMAPClient.init() reconnects with its own backoff, but a Gmail API or Graph
|
|
385
|
+
* client whose token endpoint or profile request failed on the network used to stay
|
|
386
|
+
* 'connecting' until someone reconnected it by hand. The delay grows through a backoff
|
|
387
|
+
* that resetInitRetry() clears once an attempt succeeds, init()/close()/delete() cancel a
|
|
388
|
+
* pending attempt, and a client closed in the meantime is left alone when the timer fires.
|
|
389
|
+
* The timer never keeps the worker alive on its own
|
|
390
|
+
* @param {Function} retry - Runs the next attempt
|
|
391
|
+
*/
|
|
392
|
+
scheduleInitRetry(retry) {
|
|
393
|
+
if (this.closed) {
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
this.initRetryBackoff = this.initRetryBackoff || new ReconnectBackoff({ baseDelay: 2000, maxDelay: 30000, jitter: 1000 });
|
|
398
|
+
const delay = this.initRetryBackoff.nextDelay();
|
|
399
|
+
this.logger.info({
|
|
400
|
+
msg: 'Scheduling account initialization retry',
|
|
401
|
+
account: this.account,
|
|
402
|
+
delay: Math.round(delay),
|
|
403
|
+
attempt: this.initRetryBackoff.attempts
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
clearTimeout(this.initRetryTimer);
|
|
407
|
+
this.initRetryTimer = setTimeout(() => {
|
|
408
|
+
if (this.closed) {
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
retry();
|
|
412
|
+
}, delay);
|
|
413
|
+
this.initRetryTimer.unref();
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Drops a pending init() retry, if any
|
|
418
|
+
*/
|
|
419
|
+
cancelInitRetry() {
|
|
420
|
+
clearTimeout(this.initRetryTimer);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Starts the retry delays over after init() succeeded
|
|
425
|
+
*/
|
|
426
|
+
resetInitRetry() {
|
|
427
|
+
if (this.initRetryBackoff) {
|
|
428
|
+
this.initRetryBackoff.reset();
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
343
432
|
/**
|
|
344
433
|
* Generates a random 20-character ID for connection tracking
|
|
345
434
|
* @returns {string} Random ID string
|
|
@@ -399,6 +488,136 @@ class BaseClient {
|
|
|
399
488
|
return `${REDIS_PREFIX}iar:s:${this.account}`;
|
|
400
489
|
}
|
|
401
490
|
|
|
491
|
+
/**
|
|
492
|
+
* Redis hash holding the bounces detected for this account, keyed by the Message-ID of
|
|
493
|
+
* the message that bounced. Filled by the new-message processors of every client type
|
|
494
|
+
* and read back into the `bounces` field of the message details response
|
|
495
|
+
*/
|
|
496
|
+
getBounceKey() {
|
|
497
|
+
return `${REDIS_PREFIX}iar:b:${this.account}`;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* Records a detected bounce against the Message-ID of the message that bounced
|
|
502
|
+
* @param {string} bounceMessageId - EmailEngine id of the bounce message itself
|
|
503
|
+
* @param {Object} bounce - Parsed bounce (recipient, action, messageId, response)
|
|
504
|
+
* @returns {Promise<number|boolean>} appendList.append() result
|
|
505
|
+
*/
|
|
506
|
+
async storeBounce(bounceMessageId, bounce) {
|
|
507
|
+
let storedBounce = {
|
|
508
|
+
i: bounceMessageId,
|
|
509
|
+
r: bounce.recipient,
|
|
510
|
+
t: Date.now(),
|
|
511
|
+
a: bounce.action
|
|
512
|
+
};
|
|
513
|
+
|
|
514
|
+
if (bounce.response && bounce.response.message) {
|
|
515
|
+
storedBounce.m = bounce.response.message;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
if (bounce.response && bounce.response.status) {
|
|
519
|
+
storedBounce.s = bounce.response.status;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
return await appendList.append(this.redis, this.getBounceKey(), bounce.messageId, storedBounce);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* Lists the bounces recorded for a Message-ID in the shape of the `bounces` response field
|
|
527
|
+
* @param {string} messageId - Message-ID header value of the sent message
|
|
528
|
+
* @returns {Promise<Object[]>} Bounce entries, empty when none were recorded
|
|
529
|
+
*/
|
|
530
|
+
async listBounces(messageId) {
|
|
531
|
+
let rows = await appendList.list(this.redis, this.getBounceKey(), messageId);
|
|
532
|
+
return rows.map(row => {
|
|
533
|
+
let bounce = {
|
|
534
|
+
message: row.i,
|
|
535
|
+
recipient: row.r,
|
|
536
|
+
action: row.a
|
|
537
|
+
};
|
|
538
|
+
if (row.m || row.s) {
|
|
539
|
+
bounce.response = {};
|
|
540
|
+
}
|
|
541
|
+
if (row.m) {
|
|
542
|
+
bounce.response.message = row.m;
|
|
543
|
+
}
|
|
544
|
+
if (row.s) {
|
|
545
|
+
bounce.response.status = row.s;
|
|
546
|
+
}
|
|
547
|
+
bounce.date = new Date(row.t).toISOString();
|
|
548
|
+
return bounce;
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/**
|
|
553
|
+
* Adds the recorded bounces to a formatted message, when there are any. A lookup failure
|
|
554
|
+
* is logged and leaves the message without the field rather than failing the fetch
|
|
555
|
+
* @param {Object} messageData - Formatted message (needs `messageId`), updated in place
|
|
556
|
+
*/
|
|
557
|
+
async attachBounces(messageData) {
|
|
558
|
+
if (!messageData || !messageData.messageId) {
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
try {
|
|
562
|
+
let bounces = await this.listBounces(messageData.messageId);
|
|
563
|
+
if (bounces.length) {
|
|
564
|
+
messageData.bounces = bounces;
|
|
565
|
+
}
|
|
566
|
+
} catch (err) {
|
|
567
|
+
this.logger.error({
|
|
568
|
+
msg: 'Failed to fetch bounces',
|
|
569
|
+
id: messageData.id,
|
|
570
|
+
uid: messageData.uid,
|
|
571
|
+
messageId: messageData.messageId,
|
|
572
|
+
err
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* Decodes a base64url msgpack identifier the API clients hand out for text and
|
|
579
|
+
* attachment references. A truncated or foreign value used to surface as a RangeError,
|
|
580
|
+
* or as a TypeError from destructuring a non-array, which the API reported as a 500
|
|
581
|
+
* @param {string} encoded - Identifier from the request
|
|
582
|
+
* @param {Function} isValid - Receives the decoded array, returns whether it has the expected shape
|
|
583
|
+
* @returns {Array} Decoded parts
|
|
584
|
+
*/
|
|
585
|
+
unpackApiId(encoded, isValid) {
|
|
586
|
+
let parts;
|
|
587
|
+
try {
|
|
588
|
+
parts = msgpack.decode(Buffer.from((encoded || '').toString(), 'base64url'));
|
|
589
|
+
} catch (err) {
|
|
590
|
+
parts = null;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if (!Array.isArray(parts) || !isValid(parts)) {
|
|
594
|
+
let error = new Error('Invalid identifier');
|
|
595
|
+
error.info = {
|
|
596
|
+
response: 'The provided identifier can not be decoded'
|
|
597
|
+
};
|
|
598
|
+
error.code = 'InvalidId';
|
|
599
|
+
error.statusCode = 400;
|
|
600
|
+
throw error;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
return parts;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Builds the canonical 404 error for a mailbox path that does not exist on the account
|
|
608
|
+
* @param {string} path - Requested mailbox path
|
|
609
|
+
* @returns {Error} Error object with code and statusCode set
|
|
610
|
+
*/
|
|
611
|
+
unknownPathError(path) {
|
|
612
|
+
let error = new Error('Unknown path');
|
|
613
|
+
error.info = {
|
|
614
|
+
response: `Mailbox doesn't exist: ${path}`
|
|
615
|
+
};
|
|
616
|
+
error.code = 'NotFound';
|
|
617
|
+
error.statusCode = 404;
|
|
618
|
+
return error;
|
|
619
|
+
}
|
|
620
|
+
|
|
402
621
|
getLogKey() {
|
|
403
622
|
// this format ensures that the key is deleted when user is removed
|
|
404
623
|
return `${REDIS_PREFIX}iam:${this.account}:g`;
|
|
@@ -882,6 +1101,23 @@ class BaseClient {
|
|
|
882
1101
|
return { oauth2User, accessToken, oauth2App };
|
|
883
1102
|
}
|
|
884
1103
|
|
|
1104
|
+
/**
|
|
1105
|
+
* Resolves the current access token through the subclass getTokenData()
|
|
1106
|
+
* @returns {Promise<string>} Access token
|
|
1107
|
+
*/
|
|
1108
|
+
async getToken() {
|
|
1109
|
+
return (await this.getTokenData()).accessToken;
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
/**
|
|
1113
|
+
* Expires the stored access token so the next getToken() renews it. Used when the
|
|
1114
|
+
* provider rejects a token that is still within its recorded lifetime. A delegated
|
|
1115
|
+
* (shared mailbox) account holds the credential, so the token is expired there
|
|
1116
|
+
*/
|
|
1117
|
+
async invalidateAccessToken() {
|
|
1118
|
+
await (this.delegatedAccountObject || this.accountObject).invalidateAccessToken();
|
|
1119
|
+
}
|
|
1120
|
+
|
|
885
1121
|
/**
|
|
886
1122
|
* Resolves delegated account chain for OAuth2 authentication
|
|
887
1123
|
* Follows delegation chain up to 20 hops, detecting loops
|
|
@@ -1413,7 +1649,7 @@ class BaseClient {
|
|
|
1413
1649
|
// Permanent 404 error - respect ignoreMissing
|
|
1414
1650
|
if (!data.reference.ignoreMissing) {
|
|
1415
1651
|
let error = new Error('Referenced message was not found');
|
|
1416
|
-
error.code = '
|
|
1652
|
+
error.code = 'ReferenceNotFound';
|
|
1417
1653
|
error.statusCode = 404;
|
|
1418
1654
|
throw error;
|
|
1419
1655
|
}
|
|
@@ -1427,7 +1663,7 @@ class BaseClient {
|
|
|
1427
1663
|
|
|
1428
1664
|
if (!referencedMessage && !data.reference.ignoreMissing) {
|
|
1429
1665
|
let err = new Error('Referenced message was not found');
|
|
1430
|
-
err.code = '
|
|
1666
|
+
err.code = 'ReferenceNotFound';
|
|
1431
1667
|
err.statusCode = 404;
|
|
1432
1668
|
throw err;
|
|
1433
1669
|
}
|
|
@@ -2629,7 +2865,11 @@ class BaseClient {
|
|
|
2629
2865
|
}
|
|
2630
2866
|
}
|
|
2631
2867
|
|
|
2868
|
+
let stored = 0;
|
|
2632
2869
|
if (bounce.action && bounce.recipient && bounce.messageId) {
|
|
2870
|
+
// Record it for the `bounces` field of the bounced message, as the IMAP path does
|
|
2871
|
+
stored = await this.storeBounce(messageData.id, bounce);
|
|
2872
|
+
|
|
2633
2873
|
bounceNotifyInfo = Object.assign({ bounceMessage: messageData.id }, bounce);
|
|
2634
2874
|
|
|
2635
2875
|
messageData.isBounce = true;
|
|
@@ -2641,7 +2881,8 @@ class BaseClient {
|
|
|
2641
2881
|
id: messageData.id,
|
|
2642
2882
|
uid: messageData.uid,
|
|
2643
2883
|
messageId: messageData.messageId,
|
|
2644
|
-
bounce
|
|
2884
|
+
bounce,
|
|
2885
|
+
stored
|
|
2645
2886
|
});
|
|
2646
2887
|
}
|
|
2647
2888
|
} catch (err) {
|
|
@@ -3481,10 +3722,12 @@ class BaseClient {
|
|
|
3481
3722
|
})
|
|
3482
3723
|
);
|
|
3483
3724
|
|
|
3484
|
-
// Enhance error with additional context
|
|
3725
|
+
// Enhance error with additional context. The API clients report their send failures
|
|
3726
|
+
// through here as well, and those arrive with a statusCode and info of their own that
|
|
3727
|
+
// must survive - only an SMTP reply code overrides the status
|
|
3485
3728
|
err.code = err.code || 'SubmitFail';
|
|
3486
|
-
err.statusCode = Number(err.responseCode) || null;
|
|
3487
|
-
err.info = { networkRouting };
|
|
3729
|
+
err.statusCode = Number(err.responseCode) || err.statusCode || null;
|
|
3730
|
+
err.info = Object.assign({}, err.info, { networkRouting });
|
|
3488
3731
|
}
|
|
3489
3732
|
|
|
3490
3733
|
// stub - to be implemented by subclasses
|
|
@@ -3496,4 +3739,11 @@ class BaseClient {
|
|
|
3496
3739
|
// Re-export postMetrics from notification-handler for backward compatibility
|
|
3497
3740
|
// applyReferenceRecipients is exported for tests: the methods that call it need a live
|
|
3498
3741
|
// account, a connection and a referenced message fetched from the server
|
|
3499
|
-
module.exports = {
|
|
3742
|
+
module.exports = {
|
|
3743
|
+
BaseClient,
|
|
3744
|
+
metricsMeta: postMetrics,
|
|
3745
|
+
applyReferenceRecipients,
|
|
3746
|
+
isTransientNetworkError,
|
|
3747
|
+
markRejectedAccessToken,
|
|
3748
|
+
renewRejectedAccessToken
|
|
3749
|
+
};
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const { metricsMeta } = require('../base-client');
|
|
4
|
-
const { TRANSIENT_NETWORK_CODES } = require('../../consts');
|
|
3
|
+
const { metricsMeta, markRejectedAccessToken, renewRejectedAccessToken, isTransientNetworkError } = require('../base-client');
|
|
5
4
|
|
|
6
5
|
// Gmail API configuration
|
|
7
6
|
const GMAIL_API_BASE = 'https://gmail.googleapis.com';
|
|
@@ -89,12 +88,13 @@ function calculateRetryDelay(err, attempt) {
|
|
|
89
88
|
async function request(context, url, method, payload, options = {}) {
|
|
90
89
|
const maxRetries = options.maxRetries ?? MAX_RETRY_ATTEMPTS;
|
|
91
90
|
let lastError;
|
|
91
|
+
let tokenRenewed = false;
|
|
92
92
|
|
|
93
93
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
94
|
-
let result,
|
|
94
|
+
let result, tokenData;
|
|
95
95
|
|
|
96
96
|
try {
|
|
97
|
-
|
|
97
|
+
tokenData = await context.getTokenData();
|
|
98
98
|
} catch (err) {
|
|
99
99
|
context.logger.error({ msg: 'Failed to load access token', account: context.account, err });
|
|
100
100
|
throw err;
|
|
@@ -105,7 +105,7 @@ async function request(context, url, method, payload, options = {}) {
|
|
|
105
105
|
await context.getClient();
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
-
result = await context.oAuth2Client.request(accessToken, url, method, payload, options);
|
|
108
|
+
result = await context.oAuth2Client.request(tokenData.accessToken, url, method, payload, options);
|
|
109
109
|
|
|
110
110
|
// Track successful API request
|
|
111
111
|
metricsMeta({ account: context.account }, context.logger, 'oauth2ApiRequest', 'inc', {
|
|
@@ -118,8 +118,16 @@ async function request(context, url, method, payload, options = {}) {
|
|
|
118
118
|
} catch (err) {
|
|
119
119
|
lastError = err;
|
|
120
120
|
|
|
121
|
+
// A rejected cached token is renewed and the request repeated once, see
|
|
122
|
+
// renewRejectedAccessToken()
|
|
123
|
+
if (await renewRejectedAccessToken(context, err, tokenData, tokenRenewed)) {
|
|
124
|
+
tokenRenewed = true;
|
|
125
|
+
attempt -= 1;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
|
|
121
129
|
// Check if this is a transient network error
|
|
122
|
-
if (
|
|
130
|
+
if (isTransientNetworkError(err) && attempt < maxRetries) {
|
|
123
131
|
const delay = RETRY_BASE_DELAY * Math.pow(2, attempt) + Math.random() * 500;
|
|
124
132
|
|
|
125
133
|
context.logger.warn({
|
|
@@ -183,7 +191,7 @@ async function request(context, url, method, payload, options = {}) {
|
|
|
183
191
|
statusCode
|
|
184
192
|
});
|
|
185
193
|
|
|
186
|
-
throw err;
|
|
194
|
+
throw markRejectedAccessToken(err);
|
|
187
195
|
}
|
|
188
196
|
}
|
|
189
197
|
|