emailengine-app 2.82.0 → 2.82.2

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 (67) hide show
  1. package/.ncurc.js +23 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +51 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/bin/emailengine.js +77 -7
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +35 -10
  8. package/lib/api-routes/account-binding.js +58 -0
  9. package/lib/api-routes/account-routes.js +48 -9
  10. package/lib/api-routes/behavior-notes.js +4 -0
  11. package/lib/api-routes/gateway-routes.js +10 -2
  12. package/lib/api-routes/message-routes.js +10 -3
  13. package/lib/api-routes/outbox-routes.js +1 -1
  14. package/lib/api-routes/settings-routes.js +1 -2
  15. package/lib/api-routes/token-routes.js +1 -1
  16. package/lib/autodetect-imap-settings.js +146 -4
  17. package/lib/consts.js +12 -0
  18. package/lib/db.js +1 -19
  19. package/lib/delivery-error.js +68 -1
  20. package/lib/email-client/base-client.js +6 -13
  21. package/lib/email-client/credential-errors.js +21 -5
  22. package/lib/email-client/gmail-client.js +2 -2
  23. package/lib/email-client/imap-client.js +2 -1
  24. package/lib/email-client/message-builder.js +41 -11
  25. package/lib/email-client/outlook-client.js +263 -84
  26. package/lib/email-client/outlook-fallback-poll.js +30 -0
  27. package/lib/enum-descriptions.js +5 -1
  28. package/lib/export.js +8 -2
  29. package/lib/gateway.js +5 -0
  30. package/lib/get-secret.js +1 -21
  31. package/lib/mcp/tools.js +95 -36
  32. package/lib/oauth/gmail.js +42 -12
  33. package/lib/oauth/mail-ru.js +24 -17
  34. package/lib/oauth/outlook.js +34 -24
  35. package/lib/oauth/scope-checker.js +35 -1
  36. package/lib/oauth/scope-list.js +55 -0
  37. package/lib/oauth/token-fetch.js +47 -0
  38. package/lib/oauth2-apps.js +16 -47
  39. package/lib/outbox.js +2 -7
  40. package/lib/queue-retention.js +4 -2
  41. package/lib/read-env-value.js +33 -2
  42. package/lib/schemas.js +62 -15
  43. package/lib/token-audit-log.js +3 -2
  44. package/lib/tools.js +1 -1
  45. package/lib/ui-routes/account-routes.js +40 -7
  46. package/lib/ui-routes/oauth-config-routes.js +3 -14
  47. package/lib/ui-routes/outlook-subscription-view.js +36 -0
  48. package/lib/ui-routes/route-helpers.js +25 -37
  49. package/lib/ui-routes/special-use-paths.js +33 -0
  50. package/lib/utils/network.js +9 -17
  51. package/package.json +18 -18
  52. package/sbom.json +1 -1
  53. package/server.js +21 -3
  54. package/setup-production.sh +16 -7
  55. package/static/licenses.html +30 -20
  56. package/translations/messages.pot +74 -56
  57. package/views/account-workspace-error.hbs +30 -0
  58. package/views/accounts/account.hbs +14 -6
  59. package/views/accounts/edit.hbs +11 -2
  60. package/views/internals/index.hbs +1 -1
  61. package/views/partials/gmail_api_scopes.hbs +16 -0
  62. package/views/partials/oauth_form.hbs +67 -94
  63. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  64. package/views/partials/scope_info.hbs +14 -23
  65. package/workers/api.js +62 -27
  66. package/workers/imap.js +6 -3
  67. package/workers/submit.js +2 -5
@@ -27,7 +27,11 @@ const ENUM_DESCRIPTIONS = {
27
27
  disconnected: 'The connection dropped and EmailEngine is retrying with backoff',
28
28
  paused: 'Syncing was paused through the API. No connection is maintained',
29
29
  authenticationError: 'The credentials were rejected. Requires re-authentication before syncing resumes',
30
- connectError: 'The server could not be reached or the TLS handshake failed. Retried with backoff',
30
+ // No note here about account operations answering 503: every state outside connected,
31
+ // connecting and syncing does that, so saying it under one of them reads as if the others
32
+ // did not
33
+ connectError:
34
+ 'The server could not be reached, the TLS handshake failed, or - for an MS Graph account - its change subscription could not be created or renewed, which leaves the account with no way to learn about new mail. Retried with backoff',
31
35
  unset: 'The account is not syncing: either no IMAP or OAuth2 configuration is set, or syncing was switched off - by the operator, or automatically after repeated authentication failures'
32
36
  },
33
37
 
package/lib/export.js CHANGED
@@ -12,6 +12,7 @@ const settings = require('./settings');
12
12
  const logger = require('./logger');
13
13
  const getSecret = require('./get-secret');
14
14
  const { escapeRedisGlob } = require('./tools');
15
+ const { readEnvValue } = require('./read-env-value');
15
16
  const { ImapFlowErrorCode } = require('imapflow');
16
17
 
17
18
  const {
@@ -340,13 +341,18 @@ function getExportQueueKey(account, exportId) {
340
341
  return `${REDIS_PREFIX}exq:${account}:${exportId}`;
341
342
  }
342
343
 
344
+ // The directory exports are written to and served from. Deliberately NOT a setting: the value is a
345
+ // filesystem path this process writes files into, so a settings editor that could move it would be an
346
+ // arbitrary file write, and an operator picks a deployment path through the environment anyway. This
347
+ // used to consult an `exportPath` setting first, which no schema declares and so nothing could ever
348
+ // have written.
343
349
  async function getExportPath() {
344
- return (await settings.get('exportPath')) || process.env.EENGINE_EXPORT_PATH || os.tmpdir();
350
+ return readEnvValue('EENGINE_EXPORT_PATH') || os.tmpdir();
345
351
  }
346
352
 
347
353
  async function getExportMaxAge() {
348
354
  const settingsMaxAge = await settings.get('exportMaxAge');
349
- const envMaxAge = process.env.EENGINE_EXPORT_MAX_AGE;
355
+ const envMaxAge = readEnvValue('EENGINE_EXPORT_MAX_AGE');
350
356
 
351
357
  if (settingsMaxAge && !isNaN(settingsMaxAge)) return Number(settingsMaxAge);
352
358
  if (envMaxAge && !isNaN(envMaxAge)) return Number(envMaxAge);
package/lib/gateway.js CHANGED
@@ -169,6 +169,11 @@ class Gateway {
169
169
  // account's own SMTP server, which nothing asked for
170
170
  let error = Boom.boomify(new Error(`Gateway "${this.gateway}" was not found`), { statusCode: 404 });
171
171
  error.code = 'GatewayNotFound';
172
+ // Boom serializes output.payload and not the error's own properties, so the code has to be
173
+ // written there as well or an in-process caller (GET /v1/gateway/{gateway}, the delivery
174
+ // test) answers a 404 without the `code` field every other not-found answer carries.
175
+ // handleError() passes a Boom error through untouched (lib/api-routes/route-helpers.js)
176
+ error.output.payload.code = error.code;
172
177
  // Boom keeps the status in output.statusCode, which the worker RPC hop does not carry
173
178
  // (lib/worker-rpc-error.js), so the submit worker and the API caller get it here too
174
179
  error.statusCode = 404;
package/lib/get-secret.js CHANGED
@@ -6,30 +6,10 @@ if (!process.env.EE_ENV_LOADED) {
6
6
  }
7
7
 
8
8
  const config = require('@zone-eu/wild-config');
9
- const fs = require('fs');
10
- const logger = require('./logger');
9
+ const { readEnvValue } = require('./read-env-value');
11
10
 
12
11
  config.service = config.service || {};
13
12
 
14
- // duplicate function declaration to avoid requiring tools.js
15
- const readEnvValue = key => {
16
- if (key in process.env) {
17
- return process.env[key];
18
- }
19
-
20
- if (typeof process.env[`${key}_FILE`] === 'string' && process.env[`${key}_FILE`]) {
21
- try {
22
- // try to load from file
23
- process.env[key] = fs.readFileSync(process.env[`${key}_FILE`], 'utf-8').replace(/\r?\n$/, '');
24
- logger.trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
25
- } catch (err) {
26
- logger.error({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
27
- process.env[key] = '';
28
- }
29
- return process.env[key];
30
- }
31
- };
32
-
33
13
  const ENCRYPT_SECRET = readEnvValue('EENGINE_SECRET') || config.service.secret;
34
14
 
35
15
  async function getSecret() {
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,6 +16,7 @@
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');
@@ -39,9 +40,27 @@ const MAX_TOOL_BINARY_BYTES = 1024 * 1024;
39
40
 
40
41
  const TRUNCATION_NOTICE = size => `\n\n[Result truncated by EmailEngine: the full response was ${size} bytes. Narrow the request to see the rest.]`;
41
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
+
42
48
  // Every key a plugins.mcp block may carry. The one place the block's shape is written down, so a
43
49
  // misspelling is a build failure rather than a knob that quietly does nothing.
44
- 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
+ ]);
45
64
 
46
65
  // One registry per Hapi server, built on first use and held for the life of the worker - route
47
66
  // definitions cannot change while it runs, and the build walks every joi schema of every wrapped
@@ -279,7 +298,19 @@ function buildToolRegistry(routes) {
279
298
  // are declared: the other half of what tools/list filters on, and what the admin
280
299
  // pages group and count by
281
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),
282
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,
283
314
  resourceUriTemplate: options.resourceUriTemplate
284
315
  });
285
316
  }
@@ -291,7 +322,7 @@ function buildToolRegistry(routes) {
291
322
  // the worker and three admin pages plus the MCP door read this.
292
323
  const grants = tools.map(tool => {
293
324
  const entry = byName.get(tool.name);
294
- 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);
295
326
  });
296
327
 
297
328
  return { tools, byName, grants };
@@ -318,7 +349,7 @@ function buildToolRegistry(routes) {
318
349
  function effectiveArguments(tool, args, boundAccount) {
319
350
  const effective = Object.assign({}, args, tool.forcedValues);
320
351
 
321
- 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 === '')) {
322
353
  effective.account = boundAccount;
323
354
  }
324
355
 
@@ -371,8 +402,22 @@ function buildQuery(args, sources) {
371
402
  return rendered ? `?${rendered}` : '';
372
403
  }
373
404
 
374
- function textResult(text, { isError = false } = {}) {
375
- 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) }] };
376
421
  if (isError) {
377
422
  result.isError = true;
378
423
  }
@@ -380,44 +425,58 @@ function textResult(text, { isError = false } = {}) {
380
425
  }
381
426
 
382
427
  /**
383
- * 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.
429
+ *
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.
384
434
  *
385
- * String.slice() counts UTF-16 code units, so slicing to the byte cap left a result up to three
386
- * times over it - a mailbox of CJK or Cyrillic text sailed through the cap while carrying a
387
- * notice claiming it had been truncated. Cutting the encoded bytes instead, then walking back off
388
- * any trailing continuation byte, keeps the budget honest and never emits a split code point.
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
389
438
  */
390
- function truncateToBytes(text, maxBytes) {
439
+ function capText(text, tail) {
391
440
  const buf = Buffer.from(text, 'utf8');
392
- if (buf.length <= maxBytes) {
441
+ if (buf.length <= MAX_TOOL_RESULT_BYTES) {
393
442
  return text;
394
443
  }
444
+ return tail ? LEADING_TRUNCATION_NOTICE(buf.length) + lastBytesOf(buf) : firstBytesOf(buf) + TRUNCATION_NOTICE(buf.length);
445
+ }
395
446
 
396
- let end = maxBytes;
397
- // 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;
398
451
  while (end > 0 && (buf[end] & 0xc0) === 0x80) {
399
452
  end--;
400
453
  }
401
-
402
454
  return buf.subarray(0, end).toString('utf8');
403
455
  }
404
456
 
405
- function jsonResult(value) {
406
- // Compact on purpose: an indent is pure padding to a model, it inflates every response by a
407
- // double-digit percentage, and it counts against the size cap below
408
- let text = JSON.stringify(value);
409
- let structuredContent = value;
410
-
411
- const size = Buffer.byteLength(text);
412
- if (size > MAX_TOOL_RESULT_BYTES) {
413
- text = truncateToBytes(text, MAX_TOOL_RESULT_BYTES) + TRUNCATION_NOTICE(size);
414
- // A structuredContent that repeats the oversized value would defeat the cap
415
- 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++;
416
465
  }
466
+ const lineBreak = buf.indexOf(0x0a, start);
467
+ return buf.subarray(lineBreak < 0 ? start : lineBreak + 1).toString('utf8');
468
+ }
417
469
 
418
- const result = { content: [{ type: 'text', text }] };
419
- if (structuredContent !== undefined && structuredContent !== null && typeof structuredContent === 'object') {
420
- 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;
421
480
  }
422
481
  return result;
423
482
  }
@@ -521,7 +580,7 @@ async function callTool({ server, tool, args, request }) {
521
580
  }
522
581
 
523
582
  if (typeof res.result === 'string') {
524
- return textResult(res.result);
583
+ return textResult(res.result, { tail: tool.tail });
525
584
  }
526
585
 
527
586
  return jsonResult(dropPlaintextTwin(res.result));
@@ -564,7 +623,7 @@ function buildResourceUri(tool, args) {
564
623
  * The single spelling of what tools/list filters on, so a credential's view of the catalog is
565
624
  * decided in one place. Two rules, and a consumer that applies only one of them overstates the
566
625
  * catalog: the permission record, and the account binding - a credential bound to one account is
567
- * 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.
568
627
  *
569
628
  * Advertisement only. tools/call dispatches whatever is asked and the injected inner request stays
570
629
  * the enforcement, so this is allowed to be a prediction rather than a gate.
@@ -576,7 +635,7 @@ function buildResourceUri(tool, args) {
576
635
  * @returns {Boolean}
577
636
  */
578
637
  function toolVisibleTo(entry, { tokenData, boundAccount }) {
579
- if (boundAccount && !entry.sources.has('account')) {
638
+ if (boundAccount && !entry.accountScoped) {
580
639
  return false;
581
640
  }
582
641
  // The scope bound first: a credential holding only the mail scope is not offered the
@@ -605,7 +664,7 @@ function toolVisibleTo(entry, { tokenData, boundAccount }) {
605
664
  * @returns {Object} the tool definition to advertise
606
665
  */
607
666
  function toolDefinitionFor(entry, { boundAccount } = {}) {
608
- if (!boundAccount || !entry.sources.has('account')) {
667
+ if (!boundAccount || !entry.accountScoped) {
609
668
  return entry.definition;
610
669
  }
611
670
 
@@ -7,6 +7,7 @@ const crypto = require('crypto');
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;
@@ -372,12 +399,12 @@ class GmailOauth {
372
399
  body: tokenRequest.body
373
400
  };
374
401
 
375
- let res = await fetchCmd(
376
- requestUrl,
377
- Object.assign(fetchOpts, {
378
- dispatcher: httpAgent.retry
379
- })
380
- );
402
+ let res = await fetchTokenRequest(requestUrl, fetchOpts, {
403
+ grant: 'authorization_code',
404
+ provider: this.provider,
405
+ clientId: this.clientId,
406
+ serviceClient: this.serviceClient
407
+ });
381
408
 
382
409
  let responseJson;
383
410
  try {
@@ -487,12 +514,12 @@ class GmailOauth {
487
514
  body: bodyString
488
515
  };
489
516
 
490
- let res = await fetchCmd(
491
- requestUrl,
492
- Object.assign(fetchOpts, {
493
- dispatcher: httpAgent.retry
494
- })
495
- );
517
+ let res = await fetchTokenRequest(requestUrl, fetchOpts, {
518
+ grant: 'refresh_token',
519
+ provider: this.provider,
520
+ clientId: this.clientId,
521
+ serviceClient: this.serviceClient
522
+ });
496
523
 
497
524
  let responseJson;
498
525
  try {
@@ -826,8 +853,11 @@ module.exports.GmailOauth = GmailOauth;
826
853
  // Exported for unit testing the auth error-to-flag mapping.
827
854
  module.exports.checkForFlags = checkForFlags;
828
855
  module.exports.checkForUserFlags = checkForUserFlags;
856
+ module.exports.workspaceDomainOf = workspaceDomainOf;
829
857
  module.exports.GMAIL_SCOPES = GMAIL_SCOPES;
830
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;
831
861
  module.exports.OPENID_SCOPES = OPENID_SCOPES;
832
862
  module.exports.LocalKeySigner = LocalKeySigner;
833
863
  module.exports.parseExternalAccountConfig = parseExternalAccountConfig;
@@ -2,6 +2,7 @@
2
2
 
3
3
  const packageData = require('../../package.json');
4
4
  const { fetch: fetchCmd } = require('undici');
5
+ const { fetchTokenRequest } = require('./token-fetch');
5
6
  const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError } = require('../tools');
6
7
 
7
8
  const MAIL_RU_SCOPES = ['userinfo', 'mail.imap'];
@@ -109,16 +110,19 @@ class MailRuOauth {
109
110
  let requestUrl = tokenRequest.url;
110
111
  let method = 'post';
111
112
 
112
- let res = await fetchCmd(tokenRequest.url, {
113
- method,
114
- headers: {
115
- 'Content-Type': 'application/x-www-form-urlencoded',
116
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`,
117
- Authorization: `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString('base64')}`
113
+ let res = await fetchTokenRequest(
114
+ tokenRequest.url,
115
+ {
116
+ method,
117
+ headers: {
118
+ 'Content-Type': 'application/x-www-form-urlencoded',
119
+ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`,
120
+ Authorization: `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString('base64')}`
121
+ },
122
+ body: tokenRequest.body
118
123
  },
119
- body: tokenRequest.body,
120
- dispatcher: httpAgent.retry
121
- });
124
+ { grant: 'authorization_code', provider: this.provider, clientId: this.clientId }
125
+ );
122
126
 
123
127
  let responseJson;
124
128
  try {
@@ -194,15 +198,18 @@ class MailRuOauth {
194
198
  let method = 'post';
195
199
 
196
200
  const bodyString = url.searchParams.toString();
197
- let res = await fetchCmd(requestUrl, {
198
- method,
199
- headers: {
200
- 'Content-Type': 'application/x-www-form-urlencoded',
201
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
201
+ let res = await fetchTokenRequest(
202
+ requestUrl,
203
+ {
204
+ method,
205
+ headers: {
206
+ 'Content-Type': 'application/x-www-form-urlencoded',
207
+ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
208
+ },
209
+ body: bodyString
202
210
  },
203
- body: bodyString,
204
- dispatcher: httpAgent.retry
205
- });
211
+ { grant: 'refresh_token', provider: this.provider, clientId: this.clientId }
212
+ );
206
213
 
207
214
  let responseJson;
208
215
  try {
@@ -4,6 +4,7 @@ const packageData = require('../../package.json');
4
4
  const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError, parseRetryAfter } = require('../tools');
5
5
 
6
6
  const { fetch: fetchCmd } = require('undici');
7
+ const { fetchTokenRequest } = require('./token-fetch');
7
8
 
8
9
  // Individual MS Graph API scope names for detection
9
10
  // These are the scope names extracted from full MS Graph API scope URLs
@@ -269,15 +270,18 @@ class OutlookOauth {
269
270
  let requestUrl = tokenRequest.url;
270
271
  let method = 'post';
271
272
 
272
- let res = await fetchCmd(tokenRequest.url, {
273
- method,
274
- headers: {
275
- 'Content-Type': 'application/x-www-form-urlencoded',
276
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
273
+ let res = await fetchTokenRequest(
274
+ tokenRequest.url,
275
+ {
276
+ method,
277
+ headers: {
278
+ 'Content-Type': 'application/x-www-form-urlencoded',
279
+ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
280
+ },
281
+ body: tokenRequest.body
277
282
  },
278
- body: tokenRequest.body,
279
- dispatcher: httpAgent.retry
280
- });
283
+ { grant: 'authorization_code', provider: this.provider, clientId: this.clientId, authority: this.authority }
284
+ );
281
285
 
282
286
  let responseJson;
283
287
  try {
@@ -370,15 +374,18 @@ class OutlookOauth {
370
374
  let method = 'post';
371
375
 
372
376
  const bodyString = url.searchParams.toString();
373
- let res = await fetchCmd(requestUrl, {
374
- method,
375
- headers: {
376
- 'Content-Type': 'application/x-www-form-urlencoded',
377
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
377
+ let res = await fetchTokenRequest(
378
+ requestUrl,
379
+ {
380
+ method,
381
+ headers: {
382
+ 'Content-Type': 'application/x-www-form-urlencoded',
383
+ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
384
+ },
385
+ body: bodyString
378
386
  },
379
- body: bodyString,
380
- dispatcher: httpAgent.retry
381
- });
387
+ { grant: 'refresh_token', provider: this.provider, clientId: this.clientId, authority: this.authority }
388
+ );
382
389
 
383
390
  let responseJson;
384
391
  try {
@@ -461,15 +468,18 @@ class OutlookOauth {
461
468
  let method = 'post';
462
469
 
463
470
  const bodyString = url.searchParams.toString();
464
- let res = await fetchCmd(requestUrl, {
465
- method,
466
- headers: {
467
- 'Content-Type': 'application/x-www-form-urlencoded',
468
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
471
+ let res = await fetchTokenRequest(
472
+ requestUrl,
473
+ {
474
+ method,
475
+ headers: {
476
+ 'Content-Type': 'application/x-www-form-urlencoded',
477
+ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
478
+ },
479
+ body: bodyString
469
480
  },
470
- body: bodyString,
471
- dispatcher: httpAgent.retry
472
- });
481
+ { grant: 'client_credentials', provider: this.provider, clientId: this.clientId, authority: this.authority }
482
+ );
473
483
 
474
484
  let responseJson;
475
485
  try {
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const { GMAIL_API_SCOPES } = require('./gmail');
3
+ const { GMAIL_API_SCOPES, GMAIL_SCOPES, GMAIL_PROVIDERS, GMAIL_SCOPE_PREFIX } = require('./gmail');
4
+ const { formatExtraScopes } = require('./scope-list');
4
5
  const { OUTLOOK_API_SCOPES } = require('./outlook');
5
6
 
6
7
  // Known Microsoft Graph API endpoints across different cloud environments
@@ -173,6 +174,38 @@ function checkOutlookScopes(accountData, logger) {
173
174
  return checkAccountScopes('outlook', scopes, logger);
174
175
  }
175
176
 
177
+ /**
178
+ * Whether an OAuth2 APPLICATION is configured for sending only, as the app page presents it.
179
+ *
180
+ * Only an API-based Gmail app can be: `baseScopes: 'api'` is what makes one reach the Gmail HTTP API
181
+ * rather than IMAP XOAUTH2, and it is not a property of the provider - a service account delegated
182
+ * gmail.send alone is as send-only as an interactive app, which the admin route used to miss by keying
183
+ * on `provider === 'gmail'`.
184
+ *
185
+ * Judged on the scopes the app really requests, which is the list the authentication URL is built from:
186
+ * the api-mode default it does not have to repeat, its own extras, minus what skipScopes removes.
187
+ * Reading extraScopes alone called an app send-only while it still requested gmail.modify. A scope may
188
+ * be stored under its short name, which Google's own scope URLs are not, so the list is expanded first.
189
+ *
190
+ * Pure: extracted out of lib/ui-routes/oauth-config-routes.js, which built an Account instance and
191
+ * resolved the encryption secret only to reach checkAccountScopes() above.
192
+ *
193
+ * @param {Object} app - A stored OAuth2 application record
194
+ * @returns {boolean} True when the app grants sending but not reading
195
+ */
196
+ function isSendOnlyGmailApp(app) {
197
+ if (!app || !GMAIL_PROVIDERS.has(app.provider) || app.baseScopes !== 'api') {
198
+ return false;
199
+ }
200
+
201
+ const scopes = formatExtraScopes(app.extraScopes, app.baseScopes, GMAIL_SCOPES, app.skipScopes, GMAIL_SCOPE_PREFIX).map(scope =>
202
+ scope.startsWith('https://') ? scope : `${GMAIL_SCOPE_PREFIX}/${scope}`
203
+ );
204
+ const { hasSendScope, hasReadScope } = checkAccountScopes('gmail', scopes);
205
+
206
+ return hasSendScope && !hasReadScope;
207
+ }
208
+
176
209
  /**
177
210
  * Determines if an account is in send-only mode based on its scopes.
178
211
  *
@@ -189,6 +222,7 @@ function isSendOnlyByScopes(provider, accountData, logger) {
189
222
 
190
223
  module.exports = {
191
224
  checkAccountScopes,
225
+ isSendOnlyGmailApp,
192
226
  checkGmailScopes,
193
227
  checkOutlookScopes,
194
228
  isSendOnlyByScopes,