emailengine-app 2.81.1 → 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 (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  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/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. package/workers/documents.js +0 -1128
@@ -44,13 +44,52 @@ function recordTokenMetric(status, provider, statusCode) {
44
44
  }
45
45
 
46
46
  const { OutlookOauth, outlookScopes } = require('./oauth/outlook');
47
- const { GmailOauth, GMAIL_SCOPES } = require('./oauth/gmail');
47
+ const { GmailOauth, GMAIL_SCOPES, parseExternalAccountConfig } = require('./oauth/gmail');
48
+ const { ExternalAccountSigner } = require('./oauth/external-account-signer');
49
+ const crypto = require('crypto');
48
50
  const { MailRuOauth, MAIL_RU_SCOPES } = require('./oauth/mail-ru');
49
51
 
50
52
  // Historical app IDs of the retired settings-based OAuth2 configuration. Only used by
51
53
  // migrateLegacyApps(); migrated apps keep these IDs, but are otherwise regular apps.
52
54
  const LEGACY_KEYS = ['gmail', 'gmailService', 'outlook', 'mailRu'];
53
55
 
56
+ // A successful API request clears the app's auth flag. Checking for one costs a Redis read, so a
57
+ // client checks at most this often; setting a flag is never throttled
58
+ const AUTH_FLAG_CLEAR_INTERVAL = 60 * 1000;
59
+
60
+ // When each app's auth flag was last checked for clearing, keyed by app id. Kept here rather
61
+ // than in the client's closure because a token renewal builds a new client every time, and the
62
+ // first successful request of every one of them then read the meta blob again. Entries are
63
+ // dropped when the app is deleted
64
+ const authFlagClearChecks = new Map();
65
+
66
+ // Used when a token response carries no usable expires_in (Google's service tokens live an hour)
67
+ const DEFAULT_SERVICE_TOKEN_TTL = 3600;
68
+
69
+ // Workload Identity Federation signers, per app id. The signer caches the federated token and
70
+ // deduplicates concurrent refreshes, which only helps when it outlives the GmailOauth client
71
+ // built for each token renewal: without this every account ran its own STS exchange every hour.
72
+ // Keyed on a hash of the configuration so a changed one is never served from the cache, and
73
+ // dropped on app update and delete
74
+ const externalAccountSigners = new Map();
75
+
76
+ function getExternalAccountSigner(id, externalAccount) {
77
+ let source = typeof externalAccount === 'string' ? externalAccount : JSON.stringify(externalAccount);
78
+ let hash = crypto.createHash('sha256').update(source).digest('hex');
79
+
80
+ let cached = externalAccountSigners.get(id);
81
+ if (cached && cached.hash === hash) {
82
+ return cached.signer;
83
+ }
84
+
85
+ let signer = new ExternalAccountSigner({
86
+ config: parseExternalAccountConfig(externalAccount),
87
+ logger: logger.child({ component: 'external-account-signer', app: id })
88
+ });
89
+ externalAccountSigners.set(id, { hash, signer });
90
+ return signer;
91
+ }
92
+
54
93
  const PUBSUB_PERM_MANAGE = 'Service client does not have permission to manage Pub/Sub topics. Grant the service user the "Pub/Sub Admin" role.';
55
94
  const PUBSUB_PERM_VIEW = 'Service client does not have permission to view Pub/Sub topics. Grant the service user the "Pub/Sub Admin" role.';
56
95
 
@@ -750,6 +789,12 @@ class OAuth2AppsHandler {
750
789
 
751
790
  let existingData = msgpack.decode(existingDataBuf);
752
791
 
792
+ // The next client is built from the updated configuration. Not on the partial writes that
793
+ // store a renewed service token: the cache key already covers a changed configuration
794
+ if (!opts.partial || (data && 'externalAccount' in data)) {
795
+ externalAccountSigners.delete(id);
796
+ }
797
+
753
798
  // The authentication method is fixed once an app has been configured with
754
799
  // a credential - never allow switching between serviceKey and externalAccount
755
800
  // (WIF). Pin the stored method, ignoring any incoming change.
@@ -820,6 +865,9 @@ class OAuth2AppsHandler {
820
865
  }
821
866
 
822
867
  async del(id) {
868
+ externalAccountSigners.delete(id);
869
+ authFlagClearChecks.delete(id);
870
+
823
871
  let appData = await this.get(id);
824
872
 
825
873
  if (!appData) {
@@ -944,13 +992,87 @@ class OAuth2AppsHandler {
944
992
  return flags;
945
993
  }
946
994
 
995
+ /**
996
+ * The setFlag callback handed to a provider client. The client calls it with no flag after
997
+ * every successful request, which used to read and rewrite the whole shared meta blob each
998
+ * time: two extra round trips per API call on one hot key, and a window for losing a
999
+ * concurrent pubSubFlag or ttlWarning write. Clearing now happens only when a flag is actually
1000
+ * set, and is checked at most once per AUTH_FLAG_CLEAR_INTERVAL per app
1001
+ * @param {string} id - App ID
1002
+ * @param {string} provider - Provider name for logging
1003
+ * @returns {Function} async flag => void, never throws
1004
+ */
1005
+ createFlagSetter(id, provider) {
1006
+ return async flag => {
1007
+ try {
1008
+ if (flag) {
1009
+ authFlagClearChecks.delete(id);
1010
+ await this.setMeta(id, { authFlag: flag });
1011
+ return;
1012
+ }
1013
+ let now = Date.now();
1014
+ if (now - (authFlagClearChecks.get(id) || 0) < AUTH_FLAG_CLEAR_INTERVAL) {
1015
+ return;
1016
+ }
1017
+ authFlagClearChecks.set(id, now);
1018
+ await this.clearAuthFlag(id);
1019
+ } catch (err) {
1020
+ // Log but don't throw - flag setting is non-critical
1021
+ logger.error({ msg: 'Failed to set OAuth flag', app: id, provider, err });
1022
+ }
1023
+ };
1024
+ }
1025
+
1026
+ /**
1027
+ * Reads the meta blob of an app (auth flag, pubsub flag, ttl warning)
1028
+ * @param {string} id - App ID
1029
+ * @returns {Promise<Object|null>} the decoded meta, an empty object when there is none, null
1030
+ * when the stored blob cannot be decoded
1031
+ */
1032
+ async readMeta(id) {
1033
+ let existingMetaBuf = await this.redis.hgetBuffer(this.getDataKey(), `${id}:meta`);
1034
+ if (!existingMetaBuf) {
1035
+ return {};
1036
+ }
1037
+ try {
1038
+ return msgpack.decode(existingMetaBuf) || {};
1039
+ } catch (err) {
1040
+ // an unreadable blob is replaced by the next write rather than blocking every later flag update
1041
+ logger.error({ msg: 'Failed to process app meta, replacing it', app: id, entryLength: existingMetaBuf.length, err });
1042
+ return null;
1043
+ }
1044
+ }
1045
+
1046
+ /**
1047
+ * Clears the auth flag of an app, writing only when one is set
1048
+ * @param {string} id - App ID
1049
+ * @returns {Promise<boolean>} true if a flag was cleared
1050
+ */
1051
+ async clearAuthFlag(id) {
1052
+ let existingMeta = await this.readMeta(id);
1053
+ if (existingMeta && !existingMeta.authFlag) {
1054
+ return false;
1055
+ }
1056
+ await this.setMeta(id, { authFlag: null }, existingMeta);
1057
+ return true;
1058
+ }
1059
+
1060
+ // Drops the cached service access token of an app, so the next request fetches a new one.
1061
+ // Used when the API refused the cached token before its recorded expiry
1062
+ async invalidateServiceAccessToken(id) {
1063
+ await this.update(id, { accessToken: null, accessTokenExpires: null }, { partial: true });
1064
+ }
1065
+
947
1066
  // Note: not atomic (read-modify-write). Concurrent callers use last-write-wins,
948
1067
  // which is acceptable for self-correcting informational metadata.
949
- async setMeta(id, meta) {
950
- let existingMetaBuf = await this.redis.hgetBuffer(this.getDataKey(), `${id}:meta`);
951
- let existingMeta = existingMetaBuf ? msgpack.decode(existingMetaBuf) : {};
1068
+ // @param {Object} [existingMeta] - The meta as readMeta() returned it, when the caller has
1069
+ // just read it; otherwise it is read here
1070
+ async setMeta(id, meta, existingMeta) {
1071
+ if (existingMeta === undefined) {
1072
+ existingMeta = await this.readMeta(id);
1073
+ }
952
1074
 
953
- let entry = Object.assign(existingMeta, meta || {});
1075
+ let entry = Object.assign(existingMeta || {}, meta || {});
954
1076
 
955
1077
  await this.redis.hmset(this.getDataKey(), {
956
1078
  [`${id}:meta`]: msgpack.encode(entry)
@@ -1563,14 +1685,7 @@ class OAuth2AppsHandler {
1563
1685
  scopes,
1564
1686
  googleProjectId,
1565
1687
  workspaceAccounts,
1566
- setFlag: async flag => {
1567
- try {
1568
- await this.setMeta(id, { authFlag: flag });
1569
- } catch (err) {
1570
- // Log but don't throw - flag setting is non-critical
1571
- logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'gmail', err });
1572
- }
1573
- }
1688
+ setFlag: this.createFlagSetter(id, 'gmail')
1574
1689
  },
1575
1690
  extraOpts
1576
1691
  )
@@ -1603,18 +1718,12 @@ class OAuth2AppsHandler {
1603
1718
  authMethod,
1604
1719
  serviceKey,
1605
1720
  externalAccount,
1721
+ externalAccountSigner: authMethod === 'externalAccount' ? getExternalAccountSigner(id, externalAccount) : undefined,
1606
1722
  googleProjectId,
1607
1723
  serviceClientEmail,
1608
1724
  scopes,
1609
1725
  workspaceAccounts,
1610
- setFlag: async flag => {
1611
- try {
1612
- await this.setMeta(id, { authFlag: flag });
1613
- } catch (err) {
1614
- // Log but don't throw - flag setting is non-critical
1615
- logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'gmailService', err });
1616
- }
1617
- }
1726
+ setFlag: this.createFlagSetter(id, 'gmailService')
1618
1727
  },
1619
1728
  extraOpts
1620
1729
  )
@@ -1645,14 +1754,7 @@ class OAuth2AppsHandler {
1645
1754
  redirectUrl,
1646
1755
  scopes,
1647
1756
  cloud,
1648
- setFlag: async flag => {
1649
- try {
1650
- await this.setMeta(id, { authFlag: flag });
1651
- } catch (err) {
1652
- // Log but don't throw - flag setting is non-critical
1653
- logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'outlook', err });
1654
- }
1655
- }
1757
+ setFlag: this.createFlagSetter(id, 'outlook')
1656
1758
  },
1657
1759
  extraOpts
1658
1760
  )
@@ -1681,13 +1783,7 @@ class OAuth2AppsHandler {
1681
1783
  cloud,
1682
1784
  provider: 'outlookService',
1683
1785
  useClientCredentials: true,
1684
- setFlag: async flag => {
1685
- try {
1686
- await this.setMeta(id, { authFlag: flag });
1687
- } catch (err) {
1688
- logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'outlookService', err });
1689
- }
1690
- }
1786
+ setFlag: this.createFlagSetter(id, 'outlookService')
1691
1787
  },
1692
1788
  extraOpts
1693
1789
  )
@@ -1712,14 +1808,7 @@ class OAuth2AppsHandler {
1712
1808
  clientSecret,
1713
1809
  redirectUrl,
1714
1810
  scopes,
1715
- setFlag: async flag => {
1716
- try {
1717
- await this.setMeta(id, { authFlag: flag });
1718
- } catch (err) {
1719
- // Log but don't throw - flag setting is non-critical
1720
- logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'mailRu', err });
1721
- }
1722
- }
1811
+ setFlag: this.createFlagSetter(id, 'mailRu')
1723
1812
  },
1724
1813
  extraOpts
1725
1814
  )
@@ -1781,6 +1870,12 @@ class OAuth2AppsHandler {
1781
1870
  // create new
1782
1871
  let isPrincipal = true;
1783
1872
  let { access_token: accessToken, expires_in: expiresIn } = await client.refreshToken({ isPrincipal });
1873
+ // A response without a numeric expires_in made the expiry an Invalid Date, and
1874
+ // toISOString() below threw a RangeError after a successful renewal
1875
+ expiresIn = Number(expiresIn);
1876
+ if (!Number.isFinite(expiresIn) || expiresIn <= 0) {
1877
+ expiresIn = DEFAULT_SERVICE_TOKEN_TTL;
1878
+ }
1784
1879
  let expires = new Date(now + expiresIn * 1000);
1785
1880
  if (!accessToken) {
1786
1881
  recordTokenMetric('failure', appData.provider || 'unknown', '0');
@@ -81,7 +81,7 @@ function assignVendorExtensions(target, source) {
81
81
 
82
82
  class DocumentBuilder {
83
83
  constructor() {
84
- this.converter = new SchemaConverter();
84
+ this.converter = new SchemaConverter({ sentinelBranches: true });
85
85
  }
86
86
 
87
87
  /**
@@ -29,6 +29,10 @@ const Joi = require('joi');
29
29
 
30
30
  const SCHEMA_REF_PREFIX = '#/components/schemas/';
31
31
 
32
+ // Where parseEnum() parks allowed values whose JSON type differs from the schema's, until
33
+ // parseProperty() has the finished schema to put them beside
34
+ const FOREIGN_VALUES = Symbol('foreignValues');
35
+
32
36
  // joi type to the OpenAPI type it starts out as. `alternatives` is not an OpenAPI type; it is a
33
37
  // marker that gets replaced by `anyOf` once the branches are known.
34
38
  //
@@ -141,7 +145,16 @@ function regexSource(value) {
141
145
  }
142
146
 
143
147
  class SchemaConverter {
144
- constructor() {
148
+ /**
149
+ * @param {Object} [options]
150
+ * @param {Boolean} [options.sentinelBranches=false] - publish an allowed value of another JSON
151
+ * type (`.allow(false)` on an object) as its own anyOf branch rather than in the enum.
152
+ * The OpenAPI document turns it on; lib/mcp/json-schema.js does its own split into
153
+ * `const` branches from the enum form and leaves it off.
154
+ */
155
+ constructor(options) {
156
+ this.sentinelBranches = !!(options && options.sentinelBranches);
157
+
145
158
  // Named schemas, keyed by the name a $ref points at
146
159
  this.definitions = {};
147
160
 
@@ -185,7 +198,7 @@ class SchemaConverter {
185
198
  }
186
199
 
187
200
  // A forbidden key exists only to be rejected, and swaggerHidden is how a schema opts out of
188
- // the public document (deprecated Document Store fields use it). Both must not appear.
201
+ // the public document. Both must not appear.
189
202
  if (flag(description, 'presence') === 'forbidden' || metaValue(description, 'swaggerHidden') === true) {
190
203
  return undefined;
191
204
  }
@@ -209,6 +222,10 @@ class SchemaConverter {
209
222
  property = this.parseMetadata(property, description);
210
223
  property = this.parseEnum(property, description);
211
224
 
225
+ // Allowed values of another JSON type than the schema's own, set aside by parseEnum()
226
+ const foreignValues = property[FOREIGN_VALUES];
227
+ delete property[FOREIGN_VALUES];
228
+
212
229
  if (property.type === 'string') {
213
230
  property = this.parseString(property, description);
214
231
  }
@@ -241,13 +258,47 @@ class SchemaConverter {
241
258
 
242
259
  // A named schema is registered once and referenced everywhere it is used. Scalars are inlined,
243
260
  // except for a set of allowed strings: that is worth a schema of its own so every operation
244
- // accepting it points at the same list. A numeric `enum` is not the same thing - it comes from
245
- // `.allow(false)` on a number, which is a sentinel value rather than a named vocabulary.
246
- if (context.useDefinitions && (['object', 'array'].includes(property.type) || (property.type === 'string' && property.enum))) {
247
- return { $ref: SCHEMA_REF_PREFIX + this.append(name, deleteEmptyProperties(property)) };
261
+ // accepting it points at the same list. A string whose only allowed value is a sentinel of
262
+ // another type stays a named schema too: it was one before the sentinel moved out of its
263
+ // enum, and a label is a public type name.
264
+ if (context.useDefinitions && (['object', 'array'].includes(property.type) || (property.type === 'string' && (property.enum || foreignValues)))) {
265
+ return this.withForeignValues({ $ref: SCHEMA_REF_PREFIX + this.append(name, deleteEmptyProperties(property)) }, foreignValues);
266
+ }
267
+
268
+ return this.withForeignValues(deleteEmptyProperties(property), foreignValues);
269
+ }
270
+
271
+ // `.allow(false)` on an object, a string or a number is how the schemas say "or false to clear
272
+ // it". Written as `enum: [false]` on the typed schema it described a value no JSON document can
273
+ // be (an object that is also one of [false]), so strict validators and generated clients refused
274
+ // real configurations. The sentinel becomes its own branch instead.
275
+ withForeignValues(schema, values) {
276
+ if (!values || !values.length) {
277
+ return schema;
278
+ }
279
+
280
+ const branches = [schema];
281
+ for (const type of ['boolean', 'number', 'string']) {
282
+ const group = values.filter(value => typeof value === type);
283
+ if (group.length) {
284
+ branches.push({ type, enum: group });
285
+ }
286
+ }
287
+
288
+ const wrapped = { anyOf: branches };
289
+
290
+ // Describing the value as a whole, so it stays on the property a reader looks at rather
291
+ // than inside the first branch. A $ref carries its own in the component.
292
+ if (!schema.$ref) {
293
+ for (const key of ['description', 'x-meta']) {
294
+ if (schema[key] !== undefined) {
295
+ wrapped[key] = schema[key];
296
+ delete schema[key];
297
+ }
298
+ }
248
299
  }
249
300
 
250
- return deleteEmptyProperties(property);
301
+ return wrapped;
251
302
  }
252
303
 
253
304
  // Records the child's name in the parent's `required` array. A `.when()` branch that makes the
@@ -340,8 +391,26 @@ class SchemaConverter {
340
391
  }
341
392
 
342
393
  const values = allowed.filter(value => value !== '' && value !== null);
343
- if (values.length) {
344
- property.enum = values;
394
+
395
+ // A primitive of another JSON type than the schema's own can not sit in its enum (see
396
+ // withForeignValues()). Only primitives: anything else keeps the historical behaviour.
397
+ // A joi `any` is published as a string for historical reasons, but really accepts anything,
398
+ // so its allowed values are left where they were.
399
+ const jsonType =
400
+ !this.sentinelBranches || ['any', 'function'].includes(description.type)
401
+ ? null
402
+ : { string: 'string', number: 'number', boolean: 'boolean', object: 'object', array: 'array' }[property.type];
403
+ const isForeign = value => jsonType && ['boolean', 'number', 'string'].includes(typeof value) && typeof value !== jsonType;
404
+
405
+ const own = values.filter(value => !isForeign(value));
406
+ const foreign = values.filter(isForeign);
407
+
408
+ if (own.length) {
409
+ property.enum = own;
410
+ }
411
+
412
+ if (foreign.length) {
413
+ property[FOREIGN_VALUES] = foreign;
345
414
  }
346
415
 
347
416
  if (allowed.includes(null)) {
@@ -0,0 +1,21 @@
1
+ 'use strict';
2
+
3
+ // Every message EmailEngine parses with mailparser is parsed here, so an option every parse needs
4
+ // is set once. test/fips-guardrail-test.js refuses a simpleParser() call anywhere else.
5
+ //
6
+ // checksumAlgo: mailparser hashes every attachment, with MD5 unless told otherwise, and an OpenSSL
7
+ // FIPS provider refuses MD5. Nothing in EmailEngine reads the checksum, so the algorithm only has
8
+ // to exist on every host.
9
+
10
+ const { simpleParser } = require('mailparser');
11
+
12
+ /**
13
+ * @param {Buffer|String|Stream} input - The message source
14
+ * @param {Object} [options] - mailparser options, applied over the defaults
15
+ * @returns {Promise<Object>} The parsed message
16
+ */
17
+ function parseMessage(input, options) {
18
+ return simpleParser(input, { checksumAlgo: 'sha256', ...options });
19
+ }
20
+
21
+ module.exports = { parseMessage };
@@ -90,15 +90,16 @@
90
90
  "category": "primary",
91
91
  "messageSpecialUse": "\\Inbox",
92
92
  "summary": {
93
- "id": "chatcmpl-7IzVIEp5UL3hdQ3aZJ8AHyrJrt3R0",
94
- "tokens": 2060,
95
- "model": "gpt-4",
96
93
  "sentiment": "positive",
97
94
  "summary": "Request to contribute 2 to 5 euros for flowers for choir teachers and concertmaster, with excess funds used for a bouquet for the class teacher at end of the year.",
98
95
  "shouldReply": true,
96
+ "riskAssessment": {
97
+ "risk": 1
98
+ },
99
99
  "events": [
100
100
  {
101
101
  "description": "Flower bouquets for choir teachers and concertmaster",
102
+ "type": "event",
102
103
  "startTime": "2023-05-22"
103
104
  }
104
105
  ],
@@ -109,10 +110,6 @@
109
110
  }
110
111
  ]
111
112
  },
112
- "riskAssessment": {
113
- "risk": 1,
114
- "assessment": "Sender information matches and authentication checks have passed."
115
- },
116
113
  "threadId": "617dd693-d78b-48df-bc20-6330a5b1fa85"
117
114
  }
118
115
  }
@@ -0,0 +1,101 @@
1
+ 'use strict';
2
+
3
+ // Admin password hashing in the PHC string format, on Node's own crypto. Replaces @phc/pbkdf2
4
+ // (unmaintained since 2018) and stays byte-compatible with every hash that package stored:
5
+ //
6
+ // $pbkdf2-<digest>$i=<iterations>$<salt>$<hash>
7
+ //
8
+ // with the salt and the derived key in standard base64 without padding. A hash written by an
9
+ // earlier release, or handed in through EENGINE_PREPARED_PASSWORD, keeps verifying, and a hash
10
+ // written here verifies on an earlier release. test/pbkdf2-phc-test.js pins hashes the old
11
+ // package produced.
12
+
13
+ const crypto = require('crypto');
14
+ const { promisify } = require('util');
15
+ const { PDKDF2_ITERATIONS, PDKDF2_SALT_SIZE, PDKDF2_DIGEST } = require('./consts');
16
+
17
+ const pbkdf2 = promisify(crypto.pbkdf2);
18
+
19
+ // Derived key length per digest: the digest's own output size, as the old package used
20
+ const DIGESTS = { sha1: 20, sha256: 32, sha512: 64 };
21
+ const MAX_UINT32 = 2 ** 32 - 1;
22
+ const MAX_SALT_SIZE = 1024;
23
+
24
+ // Only the four-field form pbkdf2 hashes take. A version field, padded base64 or a foreign
25
+ // identifier is a malformed string, which the caller treats as a failed check
26
+ const PHC_RE = /^\$pbkdf2-([a-z0-9]+)\$i=(0|[1-9][0-9]*)\$([A-Za-z0-9+/]+)\$([A-Za-z0-9+/]+)$/;
27
+
28
+ function b64(buf) {
29
+ return buf.toString('base64').replace(/=+$/, '');
30
+ }
31
+
32
+ function digestKeyLength(digest) {
33
+ if (!Object.prototype.hasOwnProperty.call(DIGESTS, digest)) {
34
+ throw new TypeError(`Unsupported ${digest} digest function`);
35
+ }
36
+ return DIGESTS[digest];
37
+ }
38
+
39
+ /**
40
+ * Hashes a password into a PHC string. The defaults are the values EmailEngine has always
41
+ * used for the admin password (lib/consts.js).
42
+ *
43
+ * @param {string} password
44
+ * @param {object} [options]
45
+ * @param {number} [options.iterations]
46
+ * @param {number} [options.saltSize] - Salt length in bytes
47
+ * @param {string} [options.digest] - sha1, sha256 or sha512
48
+ * @returns {Promise<string>}
49
+ */
50
+ async function hash(password, options) {
51
+ let { iterations = PDKDF2_ITERATIONS, saltSize = PDKDF2_SALT_SIZE, digest = PDKDF2_DIGEST } = options || {};
52
+
53
+ if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_UINT32) {
54
+ throw new TypeError(`The 'iterations' option must be an integer in the range (1 <= iterations <= ${MAX_UINT32})`);
55
+ }
56
+ if (!Number.isInteger(saltSize) || saltSize < 1 || saltSize > MAX_SALT_SIZE) {
57
+ throw new TypeError(`The 'saltSize' option must be an integer in the range (1 <= saltSize <= ${MAX_SALT_SIZE})`);
58
+ }
59
+ digest = String(digest).toLowerCase();
60
+ let keyLength = digestKeyLength(digest);
61
+
62
+ let salt = crypto.randomBytes(saltSize);
63
+ let key = await pbkdf2(password, salt, iterations, keyLength, digest);
64
+
65
+ return `$pbkdf2-${digest}$i=${iterations}$${b64(salt)}$${b64(key)}`;
66
+ }
67
+
68
+ /**
69
+ * Checks a password against a PHC string. Resolves false for a wrong password and rejects for
70
+ * a string that is not a pbkdf2 PHC hash at all, the same contract the old package had.
71
+ *
72
+ * @param {string} phcString
73
+ * @param {string} password
74
+ * @returns {Promise<boolean>}
75
+ */
76
+ async function verify(phcString, password) {
77
+ let match = typeof phcString === 'string' ? PHC_RE.exec(phcString) : null;
78
+ if (!match) {
79
+ throw new TypeError('Not a pbkdf2 PHC string');
80
+ }
81
+
82
+ let [, digest, iterationsValue, saltValue, hashValue] = match;
83
+ digestKeyLength(digest);
84
+
85
+ let iterations = Number(iterationsValue);
86
+ if (iterations < 1 || iterations > MAX_UINT32) {
87
+ throw new TypeError(`The 'i' param must be in the range (1 <= i <= ${MAX_UINT32})`);
88
+ }
89
+
90
+ let salt = Buffer.from(saltValue, 'base64');
91
+ let expected = Buffer.from(hashValue, 'base64');
92
+ if (!expected.length) {
93
+ // an empty derived key would compare equal to an empty expected key for any password
94
+ throw new TypeError('No hash found in the given string');
95
+ }
96
+
97
+ let derived = await pbkdf2(password, salt, iterations, expected.length, digest);
98
+ return crypto.timingSafeEqual(derived, expected);
99
+ }
100
+
101
+ module.exports = { hash, verify };
@@ -115,20 +115,6 @@ const PRIVILEGED_SETTINGS_GROUPS = [
115
115
  label: 'the MCP and audit switches',
116
116
  keys: ['mcpEnabled', 'mcpOAuthEnabled', 'tokenAuditLog']
117
117
  },
118
- {
119
- // The deprecated Document Store's endpoint and credentials
120
- label: 'the Document Store',
121
- keys: [
122
- 'documentStoreEnabled',
123
- 'documentStoreUrl',
124
- 'documentStoreIndex',
125
- 'documentStoreAuthEnabled',
126
- 'documentStoreUsername',
127
- 'documentStorePassword',
128
- 'documentStoreGenerateEmbeddings',
129
- 'documentStorePreProcessingEnabled'
130
- ]
131
- },
132
118
  {
133
119
  // The error reporting target
134
120
  label: 'error reporting',