emailengine-app 2.85.0 → 2.86.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.ncurc.js +24 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +74 -0
- package/Dockerfile +14 -1
- package/ENVIRONMENT.md +139 -0
- package/README.md +1 -1
- package/config/default.toml +2 -0
- package/copy-static-files.sh +4 -2
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +4 -3
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +194 -165
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +78 -26
- package/lib/api-routes/blocklist-routes.js +68 -2
- package/lib/api-routes/delivery-test-routes.js +1 -1
- package/lib/api-routes/gateway-routes.js +82 -10
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +3 -3
- package/lib/api-routes/message-routes.js +15 -7
- package/lib/api-routes/oauth2-app-routes.js +15 -8
- package/lib/api-routes/outbox-routes.js +77 -66
- package/lib/api-routes/permission-map.js +55 -6
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +11 -4
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +4 -3
- package/lib/api-routes/template-routes.js +7 -6
- package/lib/api-routes/token-routes.js +11 -5
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +119 -4
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -46
- package/lib/db.js +14 -6
- package/lib/delivery-error.js +6 -0
- package/lib/deprecations.js +270 -0
- package/lib/email-client/base-client.js +130 -156
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +51 -11
- package/lib/email-client/imap/adaptive-idle-store.js +73 -0
- package/lib/email-client/imap/adaptive-idle.js +278 -0
- package/lib/email-client/imap/connection-errors.js +14 -1
- package/lib/email-client/imap/idle-settings.js +31 -5
- package/lib/email-client/imap/listing-diff.js +37 -0
- package/lib/email-client/imap/mailbox.js +372 -226
- package/lib/email-client/imap/subconnection.js +7 -29
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +227 -163
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/outlook-client.js +372 -338
- package/lib/email-client/smtp-pool-manager.js +16 -13
- package/lib/email-client/sync-state-fields.js +19 -0
- package/lib/encrypt.js +157 -41
- package/lib/enum-descriptions.js +3 -1
- package/lib/env-setting-overrides.js +288 -0
- package/lib/export-worker.js +751 -0
- package/lib/export.js +64 -15
- package/lib/gateway.js +17 -1
- package/lib/get-raw-email.js +25 -107
- package/lib/health.js +75 -0
- package/lib/lock-run.js +119 -0
- package/lib/logger-consts.js +48 -0
- package/lib/logger.js +1 -1
- package/lib/lua/z-head-scores.lua +28 -0
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +20 -1
- package/lib/oauth2-apps.js +630 -655
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/privileged-settings.js +2 -2
- package/lib/queue-browser/definitions.js +11 -0
- package/lib/queue-browser/index.js +68 -19
- package/lib/queue-job-actions.js +18 -1
- package/lib/queue-retention.js +48 -12
- package/lib/queue-stats.js +11 -2
- package/lib/read-env-value.js +3 -0
- package/lib/redis-memory-warnings.js +99 -0
- package/lib/redis-reconnect.js +29 -0
- package/lib/request-timing.js +23 -0
- package/lib/respawn-backoff.js +35 -0
- package/lib/rewrite-text-nodes.js +19 -59
- package/lib/schemas.js +163 -39
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/thread-diagnostics.js +18 -1
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +4 -3
- package/lib/tools.js +8 -41
- package/lib/ui-routes/admin-config-routes.js +64 -90
- package/lib/ui-routes/admin-entities-routes.js +2 -14
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/outlook-subscription-view.js +1 -1
- package/lib/ui-routes/overridable-fields.js +84 -0
- package/lib/ui-routes/queue-routes.js +8 -5
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/utils/decode-headers.js +3 -12
- package/lib/utils/filter-empty.js +20 -0
- package/lib/utils/int-setting.js +48 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/web-safe-html.js +18 -105
- package/lib/webhook-delivery.js +461 -0
- package/lib/webhook-failures.js +132 -0
- package/lib/webhook-request.js +29 -1
- package/lib/webhook-routing.js +30 -1
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +54 -41
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +21 -20
- package/sbom.json +304 -382
- package/server.js +149 -76
- package/static/js/ace/ace.js +1 -1
- package/static/licenses.html +21 -31
- package/translations/messages.pot +26 -26
- package/views/config/security.hbs +22 -0
- package/views/config/service.hbs +44 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/workers/api.js +102 -28
- package/workers/export.js +16 -631
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/webhooks.js +18 -432
- package/lib/email-client/outlook-fallback-poll.js +0 -30
|
@@ -14,14 +14,26 @@ const { oauth2Apps } = require('../oauth2-apps');
|
|
|
14
14
|
|
|
15
15
|
const { Subconnection } = require('./imap/subconnection');
|
|
16
16
|
const { imapResponseLabels } = require('./imap/response-metrics');
|
|
17
|
-
const {
|
|
17
|
+
const {
|
|
18
|
+
decodeStoredListing,
|
|
19
|
+
diffMailboxListing,
|
|
20
|
+
buildStoredListingObject,
|
|
21
|
+
matchesListingEntry,
|
|
22
|
+
accountPathList,
|
|
23
|
+
folderMonitoring
|
|
24
|
+
} = require('./imap/listing-diff');
|
|
18
25
|
const { samePath } = require('../utils/mailbox-path');
|
|
19
26
|
const { detachImapClient } = require('./imap/detach-client');
|
|
20
27
|
const { connectionNotAvailableError, connectionUnavailableError } = require('./imap/connection-errors');
|
|
21
28
|
const { ReconnectBackoff } = require('./reconnect-backoff');
|
|
22
29
|
const { isRefusedImapLogin, imapResponseText } = require('./imap/login-failure');
|
|
23
30
|
const { knownUidNext, planStaleViewProbe, evaluateStaleViewProbe } = require('./imap/stale-view');
|
|
24
|
-
const { applyIdleSettings } = require('./imap/idle-settings');
|
|
31
|
+
const { applyIdleSettings, commandSocketTimeout } = require('./imap/idle-settings');
|
|
32
|
+
const { learnedInterval, recordClose } = require('./imap/adaptive-idle-store');
|
|
33
|
+
|
|
34
|
+
// How long a learned IDLE interval read for one connection is reused for the account's others
|
|
35
|
+
const LEARNED_IDLE_CACHE_TTL = 60 * 1000;
|
|
36
|
+
const { runLocked, rethrowUnavailableLock } = require('../lock-run');
|
|
25
37
|
|
|
26
38
|
const {
|
|
27
39
|
normalizePath,
|
|
@@ -201,6 +213,59 @@ class IMAPClient extends BaseClient {
|
|
|
201
213
|
this.closeReconnectBackoff = new ReconnectBackoff({ baseDelay: 2000, maxDelay: 30000, jitter: 1000 });
|
|
202
214
|
}
|
|
203
215
|
|
|
216
|
+
/**
|
|
217
|
+
* The IDLE interval learned for the server, read once for the burst of connections an account
|
|
218
|
+
* opens together (primary, subconnections, command connection) rather than once each
|
|
219
|
+
* @param {string} host - IMAP server host
|
|
220
|
+
* @returns {Promise<number|null>}
|
|
221
|
+
*/
|
|
222
|
+
async getLearnedIdleInterval(host) {
|
|
223
|
+
const cached = this.learnedIdleCache;
|
|
224
|
+
if (cached && cached.host === host && Date.now() - cached.time < LEARNED_IDLE_CACHE_TTL) {
|
|
225
|
+
return cached.interval;
|
|
226
|
+
}
|
|
227
|
+
let interval = null;
|
|
228
|
+
try {
|
|
229
|
+
interval = await learnedInterval(this.redis, host);
|
|
230
|
+
} catch (err) {
|
|
231
|
+
this.logger.debug({ msg: 'Failed to read the learned IDLE interval', host, err });
|
|
232
|
+
}
|
|
233
|
+
this.learnedIdleCache = { host, interval, time: Date.now() };
|
|
234
|
+
return interval;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Records what an unexpected close of the primary connection says about the server's idle
|
|
239
|
+
* timer, see lib/email-client/imap/adaptive-idle.js. Best effort: learning is never a reason for
|
|
240
|
+
* the close handling to fail
|
|
241
|
+
* @param {Object} imapClient - The closed connection
|
|
242
|
+
* @param {number} [closedAt] - When it closed, epoch ms
|
|
243
|
+
*/
|
|
244
|
+
async recordIdleClose(imapClient, closedAt = Date.now()) {
|
|
245
|
+
try {
|
|
246
|
+
const host = imapClient.options?.host || this.imapConfig?.host;
|
|
247
|
+
const recorded = await recordClose(this.redis, host, imapClient, closedAt);
|
|
248
|
+
if (recorded && recorded.before !== recorded.after) {
|
|
249
|
+
// this account's next connection uses what it just recorded, not a cached read
|
|
250
|
+
this.learnedIdleCache = { host, interval: recorded.after, time: Date.now() };
|
|
251
|
+
this.logger.info({
|
|
252
|
+
msg: !recorded.after
|
|
253
|
+
? 'Dropped the learned IDLE restart interval for the server'
|
|
254
|
+
: recorded.before && recorded.after > recorded.before
|
|
255
|
+
? 'Relaxed the learned IDLE restart interval for the server'
|
|
256
|
+
: 'Learned an IDLE restart interval for the server',
|
|
257
|
+
host,
|
|
258
|
+
account: this.account,
|
|
259
|
+
interval: recorded.after,
|
|
260
|
+
previous: recorded.before,
|
|
261
|
+
observation: recorded.observation
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
} catch (err) {
|
|
265
|
+
this.logger.debug({ msg: 'Failed to record the IDLE close', account: this.account, err });
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
204
269
|
/**
|
|
205
270
|
* Checks whether a dropped connection had proven itself stable by
|
|
206
271
|
* surviving STABLE_CONNECTION_TIME, resetting the survival-gated close
|
|
@@ -213,7 +278,7 @@ class IMAPClient extends BaseClient {
|
|
|
213
278
|
* @returns {Boolean} True when the connection had proven itself stable
|
|
214
279
|
*/
|
|
215
280
|
validateConnectionAge(imapClient) {
|
|
216
|
-
if (Date.now() - imapClient.
|
|
281
|
+
if (Date.now() - imapClient.context?.startedAt >= STABLE_CONNECTION_TIME) {
|
|
217
282
|
this.closeReconnectBackoff.reset();
|
|
218
283
|
return true;
|
|
219
284
|
}
|
|
@@ -350,120 +415,109 @@ class IMAPClient extends BaseClient {
|
|
|
350
415
|
}
|
|
351
416
|
|
|
352
417
|
// Acquire a lock to prevent multiple simultaneous connection attempts
|
|
353
|
-
let lock = this.accountObject.getLock();
|
|
354
|
-
|
|
355
|
-
let connectLock;
|
|
356
418
|
let lockKey = ['commandClient', this.account].join(':');
|
|
357
419
|
|
|
358
|
-
|
|
359
|
-
this.
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
this.logger.error({ msg: 'Failed to get lock', lockKey, err });
|
|
367
|
-
throw err;
|
|
368
|
-
}
|
|
420
|
+
return await runLocked(
|
|
421
|
+
this.accountObject.getLock(),
|
|
422
|
+
lockKey,
|
|
423
|
+
{ ttl: 5 * 60 * 1000, wait: 1 * 60 * 1000 },
|
|
424
|
+
() => this.createCommandConnection(reason),
|
|
425
|
+
rethrowUnavailableLock(this.logger, 'Failed to get connection lock', { lockKey })
|
|
426
|
+
);
|
|
427
|
+
}
|
|
369
428
|
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
429
|
+
/**
|
|
430
|
+
* The part of getCommandConnection() that runs under the connection lock: opens the command
|
|
431
|
+
* connection unless one was created while waiting for the lock
|
|
432
|
+
* @param {string} reason - Why the connection is needed
|
|
433
|
+
* @returns {Promise<Object|null>} The command connection, null when IMAP is not usable
|
|
434
|
+
*/
|
|
435
|
+
async createCommandConnection(reason) {
|
|
436
|
+
// create a new connection for the command channel
|
|
437
|
+
let accountData = await this.accountObject.loadAccountData();
|
|
373
438
|
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
439
|
+
// Check if IMAP is configured and enabled
|
|
440
|
+
if ((!accountData.imap && !accountData.oauth2) || (accountData.imap && accountData.imap.disabled)) {
|
|
441
|
+
return null;
|
|
442
|
+
}
|
|
378
443
|
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
444
|
+
// Check again if command client was created while waiting for lock
|
|
445
|
+
if (this.commandClient && this.commandClient.usable) {
|
|
446
|
+
// use existing command channel created during the lock
|
|
447
|
+
return this.commandClient;
|
|
448
|
+
}
|
|
384
449
|
|
|
385
|
-
|
|
386
|
-
|
|
450
|
+
// Generate unique connection ID for tracking
|
|
451
|
+
const commandCid = `${this.cid}:c:${this.connectionCount++}`;
|
|
387
452
|
|
|
388
|
-
|
|
453
|
+
let imapConfig = await this.getImapConfig(accountData);
|
|
389
454
|
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
})
|
|
455
|
+
// Create new IMAP connection with specific settings for command operations
|
|
456
|
+
let commandClient = createImapClient(
|
|
457
|
+
Object.assign({}, imapConfig, {
|
|
458
|
+
disableAutoIdle: true, // Don't automatically IDLE on this connection
|
|
459
|
+
id: commandCid,
|
|
460
|
+
socketTimeout: commandSocketTimeout(imapConfig.maxIdleTime),
|
|
461
|
+
logger: this.logger.child({
|
|
462
|
+
cid: commandCid,
|
|
463
|
+
channel: 'command'
|
|
400
464
|
})
|
|
401
|
-
)
|
|
402
|
-
|
|
403
|
-
|
|
465
|
+
})
|
|
466
|
+
);
|
|
467
|
+
this.connections.add(commandClient);
|
|
468
|
+
await this.redis.hSetExists(this.getAccountKey(), 'connections', this.connections.size.toString());
|
|
404
469
|
|
|
405
|
-
|
|
470
|
+
commandClient.log.debug({ msg: 'Created command client', reason });
|
|
406
471
|
|
|
407
|
-
|
|
472
|
+
this.commandClient = commandClient;
|
|
408
473
|
|
|
409
|
-
|
|
410
|
-
|
|
474
|
+
// Set up error handling for the command connection
|
|
475
|
+
const onErr = err => {
|
|
476
|
+
// Idle timeout (ETIMEOUT) is expected - the command client has no keepalive
|
|
477
|
+
const logLevel = err.code === 'ETIMEOUT' ? 'debug' : 'warn';
|
|
478
|
+
if (!commandClient) {
|
|
479
|
+
// the close handler already let go of this client
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
commandClient.log[logLevel]({ msg: 'IMAP connection error', cid: commandCid, channel: 'command', account: this.account, err });
|
|
483
|
+
commandClient.close();
|
|
484
|
+
// A late event from a replaced client must not drop the reference to its successor,
|
|
485
|
+
// which would then stay open until its own socket timeout
|
|
486
|
+
if (this.commandClient === commandClient) {
|
|
487
|
+
this.commandClient = null;
|
|
488
|
+
}
|
|
489
|
+
};
|
|
490
|
+
commandClient.on('error', onErr);
|
|
411
491
|
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
// A late event from a replaced client must not drop the reference to its successor,
|
|
423
|
-
// which would then stay open until its own socket timeout
|
|
424
|
-
if (this.commandClient === commandClient) {
|
|
425
|
-
this.commandClient = null;
|
|
426
|
-
}
|
|
427
|
-
};
|
|
428
|
-
commandClient.on('error', onErr);
|
|
492
|
+
try {
|
|
493
|
+
await commandClient.connect();
|
|
494
|
+
commandClient.log.info({ msg: 'Command channel connected', cid: commandCid, channel: 'command', account: this.account });
|
|
495
|
+
} catch (err) {
|
|
496
|
+
// untrackConnection() swallows its own Redis failure, so the connect error is
|
|
497
|
+
// what the caller sees - a hiccup while updating the count must not replace it
|
|
498
|
+
await this.untrackConnection(commandClient);
|
|
499
|
+
commandClient.log.warn({ msg: 'Failed to connect command client', cid: commandCid, channel: 'command', account: this.account, err });
|
|
500
|
+
throw err;
|
|
501
|
+
}
|
|
429
502
|
|
|
503
|
+
// Clean up when connection closes. EventEmitter never observes what an async listener
|
|
504
|
+
// returns, so nothing in this body may escape - see the primary connection's handler
|
|
505
|
+
commandClient.on('close', async () => {
|
|
430
506
|
try {
|
|
431
|
-
await commandClient.connect();
|
|
432
|
-
commandClient.log.info({ msg: 'Command channel connected', cid: commandCid, channel: 'command', account: this.account });
|
|
433
|
-
} catch (err) {
|
|
434
|
-
// untrackConnection() swallows its own Redis failure, so the connect error is
|
|
435
|
-
// what the caller sees - a hiccup while updating the count must not replace it
|
|
436
507
|
await this.untrackConnection(commandClient);
|
|
437
|
-
commandClient.log.
|
|
438
|
-
|
|
508
|
+
commandClient.log.info({ msg: 'Connection closed', cid: commandCid, channel: 'command', account: this.account });
|
|
509
|
+
} catch (err) {
|
|
510
|
+
this.logger.error({ msg: 'Error in command client close handler', cid: commandCid, account: this.account, err });
|
|
439
511
|
}
|
|
440
512
|
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
commandClient.on('close', async () => {
|
|
444
|
-
try {
|
|
445
|
-
await this.untrackConnection(commandClient);
|
|
446
|
-
commandClient.log.info({ msg: 'Connection closed', cid: commandCid, channel: 'command', account: this.account });
|
|
447
|
-
} catch (err) {
|
|
448
|
-
this.logger.error({ msg: 'Error in command client close handler', cid: commandCid, account: this.account, err });
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
if (this.commandClient === commandClient) {
|
|
452
|
-
this.commandClient = null;
|
|
453
|
-
}
|
|
454
|
-
detachImapClient(commandClient, this.logger, { type: 'commandClient', cid: commandCid, account: this.account });
|
|
455
|
-
commandClient = null;
|
|
456
|
-
});
|
|
457
|
-
|
|
458
|
-
return commandClient;
|
|
459
|
-
} finally {
|
|
460
|
-
// Always release the lock
|
|
461
|
-
if (connectLock?.success) {
|
|
462
|
-
this.logger.debug({ msg: 'Releasing connection lock', lockKey, index: connectLock.index });
|
|
463
|
-
await lock.releaseLock(connectLock);
|
|
464
|
-
this.logger.debug({ msg: 'Released connection lock', lockKey, index: connectLock.index });
|
|
513
|
+
if (this.commandClient === commandClient) {
|
|
514
|
+
this.commandClient = null;
|
|
465
515
|
}
|
|
466
|
-
|
|
516
|
+
detachImapClient(commandClient, this.logger, { type: 'commandClient', cid: commandCid, account: this.account });
|
|
517
|
+
commandClient = null;
|
|
518
|
+
});
|
|
519
|
+
|
|
520
|
+
return commandClient;
|
|
467
521
|
}
|
|
468
522
|
|
|
469
523
|
/**
|
|
@@ -482,9 +536,11 @@ class IMAPClient extends BaseClient {
|
|
|
482
536
|
* This creates a unique identifier that can be unpacked later to retrieve the message
|
|
483
537
|
* @param {Object|string} mailbox - Mailbox object or path
|
|
484
538
|
* @param {number} uid - Message UID
|
|
539
|
+
* @param {Map} [statusCache] - Stored status by mailbox path, for a caller packing many UIDs
|
|
540
|
+
* of the same folder (a listing): the status is read once instead of one HGETALL per message
|
|
485
541
|
* @returns {string|false} Base64url encoded ID or false on error
|
|
486
542
|
*/
|
|
487
|
-
async packUid(mailbox, uid) {
|
|
543
|
+
async packUid(mailbox, uid, statusCache) {
|
|
488
544
|
if (isNaN(uid) || !mailbox) {
|
|
489
545
|
return false;
|
|
490
546
|
}
|
|
@@ -503,7 +559,10 @@ class IMAPClient extends BaseClient {
|
|
|
503
559
|
}
|
|
504
560
|
|
|
505
561
|
// Get stored mailbox status including UID validity
|
|
506
|
-
let storedStatus =
|
|
562
|
+
let storedStatus = statusCache?.get(mailbox.path);
|
|
563
|
+
if (!storedStatus) {
|
|
564
|
+
storedStatus = await mailbox.getStoredStatus();
|
|
565
|
+
}
|
|
507
566
|
|
|
508
567
|
// If stored status missing uidValidity, try live IMAP mailbox status
|
|
509
568
|
if (!validUidValidity(storedStatus.uidValidity)) {
|
|
@@ -547,6 +606,9 @@ class IMAPClient extends BaseClient {
|
|
|
547
606
|
return false;
|
|
548
607
|
}
|
|
549
608
|
|
|
609
|
+
// Only a usable status is reused, so a folder whose status is missing is looked at again
|
|
610
|
+
statusCache?.set(mailbox.path, storedStatus);
|
|
611
|
+
|
|
550
612
|
// Pack UID validity and mailbox path into a buffer
|
|
551
613
|
let uidValBuf = Buffer.alloc(8);
|
|
552
614
|
uidValBuf.writeBigUInt64BE(storedStatus.uidValidity, 0);
|
|
@@ -841,25 +903,15 @@ class IMAPClient extends BaseClient {
|
|
|
841
903
|
let accountData = await this.accountObject.loadAccountData();
|
|
842
904
|
|
|
843
905
|
// Get configured paths to monitor (default to all)
|
|
844
|
-
const accountPaths =
|
|
845
|
-
if (!accountPaths.length) {
|
|
846
|
-
accountPaths.push('*');
|
|
847
|
-
}
|
|
906
|
+
const accountPaths = accountPathList(accountData);
|
|
848
907
|
|
|
849
908
|
for (let entry of listing || []) {
|
|
850
909
|
if (
|
|
851
910
|
// previously unseen
|
|
852
911
|
!this.mailboxes.has(normalizePath(entry.path))
|
|
853
912
|
) {
|
|
854
|
-
//
|
|
855
|
-
if (!accountPaths.
|
|
856
|
-
if (configuredPathIndex(accountPaths, entry) < 0) {
|
|
857
|
-
// ignore changes
|
|
858
|
-
entry.syncDisabled = true;
|
|
859
|
-
}
|
|
860
|
-
} else if (this.isGmail && !['\\All', '\\Junk', '\\Trash'].includes(entry.specialUse)) {
|
|
861
|
-
// For Gmail, only monitor All Mail, Spam, and Trash folders
|
|
862
|
-
// Other folders are just labels and covered by All Mail
|
|
913
|
+
// the same rule connect() applies to the folders it registers
|
|
914
|
+
if (!folderMonitoring(accountPaths, entry, this.isGmail).monitored) {
|
|
863
915
|
entry.syncDisabled = true;
|
|
864
916
|
}
|
|
865
917
|
|
|
@@ -968,8 +1020,8 @@ class IMAPClient extends BaseClient {
|
|
|
968
1020
|
|
|
969
1021
|
if (this.isClosing || this.isClosed || this.paused) {
|
|
970
1022
|
// pause() or close() was called while account data was loading. No
|
|
971
|
-
// socket exists yet (imapClient.connect() below is what dials out,
|
|
972
|
-
//
|
|
1023
|
+
// socket exists yet (imapClient.connect() below is what dials out), so
|
|
1024
|
+
// bail out here rather than let connect() refuse a closed client, and
|
|
973
1025
|
// without overwriting the paused/closed state
|
|
974
1026
|
return false;
|
|
975
1027
|
}
|
|
@@ -997,37 +1049,26 @@ class IMAPClient extends BaseClient {
|
|
|
997
1049
|
this.isOutlook = /\boffice365\.com$/i.test(imapClient.host); // || /The Microsoft Exchange IMAP4 service is ready/.test(imapClient.greeting);
|
|
998
1050
|
this.isLarkSuite = /\blarksuite\.com$/i.test(imapClient.host);
|
|
999
1051
|
|
|
1000
|
-
const accountPaths =
|
|
1001
|
-
|
|
1002
|
-
accountPaths.push('*');
|
|
1003
|
-
}
|
|
1052
|
+
const accountPaths = accountPathList(accountData);
|
|
1053
|
+
const watchesAll = accountPaths.includes('*');
|
|
1004
1054
|
|
|
1005
1055
|
// store synced folder entries
|
|
1006
1056
|
const mainList = [];
|
|
1007
1057
|
|
|
1008
1058
|
// Process mailbox listing and determine which folders to monitor
|
|
1009
1059
|
for (let entry of listing) {
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
entry.syncDisabled = true;
|
|
1015
|
-
} else {
|
|
1016
|
-
// insert to stored list with the sorting index
|
|
1017
|
-
mainList.push({ index, entry });
|
|
1018
|
-
}
|
|
1019
|
-
} else {
|
|
1020
|
-
// Monitor all folders - determine main folder for IDLE
|
|
1021
|
-
if ((this.isGmail && entry.specialUse === '\\All') || (!this.isGmail && entry.specialUse === '\\Inbox')) {
|
|
1022
|
-
// In case of gmail prefer All mail folder as the folder to actively track, otherwise INBOX
|
|
1023
|
-
// idle in this folder
|
|
1024
|
-
this.main = entry;
|
|
1025
|
-
}
|
|
1060
|
+
let { monitored, index } = folderMonitoring(accountPaths, entry, this.isGmail);
|
|
1061
|
+
if (!monitored) {
|
|
1062
|
+
entry.syncDisabled = true;
|
|
1063
|
+
}
|
|
1026
1064
|
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1065
|
+
if (index >= 0) {
|
|
1066
|
+
// limited path monitoring: insert to stored list with the sorting index
|
|
1067
|
+
mainList.push({ index, entry });
|
|
1068
|
+
} else if (watchesAll && ((this.isGmail && entry.specialUse === '\\All') || (!this.isGmail && entry.specialUse === '\\Inbox'))) {
|
|
1069
|
+
// In case of gmail prefer All mail folder as the folder to actively track, otherwise INBOX
|
|
1070
|
+
// idle in this folder
|
|
1071
|
+
this.main = entry;
|
|
1031
1072
|
}
|
|
1032
1073
|
|
|
1033
1074
|
this.registerMailbox(entry);
|
|
@@ -1055,6 +1096,9 @@ class IMAPClient extends BaseClient {
|
|
|
1055
1096
|
// Handle flag changes
|
|
1056
1097
|
imapClient.on('flags', event => this.handleFlagsEvent(imapClient, event));
|
|
1057
1098
|
|
|
1099
|
+
// A polling server without IDLE reports flag changes only through its HIGHESTMODSEQ
|
|
1100
|
+
imapClient.on('highestModseq', event => this.handleHighestModseqEvent(imapClient, event));
|
|
1101
|
+
|
|
1058
1102
|
// The loop above registered a Mailbox for every listed folder, which is what
|
|
1059
1103
|
// processListing() would have done, so the sync that follows this call has
|
|
1060
1104
|
// nothing left to discover from a second listing. Keep the two registration
|
|
@@ -1143,6 +1187,23 @@ class IMAPClient extends BaseClient {
|
|
|
1143
1187
|
}
|
|
1144
1188
|
}
|
|
1145
1189
|
|
|
1190
|
+
/**
|
|
1191
|
+
* Handles a HIGHESTMODSEQ change found by ImapFlow's polling fallback
|
|
1192
|
+
* @param {Object} imapClient - IMAP connection that emitted the event
|
|
1193
|
+
* @param {Object} event - Event payload
|
|
1194
|
+
*/
|
|
1195
|
+
async handleHighestModseqEvent(imapClient, event) {
|
|
1196
|
+
try {
|
|
1197
|
+
let mailbox = this.resolveEventMailbox(event);
|
|
1198
|
+
if (!mailbox) {
|
|
1199
|
+
return;
|
|
1200
|
+
}
|
|
1201
|
+
await mailbox.onHighestModseq(event);
|
|
1202
|
+
} catch (err) {
|
|
1203
|
+
imapClient.log.error({ msg: 'Failed to process HIGHESTMODSEQ change', path: event?.path, err });
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1146
1207
|
/**
|
|
1147
1208
|
* Handles a mailbox open notification
|
|
1148
1209
|
* @param {Object} imapClient - IMAP connection that emitted the event
|
|
@@ -1694,8 +1755,9 @@ class IMAPClient extends BaseClient {
|
|
|
1694
1755
|
}
|
|
1695
1756
|
}
|
|
1696
1757
|
|
|
1697
|
-
// Provider IDLE workarounds, and the account's own
|
|
1698
|
-
|
|
1758
|
+
// Provider IDLE workarounds, what this host's dropped sessions taught, and the account's own
|
|
1759
|
+
// IDLE restart interval
|
|
1760
|
+
applyIdleSettings(imapConfig, accountData.imap, await this.getLearnedIdleInterval(imapConfig.host));
|
|
1699
1761
|
|
|
1700
1762
|
// Apply global settings
|
|
1701
1763
|
if (DISABLE_IMAP_COMPRESSION) {
|
|
@@ -1732,7 +1794,7 @@ class IMAPClient extends BaseClient {
|
|
|
1732
1794
|
if (this.imapClient) {
|
|
1733
1795
|
this.logger.debug({ msg: 'Clearing previous connection' });
|
|
1734
1796
|
let prevImapClient = this.imapClient;
|
|
1735
|
-
prevImapClient.disabled = true;
|
|
1797
|
+
prevImapClient.context.disabled = true;
|
|
1736
1798
|
try {
|
|
1737
1799
|
detachImapClient(prevImapClient, this.logger, { type: 'imapClient', previous: true, account: this.account });
|
|
1738
1800
|
prevImapClient.close();
|
|
@@ -1784,13 +1846,14 @@ class IMAPClient extends BaseClient {
|
|
|
1784
1846
|
// Create new IMAP connection instance
|
|
1785
1847
|
let imapClient = createImapClient(
|
|
1786
1848
|
Object.assign({}, imapConfig, {
|
|
1787
|
-
expungeHandler: async payload => await this.expungeHandler(payload)
|
|
1849
|
+
expungeHandler: async payload => await this.expungeHandler(payload),
|
|
1850
|
+
// startedAt is the birth time of this connection attempt: the unexpected-close
|
|
1851
|
+
// handler uses the age to tell a stable connection dropping from a connect/drop
|
|
1852
|
+
// cycle that needs throttling. Not ImapFlow's connectedAt, which stays unset
|
|
1853
|
+
// when the attempt never got a socket. `disabled` marks a replaced client
|
|
1854
|
+
context: { startedAt: Date.now(), disabled: false }
|
|
1788
1855
|
})
|
|
1789
1856
|
);
|
|
1790
|
-
// Birth time of this connection attempt - the unexpected-close
|
|
1791
|
-
// handler uses the age to tell a stable connection dropping from a
|
|
1792
|
-
// connect/drop cycle that needs throttling
|
|
1793
|
-
imapClient.connectionStartTime = Date.now();
|
|
1794
1857
|
this.connections.add(imapClient);
|
|
1795
1858
|
await this.redis.hSetExists(this.getAccountKey(), 'connections', this.connections.size.toString());
|
|
1796
1859
|
|
|
@@ -1798,9 +1861,6 @@ class IMAPClient extends BaseClient {
|
|
|
1798
1861
|
|
|
1799
1862
|
this.imapClient = imapClient;
|
|
1800
1863
|
|
|
1801
|
-
// Mark as primary connection
|
|
1802
|
-
imapClient.primaryConnection = true;
|
|
1803
|
-
|
|
1804
1864
|
// Forward IMAP logs to account logger
|
|
1805
1865
|
// if emitLogs option is true then separate log event is fired for every log entry
|
|
1806
1866
|
imapClient.on('log', entry => {
|
|
@@ -1853,9 +1913,11 @@ class IMAPClient extends BaseClient {
|
|
|
1853
1913
|
// rejection and takes the whole worker down. The steps below carry their own
|
|
1854
1914
|
// catches; this outer one is what keeps that true for an await added outside them.
|
|
1855
1915
|
imapClient.on('close', async () => {
|
|
1916
|
+
// before the awaits below, which would otherwise count as quiet time
|
|
1917
|
+
const closedAt = Date.now();
|
|
1856
1918
|
try {
|
|
1857
1919
|
await this.untrackConnection(imapClient);
|
|
1858
|
-
imapClient?.log.info({ msg: 'Connection closed', type: 'imapClient', account: this.account, disabled: imapClient.disabled });
|
|
1920
|
+
imapClient?.log.info({ msg: 'Connection closed', type: 'imapClient', account: this.account, disabled: imapClient.context?.disabled });
|
|
1859
1921
|
|
|
1860
1922
|
// Update state on unexpected disconnect
|
|
1861
1923
|
if (['init', 'connecting', 'syncing', 'connected'].includes(this.state)) {
|
|
@@ -1899,9 +1961,16 @@ class IMAPClient extends BaseClient {
|
|
|
1899
1961
|
imapClient.log.error({ msg: 'Connection close error', err });
|
|
1900
1962
|
}
|
|
1901
1963
|
|
|
1964
|
+
// a close of the live primary connection that nothing here asked for
|
|
1965
|
+
const unexpected = !imapClient.context?.disabled && imapClient === this.imapClient;
|
|
1966
|
+
if (unexpected) {
|
|
1967
|
+
// not awaited: learning must not hold up the reconnect, and handles its own errors
|
|
1968
|
+
this.recordIdleClose(imapClient, closedAt);
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1902
1971
|
try {
|
|
1903
1972
|
// Attempt reconnection if this was an unexpected close
|
|
1904
|
-
if (
|
|
1973
|
+
if (unexpected && !this._connecting) {
|
|
1905
1974
|
if (this.validateConnectionAge(imapClient)) {
|
|
1906
1975
|
// A proven-stable connection dropped - reconnect right away
|
|
1907
1976
|
if (!this.reconnectTimer) {
|
|
@@ -2048,7 +2117,7 @@ class IMAPClient extends BaseClient {
|
|
|
2048
2117
|
this.isClosing = true;
|
|
2049
2118
|
|
|
2050
2119
|
if (this.imapClient) {
|
|
2051
|
-
this.imapClient.disabled = true;
|
|
2120
|
+
this.imapClient.context.disabled = true;
|
|
2052
2121
|
this.imapClient.close();
|
|
2053
2122
|
if (this.commandClient) {
|
|
2054
2123
|
this.commandClient.close();
|
|
@@ -2103,6 +2172,9 @@ class IMAPClient extends BaseClient {
|
|
|
2103
2172
|
this.isClosing = true;
|
|
2104
2173
|
|
|
2105
2174
|
if (this.imapClient) {
|
|
2175
|
+
// a close asked for here (pause, shutdown, a move to another worker, a requested
|
|
2176
|
+
// reconnect): the close handler must neither reconnect it nor learn from it
|
|
2177
|
+
this.imapClient.context.disabled = true;
|
|
2106
2178
|
this.imapClient.close();
|
|
2107
2179
|
}
|
|
2108
2180
|
|
|
@@ -2946,12 +3018,7 @@ class IMAPClient extends BaseClient {
|
|
|
2946
3018
|
let uploadResponse = await connectionClient.append(data.path, raw, data.flags, data.internalDate);
|
|
2947
3019
|
|
|
2948
3020
|
// Return to IDLE if using primary connection
|
|
2949
|
-
|
|
2950
|
-
// force back to IDLE
|
|
2951
|
-
this.imapClient.idle().catch(err => {
|
|
2952
|
-
this.logger.warn({ msg: 'IDLE error', err });
|
|
2953
|
-
});
|
|
2954
|
-
}
|
|
3021
|
+
this.resumeIdle(connectionClient);
|
|
2955
3022
|
|
|
2956
3023
|
// Pack response data. ImapFlow's append() returns `destination` as the
|
|
2957
3024
|
// append target and `path` as the currently selected mailbox (often the
|
|
@@ -3105,10 +3172,7 @@ class IMAPClient extends BaseClient {
|
|
|
3105
3172
|
continue;
|
|
3106
3173
|
}
|
|
3107
3174
|
|
|
3108
|
-
const accountPaths =
|
|
3109
|
-
if (!accountPaths.length) {
|
|
3110
|
-
accountPaths.push('*');
|
|
3111
|
-
}
|
|
3175
|
+
const accountPaths = accountPathList(accountData);
|
|
3112
3176
|
|
|
3113
3177
|
// Check if already covered by primary connection
|
|
3114
3178
|
if (samePath(accountPaths[0], entry.path)) {
|