emailengine-app 2.73.0 → 2.74.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.
Files changed (42) hide show
  1. package/.github/docker-smoke-test.sh +45 -0
  2. package/.github/workflows/deploy.yml +22 -0
  3. package/.github/workflows/e2e.yml +1 -2
  4. package/.github/workflows/release.yaml +19 -0
  5. package/.github/workflows/test.yml +31 -0
  6. package/CHANGELOG.md +52 -0
  7. package/Dockerfile +14 -5
  8. package/README.md +55 -25
  9. package/config/e2e.toml +2 -2
  10. package/data/google-crawlers.json +1 -1
  11. package/lib/account.js +14 -6
  12. package/lib/api-routes/account-routes.js +4 -1
  13. package/lib/api-routes/token-routes.js +13 -0
  14. package/lib/consts.js +15 -25
  15. package/lib/delivery-error.js +34 -11
  16. package/lib/email-client/gmail-client.js +1 -1
  17. package/lib/email-client/imap/mailbox.js +96 -1
  18. package/lib/email-client/imap-client.js +101 -28
  19. package/lib/email-client/outlook-client.js +1 -1
  20. package/lib/es.js +0 -27
  21. package/lib/license-beacon.js +1 -5
  22. package/lib/schemas.js +12 -0
  23. package/lib/settings.js +13 -0
  24. package/lib/tokens.js +15 -0
  25. package/lib/ui-routes/account-routes.js +65 -5
  26. package/lib/ui-routes/admin-entities-routes.js +13 -0
  27. package/lib/worker-rpc-error.js +54 -0
  28. package/package.json +6 -6
  29. package/sbom.json +1 -1
  30. package/server.js +3 -19
  31. package/setup-production.sh +7 -2
  32. package/static/licenses.html +12 -12
  33. package/translations/messages.pot +36 -36
  34. package/views/accounts/edit.hbs +6 -0
  35. package/workers/api.js +5 -14
  36. package/workers/imap.js +3 -16
  37. package/workers/submit.js +3 -18
  38. package/.env.development +0 -49
  39. package/.env.example +0 -82
  40. package/.env.production +0 -87
  41. package/.eslintignore +0 -1
  42. package/Dockerfile-legacy +0 -18
@@ -30,7 +30,9 @@ const {
30
30
  MAX_INLINE_ATTACHMENT_SIZE,
31
31
  MAX_ALLOWED_DOWNLOAD_SIZE,
32
32
  MAILBOX_HASH,
33
- TRANSIENT_NETWORK_CODES
33
+ TRANSIENT_NETWORK_CODES,
34
+ PHANTOM_SELECT_FAIL_THRESHOLD,
35
+ PHANTOM_REPROBE_INTERVAL
34
36
  } = require('../../consts');
35
37
 
36
38
  const {
@@ -44,6 +46,16 @@ const {
44
46
  FULL_SYNC_DELAY
45
47
  } = require('./sync-operations');
46
48
 
49
+ /**
50
+ * Compact fingerprint of the STATUS counters stored in the phantom folder
51
+ * marker - a parked phantom folder is re-probed as soon as this changes
52
+ * @param {Object} status - STATUS response counters
53
+ * @returns {String} Fingerprint string
54
+ */
55
+ function phantomStatusKey(status) {
56
+ return `${status.uidValidity || ''}:${status.uidNext || 0}:${status.messages || 0}`;
57
+ }
58
+
47
59
  /**
48
60
  * Represents a single IMAP mailbox/folder and handles all operations on it
49
61
  */
@@ -501,6 +513,30 @@ class Mailbox {
501
513
  return false;
502
514
  }
503
515
 
516
+ // A phantom folder (listed but repeatedly rejecting SELECT, e.g. a
517
+ // Dovecot shared namespace root without \Noselect) is treated like
518
+ // \Noselect instead of re-attempting the SELECT on every sync pass -
519
+ // on some servers the failed SELECT poisons the session, which then
520
+ // gets killed, tearing down the whole account connection each cycle.
521
+ // The folder is re-probed once the interval passes, right away if its
522
+ // STATUS counters changed (something appeared in the folder), and the
523
+ // marker is cleared on a successful SELECT
524
+ let phantomState = await this.getPhantomState();
525
+ if (
526
+ phantomState &&
527
+ phantomState.count >= PHANTOM_SELECT_FAIL_THRESHOLD &&
528
+ phantomState.statusKey === phantomStatusKey(status) &&
529
+ Date.now() - phantomState.time < PHANTOM_REPROBE_INTERVAL
530
+ ) {
531
+ this.logger.debug({
532
+ msg: 'Skipped select of a phantom mailbox',
533
+ path: this.path,
534
+ selectFailures: phantomState.count,
535
+ lastFailure: new Date(phantomState.time).toISOString()
536
+ });
537
+ return;
538
+ }
539
+
504
540
  // Need to sync - create promise that resolves when sync is complete
505
541
  let syncedPromise = new Promise((resolve, reject) => {
506
542
  this.synced = resolve;
@@ -537,10 +573,69 @@ class Mailbox {
537
573
  responseText: err.responseText
538
574
  });
539
575
  this.synced = false;
576
+ // Count the failure so a permanent phantom stops being probed on
577
+ // every sync pass once it hits PHANTOM_SELECT_FAIL_THRESHOLD
578
+ await this.setPhantomState(phantomState, status);
540
579
  return;
541
580
  }
542
581
  throw err;
543
582
  }
583
+
584
+ if (phantomState) {
585
+ // the folder can be selected again, drop the failure marker
586
+ await this.clearPhantomState();
587
+ }
588
+ }
589
+
590
+ /**
591
+ * Reads the phantom folder marker: how many times in a row a SELECT of
592
+ * this listed folder has been rejected, when the last rejection happened,
593
+ * and a fingerprint of the STATUS counters observed at that time
594
+ * @returns {Object|false} Marker object {count, time, statusKey} or false
595
+ */
596
+ async getPhantomState() {
597
+ let raw = await this.connection.redis.hget(this.getMailboxKey(), 'phantomState');
598
+ if (!raw) {
599
+ return false;
600
+ }
601
+ try {
602
+ let value = JSON.parse(raw);
603
+ if (value && typeof value.count === 'number' && typeof value.time === 'number') {
604
+ return value;
605
+ }
606
+ } catch (err) {
607
+ // corrupted marker, treat as unset
608
+ }
609
+ return false;
610
+ }
611
+
612
+ /**
613
+ * Records a failed SELECT of a listed folder
614
+ * @param {Object|false} phantomState - Previous marker from getPhantomState()
615
+ * @param {Object} status - STATUS counters from the failing sync pass
616
+ */
617
+ async setPhantomState(phantomState, status) {
618
+ try {
619
+ await this.connection.redis.hset(
620
+ this.getMailboxKey(),
621
+ 'phantomState',
622
+ JSON.stringify({
623
+ count: (phantomState ? phantomState.count : 0) + 1,
624
+ time: Date.now(),
625
+ statusKey: phantomStatusKey(status)
626
+ })
627
+ );
628
+ } catch (err) {
629
+ // failing to persist the marker must not mask the skip handling
630
+ this.logger.error({ msg: 'Failed to store phantom folder marker', path: this.path, err });
631
+ }
632
+ }
633
+
634
+ /**
635
+ * Removes the phantom folder marker
636
+ */
637
+ async clearPhantomState() {
638
+ await this.connection.redis.hdel(this.getMailboxKey(), 'phantomState');
544
639
  }
545
640
 
546
641
  /**
@@ -33,7 +33,15 @@ const RESYNC_DELAY = 15 * 60;
33
33
  // TTL for ensuring main mailbox selection after operations (5 seconds)
34
34
  const ENSURE_MAIN_TTL = 5 * 1000;
35
35
 
36
- const { AUTH_ERROR_NOTIFY, AUTH_SUCCESS_NOTIFY, CONNECT_ERROR_NOTIFY, DEFAULT_DOWNLOAD_CHUNK_SIZE, MAX_BACKOFF_DELAY, TLS_DEFAULTS } = require('../consts');
36
+ const {
37
+ AUTH_ERROR_NOTIFY,
38
+ AUTH_SUCCESS_NOTIFY,
39
+ CONNECT_ERROR_NOTIFY,
40
+ DEFAULT_DOWNLOAD_CHUNK_SIZE,
41
+ MAX_BACKOFF_DELAY,
42
+ STABLE_CONNECTION_TIME,
43
+ TLS_DEFAULTS
44
+ } = require('../consts');
37
45
 
38
46
  // Configuration for download operations - chunk size for streaming attachments/messages
39
47
  const DOWNLOAD_CHUNK_SIZE = getByteSize(readEnvValue('EENGINE_CHUNK_SIZE')) || DEFAULT_DOWNLOAD_CHUNK_SIZE;
@@ -155,6 +163,63 @@ class IMAPClient extends BaseClient {
155
163
  // the first use (3000, 4500, ... capped at 30000)
156
164
  this.errorReconnectBackoff = new ReconnectBackoff({ baseDelay: 3000, maxDelay: 30000 });
157
165
  this.reconnectTimer = null;
166
+
167
+ // Unexpected-close reconnection throttle. Deliberately NOT reset after
168
+ // a successful sync like the two backoffs above - a connection only
169
+ // validates it by surviving STABLE_CONNECTION_TIME. A server that
170
+ // accepts the full connection setup and then drops the connection
171
+ // would otherwise reset the delay on every cycle and loop at full
172
+ // speed (measured ~17 logins/sec against such a server). Jitter keeps
173
+ // a fleet of accounts on one failing host from reconnecting in sync
174
+ this.closeReconnectBackoff = new ReconnectBackoff({ baseDelay: 2000, maxDelay: 30000, jitter: 1000 });
175
+ }
176
+
177
+ /**
178
+ * Checks whether a dropped connection had proven itself stable by
179
+ * surviving STABLE_CONNECTION_TIME, resetting the survival-gated close
180
+ * backoff when it had. Both the error and the close handler consult this,
181
+ * so a server that accepts the full connection setup and then drops the
182
+ * connection gets throttled the same way regardless of whether the drop
183
+ * surfaces as an error event or a bare close - the other backoffs are
184
+ * reset by a completed setup, which such a server passes on every cycle
185
+ * @param {Object} imapClient - The dropped connection
186
+ * @returns {Boolean} True when the connection had proven itself stable
187
+ */
188
+ validateConnectionAge(imapClient) {
189
+ if (Date.now() - imapClient.connectionStartTime >= STABLE_CONNECTION_TIME) {
190
+ this.closeReconnectBackoff.reset();
191
+ return true;
192
+ }
193
+ return false;
194
+ }
195
+
196
+ /**
197
+ * Schedules a debounced reconnection attempt. Shared by the error and
198
+ * close handlers - both draw from the single reconnectTimer slot, so
199
+ * whichever fires first owns the retry
200
+ * @param {Object} backoff - ReconnectBackoff instance that provides the delay
201
+ * @param {String} msg - Log message for the scheduling entry
202
+ */
203
+ scheduleReconnect(backoff, msg) {
204
+ if (this.reconnectTimer) {
205
+ return;
206
+ }
207
+ const retryDelay = backoff.nextDelay();
208
+ this.logger.info({ msg, account: this.account, attempt: backoff.attempts, delay: Math.round(retryDelay) });
209
+ this.reconnectTimer = setTimeout(() => {
210
+ this.reconnectTimer = null;
211
+ // The backoff counter is reset after a successful sync (or for the
212
+ // close backoff by proven connection survival), not here -
213
+ // reconnect() also resolves when the setup failed and was rescheduled
214
+ this.reconnect().catch(err => {
215
+ this.logger.warn({
216
+ msg: 'IMAP reconnection error',
217
+ account: this.account,
218
+ err,
219
+ attempt: backoff.attempts
220
+ });
221
+ });
222
+ }, retryDelay);
158
223
  }
159
224
 
160
225
  /**
@@ -1490,6 +1555,10 @@ class IMAPClient extends BaseClient {
1490
1555
  expungeHandler: async payload => await this.expungeHandler(payload)
1491
1556
  })
1492
1557
  );
1558
+ // Birth time of this connection attempt - the unexpected-close
1559
+ // handler uses the age to tell a stable connection dropping from a
1560
+ // connect/drop cycle that needs throttling
1561
+ imapClient.connectionStartTime = Date.now();
1493
1562
  this.connections.add(imapClient);
1494
1563
  await this.redis.hSetExists(this.getAccountKey(), 'connections', this.connections.size.toString());
1495
1564
 
@@ -1523,29 +1592,14 @@ class IMAPClient extends BaseClient {
1523
1592
  }
1524
1593
  imapClient.close(); // ensure the client is closed on errors
1525
1594
 
1526
- // Debounced reconnection with exponential backoff
1527
- if (!this.reconnectTimer) {
1528
- // Calculate delay with cap
1529
- const errorRetryDelay = this.errorReconnectBackoff.nextDelay();
1530
-
1531
- this.logger.info({
1532
- msg: 'Scheduling error-triggered reconnection',
1533
- delay: errorRetryDelay
1534
- });
1535
-
1536
- this.reconnectTimer = setTimeout(() => {
1537
- this.reconnectTimer = null;
1538
- // The backoff delay is reset after a successful sync, not here -
1539
- // reconnect() also resolves when the setup failed and was rescheduled
1540
- this.reconnect().catch(err => {
1541
- this.logger.warn({
1542
- msg: 'IMAP reconnection error',
1543
- account: this.account,
1544
- err,
1545
- attempt: this.errorReconnectBackoff.attempts
1546
- });
1547
- });
1548
- }, errorRetryDelay);
1595
+ if (this.validateConnectionAge(imapClient)) {
1596
+ // Transient error on a proven-stable connection
1597
+ this.scheduleReconnect(this.errorReconnectBackoff, 'Scheduling error-triggered reconnection');
1598
+ } else {
1599
+ // The connection died soon after it was set up - use the
1600
+ // survival-gated backoff, the error backoff is reset by
1601
+ // every completed setup and would never grow here
1602
+ this.scheduleReconnect(this.closeReconnectBackoff, 'Throttling reconnection of a short-lived connection');
1549
1603
  }
1550
1604
  });
1551
1605
 
@@ -1610,8 +1664,22 @@ class IMAPClient extends BaseClient {
1610
1664
  try {
1611
1665
  // Attempt reconnection if this was an unexpected close
1612
1666
  if (!imapClient.disabled && imapClient === this.imapClient && !this._connecting) {
1613
- imapClient.log.debug({ msg: 'Requesting reconnection due to unexpected close', type: 'imapClient', account: this.account });
1614
- await this.reconnect();
1667
+ if (this.validateConnectionAge(imapClient)) {
1668
+ // A proven-stable connection dropped - reconnect right away
1669
+ if (!this.reconnectTimer) {
1670
+ imapClient.log.debug({ msg: 'Requesting reconnection due to unexpected close', type: 'imapClient', account: this.account });
1671
+ await this.reconnect();
1672
+ }
1673
+ } else {
1674
+ // The connection died soon after it was set up. An
1675
+ // immediate retry against a server that drops
1676
+ // connections right after setup turns into an
1677
+ // unthrottled login loop (the setup itself
1678
+ // "succeeds", so the sync-reset backoffs never
1679
+ // grow), so schedule the reconnect with a growing
1680
+ // delay instead
1681
+ this.scheduleReconnect(this.closeReconnectBackoff, 'Throttling reconnection of a short-lived connection');
1682
+ }
1615
1683
  }
1616
1684
  } catch (err) {
1617
1685
  imapClient.log.error({ msg: 'Reconnection error', err });
@@ -1711,17 +1779,22 @@ class IMAPClient extends BaseClient {
1711
1779
  }
1712
1780
  }
1713
1781
 
1782
+ // ImapFlow rewrites err.response into a string for authentication
1783
+ // failures, but for other command failures it is the parsed response
1784
+ // object - prefer the response text so the stored error state and
1785
+ // webhook payloads never render as "[object Object]"
1786
+ let errorResponse = (typeof err.response === 'string' && err.response) || err.responseText;
1714
1787
  if (err.authenticationFailed) {
1715
1788
  this.logger.error({ msg: 'Failed to authenticate', account: this.account, err });
1716
1789
  await this.notify(false, AUTH_ERROR_NOTIFY, {
1717
- response: err.response,
1790
+ response: errorResponse,
1718
1791
  serverResponseCode: err.serverResponseCode
1719
1792
  });
1720
1793
  this.state = 'authenticationError';
1721
1794
  } else {
1722
1795
  this.logger.error({ msg: 'Failed to connect', account: this.account, err });
1723
1796
  await this.notify(false, CONNECT_ERROR_NOTIFY, {
1724
- response: err.response || err.message,
1797
+ response: errorResponse || err.message,
1725
1798
  serverResponseCode: err.serverResponseCode || err.code
1726
1799
  });
1727
1800
  this.state = 'connectError';
@@ -2840,7 +2840,7 @@ class OutlookClient extends BaseClient {
2840
2840
  }
2841
2841
  // Pass `call` so Account.update() can dispatch a reconnect back to this worker when
2842
2842
  // OAuth credentials are re-authorized for an account in an error state (same channel the
2843
- // IMAP path uses). Without it, renewAccessToken() -> update() would throw on the reconnect.
2843
+ // IMAP path uses).
2844
2844
  this.accountObject = new Account({ redis: this.redis, account: this.account, secret: await getSecret(), call: msg => this.call(msg) });
2845
2845
 
2846
2846
  return this.accountObject;
package/lib/es.js CHANGED
@@ -755,30 +755,3 @@ module.exports = {
755
755
  // immutable copy
756
756
  defaultMappings: Object.freeze(structuredClone(mappings))
757
757
  };
758
-
759
- /*
760
- const { Client: ElasticSearch } = require('@elastic/elasticsearch');
761
- async function main() {
762
- const client = new ElasticSearch({
763
- node: { url: new URL('https://127.0.0.1:9200'), tls: { rejectUnauthorized: false } },
764
- auth: {
765
- username: 'elastic',
766
- password: 'NqDHHrrPVBQtxy9cvIYa'
767
- }
768
- });
769
-
770
- for (let index of ['mastiff', 'kastiff']) {
771
- console.log(index, await module.exports.ensureIndex(client, index, { mappings, analyzer, tokenizer, filter }));
772
-
773
- await client.index({
774
- index: `${index}.threads`,
775
- id: 'test',
776
- document: {
777
- tere: 'vana'
778
- }
779
- });
780
- }
781
- }
782
-
783
- main().catch(err => console.error(err));
784
- */
@@ -20,7 +20,7 @@ const msgpack = require('msgpack5')();
20
20
 
21
21
  const settings = require('./settings');
22
22
  const { getCounterValues, hasEnvValue, readEnvValue, getBoolean } = require('./tools');
23
- const { REDIS_PREFIX, EE_DOCKER_LEGACY } = require('./consts');
23
+ const { REDIS_PREFIX } = require('./consts');
24
24
  const { oauth2Apps } = require('./oauth2-apps');
25
25
  const passkeys = require('./passkeys');
26
26
  const featureFlags = require('./feature-flags');
@@ -110,9 +110,6 @@ function installChannel() {
110
110
  if (getBoolean(readEnvValue('EENGINE_INSTALL_SCRIPT'))) {
111
111
  return 'script';
112
112
  }
113
- if (EE_DOCKER_LEGACY) {
114
- return 'docker-legacy';
115
- }
116
113
  return 'general';
117
114
  }
118
115
 
@@ -275,7 +272,6 @@ async function collectBeacon({ redis, logger }) {
275
272
  if (on('documentStorePreProcessingEnabled')) dep.push('ds_preproc');
276
273
  if (on('gmailEnabled') || on('outlookEnabled') || on('mailRuEnabled')) dep.push('legacyOauth');
277
274
  if (on('trackSentMessages')) dep.push('trackSent');
278
- if (EE_DOCKER_LEGACY) dep.push('dockerLegacy');
279
275
  await safe(async () => {
280
276
  const ids = await redis.smembers(`${REDIS_PREFIX}wh:i`);
281
277
  if (ids && ids.length && ids.length <= WH_SCAN_LIMIT) {
package/lib/schemas.js CHANGED
@@ -677,6 +677,13 @@ const imapSchema = {
677
677
  .unknown()
678
678
  .description('Advanced TLS configuration options')
679
679
  .label('ImapTlsOptions'),
680
+ // the field name deliberately matches the ImapFlow option name - the stored
681
+ // imap object is merged verbatim into the ImapFlow connection config
682
+ disableIMAP4rev2: Joi.boolean()
683
+ .example(false)
684
+ .description(
685
+ 'Do not use IMAP4rev2 even if the server supports it. Set this for servers with a broken IMAP4rev2 implementation. Only applies to accounts using regular password authentication.'
686
+ ),
680
687
  resyncDelay: Joi.number().integer().example(RESYNC_DELAY).description('Delay in seconds between full mailbox resynchronizations').default(RESYNC_DELAY),
681
688
  disabled: Joi.boolean().example(false).description('Temporarily disable IMAP operations for this account'),
682
689
 
@@ -864,6 +871,11 @@ const imapUpdateSchema = {
864
871
  .unknown()
865
872
  .description('Advanced TLS configuration options')
866
873
  .label('ImapUpdateTlsOptions'),
874
+ disableIMAP4rev2: Joi.boolean()
875
+ .example(false)
876
+ .description(
877
+ 'Do not use IMAP4rev2 even if the server supports it. Set this for servers with a broken IMAP4rev2 implementation. Only applies to accounts using regular password authentication.'
878
+ ),
867
879
  resyncDelay: Joi.number().integer().example(RESYNC_DELAY).description('Delay in seconds between full mailbox resynchronizations'),
868
880
 
869
881
  disabled: Joi.boolean().example(false).description('Temporarily disable IMAP operations for this account'),
package/lib/settings.js CHANGED
@@ -29,6 +29,19 @@ const ENCRYPTED_KEYS = [
29
29
  module.exports = {
30
30
  encryptedKeys: ENCRYPTED_KEYS,
31
31
 
32
+ /**
33
+ * Whether admin authentication is configured for this instance.
34
+ *
35
+ * The single spelling of the test that gates `server.auth.default('session')` in workers/api.js.
36
+ * Routes that are only protected by that default are reachable by anyone when it returns false,
37
+ * so anything they expose has to gate on this explicitly.
38
+ *
39
+ * @returns {Promise<Boolean>} True when an admin password has been set
40
+ */
41
+ async isInstanceSecured() {
42
+ return !!(await module.exports.get('authData'));
43
+ },
44
+
32
45
  async getValue(encryptSecret, key, value) {
33
46
  if (!value) {
34
47
  return null;
package/lib/tokens.js CHANGED
@@ -80,6 +80,21 @@ module.exports = {
80
80
  return true;
81
81
  },
82
82
 
83
+ /**
84
+ * Provisions a new access token.
85
+ *
86
+ * Deliberately unguarded. The admin-password requirement belongs to the routes, not here,
87
+ * because only they can tell whether the caller actually presented a credential. Gating this
88
+ * function instead refused headless deployments too (EENGINE_PREPARED_TOKEN with no admin
89
+ * password is a supported configuration), and the CLI needs shell access anyway.
90
+ *
91
+ * Both HTTP callers gate themselves: POST /admin/tokens/new unconditionally, since
92
+ * `server.auth.default('session')` leaves it open while authData is unset; POST /v1/token only
93
+ * for the `preauth` caller that the `disableTokens` setting lets through without a credential.
94
+ *
95
+ * @param {Object} opts - Token options. May originate from a request payload.
96
+ * @returns {String} The token value (only ever returned here - it is stored hashed)
97
+ */
83
98
  async provision(opts) {
84
99
  opts = opts || {};
85
100
  const { account, restrictions, ip, remoteAddress, description, metadata, scopes, nolog } = opts;
@@ -1695,7 +1695,9 @@ function init(args) {
1695
1695
  const values = Object.assign({}, flattenObjectKeys(accountData), {
1696
1696
  imap: true,
1697
1697
  imap_disabled: (!accountData.imap && !accountData.oauth2) || (accountData.imap && accountData.imap.disabled),
1698
+ imap_tls_ignoreCertErrors: !!(accountData.imap && accountData.imap.tls && accountData.imap.tls.rejectUnauthorized === false),
1698
1699
  smtp: !!accountData.smtp,
1700
+ smtp_tls_ignoreCertErrors: !!(accountData.smtp && accountData.smtp.tls && accountData.smtp.tls.rejectUnauthorized === false),
1699
1701
  oauth2: !!accountData.oauth2,
1700
1702
 
1701
1703
  imap_auth_pass: '',
@@ -1790,9 +1792,7 @@ function init(args) {
1790
1792
  if (request.payload.imap) {
1791
1793
  let imapTls = (oldData.imap && oldData.imap.tls) || {};
1792
1794
 
1793
- let updateKeys = {
1794
- tls: imapTls
1795
- };
1795
+ let updateKeys = {};
1796
1796
 
1797
1797
  for (let key of ['host', 'port', 'disabled', 'sentMailPath']) {
1798
1798
  if (`imap_${key}` in request.payload) {
@@ -1807,6 +1807,22 @@ function init(args) {
1807
1807
  }
1808
1808
  updateKeys.auth = imapAuth;
1809
1809
  updateKeys.secure = request.payload.imap_secure;
1810
+ // The connection settings section is hidden for OAuth2 and disabled
1811
+ // accounts, so like `secure` these only apply when it was submitted.
1812
+ // Written only when the effective state changes - an untouched form
1813
+ // save must not add new keys, as any imap diff forces a reconnect
1814
+ if (request.payload.imap_tls_ignoreCertErrors !== (imapTls.rejectUnauthorized === false)) {
1815
+ imapTls.rejectUnauthorized = !request.payload.imap_tls_ignoreCertErrors;
1816
+ }
1817
+ if (request.payload.imap_disableIMAP4rev2 !== !!(oldData.imap && oldData.imap.disableIMAP4rev2)) {
1818
+ updateKeys.disableIMAP4rev2 = request.payload.imap_disableIMAP4rev2;
1819
+ }
1820
+ }
1821
+
1822
+ // skipped while empty and absent from the stored account for the same
1823
+ // reason as above - a no-op save must not introduce a tls:{} key
1824
+ if (Object.keys(imapTls).length) {
1825
+ updateKeys.tls = imapTls;
1810
1826
  }
1811
1827
 
1812
1828
  updates.imap = Object.assign(oldData.imap || {}, updateKeys);
@@ -1824,13 +1840,23 @@ function init(args) {
1824
1840
  smtpAuth.pass = request.payload.smtp_auth_pass;
1825
1841
  }
1826
1842
 
1843
+ // written only when the effective state changes, and the tls object is
1844
+ // skipped while empty - same as the IMAP flags, a no-op save must not
1845
+ // modify the stored account
1846
+ if (request.payload.smtp_tls_ignoreCertErrors !== (smtpTls.rejectUnauthorized === false)) {
1847
+ smtpTls.rejectUnauthorized = !request.payload.smtp_tls_ignoreCertErrors;
1848
+ }
1849
+
1827
1850
  updates.smtp = Object.assign(oldData.smtp || {}, {
1828
1851
  host: request.payload.smtp_host,
1829
1852
  port: request.payload.smtp_port,
1830
1853
  secure: request.payload.smtp_secure,
1831
- auth: smtpAuth,
1832
- tls: smtpTls
1854
+ auth: smtpAuth
1833
1855
  });
1856
+
1857
+ if (Object.keys(smtpTls).length) {
1858
+ updates.smtp.tls = smtpTls;
1859
+ }
1834
1860
  }
1835
1861
 
1836
1862
  await accountObject.update(updates);
@@ -1852,6 +1878,14 @@ function init(args) {
1852
1878
 
1853
1879
  menuAccounts: true,
1854
1880
  account: request.params.account,
1881
+ // re-render the form from the submitted payload (the field names
1882
+ // match the template values); without this the form comes back
1883
+ // blank and the IMAP/SMTP cards disappear entirely
1884
+ values: Object.assign({}, request.payload, {
1885
+ oauth2: !!accountData.oauth2,
1886
+ imap_auth_pass: '',
1887
+ smtp_auth_pass: ''
1888
+ }),
1855
1889
  availablePaths: JSON.stringify(mailboxes.map(entry => entry.path)),
1856
1890
 
1857
1891
  isApi: accountData.isApi,
@@ -1902,6 +1936,14 @@ function init(args) {
1902
1936
  menuAccounts: true,
1903
1937
  account: request.params.account,
1904
1938
  errors,
1939
+ // re-render the form from the (raw, unvalidated) submitted
1940
+ // payload so the entered values and the IMAP/SMTP cards
1941
+ // survive a validation failure
1942
+ values: Object.assign({}, request.payload, {
1943
+ oauth2: !!accountData.oauth2,
1944
+ imap_auth_pass: '',
1945
+ smtp_auth_pass: ''
1946
+ }),
1905
1947
  availablePaths: JSON.stringify(mailboxes.map(entry => entry.path)),
1906
1948
 
1907
1949
  isApi: accountData.isApi,
@@ -1945,6 +1987,18 @@ function init(args) {
1945
1987
  .default(false)
1946
1988
  .example(true)
1947
1989
  .description('Should connection use TLS. Usually true for port 993'),
1990
+ imap_tls_ignoreCertErrors: Joi.boolean()
1991
+ .truthy('Y', 'true', '1', 'on')
1992
+ .falsy('N', 'false', 0, '')
1993
+ .default(false)
1994
+ .example(false)
1995
+ .description('Allow connections to servers with invalid TLS certificates for this account'),
1996
+ imap_disableIMAP4rev2: Joi.boolean()
1997
+ .truthy('Y', 'true', '1', 'on')
1998
+ .falsy('N', 'false', 0, '')
1999
+ .default(false)
2000
+ .example(false)
2001
+ .description('Do not use IMAP4rev2 even if the server supports it'),
1948
2002
  imap_disabled: Joi.boolean()
1949
2003
  .truthy('Y', 'true', '1', 'on')
1950
2004
  .falsy('N', 'false', 0, '')
@@ -1988,6 +2042,12 @@ function init(args) {
1988
2042
  .default(false)
1989
2043
  .example(true)
1990
2044
  .description('Should connection use TLS. Usually true for port 465'),
2045
+ smtp_tls_ignoreCertErrors: Joi.boolean()
2046
+ .truthy('Y', 'true', '1', 'on')
2047
+ .falsy('N', 'false', 0, '')
2048
+ .default(false)
2049
+ .example(false)
2050
+ .description('Allow connections to servers with invalid TLS certificates for this account'),
1991
2051
 
1992
2052
  customHeaders: Joi.string()
1993
2053
  .allow('')
@@ -2336,6 +2336,19 @@ return payload;`)
2336
2336
 
2337
2337
  async handler(request) {
2338
2338
  try {
2339
+ // Nothing invalidates an access token once it is minted, so a token handed out while
2340
+ // this route is reachable without a login keeps working afterwards. The route is only
2341
+ // protected by `server.auth.default('session')`, which workers/api.js applies
2342
+ // conditionally - and only in the API worker that observes the password being set, so
2343
+ // it is NOT reliably in force just because a password now exists in Redis (the CLI
2344
+ // `emailengine password` path and sibling API workers never apply it until restart).
2345
+ // So gate on whether THIS request actually carries an authenticated admin session
2346
+ // rather than on the global secured-state: an unauthenticated caller must not mint a
2347
+ // lasting token, and an authenticated admin always may.
2348
+ if (!request.auth.isAuthenticated) {
2349
+ throw Boom.forbidden('Can not provision an access token without an authenticated admin session');
2350
+ }
2351
+
2339
2352
  let data = {
2340
2353
  ip: request.app.ip,
2341
2354
  remoteAddress: request.app.ip,
@@ -0,0 +1,54 @@
1
+ 'use strict';
2
+
3
+ // Serialization of an Error across a worker-thread RPC hop.
4
+ //
5
+ // submitMessage() runs in the IMAP worker and the error it throws reaches the submit worker through
6
+ // two postMessage relays (workers/imap.js -> server.js -> workers/submit.js). postMessage cannot
7
+ // clone an Error's own enumerable-but-non-standard properties reliably, so each hop copies an
8
+ // explicit field list onto a plain payload and rebuilds an Error on the far side. Any field not
9
+ // listed here is silently dropped in transit.
10
+ //
11
+ // `responseCode` (the numeric SMTP reply code) is on the list because lib/delivery-error.js needs it
12
+ // to tell a transient 4xx rejection (e.g. greylisting) from a permanent 5xx one. It used to be
13
+ // dropped, so the predicate's SMTP-reply branch never fired in production; keeping the field list in
14
+ // one place makes that dependency explicit and unit-testable (see test/worker-rpc-error-test.js).
15
+ //
16
+ // These helpers are used at the delivery-error RPC path - the imap/submit workers and the main-thread
17
+ // hub (server.js) that relays between them. The other workers (webhooks/export/documents/smtp/api)
18
+ // keep their own inline resp-handler copies: they never carry a delivery error, so `responseCode`
19
+ // does not apply to them. Route a delivery error through a new worker and it must switch to these too.
20
+ const RPC_ERROR_FIELDS = ['code', 'statusCode', 'responseCode', 'info'];
21
+
22
+ /**
23
+ * Serializes an Error into the plain payload sent over postMessage.
24
+ *
25
+ * @param {Error} err - Error to serialize
26
+ * @returns {Object} Payload with `error` (the message) plus every present RPC_ERROR_FIELD
27
+ */
28
+ function packRpcError(err) {
29
+ let payload = { error: err.message };
30
+ for (let field of RPC_ERROR_FIELDS) {
31
+ if (err[field] != null) {
32
+ payload[field] = err[field];
33
+ }
34
+ }
35
+ return payload;
36
+ }
37
+
38
+ /**
39
+ * Rebuilds an Error from a received postMessage payload.
40
+ *
41
+ * @param {Object} message - Payload produced by packRpcError (may carry extra fields, e.g. cmd/mid)
42
+ * @returns {Error} Error with its message and every present RPC_ERROR_FIELD restored
43
+ */
44
+ function unpackRpcError(message) {
45
+ let err = new Error(message.error);
46
+ for (let field of RPC_ERROR_FIELDS) {
47
+ if (message[field] != null) {
48
+ err[field] = message[field];
49
+ }
50
+ }
51
+ return err;
52
+ }
53
+
54
+ module.exports = { packRpcError, unpackRpcError };