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
@@ -18,12 +18,18 @@ Returns:
18
18
  - bucketKey: The Redis key where the idempotency entry is stored
19
19
  - runIndex: The run index of the task
20
20
  - threadId: The thread ID processing the task
21
+
22
+ Single-node only: the bucket hashes are built from the prefix inside the script instead of being
23
+ declared in KEYS, so a Redis Cluster cannot route or slot-check them.
24
+
25
+ An entry that does not decode, or carries no numeric runIndex, is treated like a stale pending
26
+ task and replaced. It used to raise a Lua error, which failed the caller's whole transaction.
21
27
  --]]
22
28
 
23
29
  local bucketKeyPrefix = KEYS[1];
24
30
  local idempotencyKey = ARGV[1];
25
31
 
26
- local runIndex = tonumber(ARGV[2]);
32
+ local runIndex = tonumber(ARGV[2]) or 0;
27
33
  local threadId = tonumber(ARGV[3]);
28
34
 
29
35
  local buckets = ARGV[4];
@@ -36,13 +42,19 @@ for bucket in string.gmatch(buckets, "([^,]+)") do
36
42
  if redis.call("HEXISTS", bucketKey, idempotencyKey) == 1 then
37
43
  local existingValue = redis.call("HGET", bucketKey, idempotencyKey);
38
44
 
39
- local parsedValue = cjson.decode(existingValue);
45
+ local decoded, parsedValue = pcall(cjson.decode, existingValue);
46
+ if not decoded or type(parsedValue) ~= "table" then
47
+ parsedValue = {};
48
+ end
40
49
  local existingStatus = parsedValue["status"];
41
50
  local existingRunIndex = parsedValue["runIndex"];
42
51
  local existingThreadId = parsedValue["threadId"];
43
52
 
53
+ if existingStatus == nil then
54
+ -- Unreadable entry, treat it as absent
55
+ redis.log( redis.LOG_WARNING, "EE: Ignoring unreadable idempotency entry in " .. bucketKey);
44
56
  -- Check if this is a stale pending task from a previous run
45
- if existingStatus == "pending" and (existingRunIndex < runIndex or existingThreadId ~= threadId) then
57
+ elseif existingStatus == "pending" and (type(existingRunIndex) ~= "number" or existingRunIndex < runIndex or existingThreadId ~= threadId) then
46
58
  -- Ignore stale pending task
47
59
  redis.log( redis.LOG_NOTICE, "EE: Ignoring pending task with old run index: " .. existingValue .. " Current run index: " .. tostring(runIndex).. " Current thread ID: " .. tostring(threadId));
48
60
  else
@@ -0,0 +1,23 @@
1
+ --[[
2
+ Script: ee-release-attempts.lua
3
+ Purpose: Gives back a reservation made by ee-reserve-attempts.lua, for an attempt that succeeded
4
+
5
+ A counter that is back at zero is deleted, and one that already expired is not recreated as a
6
+ negative number.
7
+
8
+ KEYS:
9
+ [i] the counter of budget i
10
+
11
+ Returns:
12
+ 1
13
+ --]]
14
+
15
+ for _, key in ipairs(KEYS) do
16
+ if redis.call("EXISTS", key) == 1 then
17
+ if redis.call("DECR", key) <= 0 then
18
+ redis.call("DEL", key)
19
+ end
20
+ end
21
+ end
22
+
23
+ return 1
@@ -0,0 +1,42 @@
1
+ --[[
2
+ Script: ee-reserve-attempts.lua
3
+ Purpose: Reserves one attempt in every failure budget at once, or in none of them
4
+
5
+ INCR and the limit check are one step, so parallel attempts cannot all read the same count and
6
+ each go ahead. A refused reservation is taken back, so a spent budget holds at its limit rather
7
+ than growing with every refused attempt. A reservation for an attempt that then succeeds is
8
+ given back with ee-release-attempts.lua, so only failures stay counted.
9
+
10
+ KEYS:
11
+ [i] the counter of budget i
12
+
13
+ ARGV:
14
+ [2i-1] limit - attempts budget i admits, inclusive
15
+ [2i] ttl - seconds its counter lives, refreshed on every reservation
16
+
17
+ Returns:
18
+ {1, count1, count2, ...} when the attempt was reserved, the counts including it
19
+ {0, count1, count2, ...} when some budget is spent, the counts as they were
20
+ --]]
21
+
22
+ local counts = {}
23
+ local over = false
24
+
25
+ for i, key in ipairs(KEYS) do
26
+ local count = redis.call("INCR", key)
27
+ redis.call("EXPIRE", key, ARGV[i * 2])
28
+ counts[i] = count
29
+ if count > tonumber(ARGV[i * 2 - 1]) then
30
+ over = true
31
+ end
32
+ end
33
+
34
+ if over then
35
+ for i, key in ipairs(KEYS) do
36
+ redis.call("DECR", key)
37
+ counts[i] = counts[i] - 1
38
+ end
39
+ return {0, unpack(counts)}
40
+ end
41
+
42
+ return {1, unpack(counts)}
@@ -14,6 +14,10 @@ Returns:
14
14
  2 if field didn't exist but hash exists (created)
15
15
  1 if field existed but new value was not bigger (no change)
16
16
  0 if hash doesn't exist (no operation)
17
+
18
+ A stored value that is not a number is treated as smaller than any number and replaced. A new
19
+ value that is not a number is never written (returns 1). Either used to raise a Lua error, which
20
+ failed the whole MULTI the caller queued this in.
17
21
  --]]
18
22
 
19
23
  local hashKey = KEYS[1];
@@ -23,14 +27,20 @@ local value = ARGV[2];
23
27
 
24
28
  if redis.call("HEXISTS", hashKey, entryKey) == 1 then
25
29
  -- Field exists, compare values
26
- local existing = redis.call("HGET", hashKey, entryKey);
27
- if tonumber(value) > tonumber(existing) then
30
+ local existing = tonumber(redis.call("HGET", hashKey, entryKey));
31
+ local newValue = tonumber(value);
32
+ if newValue == nil then
33
+ return 1; -- Not a number, nothing to compare
34
+ end;
35
+ if existing == nil or newValue > existing then
28
36
  -- New value is bigger, update it
29
37
  redis.call("HSET", hashKey, entryKey, value);
30
38
  return 3; -- Updated with bigger value
31
39
  else
32
40
  return 1; -- Existing value is bigger or equal, no change
33
41
  end;
42
+ elseif tonumber(value) == nil then
43
+ return 1; -- Not a number, never stored
34
44
  elseif redis.call("EXISTS", hashKey) == 1 then
35
45
  -- Hash exists but field doesn't, create new field
36
46
  redis.call("HSET", hashKey, entryKey, value);
@@ -22,7 +22,8 @@ Returns:
22
22
  [2] Skip value used
23
23
  [3] Array of account data (HGETALL results for each matching account)
24
24
 
25
- NOTE: This script is not compatible with Redis clustering if using account id as the hash slot key
25
+ NOTE: Single-node only. The per-account hashes are built from the prefix inside the script
26
+ instead of being declared in KEYS, so a Redis Cluster cannot route or slot-check them.
26
27
  --]]
27
28
 
28
29
  local listKey = KEYS[1];
@@ -46,8 +47,10 @@ local total = redis.call("SCARD", listKey); -- Get total account count
46
47
 
47
48
  local list = redis.call("SMEMBERS", listKey); -- Load all account IDs
48
49
 
49
- -- Early return if offset exceeds total
50
- if skip >= total then
50
+ -- Early return if offset exceeds total. Only for an unfiltered listing: with a state filter or a
51
+ -- search the first value is the number of MATCHING accounts, which SCARD is not, so a page past the
52
+ -- end used to report every account as matching.
53
+ if skip >= total and filterState == '*' and strsearch == '' then
51
54
  return {total,skip, {}}
52
55
  end
53
56
 
package/lib/mcp/index.js CHANGED
@@ -18,8 +18,7 @@ const mcpFeatureEnabled = hasEnvValue('EENGINE_MCP_ENABLED')
18
18
  : getBoolean(config.mcp ? config.mcp.enabled : true);
19
19
 
20
20
  // Effective runtime state: the feature must be available (gate) AND enabled in settings. When
21
- // the gate is off this is always false, mirroring isDocumentStoreEnabled() in
22
- // lib/document-store.js.
21
+ // the gate is off this is always false.
23
22
  const isMcpEnabled = async () => mcpFeatureEnabled && !!(await settings.get('mcpEnabled'));
24
23
 
25
24
  // The one error every first-time integrator hits, so every surface that reports it names the
package/lib/mcp/listen.js CHANGED
@@ -44,6 +44,26 @@ const MAX_RESOURCE_SUBSCRIPTIONS = 20;
44
44
  const AUTH_CHECK_CONCURRENCY = 5;
45
45
  const MAX_STREAMS_PER_CREDENTIAL = 4;
46
46
 
47
+ // How often an open stream re-asks whether its credential may still read what it subscribed to.
48
+ // Authorization used to happen once, at accept time, so a revoked token kept receiving account
49
+ // change notifications for as long as the socket stayed up.
50
+ const LISTEN_RECHECK_INTERVAL = 60 * 1000;
51
+
52
+ // One timer serves every open stream: it runs while any stream has a server to re-check against
53
+ // and stops with the last of them. A timer per stream was one setInterval and one round of
54
+ // injected requests per stream, even for streams of the same credential watching the same
55
+ // accounts. The period is the shortest one asked for, which outside the tests is always
56
+ // LISTEN_RECHECK_INTERVAL.
57
+ let recheckTimer = null;
58
+ let recheckPeriod = Infinity;
59
+ let recheckInFlight = null;
60
+
61
+ // Streams per credential that have been admitted but are still waiting on the accept-time
62
+ // authorization checks. Counted alongside the open ones: the checks are awaited before the stream
63
+ // exists, and counting only open streams let concurrent requests all pass the cap at once and each
64
+ // start its own round of injected requests.
65
+ const pendingListenStreams = new Map();
66
+
47
67
  /**
48
68
  * The credential a stream belongs to, for the per-credential stream cap. Token records are keyed
49
69
  * by their hash; the `preauth` caller of the disableTokens mode has no record and shares one
@@ -58,7 +78,7 @@ function credentialId(request) {
58
78
  */
59
79
  function canOpenListenStream(request) {
60
80
  const id = credentialId(request);
61
- let open = 0;
81
+ let open = pendingListenStreams.get(id) || 0;
62
82
  for (const stream of mcpListenStreams) {
63
83
  if (stream.mcpSubscription && stream.mcpSubscription.credentialId === id) {
64
84
  open++;
@@ -67,6 +87,35 @@ function canOpenListenStream(request) {
67
87
  return open < MAX_STREAMS_PER_CREDENTIAL;
68
88
  }
69
89
 
90
+ /**
91
+ * Takes one of the credential's stream slots, synchronously, for the time between admitting a
92
+ * listen request and registering its stream.
93
+ *
94
+ * @returns {Function|null} release function (idempotent), or null when the credential is at its cap
95
+ */
96
+ function reserveListenStream(request) {
97
+ if (!canOpenListenStream(request)) {
98
+ return null;
99
+ }
100
+
101
+ const id = credentialId(request);
102
+ pendingListenStreams.set(id, (pendingListenStreams.get(id) || 0) + 1);
103
+
104
+ let released = false;
105
+ return () => {
106
+ if (released) {
107
+ return;
108
+ }
109
+ released = true;
110
+ const left = (pendingListenStreams.get(id) || 1) - 1;
111
+ if (left > 0) {
112
+ pendingListenStreams.set(id, left);
113
+ } else {
114
+ pendingListenStreams.delete(id);
115
+ }
116
+ };
117
+ }
118
+
70
119
  /**
71
120
  * Validates a requested notification filter against what the caller may actually see.
72
121
  *
@@ -79,26 +128,135 @@ async function acceptFilter({ server, request, filter }) {
79
128
 
80
129
  const accounts = [...new Set(requested.map(uri => parseAccountUri(uri)).filter(Boolean))];
81
130
 
82
- // Independent yes/no checks about separate accounts, so they run concurrently - serialized,
83
- // a broad subscription would pay one full request pipeline per URI in connect latency. In
84
- // batches rather than all at once: every check is a full injected request, and one client
85
- // should not be able to put twenty of those in flight with a single POST.
86
- const uris = [];
131
+ const statuses = await probeAccounts({ server, request, accounts });
132
+ const uris = accounts.filter(account => statuses.get(account) < 400).map(account => accountUri(account));
133
+ if (uris.length) {
134
+ accepted.resourceSubscriptions = uris;
135
+ }
136
+
137
+ return accepted;
138
+ }
139
+
140
+ /**
141
+ * Asks, with the caller's own credential, whether each account may be read: one injected
142
+ * GET /v1/account/{account} per account. Independent yes/no checks about separate accounts, so
143
+ * they run concurrently - serialized, a broad subscription would pay one full request pipeline
144
+ * per URI in connect latency. In batches rather than all at once: every check is a full injected
145
+ * request, and one client should not be able to put twenty of those in flight with a single POST.
146
+ *
147
+ * @returns {Promise<Map>} account -> HTTP status of its check. A failed dispatch rejects; the
148
+ * caller decides whether that fails the request (accept time) or changes nothing (re-check)
149
+ */
150
+ async function probeAccounts({ server, request, accounts }) {
151
+ const statuses = new Map();
87
152
  for (let pos = 0; pos < accounts.length; pos += AUTH_CHECK_CONCURRENCY) {
88
153
  const batch = accounts.slice(pos, pos + AUTH_CHECK_CONCURRENCY);
89
- const admitted = await Promise.all(
90
- batch.map(async account => {
91
- const res = await apiInject({ server, request, method: 'get', url: `/v1/account/${encodeURIComponent(account)}` });
92
- return res.statusCode < 400 ? accountUri(account) : null;
93
- })
154
+ const results = await Promise.all(
155
+ batch.map(account => apiInject({ server, request, method: 'get', url: `/v1/account/${encodeURIComponent(account)}` }))
94
156
  );
95
- uris.push(...admitted.filter(Boolean));
157
+ batch.forEach((account, i) => statuses.set(account, results[i].statusCode));
96
158
  }
97
- if (uris.length) {
98
- accepted.resourceSubscriptions = uris;
159
+ return statuses;
160
+ }
161
+
162
+ /**
163
+ * Re-runs the per-account authorization of every open stream, once per (credential, account)
164
+ * pair however many streams share it. A URI the credential can no longer read (403) or that no
165
+ * longer exists (404) is dropped from each stream holding it; a credential that is gone (401), or
166
+ * a stream left with nothing it may read, is closed. Anything else, a 5xx or a failed dispatch,
167
+ * is treated as transient and changes nothing. A call made while a pass is running joins it.
168
+ *
169
+ * @returns {Promise<void>}
170
+ */
171
+ function recheckListenStreams() {
172
+ if (!recheckInFlight) {
173
+ recheckInFlight = runRecheckPass().finally(() => {
174
+ recheckInFlight = null;
175
+ });
99
176
  }
177
+ return recheckInFlight;
178
+ }
100
179
 
101
- return accepted;
180
+ async function runRecheckPass() {
181
+ // Streams grouped by credential, with the union of the accounts they watch
182
+ const groups = new Map();
183
+ for (const stream of mcpListenStreams) {
184
+ const subscription = stream.mcpSubscription;
185
+ if (!subscription || !subscription.recheck || !subscription.resourceUris.size) {
186
+ continue;
187
+ }
188
+ let group = groups.get(subscription.credentialId);
189
+ if (!group) {
190
+ group = { server: subscription.recheck.server, request: subscription.recheck.request, accounts: new Set(), streams: [] };
191
+ groups.set(subscription.credentialId, group);
192
+ }
193
+ group.streams.push(stream);
194
+ for (const uri of subscription.resourceUris) {
195
+ group.accounts.add(parseAccountUri(uri));
196
+ }
197
+ }
198
+
199
+ for (const group of groups.values()) {
200
+ let statuses;
201
+ try {
202
+ statuses = await probeAccounts({ server: group.server, request: group.request, accounts: [...group.accounts] });
203
+ } catch (err) {
204
+ // a failed dispatch says nothing about the credential
205
+ continue;
206
+ }
207
+
208
+ for (const stream of group.streams) {
209
+ if (stream._finalized || stream.destroyed) {
210
+ continue;
211
+ }
212
+ const subscription = stream.mcpSubscription;
213
+ let revoked = false;
214
+ for (const uri of [...subscription.resourceUris]) {
215
+ const status = statuses.get(parseAccountUri(uri));
216
+ if (status === 401) {
217
+ revoked = true;
218
+ break;
219
+ }
220
+ if (status === 403 || status === 404) {
221
+ subscription.resourceUris.delete(uri);
222
+ }
223
+ }
224
+ if (revoked || !subscription.resourceUris.size) {
225
+ stream.finalize();
226
+ }
227
+ }
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Starts the shared re-check timer, or shortens its period to the one asked for.
233
+ */
234
+ function ensureRecheckTimer(period) {
235
+ if (recheckTimer && period >= recheckPeriod) {
236
+ return;
237
+ }
238
+ if (recheckTimer) {
239
+ clearInterval(recheckTimer);
240
+ }
241
+ recheckPeriod = period;
242
+ recheckTimer = setInterval(recheckListenStreams, period);
243
+ recheckTimer.unref();
244
+ }
245
+
246
+ /**
247
+ * Stops the shared timer once no open stream is left to re-check.
248
+ */
249
+ function releaseRecheckTimer() {
250
+ for (const stream of mcpListenStreams) {
251
+ if (stream.mcpSubscription && stream.mcpSubscription.recheck) {
252
+ return;
253
+ }
254
+ }
255
+ if (recheckTimer) {
256
+ clearInterval(recheckTimer);
257
+ recheckTimer = null;
258
+ recheckPeriod = Infinity;
259
+ }
102
260
  }
103
261
 
104
262
  /**
@@ -109,9 +267,13 @@ async function acceptFilter({ server, request, filter }) {
109
267
  * @param {Object} opts.request - the /mcp request, for the credential the stream is counted under
110
268
  * @param {*} opts.subscriptionId - the JSON-RPC id of the subscriptions/listen request
111
269
  * @param {Object} opts.accepted - the acknowledged filter subset from acceptFilter()
270
+ * @param {Object} [opts.server] - Hapi server; when given, the stream joins the periodic
271
+ * re-check of its authorization
272
+ * @param {number} [opts.recheckInterval] - period of the shared re-check timer, defaults to
273
+ * LISTEN_RECHECK_INTERVAL; a shorter one than the timer already runs at replaces it
112
274
  * @returns {Object} Hapi response
113
275
  */
114
- function openListenStream({ h, request, subscriptionId, accepted }) {
276
+ function openListenStream({ h, request, subscriptionId, accepted, server, recheckInterval }) {
115
277
  const { stream, response } = openSseStream(h, {
116
278
  registry: mcpListenStreams,
117
279
  onOpen: opened =>
@@ -128,12 +290,42 @@ function openListenStream({ h, request, subscriptionId, accepted }) {
128
290
  stream.mcpSubscription = {
129
291
  id: subscriptionId,
130
292
  credentialId: credentialId(request),
131
- resourceUris: new Set(accepted.resourceSubscriptions || [])
293
+ resourceUris: new Set(accepted.resourceSubscriptions || []),
294
+ // What the periodic re-check asks again with: this stream's own credential
295
+ recheck: server ? { server, request } : null
132
296
  };
133
297
 
298
+ if (server) {
299
+ ensureRecheckTimer(recheckInterval || LISTEN_RECHECK_INTERVAL);
300
+ // finalize() has already dropped the stream from the registry by the time this fires
301
+ stream.once('close', releaseRecheckTimer);
302
+ }
303
+
134
304
  return response;
135
305
  }
136
306
 
307
+ /**
308
+ * The whole subscriptions/listen admission: reserve a stream slot, authorize the requested
309
+ * subscriptions, open the stream. The slot is taken before the first await and held until the
310
+ * stream is registered, so concurrent requests cannot all pass the cap.
311
+ *
312
+ * @returns {Promise<Object|null>} Hapi response, or null when the credential is at its stream cap
313
+ */
314
+ async function handleListen({ h, server, request, subscriptionId, filter, recheckInterval }) {
315
+ const release = reserveListenStream(request);
316
+ if (!release) {
317
+ return null;
318
+ }
319
+
320
+ try {
321
+ const accepted = await acceptFilter({ server, request, filter });
322
+ // Registers the stream synchronously, so releasing the reservation below does not open a gap
323
+ return openListenStream({ h, request, subscriptionId, accepted, server, recheckInterval });
324
+ } finally {
325
+ release();
326
+ }
327
+ }
328
+
137
329
  /**
138
330
  * Fans one account state-change event out to the listen streams that subscribed to it.
139
331
  * Called from the API worker's 'change' message handler, alongside the admin feed fanout.
@@ -168,4 +360,15 @@ function publishAccountChange(data, logger) {
168
360
  }
169
361
  }
170
362
 
171
- module.exports = { acceptFilter, openListenStream, publishAccountChange, canOpenListenStream, MAX_STREAMS_PER_CREDENTIAL, MAX_RESOURCE_SUBSCRIPTIONS };
363
+ module.exports = {
364
+ acceptFilter,
365
+ openListenStream,
366
+ handleListen,
367
+ reserveListenStream,
368
+ probeAccounts,
369
+ recheckListenStreams,
370
+ publishAccountChange,
371
+ canOpenListenStream,
372
+ MAX_STREAMS_PER_CREDENTIAL,
373
+ MAX_RESOURCE_SUBSCRIPTIONS
374
+ };
package/lib/mcp/oauth.js CHANGED
@@ -36,6 +36,17 @@ const { LOOPBACK_HOSTNAMES } = require('./protocol');
36
36
  // stays stable.
37
37
  const CLIENT_TTL = 30 * 24 * 3600;
38
38
 
39
+ // Registration is open and unauthenticated, so a new registration only lives long enough to reach
40
+ // the consent page. It gets the full CLIENT_TTL once it does (touchClient). A registration nobody
41
+ // consents to used to hold its record for 30 days, and a caller rotating addresses past the per-IP
42
+ // rate limit could grow Redis without a real bound.
43
+ const PENDING_CLIENT_TTL = 10 * 60;
44
+
45
+ // How many registrations may be waiting for consent at once, instance wide. With the short TTL
46
+ // above this is a bound on memory, not a quota a working flow ever meets: a real client registers
47
+ // once and reaches consent within minutes.
48
+ const MAX_PENDING_CLIENTS = 1000;
49
+
39
50
  // An authorization code is redeemed within seconds in a working flow; ten minutes is the
40
51
  // conventional upper bound.
41
52
  const CODE_TTL = 10 * 60;
@@ -64,6 +75,8 @@ function normalizeScopes(scopes) {
64
75
  }
65
76
 
66
77
  const clientKey = clientId => `${REDIS_PREFIX}mcp:oauth:client:${clientId}`;
78
+ // Registrations still waiting for consent, scored by when they expire, so they can be counted
79
+ const pendingClientsKey = () => `${REDIS_PREFIX}mcp:oauth:pending-clients`;
67
80
  const codeKey = code => `${REDIS_PREFIX}mcp:oauth:code:${code}`;
68
81
 
69
82
  /**
@@ -142,9 +155,12 @@ function isAcceptableRedirectUri(value) {
142
155
  * @param {Object} opts
143
156
  * @param {Array} opts.redirectUris
144
157
  * @param {String} [opts.clientName]
158
+ * @param {Number} [opts.maxPending] - registrations awaiting consent this one may join, default
159
+ * MAX_PENDING_CLIENTS; a unit test lowers it rather than filling the set every other suite
160
+ * shares with a thousand entries
145
161
  * @returns {Promise<Object>} the stored client record
146
162
  */
147
- async function registerClient({ redirectUris, clientName }) {
163
+ async function registerClient({ redirectUris, clientName, maxPending = MAX_PENDING_CLIENTS }) {
148
164
  const uris = [].concat(redirectUris || []);
149
165
 
150
166
  if (!uris.length || uris.length > MAX_REDIRECT_URIS) {
@@ -172,7 +188,25 @@ async function registerClient({ redirectUris, clientName }) {
172
188
  client_name: (clientName || '').toString().slice(0, 256) || undefined
173
189
  };
174
190
 
175
- await redis.set(clientKey(client.client_id), msgpack.encode(client), 'EX', CLIENT_TTL);
191
+ const now = Date.now();
192
+ const [[pruneErr], [countErr, pending]] = await redis.multi().zremrangebyscore(pendingClientsKey(), '-inf', now).zcard(pendingClientsKey()).exec();
193
+ if (pruneErr || countErr) {
194
+ throw pruneErr || countErr;
195
+ }
196
+ if (pending >= maxPending) {
197
+ const err = oauthFailure('temporarily_unavailable', 'Too many client registrations are waiting for consent, try again later');
198
+ err.statusCode = 503;
199
+ throw err;
200
+ }
201
+
202
+ const [[setErr], [addErr]] = await redis
203
+ .multi()
204
+ .set(clientKey(client.client_id), msgpack.encode(client), 'EX', PENDING_CLIENT_TTL)
205
+ .zadd(pendingClientsKey(), now + PENDING_CLIENT_TTL * 1000, client.client_id)
206
+ .exec();
207
+ if (setErr || addErr) {
208
+ throw setErr || addErr;
209
+ }
176
210
 
177
211
  return client;
178
212
  }
@@ -194,9 +228,10 @@ async function getClient(clientId) {
194
228
  }
195
229
  }
196
230
 
197
- // A client that reached the consent page is in active use; keep its registration alive
231
+ // A client that reached the consent page is in active use; keep its registration alive, and stop
232
+ // counting it against the registrations waiting for consent
198
233
  async function touchClient(clientId) {
199
- await redis.expire(clientKey(clientId), CLIENT_TTL);
234
+ await redis.multi().expire(clientKey(clientId), CLIENT_TTL).zrem(pendingClientsKey(), clientId).exec();
200
235
  }
201
236
 
202
237
  // Trailing slashes carry no meaning for a resource identifier, so every comparison below runs
@@ -358,5 +393,9 @@ module.exports = {
358
393
  createAuthorizationCode,
359
394
  redeemAuthorizationCode,
360
395
  verifyPkce,
361
- MAX_REDIRECT_URIS
396
+ MAX_REDIRECT_URIS,
397
+ CLIENT_TTL,
398
+ PENDING_CLIENT_TTL,
399
+ MAX_PENDING_CLIENTS,
400
+ pendingClientsKey
362
401
  };
@@ -21,6 +21,12 @@ function accountUri(account) {
21
21
  return ACCOUNT_URI_PREFIX + encodeURIComponent(account);
22
22
  }
23
23
 
24
+ // A path segment that would stop being one. encodeURIComponent leaves `.` and `..` as they are,
25
+ // and Hapi collapses them as dot segments, so a URL built from one reaches a different route than
26
+ // the one named: a read of emailengine://account/.. was dispatched to /v1/, and a tool call with
27
+ // such an argument left the argument shaping the tool applies. Shared with lib/mcp/tools.js.
28
+ const DOT_SEGMENT = /^\.{1,2}$/;
29
+
24
30
  /**
25
31
  * Whether an account id survives the URI round-trip. parseAccountUri refuses decoded URI
26
32
  * structure, so an id carrying any would be listed under a URI that resources/read and the
@@ -28,7 +34,7 @@ function accountUri(account) {
28
34
  * addressable as a resource, and the listings skip it rather than advertise a dead URI.
29
35
  */
30
36
  function isRepresentableAccountId(account) {
31
- return typeof account === 'string' && !!account && !/[/?#]/.test(account);
37
+ return typeof account === 'string' && !!account && !/[/?#]/.test(account) && !DOT_SEGMENT.test(account);
32
38
  }
33
39
 
34
40
  /**
@@ -136,4 +142,4 @@ async function readResource({ server, request, uri }) {
136
142
  ];
137
143
  }
138
144
 
139
- module.exports = { listResources, readResource, accountUri, parseAccountUri, isRepresentableAccountId, ACCOUNT_URI_PREFIX };
145
+ module.exports = { listResources, readResource, accountUri, parseAccountUri, isRepresentableAccountId, ACCOUNT_URI_PREFIX, DOT_SEGMENT };
package/lib/mcp/tools.js CHANGED
@@ -20,6 +20,7 @@ const tokenPermissions = require('../token-permissions');
20
20
  const { mcpOptions } = require('../api-routes/route-metadata');
21
21
  const { joiToJsonSchema } = require('./json-schema');
22
22
  const { apiInject } = require('./inject');
23
+ const { DOT_SEGMENT } = require('./resources');
23
24
 
24
25
  // Serialized tool results larger than this are truncated. Message text is attacker-sized input
25
26
  // (a single mail can carry megabytes of text), and an oversized tool result degrades or breaks
@@ -334,6 +335,13 @@ function effectiveArguments(tool, args, boundAccount) {
334
335
  return { args: effective, sources: tool.forcedSources };
335
336
  }
336
337
 
338
+ // Path parameters that would stop being a segment (DOT_SEGMENT): the injected call would reach a
339
+ // different route than the tool names, out from under the argument shaping the tool applies.
340
+ function dotSegmentArguments(template, args, sources) {
341
+ const names = [...template.matchAll(/\{([^}]+)\}/g)].map(match => match[1]);
342
+ return names.filter(name => sources.has(name) && args[name] !== undefined && args[name] !== null && DOT_SEGMENT.test(String(args[name])));
343
+ }
344
+
337
345
  // Fills a Hapi path template ('/v1/account/{account}/message/{message}') from tool arguments.
338
346
  function buildPath(template, args, sources) {
339
347
  return template.replace(/\{([^}]+)\}/g, (match, name) => {
@@ -451,6 +459,11 @@ async function callTool({ server, tool, args, request }) {
451
459
  return textResult(`Missing required tool argument${missing.length > 1 ? 's' : ''}: ${missing.join(', ')}`, { isError: true });
452
460
  }
453
461
 
462
+ const dotSegments = dotSegmentArguments(tool.path, effective.args, effective.sources);
463
+ if (dotSegments.length) {
464
+ return textResult(`Invalid value for tool argument${dotSegments.length > 1 ? 's' : ''}: ${dotSegments.join(', ')}`, { isError: true });
465
+ }
466
+
454
467
  const payload = {};
455
468
  let hasPayload = false;
456
469
  for (const [key, sourceName] of effective.sources) {