emailengine-app 2.86.0 → 2.87.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.
Files changed (74) hide show
  1. package/.ncurc.js +2 -4
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +42 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +5 -6
  6. package/README.md +4 -0
  7. package/bin/emailengine.js +2 -4
  8. package/bin/healthcheck.js +20 -0
  9. package/data/google-crawlers.json +1 -1
  10. package/data/public_suffix_list.dat +3 -7
  11. package/lib/account/auth-failure-backfill.js +3 -2
  12. package/lib/account/expected-identity.js +2 -2
  13. package/lib/account.js +101 -39
  14. package/lib/api-listener.js +40 -0
  15. package/lib/api-routes/account-routes.js +14 -7
  16. package/lib/api-routes/submit-routes.js +21 -2
  17. package/lib/api-token-auth.js +406 -0
  18. package/lib/autodetect-imap-settings.js +36 -3
  19. package/lib/consts.js +5 -0
  20. package/lib/email-client/base-client.js +27 -109
  21. package/lib/email-client/gmail-client.js +15 -4
  22. package/lib/email-client/imap/mailbox.js +97 -97
  23. package/lib/email-client/imap/sync-operations.js +13 -6
  24. package/lib/email-client/imap-client.js +28 -7
  25. package/lib/email-client/new-message-steps.js +162 -0
  26. package/lib/email-client/outlook-client.js +10 -2
  27. package/lib/env-setting-overrides.js +6 -2
  28. package/lib/export-worker.js +3 -2
  29. package/lib/export.js +43 -4
  30. package/lib/field-usage.js +1 -1
  31. package/lib/get-boolean.js +38 -0
  32. package/lib/get-raw-email.js +10 -1
  33. package/lib/health-probe.js +71 -0
  34. package/lib/imapproxy/imap-server.js +4 -55
  35. package/lib/net-tos-guard.js +42 -0
  36. package/lib/oauth/gmail.js +54 -29
  37. package/lib/oauth2-apps.js +2 -1
  38. package/lib/otp.js +66 -0
  39. package/lib/read-env-value.js +19 -7
  40. package/lib/redis-keys.js +19 -0
  41. package/lib/redis-operations.js +7 -3
  42. package/lib/schemas.js +62 -2
  43. package/lib/security-headers.js +18 -0
  44. package/lib/session-default.js +50 -0
  45. package/lib/settings.js +2 -1
  46. package/lib/stream-encrypt.js +71 -20
  47. package/lib/sub-script.js +8 -2
  48. package/lib/submit-lock.js +84 -0
  49. package/lib/submit-processor.js +283 -0
  50. package/lib/swagger-options.js +2 -2
  51. package/lib/templates.js +6 -3
  52. package/lib/tls/context.js +2 -16
  53. package/lib/tools.js +8 -30
  54. package/lib/utils/redis-errors.js +44 -0
  55. package/lib/webhook-delivery.js +3 -4
  56. package/lib/webhooks.js +5 -0
  57. package/lib/worker-rpc-error.js +10 -5
  58. package/lib/worker-rpc.js +138 -0
  59. package/package.json +25 -26
  60. package/sbom.json +660 -1736
  61. package/server.js +6 -5
  62. package/static/css/flyonui.css +2 -2
  63. package/static/js/ee-client.js +650 -196
  64. package/static/licenses.html +280 -1393
  65. package/translations/messages.pot +16 -16
  66. package/views/layout/app.hbs +9 -6
  67. package/views/legal.hbs +8 -0
  68. package/workers/api.js +51 -474
  69. package/workers/export.js +14 -55
  70. package/workers/imap-proxy.js +5 -18
  71. package/workers/imap.js +27 -49
  72. package/workers/smtp.js +7 -69
  73. package/workers/submit.js +21 -279
  74. package/workers/webhooks.js +7 -72
package/.ncurc.js CHANGED
@@ -53,7 +53,8 @@ module.exports = {
53
53
  // from the CommonJS rule); the Node requirement does, since the tooling has to
54
54
  // run on the Node 20 floor too.
55
55
  // undici - 8.x requires Node >=22.19 and crashes at require() on Node 20. Permanent while the
56
- // Node 20 floor above stands.
56
+ // Node 20 floor above stands. lib/net-tos-guard.js covers a 7.x crash 8.x fixed
57
+ // itself (unguarded setTypeOfService); remove it with the upgrade.
57
58
  // marked - 16.x dropped the CommonJS build (ESM-only, needs require(esm)/Node >=20.19); 15.x is the
58
59
  // last require()-compatible line. 15.0.12 verified on Node 20-24 and in a yao/pkg node24 build.
59
60
  // Permanent: an ESM-only release cannot be bundled by pkg, whatever the Node floor.
@@ -91,9 +92,6 @@ module.exports = {
91
92
  // bump still needs a look at the generated document: test/openapi-golden-test.js fails if joi's
92
93
  // describe() output changes shape.
93
94
  reject: [
94
- // @asamuzakjp/css-color >=4.1.2 pulls in @csstools/* v4 which are pure ESM and break pkg bundling
95
- // (transitive via @postalsys/email-text-tools -> jsdom -> cssstyle; also pinned in package.json "overrides").
96
- '@asamuzakjp/css-color'
97
95
  // Not a direct dependency, so nothing here moves it: the "overrides" entry in package.json
98
96
  // lifts cheerio from the 1.0.0 that juice 11 (via @postalsys/email-text-tools) pins exactly,
99
97
  // which drags in a second copy of undici (6.x) next to ours. cheerio 1.2.0 shares our undici
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.86.0"
2
+ ".": "2.87.1"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.87.1](https://github.com/postalsys/emailengine/compare/v2.87.0...v2.87.1) (2026-11-05)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * bind export encryption chunks to their position in the file ([c138b61](https://github.com/postalsys/emailengine/commit/c138b6145ad0dab33b92d8d5f1571ffd32fc96c3))
9
+ * export recovery ownership and sent-marker durability (2.87.1 review) ([5c24113](https://github.com/postalsys/emailengine/commit/5c2411311ee1652ed4580fd53d40f0fdc81bd7f4))
10
+ * keep the sent marker until the submit job is recorded as completed ([aecf19f](https://github.com/postalsys/emailengine/commit/aecf19f6ac7a431f87441102e3302228ab1728ad))
11
+ * make the Docker health check follow the API's TLS setting, port and bind address ([957dec0](https://github.com/postalsys/emailengine/commit/957dec0923ab359355761bd531d6d08003a3dd05))
12
+ * never fail an export another export worker is still running ([74d1755](https://github.com/postalsys/emailengine/commit/74d1755aa2fec63565bae64fcad55153e5294c5d))
13
+ * read the TLS mode from <Encryption> in Exchange autodiscover answers ([5a1b7e9](https://github.com/postalsys/emailengine/commit/5a1b7e9e3df33a38b65b80447e6628a8e908223e))
14
+ * report a template id with an out-of-range timestamp as not found ([ac043db](https://github.com/postalsys/emailengine/commit/ac043db8d1540a025d8143d1d261cf3d2f1400cb))
15
+ * set text.hasMore when an IMAP text part is cut at maxBytes ([f070b5e](https://github.com/postalsys/emailengine/commit/f070b5ea91ad3763936c975a302a23d20d768e69))
16
+ * share the worker RPC, token check and new-message steps instead of copies ([ac4cf28](https://github.com/postalsys/emailengine/commit/ac4cf28ae3925bcf4a01373f3c05d51a5c4da8f3))
17
+ * standalone fixes for new-folder ids, Redis-refused work, duplicate sends, CLI password and queued exports ([#685](https://github.com/postalsys/emailengine/issues/685)) ([8e934c0](https://github.com/postalsys/emailengine/commit/8e934c0cf9cda2e33cfbdb7a42cfe2a77172523d))
18
+ * update dependencies ([56df020](https://github.com/postalsys/emailengine/commit/56df02073fb6a76e984531710fd97fee0163e58b))
19
+ * update dependencies ([25ee28f](https://github.com/postalsys/emailengine/commit/25ee28fc5bd5623c4b73b55e0890c027832825cf))
20
+ * update dependencies (bullmq 6.5.4, fast-xml-parser 5.12.0) ([5624ee1](https://github.com/postalsys/emailengine/commit/5624ee1844c6ed2f377bbbe7161f21f035d7c943))
21
+
22
+ ## [2.87.0](https://github.com/postalsys/emailengine/compare/v2.86.0...v2.87.0) (2026-10-29)
23
+
24
+
25
+ ### Features
26
+
27
+ * send and read one-time passcodes through the OTP-Token header ([ad2f388](https://github.com/postalsys/emailengine/commit/ad2f388e7fb5532bbd581f5c37c0f5c65525cc96))
28
+
29
+
30
+ ### Bug Fixes
31
+
32
+ * bump bullmq to 6.5.0 and @sentry/node-core to 10.77.1 ([250ec90](https://github.com/postalsys/emailengine/commit/250ec9060e1c392977961f6617e884071e426f86))
33
+ * bump nodemailer to 10.3.0, mailparser to 3.13.0 and other dependencies ([ad88bc7](https://github.com/postalsys/emailengine/commit/ad88bc79f5f1c4958ffb3012b09ce7f7f533824b))
34
+ * let the AI summary trust Google's authentication header on Gmail API accounts ([78038c5](https://github.com/postalsys/emailengine/commit/78038c5d7828050fd1c94af8d268e7c50081d8df))
35
+ * move the Docker image to Node 24.22.2 for the Brotli decoder fix (CVE-2026-111497) ([b6efd8e](https://github.com/postalsys/emailengine/commit/b6efd8e4dc81199cf427185c17e0ffb0933f08be))
36
+ * point support links at emailengine.app/support and support@postalsys.com ([795b217](https://github.com/postalsys/emailengine/commit/795b217458cf379699f68e333935ae8066310c1b))
37
+ * report the OAuth2 revocation outcome on account delete, and add revoke=required ([cc5908d](https://github.com/postalsys/emailengine/commit/cc5908de9e286ade29e1ad50a835d81f144c827c))
38
+ * separate the admin footer links into a labelled link list ([65aa96d](https://github.com/postalsys/emailengine/commit/65aa96d1b4ca540b670ae5c11ca441afa09b67e7))
39
+ * update @postalsys/certs to 2.0.3 and smtp-server to 3.21.2 ([d4a1946](https://github.com/postalsys/emailengine/commit/d4a194607a083a47fcc7b9ca772fa52c5d0b67d6))
40
+ * update bullmq to 6.4.2 ([4af5825](https://github.com/postalsys/emailengine/commit/4af582514507306dd7b677ad7d3ca4fe3f557e1c))
41
+ * update ee-client to 1.10.0 ([6595d46](https://github.com/postalsys/emailengine/commit/6595d46f23dd7cfd7e388641f763d1310c6a3883))
42
+ * update imapflow to 2.10.0 ([06928a5](https://github.com/postalsys/emailengine/commit/06928a507fb52696ecae1204e0641a24b43f9359))
43
+ * update nodemailer to 10.3.1, mailparser to 3.14.1, ee-client to 1.9.0 and email-ai-tools to 2.4.0 ([8aeafb4](https://github.com/postalsys/emailengine/commit/8aeafb498f663fc749e13da7f1f497a7d577b9ba))
44
+
3
45
  ## [2.86.0](https://github.com/postalsys/emailengine/compare/v2.85.0...v2.86.0) (2026-10-22)
4
46
 
5
47
 
@@ -492,6 +492,7 @@ docker-compose restart
492
492
 
493
493
  ## Support
494
494
 
495
+ - Support: https://emailengine.app/support or support@postalsys.com
495
496
  - Documentation: https://learn.emailengine.app/
496
497
  - API Reference: https://learn.emailengine.app/docs/api/emailengine-api
497
- - Issues: https://github.com/postalsys/emailengine/issues
498
+ - Bug reports: https://github.com/postalsys/emailengine/issues
package/Dockerfile CHANGED
@@ -11,7 +11,7 @@
11
11
  # here; the runtime stage below copies out only the finished tree, so npm and its dependencies never
12
12
  # reach the published image. npm accounted for 38 of the 59 HIGH/CRITICAL findings in the old image
13
13
  # (a vendored tar, pacote, sigstore, minimatch) and nothing at runtime ever invokes it.
14
- FROM node:24-alpine@sha256:44fce696f38ba8c987c4db89954051000bbd05ffd8d8659ba15ed4a8602e937f AS builder
14
+ FROM node:24-alpine@sha256:8a32c8cf649a49915a66e81e7a609223c708d0adabf288ee3f4077d765542f85 AS builder
15
15
 
16
16
  ARG BUILDPLATFORM
17
17
  ARG TARGETPLATFORM
@@ -74,7 +74,7 @@ RUN : "${EE_COMMIT_HASH:?EE_COMMIT_HASH build arg is required, e.g. --build-arg
74
74
  && rm -f update-info.sh
75
75
 
76
76
  # Runtime stage.
77
- FROM node:24-alpine@sha256:44fce696f38ba8c987c4db89954051000bbd05ffd8d8659ba15ed4a8602e937f
77
+ FROM node:24-alpine@sha256:8a32c8cf649a49915a66e81e7a609223c708d0adabf288ee3f4077d765542f85
78
78
 
79
79
  # `apk upgrade` patches the Alpine packages that the base image itself lags on - at the time of
80
80
  # writing node:24-alpine still carries an openssl below 3.5.8-r0. dumb-init reaps zombies as PID 1.
@@ -114,11 +114,10 @@ EXPOSE 3000
114
114
 
115
115
  # The liveness check: answers while the process can serve HTTP, without waiting on Redis or the
116
116
  # workers, so an orchestrator restarts the container only when restarting can help. Readiness
117
- # (workers and Redis) is /health/ready, for whatever routes traffic to it. 127.0.0.1 rather than
118
- # localhost for the reason docker-compose.yml gives: BusyBox wget on musl tries ::1 only, and
119
- # EmailEngine listens on IPv4. Shell form so a changed EENGINE_PORT (or PORT) is followed.
117
+ # (workers and Redis) is /health/ready, for whatever routes traffic to it. A Node script rather than
118
+ # wget so the probe follows the API's own port, bind address and TLS switch (lib/health-probe.js).
120
119
  HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
121
- CMD wget --no-verbose --tries=1 --spider "http://127.0.0.1:${EENGINE_PORT:-${PORT:-3000}}/health/live" || exit 1
120
+ CMD ["node", "/emailengine/bin/healthcheck.js"]
122
121
 
123
122
  ENTRYPOINT ["/usr/bin/dumb-init", "--"]
124
123
  CMD ["node", "/emailengine/server.js"]
package/README.md CHANGED
@@ -169,6 +169,10 @@ To log raw IMAP traffic for every account instead, start EmailEngine with `--log
169
169
 
170
170
  For detailed security and data compliance information, refer to [this guide](https://learn.emailengine.app/docs/deployment/compliance).
171
171
 
172
+ ## Support
173
+
174
+ See [emailengine.app/support](https://emailengine.app/support) for support options, or email [support@postalsys.com](mailto:support@postalsys.com). GitHub issues are for reproducible bugs only and are not actively monitored.
175
+
172
176
  ## Licensing
173
177
 
174
178
  EmailEngine is licensed under the commercial [EmailEngine License](./LICENSE_EMAILENGINE.txt).
@@ -412,10 +412,8 @@ function runPassword() {
412
412
  let returnValue = argv.hash || argv.r ? Buffer.from(res.passwordHash).toString('base64url') : res.password;
413
413
  process.stdout.write(returnValue);
414
414
  // The password is stored, and every existing session is ended by the
415
- // version bump; the login requirement itself is installed by each API
416
- // worker at startup, so an instance that was running without a password
417
- // keeps serving the admin pages without one until it is restarted
418
- process.stderr.write('\nRestart running EmailEngine instances for the new password to take effect\n');
415
+ // version bump; a running instance that had no password asks for a login
416
+ // from its next admin request on (lib/session-default.js)
419
417
  return process.exit(0);
420
418
  })
421
419
  .catch(err => {
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // The Docker image's HEALTHCHECK: exits 0 when the API answers /health/live, 1 otherwise. See
5
+ // lib/health-probe.js.
6
+
7
+ // Resolve `.env` and `config/` against the application root, in the same order as server.js
8
+ process.chdir(require('path').join(__dirname, '..'));
9
+ require('dotenv').config({ quiet: true });
10
+
11
+ const config = require('@zone-eu/wild-config');
12
+ const { probeTarget, probe } = require('../lib/health-probe');
13
+
14
+ const target = probeTarget(config.api || {});
15
+
16
+ probe(target).then(result => {
17
+ const url = `${target.protocol}://${target.host}:${target.port}`;
18
+ process.stdout.write(result.ok ? `${url} is live\n` : `${url} is not live: ${result.error || `HTTP ${result.statusCode}`}\n`);
19
+ process.exit(result.ok ? 0 : 1);
20
+ });
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-10-22T14:46:14.000000",
2
+ "creationTime": "2026-11-04T15:46:00.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
@@ -5,8 +5,8 @@
5
5
  // Please pull this list from, and only from https://publicsuffix.org/list/public_suffix_list.dat,
6
6
  // rather than any other VCS sites. Pulling from any other URL is not guaranteed to be supported.
7
7
 
8
- // VERSION: 2026-10-22_08-36-41_UTC
9
- // COMMIT: 8437e5262f13305f94087abe699b4fe2be1d1de8
8
+ // VERSION: 2026-10-31_14-17-28_UTC
9
+ // COMMIT: 73f8cc701c084fe07d888ec552b2f0b53281a674
10
10
 
11
11
  // Instructions on pulling and using this list can be found at https://publicsuffix.org/list/.
12
12
 
@@ -6812,7 +6812,7 @@ org.zw
6812
6812
 
6813
6813
  // newGTLDs
6814
6814
 
6815
- // List of new gTLDs imported from https://www.icann.org/resources/registries/gtlds/v2/gtlds.json on 2026-10-16T18:37:24Z
6815
+ // List of new gTLDs imported from https://www.icann.org/resources/registries/gtlds/v2/gtlds.json on 2026-10-30T19:51:02Z
6816
6816
  // This list is auto-generated, don't edit it manually.
6817
6817
  // aaa : American Automobile Association, Inc.
6818
6818
  // https://www.iana.org/domains/root/db/aaa.html
@@ -8498,10 +8498,6 @@ healthcare
8498
8498
  // https://www.iana.org/domains/root/db/help.html
8499
8499
  help
8500
8500
 
8501
- // helsinki : City of Helsinki
8502
- // https://www.iana.org/domains/root/db/helsinki.html
8503
- helsinki
8504
-
8505
8501
  // here : Charleston Road Registry Inc.
8506
8502
  // https://www.iana.org/domains/root/db/here.html
8507
8503
  here
@@ -39,6 +39,7 @@
39
39
  // rolling upgrade, would leave a second batch that the key then hides; re-arming means deleting
40
40
  // BACKFILL_KEY and restarting.
41
41
 
42
+ const { accountDataKey } = require('../redis-keys');
42
43
  const { redis } = require('../db');
43
44
  const logger = require('../logger');
44
45
  const { parseImapData } = require('./imap-data');
@@ -130,7 +131,7 @@ async function backfillAuthFailureDisabled(opts = {}) {
130
131
 
131
132
  const readReq = client.pipeline();
132
133
  for (const account of chunk) {
133
- readReq.hmget(`${REDIS_PREFIX}iad:${account}`, ...SCAN_FIELDS);
134
+ readReq.hmget(accountDataKey(account), ...SCAN_FIELDS);
134
135
  }
135
136
  const rows = await readReq.exec();
136
137
 
@@ -142,7 +143,7 @@ async function backfillAuthFailureDisabled(opts = {}) {
142
143
  // hSetExists rather than hset, for the same reason the safety net writes it that way: an
143
144
  // account deleted between the read above and this write must not come back as a hash
144
145
  // holding nothing but a marker.
145
- writeReq.hSetExists(`${REDIS_PREFIX}iad:${chunk[j]}`, AUTH_FAILURE_DISABLED_FIELD, stamp);
146
+ writeReq.hSetExists(accountDataKey(chunk[j]), AUTH_FAILURE_DISABLED_FIELD, stamp);
146
147
  queued++;
147
148
  }
148
149
  }
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const { REDIS_PREFIX } = require('../consts');
3
+ const { accountDataKey } = require('../redis-keys');
4
4
 
5
5
  // An account can carry an expected identity: the address that must own it, set by an authenticated API
6
6
  // caller through `expectedEmail` on POST /v1/authentication/form, POST /v1/account or
@@ -82,7 +82,7 @@ async function resolveExpectedIdentity(redis, opts) {
82
82
  return null;
83
83
  }
84
84
 
85
- return normalizeEmail(await redis.hget(`${REDIS_PREFIX}iad:${account}`, 'expectedEmail')) || null;
85
+ return normalizeEmail(await redis.hget(accountDataKey(account), 'expectedEmail')) || null;
86
86
  }
87
87
 
88
88
  module.exports = { normalizeEmail, matchesExpectedIdentity, pendingSetupExpectation, resolveExpectedIdentity };
package/lib/account.js CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { accountDataKey } = require('./redis-keys');
3
4
  const logger = require('./logger');
4
5
  const Boom = require('@hapi/boom');
5
6
  const msgpack = require('./msgpack');
@@ -54,6 +55,25 @@ const ACCOUNT_UPDATE_LOCK_WAIT = 5 * 1000;
54
55
  // re-encrypts exactly this list.
55
56
  const ENCRYPTED_ACCOUNT_FIELDS = ['webhooks', 'webhooksCustomHeaders', 'proxy'];
56
57
 
58
+ // Revocation outcomes that leave no grant EmailEngine could revoke, so revoke: 'required' lets the
59
+ // deletion go ahead: not an OAuth2 account, a Workspace service account, or a token the provider
60
+ // already considers revoked or expired
61
+ const NO_GRANT_REASONS = new Set(['NotOAuth2', 'ServiceAccount', 'TokenInvalid']);
62
+
63
+ function grantRemains(revocation) {
64
+ return !revocation.revoked && !NO_GRANT_REASONS.has(revocation.reason);
65
+ }
66
+
67
+ // The error a deletion with revoke: 'required' fails with. 502 when the provider was asked and did
68
+ // not confirm, which a retry can fix; 409 when there was nothing it could be asked with
69
+ function revocationNotConfirmed(revocation) {
70
+ let err = new Error('The OAuth2 grant was not revoked, so the account was not deleted');
71
+ err.code = 'RevocationNotConfirmed';
72
+ err.statusCode = revocation.attempted ? 502 : 409;
73
+ err.info = { revocation };
74
+ return err;
75
+ }
76
+
57
77
  /**
58
78
  * The encrypted credential fields of an unserialized account, as [holder, key] pairs: a credential
59
79
  * is under `auth` when the configuration has one, otherwise on the configuration itself
@@ -349,7 +369,7 @@ class Account {
349
369
  let delegatedAccount = await resolveDelegatedAccount(this.redis, accountData.account);
350
370
  if (delegatedAccount) {
351
371
  accountData.delegatedAccount = delegatedAccount;
352
- let delegatedAccountRow = await this.redis.hgetall(`${REDIS_PREFIX}iad:${delegatedAccount}`);
372
+ let delegatedAccountRow = await this.redis.hgetall(accountDataKey(delegatedAccount));
353
373
  let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow, { skipDecrypt: true });
354
374
  if (delegatedAccountData.oauth2 && delegatedAccountData.oauth2.provider) {
355
375
  let app;
@@ -424,7 +444,7 @@ class Account {
424
444
  }
425
445
 
426
446
  getAccountKey() {
427
- return `${REDIS_PREFIX}iad:${this.account}`;
447
+ return accountDataKey(this.account);
428
448
  }
429
449
 
430
450
  getMailboxListKey() {
@@ -1005,7 +1025,7 @@ class Account {
1005
1025
  let delegatedAccount = await resolveDelegatedAccount(this.redis, accountData.account);
1006
1026
  if (delegatedAccount) {
1007
1027
  accountData.delegatedAccount = delegatedAccount;
1008
- let delegatedAccountRow = await this.redis.hgetall(`${REDIS_PREFIX}iad:${delegatedAccount}`);
1028
+ let delegatedAccountRow = await this.redis.hgetall(accountDataKey(delegatedAccount));
1009
1029
  let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow, { skipDecrypt: true });
1010
1030
  if (delegatedAccountData.oauth2 && delegatedAccountData.oauth2.provider) {
1011
1031
  let app = await oauth2Apps.get(delegatedAccountData.oauth2.provider);
@@ -1377,7 +1397,7 @@ class Account {
1377
1397
  let retries = 0;
1378
1398
  while (retries++ < 20) {
1379
1399
  id = randomId();
1380
- let alreadyExists = await this.redis.hexists(`${REDIS_PREFIX}iad:${id}`, 'account');
1400
+ let alreadyExists = await this.redis.hexists(accountDataKey(id), 'account');
1381
1401
  if (alreadyExists) {
1382
1402
  id = false;
1383
1403
  } else {
@@ -1703,32 +1723,33 @@ class Account {
1703
1723
 
1704
1724
  let accountData = await this.loadAccountData(this.account);
1705
1725
 
1726
+ // revoke: 'required' keeps the account unless the grant is gone. A grant that cannot even be
1727
+ // attempted is refused before anything is torn down
1728
+ let required = opts.revoke === 'required';
1729
+ let grant = opts.revoke ? await this.findRevocableGrant(accountData) : null;
1730
+ let revocation = grant?.reason ? { attempted: false, revoked: false, reason: grant.reason } : undefined;
1731
+ if (required && revocation && grantRemains(revocation)) {
1732
+ throw revocationNotConfirmed(revocation);
1733
+ }
1734
+
1706
1735
  // First, while the record and its token still exist: the worker's own teardown after the
1707
1736
  // unlink below has no token left, so the Graph subscription and the Gmail watch used to
1708
1737
  // outlive the account. Ahead of the revoke for the same reason
1709
1738
  await this.releaseRemoteResources();
1710
1739
 
1711
- if (opts.revoke && accountData.oauth2?.provider) {
1712
- // Prefer refresh token over access token: revoking either invalidates the grant per Google's docs,
1713
- // but the stored access token may be expired (a 400 from the provider would leave the grant intact),
1714
- // while the refresh token is long-lived. Skip gmailService - Workspace service accounts have no
1715
- // per-user grant to revoke.
1716
- let token = accountData.oauth2.refreshToken || accountData.oauth2.accessToken;
1717
- if (token) {
1718
- try {
1719
- let oauth2App = await oauth2Apps.get(accountData.oauth2.provider);
1720
- if (oauth2App && oauth2App.provider !== 'gmailService') {
1721
- let oauthClient = await oauth2Apps.getClient(accountData.oauth2.provider, {
1722
- logger: this.logger,
1723
- route: await this.getHttpRoute(accountData)
1724
- });
1725
- if (oauthClient && typeof oauthClient.revokeToken === 'function') {
1726
- await oauthClient.revokeToken(token);
1727
- }
1728
- }
1729
- } catch (err) {
1730
- this.logger.warn({ msg: 'Failed to revoke OAuth2 grant before account delete', account: this.account, err });
1731
- }
1740
+ if (grant) {
1741
+ if (!revocation) {
1742
+ revocation = Object.assign({ attempted: true }, await grant.client.revokeToken(grant.token));
1743
+ }
1744
+
1745
+ this.logger[revocation.revoked ? 'info' : 'warn']({ msg: 'OAuth2 grant revocation before account delete', account: this.account, revocation });
1746
+
1747
+ if (required && grantRemains(revocation)) {
1748
+ // The teardown above stopped the Gmail watch of an account that now stays. A
1749
+ // reconnect sets it up again; not awaited, the refusal does not depend on it and
1750
+ // notifyWorker() logs its own failure
1751
+ this.notifyWorker('reconnect');
1752
+ throw revocationNotConfirmed(revocation);
1732
1753
  }
1733
1754
  }
1734
1755
 
@@ -1801,19 +1822,60 @@ class Account {
1801
1822
  this.logger.error({ msg: 'Failed to delete the log keys of a deleted account', account: this.account, err });
1802
1823
  }
1803
1824
 
1804
- if (!result || !result[1] || !result[1][1]) {
1805
- return {
1806
- account: this.account,
1807
- deleted: false
1808
- };
1825
+ let deleted = !!(result && result[1] && result[1][1]);
1826
+ if (deleted) {
1827
+ await this.notifyWorker('delete');
1809
1828
  }
1810
1829
 
1811
- await this.notifyWorker('delete');
1830
+ let response = { account: this.account, deleted };
1831
+ if (revocation) {
1832
+ // Only when revoke was requested, so a plain delete answers exactly as it always has
1833
+ response.revocation = revocation;
1834
+ }
1835
+ return response;
1836
+ }
1812
1837
 
1813
- return {
1814
- account: this.account,
1815
- deleted: true
1816
- };
1838
+ /**
1839
+ * Finds the grant a deletion with `revoke` should revoke.
1840
+ *
1841
+ * @returns {Promise<{client: Object, token: string}|{reason: string}>} The client and token to
1842
+ * revoke with, or the reason there is nothing EmailEngine can revoke
1843
+ */
1844
+ async findRevocableGrant(accountData) {
1845
+ if (!accountData.oauth2?.provider) {
1846
+ return { reason: 'NotOAuth2' };
1847
+ }
1848
+
1849
+ // Prefer refresh token over access token: revoking either invalidates the grant per Google's docs,
1850
+ // but the stored access token may be expired (a 400 from the provider would leave the grant intact),
1851
+ // while the refresh token is long-lived.
1852
+ let token = accountData.oauth2.refreshToken || accountData.oauth2.accessToken;
1853
+ if (!token) {
1854
+ return { reason: 'NoToken' };
1855
+ }
1856
+
1857
+ try {
1858
+ let oauth2App = await oauth2Apps.get(accountData.oauth2.provider);
1859
+ if (!oauth2App) {
1860
+ return { reason: 'AppNotFound' };
1861
+ }
1862
+ // Workspace service accounts have no per-user grant to revoke
1863
+ if (oauth2App.provider === 'gmailService') {
1864
+ return { reason: 'ServiceAccount' };
1865
+ }
1866
+ let client = await oauth2Apps.getClient(accountData.oauth2.provider, {
1867
+ logger: this.logger,
1868
+ route: await this.getHttpRoute(accountData)
1869
+ });
1870
+ // Only GmailOauth implements it. Microsoft offers no endpoint that revokes one grant
1871
+ if (typeof client?.revokeToken !== 'function') {
1872
+ return { reason: 'Unsupported' };
1873
+ }
1874
+ return { client, token };
1875
+ } catch (err) {
1876
+ this.logger.warn({ msg: 'Failed to load the OAuth2 application to revoke a grant', account: this.account, err });
1877
+ return { reason: 'AppError' };
1878
+ }
1817
1879
  }
1818
1880
 
1819
1881
  // Creates the consumer side of a cross-thread download stream, with a guard listener:
@@ -2741,7 +2803,7 @@ class Account {
2741
2803
  let delegatedAccount = await resolveDelegatedAccount(this.redis, accountData.account);
2742
2804
  if (delegatedAccount) {
2743
2805
  accountData.delegatedAccount = delegatedAccount;
2744
- let delegatedAccountRow = await this.redis.hgetall(`${REDIS_PREFIX}iad:${delegatedAccount}`);
2806
+ let delegatedAccountRow = await this.redis.hgetall(accountDataKey(delegatedAccount));
2745
2807
  let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow, { skipDecrypt: true });
2746
2808
  if (delegatedAccountData?.oauth2?.provider) {
2747
2809
  let app = await oauth2Apps.get(delegatedAccountData.oauth2.provider);
@@ -2950,7 +3012,7 @@ const DEFERRED_CHANGE_BATCH = 100;
2950
3012
  // the mandatory marker field of the account hash (the same idiom the notify worker and
2951
3013
  // genId() rely on), so its presence is the canonical "this account exists" signal.
2952
3014
  async function accountExists(redis, account) {
2953
- return (await redis.hexists(`${REDIS_PREFIX}iad:${account}`, 'account')) === 1;
3015
+ return (await redis.hexists(accountDataKey(account), 'account')) === 1;
2954
3016
  }
2955
3017
 
2956
3018
  /**
@@ -2970,7 +3032,7 @@ async function accountsExist(redis, accounts) {
2970
3032
 
2971
3033
  let pipeline = redis.pipeline();
2972
3034
  for (let account of accounts) {
2973
- pipeline = pipeline.hexists(`${REDIS_PREFIX}iad:${account}`, 'account');
3035
+ pipeline = pipeline.hexists(accountDataKey(account), 'account');
2974
3036
  }
2975
3037
 
2976
3038
  // A pipeline reports a per-command failure in its results rather than rejecting, and
@@ -2999,7 +3061,7 @@ async function accountSummary(redis, account) {
2999
3061
  }
3000
3062
 
3001
3063
  // `account` is the existence marker (see accountExists); the rest are optional on a record
3002
- let [exists, name, email, state] = await redis.hmget(`${REDIS_PREFIX}iad:${account}`, 'account', 'name', 'email', 'state');
3064
+ let [exists, name, email, state] = await redis.hmget(accountDataKey(account), 'account', 'name', 'email', 'state');
3003
3065
  if (!exists) {
3004
3066
  return null;
3005
3067
  }
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+
3
+ // Where and how the API listens, resolved from the environment and the config file. One copy for
4
+ // every process that needs the answer: the main thread and the API worker build the listener from
5
+ // it, the certificate reconciler asks whether it serves TLS, and the Docker health check
6
+ // (lib/health-probe.js) probes it. Kept to leaf modules so the health check can load it without
7
+ // reaching Redis, which lib/tools.js and lib/settings.js do as they load.
8
+
9
+ const config = require('@zone-eu/wild-config');
10
+ const { readEnvValue, hasEnvValue } = require('./read-env-value');
11
+ const { getBoolean } = require('./get-boolean');
12
+
13
+ /**
14
+ * @param {Object} [api] - The `[api]` section of the configuration
15
+ * @returns {number|undefined} EENGINE_PORT, then PORT, then `[api] port`
16
+ */
17
+ function apiPort(api = config.api || {}) {
18
+ return (hasEnvValue('EENGINE_PORT') && Number(readEnvValue('EENGINE_PORT'))) || (hasEnvValue('PORT') && Number(readEnvValue('PORT'))) || api.port;
19
+ }
20
+
21
+ /**
22
+ * @param {Object} [api] - The `[api]` section of the configuration
23
+ * @returns {string|undefined} EENGINE_HOST, then `[api] host`
24
+ */
25
+ function apiHost(api = config.api || {}) {
26
+ return readEnvValue('EENGINE_HOST') || api.host;
27
+ }
28
+
29
+ /**
30
+ * Whether, and how, the API listener serves TLS: EENGINE_API_TLS and `[api.tls]`.
31
+ *
32
+ * @param {Object} [api] - The `[api]` section of the configuration
33
+ * @returns {Object|false} The `[api.tls]` options to build the listener from, or false when the
34
+ * API serves plain HTTP
35
+ */
36
+ function apiTlsConfig(api = config.api || {}) {
37
+ return hasEnvValue('EENGINE_API_TLS') ? getBoolean(readEnvValue('EENGINE_API_TLS')) && (api.tls || {}) : api.tls || false;
38
+ }
39
+
40
+ module.exports = { apiPort, apiHost, apiTlsConfig };
@@ -43,7 +43,8 @@ const {
43
43
  apiBoolean,
44
44
  mailboxAddressSchema,
45
45
  accountProxySchema,
46
- verifyResultSchema
46
+ verifyResultSchema,
47
+ accountRevocationSchema
47
48
  } = require('../schemas');
48
49
 
49
50
  const { REDIS_PREFIX, MAX_FORM_TTL, NONCE_BYTES, MCP_MAX_PAGE_SIZE, OUTLOOK_SYNC_MAX_LOOKBACK } = require('../consts');
@@ -850,7 +851,9 @@ function registerDeleteAccount(server, args) {
850
851
  account: request.params.account,
851
852
  call,
852
853
  secret: await getSecret(),
853
- timeout: request.headers['x-ee-timeout']
854
+ timeout: request.headers['x-ee-timeout'],
855
+ // The revocation outcome is logged with this request's id and token
856
+ logger: request.logger
854
857
  });
855
858
 
856
859
  try {
@@ -862,7 +865,7 @@ function registerDeleteAccount(server, args) {
862
865
  options: {
863
866
  description: 'Remove account',
864
867
  notes: [
865
- "Stop processing and clear the account's cache. Pass revoke=true to also attempt revocation of the upstream OAuth2 grant at the provider before the account is removed.",
868
+ "Stop processing and clear the account's cache. Pass revoke=true to also attempt revocation of the upstream OAuth2 grant at the provider before the account is removed; the response then reports the outcome under `revocation`. Pass revoke=required to delete the account only when the grant is gone: when the provider does not confirm the revocation the request fails with code RevocationNotConfirmed (502 when the provider was asked, 409 when it could not be) and the account and its credentials are kept, so the request can be retried.",
866
869
  BEHAVIOR.DELETION_SCOPE
867
870
  ],
868
871
 
@@ -873,7 +876,7 @@ function registerDeleteAccount(server, args) {
873
876
  name: 'delete_account',
874
877
  title: 'Delete account',
875
878
  description:
876
- 'Remove an account from this instance, with its synced index and the tokens bound to it. The mailbox at the provider is untouched. Set revoke to true to also revoke the OAuth2 grant at the provider. Confirm with the user before calling this.'
879
+ 'Remove an account from this instance, with its synced index and the tokens bound to it. The mailbox at the provider is untouched. Set revoke to true to also revoke the OAuth2 grant at the provider, or to "required" to keep the account unless the provider confirms the revocation. Confirm with the user before calling this.'
877
880
  },
878
881
  openapi: {
879
882
  'x-ee-impact': IMPACT.DESTRUCTIVE,
@@ -909,9 +912,12 @@ function registerDeleteAccount(server, args) {
909
912
  }),
910
913
 
911
914
  query: Joi.object({
912
- revoke: apiBoolean()
915
+ revoke: Joi.alternatives()
916
+ .try(apiBoolean(), Joi.string().valid('required'))
913
917
  .default(false)
914
- .description('Revoke the upstream OAuth2 grant at the provider before deleting the account')
918
+ .description(
919
+ 'Revoke the upstream OAuth2 grant at the provider before deleting the account. `true` deletes the account whatever the outcome, `required` keeps it unless the grant is gone'
920
+ )
915
921
  .meta({ usage: FIELD_USAGE.revokeGrant })
916
922
  })
917
923
  },
@@ -919,7 +925,8 @@ function registerDeleteAccount(server, args) {
919
925
  response: {
920
926
  schema: Joi.object({
921
927
  account: accountIdSchema.required(),
922
- deleted: apiBoolean().default(true).description('Was the account deleted')
928
+ deleted: apiBoolean().default(true).description('Was the account deleted'),
929
+ revocation: accountRevocationSchema
923
930
  }).label('DeleteAccountResponse'),
924
931
  failAction: 'log'
925
932
  }