emailengine-app 2.72.1 → 2.72.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.72.3](https://github.com/postalsys/emailengine/compare/v2.72.2...v2.72.3) (2026-07-06)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * bump imapflow to 1.4.4 (dedupe nodemailer/iconv-lite) ([5acc8cd](https://github.com/postalsys/emailengine/commit/5acc8cd99f9179fabb8d8486cf23b0558e4514bf))
9
+ * bump imapflow/mailparser/mailsplit/email-ai-tools (collapse iconv-lite) ([51dcffb](https://github.com/postalsys/emailengine/commit/51dcffb3ff0f22f9b9634d078e58b35aaf7a0312))
10
+ * bump libmime/mailparser/smtp-server/pubface (uniform nodemailer) ([eee89bb](https://github.com/postalsys/emailengine/commit/eee89bb716655519c72fb922849272c1058cbc9a))
11
+ * constant-time MS Graph clientState check and escape unsubscribe email ([3def225](https://github.com/postalsys/emailengine/commit/3def225ab1d598dec4f0b44443ff842295736039))
12
+ * escape Redis glob metacharacters in account-scoped SCAN patterns ([603d9db](https://github.com/postalsys/emailengine/commit/603d9dbce9c4e21b390e10dc7499f2cc5989c875))
13
+ * escape untrusted email fields in message browser to prevent stored XSS ([1159cc1](https://github.com/postalsys/emailengine/commit/1159cc193a98eb972454a5ae61ec01d7df77f06a))
14
+ * gate hosted auth form with a single-use nonce and probe cap, harden serviceSecret ([7ea4ff7](https://github.com/postalsys/emailengine/commit/7ea4ff7e6ca4d9239201f556b24ebd9cf8ab8250))
15
+ * harden hosted authentication form (SSRF gate, fail-closed HMAC, XSS) ([4267df7](https://github.com/postalsys/emailengine/commit/4267df7fd0252aa84ff1d257846126a8f943bf1a))
16
+ * HTML-escape json Handlebars helper to prevent stored XSS in error logs ([af2c153](https://github.com/postalsys/emailengine/commit/af2c153eb4d7de06b2730da6fdeb17bbe868472b))
17
+ * override grunt's transitive js-yaml to 3.15.0 (GHSA-h67p-54hq-rp68) ([024a923](https://github.com/postalsys/emailengine/commit/024a923de3ff2a880e79c7ddbf34bbc058fcbea3))
18
+ * stop logging the MS Graph access token on HTTP 401 ([f2f0300](https://github.com/postalsys/emailengine/commit/f2f03008cbcbaba8b7c2ff9c043ede7930c5c4ef))
19
+ * update dependencies (@postalsys/ee-client 1.3.2, nodemailer 9.0.3, bullmq 5.79.2, @sentry/node 10.63.0, [@bull-board](https://github.com/bull-board) 8.0.2) ([b954f67](https://github.com/postalsys/emailengine/commit/b954f67e1250d8a0029d355a5a8c6fc9d7f00e8e))
20
+ * update dependencies (email-text-tools 2.4.10, email-ai-tools 1.13.10) ([73df05c](https://github.com/postalsys/emailengine/commit/73df05c02db79fc47623ee41e27a315952c289b1))
21
+ * use constant-time comparison for secret and MAC checks ([453caf3](https://github.com/postalsys/emailengine/commit/453caf3ac01e58248a3a7019aa4ec3c2179b3abc))
22
+ * verify HMAC signature on the human-facing unsubscribe routes ([e30be83](https://github.com/postalsys/emailengine/commit/e30be836a71bc7e96baee19e5b019da5b0de40fa))
23
+
24
+ ## [2.72.2](https://github.com/postalsys/emailengine/compare/v2.72.1...v2.72.2) (2026-06-26)
25
+
26
+
27
+ ### Bug Fixes
28
+
29
+ * reconnect error-state accounts after OAuth re-auth via create() ([77cee1e](https://github.com/postalsys/emailengine/commit/77cee1eb1916fbd6582cfcf931023d53f6cc8abf))
30
+ * resume sync after OAuth re-auth and enable Run sync for Gmail/Outlook ([f3bef82](https://github.com/postalsys/emailengine/commit/f3bef823ee90cd6fcf90b95fadcb6f2730657441))
31
+ * update dependencies (libmime 5.4.0, mailparser 3.9.12, imapflow 1.4.3, email-ai-tools 1.13.9) ([8c999d8](https://github.com/postalsys/emailengine/commit/8c999d8c5e6b550c6d3a28fd4ec118c48d095901))
32
+
3
33
  ## [2.72.1](https://github.com/postalsys/emailengine/compare/v2.72.0...v2.72.1) (2026-06-19)
4
34
 
5
35
 
package/Gruntfile.js CHANGED
@@ -12,7 +12,10 @@ module.exports = function (grunt) {
12
12
  command: "npx eslint 'lib/**/*.js' 'workers/**/*.js' server.js Gruntfile.js"
13
13
  },
14
14
  server: {
15
- command: 'node server.js',
15
+ // Short Gmail fallback-poll interval so gmail-polling-test can exercise the poller
16
+ // quickly. Harmless for push-based Gmail accounts in api-test: notifications keep
17
+ // resetting the timer, and a stray fallback sync is coalesced/idempotent.
18
+ command: 'EENGINE_GMAIL_FALLBACK_POLL_INTERVAL=15000 node server.js',
16
19
  options: {
17
20
  async: true
18
21
  }
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-06-19T14:46:02.000000",
2
+ "creationTime": "2026-06-29T14:45:46.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
@@ -17,6 +17,10 @@ const ACCOUNT_STATES = {
17
17
  // States that indicate the account is operational
18
18
  const VALID_STATES = [ACCOUNT_STATES.CONNECTED, ACCOUNT_STATES.CONNECTING, ACCOUNT_STATES.SYNCING];
19
19
 
20
+ // Non-operational error states. Re-authorizing / re-saving credentials for an account in one of
21
+ // these states should trigger a full reconnect so syncing resumes.
22
+ const ERROR_STATES = [ACCOUNT_STATES.AUTHENTICATION_ERROR, ACCOUNT_STATES.CONNECT_ERROR];
23
+
20
24
  // States that bypass runIndex checking
21
25
  const BYPASS_RUN_INDEX_STATES = [ACCOUNT_STATES.INIT, ACCOUNT_STATES.UNSET];
22
26
 
@@ -225,6 +229,7 @@ module.exports = {
225
229
  // Constants
226
230
  ACCOUNT_STATES,
227
231
  VALID_STATES,
232
+ ERROR_STATES,
228
233
  BYPASS_RUN_INDEX_STATES,
229
234
 
230
235
  // State calculation
package/lib/account.js CHANGED
@@ -11,7 +11,8 @@ const {
11
11
  download,
12
12
  resolveCredentials,
13
13
  isEmail,
14
- resolveDelegatedAccount
14
+ resolveDelegatedAccount,
15
+ escapeRedisGlob
15
16
  } = require('./tools');
16
17
  const crypto = require('crypto');
17
18
  const { MessageChannel } = require('worker_threads');
@@ -29,7 +30,7 @@ const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
29
30
  const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, MAILBOX_HASH } = require('./consts');
30
31
  const { mimeHtml } = require('@postalsys/email-text-tools');
31
32
  const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
32
- const { ACCOUNT_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
33
+ const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
33
34
 
34
35
  // Shared Lock instance to prevent Redis connection leak (one subscriber per Lock instance)
35
36
  // Previously, each Account created its own Lock, causing ~30k connections with 30k accounts
@@ -848,6 +849,39 @@ class Account {
848
849
  });
849
850
  }
850
851
 
852
+ // When OAuth2 credentials are re-authorized for an account that is currently in a
853
+ // non-operational error state, trigger a full reconnect so syncing resumes without a
854
+ // manual "Reconnect". Gated on the error state and on the credentials actually
855
+ // changing, so routine token renewal - which runs while the account is connected and
856
+ // re-saves oauth2 hourly - never triggers a reconnect. During an actual reconnect the
857
+ // state is set to "connecting" before tokens are fetched, so this cannot loop.
858
+ if (
859
+ !reconnectRequested &&
860
+ 'oauth2' in accountData &&
861
+ accountData.oauth2?.accessToken &&
862
+ (accountData.oauth2.accessToken !== oldAccountData.oauth2?.accessToken ||
863
+ accountData.oauth2.refreshToken !== oldAccountData.oauth2?.refreshToken) &&
864
+ ERROR_STATES.includes(oldAccountData.state)
865
+ ) {
866
+ this.logger.info({
867
+ msg: 'OAuth2 credentials re-authorized for account in error state, requesting reconnect',
868
+ account: this.account,
869
+ state: oldAccountData.state
870
+ });
871
+ try {
872
+ await this.call({
873
+ cmd: 'reconnect',
874
+ account: this.account,
875
+ timeout: this.timeout
876
+ });
877
+ } catch (err) {
878
+ // Credentials are already persisted; a failed reconnect dispatch must not turn a
879
+ // saved credential update into an error response. The next periodic reconnect
880
+ // recovers. Log and continue.
881
+ this.logger.error({ msg: 'Failed to request reconnect after credential update', account: this.account, state: oldAccountData.state, err });
882
+ }
883
+ }
884
+
851
885
  return {
852
886
  account: this.account
853
887
  };
@@ -961,11 +995,42 @@ class Account {
961
995
  // ignore
962
996
  }
963
997
 
964
- await this.call({
965
- cmd: 'update',
966
- account: this.account,
967
- timeout: this.timeout
968
- });
998
+ const oldState = result[0][1].state;
999
+ if (ERROR_STATES.includes(oldState)) {
1000
+ // Re-registration of an account that was in a non-operational error state (the
1001
+ // interactive OAuth re-auth redirect and the IMAP re-credentials form both land here).
1002
+ // cmd:'update' only calls reconnect() on the existing client instance, which cannot
1003
+ // switch client type (IMAP to API or back) and is a no-op against a torn-down
1004
+ // connection, so syncing would not resume without a manual "Reconnect". cmd:'reconnect'
1005
+ // closes and re-assigns a fresh client of the correct provider type. assignConnection
1006
+ // sets the state to "connecting" before any network work, so this cannot loop.
1007
+ // Gated on the error state alone (unlike update(), which also requires the oauth2
1008
+ // token to have changed): create() runs only on explicit re-registration, never on
1009
+ // routine token renewal, so there is no healthy-account churn to suppress here.
1010
+ this.logger.info({
1011
+ msg: 'Account re-created while in error state, requesting full reconnect',
1012
+ account: this.account,
1013
+ state: oldState
1014
+ });
1015
+ try {
1016
+ await this.call({
1017
+ cmd: 'reconnect',
1018
+ account: this.account,
1019
+ timeout: this.timeout
1020
+ });
1021
+ } catch (err) {
1022
+ // Credentials are already persisted (the hmset above returned OK). A failed
1023
+ // reconnect dispatch must not fail the re-auth or surface a 500; the next periodic
1024
+ // reconnect or a manual Reconnect will recover. Log and continue.
1025
+ this.logger.error({ msg: 'Failed to request reconnect after re-auth', account: this.account, state: oldState, err });
1026
+ }
1027
+ } else {
1028
+ await this.call({
1029
+ cmd: 'update',
1030
+ account: this.account,
1031
+ timeout: this.timeout
1032
+ });
1033
+ }
969
1034
  } else {
970
1035
  state = 'new';
971
1036
  await this.call({
@@ -1040,7 +1105,7 @@ class Account {
1040
1105
 
1041
1106
  // scan and delete keys
1042
1107
  // should we wait though? might take a lot of time
1043
- await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${this.account}:*`);
1108
+ await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${escapeRedisGlob(this.account)}:*`);
1044
1109
 
1045
1110
  if (!result || !result[0] || !result[0][1]) {
1046
1111
  return {
@@ -2405,7 +2470,7 @@ class Account {
2405
2470
  await pipeline.exec();
2406
2471
 
2407
2472
  // scan and delete keys
2408
- await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${this.account}:*`);
2473
+ await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${escapeRedisGlob(this.account)}:*`);
2409
2474
 
2410
2475
  if (await isDocumentStoreEnabled()) {
2411
2476
  // Flush ElasticSearch index for this account
@@ -24,10 +24,18 @@ const { httpAgent } = require('./tools');
24
24
 
25
25
  const RESOLV_TIMEOUT = 5 * 1000;
26
26
 
27
+ // Shorter cap for the app-password hint MX lookup: it runs on the hosted form's validation-error
28
+ // re-render and only produces a cosmetic label, so it must not stall the page for the full RESOLV_TIMEOUT.
29
+ const APP_PASSWORD_MX_TIMEOUT = 1500;
30
+
27
31
  // use a function instead of const to prevent translations before locale is set
32
+ // The canonical consumer domains are listed alongside the exchange regexes so a plain domain match
33
+ // (getAppPassword with exchange=false) resolves the big providers without any MX lookup - each listed
34
+ // domain's MX points at the same entry the regex would select, so autodetect results do not change.
28
35
  const getAppPasswords = gt => [
29
36
  {
30
37
  trigger: {
38
+ domains: ['gmail.com', 'googlemail.com'],
31
39
  exchange: /\bl\.google\.com$/i
32
40
  },
33
41
  value: {
@@ -39,6 +47,7 @@ const getAppPasswords = gt => [
39
47
 
40
48
  {
41
49
  trigger: {
50
+ domains: ['icloud.com', 'me.com', 'mac.com'],
42
51
  exchange: /\.icloud\.com$/i
43
52
  },
44
53
  value: {
@@ -73,6 +82,7 @@ const getAppPasswords = gt => [
73
82
 
74
83
  {
75
84
  trigger: {
85
+ domains: ['outlook.com', 'hotmail.com', 'live.com'],
76
86
  exchange: /\.outlook\.com$/i
77
87
  },
78
88
  value: {
@@ -87,6 +97,7 @@ const getAppPasswords = gt => [
87
97
 
88
98
  {
89
99
  trigger: {
100
+ domains: ['t-online.de'],
90
101
  exchange: /\.t-online\.de$/i
91
102
  },
92
103
  value: {
@@ -111,6 +122,53 @@ function getAppPassword(email, exchange, gt) {
111
122
  return false;
112
123
  }
113
124
 
125
+ // Resolve the lowest-priority MX exchange for a domain (lowercased). Throws if the domain has no MX
126
+ // record (callers decide whether that is fatal or just "no exchange-based match").
127
+ async function resolveExchange(domain) {
128
+ let srvList = await dns.resolveMx(domain);
129
+ if (!srvList || !srvList.length) {
130
+ throw new Error('No MX record found for domain');
131
+ }
132
+
133
+ const firstItem = srvList.sort((a, b) => a.priority - b.priority).shift();
134
+ return firstItem && firstItem.exchange ? firstItem.exchange.trim().toLowerCase() : undefined;
135
+ }
136
+
137
+ // Resolve only the app-password hint for an email address - a domain match plus, for exchange-based
138
+ // providers (Gmail, iCloud, Outlook, ...), a single MX lookup. Much cheaper than autodetectImapSettings
139
+ // (one DNS query, no HTTP). The hosted form's failAction re-render uses this to restore the
140
+ // app-password label/instructions server-side rather than trusting the submitted (client-controlled)
141
+ // hidden fields, which feed unescaped template sinks. Returns the trusted hint object or false; the
142
+ // returned values are static table constants, so they are safe to render. Never throws.
143
+ async function resolveAppPassword(email, gt) {
144
+ if (!email || typeof email !== 'string' || email.indexOf('@') < 0) {
145
+ return false;
146
+ }
147
+
148
+ // Fast path: a domain-only match (e.g. aol.com) needs no network.
149
+ let hint = getAppPassword(email, false, gt);
150
+ if (hint) {
151
+ return hint;
152
+ }
153
+
154
+ let domain = email.split('@').pop().trim().toLowerCase();
155
+ try {
156
+ domain = punycode.toASCII(domain);
157
+ } catch (err) {
158
+ // ignore - use the raw domain
159
+ }
160
+
161
+ let exchange;
162
+ try {
163
+ exchange = await timedFunction(resolveExchange(domain), APP_PASSWORD_MX_TIMEOUT, 'mx');
164
+ } catch (err) {
165
+ // No MX record / lookup failed / timed out - no exchange-based hint to add.
166
+ return false;
167
+ }
168
+
169
+ return getAppPassword(email, exchange, gt);
170
+ }
171
+
114
172
  async function processAutoconfigFile(email, domain, text, source) {
115
173
  domain = domain || email.split('@').pop().trim().toLowerCase();
116
174
  let user = email.split('@').shift().trim();
@@ -335,17 +393,7 @@ async function resolveUsingMX(email, domain, gt) {
335
393
  }
336
394
 
337
395
  // do not catch potential error as there's nothing to do if we do not find the MX record
338
- let srvList = await dns.resolveMx(domain);
339
- if (!srvList || !srvList.length) {
340
- throw new Error('No MX record found for domain');
341
- }
342
-
343
- let exchange;
344
- const firstItem = srvList.sort((a, b) => a.priority - b.priority).shift();
345
-
346
- if (firstItem && firstItem.exchange) {
347
- exchange = firstItem.exchange.trim().toLowerCase();
348
- }
396
+ let exchange = await resolveExchange(domain);
349
397
 
350
398
  let resolveConfig = async () => {
351
399
  // look for some well known MX servers
@@ -777,3 +825,10 @@ async function autodetectImapSettings(email, gt) {
777
825
  }
778
826
 
779
827
  module.exports.autodetectImapSettings = autodetectImapSettings;
828
+
829
+ // Exposed for unit testing of the pure parsing/matching helpers. These have no
830
+ // network side effects, so they can be exercised directly without mocking DNS or HTTP.
831
+ module.exports.processAutoconfigFile = processAutoconfigFile;
832
+ module.exports.getAppPassword = getAppPassword;
833
+ module.exports.resolveAppPassword = resolveAppPassword;
834
+ module.exports.escapeXml = escapeXml;
package/lib/consts.js CHANGED
@@ -184,6 +184,13 @@ module.exports = {
184
184
  // how long is an authentication form valid
185
185
  MAX_FORM_TTL: 1 * 24 * 3600 * 1000,
186
186
 
187
+ // Max number of outbound-probe requests (email autodiscovery + "Verify connection" tests) allowed per
188
+ // issued form blob. These hosted-form endpoints authorize the caller by signature but do not consume
189
+ // the single-use nonce (a form autodetects/tests several times before submitting), so this shared cap
190
+ // bounds a leaked signed link from being replayed as an unlimited outbound-probe / SSRF oracle.
191
+ // Generous enough not to impede real use.
192
+ MAX_FORM_PROBE_ATTEMPTS: 50,
193
+
187
194
  NONCE_BYTES: 16,
188
195
 
189
196
  // We are using a legacy hash function in caching operations
@@ -2,7 +2,7 @@
2
2
 
3
3
  const { Account } = require('../account');
4
4
  const { oauth2Apps } = require('../oauth2-apps');
5
- const { checkAccountScopes } = require('../oauth/scope-checker');
5
+ const { checkAccountScopes, isSendOnlyByScopes } = require('../oauth/scope-checker');
6
6
  const getSecret = require('../get-secret');
7
7
  const msgpack = require('msgpack5')();
8
8
  const addressparser = require('nodemailer/lib/addressparser');
@@ -72,7 +72,10 @@ function toGmailLabelId(label) {
72
72
  // Timing constants for Gmail Pub/Sub watch
73
73
  const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h - how often to check if watch needs renewal
74
74
  const MIN_WATCH_TTL = 24 * 3600 * 1000; // 1day - minimum time before renewing watch
75
- const FALLBACK_POLLING_INTERVAL = 10 * 60 * 1000; // 10min - fallback polling if no Pub/Sub notifications
75
+ // 10min default - fallback polling if no Pub/Sub notifications. Overridable via
76
+ // EENGINE_GMAIL_FALLBACK_POLL_INTERVAL (ms) so integration tests can exercise the poller
77
+ // without waiting the full interval.
78
+ const FALLBACK_POLLING_INTERVAL = Number((process.env.EENGINE_GMAIL_FALLBACK_POLL_INTERVAL || '').toString().trim()) || 10 * 60 * 1000;
76
79
 
77
80
  /*
78
81
  Gmail API implementation status:
@@ -509,6 +512,46 @@ class GmailClient extends BaseClient {
509
512
  return null;
510
513
  }
511
514
 
515
+ /**
516
+ * Performs an on-demand catch-up sync. Triggered by the "Run sync" action
517
+ * (PUT /v1/account/{account}/sync). Gmail has no folder-walk sync like IMAP; instead it
518
+ * reads the current history checkpoint and processes anything that arrived since the last
519
+ * stored historyId, reusing the same code path as live Pub/Sub notifications.
520
+ */
521
+ async syncMailboxes() {
522
+ if (this.closed) {
523
+ return null;
524
+ }
525
+
526
+ let accountData = await this.accountObject.loadAccountData(this.account, false);
527
+
528
+ // Send-only accounts have no mailbox to sync
529
+ if (isSendOnlyByScopes('gmail', accountData)) {
530
+ return null;
531
+ }
532
+
533
+ let profileRes;
534
+ try {
535
+ profileRes = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/profile`);
536
+ } catch (err) {
537
+ this.logger.error({ msg: 'Failed to fetch profile for manual sync', account: this.account, err });
538
+ return null;
539
+ }
540
+
541
+ let currentHistoryId = Number(profileRes?.historyId) || null;
542
+ // googleHistoryId is already loaded with the account data; reuse it (matches init())
543
+ let storedHistoryId = Number(accountData.googleHistoryId) || null;
544
+
545
+ if (currentHistoryId && storedHistoryId && currentHistoryId > storedHistoryId) {
546
+ // Reuse triggerSync so the processingHistory guard prevents overlap with a
547
+ // concurrent Pub/Sub-driven sync. triggerSync is fire-and-forget but catches its
548
+ // own errors, so it cannot produce an unhandled rejection.
549
+ this.triggerSync(storedHistoryId, currentHistoryId);
550
+ }
551
+
552
+ return true;
553
+ }
554
+
512
555
  async currentState() {
513
556
  return (await this.redis.hget(this.getAccountKey(), 'state')) || 'disconnected';
514
557
  }
@@ -126,7 +126,9 @@ async function request(context, url, method, payload, options = {}) {
126
126
 
127
127
  switch (status) {
128
128
  case 401:
129
- context.logger.error({ msg: 'Failed to authenticate API request', account: context.account, accessToken, err });
129
+ // NOTE: never include `accessToken` here - this logger persists to the per-account
130
+ // log store (exposed via the account logs API/UI) and to Sentry (security review M3).
131
+ context.logger.error({ msg: 'Failed to authenticate API request', account: context.account, err });
130
132
  throw err;
131
133
 
132
134
  case 429:
@@ -409,6 +409,28 @@ class OutlookClient extends BaseClient {
409
409
  return null;
410
410
  }
411
411
 
412
+ /**
413
+ * Performs an on-demand catch-up sync. Triggered by the "Run sync" action
414
+ * (PUT /v1/account/{account}/sync). Outlook syncs via webhook subscriptions and delta
415
+ * queries rather than a folder walk, so a manual sync refreshes the folder cache and runs
416
+ * the missed-notification recovery (with the cooldown bypassed for this explicit action).
417
+ */
418
+ async syncMailboxes() {
419
+ if (this.closed) {
420
+ return null;
421
+ }
422
+
423
+ try {
424
+ await this.renewMailboxFolderCache();
425
+ } catch (err) {
426
+ this.logger.error({ msg: 'Failed to refresh folder cache for manual sync', account: this.account, err });
427
+ }
428
+
429
+ await this.syncMissedMessages({ force: true });
430
+
431
+ return true;
432
+ }
433
+
412
434
  /**
413
435
  * Get the current connection state from Redis
414
436
  */
@@ -3968,13 +3990,19 @@ class OutlookClient extends BaseClient {
3968
3990
  * Queries recent messages and processes any not already seen via normal webhooks.
3969
3991
  * @returns {boolean} Whether recovery ran (false if debounced)
3970
3992
  */
3971
- async syncMissedMessages() {
3972
- // Debounce: skip if recovery already ran recently
3993
+ async syncMissedMessages(opts) {
3994
+ let { force } = opts || {};
3995
+
3996
+ // Debounce: skip if recovery already ran recently. A manual "Run sync" passes
3997
+ // force:true to bypass the cooldown; duplicate suppression is still handled per
3998
+ // message by rollingBucketLock below, so forcing cannot re-emit seen messages.
3973
3999
  const cooldownKey = `${REDIS_PREFIX}iam:${this.account}:missedRecovery`;
3974
- const acquired = await this.redis.set(cooldownKey, '1', 'EX', 300, 'NX');
3975
- if (!acquired) {
3976
- this.logger.debug({ msg: 'Missed notification recovery skipped (cooldown active)', account: this.account });
3977
- return false;
4000
+ if (!force) {
4001
+ const acquired = await this.redis.set(cooldownKey, '1', 'EX', 300, 'NX');
4002
+ if (!acquired) {
4003
+ this.logger.debug({ msg: 'Missed notification recovery skipped (cooldown active)', account: this.account });
4004
+ return false;
4005
+ }
3978
4006
  }
3979
4007
 
3980
4008
  // Determine lookback window
@@ -190,7 +190,8 @@ module.exports = {
190
190
  getMailTransport,
191
191
  closePooledConnection,
192
192
  getPoolSize,
193
- // Export constants for testing
193
+ // Exported for testing
194
+ generatePoolKey,
194
195
  SMTP_POOL_MAX_IDLE,
195
196
  SMTP_POOL_CLEANUP_INTERVAL
196
197
  };
package/lib/export.js CHANGED
@@ -9,6 +9,7 @@ const { redis, exportQueue } = require('./db');
9
9
  const settings = require('./settings');
10
10
  const logger = require('./logger');
11
11
  const getSecret = require('./get-secret');
12
+ const { escapeRedisGlob } = require('./tools');
12
13
 
13
14
  const {
14
15
  REDIS_PREFIX,
@@ -304,7 +305,7 @@ class Export {
304
305
  const page = Number(options.page) || 0;
305
306
  const pageSize = Number(options.pageSize) || 20;
306
307
 
307
- const pattern = `${REDIS_PREFIX}exp:${account}:${EXPORT_ID_PREFIX}*`;
308
+ const pattern = `${REDIS_PREFIX}exp:${escapeRedisGlob(account)}:${EXPORT_ID_PREFIX}*`;
308
309
  const keys = await scanKeys(pattern);
309
310
 
310
311
  const exports = [];
@@ -567,7 +568,7 @@ class Export {
567
568
  if (!file.startsWith(EXPORT_ID_PREFIX)) continue;
568
569
 
569
570
  const exportId = file.split('.')[0];
570
- const pattern = `${REDIS_PREFIX}exp:*:${exportId}`;
571
+ const pattern = `${REDIS_PREFIX}exp:*:${escapeRedisGlob(exportId)}`;
571
572
  const keys = await scanKeys(pattern);
572
573
 
573
574
  if (keys.length === 0) {
@@ -12,6 +12,7 @@ const { Account } = require('./account');
12
12
  const getSecret = require('./get-secret');
13
13
  const { isApiBasedApp } = require('./oauth2-apps');
14
14
  const { validateAuthToken, REASON_MESSAGES } = require('./auth-token');
15
+ const { constantTimeEqual } = require('./tools');
15
16
 
16
17
  /**
17
18
  * Builds the IMAP proxy authentication handler.
@@ -25,7 +26,7 @@ function createImapProxyAuthHandler({ call }) {
25
26
  let account = auth.username;
26
27
 
27
28
  let imapPassword = await settings.get('imapProxyServerPassword');
28
- if (!imapPassword || auth.password !== imapPassword) {
29
+ if (!imapPassword || !constantTimeEqual(auth.password, imapPassword)) {
29
30
  // fall back to API token authentication
30
31
  let result = await validateAuthToken({
31
32
  password: auth.password,
package/lib/schemas.js CHANGED
@@ -48,6 +48,19 @@ const ADDRESS_STRATEGIES = [
48
48
 
49
49
  const accountIdSchema = Joi.string().empty('').trim().max(256).example('user123').description('Unique identifier for the email account');
50
50
 
51
+ // The service-secret-signed blob (base64url `data` + its HMAC `sig`) carried by every hosted
52
+ // authentication-form page. Defined once so the security-relevant field definitions cannot drift across
53
+ // the auth:false hosted-form endpoints. Both fields required: every issuer signs unconditionally and every
54
+ // template renders the sig hidden input, so a request without one is always hand-crafted. NB: the tracking
55
+ // endpoints (/redirect, /open.gif, /unsubscribe in workers/api.js) intentionally keep `sig` OPTIONAL at the
56
+ // Joi layer - their handlers fail closed on a missing/bad signature, and /unsubscribe must not turn a
57
+ // missing-sig request into a Joi 400 (RFC 8058 one-click wants a benign non-throwing response) - so they do
58
+ // NOT use this fragment.
59
+ const signedFormBlobFields = {
60
+ data: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required(),
61
+ sig: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required()
62
+ };
63
+
51
64
  // All states that the account state field can expose over the API. In addition to the state
52
65
  // machine states, 'disconnected' and 'paused' are client-level display states set by imap-client
53
66
  const ACCOUNT_DISPLAY_STATES = [...Object.values(ACCOUNT_STATES), 'disconnected', 'paused'];
@@ -2466,6 +2479,7 @@ module.exports = {
2466
2479
  responseFromAddressSchema,
2467
2480
  emailIdSchema,
2468
2481
  threadIdSchema,
2482
+ signedFormBlobFields,
2469
2483
  outboxEntrySchema,
2470
2484
  googleProjectIdSchema,
2471
2485
  googleTopicNameSchema,
package/lib/settings.js CHANGED
@@ -142,16 +142,36 @@ module.exports = {
142
142
  return value;
143
143
  },
144
144
 
145
- async set(key, value) {
146
- const encryptSecret = await getSecret();
147
-
148
- let formattedValue = module.exports.formatSettingValue(key, value);
149
- value = JSON.stringify(formattedValue);
145
+ // Serialize an already-formatted setting value the way get()/getValue() expect it back:
146
+ // JSON-encoded, encrypted for ENCRYPTED_KEYS members. Every writer (set, setMulti,
147
+ // setIfMissing) must go through this so the encoding cannot drift between them.
148
+ encodeSettingValue(key, formattedValue, encryptSecret) {
149
+ let value = JSON.stringify(formattedValue);
150
150
 
151
151
  if (encryptSecret && ENCRYPTED_KEYS.includes(key)) {
152
152
  value = encrypt(value, encryptSecret);
153
153
  }
154
154
 
155
+ return value;
156
+ },
157
+
158
+ async set(key, value) {
159
+ // A blank serviceSecret must never be persisted: an empty stored secret breaks HMAC
160
+ // signing/verification for every hosted-form and tracking link, and makes getServiceSecret()
161
+ // silently mint a fresh secret - invalidating every signed link already out in delivered mail.
162
+ // A blank value means "keep the current secret", not "clear it". Enforced here so it covers every
163
+ // writer that reaches set() (the /v1/settings API and the EENGINE_SETTINGS prepared config), not
164
+ // just the admin UI which additionally surfaces a flash. Boot-time minting (server.js) passes a
165
+ // non-empty random value, so it is unaffected.
166
+ if (key === 'serviceSecret' && (typeof value !== 'string' || !value.trim())) {
167
+ return 0;
168
+ }
169
+
170
+ const encryptSecret = await getSecret();
171
+
172
+ let formattedValue = module.exports.formatSettingValue(key, value);
173
+ value = module.exports.encodeSettingValue(key, formattedValue, encryptSecret);
174
+
155
175
  if (/^documentStore/.test(key)) {
156
176
  // increase version for documentStore settings
157
177
  try {
@@ -178,19 +198,30 @@ module.exports = {
178
198
  return await redis.hset(`${REDIS_PREFIX}settings`, key, value);
179
199
  },
180
200
 
201
+ // Store a value only if the key does not exist yet (atomic HSETNX). Meant for one-shot
202
+ // initialization keys (currently the auto-generated serviceSecret) where concurrent minters
203
+ // must converge on a single stored value instead of overwriting each other. Skips the
204
+ // documentStore/openAi side effects of set() on purpose. Returns true when the value was stored.
205
+ async setIfMissing(key, value) {
206
+ const encryptSecret = await getSecret();
207
+
208
+ value = module.exports.encodeSettingValue(key, module.exports.formatSettingValue(key, value), encryptSecret);
209
+
210
+ return (await redis.hsetnx(`${REDIS_PREFIX}settings`, key, value)) === 1;
211
+ },
212
+
181
213
  async setMulti(obj) {
182
214
  const encryptSecret = await getSecret();
183
215
  let docStoreUpdated = false;
184
216
  const storeObj = {};
185
217
  for (let key of Object.keys(obj)) {
186
- let formattedValue = module.exports.formatSettingValue(key, obj[key]);
187
- let value = JSON.stringify(formattedValue);
188
-
189
- if (encryptSecret && ENCRYPTED_KEYS.includes(key)) {
190
- value = encrypt(value, encryptSecret);
218
+ // See set(): never persist a blank serviceSecret - a blank value means "keep the current one".
219
+ if (key === 'serviceSecret' && (typeof obj[key] !== 'string' || !obj[key].trim())) {
220
+ continue;
191
221
  }
192
222
 
193
- storeObj[key] = value;
223
+ let formattedValue = module.exports.formatSettingValue(key, obj[key]);
224
+ storeObj[key] = module.exports.encodeSettingValue(key, formattedValue, encryptSecret);
194
225
 
195
226
  if (/^documentStore/.test(key)) {
196
227
  docStoreUpdated = true;