emailengine-app 2.81.2 → 2.82.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 (204) hide show
  1. package/.ncurc.js +12 -11
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/Dockerfile +2 -0
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/expected-identity.js +1 -1
  13. package/lib/account-assignment.js +138 -1
  14. package/lib/account.js +254 -859
  15. package/lib/api-reference/index.js +2 -3
  16. package/lib/api-reference/schema-tree.js +53 -3
  17. package/lib/api-routes/account-routes.js +18 -29
  18. package/lib/api-routes/blocklist-routes.js +2 -2
  19. package/lib/api-routes/bull-board-routes.js +1 -6
  20. package/lib/api-routes/export-routes.js +2 -22
  21. package/lib/api-routes/gateway-routes.js +5 -14
  22. package/lib/api-routes/index.js +1 -13
  23. package/lib/api-routes/mailbox-routes.js +2 -7
  24. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  25. package/lib/api-routes/mcp-routes.js +7 -7
  26. package/lib/api-routes/message-routes.js +40 -235
  27. package/lib/api-routes/mint-bounds.js +110 -0
  28. package/lib/api-routes/oauth2-app-routes.js +23 -32
  29. package/lib/api-routes/operation-impact.js +1 -1
  30. package/lib/api-routes/outbox-routes.js +2 -2
  31. package/lib/api-routes/permission-map.js +1 -7
  32. package/lib/api-routes/route-helpers.js +11 -5
  33. package/lib/api-routes/settings-routes.js +19 -19
  34. package/lib/api-routes/stats-routes.js +1 -1
  35. package/lib/api-routes/submit-routes.js +17 -18
  36. package/lib/api-routes/template-routes.js +4 -9
  37. package/lib/api-routes/token-routes.js +27 -5
  38. package/lib/api-token-scheme.js +71 -0
  39. package/lib/arf-detect.js +33 -6
  40. package/lib/auth-token.js +44 -24
  41. package/lib/autodetect-imap-settings.js +163 -123
  42. package/lib/bounce-detect.js +25 -16
  43. package/lib/calendar-event.js +78 -0
  44. package/lib/consts.js +42 -5
  45. package/lib/create-imap-client.js +24 -0
  46. package/lib/db.js +76 -11
  47. package/lib/delivery-error.js +2 -1
  48. package/lib/egress-fetch.js +54 -3
  49. package/lib/egress-filter.js +11 -0
  50. package/lib/email-client/api-retry.js +147 -0
  51. package/lib/email-client/base-client.js +377 -523
  52. package/lib/email-client/gmail/gmail-api.js +38 -125
  53. package/lib/email-client/gmail/send-request.js +1 -1
  54. package/lib/email-client/gmail-client.js +76 -50
  55. package/lib/email-client/imap/mailbox.js +158 -324
  56. package/lib/email-client/imap/stale-view.js +109 -0
  57. package/lib/email-client/imap/subconnection.js +46 -9
  58. package/lib/email-client/imap/sync-operations.js +5 -37
  59. package/lib/email-client/imap-client.js +188 -64
  60. package/lib/email-client/message-builder.js +9 -14
  61. package/lib/email-client/notification-handler.js +5 -219
  62. package/lib/email-client/outlook/graph-api.js +147 -126
  63. package/lib/email-client/outlook/send-request.js +10 -4
  64. package/lib/email-client/outlook-client.js +194 -397
  65. package/lib/email-client/smtp-pool-manager.js +3 -2
  66. package/lib/encrypt.js +184 -19
  67. package/lib/enum-descriptions.js +1 -2
  68. package/lib/export.js +133 -39
  69. package/lib/gateway.js +20 -6
  70. package/lib/get-raw-email.js +26 -44
  71. package/lib/handlebars-helpers.js +31 -10
  72. package/lib/imap-proxy-auth.js +13 -29
  73. package/lib/imapproxy/imap-core/README.md +1 -0
  74. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  75. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  76. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  77. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  78. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  79. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  80. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  81. package/lib/imapproxy/imap-server.js +17 -177
  82. package/lib/imapproxy/proxy-handoff.js +235 -0
  83. package/lib/imapproxy/response-error.js +33 -0
  84. package/lib/imapproxy/upstream-client.js +2 -2
  85. package/lib/license-beacon.js +3 -9
  86. package/lib/llm-pre-process.js +182 -43
  87. package/lib/logger.js +1 -1
  88. package/lib/lua/ee-export-queue-add.lua +39 -0
  89. package/lib/lua/ee-get-idempotency.lua +15 -3
  90. package/lib/lua/ee-release-attempts.lua +23 -0
  91. package/lib/lua/ee-reserve-attempts.lua +42 -0
  92. package/lib/lua/h-set-bigger.lua +12 -2
  93. package/lib/lua/s-list-accounts.lua +6 -3
  94. package/lib/mcp/index.js +1 -2
  95. package/lib/mcp/listen.js +221 -18
  96. package/lib/mcp/oauth.js +44 -5
  97. package/lib/mcp/resources.js +8 -2
  98. package/lib/mcp/tools.js +13 -0
  99. package/lib/message-port-stream.js +64 -6
  100. package/lib/oauth/external-account-signer.js +16 -13
  101. package/lib/oauth/gmail.js +22 -20
  102. package/lib/oauth/outlook.js +19 -16
  103. package/lib/oauth/pubsub/google.js +38 -2
  104. package/lib/oauth/scope-checker.js +4 -7
  105. package/lib/oauth/verify-app.js +2 -2
  106. package/lib/oauth2-apps.js +139 -44
  107. package/lib/openapi/build-document.js +1 -1
  108. package/lib/openapi/joi-schema.js +78 -9
  109. package/lib/parse-message.js +21 -0
  110. package/lib/payload-examples-webhooks.json +4 -7
  111. package/lib/pbkdf2-phc.js +101 -0
  112. package/lib/privileged-settings.js +0 -14
  113. package/lib/rate-limit.js +54 -15
  114. package/lib/redis-scan-delete.js +56 -29
  115. package/lib/redis-url.js +3 -1
  116. package/lib/respawn-backoff.js +5 -4
  117. package/lib/response-stream.js +25 -4
  118. package/lib/rewrite-text-nodes.js +27 -40
  119. package/lib/routes-ui.js +0 -5
  120. package/lib/schemas.js +122 -242
  121. package/lib/sentry.js +21 -5
  122. package/lib/settings.js +58 -59
  123. package/lib/smtp-auth.js +6 -2
  124. package/lib/smtp-message-processor.js +28 -7
  125. package/lib/sso.js +7 -3
  126. package/lib/stream-encrypt.js +14 -13
  127. package/lib/swagger-options.js +3 -1
  128. package/lib/tls/provision.js +69 -3
  129. package/lib/tls/store.js +14 -1
  130. package/lib/tools.js +113 -52
  131. package/lib/totp.js +16 -1
  132. package/lib/ui-routes/account-routes.js +27 -63
  133. package/lib/ui-routes/admin-config-routes.js +111 -134
  134. package/lib/ui-routes/admin-entities-routes.js +101 -191
  135. package/lib/ui-routes/ai-options.js +104 -0
  136. package/lib/ui-routes/auth-routes.js +98 -18
  137. package/lib/ui-routes/export-routes.js +3 -23
  138. package/lib/ui-routes/internals-routes.js +12 -9
  139. package/lib/ui-routes/network-config-routes.js +8 -18
  140. package/lib/ui-routes/oauth-config-routes.js +80 -214
  141. package/lib/ui-routes/route-helpers.js +40 -44
  142. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  143. package/lib/utils/decode-headers.js +32 -5
  144. package/lib/utils/header-map.js +62 -1
  145. package/lib/utils/network.js +2 -0
  146. package/lib/web-safe-html.js +77 -4
  147. package/lib/webhook-request.js +9 -1
  148. package/lib/webhook-routing.js +27 -1
  149. package/lib/webhooks.js +120 -43
  150. package/lib/worker-rpc-error.js +43 -2
  151. package/list-generate.js +13 -2
  152. package/package.json +33 -41
  153. package/sbom.json +1 -1
  154. package/scripts/refresh-test-tokens.js +42 -14
  155. package/server.js +317 -289
  156. package/static/css/flyonui.css +1 -1
  157. package/static/css/src/app.tailwind.css +7 -8
  158. package/static/js/ee-client.js +145 -70
  159. package/static/js/ui.js +350 -154
  160. package/static/licenses.html +434 -1835
  161. package/translations/messages.pot +97 -97
  162. package/views/accounts/browse.hbs +10 -4
  163. package/views/config/ai.hbs +49 -41
  164. package/views/config/oauth/app.hbs +2 -1
  165. package/views/dashboard.hbs +18 -16
  166. package/views/layout/app.hbs +0 -22
  167. package/views/layout/login.hbs +2 -1
  168. package/views/partials/filter_editor_js.hbs +4 -3
  169. package/views/partials/side_menu.hbs +0 -4
  170. package/views/partials/ui/account-picker.hbs +6 -32
  171. package/views/partials/ui/model-picker.hbs +31 -0
  172. package/views/partials/ui/pagination.hbs +6 -1
  173. package/views/partials/ui/picker.hbs +47 -0
  174. package/views/unsubscribe.hbs +1 -1
  175. package/workers/api.js +20 -20
  176. package/workers/export.js +55 -60
  177. package/workers/imap.js +126 -46
  178. package/workers/submit.js +3 -1
  179. package/workers/webhooks.js +46 -27
  180. package/.githooks/pre-commit +0 -80
  181. package/.github/CODE_OF_CONDUCT.md +0 -76
  182. package/.github/contributing.md +0 -17
  183. package/.github/dependabot.yml +0 -22
  184. package/.github/docker-smoke-test.sh +0 -61
  185. package/.github/workflows/deploy.yml +0 -215
  186. package/.github/workflows/e2e.yml +0 -55
  187. package/.github/workflows/release.yaml +0 -217
  188. package/.github/workflows/test.yml +0 -307
  189. package/lib/api-routes/chat-routes.js +0 -535
  190. package/lib/document-store.js +0 -75
  191. package/lib/es.js +0 -757
  192. package/lib/generate-text-preview.js +0 -61
  193. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  194. package/lib/pre-process.js +0 -196
  195. package/lib/threads.js +0 -155
  196. package/lib/ui-routes/document-store-routes.js +0 -806
  197. package/playwright.config.js +0 -47
  198. package/views/config/document-store/chat.hbs +0 -286
  199. package/views/config/document-store/index.hbs +0 -146
  200. package/views/config/document-store/mappings/index.hbs +0 -108
  201. package/views/config/document-store/mappings/new.hbs +0 -68
  202. package/views/config/document-store/pre-processing/index.hbs +0 -103
  203. package/views/partials/document_store_header.hbs +0 -30
  204. package/workers/documents.js +0 -1128
package/.ncurc.js CHANGED
@@ -11,10 +11,8 @@ module.exports = {
11
11
  // is a major we are deliberately soaking. Using 'minor' instead of a blanket reject so these
12
12
  // still receive security/patch updates within the safe major instead of being frozen at one
13
13
  // exact version. Verified against Node 20 (Docker) 2026-06-17.
14
- target: name =>
15
- ['nanoid', 'ical.js', 'gettext-parser', 'xgettext-template', 'chai', 'undici', 'marked', '@sentry/node'].includes(name) ? 'minor' : 'latest',
14
+ target: name => (['nanoid', 'gettext-parser', 'xgettext-template', 'chai', 'undici', 'marked', '@sentry/node-core'].includes(name) ? 'minor' : 'latest'),
16
15
  // nanoid - 4.x dropped the CommonJS require export (ESM-only)
17
- // ical.js - 2.x is ESM-only
18
16
  // gettext-parser - 8.x is ESM-only
19
17
  // xgettext-template - 6.x is ESM-only (translation build tool)
20
18
  // chai - 5.x is ESM-only (only used by the vendored imap-core tests)
@@ -23,10 +21,17 @@ module.exports = {
23
21
  // marked - 16.x dropped the CommonJS build (ESM-only, needs require(esm)/Node >=20.19); 15.x is the
24
22
  // last require()-compatible line. 15.0.12 verified on Node 20-24 and in a yao/pkg node24 build.
25
23
  // Permanent while the Node 20 floor above stands.
26
- // @sentry/node - 11.x requires Node >=20.19 (the DigitalOcean images are not guaranteed to be on a 20.x
27
- // that new), and it depends on @sentry/bundler-plugins, which pulls the 16 MB Sentry CLI
28
- // (package `sentry`, licensed FSL-1.1-Apache-2.0, not an OSI license) into the runtime
29
- // tree and the pkg bundle. Reconsider if a later 11.x drops that dependency.
24
+ // @sentry/node-core - held on the 10.x line for the reasons @sentry/node (which it replaced, through its
25
+ // `light` entry) was held there: @sentry/node 11.x requires Node >=20.19 (the DigitalOcean
26
+ // images are not guaranteed to be on a 20.x that new), and it depends on
27
+ // @sentry/bundler-plugins, which pulls the 16 MB Sentry CLI (package `sentry`, licensed
28
+ // FSL-1.1-Apache-2.0, not an OSI license) into the runtime tree and the pkg bundle. The
29
+ // node-core line is versioned in step with @sentry/node, so lift this only once an 11.x
30
+ // of node-core exists and has been checked against both points.
31
+ //
32
+ // ical.js was capped at 1.x here as "2.x is ESM-only", which was never true: every 2.x ships a CommonJS
33
+ // build behind exports.require. Moved to 2.x on 2026-09-28; it is also what resolves a DTSTART against
34
+ // the VTIMEZONE embedded in the same invite (1.x read such a value in the server's own zone).
30
35
  //
31
36
  // bullmq was capped at 5.x until 2026-08-17, when both stated reasons had expired. Now on 6.x, which
32
37
  // moves cron-parser off the deprecated 4.9.0 onto 5.x - but not off luxon, which cron-parser depends
@@ -42,10 +47,6 @@ module.exports = {
42
47
  // bump still needs a look at the generated document: test/openapi-golden-test.js fails if joi's
43
48
  // describe() output changes shape.
44
49
  reject: [
45
- // 8.16+ pulls apache-arrow (ESM) into the pkg bundle; 9.x drops it but is a major bump for
46
- // the deprecated, default-off Document Store. Even the 8.19 minor is unsafe to bundle.
47
- '@elastic/elasticsearch',
48
-
49
50
  // @asamuzakjp/css-color >=4.1.2 pulls in @csstools/* v4 which are pure ESM and break pkg bundling
50
51
  // (transitive via @postalsys/email-text-tools -> jsdom -> cssstyle; also pinned in package.json "overrides").
51
52
  '@asamuzakjp/css-color'
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.81.2"
2
+ ".": "2.82.0"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.82.0](https://github.com/postalsys/emailengine/compare/v2.81.2...v2.82.0) (2026-10-01)
4
+
5
+
6
+ ### Features
7
+
8
+ * check incoming mail in code before the AI reads it, and pick the model from a list that says what each is for ([cf6f3a6](https://github.com/postalsys/emailengine/commit/cf6f3a6fda2d7c67a7f178b9c10e5014fc497e48))
9
+ * deliver the AI summary as the model returned it, and count its usage ([854ef18](https://github.com/postalsys/emailengine/commit/854ef18f1f8969bdcabe34b5a3a99c6ee2fc71e8))
10
+ * remove embeddings generation ([f4ddd90](https://github.com/postalsys/emailengine/commit/f4ddd908326bf6489ebbbdbf3421a291043ce8f0))
11
+ * remove the Document Store ([56df159](https://github.com/postalsys/emailengine/commit/56df159e4838d7b3052dadb8c30d8ac1e85f4e12))
12
+
13
+
14
+ ### Bug Fixes
15
+
16
+ * assert the literal cap on the continuations sent before the refusal ([1aa24dc](https://github.com/postalsys/emailengine/commit/1aa24dc9d6cbd2a2b8b33b4dc8f5fd328ab435bb))
17
+ * close the findings of the 2026-09-28 codebase audit ([2db748f](https://github.com/postalsys/emailengine/commit/2db748fc9879d577d3a9634fd6676149c91c1219))
18
+ * count announced literals against the IMAP proxy cap at continuation time ([51b73d2](https://github.com/postalsys/emailengine/commit/51b73d2f498e2d1fcd85861104ad89f65f184879))
19
+ * **deps:** update libmime, mailsplit, imapflow, mailparser and email-ai-tools ([943d2f5](https://github.com/postalsys/emailengine/commit/943d2f5891a88ff040fc2b7b3eb590c16cc498c6))
20
+ * **deps:** update nodemailer, smtp-server, mailparser, email-content and email-ai-tools ([af7aa9f](https://github.com/postalsys/emailengine/commit/af7aa9f5a46fb20409c9d8a3bd64be63c6593700))
21
+ * drop the trusted authentication servers setting from the AI page ([0b01c7e](https://github.com/postalsys/emailengine/commit/0b01c7e04c80e4dc60bf3bcf6b11e3114e9bd9ff))
22
+ * **imap:** measure the stale view quiet period from the UIDNEXT the primary knows ([a3044a1](https://github.com/postalsys/emailengine/commit/a3044a1ddbdae50298ebc3f61a909102360548dd))
23
+ * **imap:** reconnect a primary connection whose view of the main mailbox stopped moving ([442955c](https://github.com/postalsys/emailengine/commit/442955c41ef2f0fa4898e089056d2ee9fa7a2fdd))
24
+ * match the model picker's search term by term and rank the answers ([632754e](https://github.com/postalsys/emailengine/commit/632754e3e2110431caedb6f6ba391a3367b58df9))
25
+ * **outlook:** keep draft replies threaded on MS Graph accounts ([1ec3c6a](https://github.com/postalsys/emailengine/commit/1ec3c6a1485ee4fd649060e6fd2f137b01d87975))
26
+ * read the browse page session token from its hidden input in the e2e spec ([eea4a58](https://github.com/postalsys/emailengine/commit/eea4a58d5d15779c322fa52b9cc03b14284f2104))
27
+ * update ImapFlow to 2.2.1 ([a007b46](https://github.com/postalsys/emailengine/commit/a007b46ab68add12486ad11e6bef84db53777974))
28
+ * use only FIPS-approved primitives, so an instance runs on a host whose OpenSSL is in FIPS mode ([5070de0](https://github.com/postalsys/emailengine/commit/5070de07d5ac4c64bfa252766b965e9602407497))
29
+
3
30
  ## [2.81.2](https://github.com/postalsys/emailengine/compare/v2.81.1...v2.81.2) (2026-09-27)
4
31
 
5
32
 
package/Dockerfile CHANGED
@@ -98,6 +98,8 @@ USER emailengineuser
98
98
 
99
99
  ENV EENGINE_HOST=0.0.0.0
100
100
  ENV EENGINE_API_PROXY=true
101
+ # The pure JavaScript msgpackr decoder is what the pkg binary uses, so npm and Docker installs decode the same way and no native addon is loaded
102
+ ENV MSGPACKR_NATIVE_ACCELERATION_DISABLED=true
101
103
 
102
104
  ENTRYPOINT ["/usr/bin/dumb-init", "--"]
103
105
  CMD ["node", "/emailengine/server.js"]
@@ -2,13 +2,17 @@
2
2
  /* eslint global-require: 0 */
3
3
  'use strict';
4
4
 
5
+ // No native addons (CLAUDE.md "Pure JavaScript only"): keep msgpackr, loaded through bullmq by
6
+ // lib/db below, off its optional node-gyp decoder. server.js sets the same for a direct start.
7
+ process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED = 'true';
8
+
5
9
  const packageData = require('../package.json');
6
10
  const fs = require('fs');
7
11
  const pathlib = require('path');
8
12
  const settings = require('../lib/settings');
9
13
  const { checkLicense } = require('../lib/tools');
10
- const pbkdf2 = require('@phc/pbkdf2');
11
- const { PDKDF2_ITERATIONS, PDKDF2_SALT_SIZE, PDKDF2_DIGEST, generateWebhookTable } = require('../lib/consts');
14
+ const pbkdf2 = require('../lib/pbkdf2-phc');
15
+ const { generateWebhookTable } = require('../lib/consts');
12
16
  const { Account } = require('../lib/account');
13
17
  const getSecret = require('../lib/get-secret');
14
18
  const { redis } = require('../lib/db');
@@ -133,13 +137,6 @@ const GLOBAL_OPTIONS = [
133
137
  { name: '--smtp.port', description: 'SMTP server port', type: 'number', default: 2525, group: 'SMTP server' },
134
138
  { name: '--smtp.proxy', description: 'Enable HAProxy PROXY protocol', type: 'boolean', default: false, group: 'SMTP server' },
135
139
  { name: '--smtp.maxMessageSize', description: 'Maximum email size', type: 'number/string', default: '25M', group: 'SMTP server' },
136
- {
137
- name: '--documentStore.enabled',
138
- description: 'Enable the deprecated Document Store (ElasticSearch) feature',
139
- type: 'boolean',
140
- default: false,
141
- group: 'Document Store (deprecated)'
142
- },
143
140
  {
144
141
  name: '--mcp.enabled',
145
142
  description: 'Register the MCP endpoint at /mcp (the mcpEnabled runtime setting still has to be turned on)',
@@ -386,11 +383,7 @@ function run() {
386
383
  }
387
384
 
388
385
  let updatePassword = async () => {
389
- let passwordHash = await pbkdf2.hash(password, {
390
- iterations: PDKDF2_ITERATIONS,
391
- saltSize: PDKDF2_SALT_SIZE,
392
- digest: PDKDF2_DIGEST
393
- });
386
+ let passwordHash = await pbkdf2.hash(password);
394
387
 
395
388
  let authData = await settings.get('authData');
396
389
 
@@ -581,7 +574,13 @@ function run() {
581
574
  case 'import':
582
575
  {
583
576
  let rawToken = (argv.token || argv.t || '').toString();
584
- let tokenData = msgpack.decode(Buffer.from(rawToken, 'base64url'));
577
+ let tokenData;
578
+ try {
579
+ tokenData = msgpack.decode(Buffer.from(rawToken, 'base64url'));
580
+ } catch (err) {
581
+ console.error(`Unable to decode token data: ${err.message}`);
582
+ return process.exit(1);
583
+ }
585
584
  tokens
586
585
  .setRawData(tokenData)
587
586
  .then(result => {
@@ -600,8 +599,12 @@ function run() {
600
599
  break;
601
600
 
602
601
  default:
603
- console.error('Future feature');
604
- break;
602
+ // Nothing else would end the process: the Redis connection opened on load
603
+ // kept it running with no output
604
+ console.error(tokensCmd ? `Unknown tokens command: ${tokensCmd}` : 'A tokens command is required');
605
+ console.error('');
606
+ console.error(generateCommandHelp('tokens'));
607
+ return process.exit(1);
605
608
  }
606
609
  }
607
610
  break;
@@ -703,10 +706,17 @@ function run() {
703
706
  }
704
707
  break;
705
708
 
706
- default:
709
+ case '':
707
710
  // run normally
708
711
  require('../server');
709
712
  break;
713
+
714
+ default:
715
+ // A mistyped command used to start the server instead
716
+ console.error(`Unknown command: ${cmd}`);
717
+ console.error('');
718
+ console.error('Run "emailengine help" to see available commands.');
719
+ return process.exit(1);
710
720
  }
711
721
  }
712
722
 
@@ -46,11 +46,6 @@ proxy = false # Set to true if using HAProxy with send-proxy option
46
46
  #maxMessageSize = "25M" # maximum message size accepted by SMTP server (default: 25MB)
47
47
  #maxClients = 100 # concurrent SMTP server connections; excess connections are refused with a 421 (default: 100)
48
48
 
49
- [documentStore]
50
- # Deprecated Document Store (ElasticSearch) feature. Disabled by default; the worker and
51
- # all document-store API/UI endpoints are only available when this is enabled.
52
- enabled = false
53
-
54
49
  [mcp]
55
50
  # MCP (Model Context Protocol) endpoint at /mcp. This deployment-level gate controls whether
56
51
  # the endpoint exists in the route table at all; the runtime on/off switch is the mcpEnabled
package/config/test.toml CHANGED
@@ -44,8 +44,3 @@ port = 7077
44
44
 
45
45
  [webhooksServer]
46
46
  port = 7078
47
-
48
- # Keep the deprecated Document Store feature available during tests so the existing
49
- # document-store API/UI endpoints stay covered. Disabled by default in production.
50
- [documentStore]
51
- enabled = true
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-09-25T14:47:24.000000",
2
+ "creationTime": "2026-09-30T14:46:44.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
package/encrypt.js CHANGED
@@ -13,8 +13,10 @@ try {
13
13
 
14
14
  const { redis } = require('./lib/db');
15
15
  const config = require('@zone-eu/wild-config');
16
- const { encrypt, decrypt, parseEncryptedData } = require('./lib/encrypt');
16
+ const { reencrypt } = require('./lib/encrypt');
17
17
  const { encryptedKeys } = require('./lib/settings');
18
+ const { ENCRYPTED_ACCOUNT_FIELDS } = require('./lib/account');
19
+ const { ENCRYPTED_ROUTE_FIELDS } = require('./lib/webhooks');
18
20
  const getSecret = require('./lib/get-secret');
19
21
  const msgpack = require('./lib/msgpack');
20
22
 
@@ -24,47 +26,7 @@ const { TLS_KEY } = require('./lib/tls/store');
24
26
 
25
27
  const DECRYPT_PASSWORDS = [].concat(config.decrypt || []);
26
28
 
27
- async function processSecret(value, encryptSecret) {
28
- let lastErr = false;
29
- let decrypted = value;
30
-
31
- for (let password of DECRYPT_PASSWORDS) {
32
- try {
33
- decrypted = decrypt(value, password);
34
- if (password === encryptSecret) {
35
- // nothing was changed
36
- return value;
37
- }
38
- break;
39
- } catch (err) {
40
- lastErr = err;
41
- }
42
- }
43
-
44
- let parsed = parseEncryptedData(decrypted);
45
- if (parsed.format !== 'cleartext') {
46
- // was not able to decrypt
47
- if (encryptSecret) {
48
- try {
49
- decrypted = decrypt(value, encryptSecret);
50
- // did not throw, so the value is already encrypted with the new password
51
- return value;
52
- } catch (err) {
53
- // ignore
54
- }
55
- }
56
-
57
- throw lastErr || new Error('Could not decrypt encrypted password');
58
- }
59
-
60
- if (encryptSecret) {
61
- // encrypt
62
- return encrypt(decrypted, encryptSecret);
63
- }
64
-
65
- // return plaintext
66
- return decrypted;
67
- }
29
+ const processSecret = (value, encryptSecret) => reencrypt(value, DECRYPT_PASSWORDS, encryptSecret);
68
30
 
69
31
  async function main() {
70
32
  console.error('EmailEngine account encryption tool');
@@ -163,6 +125,23 @@ async function main() {
163
125
  }
164
126
  }
165
127
 
128
+ // The credential-bearing fields stored as plain strings (webhooksCustomHeaders is its JSON
129
+ // encoding); '' is a cleared marker and stays as it is
130
+ for (let key of ENCRYPTED_ACCOUNT_FIELDS) {
131
+ if (!accountData[key] || typeof accountData[key] !== 'string') {
132
+ continue;
133
+ }
134
+ try {
135
+ let value = await processSecret(accountData[key], encryptSecret);
136
+ if (value !== accountData[key]) {
137
+ updates[key] = value;
138
+ updated = true;
139
+ }
140
+ } catch (err) {
141
+ console.error(`Could not process "${key}" for ${account}. Check decryption secrets.`);
142
+ }
143
+ }
144
+
166
145
  if (updated) {
167
146
  let result = await redis.hmset(`${REDIS_PREFIX}iad:${account}`, updates);
168
147
  if (result === 'OK') {
@@ -249,6 +228,55 @@ async function main() {
249
228
 
250
229
  console.log(`Updated ${updatedApps}/${apps.length} OAuth2 apps`);
251
230
 
231
+ // Custom webhook routes: the target URL and the custom header list inside each route's msgpack
232
+ // meta entry. A route written before these were encrypted holds the headers as an array, which
233
+ // is converted to the JSON string form lib/webhooks.js stores.
234
+ let updatedRoutes = 0;
235
+ let routes = await redis.smembers(`${REDIS_PREFIX}wh:i`);
236
+ for (let route of routes) {
237
+ let metaBuf = await redis.hgetBuffer(`${REDIS_PREFIX}wh:c`, `${route}:meta`);
238
+ if (!metaBuf) {
239
+ continue;
240
+ }
241
+
242
+ let meta;
243
+ try {
244
+ meta = msgpack.decode(metaBuf);
245
+ } catch (err) {
246
+ console.log(`Webhook route ${route}: failed to parse`);
247
+ continue;
248
+ }
249
+
250
+ try {
251
+ let routeUpdated = false;
252
+ for (let key of ENCRYPTED_ROUTE_FIELDS) {
253
+ let stored = Array.isArray(meta[key]) ? JSON.stringify(meta[key]) : meta[key];
254
+ if (!stored || typeof stored !== 'string') {
255
+ continue;
256
+ }
257
+ let value = await processSecret(stored, encryptSecret);
258
+ if (value !== meta[key]) {
259
+ meta[key] = value;
260
+ routeUpdated = true;
261
+ }
262
+ }
263
+
264
+ if (routeUpdated) {
265
+ let result = await redis.hmset(`${REDIS_PREFIX}wh:c`, { [`${route}:meta`]: msgpack.encode(meta) });
266
+ if (result === 'OK') {
267
+ console.log(`Webhook route ${route}: updated`);
268
+ } else {
269
+ console.log(`Webhook route ${route}: Unexpected response from DB: ${result}`);
270
+ }
271
+ updatedRoutes++;
272
+ }
273
+ } catch (err) {
274
+ console.error(`Could not process encrypted values for webhook route ${route}. Check decryption secrets.`);
275
+ }
276
+ }
277
+
278
+ console.log(`Updated ${updatedRoutes}/${routes.length} webhook routes`);
279
+
252
280
  // TLS private keys managed by @postalsys/certs. These live in the module's own hash, not in the
253
281
  // EmailEngine settings hash, so they need their own pass - without it a rotation leaves the ACME
254
282
  // account key and every domain key readable only with the old secret, and TLS fails on the next
package/getswagger.sh CHANGED
@@ -4,10 +4,6 @@ set -e
4
4
 
5
5
  export EENGINE_PORT=5678
6
6
 
7
- # Keep the deprecated Document Store endpoints in the generated spec; they are only
8
- # registered when the feature is enabled.
9
- export EENGINE_DOCUMENT_STORE_ENABLED=true
10
-
11
7
  # refuse to run if something is already listening on the port, otherwise the
12
8
  # polling loop below would silently fetch swagger.json from a stale instance
13
9
  if (exec 3<>"/dev/tcp/127.0.0.1/${EENGINE_PORT}") 2>/dev/null; then
@@ -1,7 +1,6 @@
1
1
  'use strict';
2
2
 
3
3
  const Boom = require('@hapi/boom');
4
- const { REDIS_PREFIX } = require('../consts');
5
4
 
6
5
  // Account state constants
7
6
  const ACCOUNT_STATES = {
@@ -92,102 +91,6 @@ function validateAccountState(accountData) {
92
91
  throw error;
93
92
  }
94
93
 
95
- /**
96
- * Gets the account state from Redis
97
- * @param {Object} redis - Redis client
98
- * @param {string} account - Account ID
99
- * @returns {Promise<string|null>} The current state value
100
- */
101
- async function getAccountState(redis, account) {
102
- const accountKey = `${REDIS_PREFIX}iad:${account}`;
103
- return await redis.hget(accountKey, 'state');
104
- }
105
-
106
- /**
107
- * Sets the account state in Redis
108
- * Only updates if the account exists
109
- * @param {Object} redis - Redis client
110
- * @param {string} account - Account ID
111
- * @param {string} state - New state value
112
- * @returns {Promise<boolean>} True if state was set
113
- */
114
- async function setAccountState(redis, account, state) {
115
- const accountKey = `${REDIS_PREFIX}iad:${account}`;
116
- const result = await redis.hSetExists(accountKey, 'state', state);
117
- return result === 1;
118
- }
119
-
120
- /**
121
- * Gets the last error state for an account
122
- * @param {Object} redis - Redis client
123
- * @param {string} account - Account ID
124
- * @returns {Promise<Object|null>} Parsed error state object or null
125
- */
126
- async function getLastErrorState(redis, account) {
127
- const accountKey = `${REDIS_PREFIX}iad:${account}`;
128
- const errorState = await redis.hget(accountKey, 'lastErrorState');
129
-
130
- if (!errorState) {
131
- return null;
132
- }
133
-
134
- try {
135
- return JSON.parse(errorState);
136
- } catch (err) {
137
- return null;
138
- }
139
- }
140
-
141
- /**
142
- * Sets the last error state for an account
143
- * @param {Object} redis - Redis client
144
- * @param {string} account - Account ID
145
- * @param {Object} errorData - Error state data
146
- * @returns {Promise<boolean>} True if error state was set
147
- */
148
- async function setLastErrorState(redis, account, errorData) {
149
- const accountKey = `${REDIS_PREFIX}iad:${account}`;
150
- const result = await redis.hSetExists(accountKey, 'lastErrorState', JSON.stringify(errorData));
151
- return result === 1;
152
- }
153
-
154
- /**
155
- * Clears the last error state for an account
156
- * @param {Object} redis - Redis client
157
- * @param {string} account - Account ID
158
- * @returns {Promise<number>} Number of fields removed
159
- */
160
- async function clearLastErrorState(redis, account) {
161
- const accountKey = `${REDIS_PREFIX}iad:${account}`;
162
- return await redis.hdel(accountKey, 'lastErrorState');
163
- }
164
-
165
- /**
166
- * Gets the connection count for a specific state
167
- * @param {Object} redis - Redis client
168
- * @param {string} account - Account ID
169
- * @param {string} state - State to get count for
170
- * @returns {Promise<number>} Connection count
171
- */
172
- async function getStateCount(redis, account, state) {
173
- const accountKey = `${REDIS_PREFIX}iad:${account}`;
174
- const count = await redis.hget(accountKey, `state:count:${state}`);
175
- return parseInt(count, 10) || 0;
176
- }
177
-
178
- /**
179
- * Resets the connection count for a specific state
180
- * @param {Object} redis - Redis client
181
- * @param {string} account - Account ID
182
- * @param {string} state - State to reset count for
183
- * @returns {Promise<boolean>} True if count was reset
184
- */
185
- async function resetStateCount(redis, account, state) {
186
- const accountKey = `${REDIS_PREFIX}iad:${account}`;
187
- const result = await redis.hset(accountKey, `state:count:${state}`, '0');
188
- return result >= 0;
189
- }
190
-
191
94
  // A stored timestamp is only as good as whatever wrote it: a corrupt or hand-edited record must
192
95
  // degrade to null rather than fail the response schema and 500 the endpoint
193
96
  function isoOrNull(date) {
@@ -298,18 +201,7 @@ module.exports = {
298
201
  validateAccountState,
299
202
  getDisplayState,
300
203
 
301
- // Redis operations
302
- getAccountState,
303
- setAccountState,
304
-
305
- // Error state management
306
- getLastErrorState,
307
- setLastErrorState,
308
- clearLastErrorState,
204
+ // Error state formatting
309
205
  formatLastError,
310
- formatGmailWatch,
311
-
312
- // State counters
313
- getStateCount,
314
- resetStateCount
206
+ formatGmailWatch
315
207
  };
@@ -54,7 +54,7 @@ function matchesExpectedIdentity(expectedEmail, identities) {
54
54
  //
55
55
  // Redis is read lazily, only on that fallback: a pinned link would otherwise pay a round trip for a value
56
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().
57
+ // hgetalls and decrypts the whole record.
58
58
  // The expectation carried by a pending OAuth2 setup, whichever of the two shapes it arrives in.
59
59
  //
60
60
  // Both are written by the server for an authenticated caller and stored under a random nonce, so they are
@@ -67,4 +67,141 @@ function requeueFailedAccounts({ assigned, unassigned }, failedAccounts) {
67
67
  }
68
68
  }
69
69
 
70
- module.exports = { pickLeastLoadedWorker, rollbackAssignment, releaseWorkerAccounts, requeueFailedAccounts };
70
+ /**
71
+ * Drops every record of a deleted account: from unassigned, from `assigned`, and from the account
72
+ * set of the worker that held it. Leaving it in `assigned` kept a deleted account routed to a
73
+ * worker (possibly an exited one) for the life of the process and inflated the per-worker target
74
+ * of every later assignment pass
75
+ * @param {Object} state - `workerAssigned`, `assigned` and `unassigned` (false before the first load)
76
+ * @param {string} account
77
+ * @returns {Object|null} The worker that held the account, for the cleanup call, or null
78
+ */
79
+ function forgetAccount({ workerAssigned, assigned, unassigned }, account) {
80
+ if (unassigned) {
81
+ unassigned.delete(account);
82
+ }
83
+ if (!assigned.has(account)) {
84
+ return null;
85
+ }
86
+ const worker = assigned.get(account);
87
+ assigned.delete(account);
88
+ const accounts = workerAssigned.get(worker);
89
+ if (accounts) {
90
+ accounts.delete(account);
91
+ if (!accounts.size) {
92
+ workerAssigned.delete(worker);
93
+ }
94
+ }
95
+ return worker;
96
+ }
97
+
98
+ /**
99
+ * Whether an account whose `assign` call failed goes back to unassigned. An account that no longer
100
+ * exists fails deterministically on every pass, so it is dropped instead: either the worker said so
101
+ * (404), or the account is no longer registered, which also covers a delete that raced the pass.
102
+ * A failed membership check keeps the account, a lost retry costs more than a wasted one
103
+ * @param {Error} err - The error the assign call failed with
104
+ * @param {string} account
105
+ * @param {Function} isRegistered - async account -> boolean
106
+ * @returns {Promise<boolean>}
107
+ */
108
+ async function shouldRequeueFailedAssignment(err, account, isRegistered) {
109
+ if (err && err.statusCode === 404) {
110
+ return false;
111
+ }
112
+ try {
113
+ return !!(await isRegistered(account));
114
+ } catch {
115
+ return true;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Picks accounts to move onto a worker that joined after the fleet was already serving them (a
121
+ * worker that restarted after the failsafe reassignment gave its accounts to the survivors).
122
+ * Takes from the most loaded workers until the newcomer holds its fair share
123
+ * @param {Object} state - `workerAssigned` and `availableWorkers`
124
+ * @param {Object} targetWorker - The worker that joined
125
+ * @returns {Array<{account: string, worker: Object}>} Accounts to move, with their current worker
126
+ */
127
+ function planRebalance({ workerAssigned, availableWorkers }, targetWorker) {
128
+ const loads = new Map();
129
+ let total = 0;
130
+ for (const worker of availableWorkers) {
131
+ const size = workerAssigned.get(worker)?.size || 0;
132
+ loads.set(worker, size);
133
+ total += size;
134
+ }
135
+ if (!loads.has(targetWorker) || loads.size < 2) {
136
+ return [];
137
+ }
138
+
139
+ const share = Math.floor(total / loads.size);
140
+ const taken = new Map();
141
+ const moves = [];
142
+ while (loads.get(targetWorker) < share) {
143
+ let donor = null;
144
+ for (const [worker, size] of loads) {
145
+ if (worker !== targetWorker && (!donor || size > loads.get(donor))) {
146
+ donor = worker;
147
+ }
148
+ }
149
+ // Stop once moving an account would only shift the imbalance to the donor
150
+ if (!donor || loads.get(donor) - 1 < loads.get(targetWorker) + 1) {
151
+ break;
152
+ }
153
+ if (!taken.has(donor)) {
154
+ taken.set(donor, workerAssigned.get(donor).values());
155
+ }
156
+ const next = taken.get(donor).next();
157
+ if (next.done) {
158
+ break;
159
+ }
160
+ moves.push({ account: next.value, worker: donor });
161
+ loads.set(donor, loads.get(donor) - 1);
162
+ loads.set(targetWorker, loads.get(targetWorker) + 1);
163
+ }
164
+ return moves;
165
+ }
166
+
167
+ /**
168
+ * Runs `fn` over `items` with at most `limit` calls in flight and resolves with the results in
169
+ * item order once every call has settled. Rejects with the first failure, like Promise.all, but
170
+ * only after the calls already in flight have settled, so a caller never has calls outstanding
171
+ * it does not know about
172
+ * @param {Array} items
173
+ * @param {number} limit - Calls in flight at once
174
+ * @param {Function} fn - async (item, index) -> result
175
+ * @returns {Promise<Array>}
176
+ */
177
+ async function mapConcurrent(items, limit, fn) {
178
+ const results = new Array(items.length);
179
+ let next = 0;
180
+ let failure = null;
181
+ const runner = async () => {
182
+ while (next < items.length && !failure) {
183
+ const index = next++;
184
+ try {
185
+ results[index] = await fn(items[index], index);
186
+ } catch (err) {
187
+ failure = failure || err;
188
+ }
189
+ }
190
+ };
191
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, runner));
192
+ if (failure) {
193
+ throw failure;
194
+ }
195
+ return results;
196
+ }
197
+
198
+ module.exports = {
199
+ pickLeastLoadedWorker,
200
+ rollbackAssignment,
201
+ releaseWorkerAccounts,
202
+ requeueFailedAccounts,
203
+ forgetAccount,
204
+ shouldRequeueFailedAssignment,
205
+ planRebalance,
206
+ mapConcurrent
207
+ };