emailengine-app 2.81.2 → 2.82.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/.ncurc.js +33 -10
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +71 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/Dockerfile +2 -0
  6. package/bin/emailengine.js +105 -25
  7. package/config/default.toml +0 -5
  8. package/config/test.toml +0 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +70 -42
  11. package/getswagger.sh +0 -4
  12. package/lib/account/account-state.js +2 -110
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +138 -1
  15. package/lib/account.js +289 -869
  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-binding.js +58 -0
  19. package/lib/api-routes/account-routes.js +65 -37
  20. package/lib/api-routes/behavior-notes.js +4 -0
  21. package/lib/api-routes/blocklist-routes.js +2 -2
  22. package/lib/api-routes/bull-board-routes.js +1 -6
  23. package/lib/api-routes/export-routes.js +2 -22
  24. package/lib/api-routes/gateway-routes.js +15 -16
  25. package/lib/api-routes/index.js +1 -13
  26. package/lib/api-routes/mailbox-routes.js +2 -7
  27. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  28. package/lib/api-routes/mcp-routes.js +7 -7
  29. package/lib/api-routes/message-routes.js +50 -238
  30. package/lib/api-routes/mint-bounds.js +110 -0
  31. package/lib/api-routes/oauth2-app-routes.js +23 -32
  32. package/lib/api-routes/operation-impact.js +1 -1
  33. package/lib/api-routes/outbox-routes.js +3 -3
  34. package/lib/api-routes/permission-map.js +1 -7
  35. package/lib/api-routes/route-helpers.js +11 -5
  36. package/lib/api-routes/settings-routes.js +20 -21
  37. package/lib/api-routes/stats-routes.js +1 -1
  38. package/lib/api-routes/submit-routes.js +17 -18
  39. package/lib/api-routes/template-routes.js +4 -9
  40. package/lib/api-routes/token-routes.js +28 -6
  41. package/lib/api-token-scheme.js +71 -0
  42. package/lib/arf-detect.js +33 -6
  43. package/lib/auth-token.js +44 -24
  44. package/lib/autodetect-imap-settings.js +305 -123
  45. package/lib/bounce-detect.js +25 -16
  46. package/lib/calendar-event.js +78 -0
  47. package/lib/consts.js +54 -5
  48. package/lib/create-imap-client.js +24 -0
  49. package/lib/db.js +77 -30
  50. package/lib/delivery-error.js +70 -2
  51. package/lib/egress-fetch.js +54 -3
  52. package/lib/egress-filter.js +11 -0
  53. package/lib/email-client/api-retry.js +147 -0
  54. package/lib/email-client/base-client.js +383 -536
  55. package/lib/email-client/credential-errors.js +21 -5
  56. package/lib/email-client/gmail/gmail-api.js +38 -125
  57. package/lib/email-client/gmail/send-request.js +1 -1
  58. package/lib/email-client/gmail-client.js +77 -51
  59. package/lib/email-client/imap/mailbox.js +158 -324
  60. package/lib/email-client/imap/stale-view.js +109 -0
  61. package/lib/email-client/imap/subconnection.js +46 -9
  62. package/lib/email-client/imap/sync-operations.js +5 -37
  63. package/lib/email-client/imap-client.js +190 -65
  64. package/lib/email-client/message-builder.js +50 -25
  65. package/lib/email-client/notification-handler.js +5 -219
  66. package/lib/email-client/outlook/graph-api.js +147 -126
  67. package/lib/email-client/outlook/send-request.js +10 -4
  68. package/lib/email-client/outlook-client.js +389 -463
  69. package/lib/email-client/smtp-pool-manager.js +3 -2
  70. package/lib/encrypt.js +184 -19
  71. package/lib/enum-descriptions.js +6 -3
  72. package/lib/export.js +141 -41
  73. package/lib/gateway.js +25 -6
  74. package/lib/get-raw-email.js +26 -44
  75. package/lib/get-secret.js +1 -21
  76. package/lib/handlebars-helpers.js +31 -10
  77. package/lib/imap-proxy-auth.js +13 -29
  78. package/lib/imapproxy/imap-core/README.md +1 -0
  79. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  80. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  81. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  82. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  83. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  84. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  85. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  86. package/lib/imapproxy/imap-server.js +17 -177
  87. package/lib/imapproxy/proxy-handoff.js +235 -0
  88. package/lib/imapproxy/response-error.js +33 -0
  89. package/lib/imapproxy/upstream-client.js +2 -2
  90. package/lib/license-beacon.js +3 -9
  91. package/lib/llm-pre-process.js +182 -43
  92. package/lib/logger.js +1 -1
  93. package/lib/lua/ee-export-queue-add.lua +39 -0
  94. package/lib/lua/ee-get-idempotency.lua +15 -3
  95. package/lib/lua/ee-release-attempts.lua +23 -0
  96. package/lib/lua/ee-reserve-attempts.lua +42 -0
  97. package/lib/lua/h-set-bigger.lua +12 -2
  98. package/lib/lua/s-list-accounts.lua +6 -3
  99. package/lib/mcp/index.js +1 -2
  100. package/lib/mcp/listen.js +221 -18
  101. package/lib/mcp/oauth.js +44 -5
  102. package/lib/mcp/resources.js +8 -2
  103. package/lib/mcp/tools.js +108 -36
  104. package/lib/message-port-stream.js +64 -6
  105. package/lib/oauth/external-account-signer.js +16 -13
  106. package/lib/oauth/gmail.js +64 -32
  107. package/lib/oauth/mail-ru.js +24 -17
  108. package/lib/oauth/outlook.js +53 -40
  109. package/lib/oauth/pubsub/google.js +38 -2
  110. package/lib/oauth/scope-checker.js +39 -8
  111. package/lib/oauth/scope-list.js +55 -0
  112. package/lib/oauth/token-fetch.js +47 -0
  113. package/lib/oauth/verify-app.js +2 -2
  114. package/lib/oauth2-apps.js +154 -90
  115. package/lib/openapi/build-document.js +1 -1
  116. package/lib/openapi/joi-schema.js +78 -9
  117. package/lib/outbox.js +2 -7
  118. package/lib/parse-message.js +21 -0
  119. package/lib/payload-examples-webhooks.json +4 -7
  120. package/lib/pbkdf2-phc.js +101 -0
  121. package/lib/privileged-settings.js +0 -14
  122. package/lib/queue-retention.js +4 -2
  123. package/lib/rate-limit.js +54 -15
  124. package/lib/read-env-value.js +33 -2
  125. package/lib/redis-scan-delete.js +56 -29
  126. package/lib/redis-url.js +3 -1
  127. package/lib/respawn-backoff.js +5 -4
  128. package/lib/response-stream.js +25 -4
  129. package/lib/rewrite-text-nodes.js +27 -40
  130. package/lib/routes-ui.js +0 -5
  131. package/lib/schemas.js +180 -253
  132. package/lib/sentry.js +21 -5
  133. package/lib/settings.js +58 -59
  134. package/lib/smtp-auth.js +6 -2
  135. package/lib/smtp-message-processor.js +28 -7
  136. package/lib/sso.js +7 -3
  137. package/lib/stream-encrypt.js +14 -13
  138. package/lib/swagger-options.js +3 -1
  139. package/lib/tls/provision.js +69 -3
  140. package/lib/tls/store.js +14 -1
  141. package/lib/token-audit-log.js +3 -2
  142. package/lib/tools.js +114 -53
  143. package/lib/totp.js +16 -1
  144. package/lib/ui-routes/account-routes.js +67 -70
  145. package/lib/ui-routes/admin-config-routes.js +111 -134
  146. package/lib/ui-routes/admin-entities-routes.js +101 -191
  147. package/lib/ui-routes/ai-options.js +104 -0
  148. package/lib/ui-routes/auth-routes.js +98 -18
  149. package/lib/ui-routes/export-routes.js +3 -23
  150. package/lib/ui-routes/internals-routes.js +12 -9
  151. package/lib/ui-routes/network-config-routes.js +8 -18
  152. package/lib/ui-routes/oauth-config-routes.js +83 -228
  153. package/lib/ui-routes/route-helpers.js +63 -67
  154. package/lib/ui-routes/special-use-paths.js +33 -0
  155. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  156. package/lib/utils/decode-headers.js +32 -5
  157. package/lib/utils/header-map.js +62 -1
  158. package/lib/utils/network.js +11 -17
  159. package/lib/web-safe-html.js +77 -4
  160. package/lib/webhook-request.js +9 -1
  161. package/lib/webhook-routing.js +27 -1
  162. package/lib/webhooks.js +120 -43
  163. package/lib/worker-rpc-error.js +43 -2
  164. package/list-generate.js +13 -2
  165. package/package.json +38 -46
  166. package/sbom.json +1 -1
  167. package/scripts/refresh-test-tokens.js +42 -14
  168. package/server.js +338 -292
  169. package/setup-production.sh +16 -7
  170. package/static/css/flyonui.css +1 -1
  171. package/static/css/src/app.tailwind.css +7 -8
  172. package/static/js/ee-client.js +145 -70
  173. package/static/js/ui.js +350 -154
  174. package/static/licenses.html +349 -1740
  175. package/translations/messages.pot +129 -111
  176. package/views/account-workspace-error.hbs +30 -0
  177. package/views/accounts/account.hbs +9 -4
  178. package/views/accounts/browse.hbs +10 -4
  179. package/views/accounts/edit.hbs +11 -2
  180. package/views/config/ai.hbs +49 -41
  181. package/views/config/oauth/app.hbs +2 -1
  182. package/views/dashboard.hbs +18 -16
  183. package/views/internals/index.hbs +1 -1
  184. package/views/layout/app.hbs +0 -22
  185. package/views/layout/login.hbs +2 -1
  186. package/views/partials/filter_editor_js.hbs +4 -3
  187. package/views/partials/gmail_api_scopes.hbs +16 -0
  188. package/views/partials/oauth_form.hbs +67 -94
  189. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  190. package/views/partials/scope_info.hbs +14 -23
  191. package/views/partials/side_menu.hbs +0 -4
  192. package/views/partials/ui/account-picker.hbs +6 -32
  193. package/views/partials/ui/model-picker.hbs +31 -0
  194. package/views/partials/ui/pagination.hbs +6 -1
  195. package/views/partials/ui/picker.hbs +47 -0
  196. package/views/unsubscribe.hbs +1 -1
  197. package/workers/api.js +82 -47
  198. package/workers/export.js +55 -60
  199. package/workers/imap.js +132 -49
  200. package/workers/submit.js +5 -6
  201. package/workers/webhooks.js +46 -27
  202. package/.githooks/pre-commit +0 -80
  203. package/.github/CODE_OF_CONDUCT.md +0 -76
  204. package/.github/contributing.md +0 -17
  205. package/.github/dependabot.yml +0 -22
  206. package/.github/docker-smoke-test.sh +0 -61
  207. package/.github/workflows/deploy.yml +0 -215
  208. package/.github/workflows/e2e.yml +0 -55
  209. package/.github/workflows/release.yaml +0 -217
  210. package/.github/workflows/test.yml +0 -307
  211. package/lib/api-routes/chat-routes.js +0 -535
  212. package/lib/document-store.js +0 -75
  213. package/lib/es.js +0 -757
  214. package/lib/generate-text-preview.js +0 -61
  215. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  216. package/lib/pre-process.js +0 -196
  217. package/lib/threads.js +0 -155
  218. package/lib/ui-routes/document-store-routes.js +0 -806
  219. package/playwright.config.js +0 -47
  220. package/views/config/document-store/chat.hbs +0 -286
  221. package/views/config/document-store/index.hbs +0 -146
  222. package/views/config/document-store/mappings/index.hbs +0 -108
  223. package/views/config/document-store/mappings/new.hbs +0 -68
  224. package/views/config/document-store/pre-processing/index.hbs +0 -103
  225. package/views/partials/document_store_header.hbs +0 -30
  226. package/workers/documents.js +0 -1128
@@ -44,13 +44,53 @@ 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, GMAIL_PROVIDERS, parseExternalAccountConfig } = require('./oauth/gmail');
48
+ const { ExternalAccountSigner } = require('./oauth/external-account-signer');
49
+ const { formatExtraScopes } = require('./oauth/scope-list');
50
+ const crypto = require('crypto');
48
51
  const { MailRuOauth, MAIL_RU_SCOPES } = require('./oauth/mail-ru');
49
52
 
50
53
  // Historical app IDs of the retired settings-based OAuth2 configuration. Only used by
51
54
  // migrateLegacyApps(); migrated apps keep these IDs, but are otherwise regular apps.
52
55
  const LEGACY_KEYS = ['gmail', 'gmailService', 'outlook', 'mailRu'];
53
56
 
57
+ // A successful API request clears the app's auth flag. Checking for one costs a Redis read, so a
58
+ // client checks at most this often; setting a flag is never throttled
59
+ const AUTH_FLAG_CLEAR_INTERVAL = 60 * 1000;
60
+
61
+ // When each app's auth flag was last checked for clearing, keyed by app id. Kept here rather
62
+ // than in the client's closure because a token renewal builds a new client every time, and the
63
+ // first successful request of every one of them then read the meta blob again. Entries are
64
+ // dropped when the app is deleted
65
+ const authFlagClearChecks = new Map();
66
+
67
+ // Used when a token response carries no usable expires_in (Google's service tokens live an hour)
68
+ const DEFAULT_SERVICE_TOKEN_TTL = 3600;
69
+
70
+ // Workload Identity Federation signers, per app id. The signer caches the federated token and
71
+ // deduplicates concurrent refreshes, which only helps when it outlives the GmailOauth client
72
+ // built for each token renewal: without this every account ran its own STS exchange every hour.
73
+ // Keyed on a hash of the configuration so a changed one is never served from the cache, and
74
+ // dropped on app update and delete
75
+ const externalAccountSigners = new Map();
76
+
77
+ function getExternalAccountSigner(id, externalAccount) {
78
+ let source = typeof externalAccount === 'string' ? externalAccount : JSON.stringify(externalAccount);
79
+ let hash = crypto.createHash('sha256').update(source).digest('hex');
80
+
81
+ let cached = externalAccountSigners.get(id);
82
+ if (cached && cached.hash === hash) {
83
+ return cached.signer;
84
+ }
85
+
86
+ let signer = new ExternalAccountSigner({
87
+ config: parseExternalAccountConfig(externalAccount),
88
+ logger: logger.child({ component: 'external-account-signer', app: id })
89
+ });
90
+ externalAccountSigners.set(id, { hash, signer });
91
+ return signer;
92
+ }
93
+
54
94
  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
95
  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
96
 
@@ -82,7 +122,13 @@ function oauth2ProviderData(provider, selector) {
82
122
  name: 'OAuth2',
83
123
  provider,
84
124
  caseName,
85
- comment: OAUTH_PROVIDERS[provider] || caseName
125
+ comment: OAUTH_PROVIDERS[provider] || caseName,
126
+ // Whether this provider can reach Gmail over the HTTP API instead of IMAP, which is what
127
+ // `baseScopes: 'api'` selects. True of both Gmail providers: isApiBasedApp() keys on that
128
+ // field and not on the provider, so a service account delegated gmail.modify is as API-based
129
+ // as an interactive app. The form guards the controls that only make sense in that mode - the
130
+ // scope presets, the Pub/Sub service account - on this rather than on one provider name.
131
+ gmailApi: GMAIL_PROVIDERS.has(provider)
86
132
  };
87
133
 
88
134
  switch (provider) {
@@ -181,50 +227,6 @@ function oauth2ProviderData(provider, selector) {
181
227
  return providerData;
182
228
  }
183
229
 
184
- function formatExtraScopes(extraScopes, baseScopes, defaultScopesList, skipScopes, scopePrefix) {
185
- let defaultScopes;
186
-
187
- skipScopes = [].concat(skipScopes || []);
188
-
189
- if (Array.isArray(defaultScopesList)) {
190
- defaultScopes = defaultScopesList;
191
- } else {
192
- defaultScopes = (baseScopes && defaultScopesList[baseScopes]) || defaultScopesList.imap;
193
- }
194
-
195
- if (!extraScopes && !skipScopes.length) {
196
- return defaultScopes;
197
- }
198
-
199
- extraScopes = extraScopes || [];
200
-
201
- let extras = [];
202
- for (let extraScope of extraScopes) {
203
- if (defaultScopes.includes(extraScope) || (scopePrefix && defaultScopes.includes(`${scopePrefix}/${extraScope}`))) {
204
- // skip existing
205
- continue;
206
- }
207
- extras.push(extraScope);
208
- }
209
-
210
- let result = extras.length ? extras.concat(defaultScopes) : defaultScopes;
211
-
212
- if (skipScopes.length) {
213
- result = result.filter(
214
- scope =>
215
- !skipScopes.some(
216
- skipScope =>
217
- scope === skipScope ||
218
- scope === `https://outlook.office.com/${skipScope}` ||
219
- scope === `https://graph.microsoft.com/${skipScope}` ||
220
- scope === `https://www.googleapis.com/auth/${skipScope}`
221
- )
222
- );
223
- }
224
-
225
- return result;
226
- }
227
-
228
230
  class OAuth2AppsHandler {
229
231
  constructor(options) {
230
232
  this.options = options || {};
@@ -750,6 +752,12 @@ class OAuth2AppsHandler {
750
752
 
751
753
  let existingData = msgpack.decode(existingDataBuf);
752
754
 
755
+ // The next client is built from the updated configuration. Not on the partial writes that
756
+ // store a renewed service token: the cache key already covers a changed configuration
757
+ if (!opts.partial || (data && 'externalAccount' in data)) {
758
+ externalAccountSigners.delete(id);
759
+ }
760
+
753
761
  // The authentication method is fixed once an app has been configured with
754
762
  // a credential - never allow switching between serviceKey and externalAccount
755
763
  // (WIF). Pin the stored method, ignoring any incoming change.
@@ -820,6 +828,9 @@ class OAuth2AppsHandler {
820
828
  }
821
829
 
822
830
  async del(id) {
831
+ externalAccountSigners.delete(id);
832
+ authFlagClearChecks.delete(id);
833
+
823
834
  let appData = await this.get(id);
824
835
 
825
836
  if (!appData) {
@@ -944,13 +955,87 @@ class OAuth2AppsHandler {
944
955
  return flags;
945
956
  }
946
957
 
958
+ /**
959
+ * The setFlag callback handed to a provider client. The client calls it with no flag after
960
+ * every successful request, which used to read and rewrite the whole shared meta blob each
961
+ * time: two extra round trips per API call on one hot key, and a window for losing a
962
+ * concurrent pubSubFlag or ttlWarning write. Clearing now happens only when a flag is actually
963
+ * set, and is checked at most once per AUTH_FLAG_CLEAR_INTERVAL per app
964
+ * @param {string} id - App ID
965
+ * @param {string} provider - Provider name for logging
966
+ * @returns {Function} async flag => void, never throws
967
+ */
968
+ createFlagSetter(id, provider) {
969
+ return async flag => {
970
+ try {
971
+ if (flag) {
972
+ authFlagClearChecks.delete(id);
973
+ await this.setMeta(id, { authFlag: flag });
974
+ return;
975
+ }
976
+ let now = Date.now();
977
+ if (now - (authFlagClearChecks.get(id) || 0) < AUTH_FLAG_CLEAR_INTERVAL) {
978
+ return;
979
+ }
980
+ authFlagClearChecks.set(id, now);
981
+ await this.clearAuthFlag(id);
982
+ } catch (err) {
983
+ // Log but don't throw - flag setting is non-critical
984
+ logger.error({ msg: 'Failed to set OAuth flag', app: id, provider, err });
985
+ }
986
+ };
987
+ }
988
+
989
+ /**
990
+ * Reads the meta blob of an app (auth flag, pubsub flag, ttl warning)
991
+ * @param {string} id - App ID
992
+ * @returns {Promise<Object|null>} the decoded meta, an empty object when there is none, null
993
+ * when the stored blob cannot be decoded
994
+ */
995
+ async readMeta(id) {
996
+ let existingMetaBuf = await this.redis.hgetBuffer(this.getDataKey(), `${id}:meta`);
997
+ if (!existingMetaBuf) {
998
+ return {};
999
+ }
1000
+ try {
1001
+ return msgpack.decode(existingMetaBuf) || {};
1002
+ } catch (err) {
1003
+ // an unreadable blob is replaced by the next write rather than blocking every later flag update
1004
+ logger.error({ msg: 'Failed to process app meta, replacing it', app: id, entryLength: existingMetaBuf.length, err });
1005
+ return null;
1006
+ }
1007
+ }
1008
+
1009
+ /**
1010
+ * Clears the auth flag of an app, writing only when one is set
1011
+ * @param {string} id - App ID
1012
+ * @returns {Promise<boolean>} true if a flag was cleared
1013
+ */
1014
+ async clearAuthFlag(id) {
1015
+ let existingMeta = await this.readMeta(id);
1016
+ if (existingMeta && !existingMeta.authFlag) {
1017
+ return false;
1018
+ }
1019
+ await this.setMeta(id, { authFlag: null }, existingMeta);
1020
+ return true;
1021
+ }
1022
+
1023
+ // Drops the cached service access token of an app, so the next request fetches a new one.
1024
+ // Used when the API refused the cached token before its recorded expiry
1025
+ async invalidateServiceAccessToken(id) {
1026
+ await this.update(id, { accessToken: null, accessTokenExpires: null }, { partial: true });
1027
+ }
1028
+
947
1029
  // Note: not atomic (read-modify-write). Concurrent callers use last-write-wins,
948
1030
  // 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) : {};
1031
+ // @param {Object} [existingMeta] - The meta as readMeta() returned it, when the caller has
1032
+ // just read it; otherwise it is read here
1033
+ async setMeta(id, meta, existingMeta) {
1034
+ if (existingMeta === undefined) {
1035
+ existingMeta = await this.readMeta(id);
1036
+ }
952
1037
 
953
- let entry = Object.assign(existingMeta, meta || {});
1038
+ let entry = Object.assign(existingMeta || {}, meta || {});
954
1039
 
955
1040
  await this.redis.hmset(this.getDataKey(), {
956
1041
  [`${id}:meta`]: msgpack.encode(entry)
@@ -1563,14 +1648,7 @@ class OAuth2AppsHandler {
1563
1648
  scopes,
1564
1649
  googleProjectId,
1565
1650
  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
- }
1651
+ setFlag: this.createFlagSetter(id, 'gmail')
1574
1652
  },
1575
1653
  extraOpts
1576
1654
  )
@@ -1603,18 +1681,12 @@ class OAuth2AppsHandler {
1603
1681
  authMethod,
1604
1682
  serviceKey,
1605
1683
  externalAccount,
1684
+ externalAccountSigner: authMethod === 'externalAccount' ? getExternalAccountSigner(id, externalAccount) : undefined,
1606
1685
  googleProjectId,
1607
1686
  serviceClientEmail,
1608
1687
  scopes,
1609
1688
  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
- }
1689
+ setFlag: this.createFlagSetter(id, 'gmailService')
1618
1690
  },
1619
1691
  extraOpts
1620
1692
  )
@@ -1645,14 +1717,7 @@ class OAuth2AppsHandler {
1645
1717
  redirectUrl,
1646
1718
  scopes,
1647
1719
  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
- }
1720
+ setFlag: this.createFlagSetter(id, 'outlook')
1656
1721
  },
1657
1722
  extraOpts
1658
1723
  )
@@ -1681,13 +1746,7 @@ class OAuth2AppsHandler {
1681
1746
  cloud,
1682
1747
  provider: 'outlookService',
1683
1748
  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
- }
1749
+ setFlag: this.createFlagSetter(id, 'outlookService')
1691
1750
  },
1692
1751
  extraOpts
1693
1752
  )
@@ -1712,14 +1771,7 @@ class OAuth2AppsHandler {
1712
1771
  clientSecret,
1713
1772
  redirectUrl,
1714
1773
  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
- }
1774
+ setFlag: this.createFlagSetter(id, 'mailRu')
1723
1775
  },
1724
1776
  extraOpts
1725
1777
  )
@@ -1781,6 +1833,12 @@ class OAuth2AppsHandler {
1781
1833
  // create new
1782
1834
  let isPrincipal = true;
1783
1835
  let { access_token: accessToken, expires_in: expiresIn } = await client.refreshToken({ isPrincipal });
1836
+ // A response without a numeric expires_in made the expiry an Invalid Date, and
1837
+ // toISOString() below threw a RangeError after a successful renewal
1838
+ expiresIn = Number(expiresIn);
1839
+ if (!Number.isFinite(expiresIn) || expiresIn <= 0) {
1840
+ expiresIn = DEFAULT_SERVICE_TOKEN_TTL;
1841
+ }
1784
1842
  let expires = new Date(now + expiresIn * 1000);
1785
1843
  if (!accessToken) {
1786
1844
  recordTokenMetric('failure', appData.provider || 'unknown', '0');
@@ -1823,7 +1881,13 @@ class OAuth2AppsHandler {
1823
1881
  }
1824
1882
  }
1825
1883
 
1826
- // gmailService uses JWT -> IMAP XOAUTH2, so it is NOT API-based even though it is a service-account provider.
1884
+ // Whether an app's accounts connect through a provider API rather than IMAP.
1885
+ //
1886
+ // Being a service-account provider does not decide it: a gmailService app with the default
1887
+ // `baseScopes: 'imap'` exchanges its JWT for an IMAP XOAUTH2 credential, which is why the provider
1888
+ // name alone is not on this list. `baseScopes: 'api'` is what makes one API-based, for gmailService as
1889
+ // much as for the interactive gmail app - the schema accepts it, verifyGmailService() probes the Gmail
1890
+ // API for exactly that combination, and these accounts get the Gmail API client.
1827
1891
  function isApiBasedApp(app) {
1828
1892
  return app && (app.baseScopes === 'api' || app.provider === 'outlookService');
1829
1893
  }
@@ -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)) {
package/lib/outbox.js CHANGED
@@ -3,6 +3,7 @@
3
3
  const { submitQueue, redis } = require('./db');
4
4
  const { REDIS_PREFIX } = require('../lib/consts');
5
5
  const msgpack = require('./msgpack');
6
+ const { nextAttemptOfStoredJob } = require('./delivery-error');
6
7
 
7
8
  // Job reads and removals are issued in bounded batches. ioredis writes each command as it is
8
9
  // issued, so a batch costs one round trip rather than one per job, while the bound keeps an account
@@ -48,13 +49,7 @@ function decodeQueueEntry(entryBuf) {
48
49
  function formatQueueEntry(job) {
49
50
  let scheduled = job.timestamp + (Number(job.opts.delay) || 0);
50
51
 
51
- let backoffDelay = Number(job.opts.backoff && job.opts.backoff.delay) || 0;
52
- // attemptsMade already includes the failed attempt, so the retry delay is 2^(attemptsMade-1) * base
53
- let nextAttempt = job.attemptsMade ? Math.round(job.processedOn + Math.pow(2, job.attemptsMade - 1) * backoffDelay) : scheduled;
54
-
55
- if (job.opts.attempts <= job.attemptsMade) {
56
- nextAttempt = false;
57
- }
52
+ let nextAttempt = nextAttemptOfStoredJob(job, scheduled);
58
53
 
59
54
  return Object.assign(job.data, {
60
55
  created: new Date(Number(job.data.created || job.timestamp)).toISOString(),
@@ -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 };