emailengine-app 2.77.0 → 2.78.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 (94) hide show
  1. package/.github/workflows/test.yml +80 -0
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +31 -0
  4. package/bin/emailengine.js +1 -1
  5. package/data/google-crawlers.json +1 -1
  6. package/encrypt.js +1 -1
  7. package/lib/account/expected-identity.js +88 -0
  8. package/lib/account.js +75 -26
  9. package/lib/api-reference/format.js +14 -0
  10. package/lib/api-reference/index.js +24 -7
  11. package/lib/api-reference/model.js +4 -2
  12. package/lib/api-routes/account-routes.js +19 -2
  13. package/lib/api-routes/behavior-notes.js +3 -0
  14. package/lib/append-list.js +3 -14
  15. package/lib/arf-detect.js +23 -1
  16. package/lib/autodetect-imap-settings.js +40 -16
  17. package/lib/base32.js +30 -0
  18. package/lib/bounce-detect.js +182 -62
  19. package/lib/egress-filter.js +89 -8
  20. package/lib/email-client/base-client.js +8 -72
  21. package/lib/email-client/gmail-client.js +3 -3
  22. package/lib/email-client/imap/listing-diff.js +3 -3
  23. package/lib/email-client/imap/mailbox.js +5 -69
  24. package/lib/email-client/imap-client.js +3 -2
  25. package/lib/email-client/message-builder.js +13 -13
  26. package/lib/email-client/outlook-client.js +1 -1
  27. package/lib/export.js +1 -1
  28. package/lib/gateway.js +1 -1
  29. package/lib/get-raw-email.js +1 -1
  30. package/lib/imapproxy/imap-core/lib/imap-connection.js +2 -2
  31. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  32. package/lib/imapproxy/imap-server.js +13 -3
  33. package/lib/license-beacon.js +1 -1
  34. package/lib/llm-pre-process.js +1 -1
  35. package/lib/msgpack.js +62 -0
  36. package/lib/oauth/decode-jwt-payload.js +39 -0
  37. package/lib/oauth/outlook-identity.js +61 -0
  38. package/lib/oauth/retry-setup.js +38 -0
  39. package/lib/oauth2-apps.js +1 -1
  40. package/lib/outbox.js +66 -3
  41. package/lib/pre-process.js +1 -1
  42. package/lib/read-env-value.js +37 -0
  43. package/lib/schemas.js +12 -0
  44. package/lib/templates.js +1 -1
  45. package/lib/tokens.js +1 -1
  46. package/lib/tools.js +117 -48
  47. package/lib/totp.js +67 -0
  48. package/lib/ui-routes/account-routes.js +91 -15
  49. package/lib/ui-routes/admin-config-routes.js +2 -7
  50. package/lib/ui-routes/auth-routes.js +6 -24
  51. package/lib/ui-routes/reference-routes.js +8 -5
  52. package/lib/ui-routes/route-helpers.js +28 -0
  53. package/lib/utils/is-email.js +34 -0
  54. package/lib/utils/to-camel-case.js +17 -0
  55. package/lib/webhook-egress.js +37 -0
  56. package/lib/webhooks.js +1 -1
  57. package/package.json +22 -24
  58. package/sbom.json +1 -0
  59. package/server.js +1 -1
  60. package/static/css/flyonui.css +1 -1
  61. package/static/css/public.css +3 -0
  62. package/static/css/src/app.tailwind.css +23 -0
  63. package/static/js/app.js +69 -0
  64. package/static/js/reference.js +286 -1
  65. package/static/licenses.html +656 -1558
  66. package/translations/README.md +64 -0
  67. package/translations/de.mo +0 -0
  68. package/translations/de.po +164 -120
  69. package/translations/en.po +200 -161
  70. package/translations/et.mo +0 -0
  71. package/translations/et.po +163 -120
  72. package/translations/fr.mo +0 -0
  73. package/translations/fr.po +163 -120
  74. package/translations/ja.mo +0 -0
  75. package/translations/ja.po +163 -120
  76. package/translations/messages.pot +76 -46
  77. package/translations/nl.mo +0 -0
  78. package/translations/nl.po +164 -120
  79. package/translations/pl.mo +0 -0
  80. package/translations/pl.po +163 -120
  81. package/views/account-identity-error.hbs +34 -0
  82. package/views/accounts/edit.hbs +1 -0
  83. package/views/accounts/register/imap.hbs +12 -2
  84. package/views/layout/app.hbs +29 -5
  85. package/views/oauth-scope-error.hbs +1 -1
  86. package/views/partials/reference/nav.hbs +36 -9
  87. package/views/partials/reference/operation.hbs +1 -1
  88. package/views/partials/reference/schema-node.hbs +1 -1
  89. package/views/partials/reference/token-alert.hbs +35 -10
  90. package/views/reference/index.hbs +1 -1
  91. package/workers/api.js +157 -87
  92. package/workers/imap.js +1 -1
  93. package/workers/submit.js +1 -1
  94. package/workers/webhooks.js +2 -13
@@ -126,6 +126,86 @@ jobs:
126
126
  env:
127
127
  EENGINE_DOVECOT_PLATFORM: linux/amd64
128
128
 
129
+ # Nothing else in CI bundles a binary, so pkg failures used to surface only when a release
130
+ # was cut by hand on a Mac - the one place they are most expensive and least expected. Two
131
+ # landed in a single day: a local helper named `require` in lib/openapi/ that pkg's module
132
+ # walker choked on (undetectable by any test, since it runs correctly under Node), and a
133
+ # dependency shipping a 0-byte ESM entry point that esbuild transformed to nothing. The
134
+ # first sat undetected for four days and would have broken the next release outright.
135
+ #
136
+ # One target, unsigned, uncompressed. Signing and notarization need Apple credentials and
137
+ # stay on the release machine; neither has any bearing on whether the bundle can be built.
138
+ pkg_build:
139
+ name: Binary Build (linux-x64, unsigned)
140
+ if: ${{ !startsWith(github.ref_name, 'release-please--') && !startsWith(github.head_ref, 'release-please--') }}
141
+ timeout-minutes: 20
142
+ runs-on: ubuntu-24.04
143
+ services:
144
+ redis:
145
+ image: redis
146
+ options: >-
147
+ --health-cmd "redis-cli ping"
148
+ --health-interval 10s
149
+ --health-timeout 5s
150
+ --health-retries 5
151
+ ports:
152
+ - 6379:6379
153
+ steps:
154
+ - uses: actions/checkout@v6
155
+ - name: Use Node.js 24
156
+ uses: actions/setup-node@v6
157
+ with:
158
+ node-version: 24
159
+ cache: npm
160
+
161
+ # Unpinned on purpose, matching upload.sh: releases are built with whatever pkg is
162
+ # current, so a pkg regression should fail here rather than mid-release.
163
+ - name: Install pkg
164
+ run: npm install -g @yao-pkg/pkg
165
+
166
+ # The real production tree rather than a dev install. That distinction matters: the
167
+ # empty-ESM-file failure only exists under `npm ci --omit=dev`, and
168
+ # prepare-bundle-deps.sh, which works around it, only runs from this script.
169
+ - name: Build the production source tree
170
+ run: npm run build-source
171
+
172
+ # Uncompressed - Brotli is minutes of CPU that changes nothing about the module
173
+ # resolution this job exists to exercise. `--output` ignores the `outputPath` in
174
+ # package.json, so it names the directory itself; ee-dist is already gitignored,
175
+ # which keeps a stray 260 MB binary out of the way when running this locally.
176
+ - name: Bundle a binary
177
+ run: |
178
+ mkdir -p ee-dist
179
+ pkg --target node24-linux-x64 --output ee-dist/emailengine-ci package.json
180
+
181
+ - name: Smoke test the CLI
182
+ run: |
183
+ ./ee-dist/emailengine-ci --version
184
+ ./ee-dist/emailengine-ci help > /dev/null
185
+
186
+ # Booting reaches past what the CLI touches: workers, and the views, static files and
187
+ # lua scripts that are bundled as pkg assets rather than resolved as modules, so a
188
+ # missing asset shows up here instead of in a released binary.
189
+ - name: Boot the binary and check it serves
190
+ env:
191
+ EENGINE_REDIS: redis://127.0.0.1:6379/12
192
+ EENGINE_PORT: 7311
193
+ EENGINE_HOST: 127.0.0.1
194
+ EENGINE_LOG_LEVEL: error
195
+ run: |
196
+ ./ee-dist/emailengine-ci &
197
+ for i in $(seq 1 60); do
198
+ if curl -fsS http://127.0.0.1:7311/health >/dev/null 2>&1; then
199
+ echo "binary booted and served /health"
200
+ curl -fsS -o /dev/null http://127.0.0.1:7311/swagger.json
201
+ echo "generated document served"
202
+ exit 0
203
+ fi
204
+ sleep 2
205
+ done
206
+ echo "binary never became healthy" >&2
207
+ exit 1
208
+
129
209
  integration:
130
210
  name: Integration Tests
131
211
  if: ${{ !startsWith(github.ref_name, 'release-please--') && !startsWith(github.head_ref, 'release-please--') }}
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.77.0"
2
+ ".": "2.78.0"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.78.0](https://github.com/postalsys/emailengine/compare/v2.77.0...v2.78.0) (2026-08-12)
4
+
5
+
6
+ ### Features
7
+
8
+ * **accounts:** pin an account to an expected email identity ([a64bb60](https://github.com/postalsys/emailengine/commit/a64bb6009163bed0835cb3f8342e5d0ec20549b3)), closes [#626](https://github.com/postalsys/emailengine/issues/626)
9
+ * **admin-ui:** keep the access-token banner in view and make the reference nav usable on a phone ([a4bb55f](https://github.com/postalsys/emailengine/commit/a4bb55f7a416a74c65b50a0b69879b5b21915711))
10
+ * **admin:** mark the operation being read in the API reference sidebar ([700eab7](https://github.com/postalsys/emailengine/commit/700eab7716bec0362b73bf5e8f498be971071e7e))
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * **accounts:** let a wrong-account setup be retried instead of bouncing it back ([4cd6ac4](https://github.com/postalsys/emailengine/commit/4cd6ac4d0b935244accc55b1f9abb41cf906a2dc))
16
+ * **accounts:** remove the messages an account had queued when it is deleted ([ba6897f](https://github.com/postalsys/emailengine/commit/ba6897f4a5966a1a0dcddd7c514a3804e31591c4))
17
+ * **auth:** replace unmaintained speakeasy and base32.js with in-house implementations ([9abaaaa](https://github.com/postalsys/emailengine/commit/9abaaaa4cfd1869788238db80860bbbb77694ed3))
18
+ * **bounces:** read every block of a delivery-status body ([a99878e](https://github.com/postalsys/emailengine/commit/a99878eaf2970b36a7cc0ac50a725292405c6ab3))
19
+ * **bounces:** report every delivery-status field and describe one recipient ([71300c3](https://github.com/postalsys/emailengine/commit/71300c3fcf72065764857b1e90f43626b5e258e7))
20
+ * **deps:** replace deprecated msgpack5 with @msgpack/msgpack behind a compatibility wrapper ([9c40ebc](https://github.com/postalsys/emailengine/commit/9c40ebcc5b61993dad3f6979caab8cb8632b6ad0))
21
+ * **deps:** replace stagnant xml2js with fast-xml-parser in IMAP settings autodetection ([bfd6ec5](https://github.com/postalsys/emailengine/commit/bfd6ec5e7f0925fd3b0fb16a2a7490aa2cb14c27))
22
+ * **deps:** update dependencies (libmime 5.4.2, nodemailer 9.0.5, imapflow 1.6.6) ([abd8034](https://github.com/postalsys/emailengine/commit/abd8034d1e365c5e523a361a0379649fa9c6c29c))
23
+ * **deps:** update email-text-tools and email-ai-tools to pull in patched dompurify (GHSA-55q2-fjhq-7xh7) ([148130f](https://github.com/postalsys/emailengine/commit/148130ff55680287fcd3902b5b5ff0ba9f4881de))
24
+ * **deps:** update imapflow to 1.7.0, certs to 1.0.17, templates to 2.0.2 ([cafae8c](https://github.com/postalsys/emailengine/commit/cafae8ca7b2429547bc60cf2932077af24bfa356))
25
+ * **deps:** update our own packages so the tree carries one copy of each ([4a6e79f](https://github.com/postalsys/emailengine/commit/4a6e79fcaf2d11a35870e557c4a8e6756d05b4b4))
26
+ * **oauth2:** fall back to stored credentials when useAuthServer is set but no auth server is configured ([cd460b0](https://github.com/postalsys/emailengine/commit/cd460b056673c5b148760ba25b670c4e75f1f344))
27
+ * **webhooks:** bind the egress check to the address actually connected to ([#631](https://github.com/postalsys/emailengine/issues/631)) ([2d68b37](https://github.com/postalsys/emailengine/commit/2d68b37a1d186c7f9894e4b1425c1c52870c7cb5))
28
+
29
+
30
+ ### Performance Improvements
31
+
32
+ * **accounts:** unlink the account keys instead of deleting them inline ([ec11210](https://github.com/postalsys/emailengine/commit/ec11210a750021c1ccbf2df3637816974c0f995c))
33
+
3
34
  ## [2.77.0](https://github.com/postalsys/emailengine/compare/v2.76.0...v2.77.0) (2026-08-03)
4
35
 
5
36
 
@@ -14,7 +14,7 @@ const getSecret = require('../lib/get-secret');
14
14
  const { redis } = require('../lib/db');
15
15
 
16
16
  const argv = require('minimist')(process.argv.slice(2));
17
- const msgpack = require('msgpack5')();
17
+ const msgpack = require('../lib/msgpack');
18
18
  const crypto = require('crypto');
19
19
 
20
20
  // Command definitions for dynamic help generation
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-07-31T14:45:52.000000",
2
+ "creationTime": "2026-08-11T14:47:00.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
package/encrypt.js CHANGED
@@ -16,7 +16,7 @@ const config = require('@zone-eu/wild-config');
16
16
  const { encrypt, decrypt, parseEncryptedData } = require('./lib/encrypt');
17
17
  const { encryptedKeys } = require('./lib/settings');
18
18
  const getSecret = require('./lib/get-secret');
19
- const msgpack = require('msgpack5')();
19
+ const msgpack = require('./lib/msgpack');
20
20
 
21
21
  const { REDIS_PREFIX, ENCRYPTED_APP_KEYS } = require('./lib/consts');
22
22
  const { Settings: CertSettings } = require('@postalsys/certs/lib/settings');
@@ -0,0 +1,88 @@
1
+ 'use strict';
2
+
3
+ const { REDIS_PREFIX } = require('../consts');
4
+
5
+ // An account can carry an expected identity: the address that must own it, set by an authenticated API
6
+ // caller through `expectedEmail` on POST /v1/authentication/form, POST /v1/account or
7
+ // PUT /v1/account/{account}. Every interactive setup checks it before writing credentials.
8
+ //
9
+ // How strong that is depends on the arm, and the difference is not cosmetic. On OAuth2 the provider
10
+ // vouches for the identity, so the pin genuinely stops someone binding a different mailbox. On IMAP the
11
+ // only evidence is what was typed into the form: the submitted address is checked, but the credentials
12
+ // beside it are a separate field, so a hand-crafted POST can still register the pinned address against a
13
+ // mailbox it does not own. The IMAP guarantee is therefore "the account is registered under the expected
14
+ // address", not "the account holds that mailbox". Do not restate it more strongly than that.
15
+ //
16
+ // Everything the two arms must agree on lives here - where the expectation is read from, which one wins,
17
+ // and what counts as a match - because the arms are 1500 lines apart in different workers and any of
18
+ // those drifting is a silently weaker constraint. How a rejection is PRESENTED is deliberately not here:
19
+ // both arms render views/account-identity-error.hbs, but only each arm knows where "try again" leads.
20
+ //
21
+ // What counts as EVIDENCE is the one thing each arm supplies itself, because it genuinely differs:
22
+ //
23
+ // OAuth2 - the addresses the provider returned over a back-channel. Caller-supplied hints
24
+ // (accountData.email, oauth2.auth.delegatedUser) are excluded on purpose, so for a delegated
25
+ // or shared mailbox the expectation must name the authenticating principal, not the mailbox.
26
+ // IMAP - the address submitted on the form. The credentials still have to authenticate against the
27
+ // server, but nothing proves the address belongs to that mailbox, so the guarantee is the
28
+ // weaker "the account is registered under the expected address".
29
+
30
+ function normalizeEmail(value) {
31
+ return typeof value === 'string' ? value.trim().toLowerCase() : '';
32
+ }
33
+
34
+ // Fails closed: an empty expectation is not a licence to skip the check (callers must not call it in that
35
+ // case), and an empty or unusable identity list means we learned nothing about who authenticated, which
36
+ // is a rejection rather than a pass. That also makes a future provider that forgets to collect its
37
+ // identities reject setups instead of silently admitting them.
38
+ function matchesExpectedIdentity(expectedEmail, identities) {
39
+ const expected = normalizeEmail(expectedEmail);
40
+ if (!expected || !Array.isArray(identities)) {
41
+ return false;
42
+ }
43
+
44
+ return identities.some(identity => normalizeEmail(identity) === expected);
45
+ }
46
+
47
+ // The expectation that applies to a setup: the one carried by the signed form blob, or failing that the
48
+ // one already pinned to the account it targets.
49
+ //
50
+ // The blob wins because it is a deliberate re-statement by the authenticated caller, and that is what
51
+ // gives a legitimate mailbox migration a way through. A blob carrying none (an older link, or the admin
52
+ // re-authenticate blob) inherits the stored pin instead of clearing it, which is what makes the
53
+ // constraint outlive the single link that introduced it.
54
+ //
55
+ // Redis is read lazily, only on that fallback: a pinned link would otherwise pay a round trip for a value
56
+ // it always discards. Reads the field directly rather than through Account.loadAccountData(), which
57
+ // hgetalls and decrypts the whole record - same single-field pattern as getAccountState().
58
+ // The expectation carried by a pending OAuth2 setup, whichever of the two shapes it arrives in.
59
+ //
60
+ // Both are written by the server for an authenticated caller and stored under a random nonce, so they are
61
+ // equally trustworthy - they differ only because two entry points build the pending record differently.
62
+ // The hosted form (lib/ui-routes/account-routes.js) copies the field into `_meta` alongside redirectUrl;
63
+ // POST /v1/account with oauth2.authorize stores the request payload as-is and rebuilds `_meta` from
64
+ // scratch, leaving the field at the top level. Reading only `_meta` silently skipped the check on that
65
+ // second path - on the very setup that decides which mailbox the account gets bound to - while still
66
+ // persisting the pin afterwards, so the constraint looked active when it had never run.
67
+ function pendingSetupExpectation(accountData, accountMeta) {
68
+ return (accountMeta && accountMeta.expectedEmail) || (accountData && accountData.expectedEmail) || null;
69
+ }
70
+
71
+ // Returns the normalized form, so what gets persisted back onto the account does not depend on which
72
+ // branch produced it or on how the caller happened to capitalize the address.
73
+ async function resolveExpectedIdentity(redis, opts) {
74
+ const { account, blobExpectation } = opts || {};
75
+
76
+ const fromBlob = normalizeEmail(blobExpectation);
77
+ if (fromBlob) {
78
+ return fromBlob;
79
+ }
80
+
81
+ if (!account) {
82
+ return null;
83
+ }
84
+
85
+ return normalizeEmail(await redis.hget(`${REDIS_PREFIX}iad:${account}`, 'expectedEmail')) || null;
86
+ }
87
+
88
+ module.exports = { normalizeEmail, matchesExpectedIdentity, pendingSetupExpectation, resolveExpectedIdentity };
package/lib/account.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  const logger = require('./logger');
4
4
  const Boom = require('@hapi/boom');
5
- const msgpack = require('msgpack5')();
5
+ const msgpack = require('./msgpack');
6
6
  const {
7
7
  normalizePath,
8
8
  formatAccountListingResponse,
@@ -10,6 +10,7 @@ const {
10
10
  mergeObjects,
11
11
  download,
12
12
  resolveCredentials,
13
+ useAuthServerForOAuth2,
13
14
  isEmail,
14
15
  resolveDelegatedAccount,
15
16
  escapeRedisGlob,
@@ -24,6 +25,7 @@ const settings = require('./settings');
24
25
  const { buildRetentionPolicy } = require('./queue-retention');
25
26
  const { isDocumentStoreEnabled, documentStoreFeatureEnabled } = require('./document-store');
26
27
  const redisScanDelete = require('./redis-scan-delete');
28
+ const outbox = require('./outbox');
27
29
  const { customAlphabet } = require('nanoid');
28
30
  const Lock = require('ioredfour');
29
31
  const { redis } = require('./db');
@@ -349,6 +351,13 @@ class Account {
349
351
  }
350
352
  break;
351
353
 
354
+ case 'expectedEmail':
355
+ // '' is the cleared marker written by serializeAccountData - report it as unset.
356
+ if (accountData[key]) {
357
+ result[key] = accountData[key];
358
+ }
359
+ break;
360
+
352
361
  case 'path':
353
362
  if (!accountData[key] || !accountData[key].length) {
354
363
  break;
@@ -651,6 +660,17 @@ class Account {
651
660
  }
652
661
  break;
653
662
 
663
+ case 'expectedEmail':
664
+ // Clearable, so it cannot ride the default branch: that drops nulls, and hmset only
665
+ // ever adds keys, which would leave an identity pin settable but never removable.
666
+ // Follows the same convention as `copy` above - null serializes to the empty marker
667
+ // and unserialize treats it as unset - rather than adding a per-field delete to
668
+ // persistUpdate.
669
+ if (typeof accountData[key] === 'string' || accountData[key] === null) {
670
+ result[key] = accountData[key] || '';
671
+ }
672
+ break;
673
+
654
674
  default:
655
675
  if (typeof accountData[key] !== 'undefined' && accountData[key] !== null && typeof accountData[key].toString === 'function') {
656
676
  result[key] = accountData[key].toString();
@@ -840,7 +860,15 @@ class Account {
840
860
  mergeObjects(accountData[subKey], oldAccountData[subKey]);
841
861
  }
842
862
 
843
- let pipeline = this.redis.multi().hmset(this.getAccountKey(), this.serializeAccountData(accountData));
863
+ // An update whose payload serializes to nothing - an empty request, say - must not reach hmset:
864
+ // Redis rejects a write with no field/value pairs outright ("wrong number of arguments"), which
865
+ // surfaced as a 500 on a perfectly valid request.
866
+ const updatedFields = this.serializeAccountData(accountData);
867
+
868
+ let pipeline = this.redis.multi();
869
+ if (Object.keys(updatedFields).length) {
870
+ pipeline = pipeline.hmset(this.getAccountKey(), updatedFields);
871
+ }
844
872
 
845
873
  if (addProvider && !LEGACY_KEYS.includes(addProvider)) {
846
874
  pipeline = pipeline.sadd(`${REDIS_PREFIX}oapp:a:${addProvider}`, this.account);
@@ -880,15 +908,13 @@ class Account {
880
908
  }
881
909
  }
882
910
 
883
- let [[err, result]] = await pipeline.exec();
884
- if (err) {
885
- throw err;
886
- }
887
-
888
- if (!result || result !== 'OK') {
889
- let message = 'Something went wrong';
890
- let error = Boom.boomify(new Error(message), { statusCode: 500 });
891
- throw error;
911
+ // Surface the first failing reply. Checked by scanning rather than by reading a fixed index: the
912
+ // hmset is now conditional, so a positional read would silently start asserting against whichever
913
+ // command happened to be queued first.
914
+ for (let [err] of (await pipeline.exec()) || []) {
915
+ if (err) {
916
+ throw err;
917
+ }
892
918
  }
893
919
 
894
920
  return oldAccountData;
@@ -1191,24 +1217,33 @@ class Account {
1191
1217
  const tombstoneTdy = `${REDIS_PREFIX}tomb:${this.account}:${dateKeyTdy}`;
1192
1218
  const tombstoneYdy = `${REDIS_PREFIX}tomb:${this.account}:${dateKeyYdy}`;
1193
1219
 
1220
+ // UNLINK rather than DEL throughout: none of these need the memory reclaimed synchronously,
1221
+ // and the outbox and the message ID index can hold enough entries that freeing them inline
1222
+ // would block Redis for every other worker.
1223
+ //
1224
+ // The outbox is read and unlinked in the same transaction, because that hash is the only
1225
+ // mapping from an account to the submit queue jobs of the messages it has not delivered
1226
+ // yet, and those jobs outlive the account otherwise. Reading it here means the ID list is
1227
+ // exactly what was unlinked, and costs no extra round trip.
1194
1228
  let pipeline = this.redis
1195
1229
  .multi()
1196
- .del(this.getAccountKey())
1230
+ .hkeys(`${REDIS_PREFIX}iaq:${this.account}`) // queued message IDs, removed from the submit queue below
1231
+ .unlink(this.getAccountKey())
1197
1232
  .srem(`${REDIS_PREFIX}ia:accounts`, this.account)
1198
- .del(this.getMailboxListKey()) // mailbox list
1199
- .del(this.getMailboxHashKey()) // mailbox list for ID references
1200
- .del(`${REDIS_PREFIX}iar:b:${this.account}`) // bounce list
1201
- .del(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
1202
- .del(`${REDIS_PREFIX}iaq:${this.account}`) // delayed message queue
1203
- .del(`${REDIS_PREFIX}iat:${this.account}`) // access tokens
1204
- .del(`${REDIS_PREFIX}iac:${this.account}`) // cache hash
1205
- .del(`${REDIS_PREFIX}iap:${this.account}`) // external event notification queue
1233
+ .unlink(this.getMailboxListKey()) // mailbox list
1234
+ .unlink(this.getMailboxHashKey()) // mailbox list for ID references
1235
+ .unlink(`${REDIS_PREFIX}iar:b:${this.account}`) // bounce list
1236
+ .unlink(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
1237
+ .unlink(`${REDIS_PREFIX}iaq:${this.account}`) // delayed message queue
1238
+ .unlink(`${REDIS_PREFIX}iat:${this.account}`) // access tokens
1239
+ .unlink(`${REDIS_PREFIX}iac:${this.account}`) // cache hash
1240
+ .unlink(`${REDIS_PREFIX}iap:${this.account}`) // external event notification queue
1206
1241
 
1207
- .del(tombstoneTdy)
1208
- .del(tombstoneYdy)
1242
+ .unlink(tombstoneTdy)
1243
+ .unlink(tombstoneYdy)
1209
1244
 
1210
- .del(`${REDIS_PREFIX}tpl:${this.account}:i`) // stored templates index
1211
- .del(`${REDIS_PREFIX}tpl:${this.account}:c`); // stored templates index
1245
+ .unlink(`${REDIS_PREFIX}tpl:${this.account}:i`) // stored templates index
1246
+ .unlink(`${REDIS_PREFIX}tpl:${this.account}:c`); // stored templates index
1212
1247
 
1213
1248
  if (accountData.oauth2?.provider) {
1214
1249
  pipeline = pipeline.srem(`${REDIS_PREFIX}oapp:a:${accountData.oauth2.provider}`, this.account);
@@ -1219,11 +1254,25 @@ class Account {
1219
1254
 
1220
1255
  let result = await pipeline.exec();
1221
1256
 
1257
+ // Results are positional: [0] is the outbox HKEYS, [1] the account key UNLINK. Both indexes
1258
+ // move if a command is inserted ahead of them.
1259
+ let queuedMessageIds = (result && result[0] && result[0][1]) || [];
1260
+ if (queuedMessageIds.length) {
1261
+ // Best effort: the account is already gone, so a queue that will not cooperate must not
1262
+ // turn a completed deletion into an error.
1263
+ try {
1264
+ let removed = await outbox.removeJobs(queuedMessageIds, { account: this.account, logger: this.logger });
1265
+ this.logger.info({ msg: 'Removed queued messages of a deleted account', account: this.account, queued: queuedMessageIds.length, removed });
1266
+ } catch (err) {
1267
+ this.logger.error({ msg: 'Failed to remove queued messages of a deleted account', account: this.account, err });
1268
+ }
1269
+ }
1270
+
1222
1271
  // scan and delete keys
1223
1272
  // should we wait though? might take a lot of time
1224
1273
  await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${escapeRedisGlob(this.account)}:*`);
1225
1274
 
1226
- if (!result || !result[0] || !result[0][1]) {
1275
+ if (!result || !result[1] || !result[1][1]) {
1227
1276
  return {
1228
1277
  account: this.account,
1229
1278
  deleted: false
@@ -2767,7 +2816,7 @@ class Account {
2767
2816
  throw error;
2768
2817
  }
2769
2818
 
2770
- if (accountData.oauth2.useAuthServer) {
2819
+ if (await useAuthServerForOAuth2(accountData.oauth2, this.logger, { account: this.account, target: 'api' })) {
2771
2820
  // resolve credentials
2772
2821
 
2773
2822
  let authData = await resolveCredentials(this.account, 'api');
@@ -68,6 +68,18 @@ function slugify(value) {
68
68
  .replace(/^-+|-+$/g, '');
69
69
  }
70
70
 
71
+ // Where a group and an operation live. Four surfaces link to them - the tag directory, the
72
+ // nav's group rows, its per-group lists and the filter index - so the shape of a reference
73
+ // link is stated here rather than composed at each of them. The route itself is registered in
74
+ // lib/ui-routes/reference-routes.js.
75
+ function tagUrl(tagSlug) {
76
+ return `/admin/reference/${tagSlug}`;
77
+ }
78
+
79
+ function operationUrl(tagSlug, operationId) {
80
+ return `${tagUrl(tagSlug)}#${operationId}`;
81
+ }
82
+
71
83
  const METHOD_VARIANTS = {
72
84
  get: 'info',
73
85
  post: 'success',
@@ -173,6 +185,8 @@ function stringifyExample(value) {
173
185
  module.exports = {
174
186
  formatDescription,
175
187
  slugify,
188
+ tagUrl,
189
+ operationUrl,
176
190
  methodVariant,
177
191
  constraintList,
178
192
  stringifyExample
@@ -14,6 +14,7 @@
14
14
  const settings = require('../settings');
15
15
  const { buildModel } = require('./model');
16
16
  const { buildCodeSamples } = require('./code-samples');
17
+ const { operationUrl } = require('./format');
17
18
 
18
19
  const SPEC_URL = '/swagger.json';
19
20
 
@@ -97,14 +98,30 @@ function withSamples(operation, baseUrl) {
97
98
 
98
99
  // Navigation model shared by every reference page: all tags, with the active one marked.
99
100
  // activeSlug is null on the overview page, which the nav marks instead.
101
+ //
102
+ // Every tag carries its operations, not only the active one. Below the layout's lg breakpoint
103
+ // the nav is a disclosure, where tapping a group opens its list in place instead of loading
104
+ // its page (views/partials/reference/nav.hbs), so the rows of a group you are not on have to
105
+ // already be there. The active tag's entries are in-page anchors - the same links the scroll
106
+ // spy tracks - and every other tag's carry the page they live on.
100
107
  function buildNav(model, activeSlug) {
101
- return model.tags.map(tag => ({
102
- name: tag.name,
103
- slug: tag.slug,
104
- operationCount: tag.operationCount,
105
- active: tag.slug === activeSlug,
106
- operations: tag.slug === activeSlug ? tag.operations.map(operation => ({ id: operation.id, summary: operation.summary || operation.path })) : []
107
- }));
108
+ return model.tags.map(tag => {
109
+ const active = tag.slug === activeSlug;
110
+
111
+ return {
112
+ name: tag.name,
113
+ slug: tag.slug,
114
+ url: tag.url,
115
+ operationCount: tag.operationCount,
116
+ active,
117
+ operations: tag.operations.map(operation => ({
118
+ summary: operation.summary || operation.path,
119
+ // The active tag's entries have to stay bare fragments: initScrollSpy matches
120
+ // them literally, as a[href="#<id>"], to mark the operation being read.
121
+ url: active ? `#${operation.id}` : operationUrl(tag.slug, operation.id)
122
+ }))
123
+ };
124
+ });
108
125
  }
109
126
 
110
127
  // Serializes a value for embedding in a <script> element. JSON.stringify escapes quotes but
@@ -6,7 +6,7 @@
6
6
  // API worker and shared by every request. Anything that depends on the request (the
7
7
  // base URL used in the code samples) is applied later, in lib/api-reference/index.js.
8
8
 
9
- const { formatDescription, slugify, methodVariant, constraintList, stringifyExample } = require('./format');
9
+ const { formatDescription, slugify, tagUrl, operationUrl, methodVariant, constraintList, stringifyExample } = require('./format');
10
10
  const { buildSchemaTree, buildExample, typeLabel, enumInfo, requiredFirst } = require('./schema-tree');
11
11
  const { readCodeSamples } = require('./code-samples');
12
12
  const { NOTES_SEPARATOR } = require('../openapi');
@@ -268,6 +268,7 @@ function buildModel(spec) {
268
268
  tagsByName.set(tag.name, {
269
269
  name: tag.name,
270
270
  slug: slugify(tag.name),
271
+ url: tagUrl(slugify(tag.name)),
271
272
  descriptionHtml: formatDescription(tag.description),
272
273
  externalDocs: tag.externalDocs && tag.externalDocs.url ? tag.externalDocs : null,
273
274
  operations: []
@@ -290,6 +291,7 @@ function buildModel(spec) {
290
291
  tagsByName.set(tagName, {
291
292
  name: tagName,
292
293
  slug: slugify(tagName),
294
+ url: tagUrl(slugify(tagName)),
293
295
  descriptionHtml: '',
294
296
  externalDocs: null,
295
297
  operations: []
@@ -326,7 +328,7 @@ function buildModel(spec) {
326
328
  summary: operation.summary,
327
329
  tag: operation.tag,
328
330
  search: searchCorpus(operation),
329
- url: `/admin/reference/${operation.tagSlug}#${operation.id}`
331
+ url: operationUrl(operation.tagSlug, operation.id)
330
332
  }))
331
333
  };
332
334
  }
@@ -226,6 +226,8 @@ async function init(args) {
226
226
  name: Joi.string().max(256).required().example('My Email Account').description('Display name for the account'),
227
227
  email: Joi.string().empty('').email().example('user@example.com').description('Default email address of the account'),
228
228
 
229
+ expectedEmail: accountSchemas.expectedEmail,
230
+
229
231
  path: accountPathSchema.example(['*']).label('AccountPath'),
230
232
 
231
233
  subconnections: accountSchemas.subconnections,
@@ -372,6 +374,8 @@ async function init(args) {
372
374
  name: Joi.string().max(256).example('My Email Account').description('Display name for the account'),
373
375
  email: Joi.string().empty('').email().example('user@example.com').description('Default email address of the account'),
374
376
 
377
+ expectedEmail: accountSchemas.expectedEmailUpdate,
378
+
375
379
  path: accountPathSchema.example(['*']).label('AccountPath'),
376
380
 
377
381
  subconnections: accountSchemas.subconnections,
@@ -598,12 +602,16 @@ async function init(args) {
598
602
  },
599
603
  options: {
600
604
  description: 'Remove account',
601
- notes: "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.",
605
+ notes: [
606
+ "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.",
607
+ BEHAVIOR.DELETION_SCOPE
608
+ ],
602
609
 
603
610
  tags: ['api', 'Account'],
604
611
 
605
612
  plugins: {
606
613
  openapi: {
614
+ 'x-ee-behavior': [BEHAVIOR.DELETION_SCOPE],
607
615
  responses: apiResponses(
608
616
  'Returns a deletion marker. The account stops syncing immediately; stored data is removed in the background.',
609
617
  400,
@@ -898,6 +906,7 @@ async function init(args) {
898
906
  'account',
899
907
  'name',
900
908
  'email',
909
+ 'expectedEmail',
901
910
  'copy',
902
911
  'logs',
903
912
  'notifyFrom',
@@ -1043,6 +1052,8 @@ async function init(args) {
1043
1052
  name: Joi.string().allow('').max(256).example('My Email Account').description('Display name for the account'),
1044
1053
  email: Joi.string().empty('').email().example('user@example.com').description('Default email address of the account'),
1045
1054
 
1055
+ expectedEmail: accountSchemas.expectedEmail,
1056
+
1046
1057
  copy: Joi.boolean().example(true).description('Copy submitted messages to Sent folder'),
1047
1058
  logs: Joi.boolean().example(false).description('Store recent logs'),
1048
1059
 
@@ -1368,6 +1379,7 @@ async function init(args) {
1368
1379
  account: request.payload.account,
1369
1380
  name: request.payload.name,
1370
1381
  email: request.payload.email,
1382
+ expectedEmail: request.payload.expectedEmail,
1371
1383
  syncFrom: request.payload.syncFrom,
1372
1384
  notifyFrom: request.payload.notifyFrom,
1373
1385
  subconnections: request.payload.subconnections,
@@ -1423,7 +1435,10 @@ async function init(args) {
1423
1435
 
1424
1436
  options: {
1425
1437
  description: 'Generate authentication link',
1426
- notes: 'Generates a redirect link to the hosted authentication form',
1438
+ notes: [
1439
+ 'Generates a redirect link to the hosted authentication form',
1440
+ 'If `expectedEmail` is set and the user completes the form as a different identity, the setup is rejected before any credentials are stored. The user stays on EmailEngine, which names both addresses and offers to restart the setup, so the browser is never redirected to `redirectUrl`.'
1441
+ ],
1427
1442
  tags: ['api', 'Account'],
1428
1443
 
1429
1444
  plugins: {
@@ -1466,6 +1481,8 @@ async function init(args) {
1466
1481
  .example('user@example.com')
1467
1482
  .description('Specifies the default email address for this account. Users can change it if needed.'),
1468
1483
 
1484
+ expectedEmail: accountSchemas.expectedEmail,
1485
+
1469
1486
  delegated: Joi.boolean()
1470
1487
  .empty('')
1471
1488
  .truthy('Y', 'true', '1')
@@ -39,6 +39,9 @@ module.exports = {
39
39
 
40
40
  SSE_STREAM: 'A long-lived Server-Sent Events stream rather than a normal request and response. The connection stays open until the client closes it.',
41
41
 
42
+ DELETION_SCOPE:
43
+ 'Removes the account, its credentials, its cached data and any messages still queued for delivery. Webhook events generated before the deletion are never delivered afterwards and are discarded once the queue reaches them. Records of deliveries that had already failed permanently are not removed here; they expire on the queue retention window, seven days by default.',
44
+
42
45
  // --- provider differences ----------------------------------------------------------
43
46
  NO_QUOTA_ON_API_ACCOUNTS: 'Quota reporting is not available for Gmail API or MS Graph accounts; the quota field is omitted for those.',
44
47