emailengine-app 2.81.1 → 2.82.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 +12 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +52 -0
- package/Dockerfile +4 -2
- package/bin/emailengine.js +28 -18
- package/config/default.toml +0 -5
- package/config/test.toml +0 -5
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +70 -42
- package/getswagger.sh +0 -4
- package/lib/account/account-state.js +2 -110
- package/lib/account/bounce-store-sweep.js +63 -0
- package/lib/account/expected-identity.js +1 -1
- package/lib/account-assignment.js +207 -0
- package/lib/account.js +374 -878
- package/lib/api-reference/index.js +2 -3
- package/lib/api-reference/schema-tree.js +53 -3
- package/lib/api-routes/account-routes.js +18 -29
- package/lib/api-routes/blocklist-routes.js +2 -2
- package/lib/api-routes/bull-board-routes.js +1 -6
- package/lib/api-routes/export-routes.js +2 -22
- package/lib/api-routes/gateway-routes.js +5 -14
- package/lib/api-routes/index.js +1 -13
- package/lib/api-routes/mailbox-routes.js +2 -7
- package/lib/api-routes/mcp-oauth-routes.js +2 -1
- package/lib/api-routes/mcp-routes.js +7 -7
- package/lib/api-routes/message-routes.js +44 -236
- package/lib/api-routes/mint-bounds.js +110 -0
- package/lib/api-routes/oauth2-app-routes.js +23 -32
- package/lib/api-routes/operation-impact.js +1 -1
- package/lib/api-routes/outbox-routes.js +2 -2
- package/lib/api-routes/permission-map.js +1 -7
- package/lib/api-routes/route-helpers.js +11 -5
- package/lib/api-routes/settings-routes.js +19 -19
- package/lib/api-routes/stats-routes.js +1 -1
- package/lib/api-routes/submit-routes.js +17 -18
- package/lib/api-routes/template-routes.js +4 -9
- package/lib/api-routes/token-routes.js +27 -5
- package/lib/api-token-scheme.js +71 -0
- package/lib/arf-detect.js +41 -7
- package/lib/auth-token.js +44 -24
- package/lib/autodetect-imap-settings.js +163 -123
- package/lib/bounce-detect.js +25 -16
- package/lib/calendar-event.js +78 -0
- package/lib/consts.js +51 -5
- package/lib/create-imap-client.js +24 -0
- package/lib/db.js +76 -17
- package/lib/delivery-error.js +2 -1
- package/lib/egress-fetch.js +54 -3
- package/lib/egress-filter.js +11 -0
- package/lib/email-client/api-retry.js +147 -0
- package/lib/email-client/base-client.js +628 -615
- package/lib/email-client/gmail/gmail-api.js +38 -125
- package/lib/email-client/gmail/send-request.js +1 -1
- package/lib/email-client/gmail-client.js +170 -84
- package/lib/email-client/imap/mailbox.js +244 -535
- package/lib/email-client/imap/stale-view.js +109 -0
- package/lib/email-client/imap/subconnection.js +46 -9
- package/lib/email-client/imap/sync-operations.js +5 -37
- package/lib/email-client/imap-client.js +188 -64
- package/lib/email-client/message-builder.js +9 -14
- package/lib/email-client/notification-handler.js +5 -219
- package/lib/email-client/outlook/graph-api.js +147 -126
- package/lib/email-client/outlook/send-request.js +10 -4
- package/lib/email-client/outlook-client.js +519 -617
- package/lib/email-client/smtp-pool-manager.js +3 -2
- package/lib/encrypt.js +184 -19
- package/lib/enum-descriptions.js +1 -2
- package/lib/export.js +144 -41
- package/lib/gateway.js +20 -6
- package/lib/get-raw-email.js +26 -44
- package/lib/handlebars-helpers.js +31 -10
- package/lib/imap-proxy-auth.js +13 -29
- package/lib/imapproxy/imap-core/README.md +1 -0
- package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
- package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
- package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
- package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
- package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
- package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
- package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
- package/lib/imapproxy/imap-server.js +17 -177
- package/lib/imapproxy/proxy-handoff.js +235 -0
- package/lib/imapproxy/response-error.js +33 -0
- package/lib/imapproxy/upstream-client.js +2 -2
- package/lib/license-beacon.js +3 -9
- package/lib/llm-pre-process.js +182 -43
- package/lib/logger.js +1 -1
- package/lib/lua/ee-export-queue-add.lua +39 -0
- package/lib/lua/ee-get-idempotency.lua +15 -3
- package/lib/lua/ee-release-attempts.lua +23 -0
- package/lib/lua/ee-reserve-attempts.lua +42 -0
- package/lib/lua/h-set-bigger.lua +12 -2
- package/lib/lua/s-list-accounts.lua +6 -3
- package/lib/mcp/index.js +1 -2
- package/lib/mcp/listen.js +221 -18
- package/lib/mcp/oauth.js +44 -5
- package/lib/mcp/resources.js +8 -2
- package/lib/mcp/tools.js +13 -0
- package/lib/message-port-stream.js +64 -6
- package/lib/msgpack.js +1 -6
- package/lib/oauth/external-account-signer.js +16 -13
- package/lib/oauth/gmail.js +22 -20
- package/lib/oauth/outlook.js +19 -16
- package/lib/oauth/pubsub/google.js +38 -2
- package/lib/oauth/scope-checker.js +4 -7
- package/lib/oauth/verify-app.js +2 -2
- package/lib/oauth2-apps.js +139 -44
- package/lib/openapi/build-document.js +1 -1
- package/lib/openapi/joi-schema.js +78 -9
- package/lib/parse-message.js +21 -0
- package/lib/payload-examples-webhooks.json +4 -7
- package/lib/pbkdf2-phc.js +101 -0
- package/lib/privileged-settings.js +0 -14
- package/lib/rate-limit.js +54 -15
- package/lib/redis-scan-delete.js +56 -29
- package/lib/redis-url.js +3 -1
- package/lib/respawn-backoff.js +5 -4
- package/lib/response-stream.js +25 -4
- package/lib/rewrite-text-nodes.js +27 -40
- package/lib/routes-ui.js +0 -5
- package/lib/schemas.js +129 -262
- package/lib/sentry.js +21 -5
- package/lib/settings.js +58 -59
- package/lib/smtp-auth.js +6 -2
- package/lib/smtp-message-processor.js +28 -7
- package/lib/sso.js +7 -3
- package/lib/stream-encrypt.js +14 -13
- package/lib/swagger-options.js +3 -1
- package/lib/tls/provision.js +69 -3
- package/lib/tls/store.js +14 -1
- package/lib/tools.js +113 -52
- package/lib/totp.js +16 -1
- package/lib/ui-routes/account-routes.js +27 -63
- package/lib/ui-routes/admin-config-routes.js +111 -134
- package/lib/ui-routes/admin-entities-routes.js +101 -191
- package/lib/ui-routes/ai-options.js +104 -0
- package/lib/ui-routes/auth-routes.js +98 -18
- package/lib/ui-routes/export-routes.js +3 -23
- package/lib/ui-routes/internals-routes.js +12 -9
- package/lib/ui-routes/network-config-routes.js +8 -18
- package/lib/ui-routes/oauth-config-routes.js +80 -214
- package/lib/ui-routes/route-helpers.js +40 -44
- package/lib/ui-routes/unsubscribe-routes.js +2 -2
- package/lib/utils/decode-headers.js +32 -5
- package/lib/utils/header-map.js +62 -1
- package/lib/utils/network.js +2 -0
- package/lib/web-safe-html.js +77 -4
- package/lib/webhook-request.js +9 -1
- package/lib/webhook-routing.js +27 -1
- package/lib/webhooks.js +120 -43
- package/lib/worker-rpc-error.js +43 -2
- package/list-generate.js +13 -2
- package/package.json +38 -46
- package/sbom.json +1 -1
- package/scripts/refresh-test-tokens.js +42 -14
- package/server.js +340 -336
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +7 -8
- package/static/js/ee-client.js +145 -70
- package/static/js/ui.js +350 -154
- package/static/licenses.html +460 -1861
- package/translations/messages.pot +99 -99
- package/views/accounts/browse.hbs +10 -4
- package/views/config/ai.hbs +49 -41
- package/views/config/oauth/app.hbs +2 -1
- package/views/dashboard.hbs +18 -16
- package/views/layout/app.hbs +0 -22
- package/views/layout/login.hbs +2 -1
- package/views/partials/filter_editor_js.hbs +4 -3
- package/views/partials/side_menu.hbs +0 -4
- package/views/partials/ui/account-picker.hbs +6 -32
- package/views/partials/ui/model-picker.hbs +31 -0
- package/views/partials/ui/pagination.hbs +6 -1
- package/views/partials/ui/picker.hbs +47 -0
- package/views/unsubscribe.hbs +1 -1
- package/workers/api.js +33 -23
- package/workers/export.js +55 -60
- package/workers/imap.js +134 -47
- package/workers/submit.js +3 -1
- package/workers/webhooks.js +46 -27
- package/.githooks/pre-commit +0 -80
- package/.github/CODE_OF_CONDUCT.md +0 -76
- package/.github/contributing.md +0 -17
- package/.github/dependabot.yml +0 -22
- package/.github/docker-smoke-test.sh +0 -61
- package/.github/workflows/deploy.yml +0 -215
- package/.github/workflows/e2e.yml +0 -55
- package/.github/workflows/release.yaml +0 -217
- package/.github/workflows/test.yml +0 -307
- package/lib/api-routes/chat-routes.js +0 -535
- package/lib/append-list.js +0 -63
- package/lib/document-store.js +0 -75
- package/lib/es.js +0 -757
- package/lib/generate-text-preview.js +0 -61
- package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
- package/lib/lua/h-push.lua +0 -32
- package/lib/pre-process.js +0 -196
- package/lib/threads.js +0 -155
- package/lib/ui-routes/document-store-routes.js +0 -806
- package/playwright.config.js +0 -47
- package/views/config/document-store/chat.hbs +0 -286
- package/views/config/document-store/index.hbs +0 -146
- package/views/config/document-store/mappings/index.hbs +0 -108
- package/views/config/document-store/mappings/new.hbs +0 -68
- package/views/config/document-store/pre-processing/index.hbs +0 -103
- package/views/partials/document_store_header.hbs +0 -30
- package/workers/documents.js +0 -1128
package/lib/account.js
CHANGED
|
@@ -6,25 +6,20 @@ const msgpack = require('./msgpack');
|
|
|
6
6
|
const {
|
|
7
7
|
normalizePath,
|
|
8
8
|
formatAccountListingResponse,
|
|
9
|
-
unpackUIDRangeForSearch,
|
|
10
9
|
mergeObjects,
|
|
11
|
-
download,
|
|
12
10
|
resolveCredentials,
|
|
13
11
|
useAuthServerForOAuth2,
|
|
14
12
|
isEmail,
|
|
15
13
|
resolveDelegatedAccount,
|
|
16
14
|
escapeRedisGlob,
|
|
17
|
-
getMailboxStatusKey
|
|
18
|
-
cidReferenceRegex
|
|
15
|
+
getMailboxStatusKey
|
|
19
16
|
} = require('./tools');
|
|
20
17
|
const { MessageChannel } = require('worker_threads');
|
|
21
18
|
const { MessagePortReadable } = require('./message-port-stream');
|
|
22
19
|
const { isDeepStrictEqual } = require('util');
|
|
23
|
-
const { encrypt, decrypt } = require('./encrypt');
|
|
20
|
+
const { encrypt, decrypt, decryptField, parseEncryptedData } = require('./encrypt');
|
|
24
21
|
const { oauth2Apps, isApiBasedApp } = require('./oauth2-apps');
|
|
25
22
|
const settings = require('./settings');
|
|
26
|
-
const { buildRetentionPolicy } = require('./queue-retention');
|
|
27
|
-
const { isDocumentStoreEnabled, documentStoreFeatureEnabled } = require('./document-store');
|
|
28
23
|
const redisScanDelete = require('./redis-scan-delete');
|
|
29
24
|
const { extractMultiValues, createTransaction } = require('./redis-operations');
|
|
30
25
|
const outbox = require('./outbox');
|
|
@@ -33,8 +28,8 @@ const { customAlphabet } = require('nanoid');
|
|
|
33
28
|
const Lock = require('ioredfour');
|
|
34
29
|
const { redis } = require('./db');
|
|
35
30
|
const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
|
|
36
|
-
const { REDIS_PREFIX,
|
|
37
|
-
const {
|
|
31
|
+
const { REDIS_PREFIX, AUTH_FAILURE_DISABLED_FIELD, AUTH_FAILURE_DISABLED_LEGACY_DESCRIPTION } = require('./consts');
|
|
32
|
+
const { webSafeTextResponse, applyWebSafeHtmlOptions } = require('./web-safe-html');
|
|
38
33
|
const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
|
|
39
34
|
const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
|
|
40
35
|
const { decodeStoredMailboxEntry } = require('./email-client/imap/listing-diff');
|
|
@@ -53,6 +48,14 @@ const defaultLock = new Lock({
|
|
|
53
48
|
const ACCOUNT_UPDATE_LOCK_TTL = 10 * 1000;
|
|
54
49
|
const ACCOUNT_UPDATE_LOCK_WAIT = 5 * 1000;
|
|
55
50
|
|
|
51
|
+
// Account fields that carry a credential without being one: the webhook URL and the proxy URL may
|
|
52
|
+
// embed `user:pass@`, and the custom webhook headers typically hold an Authorization value. The
|
|
53
|
+
// global settings of the same name are encrypted at rest (settings.js CREDENTIAL_BEARING_KEYS), so
|
|
54
|
+
// these are too. A value written before that is cleartext, which decrypt() passes through, so old
|
|
55
|
+
// records keep reading until their next save or `emailengine encrypt` run. `emailengine encrypt`
|
|
56
|
+
// re-encrypts exactly this list.
|
|
57
|
+
const ENCRYPTED_ACCOUNT_FIELDS = ['webhooks', 'webhooksCustomHeaders', 'proxy'];
|
|
58
|
+
|
|
56
59
|
/**
|
|
57
60
|
* What an incoming account payload asks of `imap.disabled`.
|
|
58
61
|
*
|
|
@@ -135,14 +138,10 @@ class Account {
|
|
|
135
138
|
this.redis = options.redis;
|
|
136
139
|
this.account = options.account || false;
|
|
137
140
|
|
|
138
|
-
this.documentsQueue = options.documentsQueue || false;
|
|
139
|
-
|
|
140
141
|
this.secret = options.secret;
|
|
141
142
|
|
|
142
143
|
this.timeout = options.timeout ? Number(options.timeout) : 0;
|
|
143
144
|
|
|
144
|
-
this.esClient = options.esClient;
|
|
145
|
-
|
|
146
145
|
this.call = options.call; // async method to request data from parent
|
|
147
146
|
|
|
148
147
|
this.logger = options.logger || logger;
|
|
@@ -291,7 +290,9 @@ class Account {
|
|
|
291
290
|
|
|
292
291
|
let result = await this.redis.sListAccounts(`${REDIS_PREFIX}ia:accounts`, filterState, skip, limit, `${REDIS_PREFIX}`, search);
|
|
293
292
|
|
|
294
|
-
|
|
293
|
+
// No decryption here: the listing outputs none of the credentials, and the two
|
|
294
|
+
// credential-bearing URLs it does output are decrypted below, only for rows that set them
|
|
295
|
+
let accounts = result[2].map(formatAccountListingResponse).map(row => this.unserializeAccountData(row, { skipDecrypt: true }));
|
|
295
296
|
let oauthApps = new Map();
|
|
296
297
|
|
|
297
298
|
for (let accountData of accounts) {
|
|
@@ -324,7 +325,7 @@ class Account {
|
|
|
324
325
|
if (delegatedAccount) {
|
|
325
326
|
accountData.delegatedAccount = delegatedAccount;
|
|
326
327
|
let delegatedAccountRow = await this.redis.hgetall(`${REDIS_PREFIX}iad:${delegatedAccount}`);
|
|
327
|
-
let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow);
|
|
328
|
+
let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow, { skipDecrypt: true });
|
|
328
329
|
if (delegatedAccountData.oauth2 && delegatedAccountData.oauth2.provider) {
|
|
329
330
|
let app;
|
|
330
331
|
if (oauthApps.has(delegatedAccountData.oauth2.provider)) {
|
|
@@ -376,8 +377,8 @@ class Account {
|
|
|
376
377
|
: undefined,
|
|
377
378
|
state: getDisplayState(accountData, runIndex),
|
|
378
379
|
|
|
379
|
-
webhooks: accountData.webhooks || undefined,
|
|
380
|
-
proxy: accountData.proxy || undefined,
|
|
380
|
+
webhooks: this.decryptAccountField('webhooks', accountData.webhooks, accountData.account) || undefined,
|
|
381
|
+
proxy: this.decryptAccountField('proxy', accountData.proxy, accountData.account) || undefined,
|
|
381
382
|
smtpEhloName: accountData.smtpEhloName || undefined,
|
|
382
383
|
|
|
383
384
|
counters: accountData.counters,
|
|
@@ -418,6 +419,11 @@ class Account {
|
|
|
418
419
|
return `${REDIS_PREFIX}iap:${this.account}`;
|
|
419
420
|
}
|
|
420
421
|
|
|
422
|
+
// Mailbox changes waiting for a retry (Gmail and MS Graph), scored by the time they are due
|
|
423
|
+
getDeferredQueueKey() {
|
|
424
|
+
return `${REDIS_PREFIX}iap:${this.account}:r`;
|
|
425
|
+
}
|
|
426
|
+
|
|
421
427
|
// Shared log entry for unserializeAccountData() failures. The raw value is withheld on
|
|
422
428
|
// purpose: imap/smtp/oauth2 payloads may carry cleartext credentials when no EENGINE_SECRET is
|
|
423
429
|
// set, so only its length is logged. `ownerAccount` is the row's own marker when available -
|
|
@@ -432,7 +438,22 @@ class Account {
|
|
|
432
438
|
});
|
|
433
439
|
}
|
|
434
440
|
|
|
435
|
-
|
|
441
|
+
/**
|
|
442
|
+
* Turns a stored account hash into the account object.
|
|
443
|
+
*
|
|
444
|
+
* @param {Object} accountData - The hash as read from Redis
|
|
445
|
+
* @param {Object} [opts]
|
|
446
|
+
* @param {boolean} [opts.skipDecrypt] - Leave every encrypted value as stored. Each stored value
|
|
447
|
+
* has its own salt, so a cold decrypt is a synchronous key derivation; a listing that decrypted the
|
|
448
|
+
* IMAP/SMTP passwords and OAuth2 tokens of every row blocked the API worker for tens of
|
|
449
|
+
* seconds on a 1000-account page, for fields it never outputs. For callers that read only
|
|
450
|
+
* the non-secret structure (listings, delegated-row lookups): the credentials and the
|
|
451
|
+
* ENCRYPTED_ACCOUNT_FIELDS stay ciphertext, and an encrypted custom header list is left out
|
|
452
|
+
* rather than failing to parse. decryptAccountField() opens the few such values a caller needs.
|
|
453
|
+
* @returns {Object} The unserialized account
|
|
454
|
+
*/
|
|
455
|
+
unserializeAccountData(accountData, opts) {
|
|
456
|
+
const skipDecrypt = !!(opts && opts.skipDecrypt);
|
|
436
457
|
const result = {};
|
|
437
458
|
|
|
438
459
|
// The loop below drops every `_`-prefixed field, which is what keeps the auth-failure marker
|
|
@@ -468,7 +489,6 @@ class Account {
|
|
|
468
489
|
|
|
469
490
|
switch (key) {
|
|
470
491
|
case 'notifyFrom':
|
|
471
|
-
case 'syncFrom':
|
|
472
492
|
case 'lastWatch':
|
|
473
493
|
// Date object
|
|
474
494
|
if (accountData[key]) {
|
|
@@ -519,8 +539,41 @@ class Account {
|
|
|
519
539
|
}
|
|
520
540
|
break;
|
|
521
541
|
|
|
542
|
+
case 'webhooks':
|
|
543
|
+
case 'proxy': {
|
|
544
|
+
let value = skipDecrypt ? accountData[key] : this.decryptAccountField(key, accountData[key], accountData.account);
|
|
545
|
+
if (typeof value !== 'undefined') {
|
|
546
|
+
result[key] = value;
|
|
547
|
+
}
|
|
548
|
+
break;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
case 'webhooksCustomHeaders': {
|
|
552
|
+
let stored = accountData[key];
|
|
553
|
+
if (skipDecrypt) {
|
|
554
|
+
if (this.secret && parseEncryptedData(stored).format !== 'cleartext') {
|
|
555
|
+
// not read by any caller that skips decryption
|
|
556
|
+
break;
|
|
557
|
+
}
|
|
558
|
+
} else {
|
|
559
|
+
stored = this.decryptAccountField(key, stored, accountData.account);
|
|
560
|
+
if (typeof stored === 'undefined') {
|
|
561
|
+
break;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
try {
|
|
565
|
+
let value = JSON.parse(stored);
|
|
566
|
+
if (value === null) {
|
|
567
|
+
break;
|
|
568
|
+
}
|
|
569
|
+
result[key] = value;
|
|
570
|
+
} catch (err) {
|
|
571
|
+
this.logUnserializeFailure('Failed to parse input from Redis', key, stored, accountData.account, err);
|
|
572
|
+
}
|
|
573
|
+
break;
|
|
574
|
+
}
|
|
575
|
+
|
|
522
576
|
// generic JSON values
|
|
523
|
-
case 'webhooksCustomHeaders':
|
|
524
577
|
case 'subconnections':
|
|
525
578
|
case 'watchResponse':
|
|
526
579
|
case 'watchFailure':
|
|
@@ -604,7 +657,7 @@ class Account {
|
|
|
604
657
|
});
|
|
605
658
|
|
|
606
659
|
// decrypt secrets
|
|
607
|
-
if (this.secret) {
|
|
660
|
+
if (this.secret && !skipDecrypt) {
|
|
608
661
|
for (let type of ['imap', 'smtp', 'oauth2']) {
|
|
609
662
|
if (result[type] && result[type].auth) {
|
|
610
663
|
for (let key of ['pass', 'accessToken', 'refreshToken']) {
|
|
@@ -647,6 +700,31 @@ class Account {
|
|
|
647
700
|
return result;
|
|
648
701
|
}
|
|
649
702
|
|
|
703
|
+
/**
|
|
704
|
+
* Decrypts one of ENCRYPTED_ACCOUNT_FIELDS. Cleartext (a value stored before the field was
|
|
705
|
+
* encrypted, or written without a secret) passes through unchanged.
|
|
706
|
+
*
|
|
707
|
+
* @returns {String|undefined} The cleartext, or undefined when the value does not decrypt with
|
|
708
|
+
* the current secret; the field then reads as unset rather than failing the whole account
|
|
709
|
+
*/
|
|
710
|
+
decryptAccountField(key, value, ownerAccount) {
|
|
711
|
+
return decryptField(value, this.secret, err => this.logUnserializeFailure('Failed to decrypt value', key, value, ownerAccount, err));
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// Encrypts one of ENCRYPTED_ACCOUNT_FIELDS for storage. The empty string is a marker (a cleared
|
|
715
|
+
// value) and is stored as is.
|
|
716
|
+
encryptAccountField(key, value) {
|
|
717
|
+
if (!this.secret || !value) {
|
|
718
|
+
return value;
|
|
719
|
+
}
|
|
720
|
+
try {
|
|
721
|
+
return encrypt(value, this.secret);
|
|
722
|
+
} catch (err) {
|
|
723
|
+
this.logger.error({ msg: 'Failed to encrypt value', key, account: this.account, err });
|
|
724
|
+
return value;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
|
|
650
728
|
serializeAccountData(accountData) {
|
|
651
729
|
let result = {};
|
|
652
730
|
|
|
@@ -657,7 +735,6 @@ class Account {
|
|
|
657
735
|
}
|
|
658
736
|
switch (key) {
|
|
659
737
|
case 'notifyFrom':
|
|
660
|
-
case 'syncFrom':
|
|
661
738
|
case 'lastWatch':
|
|
662
739
|
// Date object
|
|
663
740
|
if (accountData[key] === 'now') {
|
|
@@ -695,9 +772,22 @@ class Account {
|
|
|
695
772
|
}
|
|
696
773
|
break;
|
|
697
774
|
|
|
775
|
+
case 'webhooksCustomHeaders':
|
|
776
|
+
try {
|
|
777
|
+
result[key] = this.encryptAccountField(key, JSON.stringify(accountData[key]));
|
|
778
|
+
} catch (err) {
|
|
779
|
+
this.logger.error({ msg: 'Failed to stringify input for Redis', key, account: this.account, err });
|
|
780
|
+
}
|
|
781
|
+
break;
|
|
782
|
+
|
|
783
|
+
case 'proxy':
|
|
784
|
+
if (typeof accountData[key] !== 'undefined' && accountData[key] !== null && typeof accountData[key].toString === 'function') {
|
|
785
|
+
result[key] = this.encryptAccountField(key, accountData[key].toString());
|
|
786
|
+
}
|
|
787
|
+
break;
|
|
788
|
+
|
|
698
789
|
// generic JSON values
|
|
699
790
|
case 'subconnections':
|
|
700
|
-
case 'webhooksCustomHeaders':
|
|
701
791
|
case 'watchResponse':
|
|
702
792
|
case 'watchFailure':
|
|
703
793
|
try {
|
|
@@ -782,11 +872,12 @@ class Account {
|
|
|
782
872
|
|
|
783
873
|
case 'webhooks':
|
|
784
874
|
if (typeof accountData[key] !== 'undefined' && accountData[key] !== null && typeof accountData[key].toString === 'function') {
|
|
785
|
-
|
|
786
|
-
if (!
|
|
875
|
+
let value = accountData[key].toString();
|
|
876
|
+
if (!value) {
|
|
787
877
|
// clear potential error flag
|
|
788
878
|
result.webhookErrorFlag = '{}';
|
|
789
879
|
}
|
|
880
|
+
result[key] = this.encryptAccountField(key, value);
|
|
790
881
|
}
|
|
791
882
|
break;
|
|
792
883
|
|
|
@@ -860,7 +951,7 @@ class Account {
|
|
|
860
951
|
if (delegatedAccount) {
|
|
861
952
|
accountData.delegatedAccount = delegatedAccount;
|
|
862
953
|
let delegatedAccountRow = await this.redis.hgetall(`${REDIS_PREFIX}iad:${delegatedAccount}`);
|
|
863
|
-
let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow);
|
|
954
|
+
let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow, { skipDecrypt: true });
|
|
864
955
|
if (delegatedAccountData.oauth2 && delegatedAccountData.oauth2.provider) {
|
|
865
956
|
let app = await oauth2Apps.get(delegatedAccountData.oauth2.provider);
|
|
866
957
|
if (app) {
|
|
@@ -912,14 +1003,61 @@ class Account {
|
|
|
912
1003
|
* external caller, i.e. possible operator re-authorization. Only the public account-update
|
|
913
1004
|
* API route sets it; every unattended writer (token renewal, client initialize(),
|
|
914
1005
|
* invalidateAccessToken) leaves it false and can therefore never trigger the reconnect gate.
|
|
915
|
-
* @
|
|
1006
|
+
* @param {String} [opts.expectedRefreshToken] - Write only while the stored OAuth2 refresh token
|
|
1007
|
+
* is still this one. Token renewal reads the account, then waits on the provider without the
|
|
1008
|
+
* update lock; a re-authorization landing in that window must not be overwritten with the
|
|
1009
|
+
* renewal's older grant. Checked under the lock, against the stored value.
|
|
1010
|
+
* @returns {Promise<Object>} `{ account }`, plus `skipped: true` when expectedRefreshToken no
|
|
1011
|
+
* longer matched and nothing was written
|
|
916
1012
|
*/
|
|
917
|
-
async update(accountData, { reauthorized = false } = {}) {
|
|
1013
|
+
async update(accountData, { reauthorized = false, expectedRefreshToken } = {}) {
|
|
918
1014
|
// Captured before persistUpdate() merges a `partial` payload into the stored object
|
|
919
1015
|
const disabledIntent = imapDisabledIntent(accountData);
|
|
920
1016
|
|
|
1017
|
+
let current = null;
|
|
1018
|
+
let oldAccountData = await this.withUpdateLock(accountData.account, async () => {
|
|
1019
|
+
let stored;
|
|
1020
|
+
if (typeof expectedRefreshToken === 'string') {
|
|
1021
|
+
stored = await this.loadAccountData(accountData.account);
|
|
1022
|
+
// A grant without a refresh token (a service account) is spelled ''
|
|
1023
|
+
if (((stored.oauth2 && stored.oauth2.refreshToken) || '') !== expectedRefreshToken) {
|
|
1024
|
+
current = stored;
|
|
1025
|
+
return null;
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
// The record just read is handed on, so the write does not load and decrypt it again
|
|
1029
|
+
return await this.persistUpdate(accountData, stored);
|
|
1030
|
+
});
|
|
1031
|
+
|
|
1032
|
+
if (!oldAccountData) {
|
|
1033
|
+
this.logger.info({ msg: 'Skipped a token write, the stored OAuth2 grant changed meanwhile', account: this.account });
|
|
1034
|
+
// `current` is the account as stored now, so the caller need not read it a third time
|
|
1035
|
+
return {
|
|
1036
|
+
account: this.account,
|
|
1037
|
+
skipped: true,
|
|
1038
|
+
current
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
await this.dispatchPostUpdateCommands(accountData, oldAccountData, reauthorized, disabledIntent);
|
|
1043
|
+
|
|
1044
|
+
return {
|
|
1045
|
+
account: this.account
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/**
|
|
1050
|
+
* Runs `fn` holding the per-account update lock that serializes account writes.
|
|
1051
|
+
*
|
|
1052
|
+
* Lock acquisition failing is not treated as an error, see update() for why.
|
|
1053
|
+
*
|
|
1054
|
+
* @param {String} account - Account ID
|
|
1055
|
+
* @param {Function} fn - Async critical section
|
|
1056
|
+
* @returns {Promise<*>} Whatever `fn` resolves to
|
|
1057
|
+
*/
|
|
1058
|
+
async withUpdateLock(account, fn) {
|
|
921
1059
|
const lock = this.getLock();
|
|
922
|
-
const lockKey = `account:update:${
|
|
1060
|
+
const lockKey = `account:update:${account}`;
|
|
923
1061
|
let updateLock;
|
|
924
1062
|
|
|
925
1063
|
let lockErr;
|
|
@@ -930,28 +1068,49 @@ class Account {
|
|
|
930
1068
|
}
|
|
931
1069
|
|
|
932
1070
|
if (!updateLock?.success) {
|
|
933
|
-
this.logger.warn({ msg: 'Failed to get account update lock, proceeding unserialized', account
|
|
1071
|
+
this.logger.warn({ msg: 'Failed to get account update lock, proceeding unserialized', account, lockKey, err: lockErr });
|
|
934
1072
|
}
|
|
935
1073
|
|
|
936
|
-
let oldAccountData;
|
|
937
1074
|
try {
|
|
938
|
-
|
|
1075
|
+
return await fn();
|
|
939
1076
|
} finally {
|
|
940
1077
|
if (updateLock?.success) {
|
|
941
1078
|
try {
|
|
942
1079
|
await lock.releaseLock(updateLock);
|
|
943
1080
|
} catch (err) {
|
|
944
1081
|
// The lock expires on its own, so a failed release must not mask the result
|
|
945
|
-
this.logger.warn({ msg: 'Failed to release account update lock', account
|
|
1082
|
+
this.logger.warn({ msg: 'Failed to release account update lock', account, lockKey, err });
|
|
946
1083
|
}
|
|
947
1084
|
}
|
|
948
1085
|
}
|
|
1086
|
+
}
|
|
949
1087
|
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
1088
|
+
/**
|
|
1089
|
+
* Sends a command to the worker that owns the account after a change was already written.
|
|
1090
|
+
* The write stands either way, so a dispatch that fails (an RPC timeout, no worker yet) is
|
|
1091
|
+
* logged rather than thrown: an error response for a saved change made a retried create report
|
|
1092
|
+
* the account as existing and a retried delete answer 404. The worker catches up on its next
|
|
1093
|
+
* reconnect or assignment pass.
|
|
1094
|
+
*
|
|
1095
|
+
* @returns {Promise<Boolean>} Whether the worker acknowledged the command
|
|
1096
|
+
*/
|
|
1097
|
+
async notifyWorker(cmd) {
|
|
1098
|
+
if (typeof this.call !== 'function') {
|
|
1099
|
+
// This Account instance has no parent RPC channel (constructed without `call`)
|
|
1100
|
+
this.logger.warn({ msg: 'Skipping worker command dispatch, no parent RPC channel', account: this.account, cmd });
|
|
1101
|
+
return false;
|
|
1102
|
+
}
|
|
1103
|
+
try {
|
|
1104
|
+
await this.call({
|
|
1105
|
+
cmd,
|
|
1106
|
+
account: this.account,
|
|
1107
|
+
timeout: this.timeout
|
|
1108
|
+
});
|
|
1109
|
+
return true;
|
|
1110
|
+
} catch (err) {
|
|
1111
|
+
this.logger.error({ msg: 'Failed to notify the worker after a saved account change', account: this.account, cmd, err });
|
|
1112
|
+
return false;
|
|
1113
|
+
}
|
|
955
1114
|
}
|
|
956
1115
|
|
|
957
1116
|
/**
|
|
@@ -961,8 +1120,9 @@ class Account {
|
|
|
961
1120
|
* @param {Object} accountData - Account fields to write
|
|
962
1121
|
* @returns {Promise<Object>} The account as it was before the write
|
|
963
1122
|
*/
|
|
964
|
-
async persistUpdate(accountData) {
|
|
965
|
-
|
|
1123
|
+
async persistUpdate(accountData, oldAccountData) {
|
|
1124
|
+
// update() hands over the record it already loaded under the lock, when it loaded one
|
|
1125
|
+
oldAccountData = oldAccountData || (await this.loadAccountData(accountData.account));
|
|
966
1126
|
|
|
967
1127
|
if (accountData.oauth2?.provider) {
|
|
968
1128
|
// check if this OAuth2 provider exists
|
|
@@ -1158,17 +1318,7 @@ class Account {
|
|
|
1158
1318
|
// Changes detected. The full reconnect above supersedes this: it assigns a fresh
|
|
1159
1319
|
// client, which reads the changed settings on its way in.
|
|
1160
1320
|
this.logger.info({ msg: 'IMAP configuration changed for account', account: this.account });
|
|
1161
|
-
|
|
1162
|
-
await this.call({
|
|
1163
|
-
cmd: 'update',
|
|
1164
|
-
account: this.account,
|
|
1165
|
-
timeout: this.timeout
|
|
1166
|
-
});
|
|
1167
|
-
} else {
|
|
1168
|
-
// This Account instance has no parent RPC channel (constructed without `call`).
|
|
1169
|
-
// Skip the dispatch instead of throwing - the persisted change stands.
|
|
1170
|
-
this.logger.warn({ msg: 'Skipping update command dispatch, no parent RPC channel', account: this.account });
|
|
1171
|
-
}
|
|
1321
|
+
await this.notifyWorker('update');
|
|
1172
1322
|
}
|
|
1173
1323
|
}
|
|
1174
1324
|
|
|
@@ -1311,6 +1461,22 @@ class Account {
|
|
|
1311
1461
|
cmd: 'runIndex'
|
|
1312
1462
|
});
|
|
1313
1463
|
|
|
1464
|
+
// Under the same lock as update(): the OAuth2 user uniqueness check below is a
|
|
1465
|
+
// check-then-set, and a re-registration racing an update or a token renewal of the same
|
|
1466
|
+
// account would otherwise interleave its write with theirs
|
|
1467
|
+
let result = await this.withUpdateLock(this.account, async () => await this.writeCreatedAccount(accountData, runIndex));
|
|
1468
|
+
|
|
1469
|
+
if (!result || !result[1] || result[1][0] || result[1][1] !== 'OK') {
|
|
1470
|
+
let message = 'Something went wrong';
|
|
1471
|
+
let error = Boom.boomify(new Error(message), { statusCode: 500 });
|
|
1472
|
+
throw error;
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
return await this.finishCreate(accountData, result);
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
// The write half of create(), run under the account update lock
|
|
1479
|
+
async writeCreatedAccount(accountData, runIndex) {
|
|
1314
1480
|
let pipeline = this.redis
|
|
1315
1481
|
.multi()
|
|
1316
1482
|
.hgetall(this.getAccountKey())
|
|
@@ -1349,14 +1515,11 @@ class Account {
|
|
|
1349
1515
|
}
|
|
1350
1516
|
}
|
|
1351
1517
|
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
if (!result || !result[1] || result[1][0] || result[1][1] !== 'OK') {
|
|
1355
|
-
let message = 'Something went wrong';
|
|
1356
|
-
let error = Boom.boomify(new Error(message), { statusCode: 500 });
|
|
1357
|
-
throw error;
|
|
1358
|
-
}
|
|
1518
|
+
return await pipeline.exec();
|
|
1519
|
+
}
|
|
1359
1520
|
|
|
1521
|
+
// The post-write half of create(): provider rebinding, auth-failure recovery and the worker dispatch
|
|
1522
|
+
async finishCreate(accountData, result) {
|
|
1360
1523
|
let state;
|
|
1361
1524
|
if (result[0][1] && result[0][1].account) {
|
|
1362
1525
|
// existing user
|
|
@@ -1443,19 +1606,11 @@ class Account {
|
|
|
1443
1606
|
this.logger.error({ msg: 'Failed to request reconnect after re-auth', account: this.account, state: oldState, err });
|
|
1444
1607
|
}
|
|
1445
1608
|
} else {
|
|
1446
|
-
await this.
|
|
1447
|
-
cmd: 'update',
|
|
1448
|
-
account: this.account,
|
|
1449
|
-
timeout: this.timeout
|
|
1450
|
-
});
|
|
1609
|
+
await this.notifyWorker('update');
|
|
1451
1610
|
}
|
|
1452
1611
|
} else {
|
|
1453
1612
|
state = 'new';
|
|
1454
|
-
await this.
|
|
1455
|
-
cmd: 'new',
|
|
1456
|
-
account: this.account,
|
|
1457
|
-
timeout: this.timeout
|
|
1458
|
-
});
|
|
1613
|
+
await this.notifyWorker('new');
|
|
1459
1614
|
}
|
|
1460
1615
|
|
|
1461
1616
|
return { account: this.account, state };
|
|
@@ -1508,11 +1663,12 @@ class Account {
|
|
|
1508
1663
|
.srem(`${REDIS_PREFIX}ia:accounts`, this.account)
|
|
1509
1664
|
.unlink(this.getMailboxListKey()) // mailbox list
|
|
1510
1665
|
.unlink(this.getMailboxHashKey()) // mailbox list for ID references
|
|
1511
|
-
.unlink(`${REDIS_PREFIX}iar:b:${this.account}`) // bounce
|
|
1666
|
+
.unlink(`${REDIS_PREFIX}iar:b:${this.account}`) // retired bounce store, an older version sharing this Redis may still write it
|
|
1512
1667
|
.unlink(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
|
|
1513
1668
|
.unlink(`${REDIS_PREFIX}iaq:${this.account}`) // delayed message queue
|
|
1514
1669
|
.unlink(`${REDIS_PREFIX}iac:${this.account}`) // cache hash
|
|
1515
1670
|
.unlink(`${REDIS_PREFIX}iap:${this.account}`) // external event notification queue
|
|
1671
|
+
.unlink(this.getDeferredQueueKey()) // mailbox changes waiting for a retry
|
|
1516
1672
|
|
|
1517
1673
|
.unlink(tombstoneTdy)
|
|
1518
1674
|
.unlink(tombstoneYdy)
|
|
@@ -1557,7 +1713,12 @@ class Account {
|
|
|
1557
1713
|
|
|
1558
1714
|
// scan and delete keys
|
|
1559
1715
|
// should we wait though? might take a lot of time
|
|
1560
|
-
|
|
1716
|
+
// Best effort like the cleanups above: the account record is already gone
|
|
1717
|
+
try {
|
|
1718
|
+
await redisScanDelete(this.redis, this.logger, `${escapeRedisGlob(REDIS_PREFIX)}iam:${escapeRedisGlob(this.account)}:*`);
|
|
1719
|
+
} catch (err) {
|
|
1720
|
+
this.logger.error({ msg: 'Failed to delete the log keys of a deleted account', account: this.account, err });
|
|
1721
|
+
}
|
|
1561
1722
|
|
|
1562
1723
|
if (!result || !result[1] || !result[1][1]) {
|
|
1563
1724
|
return {
|
|
@@ -1566,39 +1727,7 @@ class Account {
|
|
|
1566
1727
|
};
|
|
1567
1728
|
}
|
|
1568
1729
|
|
|
1569
|
-
|
|
1570
|
-
// When it is off the documents worker is not running, so an enqueued job would never be
|
|
1571
|
-
// consumed and would pile up in Redis.
|
|
1572
|
-
if (documentStoreFeatureEnabled) {
|
|
1573
|
-
try {
|
|
1574
|
-
let queueKeep = (await settings.get('queueKeep')) ?? true;
|
|
1575
|
-
let serviceUrl = (await settings.get('serviceUrl')) || null;
|
|
1576
|
-
|
|
1577
|
-
let payload = {
|
|
1578
|
-
serviceUrl,
|
|
1579
|
-
account: this.account,
|
|
1580
|
-
date: new Date().toISOString(),
|
|
1581
|
-
event: ACCOUNT_DELETED_NOTIFY
|
|
1582
|
-
};
|
|
1583
|
-
|
|
1584
|
-
await this.documentsQueue.add(ACCOUNT_DELETED_NOTIFY, payload, {
|
|
1585
|
-
...buildRetentionPolicy(queueKeep),
|
|
1586
|
-
attempts: 10,
|
|
1587
|
-
backoff: {
|
|
1588
|
-
type: 'exponential',
|
|
1589
|
-
delay: 5000
|
|
1590
|
-
}
|
|
1591
|
-
});
|
|
1592
|
-
} catch (err) {
|
|
1593
|
-
this.logger.error({ msg: 'Failed to add entry to documents queue', account: this.account, err });
|
|
1594
|
-
}
|
|
1595
|
-
}
|
|
1596
|
-
|
|
1597
|
-
await this.call({
|
|
1598
|
-
cmd: 'delete',
|
|
1599
|
-
account: this.account,
|
|
1600
|
-
timeout: this.timeout
|
|
1601
|
-
});
|
|
1730
|
+
await this.notifyWorker('delete');
|
|
1602
1731
|
|
|
1603
1732
|
return {
|
|
1604
1733
|
account: this.account,
|
|
@@ -2002,43 +2131,6 @@ class Account {
|
|
|
2002
2131
|
options = Object.assign({}, options, { textType: '*' });
|
|
2003
2132
|
}
|
|
2004
2133
|
|
|
2005
|
-
if (options.documentStore && (await isDocumentStoreEnabled())) {
|
|
2006
|
-
await this.loadAccountData(this.account, false);
|
|
2007
|
-
|
|
2008
|
-
const { index, client } = this.esClient;
|
|
2009
|
-
|
|
2010
|
-
let buf = Buffer.from(text, 'base64url');
|
|
2011
|
-
let message = buf.subarray(0, 8).toString('base64url');
|
|
2012
|
-
|
|
2013
|
-
let getResult = await client.get({
|
|
2014
|
-
index,
|
|
2015
|
-
id: `${this.account}:${message}`
|
|
2016
|
-
});
|
|
2017
|
-
|
|
2018
|
-
this.logger.trace({
|
|
2019
|
-
msg: 'Executed ES query',
|
|
2020
|
-
query: { type: 'get', index, id: `${this.account}:${message}` },
|
|
2021
|
-
results: getResult && getResult._source ? 1 : 0
|
|
2022
|
-
});
|
|
2023
|
-
|
|
2024
|
-
let messageData = this.assertMessageFound(getResult && getResult._source);
|
|
2025
|
-
let response = {};
|
|
2026
|
-
|
|
2027
|
-
response.hasMore = false;
|
|
2028
|
-
for (let textType of Object.keys(messageData.text || {})) {
|
|
2029
|
-
if (['plain', 'html'].includes(textType) && (options.textType === '*' || options.textType === textType)) {
|
|
2030
|
-
if (options.maxBytes && messageData.text[textType].length > options.maxBytes) {
|
|
2031
|
-
response[textType] = messageData.text[textType].substring(0, options.maxBytes);
|
|
2032
|
-
response.hasMore = true;
|
|
2033
|
-
} else {
|
|
2034
|
-
response[textType] = messageData.text[textType];
|
|
2035
|
-
}
|
|
2036
|
-
}
|
|
2037
|
-
}
|
|
2038
|
-
|
|
2039
|
-
return this.textResponse(response, options);
|
|
2040
|
-
}
|
|
2041
|
-
|
|
2042
2134
|
await this.loadAccountData(this.account, true);
|
|
2043
2135
|
|
|
2044
2136
|
let textData = await this.call({
|
|
@@ -2050,185 +2142,13 @@ class Account {
|
|
|
2050
2142
|
});
|
|
2051
2143
|
|
|
2052
2144
|
// IMAP backend returns false for unknown messages and folders
|
|
2053
|
-
|
|
2054
|
-
}
|
|
2055
|
-
|
|
2056
|
-
// The one exit of getText(), so the document-store branch and the live one cannot answer a
|
|
2057
|
-
// webSafeHtml request differently
|
|
2058
|
-
async textResponse(textData, options) {
|
|
2145
|
+
textData = this.assertMessageFound(textData);
|
|
2059
2146
|
return options.webSafeHtml ? webSafeTextResponse(textData) : textData;
|
|
2060
2147
|
}
|
|
2061
2148
|
|
|
2062
2149
|
async getMessage(message, options) {
|
|
2063
2150
|
applyWebSafeHtmlOptions(options);
|
|
2064
2151
|
|
|
2065
|
-
if (options.documentStore && (await isDocumentStoreEnabled())) {
|
|
2066
|
-
await this.loadAccountData(this.account, false);
|
|
2067
|
-
|
|
2068
|
-
const { index, client } = this.esClient;
|
|
2069
|
-
|
|
2070
|
-
const reqOpts = {
|
|
2071
|
-
index,
|
|
2072
|
-
id: `${this.account}:${message}`,
|
|
2073
|
-
_source_excludes: 'preview,seemsLikeNew,account,created,updateTime'
|
|
2074
|
-
};
|
|
2075
|
-
|
|
2076
|
-
switch (options.textType) {
|
|
2077
|
-
case '*':
|
|
2078
|
-
break;
|
|
2079
|
-
case 'html':
|
|
2080
|
-
reqOpts._source_excludes += ',text.plain';
|
|
2081
|
-
break;
|
|
2082
|
-
case 'plain':
|
|
2083
|
-
reqOpts._source_excludes += ',text.html,text._generatedHtml';
|
|
2084
|
-
break;
|
|
2085
|
-
default:
|
|
2086
|
-
reqOpts._source_excludes += ',text.plain,text.html,text._generatedHtml';
|
|
2087
|
-
}
|
|
2088
|
-
|
|
2089
|
-
let getResult = await client.get(reqOpts);
|
|
2090
|
-
|
|
2091
|
-
this.logger.trace({
|
|
2092
|
-
msg: 'Executed ES query',
|
|
2093
|
-
query: { type: 'get', index, id: `${this.account}:${message}` },
|
|
2094
|
-
results: getResult && getResult._source ? 1 : 0
|
|
2095
|
-
});
|
|
2096
|
-
|
|
2097
|
-
let messageData = this.assertMessageFound(getResult && getResult._source);
|
|
2098
|
-
|
|
2099
|
-
// restore headers and text object as per the API response
|
|
2100
|
-
let headersObj = {};
|
|
2101
|
-
for (let { key, value } of messageData.headers) {
|
|
2102
|
-
headersObj[key] = value;
|
|
2103
|
-
}
|
|
2104
|
-
messageData.headers = headersObj;
|
|
2105
|
-
|
|
2106
|
-
if (messageData.text && (messageData.text.html || messageData.text.plain)) {
|
|
2107
|
-
messageData.text.hasMore = false;
|
|
2108
|
-
|
|
2109
|
-
for (let textType of Object.keys(messageData.text || {})) {
|
|
2110
|
-
if (['plain', 'html'].includes(textType) && options.maxBytes && messageData.text[textType].length > options.maxBytes) {
|
|
2111
|
-
messageData.text[textType] = messageData.text[textType].substring(0, options.maxBytes);
|
|
2112
|
-
messageData.text.hasMore = true;
|
|
2113
|
-
}
|
|
2114
|
-
}
|
|
2115
|
-
}
|
|
2116
|
-
|
|
2117
|
-
for (let key of ['unseen', 'flagged', 'answered', 'draft']) {
|
|
2118
|
-
if (messageData[key] === false) {
|
|
2119
|
-
delete messageData[key];
|
|
2120
|
-
}
|
|
2121
|
-
}
|
|
2122
|
-
|
|
2123
|
-
if (options.preProcessHtml && messageData.text && (messageData.text.html || messageData.text.plain)) {
|
|
2124
|
-
// If available, use the cached version
|
|
2125
|
-
messageData.text.html = messageData.text._generatedHtml || (await messageWebSafeHtml(messageData));
|
|
2126
|
-
messageData.text.webSafe = true;
|
|
2127
|
-
messageData.text._cachedWebSafe = !!messageData.text._generatedHtml;
|
|
2128
|
-
}
|
|
2129
|
-
|
|
2130
|
-
if (options.embedAttachedImages && messageData.text && messageData.text.html && messageData.attachments && messageData.attachments.length) {
|
|
2131
|
-
// map both content id forms (bare and <bracketed>) to the first attachment carrying them,
|
|
2132
|
-
// so the passes below cost one lookup per reference instead of a scan of all attachments
|
|
2133
|
-
let attachmentsByContentId = new Map();
|
|
2134
|
-
for (let attachment of messageData.attachments) {
|
|
2135
|
-
if (!attachment.contentId) {
|
|
2136
|
-
continue;
|
|
2137
|
-
}
|
|
2138
|
-
for (let key of [attachment.contentId, attachment.contentId.replace(/^<(.*)>$/, '$1')]) {
|
|
2139
|
-
if (!attachmentsByContentId.has(key)) {
|
|
2140
|
-
attachmentsByContentId.set(key, attachment);
|
|
2141
|
-
}
|
|
2142
|
-
}
|
|
2143
|
-
}
|
|
2144
|
-
|
|
2145
|
-
// first pass, find attachments to inline
|
|
2146
|
-
let attachmentsToDownload = new Set();
|
|
2147
|
-
for (let match of messageData.text.html.matchAll(cidReferenceRegex())) {
|
|
2148
|
-
let attachment = attachmentsByContentId.get(match[1]);
|
|
2149
|
-
if (attachment && !attachment.content) {
|
|
2150
|
-
attachmentsToDownload.add(attachment);
|
|
2151
|
-
}
|
|
2152
|
-
}
|
|
2153
|
-
|
|
2154
|
-
// download large inline attachments not stored in ES
|
|
2155
|
-
for (let attachment of attachmentsToDownload) {
|
|
2156
|
-
let downloadStream;
|
|
2157
|
-
try {
|
|
2158
|
-
downloadStream = await this.getAttachment(attachment.id);
|
|
2159
|
-
if (downloadStream) {
|
|
2160
|
-
let content = await download(downloadStream);
|
|
2161
|
-
this.logger.trace({ msg: 'Fetched attachment content', account: this.account, attachment, size: content.length });
|
|
2162
|
-
attachment.content = content.toString('base64');
|
|
2163
|
-
}
|
|
2164
|
-
} catch (err) {
|
|
2165
|
-
// Release the reader if download() failed mid-stream so its
|
|
2166
|
-
// MessagePort is not left open (destroy() is idempotent).
|
|
2167
|
-
if (downloadStream) {
|
|
2168
|
-
downloadStream.destroy();
|
|
2169
|
-
}
|
|
2170
|
-
this.logger.error({ msg: 'Failed to fetch attachment content', account: this.account, attachment, err });
|
|
2171
|
-
}
|
|
2172
|
-
}
|
|
2173
|
-
|
|
2174
|
-
// second pass, replace placeholders with inline attachments
|
|
2175
|
-
messageData.text.html = messageData.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
|
|
2176
|
-
let attachment = attachmentsByContentId.get(cidMatch);
|
|
2177
|
-
if (attachment && attachment.content) {
|
|
2178
|
-
return `data:${attachment.contentType || 'application/octet-stream'};base64,${attachment.content}`;
|
|
2179
|
-
}
|
|
2180
|
-
return fullMatch;
|
|
2181
|
-
});
|
|
2182
|
-
}
|
|
2183
|
-
|
|
2184
|
-
if (messageData.text && messageData.text._generatedHtml) {
|
|
2185
|
-
// remove cached pre-processed HTML from output
|
|
2186
|
-
delete messageData.text._generatedHtml;
|
|
2187
|
-
}
|
|
2188
|
-
|
|
2189
|
-
// Add event file content if the attachment exists
|
|
2190
|
-
if (messageData.calendarEvents) {
|
|
2191
|
-
for (let calendarEvent of messageData.calendarEvents) {
|
|
2192
|
-
if (!calendarEvent.content && calendarEvent.attachment) {
|
|
2193
|
-
let attachment = messageData.attachments && messageData.attachments.find(attachment => attachment.id === calendarEvent.attachment);
|
|
2194
|
-
if (attachment && attachment.content) {
|
|
2195
|
-
calendarEvent.encoding = 'base64';
|
|
2196
|
-
calendarEvent.content = attachment.content;
|
|
2197
|
-
}
|
|
2198
|
-
}
|
|
2199
|
-
}
|
|
2200
|
-
}
|
|
2201
|
-
|
|
2202
|
-
if (messageData.attachments) {
|
|
2203
|
-
for (let attachment of messageData.attachments) {
|
|
2204
|
-
delete attachment.content;
|
|
2205
|
-
}
|
|
2206
|
-
}
|
|
2207
|
-
|
|
2208
|
-
if (options.markAsSeen && (!messageData.flags || !messageData.flags.includes('\\Seen'))) {
|
|
2209
|
-
// mark message as seen
|
|
2210
|
-
if (!messageData.flags) {
|
|
2211
|
-
messageData.flags = [];
|
|
2212
|
-
}
|
|
2213
|
-
messageData.flags.push('\\Seen');
|
|
2214
|
-
// do not wait until the update is completed, return immediately
|
|
2215
|
-
this.updateMessage(message, { flags: { add: ['\\Seen'] } }).catch(err => {
|
|
2216
|
-
this.logger.error({ msg: 'Failed to mark message as Seen', account: this.account, message, err });
|
|
2217
|
-
});
|
|
2218
|
-
}
|
|
2219
|
-
|
|
2220
|
-
if (messageData.specialUse && !messageData.messageSpecialUse) {
|
|
2221
|
-
for (let specialUseTag of ['\\Junk', '\\Sent', '\\Trash', '\\Inbox', '\\Drafts']) {
|
|
2222
|
-
if (messageData.specialUse === specialUseTag || (messageData.labels && messageData.labels.includes(specialUseTag))) {
|
|
2223
|
-
messageData.messageSpecialUse = specialUseTag;
|
|
2224
|
-
break;
|
|
2225
|
-
}
|
|
2226
|
-
}
|
|
2227
|
-
}
|
|
2228
|
-
|
|
2229
|
-
return messageData;
|
|
2230
|
-
}
|
|
2231
|
-
|
|
2232
2152
|
await this.loadAccountData(this.account, true);
|
|
2233
2153
|
|
|
2234
2154
|
let messageData = await this.call({
|
|
@@ -2254,107 +2174,6 @@ class Account {
|
|
|
2254
2174
|
}
|
|
2255
2175
|
|
|
2256
2176
|
async listMessages(query) {
|
|
2257
|
-
if (query.documentStore && (await isDocumentStoreEnabled())) {
|
|
2258
|
-
await this.loadAccountData(this.account, false);
|
|
2259
|
-
|
|
2260
|
-
const { index, client } = this.esClient;
|
|
2261
|
-
|
|
2262
|
-
let inboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), 'INBOX'));
|
|
2263
|
-
let delimiter = inboxData ? inboxData.delimiter : '/'; // hope for the best
|
|
2264
|
-
|
|
2265
|
-
inboxData = inboxData || {
|
|
2266
|
-
path: 'INBOX',
|
|
2267
|
-
delimiter
|
|
2268
|
-
};
|
|
2269
|
-
|
|
2270
|
-
inboxData.specialUse = inboxData.specialUse || '\\Inbox';
|
|
2271
|
-
|
|
2272
|
-
let path = normalizePath(query.path, delimiter);
|
|
2273
|
-
let mailboxData = path === 'INBOX' ? inboxData : false;
|
|
2274
|
-
if (!mailboxData) {
|
|
2275
|
-
mailboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), path));
|
|
2276
|
-
}
|
|
2277
|
-
|
|
2278
|
-
let searchQuery = {
|
|
2279
|
-
bool: {
|
|
2280
|
-
must: [
|
|
2281
|
-
{
|
|
2282
|
-
term: {
|
|
2283
|
-
account: this.account
|
|
2284
|
-
}
|
|
2285
|
-
}
|
|
2286
|
-
]
|
|
2287
|
-
}
|
|
2288
|
-
};
|
|
2289
|
-
|
|
2290
|
-
searchQuery.bool.must.push({
|
|
2291
|
-
bool: {
|
|
2292
|
-
should: [
|
|
2293
|
-
{
|
|
2294
|
-
term: {
|
|
2295
|
-
path
|
|
2296
|
-
}
|
|
2297
|
-
},
|
|
2298
|
-
{
|
|
2299
|
-
term: {
|
|
2300
|
-
labels: (mailboxData && mailboxData.specialUse) || path
|
|
2301
|
-
}
|
|
2302
|
-
}
|
|
2303
|
-
],
|
|
2304
|
-
minimum_should_match: 1
|
|
2305
|
-
}
|
|
2306
|
-
});
|
|
2307
|
-
|
|
2308
|
-
let page = Number(query.page) || 0;
|
|
2309
|
-
let pageSize = Math.abs(Number(query.pageSize) || 20);
|
|
2310
|
-
|
|
2311
|
-
if (page < 0) {
|
|
2312
|
-
page = 0;
|
|
2313
|
-
}
|
|
2314
|
-
|
|
2315
|
-
let searchResult = await client.search({
|
|
2316
|
-
index,
|
|
2317
|
-
size: pageSize,
|
|
2318
|
-
from: pageSize * page,
|
|
2319
|
-
query: searchQuery,
|
|
2320
|
-
sort: { uid: 'desc' },
|
|
2321
|
-
_source_excludes: 'headers,text.plain,text.html,text._generatedHtml,seemsLikeNew,attachments.content,summary,riskAssessment,updateTime'
|
|
2322
|
-
});
|
|
2323
|
-
|
|
2324
|
-
this.logger.trace({
|
|
2325
|
-
msg: 'Executed ES query',
|
|
2326
|
-
query: { type: 'search', index, size: pageSize, from: pageSize * page, query: searchQuery, sort: { uid: 'desc' } },
|
|
2327
|
-
results: searchResult.hits.total.value
|
|
2328
|
-
});
|
|
2329
|
-
|
|
2330
|
-
let response = {
|
|
2331
|
-
total: searchResult.hits.total.value,
|
|
2332
|
-
page,
|
|
2333
|
-
pages: Math.max(Math.ceil(searchResult.hits.total.value / pageSize), 1),
|
|
2334
|
-
messages: searchResult.hits.hits.map(entry => {
|
|
2335
|
-
let messageData = entry._source;
|
|
2336
|
-
|
|
2337
|
-
// normalize as per the API response
|
|
2338
|
-
|
|
2339
|
-
for (let key of ['unseen', 'flagged', 'answered', 'draft']) {
|
|
2340
|
-
if (messageData[key] === false) {
|
|
2341
|
-
messageData[key] = undefined;
|
|
2342
|
-
}
|
|
2343
|
-
}
|
|
2344
|
-
|
|
2345
|
-
for (let key of ['account', 'created', 'specialUse']) {
|
|
2346
|
-
if (messageData[key]) {
|
|
2347
|
-
messageData[key] = undefined;
|
|
2348
|
-
}
|
|
2349
|
-
}
|
|
2350
|
-
|
|
2351
|
-
return messageData;
|
|
2352
|
-
})
|
|
2353
|
-
};
|
|
2354
|
-
|
|
2355
|
-
return response;
|
|
2356
|
-
}
|
|
2357
|
-
|
|
2358
2177
|
await this.loadAccountData(this.account, true);
|
|
2359
2178
|
|
|
2360
2179
|
let listing = await this.call(
|
|
@@ -2372,394 +2191,9 @@ class Account {
|
|
|
2372
2191
|
return this.assertFolderFound(listing);
|
|
2373
2192
|
}
|
|
2374
2193
|
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
if (!searchOpts.unified) {
|
|
2379
|
-
await this.loadAccountData(this.account, false);
|
|
2380
|
-
}
|
|
2381
|
-
|
|
2382
|
-
const { index, client } = this.esClient;
|
|
2383
|
-
|
|
2384
|
-
let searchQuery = {
|
|
2385
|
-
bool: {
|
|
2386
|
-
must: []
|
|
2387
|
-
}
|
|
2388
|
-
};
|
|
2389
|
-
|
|
2390
|
-
if (this.account) {
|
|
2391
|
-
searchQuery.bool.must.push({
|
|
2392
|
-
term: {
|
|
2393
|
-
account: this.account
|
|
2394
|
-
}
|
|
2395
|
-
});
|
|
2396
|
-
}
|
|
2397
|
-
|
|
2398
|
-
if (searchOpts.unified && query.accounts && query.accounts.length) {
|
|
2399
|
-
searchQuery.bool.must.push({
|
|
2400
|
-
bool: {
|
|
2401
|
-
should: query.accounts.map(account => ({
|
|
2402
|
-
term: {
|
|
2403
|
-
account
|
|
2404
|
-
}
|
|
2405
|
-
})),
|
|
2406
|
-
minimum_should_match: 1
|
|
2407
|
-
}
|
|
2408
|
-
});
|
|
2409
|
-
}
|
|
2410
|
-
|
|
2411
|
-
if (query.path) {
|
|
2412
|
-
let inboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), 'INBOX'));
|
|
2413
|
-
let delimiter = inboxData ? inboxData.delimiter : '/'; // hope for the best
|
|
2414
|
-
|
|
2415
|
-
inboxData = inboxData || {
|
|
2416
|
-
path: 'INBOX',
|
|
2417
|
-
delimiter
|
|
2418
|
-
};
|
|
2419
|
-
|
|
2420
|
-
inboxData.specialUse = inboxData.specialUse || '\\Inbox';
|
|
2421
|
-
|
|
2422
|
-
let path = normalizePath(query.path, delimiter);
|
|
2423
|
-
let mailboxData = path === 'INBOX' ? inboxData : false;
|
|
2424
|
-
if (!mailboxData) {
|
|
2425
|
-
mailboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), path));
|
|
2426
|
-
}
|
|
2427
|
-
|
|
2428
|
-
searchQuery.bool.must.push({
|
|
2429
|
-
bool: {
|
|
2430
|
-
should: [
|
|
2431
|
-
{
|
|
2432
|
-
term: {
|
|
2433
|
-
path
|
|
2434
|
-
}
|
|
2435
|
-
},
|
|
2436
|
-
{
|
|
2437
|
-
term: {
|
|
2438
|
-
labels: (mailboxData && mailboxData.specialUse) || path
|
|
2439
|
-
}
|
|
2440
|
-
}
|
|
2441
|
-
],
|
|
2442
|
-
minimum_should_match: 1
|
|
2443
|
-
}
|
|
2444
|
-
});
|
|
2445
|
-
}
|
|
2446
|
-
|
|
2447
|
-
if (searchOpts.unified && query.paths && query.paths.length) {
|
|
2448
|
-
searchQuery.bool.must.push({
|
|
2449
|
-
bool: {
|
|
2450
|
-
should: query.paths.flatMap(path => {
|
|
2451
|
-
let res = [
|
|
2452
|
-
{
|
|
2453
|
-
term: {
|
|
2454
|
-
path
|
|
2455
|
-
}
|
|
2456
|
-
},
|
|
2457
|
-
{
|
|
2458
|
-
term: {
|
|
2459
|
-
labels: path
|
|
2460
|
-
}
|
|
2461
|
-
},
|
|
2462
|
-
{
|
|
2463
|
-
term: {
|
|
2464
|
-
messageSpecialUse: path
|
|
2465
|
-
}
|
|
2466
|
-
}
|
|
2467
|
-
];
|
|
2468
|
-
|
|
2469
|
-
if (/^inbox$/i.test(path)) {
|
|
2470
|
-
res.push({
|
|
2471
|
-
term: {
|
|
2472
|
-
messageSpecialUse: '\\Inbox'
|
|
2473
|
-
}
|
|
2474
|
-
});
|
|
2475
|
-
}
|
|
2476
|
-
|
|
2477
|
-
return res;
|
|
2478
|
-
}),
|
|
2479
|
-
minimum_should_match: 1
|
|
2480
|
-
}
|
|
2481
|
-
});
|
|
2482
|
-
}
|
|
2483
|
-
|
|
2484
|
-
for (let key of ['answered', 'deleted', 'draft', 'unseen', 'flagged']) {
|
|
2485
|
-
if (typeof query.search[key] === 'boolean') {
|
|
2486
|
-
searchQuery.bool.must.push({
|
|
2487
|
-
term: {
|
|
2488
|
-
[key]: query.search[key]
|
|
2489
|
-
}
|
|
2490
|
-
});
|
|
2491
|
-
}
|
|
2492
|
-
}
|
|
2493
|
-
|
|
2494
|
-
if (typeof query.search.seen === 'boolean') {
|
|
2495
|
-
searchQuery.bool.must.push({
|
|
2496
|
-
term: {
|
|
2497
|
-
unseen: !query.search.seen
|
|
2498
|
-
}
|
|
2499
|
-
});
|
|
2500
|
-
}
|
|
2501
|
-
|
|
2502
|
-
for (let key of ['from', 'to', 'cc', 'bcc']) {
|
|
2503
|
-
if (query.search[key]) {
|
|
2504
|
-
searchQuery.bool.must.push({
|
|
2505
|
-
bool: {
|
|
2506
|
-
should: [
|
|
2507
|
-
{
|
|
2508
|
-
match: {
|
|
2509
|
-
[`${key}.name`]: {
|
|
2510
|
-
query: query.search[key],
|
|
2511
|
-
operator: 'and'
|
|
2512
|
-
}
|
|
2513
|
-
}
|
|
2514
|
-
},
|
|
2515
|
-
{
|
|
2516
|
-
term: {
|
|
2517
|
-
[`${key}.address`]: query.search[key]
|
|
2518
|
-
}
|
|
2519
|
-
}
|
|
2520
|
-
],
|
|
2521
|
-
minimum_should_match: 1
|
|
2522
|
-
}
|
|
2523
|
-
});
|
|
2524
|
-
}
|
|
2525
|
-
}
|
|
2526
|
-
|
|
2527
|
-
if (query.search.uid) {
|
|
2528
|
-
let uidEntries = unpackUIDRangeForSearch(query.search.uid);
|
|
2529
|
-
if (uidEntries && uidEntries.length) {
|
|
2530
|
-
let mustList = [];
|
|
2531
|
-
for (let entry of uidEntries) {
|
|
2532
|
-
if (typeof entry === 'number') {
|
|
2533
|
-
mustList.push({
|
|
2534
|
-
match: {
|
|
2535
|
-
uid: {
|
|
2536
|
-
query: entry,
|
|
2537
|
-
operator: 'and'
|
|
2538
|
-
}
|
|
2539
|
-
}
|
|
2540
|
-
});
|
|
2541
|
-
} else if (typeof entry === 'object') {
|
|
2542
|
-
mustList.push({
|
|
2543
|
-
range: {
|
|
2544
|
-
uid: entry
|
|
2545
|
-
}
|
|
2546
|
-
});
|
|
2547
|
-
}
|
|
2548
|
-
}
|
|
2549
|
-
|
|
2550
|
-
if (mustList.length) {
|
|
2551
|
-
searchQuery.bool.must.push({
|
|
2552
|
-
bool: {
|
|
2553
|
-
should: mustList,
|
|
2554
|
-
minimum_should_match: 1
|
|
2555
|
-
}
|
|
2556
|
-
});
|
|
2557
|
-
}
|
|
2558
|
-
}
|
|
2559
|
-
}
|
|
2560
|
-
|
|
2561
|
-
for (let key of ['emailId', 'threadId']) {
|
|
2562
|
-
if (query.search[key]) {
|
|
2563
|
-
searchQuery.bool.must.push({
|
|
2564
|
-
term: {
|
|
2565
|
-
[key]: query.search[key]
|
|
2566
|
-
}
|
|
2567
|
-
});
|
|
2568
|
-
}
|
|
2569
|
-
}
|
|
2570
|
-
|
|
2571
|
-
if (query.search.subject) {
|
|
2572
|
-
searchQuery.bool.must.push({
|
|
2573
|
-
match: {
|
|
2574
|
-
subject: {
|
|
2575
|
-
query: query.search.subject,
|
|
2576
|
-
operator: 'and'
|
|
2577
|
-
}
|
|
2578
|
-
}
|
|
2579
|
-
});
|
|
2580
|
-
}
|
|
2581
|
-
|
|
2582
|
-
if (query.search.body) {
|
|
2583
|
-
searchQuery.bool.must.push({
|
|
2584
|
-
bool: {
|
|
2585
|
-
should: [
|
|
2586
|
-
{
|
|
2587
|
-
match: {
|
|
2588
|
-
'text.plain': {
|
|
2589
|
-
query: query.search.body,
|
|
2590
|
-
operator: 'and'
|
|
2591
|
-
}
|
|
2592
|
-
}
|
|
2593
|
-
},
|
|
2594
|
-
{
|
|
2595
|
-
match: {
|
|
2596
|
-
'text.html': {
|
|
2597
|
-
query: query.search.body,
|
|
2598
|
-
operator: 'and'
|
|
2599
|
-
}
|
|
2600
|
-
}
|
|
2601
|
-
}
|
|
2602
|
-
],
|
|
2603
|
-
minimum_should_match: 1
|
|
2604
|
-
}
|
|
2605
|
-
});
|
|
2606
|
-
}
|
|
2607
|
-
|
|
2608
|
-
let dateMatch = {};
|
|
2609
|
-
|
|
2610
|
-
for (let key of ['before', 'sentBefore']) {
|
|
2611
|
-
if (query.search[key]) {
|
|
2612
|
-
dateMatch.lte = query.search[key];
|
|
2613
|
-
}
|
|
2614
|
-
}
|
|
2615
|
-
|
|
2616
|
-
for (let key of ['since', 'sentSince']) {
|
|
2617
|
-
if (query.search[key]) {
|
|
2618
|
-
dateMatch.gte = query.search[key];
|
|
2619
|
-
}
|
|
2620
|
-
}
|
|
2621
|
-
|
|
2622
|
-
if (Object.keys(dateMatch).length) {
|
|
2623
|
-
searchQuery.bool.must.push({
|
|
2624
|
-
range: { date: dateMatch }
|
|
2625
|
-
});
|
|
2626
|
-
}
|
|
2627
|
-
|
|
2628
|
-
let sizeMatch = {};
|
|
2629
|
-
|
|
2630
|
-
if (query.search.larger) {
|
|
2631
|
-
sizeMatch.gte = query.search.larger;
|
|
2632
|
-
}
|
|
2633
|
-
|
|
2634
|
-
if (query.search.smaller) {
|
|
2635
|
-
sizeMatch.lte = query.search.smaller;
|
|
2636
|
-
}
|
|
2637
|
-
|
|
2638
|
-
if (Object.keys(sizeMatch).length) {
|
|
2639
|
-
searchQuery.bool.must.push({
|
|
2640
|
-
range: { size: sizeMatch }
|
|
2641
|
-
});
|
|
2642
|
-
}
|
|
2643
|
-
|
|
2644
|
-
// headers, nested query
|
|
2645
|
-
if (Object.keys(query.search.header || {}).length) {
|
|
2646
|
-
Object.keys(query.search.header).forEach(header => {
|
|
2647
|
-
searchQuery.bool.must.push({
|
|
2648
|
-
nested: {
|
|
2649
|
-
path: 'headers',
|
|
2650
|
-
query: {
|
|
2651
|
-
bool: {
|
|
2652
|
-
must: [
|
|
2653
|
-
{
|
|
2654
|
-
term: {
|
|
2655
|
-
'headers.key': header.toLowerCase()
|
|
2656
|
-
}
|
|
2657
|
-
},
|
|
2658
|
-
{
|
|
2659
|
-
match: {
|
|
2660
|
-
'headers.value': {
|
|
2661
|
-
query: (query.search.header[header] || '').toString(),
|
|
2662
|
-
operator: 'and'
|
|
2663
|
-
}
|
|
2664
|
-
}
|
|
2665
|
-
}
|
|
2666
|
-
]
|
|
2667
|
-
}
|
|
2668
|
-
}
|
|
2669
|
-
}
|
|
2670
|
-
});
|
|
2671
|
-
});
|
|
2672
|
-
}
|
|
2673
|
-
|
|
2674
|
-
if (query.documentQuery) {
|
|
2675
|
-
searchQuery.bool.must.push(query.documentQuery);
|
|
2676
|
-
}
|
|
2677
|
-
|
|
2678
|
-
let page = Number(query.page) || 0;
|
|
2679
|
-
let pageSize = Math.abs(Number(query.pageSize) || 20);
|
|
2680
|
-
|
|
2681
|
-
if (page < 0) {
|
|
2682
|
-
page = 0;
|
|
2683
|
-
}
|
|
2684
|
-
|
|
2685
|
-
let searchResult = await client.search({
|
|
2686
|
-
index,
|
|
2687
|
-
size: pageSize,
|
|
2688
|
-
from: pageSize * page,
|
|
2689
|
-
query: searchQuery,
|
|
2690
|
-
sort: { [!searchOpts.unified ? 'uid' : 'date']: 'desc' },
|
|
2691
|
-
_source_excludes: 'headers,text.plain,text.html,text._generatedHtml,seemsLikeNew,attachments.content,summary,riskAssessment,updateTime'
|
|
2692
|
-
});
|
|
2693
|
-
|
|
2694
|
-
this.logger.trace({
|
|
2695
|
-
msg: 'Executed ES query',
|
|
2696
|
-
query: {
|
|
2697
|
-
type: 'search',
|
|
2698
|
-
index,
|
|
2699
|
-
size: pageSize,
|
|
2700
|
-
from: pageSize * page,
|
|
2701
|
-
query: searchQuery,
|
|
2702
|
-
sort: { [!searchOpts.unified ? 'uid' : 'date']: 'desc' }
|
|
2703
|
-
},
|
|
2704
|
-
results: searchResult.hits.total.value
|
|
2705
|
-
});
|
|
2706
|
-
|
|
2707
|
-
let response = {
|
|
2708
|
-
total: searchResult.hits.total.value,
|
|
2709
|
-
page,
|
|
2710
|
-
pages: Math.max(Math.ceil(searchResult.hits.total.value / pageSize), 1)
|
|
2711
|
-
};
|
|
2712
|
-
|
|
2713
|
-
if (query.exposeQuery) {
|
|
2714
|
-
response.documentStoreQuery = query;
|
|
2715
|
-
}
|
|
2716
|
-
|
|
2717
|
-
if (query.accounts) {
|
|
2718
|
-
response.accounts = query.accounts;
|
|
2719
|
-
}
|
|
2720
|
-
|
|
2721
|
-
if (query.paths) {
|
|
2722
|
-
response.paths = query.paths;
|
|
2723
|
-
}
|
|
2724
|
-
|
|
2725
|
-
response.messages = searchResult.hits.hits.map(entry => {
|
|
2726
|
-
let messageData = entry._source;
|
|
2727
|
-
|
|
2728
|
-
// normalize as per the API response
|
|
2729
|
-
|
|
2730
|
-
for (let key of ['unseen', 'flagged', 'answered', 'draft']) {
|
|
2731
|
-
if (messageData[key] === false) {
|
|
2732
|
-
messageData[key] = undefined;
|
|
2733
|
-
}
|
|
2734
|
-
}
|
|
2735
|
-
|
|
2736
|
-
for (let key of ['created', 'specialUse'].concat(!searchOpts.unified ? 'account' : [])) {
|
|
2737
|
-
if (messageData[key]) {
|
|
2738
|
-
messageData[key] = undefined;
|
|
2739
|
-
}
|
|
2740
|
-
}
|
|
2741
|
-
|
|
2742
|
-
return messageData;
|
|
2743
|
-
});
|
|
2744
|
-
|
|
2745
|
-
return response;
|
|
2746
|
-
}
|
|
2747
|
-
|
|
2748
|
-
await this.loadAccountData(this.account, true);
|
|
2749
|
-
|
|
2750
|
-
let listing = await this.call(
|
|
2751
|
-
Object.assign(
|
|
2752
|
-
{
|
|
2753
|
-
cmd: 'listMessages',
|
|
2754
|
-
account: this.account
|
|
2755
|
-
},
|
|
2756
|
-
query,
|
|
2757
|
-
{ timeout: this.timeout }
|
|
2758
|
-
)
|
|
2759
|
-
);
|
|
2760
|
-
|
|
2761
|
-
// IMAP and Gmail backends return false for unknown folders
|
|
2762
|
-
return this.assertFolderFound(listing);
|
|
2194
|
+
// A search is a listing with a `search` query; the same worker command answers both
|
|
2195
|
+
async searchMessages(query) {
|
|
2196
|
+
return await this.listMessages(query);
|
|
2763
2197
|
}
|
|
2764
2198
|
|
|
2765
2199
|
async uploadMessage(data) {
|
|
@@ -2933,7 +2367,7 @@ class Account {
|
|
|
2933
2367
|
// Note: mailbox ID hash (iah:) and listRegistry are intentionally NOT deleted
|
|
2934
2368
|
// to preserve message ID stability across reconnections. Message IDs depend on
|
|
2935
2369
|
// the specific mailbox ID entries, so deleting them would invalidate existing IDs.
|
|
2936
|
-
.del(`${REDIS_PREFIX}iar:b:${this.account}`) // bounce
|
|
2370
|
+
.del(`${REDIS_PREFIX}iar:b:${this.account}`) // retired bounce store, an older version sharing this Redis may still write it
|
|
2937
2371
|
.del(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
|
|
2938
2372
|
.del(tombstoneTdy)
|
|
2939
2373
|
.del(tombstoneYdy);
|
|
@@ -2942,64 +2376,10 @@ class Account {
|
|
|
2942
2376
|
pipeline = pipeline.hset(this.getAccountKey(), 'imapIndexer', imapIndexer);
|
|
2943
2377
|
}
|
|
2944
2378
|
|
|
2945
|
-
if (data.syncFrom || data.syncFrom === null) {
|
|
2946
|
-
pipeline = pipeline.hset(this.getAccountKey(), 'syncFrom', data.syncFrom ? data.syncFrom.toISOString() : 'null');
|
|
2947
|
-
}
|
|
2948
|
-
|
|
2949
2379
|
await pipeline.exec();
|
|
2950
2380
|
|
|
2951
2381
|
// scan and delete keys
|
|
2952
|
-
await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${escapeRedisGlob(this.account)}:*`);
|
|
2953
|
-
|
|
2954
|
-
if (await isDocumentStoreEnabled()) {
|
|
2955
|
-
// Flush ElasticSearch index for this account
|
|
2956
|
-
const { index, client } = this.esClient;
|
|
2957
|
-
if (!client) {
|
|
2958
|
-
// Account data in Redis was already flushed, only the index cleanup was skipped
|
|
2959
|
-
this.logger.error({ msg: 'Document store is enabled but the ElasticSearch client is not available', action: 'flush' });
|
|
2960
|
-
return true;
|
|
2961
|
-
}
|
|
2962
|
-
|
|
2963
|
-
let deleteResult = {};
|
|
2964
|
-
let deletedCount = 0;
|
|
2965
|
-
|
|
2966
|
-
let filterQuery = {
|
|
2967
|
-
match: {
|
|
2968
|
-
account: this.account
|
|
2969
|
-
}
|
|
2970
|
-
};
|
|
2971
|
-
|
|
2972
|
-
for (let indexName of [index, `${index}.threads`, `${index}.embeddings`]) {
|
|
2973
|
-
try {
|
|
2974
|
-
deleteResult[indexName] = await client.deleteByQuery({
|
|
2975
|
-
index: indexName,
|
|
2976
|
-
query: filterQuery
|
|
2977
|
-
});
|
|
2978
|
-
deletedCount += deleteResult[indexName].deleted || 0;
|
|
2979
|
-
} catch (err) {
|
|
2980
|
-
this.logger.error({
|
|
2981
|
-
msg: 'Failed to delete account emails from index',
|
|
2982
|
-
action: 'flush',
|
|
2983
|
-
code: 'document_delete_account_error',
|
|
2984
|
-
index: indexName,
|
|
2985
|
-
request: filterQuery,
|
|
2986
|
-
err
|
|
2987
|
-
});
|
|
2988
|
-
if (indexName === index) {
|
|
2989
|
-
throw err;
|
|
2990
|
-
}
|
|
2991
|
-
}
|
|
2992
|
-
}
|
|
2993
|
-
|
|
2994
|
-
this.logger.trace({
|
|
2995
|
-
msg: 'Deleted account emails from index',
|
|
2996
|
-
action: 'flush',
|
|
2997
|
-
code: 'document_delete_account',
|
|
2998
|
-
account: this.account,
|
|
2999
|
-
deletedCount,
|
|
3000
|
-
deleteResult
|
|
3001
|
-
});
|
|
3002
|
-
}
|
|
2382
|
+
await redisScanDelete(this.redis, this.logger, `${escapeRedisGlob(REDIS_PREFIX)}iam:${escapeRedisGlob(this.account)}:*`);
|
|
3003
2383
|
|
|
3004
2384
|
return true;
|
|
3005
2385
|
} finally {
|
|
@@ -3108,6 +2488,28 @@ class Account {
|
|
|
3108
2488
|
updates.scope = r.scope.split(/\s+/);
|
|
3109
2489
|
}
|
|
3110
2490
|
|
|
2491
|
+
// Only the token fields are written, merged into whatever is stored at write time, and
|
|
2492
|
+
// only while the stored grant is still the one this renewal used. The account was read
|
|
2493
|
+
// before the provider round trip and without the update lock, so writing that whole
|
|
2494
|
+
// snapshot back put an older refresh token and scope list over a re-authorization that
|
|
2495
|
+
// landed meanwhile. userFlag is cleared by a null, which unserialize drops.
|
|
2496
|
+
let usedRefreshToken = accountData.oauth2.refreshToken;
|
|
2497
|
+
let writeResult = await this.update(
|
|
2498
|
+
{ account: accountData.account, oauth2: Object.assign({ partial: true, userFlag: null }, updates) },
|
|
2499
|
+
{ expectedRefreshToken: usedRefreshToken || '' }
|
|
2500
|
+
);
|
|
2501
|
+
|
|
2502
|
+
if (writeResult && writeResult.skipped) {
|
|
2503
|
+
this.logger.info({
|
|
2504
|
+
msg: 'Discarded a renewed OAuth2 access token, the account was re-authorized during the renewal',
|
|
2505
|
+
action: 'ensureAccessToken',
|
|
2506
|
+
account: this.account,
|
|
2507
|
+
oauth2App: accountData.oauth2.provider
|
|
2508
|
+
});
|
|
2509
|
+
// The skipped write read the account as stored now, so that read is reused
|
|
2510
|
+
return writeResult.current || (await this.loadAccountData(this.account, false));
|
|
2511
|
+
}
|
|
2512
|
+
|
|
3111
2513
|
accountData.oauth2 = Object.assign(accountData.oauth2 || {}, updates);
|
|
3112
2514
|
delete accountData.oauth2.userFlag;
|
|
3113
2515
|
|
|
@@ -3121,8 +2523,6 @@ class Account {
|
|
|
3121
2523
|
oauth2App: accountData.oauth2.provider
|
|
3122
2524
|
});
|
|
3123
2525
|
|
|
3124
|
-
await this.update({ account: accountData.account, oauth2: accountData.oauth2 });
|
|
3125
|
-
|
|
3126
2526
|
return accountData;
|
|
3127
2527
|
} catch (err) {
|
|
3128
2528
|
this.logger.warn({
|
|
@@ -3251,7 +2651,7 @@ class Account {
|
|
|
3251
2651
|
if (delegatedAccount) {
|
|
3252
2652
|
accountData.delegatedAccount = delegatedAccount;
|
|
3253
2653
|
let delegatedAccountRow = await this.redis.hgetall(`${REDIS_PREFIX}iad:${delegatedAccount}`);
|
|
3254
|
-
let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow);
|
|
2654
|
+
let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow, { skipDecrypt: true });
|
|
3255
2655
|
if (delegatedAccountData?.oauth2?.provider) {
|
|
3256
2656
|
let app = await oauth2Apps.get(delegatedAccountData.oauth2.provider);
|
|
3257
2657
|
return isApiBasedApp(app);
|
|
@@ -3299,24 +2699,24 @@ class Account {
|
|
|
3299
2699
|
return await oAuth2Client.request(tokenData?.accessToken, url, method, payload, options);
|
|
3300
2700
|
}
|
|
3301
2701
|
|
|
3302
|
-
|
|
3303
|
-
|
|
3304
|
-
|
|
3305
|
-
|
|
3306
|
-
|
|
3307
|
-
|
|
3308
|
-
|
|
2702
|
+
/**
|
|
2703
|
+
* Queues the events of one Graph notification delivery, encoded as the envelope
|
|
2704
|
+
* pullQueueEvent() decodes. One write, so it is all or nothing, and not caught: the webhook
|
|
2705
|
+
* route has to answer with an error for Graph to deliver the notification again - a 202 after
|
|
2706
|
+
* a failed write lost it for good, and a partial write would repeat the events already queued
|
|
2707
|
+
* @param {Object[]} events - Queue events
|
|
2708
|
+
*/
|
|
2709
|
+
async pushQueueEvents(events) {
|
|
2710
|
+
const t = new Date();
|
|
2711
|
+
let res = await this.redis.lpush(this.getExternalQueueKey(), ...events.map(e => msgpack.encode({ t, e })));
|
|
3309
2712
|
|
|
3310
|
-
|
|
3311
|
-
|
|
3312
|
-
|
|
3313
|
-
|
|
3314
|
-
|
|
3315
|
-
|
|
3316
|
-
|
|
3317
|
-
} catch (err) {
|
|
3318
|
-
this.logger.error({ msg: 'Failed to insert event to account queue', account: this.account, event, err });
|
|
3319
|
-
}
|
|
2713
|
+
this.logger.debug({
|
|
2714
|
+
msg: 'MS Graph subscription event',
|
|
2715
|
+
type: 'event',
|
|
2716
|
+
account: this.account,
|
|
2717
|
+
events,
|
|
2718
|
+
res
|
|
2719
|
+
});
|
|
3320
2720
|
|
|
3321
2721
|
try {
|
|
3322
2722
|
await this.call({ cmd: 'externalNotify', accounts: [this.account] });
|
|
@@ -3340,8 +2740,103 @@ class Account {
|
|
|
3340
2740
|
|
|
3341
2741
|
return event || null;
|
|
3342
2742
|
}
|
|
2743
|
+
|
|
2744
|
+
/**
|
|
2745
|
+
* Parks a mailbox change until `dueTime`. Kept in Redis rather than a timer so a restart in
|
|
2746
|
+
* between does not lose it
|
|
2747
|
+
* @param {Object} event - Any JSON-serializable description of the change
|
|
2748
|
+
* @param {number} dueTime - Epoch milliseconds
|
|
2749
|
+
*/
|
|
2750
|
+
async deferChangeEvent(event, dueTime) {
|
|
2751
|
+
await this.redis.zadd(this.getDeferredQueueKey(), dueTime, JSON.stringify(event));
|
|
2752
|
+
}
|
|
2753
|
+
|
|
2754
|
+
/**
|
|
2755
|
+
* Lists the deferred changes that are due, a bounded batch per call. Nothing is removed here:
|
|
2756
|
+
* each is swapped for its next attempt by leaseChangeEvent() only when it is processed, so a
|
|
2757
|
+
* worker that dies mid-batch loses none of them
|
|
2758
|
+
* @returns {Promise<{due: {event: Object, member: string}[], next: number|null}>} The due
|
|
2759
|
+
* changes, and when the next one is due (epoch ms, null when none is left)
|
|
2760
|
+
*/
|
|
2761
|
+
async listDueChangeEvents() {
|
|
2762
|
+
const deferredKey = this.getDeferredQueueKey();
|
|
2763
|
+
const now = Date.now();
|
|
2764
|
+
const [[, members], [, nextDue]] = await this.redis
|
|
2765
|
+
.multi()
|
|
2766
|
+
.zrangebyscore(deferredKey, '-inf', now, 'LIMIT', 0, DEFERRED_CHANGE_BATCH)
|
|
2767
|
+
.zrangebyscore(deferredKey, `(${now}`, '+inf', 'WITHSCORES', 'LIMIT', 0, 1)
|
|
2768
|
+
.exec();
|
|
2769
|
+
|
|
2770
|
+
const due = [];
|
|
2771
|
+
for (const member of members) {
|
|
2772
|
+
try {
|
|
2773
|
+
due.push({ event: JSON.parse(member), member });
|
|
2774
|
+
} catch (err) {
|
|
2775
|
+
// one unreadable entry must not block every deferred change of the account
|
|
2776
|
+
this.logger.error({ msg: 'Dropping unreadable deferred mailbox change', account: this.account, member, err });
|
|
2777
|
+
await this.redis.zrem(deferredKey, member);
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
|
|
2781
|
+
let next = nextDue.length ? Number(nextDue[1]) : null;
|
|
2782
|
+
if (members.length === DEFERRED_CHANGE_BATCH) {
|
|
2783
|
+
// a full batch was due, there may be more behind it
|
|
2784
|
+
next = now;
|
|
2785
|
+
}
|
|
2786
|
+
|
|
2787
|
+
return { due, next };
|
|
2788
|
+
}
|
|
2789
|
+
|
|
2790
|
+
/**
|
|
2791
|
+
* Stores a request to recover missed MS Graph change notifications as a deferred change that
|
|
2792
|
+
* is due now, so it survives a worker that is not running, is retried when it fails, and
|
|
2793
|
+
* several requests are served by one recovery pass (see OutlookClient.syncMissedMessages())
|
|
2794
|
+
*/
|
|
2795
|
+
async queueMissedRecovery() {
|
|
2796
|
+
const now = Date.now();
|
|
2797
|
+
await this.deferChangeEvent({ type: 'missedRecovery', receivedAt: now }, now);
|
|
2798
|
+
}
|
|
2799
|
+
|
|
2800
|
+
/**
|
|
2801
|
+
* Swaps a deferred change for its next attempt before it is processed, see
|
|
2802
|
+
* BaseClient.processDueDeferredEvents()
|
|
2803
|
+
* @param {string} member - As listDueChangeEvents() returned it
|
|
2804
|
+
* @param {Object|null} next - The next attempt, null when the attempts are used up
|
|
2805
|
+
* @param {number} dueTime - When the next attempt is due
|
|
2806
|
+
* @returns {Promise<string|null>} The stored member of the next attempt
|
|
2807
|
+
*/
|
|
2808
|
+
async leaseChangeEvent(member, next, dueTime) {
|
|
2809
|
+
const deferredKey = this.getDeferredQueueKey();
|
|
2810
|
+
let pipeline = this.redis.multi().zrem(deferredKey, member);
|
|
2811
|
+
const nextMember = next ? JSON.stringify(next) : null;
|
|
2812
|
+
if (nextMember) {
|
|
2813
|
+
pipeline = pipeline.zadd(deferredKey, dueTime, nextMember);
|
|
2814
|
+
}
|
|
2815
|
+
await pipeline.exec();
|
|
2816
|
+
return nextMember;
|
|
2817
|
+
}
|
|
2818
|
+
|
|
2819
|
+
/**
|
|
2820
|
+
* Moves a stored change to a new due time, when the change is already stored as the attempt
|
|
2821
|
+
* that is being deferred
|
|
2822
|
+
* @param {string} member - As leaseChangeEvent() returned it
|
|
2823
|
+
* @param {number} dueTime - Epoch milliseconds
|
|
2824
|
+
*/
|
|
2825
|
+
async rescheduleChangeEvent(member, dueTime) {
|
|
2826
|
+
await this.redis.zadd(this.getDeferredQueueKey(), 'XX', dueTime, member);
|
|
2827
|
+
}
|
|
2828
|
+
|
|
2829
|
+
/**
|
|
2830
|
+
* Drops a leased change once it was processed or given up on
|
|
2831
|
+
* @param {string} member - As listDueChangeEvents() returned it
|
|
2832
|
+
*/
|
|
2833
|
+
async completeChangeEvent(member) {
|
|
2834
|
+
await this.redis.zrem(this.getDeferredQueueKey(), member);
|
|
2835
|
+
}
|
|
3343
2836
|
}
|
|
3344
2837
|
|
|
2838
|
+
const DEFERRED_CHANGE_BATCH = 100;
|
|
2839
|
+
|
|
3345
2840
|
// Cheap existence probe that does not load or decrypt account data. The `account` field is
|
|
3346
2841
|
// the mandatory marker field of the account hash (the same idiom the notify worker and
|
|
3347
2842
|
// genId() rely on), so its presence is the canonical "this account exists" signal.
|
|
@@ -3418,6 +2913,7 @@ function isAccessTokenInvalidated(oauth2) {
|
|
|
3418
2913
|
}
|
|
3419
2914
|
|
|
3420
2915
|
module.exports = {
|
|
2916
|
+
ENCRYPTED_ACCOUNT_FIELDS,
|
|
3421
2917
|
Account,
|
|
3422
2918
|
accountExists,
|
|
3423
2919
|
accountsExist,
|