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
package/lib/mcp/tools.js CHANGED
@@ -3,9 +3,9 @@
3
3
  // The MCP tool registry and executor.
4
4
  //
5
5
  // Tools are not defined here. A route opts in by carrying a `plugins.mcp` block
6
- // ({ name, title, description, keep?/omit?, force?, bounds?, binary?, resourceUriTemplate? }), and
7
- // this module derives everything else from what
8
- // the route already declares: the input schema from its joi validation schemas, the behavior
6
+ // ({ name, title, description, keep?/omit?, force?, bounds?, binary?, tail?, resourceUriTemplate? }),
7
+ // and this module derives everything else from what the route already declares: the input schema from
8
+ // its joi validation schemas, the behavior
9
9
  // annotations from routeGrant() - the same source /swagger.json publishes as x-ee-action and
10
10
  // x-ee-group - and the dispatch target from its method and path. There is deliberately no second
11
11
  // description of any endpoint: a tool cannot disagree with the route it wraps.
@@ -16,10 +16,12 @@
16
16
  // do over REST. This module never touches Redis and never bypasses a handler.
17
17
 
18
18
  const { routeGrant, surfaceAdmits, surfaceBoundAdmits, PER_REQUEST_SURFACES, ACTION } = require('../api-routes/permission-map');
19
+ const { routeAdmitsBoundToken } = require('../api-routes/account-binding');
19
20
  const tokenPermissions = require('../token-permissions');
20
21
  const { mcpOptions } = require('../api-routes/route-metadata');
21
22
  const { joiToJsonSchema } = require('./json-schema');
22
23
  const { apiInject } = require('./inject');
24
+ const { DOT_SEGMENT } = require('./resources');
23
25
 
24
26
  // Serialized tool results larger than this are truncated. Message text is attacker-sized input
25
27
  // (a single mail can carry megabytes of text), and an oversized tool result degrades or breaks
@@ -38,9 +40,27 @@ const MAX_TOOL_BINARY_BYTES = 1024 * 1024;
38
40
 
39
41
  const TRUNCATION_NOTICE = size => `\n\n[Result truncated by EmailEngine: the full response was ${size} bytes. Narrow the request to see the rest.]`;
40
42
 
43
+ // The same notice for a result cut from the front, where it has to lead so the kept text still ends
44
+ // on the newest line
45
+ const LEADING_TRUNCATION_NOTICE = size =>
46
+ `[Earlier output dropped by EmailEngine: the full response was ${size} bytes. Only the most recent output follows.]\n\n`;
47
+
41
48
  // Every key a plugins.mcp block may carry. The one place the block's shape is written down, so a
42
49
  // misspelling is a build failure rather than a knob that quietly does nothing.
43
- const MCP_OPTION_KEYS = new Set(['name', 'title', 'description', 'keep', 'omit', 'force', 'bounds', 'binary', 'resourceUriTemplate', 'endpoint', 'openWorld']);
50
+ const MCP_OPTION_KEYS = new Set([
51
+ 'name',
52
+ 'title',
53
+ 'description',
54
+ 'keep',
55
+ 'omit',
56
+ 'force',
57
+ 'bounds',
58
+ 'binary',
59
+ 'tail',
60
+ 'resourceUriTemplate',
61
+ 'endpoint',
62
+ 'openWorld'
63
+ ]);
44
64
 
45
65
  // One registry per Hapi server, built on first use and held for the life of the worker - route
46
66
  // definitions cannot change while it runs, and the build walks every joi schema of every wrapped
@@ -278,7 +298,19 @@ function buildToolRegistry(routes) {
278
298
  // are declared: the other half of what tools/list filters on, and what the admin
279
299
  // pages group and count by
280
300
  surfaces: [...PER_REQUEST_SURFACES].filter(scope => surfaceAdmits(scope, grant)),
301
+ // Whether an account-bound credential can reach this tool at all, which is the same
302
+ // question the api-token strategy answers when it checks the binding - so it is answered
303
+ // from the table that strategy switches on (lib/api-routes/account-binding.js) rather
304
+ // than from "the route takes an `account` argument". The two are different questions:
305
+ // verify_oauth2_app's `account` is a mailbox address for a delegation check, and
306
+ // create_account, create_account_setup_link and add_to_blocklist all take one in the
307
+ // payload, yet a bound token is refused every one of them.
308
+ accountScoped: routeAdmitsBoundToken(route.method, route.path),
281
309
  binary: !!options.binary,
310
+ // A text result whose newest and most useful lines are LAST, so the cap keeps its end
311
+ // rather than its beginning. Declared by the route, because which half of a response
312
+ // matters is a property of that endpoint and not something this module can infer
313
+ tail: !!options.tail,
282
314
  resourceUriTemplate: options.resourceUriTemplate
283
315
  });
284
316
  }
@@ -290,7 +322,7 @@ function buildToolRegistry(routes) {
290
322
  // the worker and three admin pages plus the MCP door read this.
291
323
  const grants = tools.map(tool => {
292
324
  const entry = byName.get(tool.name);
293
- return Object.assign({ name: tool.name, accountScoped: entry.sources.has('account'), surfaces: entry.surfaces }, entry.grant);
325
+ return Object.assign({ name: tool.name, accountScoped: entry.accountScoped, surfaces: entry.surfaces }, entry.grant);
294
326
  });
295
327
 
296
328
  return { tools, byName, grants };
@@ -317,7 +349,7 @@ function buildToolRegistry(routes) {
317
349
  function effectiveArguments(tool, args, boundAccount) {
318
350
  const effective = Object.assign({}, args, tool.forcedValues);
319
351
 
320
- if (boundAccount && tool.sources.has('account') && (effective.account === undefined || effective.account === null || effective.account === '')) {
352
+ if (boundAccount && tool.accountScoped && (effective.account === undefined || effective.account === null || effective.account === '')) {
321
353
  effective.account = boundAccount;
322
354
  }
323
355
 
@@ -334,6 +366,13 @@ function effectiveArguments(tool, args, boundAccount) {
334
366
  return { args: effective, sources: tool.forcedSources };
335
367
  }
336
368
 
369
+ // Path parameters that would stop being a segment (DOT_SEGMENT): the injected call would reach a
370
+ // different route than the tool names, out from under the argument shaping the tool applies.
371
+ function dotSegmentArguments(template, args, sources) {
372
+ const names = [...template.matchAll(/\{([^}]+)\}/g)].map(match => match[1]);
373
+ return names.filter(name => sources.has(name) && args[name] !== undefined && args[name] !== null && DOT_SEGMENT.test(String(args[name])));
374
+ }
375
+
337
376
  // Fills a Hapi path template ('/v1/account/{account}/message/{message}') from tool arguments.
338
377
  function buildPath(template, args, sources) {
339
378
  return template.replace(/\{([^}]+)\}/g, (match, name) => {
@@ -363,8 +402,22 @@ function buildQuery(args, sources) {
363
402
  return rendered ? `?${rendered}` : '';
364
403
  }
365
404
 
366
- function textResult(text, { isError = false } = {}) {
367
- const result = { content: [{ type: 'text', text }] };
405
+ /**
406
+ * An MCP text result, cut to the size cap.
407
+ *
408
+ * The cap applies here and not only in jsonResult(), because plenty of what this endpoint returns is
409
+ * already text: an account's whole connection log, a raw message source, and the API's own error body
410
+ * echoed back on a 4xx. Those used to be returned whole, so one tool call could put megabytes into
411
+ * the conversation while the JSON results beside it were held to 128KB.
412
+ *
413
+ * @param {String} text - the result text
414
+ * @param {Object} [opts]
415
+ * @param {Boolean} [opts.isError] - mark the result as a tool execution error
416
+ * @param {Boolean} [opts.tail] - keep the END of an oversized value rather than its beginning
417
+ * @returns {Object} an MCP tool result
418
+ */
419
+ function textResult(text, { isError = false, tail = false } = {}) {
420
+ const result = { content: [{ type: 'text', text: capText(text, tail) }] };
368
421
  if (isError) {
369
422
  result.isError = true;
370
423
  }
@@ -372,44 +425,58 @@ function textResult(text, { isError = false } = {}) {
372
425
  }
373
426
 
374
427
  /**
375
- * Cuts a string to a UTF-8 byte budget.
428
+ * Applies the result cap to a text value, with the notice that says what was dropped.
376
429
  *
377
- * String.slice() counts UTF-16 code units, so slicing to the byte cap left a result up to three
378
- * times over it - a mailbox of CJK or Cyrillic text sailed through the cap while carrying a
379
- * notice claiming it had been truncated. Cutting the encoded bytes instead, then walking back off
380
- * any trailing continuation byte, keeps the budget honest and never emits a split code point.
430
+ * The budget is in bytes, and String.slice() counts UTF-16 code units: slicing to the byte cap left a
431
+ * result up to three times over it, so a mailbox of CJK or Cyrillic text sailed through while carrying
432
+ * a notice claiming it had been truncated. The value is encoded once here and both halves of the cut
433
+ * work on that buffer.
434
+ *
435
+ * @param {String} text - the result text
436
+ * @param {Boolean} [tail] - keep the END of an oversized value rather than its beginning
437
+ * @returns {String} the value itself, or a cut of it carrying the notice
381
438
  */
382
- function truncateToBytes(text, maxBytes) {
439
+ function capText(text, tail) {
383
440
  const buf = Buffer.from(text, 'utf8');
384
- if (buf.length <= maxBytes) {
441
+ if (buf.length <= MAX_TOOL_RESULT_BYTES) {
385
442
  return text;
386
443
  }
444
+ return tail ? LEADING_TRUNCATION_NOTICE(buf.length) + lastBytesOf(buf) : firstBytesOf(buf) + TRUNCATION_NOTICE(buf.length);
445
+ }
387
446
 
388
- let end = maxBytes;
389
- // 0b10xxxxxx marks a continuation byte, so back up until `end` sits on a lead byte
447
+ // The first MAX_TOOL_RESULT_BYTES of an encoded value, backed off any trailing continuation byte
448
+ // (0b10xxxxxx marks one) so the cut never splits a code point into a replacement character.
449
+ function firstBytesOf(buf) {
450
+ let end = MAX_TOOL_RESULT_BYTES;
390
451
  while (end > 0 && (buf[end] & 0xc0) === 0x80) {
391
452
  end--;
392
453
  }
393
-
394
454
  return buf.subarray(0, end).toString('utf8');
395
455
  }
396
456
 
397
- function jsonResult(value) {
398
- // Compact on purpose: an indent is pure padding to a model, it inflates every response by a
399
- // double-digit percentage, and it counts against the size cap below
400
- let text = JSON.stringify(value);
401
- let structuredContent = value;
402
-
403
- const size = Buffer.byteLength(text);
404
- if (size > MAX_TOOL_RESULT_BYTES) {
405
- text = truncateToBytes(text, MAX_TOOL_RESULT_BYTES) + TRUNCATION_NOTICE(size);
406
- // A structuredContent that repeats the oversized value would defeat the cap
407
- structuredContent = undefined;
457
+ // The last MAX_TOOL_RESULT_BYTES of an encoded value, starting on a whole code point and a whole line.
458
+ // A result that declares `tail` carries one record per line (an account log is one JSON entry per
459
+ // line), so a cut landing mid-line hands the reader a fragment that does not parse; the partial first
460
+ // line is dropped when there is a later one to start from.
461
+ function lastBytesOf(buf) {
462
+ let start = buf.length - MAX_TOOL_RESULT_BYTES;
463
+ while (start < buf.length && (buf[start] & 0xc0) === 0x80) {
464
+ start++;
408
465
  }
466
+ const lineBreak = buf.indexOf(0x0a, start);
467
+ return buf.subarray(lineBreak < 0 ? start : lineBreak + 1).toString('utf8');
468
+ }
409
469
 
410
- const result = { content: [{ type: 'text', text }] };
411
- if (structuredContent !== undefined && structuredContent !== null && typeof structuredContent === 'object') {
412
- result.structuredContent = structuredContent;
470
+ function jsonResult(value) {
471
+ // Compact on purpose: an indent is pure padding to a model, it inflates every response by a
472
+ // double-digit percentage, and it counts against the size cap
473
+ const text = JSON.stringify(value);
474
+ const capped = capText(text);
475
+
476
+ const result = { content: [{ type: 'text', text: capped }] };
477
+ // A structuredContent that repeats an oversized value would defeat the cap
478
+ if (capped === text && value !== null && typeof value === 'object') {
479
+ result.structuredContent = value;
413
480
  }
414
481
  return result;
415
482
  }
@@ -451,6 +518,11 @@ async function callTool({ server, tool, args, request }) {
451
518
  return textResult(`Missing required tool argument${missing.length > 1 ? 's' : ''}: ${missing.join(', ')}`, { isError: true });
452
519
  }
453
520
 
521
+ const dotSegments = dotSegmentArguments(tool.path, effective.args, effective.sources);
522
+ if (dotSegments.length) {
523
+ return textResult(`Invalid value for tool argument${dotSegments.length > 1 ? 's' : ''}: ${dotSegments.join(', ')}`, { isError: true });
524
+ }
525
+
454
526
  const payload = {};
455
527
  let hasPayload = false;
456
528
  for (const [key, sourceName] of effective.sources) {
@@ -508,7 +580,7 @@ async function callTool({ server, tool, args, request }) {
508
580
  }
509
581
 
510
582
  if (typeof res.result === 'string') {
511
- return textResult(res.result);
583
+ return textResult(res.result, { tail: tool.tail });
512
584
  }
513
585
 
514
586
  return jsonResult(dropPlaintextTwin(res.result));
@@ -551,7 +623,7 @@ function buildResourceUri(tool, args) {
551
623
  * The single spelling of what tools/list filters on, so a credential's view of the catalog is
552
624
  * decided in one place. Two rules, and a consumer that applies only one of them overstates the
553
625
  * catalog: the permission record, and the account binding - a credential bound to one account is
554
- * never offered the tools that take no account argument, because there is nothing to bind them to.
626
+ * never offered the tools that are not about one account, because there is nothing to bind them to.
555
627
  *
556
628
  * Advertisement only. tools/call dispatches whatever is asked and the injected inner request stays
557
629
  * the enforcement, so this is allowed to be a prediction rather than a gate.
@@ -563,7 +635,7 @@ function buildResourceUri(tool, args) {
563
635
  * @returns {Boolean}
564
636
  */
565
637
  function toolVisibleTo(entry, { tokenData, boundAccount }) {
566
- if (boundAccount && !entry.sources.has('account')) {
638
+ if (boundAccount && !entry.accountScoped) {
567
639
  return false;
568
640
  }
569
641
  // The scope bound first: a credential holding only the mail scope is not offered the
@@ -592,7 +664,7 @@ function toolVisibleTo(entry, { tokenData, boundAccount }) {
592
664
  * @returns {Object} the tool definition to advertise
593
665
  */
594
666
  function toolDefinitionFor(entry, { boundAccount } = {}) {
595
- if (!boundAccount || !entry.sources.has('account')) {
667
+ if (!boundAccount || !entry.accountScoped) {
596
668
  return entry.definition;
597
669
  }
598
670
 
@@ -2,21 +2,43 @@
2
2
 
3
3
  const { Writable, Readable, pipeline } = require('stream');
4
4
 
5
- // const { MessageChannel } = require('worker_threads');
6
- // const { port1, port2 } = new MessageChannel();
5
+ // Flow control. The writer may have this many bytes posted but not yet taken by the reader; the
6
+ // reader returns credit ({ ack: bytes }) as it hands chunks to its consumer, and the writer holds
7
+ // back the callback of the write that ran out of credit until some comes back. Without it the
8
+ // writer acknowledged every chunk at once, so the IMAP download ran at network speed whatever the
9
+ // HTTP client did, and a slow client left the whole message buffered in the API worker.
10
+ //
11
+ // The reader returns credit in batches of a quarter of the window rather than one ack per chunk,
12
+ // which doubled the cross-thread traffic of every transfer. Both sides have to agree on the
13
+ // window: a reader batching against a larger window than the writer holds would sit on the
14
+ // credit the writer is waiting for.
15
+ const DEFAULT_CREDIT_WINDOW = 1024 * 1024;
16
+ const ACK_BATCH_FRACTION = 4;
7
17
 
8
18
  class MessagePortWritable extends Writable {
9
- constructor(messagePort) {
19
+ constructor(messagePort, opts) {
10
20
  super();
11
21
  this.messagePort = messagePort;
12
22
  this.portClosed = false;
13
23
 
24
+ this.credit = (opts && opts.creditWindow) || DEFAULT_CREDIT_WINDOW;
25
+ this.pendingWrite = null;
26
+
14
27
  // The reader side posts { cancel: true } when it is torn down (e.g. the
15
28
  // HTTP client aborted the download). Stop the transfer so the upstream
16
29
  // source - and the IMAP lock it holds - is released.
17
30
  this.onPortMessage = message => {
18
31
  if (message && message.cancel) {
19
32
  this.destroy();
33
+ return;
34
+ }
35
+ if (message && typeof message.ack === 'number') {
36
+ this.credit += message.ack;
37
+ if (this.pendingWrite && this.credit > 0) {
38
+ let done = this.pendingWrite;
39
+ this.pendingWrite = null;
40
+ done();
41
+ }
20
42
  }
21
43
  };
22
44
 
@@ -81,7 +103,13 @@ class MessagePortWritable extends Writable {
81
103
  }
82
104
 
83
105
  this.postToPort({ value: chunk, done: false });
84
- done();
106
+ this.credit -= chunk.length;
107
+
108
+ if (this.credit > 0 || this.portClosed) {
109
+ return done();
110
+ }
111
+ // Out of credit: the next write waits until the reader has taken some of what was sent
112
+ this.pendingWrite = done;
85
113
  }
86
114
 
87
115
  _final(done) {
@@ -91,6 +119,9 @@ class MessagePortWritable extends Writable {
91
119
  }
92
120
 
93
121
  _destroy(err, done) {
122
+ // A write waiting for credit is abandoned with the stream; destroy() does not wait for it
123
+ this.pendingWrite = null;
124
+
94
125
  // Abnormal termination: tell the reader so a truncated transfer is not
95
126
  // mistaken for a complete message, then release the port.
96
127
  if (err) {
@@ -102,7 +133,7 @@ class MessagePortWritable extends Writable {
102
133
  }
103
134
 
104
135
  class MessagePortReadable extends Readable {
105
- constructor(messagePort) {
136
+ constructor(messagePort, opts) {
106
137
  super();
107
138
  this.messagePort = messagePort;
108
139
 
@@ -110,6 +141,10 @@ class MessagePortReadable extends Readable {
110
141
  this.portClosed = false;
111
142
  this.transferComplete = false;
112
143
 
144
+ // Credit taken from the writer but not yet returned; posted once it reaches the threshold
145
+ this.pendingAck = 0;
146
+ this.ackThreshold = Math.max(1, Math.ceil(((opts && opts.creditWindow) || DEFAULT_CREDIT_WINDOW) / ACK_BATCH_FRACTION));
147
+
113
148
  this.readableQueue = [];
114
149
  this.onPortMessage = message => {
115
150
  if (!message) {
@@ -150,9 +185,32 @@ class MessagePortReadable extends Readable {
150
185
  while (this.canRead && this.readableQueue.length) {
151
186
  let message = this.readableQueue.shift();
152
187
  if (message.done) {
188
+ this.flushAck();
153
189
  return this.push(null);
154
190
  }
155
- this.canRead = this.push(Buffer.from(message.value));
191
+ let chunk = Buffer.from(message.value);
192
+ this.canRead = this.push(chunk);
193
+ // The chunk has left the queue for the consumer, so the writer may send that much more.
194
+ // readableQueue therefore never holds more than the writer's credit window.
195
+ this.pendingAck += chunk.length;
196
+ if (this.pendingAck >= this.ackThreshold) {
197
+ this.flushAck();
198
+ }
199
+ }
200
+ }
201
+
202
+ // Returns the accumulated credit to the writer. Not called from _destroy(): the cancel posted
203
+ // there destroys the writer, so credit returned alongside it would never be spent.
204
+ flushAck() {
205
+ let bytes = this.pendingAck;
206
+ this.pendingAck = 0;
207
+ if (this.portClosed || !bytes) {
208
+ return;
209
+ }
210
+ try {
211
+ this.messagePort.postMessage({ ack: bytes });
212
+ } catch (err) {
213
+ // ignore - the producer may already be gone
156
214
  }
157
215
  }
158
216
 
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
3
  const fs = require('fs');
4
- const { fetch: undiciFetch } = require('undici');
4
+ const { fetch: undiciFetch, Agent } = require('undici');
5
5
  const packageData = require('../../package.json');
6
- const { httpAgent } = require('../tools');
6
+ const { httpAgent, parseRetryAfter } = require('../tools');
7
7
  const { makeError, validateConfig, extractFromFormat } = require('./external-account-config');
8
8
 
9
9
  const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';
@@ -15,6 +15,17 @@ const TOKEN_EXPIRY_SKEW_MS = 60 * 1000;
15
15
  const DEFAULT_FEDERATED_TOKEN_TTL_MS = 3600 * 1000;
16
16
  const USER_AGENT = `${packageData.name}/${packageData.version} (+${packageData.homepage})`;
17
17
 
18
+ // The URL credential source is a local identity endpoint (a cloud metadata server such as
19
+ // 169.254.169.254, a sidecar), reachable only from this host. It must never go through the
20
+ // configured HTTP or SOCKS proxy: the proxy cannot reach it, and the request headers and the
21
+ // returned identity token would be handed to the proxy. The STS and IAM calls are ordinary
22
+ // outbound traffic and keep the shared dispatcher
23
+ const credentialSourceAgent = new Agent({
24
+ connectTimeout: 30 * 1000,
25
+ headersTimeout: 60 * 1000,
26
+ bodyTimeout: 60 * 1000
27
+ });
28
+
18
29
  class ExternalAccountSigner {
19
30
  constructor(opts) {
20
31
  opts = opts || {};
@@ -81,7 +92,7 @@ class ExternalAccountSigner {
81
92
  res = await this._fetch(source.url, {
82
93
  method: 'GET',
83
94
  headers,
84
- dispatcher: httpAgent.retry
95
+ dispatcher: credentialSourceAgent
85
96
  });
86
97
  } catch (err) {
87
98
  throw makeError(`Failed to fetch subject token from ${source.url}: ${err.message}`, 'ESubjectTokenRead', null, { cause: err });
@@ -201,17 +212,9 @@ class ExternalAccountSigner {
201
212
  this._log('callSignJwt', 'POST', url, res.ok, res.status);
202
213
 
203
214
  if (!res.ok) {
204
- let retryAfter = null;
205
- if (res.status === 429) {
206
- let header = res.headers.get('retry-after');
207
- if (header) {
208
- let parsed = parseInt(header, 10);
209
- retryAfter = isNaN(parsed) ? null : parsed;
210
- }
211
- }
212
215
  throw makeError(`signJwt returned HTTP ${res.status}`, 'ESignJwt', res.status, {
213
216
  response: responseJson || null,
214
- retryAfter
217
+ retryAfter: res.status === 429 ? parseRetryAfter(res.headers) : null
215
218
  });
216
219
  }
217
220
 
@@ -258,4 +261,4 @@ class ExternalAccountSigner {
258
261
  }
259
262
 
260
263
  module.exports.ExternalAccountSigner = ExternalAccountSigner;
261
- module.exports.__test__ = { validateConfig, extractFromFormat, makeError };
264
+ module.exports.__test__ = { validateConfig, extractFromFormat, makeError, credentialSourceAgent };
@@ -1,12 +1,13 @@
1
1
  'use strict';
2
2
 
3
3
  const packageData = require('../../package.json');
4
- const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError } = require('../tools');
4
+ const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError, parseRetryAfter } = require('../tools');
5
5
  const crypto = require('crypto');
6
6
 
7
7
  const { fetch: fetchCmd } = require('undici');
8
8
 
9
9
  const { ExternalAccountSigner } = require('./external-account-signer');
10
+ const { fetchTokenRequest } = require('./token-fetch');
10
11
 
11
12
  const SERVICE_AUTH_METHODS = new Set(['serviceKey', 'externalAccount']);
12
13
 
@@ -48,6 +49,14 @@ function parseExternalAccountConfig(externalAccount) {
48
49
  }
49
50
  }
50
51
 
52
+ // The two providers that reach Gmail, whichever way they authenticate: `gmail` sends a user through
53
+ // Google's consent screen, `gmailService` presents a service account's domain-wide delegation. What
54
+ // they reach (IMAP XOAUTH2 or the Gmail HTTP API) is decided by baseScopes, not by which of these it is.
55
+ const GMAIL_PROVIDERS = new Set(['gmail', 'gmailService']);
56
+
57
+ // Every Gmail scope is this plus a short name, which is the form the app form's skipScopes presets use
58
+ const GMAIL_SCOPE_PREFIX = 'https://www.googleapis.com/auth';
59
+
51
60
  const GMAIL_SCOPES = {
52
61
  imap: ['https://mail.google.com/'],
53
62
  api: ['https://www.googleapis.com/auth/gmail.modify'],
@@ -205,6 +214,24 @@ const formatFetchResponse = (responseObj, logRaw) => {
205
214
  return data;
206
215
  };
207
216
 
217
+ /**
218
+ * The Google Workspace or Cloud organization domain an ID token belongs to, or null.
219
+ *
220
+ * `hd=*` on the authorization URL (generateAuthUrl below, for an application with "Show only Google
221
+ * Workspace accounts") only filters the account chooser Google SHOWS. A link assembled without that
222
+ * argument, or a user who switches account inside the chooser, reaches the callback with a consumer
223
+ * account and used to complete the setup anyway. The hosted-domain claim of the ID token is the
224
+ * back-channel answer to the same question: Google sets it only for an account that belongs to a
225
+ * Workspace or Cloud organization, so its absence is what a consumer account looks like.
226
+ *
227
+ * @param {Object|null} idTokenPayload - decoded ID token payload (lib/decode-jwt-payload.js)
228
+ * @returns {String|null} the hosted domain, or null when the token names none
229
+ */
230
+ function workspaceDomainOf(idTokenPayload) {
231
+ const hd = idTokenPayload && typeof idTokenPayload.hd === 'string' ? idTokenPayload.hd.trim() : '';
232
+ return hd || null;
233
+ }
234
+
208
235
  class GmailOauth {
209
236
  constructor(opts) {
210
237
  const defaultBaseScopes = (opts.baseScopes && GMAIL_SCOPES[opts.baseScopes]) || GMAIL_SCOPES.imap;
@@ -262,11 +289,16 @@ class GmailOauth {
262
289
  // 3-legged OAuth has no serviceClient and never reaches generateServiceRequest.
263
290
  if (this.serviceClient) {
264
291
  if (this.authMethod === 'externalAccount') {
265
- this.signer = new ExternalAccountSigner({
266
- config: parseExternalAccountConfig(opts.externalAccount),
267
- logger: this.logger,
268
- logRaw: this.logRaw
269
- });
292
+ // The signer caches the federated token and deduplicates concurrent refreshes, which
293
+ // only pays off when it outlives this client: every token renewal builds a new
294
+ // GmailOauth, so the app handler passes in a signer it keeps per app
295
+ this.signer =
296
+ opts.externalAccountSigner ||
297
+ new ExternalAccountSigner({
298
+ config: parseExternalAccountConfig(opts.externalAccount),
299
+ logger: this.logger,
300
+ logRaw: this.logRaw
301
+ });
270
302
 
271
303
  // With Workload Identity Federation the JWT is signed by the
272
304
  // impersonated service account (derived from the external account
@@ -367,12 +399,12 @@ class GmailOauth {
367
399
  body: tokenRequest.body
368
400
  };
369
401
 
370
- let res = await fetchCmd(
371
- requestUrl,
372
- Object.assign(fetchOpts, {
373
- dispatcher: httpAgent.retry
374
- })
375
- );
402
+ let res = await fetchTokenRequest(requestUrl, fetchOpts, {
403
+ grant: 'authorization_code',
404
+ provider: this.provider,
405
+ clientId: this.clientId,
406
+ serviceClient: this.serviceClient
407
+ });
376
408
 
377
409
  let responseJson;
378
410
  try {
@@ -482,12 +514,12 @@ class GmailOauth {
482
514
  body: bodyString
483
515
  };
484
516
 
485
- let res = await fetchCmd(
486
- requestUrl,
487
- Object.assign(fetchOpts, {
488
- dispatcher: httpAgent.retry
489
- })
490
- );
517
+ let res = await fetchTokenRequest(requestUrl, fetchOpts, {
518
+ grant: 'refresh_token',
519
+ provider: this.provider,
520
+ clientId: this.clientId,
521
+ serviceClient: this.serviceClient
522
+ });
491
523
 
492
524
  let responseJson;
493
525
  try {
@@ -572,7 +604,11 @@ class GmailOauth {
572
604
  Authorization: `Bearer ${accessToken}`,
573
605
  'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
574
606
  },
575
- dispatcher: httpAgent.retry,
607
+ // Sent exactly once. Which failures are worth repeating depends on the method and on
608
+ // what Gmail answered, and that is decided by the request layer above this one
609
+ // (lib/email-client/api-retry.js); a transport that retried on its own replayed sends
610
+ // after a socket drop and multiplied throttled calls
611
+ dispatcher: httpAgent.fetch,
576
612
  signal: options.signal || undefined
577
613
  };
578
614
 
@@ -580,15 +616,10 @@ class GmailOauth {
580
616
  if (!Buffer.isBuffer(payload)) {
581
617
  reqData.headers.Accept = 'application/json';
582
618
  reqData.headers['Content-Type'] = options?.contentType || 'application/json';
583
- // Use string body instead of Buffer to avoid ArrayBuffer detachment on retry
584
619
  reqData.body = JSON.stringify(payload);
585
620
  } else {
586
621
  reqData.headers['Content-Type'] = options?.contentType || 'application/x-www-form-urlencoded';
587
622
  reqData.body = payload;
588
- if (payload.length > 0) {
589
- // Non-empty buffers use non-retry dispatcher to prevent ArrayBuffer detachment
590
- reqData.dispatcher = httpAgent.fetch;
591
- }
592
623
  }
593
624
  } else if (payload && method === 'get') {
594
625
  let parsedUrl = new URL(url);
@@ -626,14 +657,12 @@ class GmailOauth {
626
657
  reqTime
627
658
  };
628
659
 
629
- // Capture Retry-After header for rate limiting (429) responses
630
- if (res.status === 429) {
631
- let retryAfterHeader = res.headers.get('retry-after');
632
- if (retryAfterHeader) {
633
- let parsed = parseInt(retryAfterHeader, 10);
634
- err.retryAfter = isNaN(parsed) ? null : parsed;
635
- err.oauthRequest.retryAfter = err.retryAfter;
636
- }
660
+ // Capture Retry-After (sent with 429, and with rate-limit 403s and 503s) so the
661
+ // retry layer can honour it
662
+ let retryAfter = parseRetryAfter(res.headers);
663
+ if (retryAfter !== null) {
664
+ err.retryAfter = retryAfter;
665
+ err.oauthRequest.retryAfter = retryAfter;
637
666
  }
638
667
 
639
668
  try {
@@ -824,8 +853,11 @@ module.exports.GmailOauth = GmailOauth;
824
853
  // Exported for unit testing the auth error-to-flag mapping.
825
854
  module.exports.checkForFlags = checkForFlags;
826
855
  module.exports.checkForUserFlags = checkForUserFlags;
856
+ module.exports.workspaceDomainOf = workspaceDomainOf;
827
857
  module.exports.GMAIL_SCOPES = GMAIL_SCOPES;
828
858
  module.exports.GMAIL_API_SCOPES = GMAIL_API_SCOPES;
859
+ module.exports.GMAIL_PROVIDERS = GMAIL_PROVIDERS;
860
+ module.exports.GMAIL_SCOPE_PREFIX = GMAIL_SCOPE_PREFIX;
829
861
  module.exports.OPENID_SCOPES = OPENID_SCOPES;
830
862
  module.exports.LocalKeySigner = LocalKeySigner;
831
863
  module.exports.parseExternalAccountConfig = parseExternalAccountConfig;