emailengine-app 2.73.1 → 2.74.1

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.
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env bash
2
+ #
3
+ # Smoke test the EmailEngine CLI inside a built image.
4
+ #
5
+ # The Dockerfile copies an explicit allowlist of root-level files rather than `COPY . .`, so a CLI
6
+ # subcommand that dispatches to one (e.g. `scan` -> ../scan.js, `encrypt` -> ../encrypt.js) can be
7
+ # missing from the image while the build and the server both stay green - CMD only runs server.js.
8
+ # Both `scan` and `encrypt` shipped broken that way. Exercising the commands catches it regardless of
9
+ # how the module is referenced, which a source-level check cannot.
10
+ #
11
+ # Runs against a locally-loaded image (see the workflows) BEFORE the multi-arch push, so a broken
12
+ # image is never published - the previous version smoke tested the already-pushed image and could
13
+ # only detect the regression, not prevent shipping it.
14
+ #
15
+ # Usage: docker-smoke-test.sh <image-ref>
16
+ set -euo pipefail
17
+
18
+ image="${1:?usage: docker-smoke-test.sh <image-ref>}"
19
+ status=0
20
+
21
+ # Only the subcommands that dispatch to a root-level module can exercise the allowlist; everything
22
+ # else resolves out of lib/ or node_modules. This list is a runtime spot-check, not the completeness
23
+ # authority - test/dockerfile-cli-modules-test.js derives the full set of root-level requires from
24
+ # bin/emailengine.js and fails if any is not COPYed. Add new root-dispatching subcommands here too.
25
+ for cmd in scan encrypt; do
26
+ # These subcommands need Redis or arguments and are expected to exit non-zero; we only assert the
27
+ # module resolved. Capture the exit code explicitly (no `|| true`, which would mask a container
28
+ # that never started) so a docker/exec failure - exit >=125 - is treated as a failure, not a pass.
29
+ out=$(docker run --rm --entrypoint node "$image" bin/emailengine.js "$cmd" 2>&1) && rc=0 || rc=$?
30
+
31
+ if [ "$rc" -ge 125 ]; then
32
+ echo "::error::container failed to start for 'emailengine $cmd' (exit $rc)"
33
+ printf '%s\n' "$out"
34
+ status=1
35
+ continue
36
+ fi
37
+
38
+ if grep -q "Cannot find module" <<<"$out"; then
39
+ echo "::error::emailengine $cmd cannot resolve its module inside the image"
40
+ printf '%s\n' "$out"
41
+ status=1
42
+ fi
43
+ done
44
+
45
+ exit $status
@@ -110,7 +110,27 @@ jobs:
110
110
  tags: |
111
111
  type=raw,value=edge,enable=true
112
112
 
113
+ # Build the amd64 image locally (no push) and smoke test the CLI BEFORE publishing, so a
114
+ # broken image is never pushed - the previous version smoke tested the already-pushed
115
+ # image and could only detect the regression, not prevent shipping it. This build replays
116
+ # from the same gha cache the multi-arch push below reuses, so it is cheap.
117
+ - name: Build for smoke test (amd64, local)
118
+ uses: docker/build-push-action@v7
119
+ with:
120
+ context: .
121
+ platforms: linux/amd64
122
+ load: true
123
+ tags: emailengine:smoke-test
124
+ # Without a cache backend BuildKit starts cold on every run: setup-buildx-action
125
+ # creates a fresh builder on an ephemeral runner, so the emulated arm64 `npm ci`
126
+ # re-runs in full regardless of how the Dockerfile layers are ordered.
127
+ cache-from: type=gha
128
+
129
+ - name: Smoke test the CLI inside the image
130
+ run: bash .github/docker-smoke-test.sh emailengine:smoke-test
131
+
113
132
  - name: Build and push
133
+ id: build
114
134
  uses: docker/build-push-action@v7
115
135
  with:
116
136
  context: .
@@ -118,3 +138,5 @@ jobs:
118
138
  push: true
119
139
  tags: ${{ steps.meta.outputs.tags }}
120
140
  labels: ${{ steps.meta.outputs.labels }}
141
+ cache-from: type=gha
142
+ cache-to: type=gha,mode=max
@@ -96,12 +96,31 @@ jobs:
96
96
  username: ${{ github.repository_owner }}
97
97
  password: ${{ secrets.GITHUB_TOKEN }}
98
98
 
99
+ # Build the amd64 image locally (no push) and smoke test the CLI BEFORE publishing, so a
100
+ # broken image is never pushed to the tags users pull - the previous version smoke tested
101
+ # the already-pushed image and could only detect the regression, not prevent shipping it.
102
+ # This build replays from the same gha cache the multi-arch push below reuses.
103
+ - name: Build for smoke test (amd64, local)
104
+ uses: docker/build-push-action@v7
105
+ with:
106
+ context: .
107
+ platforms: linux/amd64
108
+ load: true
109
+ tags: emailengine:smoke-test
110
+ cache-from: type=gha
111
+
112
+ - name: Smoke test the CLI inside the image
113
+ run: bash .github/docker-smoke-test.sh emailengine:smoke-test
114
+
99
115
  - name: Build and push
116
+ id: build
100
117
  uses: docker/build-push-action@v7
101
118
  with:
102
119
  context: .
103
120
  platforms: ${{ steps.buildx.outputs.platforms }}
104
121
  push: true
122
+ cache-from: type=gha
123
+ cache-to: type=gha,mode=max
105
124
  tags: |
106
125
  ${{ github.repository }}:latest
107
126
  ${{ github.repository }}:v${{needs.release_please.outputs.major}}.${{needs.release_please.outputs.minor}}.${{needs.release_please.outputs.patch}}
@@ -100,6 +100,37 @@ jobs:
100
100
  GMAIL_API_ACCOUNT_EMAIL_1: ${{ secrets.TEST_GMAIL_API_ACCOUNT_EMAIL_1 }}
101
101
  GMAIL_API_ACCOUNT_REFRESH_1: ${{ secrets.TEST_GMAIL_API_ACCOUNT_REFRESH_1 }}
102
102
 
103
+ dovecot:
104
+ # Live IMAP tier against a real IMAP4rev2 server (Dovecot 2.4 in Docker);
105
+ # fully hermetic - needs no external mail accounts. See test/dovecot/README.md
106
+ name: Live Dovecot Tests (IMAP4rev2)
107
+ if: ${{ !startsWith(github.ref_name, 'release-please--') && !startsWith(github.head_ref, 'release-please--') }}
108
+ timeout-minutes: 15
109
+ runs-on: ubuntu-24.04
110
+ services:
111
+ redis:
112
+ image: redis
113
+ options: >-
114
+ --health-cmd "redis-cli ping"
115
+ --health-interval 10s
116
+ --health-timeout 5s
117
+ --health-retries 5
118
+ ports:
119
+ - 6379:6379
120
+ steps:
121
+ - uses: actions/checkout@v6
122
+ - name: Use Node.js 24
123
+ uses: actions/setup-node@v6
124
+ with:
125
+ node-version: 24
126
+ cache: npm
127
+ - run: npm install
128
+ - name: Run live Dovecot tests
129
+ run: |
130
+ npm run test:dovecot
131
+ env:
132
+ EENGINE_DOVECOT_PLATFORM: linux/amd64
133
+
103
134
  integration:
104
135
  name: Integration Tests
105
136
  if: ${{ !startsWith(github.ref_name, 'release-please--') && !startsWith(github.head_ref, 'release-please--') }}
package/CHANGELOG.md CHANGED
@@ -1,5 +1,60 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.74.1](https://github.com/postalsys/emailengine/compare/v2.74.0...v2.74.1) (2026-07-24)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **deps:** update dependencies (@postalsys/email-ai-tools 1.13.14) ([027f065](https://github.com/postalsys/emailengine/commit/027f0654a1a5d844dd02a22d1f594927e4c4e258))
9
+ * **ui:** document Azure OpenAI endpoints and refresh the fallback AI model list ([defef18](https://github.com/postalsys/emailengine/commit/defef1832165069d6657ebdd9a6f0c261631105a))
10
+ * **ui:** group the workers page by kind with pool health and descriptions ([8ae65a9](https://github.com/postalsys/emailengine/commit/8ae65a9e5942c2b24b76b2e815d56725567a3d59))
11
+ * **ui:** show the workers page Accounts column only for email workers ([d0fb2ef](https://github.com/postalsys/emailengine/commit/d0fb2efbb7fccb64469f2333e88d2a6768104bdf))
12
+ * **ui:** warn that Document Store will be removed on 2026-10-01 ([1415af6](https://github.com/postalsys/emailengine/commit/1415af687e24d86846482c292065916c24a9dfae))
13
+
14
+ ## [2.74.0](https://github.com/postalsys/emailengine/compare/v2.73.1...v2.74.0) (2026-07-23)
15
+
16
+
17
+ ### Features
18
+
19
+ * **imap:** add a per-account IMAP4rev2 opt-out and account-level TLS certificate override ([59764fd](https://github.com/postalsys/emailengine/commit/59764fd16f5c895b2c3e714fc769482830a19a36))
20
+ * **ui:** add the account-level invalid-certificate override to the SMTP settings as well ([7d1b9e4](https://github.com/postalsys/emailengine/commit/7d1b9e44e91e9a251743e8b61413b4ef91a177b3))
21
+
22
+
23
+ ### Bug Fixes
24
+
25
+ * **accounts:** back out the OAuth2 auth-failure park ([bc431bd](https://github.com/postalsys/emailengine/commit/bc431bd3ede97d06f58788c66b7dfa8958380c49))
26
+ * **accounts:** make the auth-failure auto-disable work for OAuth2 accounts ([77f78b4](https://github.com/postalsys/emailengine/commit/77f78b4bd852c1662fee9657d84625ccdc58f143))
27
+ * **api:** require an admin session for the Bull Board queue browser ([392723e](https://github.com/postalsys/emailengine/commit/392723e746a83dc8fc7a96fd4c719114667f8b56))
28
+ * **api:** revert the Bull Board admin-session requirement ([14590b8](https://github.com/postalsys/emailengine/commit/14590b86e1557f3b6284401fbd4e1c06a9a72d01))
29
+ * **ci:** give the Docker builds a cache backend and smoke test by digest ([4554d90](https://github.com/postalsys/emailengine/commit/4554d90b5bf38f649b8c27c65a9c26cf39951e0d))
30
+ * **ci:** smoke-test the image before publishing and harden the allowlist test ([c285fcb](https://github.com/postalsys/emailengine/commit/c285fcbbd258846537447cd730342423e6b2eaf7))
31
+ * **deps:** update dependencies ([3370f0a](https://github.com/postalsys/emailengine/commit/3370f0aa3afeb3b07bb5627602a314ec6aaf89fa))
32
+ * **deps:** update dependencies ([e1256b2](https://github.com/postalsys/emailengine/commit/e1256b296f83be3fe161f38af5087d231c8fa3bf))
33
+ * **deps:** update dependencies (imapflow 1.5.0) ([8cc45ac](https://github.com/postalsys/emailengine/commit/8cc45acacb8572d5cf9a187a34d6d284b57d4b99))
34
+ * **docker:** ship the root-level CLI modules in the image ([a63cb4e](https://github.com/postalsys/emailengine/commit/a63cb4e17b3fac9b8e003914b3472f1da20dd6ec))
35
+ * **gitignore:** cover every local env file, not just the exact name ([16124d5](https://github.com/postalsys/emailengine/commit/16124d5e83cb9ead3a0c8520db7fcb4e5eefedaa))
36
+ * **imap:** park phantom folders and throttle short-lived-connection reconnects ([da97da3](https://github.com/postalsys/emailengine/commit/da97da31eddcb327672daf28938efec11b5e55f7))
37
+ * **imap:** store the connection error response as text, not as a parsed object ([3cf8d2e](https://github.com/postalsys/emailengine/commit/3cf8d2e016ce0e8ce623468689ef6f21a90cd6f1))
38
+ * **oauth:** drop the transient token-refresh carve-out, keep the stale-token fix ([63c2d8c](https://github.com/postalsys/emailengine/commit/63c2d8c261a71158ea5670ddc7e080c690240265))
39
+ * **oauth:** make the transient token-failure and delivery-retry fixes actually fire ([5049fea](https://github.com/postalsys/emailengine/commit/5049fea5f1724d4e7ae2fa6f2b58a642af4f7f6b))
40
+ * **oauth:** report transient token failures instead of stalling on them ([10b3480](https://github.com/postalsys/emailengine/commit/10b348082016f047eda641602bfe370d1195e222))
41
+ * **oauth:** stop reporting a rate-limited token endpoint as bad credentials ([de27fca](https://github.com/postalsys/emailengine/commit/de27fca5ed0c42cabb95553a00323dc82fc422bc))
42
+ * **setup:** create production secret files owner-only ([52f0527](https://github.com/postalsys/emailengine/commit/52f052741558e9b3a5478fe2f0ecc5fb0a1679f9))
43
+ * **submit:** retry transient 4xx SMTP rejections and gate token minting on the request principal ([1688c86](https://github.com/postalsys/emailengine/commit/1688c86522d9e79715569e6735353c333d7e527c))
44
+ * **submit:** stop discarding queued mail on non-SMTP 5xx errors ([f80f475](https://github.com/postalsys/emailengine/commit/f80f4754c76e230db529031c0549caf26468d891))
45
+ * **test:** provision scope-test tokens as a trusted local caller ([20ca781](https://github.com/postalsys/emailengine/commit/20ca7817f3679797bb07e17d00e9b4cd5d6d7c4b))
46
+ * **tokens:** refuse to mint an access token before an admin password is set ([ff3dd47](https://github.com/postalsys/emailengine/commit/ff3dd47b06ebac2d7f861fe66e26549db193a9f8))
47
+
48
+
49
+ ### Performance Improvements
50
+
51
+ * **docker:** cache the dependency install and smoke test the CLI in the image ([e275733](https://github.com/postalsys/emailengine/commit/e275733dacc85ba72ea3465013242785c2d7adcf))
52
+
53
+
54
+ ### Reverts
55
+
56
+ * back out the OAuth2 token-failure rework, keep the delivery and token fixes ([496ac3d](https://github.com/postalsys/emailengine/commit/496ac3d9c8737fecaf5ccf21bf98d1bd51e7af5c))
57
+
3
58
  ## [2.73.1](https://github.com/postalsys/emailengine/compare/v2.73.0...v2.73.1) (2026-07-21)
4
59
 
5
60
 
package/Dockerfile CHANGED
@@ -19,6 +19,15 @@ RUN addgroup -S emailenginegroup && adduser -S emailengineuser -G emailenginegro
19
19
 
20
20
  WORKDIR /emailengine
21
21
 
22
+ # Install dependencies before copying any source. npm ci is by far the slowest step in this
23
+ # build - it runs under QEMU emulation for the non-native architecture - and Docker invalidates
24
+ # every layer below a changed one. With the sources copied first, an edit to any file busted
25
+ # this layer and re-ran the whole install; keeping it above them means it is only re-run when
26
+ # the lockfile actually changes.
27
+ COPY package.json package.json
28
+ COPY package-lock.json package-lock.json
29
+ RUN npm ci --omit=dev
30
+
22
31
  # Copy app folders
23
32
  COPY bin bin
24
33
  COPY config config
@@ -30,18 +39,19 @@ COPY views views
30
39
  COPY workers workers
31
40
 
32
41
  # Copy required root level files
42
+ # NB: bin/emailengine.js requires ../encrypt and ../scan for the `encrypt` and `scan`
43
+ # subcommands. This COPY list is an allowlist, so any root-level module the CLI dispatches
44
+ # to must be named here or the command fails with MODULE_NOT_FOUND inside the container.
33
45
  COPY LICENSE_EMAILENGINE.txt LICENSE_EMAILENGINE.txt
34
- COPY package.json package.json
35
- COPY package-lock.json package-lock.json
46
+ COPY encrypt.js encrypt.js
36
47
  COPY sbom.json sbom.json
48
+ COPY scan.js scan.js
37
49
  COPY server.js server.js
38
50
 
39
51
  RUN mkdir -p .git/refs/heads
40
52
  COPY .git/refs/heads/master .git/refs/heads/master
41
53
 
42
54
  COPY update-info.sh update-info.sh
43
-
44
- RUN npm ci --omit=dev
45
55
  RUN chmod +x ./update-info.sh
46
56
  RUN ./update-info.sh
47
57
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-07-17T14:46:56.000000",
2
+ "creationTime": "2026-07-22T14:46:01.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const Joi = require('joi');
4
+ const Boom = require('@hapi/boom');
4
5
  const { redis } = require('../db');
5
6
  const { Account } = require('../account');
6
7
  const getSecret = require('../get-secret');
@@ -69,6 +70,18 @@ async function init(args) {
69
70
  });
70
71
 
71
72
  try {
73
+ // Nothing invalidates an access token once it is minted, so a token handed to an
74
+ // anonymous caller keeps working indefinitely. This route normally requires a real
75
+ // credential (`auth: {strategy: 'api-token', mode: 'required'}`) and a caller
76
+ // presenting one is trusted, but the `disableTokens` setting rewrites a
77
+ // credential-less request to `access_token=preauth` and the strategy accepts it,
78
+ // marking the credentials `{preauth: true}`. That anonymous caller must never mint a
79
+ // lasting token - whether or not an admin password happens to be set - so refuse it
80
+ // here (headless provisioning uses the CLI or EENGINE_PREPARED_TOKEN, not this route).
81
+ if (request.auth.credentials?.preauth) {
82
+ throw Boom.forbidden('Can not provision an access token for an unauthenticated request');
83
+ }
84
+
72
85
  // throws if account does not exist
73
86
  await accountObject.loadAccountData();
74
87
 
package/lib/consts.js CHANGED
@@ -147,6 +147,21 @@ module.exports = {
147
147
 
148
148
  MAX_BACKOFF_DELAY: 10 * 60 * 1000, // 10 min
149
149
 
150
+ // Phantom folder handling: a folder that is listed but repeatedly rejects
151
+ // SELECT (e.g. a Dovecot shared namespace root without \Noselect) is
152
+ // treated like \Noselect after this many consecutive failures instead of
153
+ // re-attempting the SELECT on every sync pass, and is re-probed after the
154
+ // interval passes or its STATUS counters change
155
+ PHANTOM_SELECT_FAIL_THRESHOLD: 3,
156
+ PHANTOM_REPROBE_INTERVAL: 6 * 3600 * 1000, // 6 hours
157
+
158
+ // A connection that survives this long has proven itself stable: an
159
+ // unexpected close after this age reconnects immediately and resets the
160
+ // close-triggered reconnection backoff. Closes of younger connections are
161
+ // throttled - a server that accepts the full connection setup and then
162
+ // drops the connection would otherwise cause an unthrottled login loop
163
+ STABLE_CONNECTION_TIME: 5 * 60 * 1000, // 5 min
164
+
150
165
  MAX_INLINE_ATTACHMENT_SIZE: 2 * 1024 * 1024,
151
166
 
152
167
  TOTP_WINDOW_SIZE: 6,
@@ -6,9 +6,12 @@
6
6
  // the BullMQ submit worker (workers/submit.js connects to Redis and expects a
7
7
  // worker-thread parentPort at require time).
8
8
 
9
- // Nodemailer/SMTP error codes that represent permanent failures. A message that
10
- // fails with one of these will fail again on every retry, so the job is
11
- // discarded instead of being retried.
9
+ // Nodemailer/SMTP error codes that represent permanent failures when the error does NOT also carry a
10
+ // transient (4xx) SMTP reply code. nodemailer stamps these on hard failures (bad credentials, a
11
+ // malformed envelope the server never even replied to, TLS/protocol mismatch) that recur on every
12
+ // retry, so the job is discarded instead of retried. Note that nodemailer also stamps
13
+ // EAUTH/EENVELOPE/EMESSAGE on *transient* 4xx replies (e.g. a "450 greylisted" RCPT TO), which is
14
+ // why isPermanentDeliveryError() consults the SMTP reply code BEFORE this set.
12
15
  const NON_RETRYABLE_CODES = new Set([
13
16
  'EAUTH', // authentication failed
14
17
  'ENOAUTH', // no credentials provided
@@ -22,13 +25,24 @@ const NON_RETRYABLE_CODES = new Set([
22
25
  /**
23
26
  * Determines whether a delivery error is permanent (must not be retried).
24
27
  *
25
- * An error is permanent when either:
26
- * - the SMTP status code is a 5xx other than 503 (503 is treated as a
27
- * transient "try again later" response), or
28
- * - the error carries one of the NON_RETRYABLE_CODES.
28
+ * The SMTP-reply rule is keyed on nodemailer's `responseCode`, NOT on `statusCode`. Only a real SMTP
29
+ * reply puts a code in `responseCode` (base-client.js copies it into `statusCode` for the API and
30
+ * webhook payloads, which is why the two look interchangeable and are not). Across the rest of the
31
+ * codebase a 5xx `statusCode` overwhelmingly means the opposite of a rejected message: 503 "no active
32
+ * handler", 504 inter-thread RPC timeouts, 500 Redis lock failures, and every API transport's
33
+ * passthrough of the provider's HTTP status. Reading that field as an SMTP verdict silently discarded
34
+ * queued mail that nothing was wrong with. `responseCode` is forwarded across the worker-thread RPC
35
+ * hop explicitly (see lib/worker-rpc-error.js) so this branch actually fires in production.
36
+ *
37
+ * When a real SMTP reply is present it decides on its own: per RFC 5321 a 4yz reply is a TRANSIENT
38
+ * negative completion ("try again later", e.g. greylisting) and only 5yz is permanent. nodemailer
39
+ * tags envelope/message/auth rejections with EENVELOPE/EMESSAGE/EAUTH regardless of the reply class,
40
+ * so the reply code has to be consulted BEFORE the code allowlist - otherwise a soft 4xx (or a 503)
41
+ * would be discarded as if it were a hard rejection. The code allowlist is the fallback for failures
42
+ * that carry no server reply at all (missing credentials, TLS/protocol mismatch).
29
43
  *
30
44
  * @param {Object} err - Error thrown during submission
31
- * @param {Number} [err.statusCode] - SMTP/HTTP status code
45
+ * @param {Number} [err.responseCode] - SMTP reply code, set by nodemailer on real SMTP failures
32
46
  * @param {String} [err.code] - Nodemailer error code
33
47
  * @returns {Boolean} True if the error should never be retried
34
48
  */
@@ -36,9 +50,18 @@ function isPermanentDeliveryError(err) {
36
50
  if (!err) {
37
51
  return false;
38
52
  }
39
- const isPermanentSmtp = err.statusCode >= 500 && err.statusCode !== 503;
40
- const isPermanentCode = NON_RETRYABLE_CODES.has(err.code);
41
- return isPermanentSmtp || isPermanentCode;
53
+
54
+ const smtpResponseCode = Number(err.responseCode);
55
+ if (smtpResponseCode) {
56
+ // A real SMTP reply decides on its own: 5xx is permanent, everything else (transient 4xx, or
57
+ // an unexpected 2xx/3xx) is retryable. 503 is carved out and left retryable on purpose -
58
+ // discarding a message the server might still accept loses mail, while retrying a genuinely
59
+ // permanent 503 only wastes a bounded number of attempts.
60
+ return smtpResponseCode >= 500 && smtpResponseCode !== 503;
61
+ }
62
+
63
+ // No SMTP reply at all: fall back to the nodemailer error code.
64
+ return NON_RETRYABLE_CODES.has(err.code);
42
65
  }
43
66
 
44
67
  /**
@@ -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
  /**