emailengine-app 2.82.1 → 2.83.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 (59) hide show
  1. package/.ncurc.js +8 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +25 -0
  4. package/data/google-crawlers.json +1 -1
  5. package/lib/account.js +16 -3
  6. package/lib/api-routes/account-routes.js +8 -6
  7. package/lib/api-routes/blocklist-routes.js +4 -4
  8. package/lib/api-routes/oauth2-app-routes.js +5 -2
  9. package/lib/api-routes/route-helpers.js +28 -0
  10. package/lib/api-routes/submit-routes.js +6 -5
  11. package/lib/bounce-detect.js +4 -2
  12. package/lib/egress-filter.js +8 -3
  13. package/lib/email-client/gmail-client.js +3 -1
  14. package/lib/email-client/imap-client.js +2 -1
  15. package/lib/email-client/outlook-client.js +106 -47
  16. package/lib/email-client/outlook-fallback-poll.js +30 -0
  17. package/lib/enum-descriptions.js +3 -1
  18. package/lib/imapproxy/imap-core/README.md +1 -0
  19. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +11 -1
  20. package/lib/imapproxy/proxy-handoff.js +6 -3
  21. package/lib/imapproxy/response-error.js +14 -1
  22. package/lib/oauth/gcp-metadata.js +222 -0
  23. package/lib/oauth/gmail.js +115 -20
  24. package/lib/oauth/mail-ru.js +10 -4
  25. package/lib/oauth/outlook.js +11 -4
  26. package/lib/oauth/token-fetch.js +4 -2
  27. package/lib/oauth/verify-app.js +120 -32
  28. package/lib/oauth2-apps.js +46 -12
  29. package/lib/schemas.js +60 -18
  30. package/lib/tools.js +52 -2
  31. package/lib/ui-routes/admin-entities-routes.js +2 -2
  32. package/lib/ui-routes/auth-routes.js +4 -1
  33. package/lib/ui-routes/gmail-service-auth.js +64 -0
  34. package/lib/ui-routes/oauth-config-routes.js +8 -16
  35. package/lib/ui-routes/outlook-subscription-view.js +36 -0
  36. package/lib/ui-routes/route-helpers.js +2 -14
  37. package/lib/ui-routes/suppression-list-routes.js +2 -2
  38. package/lib/utils/network.js +29 -0
  39. package/lib/webhook-request.js +12 -4
  40. package/lib/webhook-routing.js +34 -11
  41. package/package.json +11 -11
  42. package/sbom.json +1 -1
  43. package/server.js +8 -2
  44. package/static/css/flyonui.css +1 -1
  45. package/static/js/app.js +2 -1
  46. package/static/js/ui.js +6 -1
  47. package/static/licenses.html +18 -28
  48. package/translations/messages.pot +73 -73
  49. package/views/accounts/account.hbs +5 -2
  50. package/views/accounts/edit.hbs +1 -1
  51. package/views/config/imap-proxy.hbs +1 -1
  52. package/views/config/network.hbs +7 -5
  53. package/views/config/oauth/app.hbs +2 -0
  54. package/views/config/smtp.hbs +1 -1
  55. package/views/config/tls.hbs +2 -2
  56. package/views/config/webhooks.hbs +1 -1
  57. package/views/partials/oauth_form.hbs +116 -27
  58. package/workers/api.js +4 -2
  59. package/workers/webhooks.js +18 -7
package/lib/schemas.js CHANGED
@@ -164,7 +164,9 @@ const settingsSchema = {
164
164
  .example('Bearer <token>')
165
165
  }).label('WebhooksCustomHeader')
166
166
  )
167
- .description('Additional HTTP headers to include with every webhook request for authentication or tracking')
167
+ .description(
168
+ "Additional HTTP headers to include with webhook requests for authentication or tracking. The global list is sent to the global webhook URL only, an account-level list accompanies that account's deliveries"
169
+ )
168
170
  .label('WebhooksCustomHeaders'),
169
171
 
170
172
  notifyHeaders: Joi.array()
@@ -406,14 +408,16 @@ const settingsSchema = {
406
408
  imapStrategy: Joi.string()
407
409
  .empty('')
408
410
  .valid(...ADDRESS_STRATEGIES.map(entry => entry.key))
409
- .description('IP address selection strategy for outbound IMAP connections when multiple local addresses are available')
411
+ .description(
412
+ 'IP address selection strategy for mailbox access when multiple local addresses are available: IMAP sessions, Gmail API and MS Graph requests, and the OAuth2 token requests of every account. The key keeps its historical name'
413
+ )
410
414
  .meta({ enumDescriptions: ENUM_DESCRIPTIONS.addressStrategy })
411
415
  .label('ImapStrategy'),
412
416
 
413
417
  smtpStrategy: Joi.string()
414
418
  .empty('')
415
419
  .valid(...ADDRESS_STRATEGIES.map(entry => entry.key))
416
- .description('IP address selection strategy for outbound SMTP connections when multiple local addresses are available')
420
+ .description('IP address selection strategy for sending over SMTP when multiple local addresses are available')
417
421
  .meta({ enumDescriptions: ENUM_DESCRIPTIONS.addressStrategy })
418
422
  .label('SmtpStrategy'),
419
423
 
@@ -437,7 +441,9 @@ const settingsSchema = {
437
441
  .empty('')
438
442
  .example('0.0.0.0')
439
443
  .description('IP address to bind the SMTP server to (empty = all interfaces)'),
440
- smtpServerProxy: formBoolean().description('Enable PROXY protocol support for the SMTP server'),
444
+ smtpServerProxy: formBoolean().description(
445
+ 'Enable PROXY protocol support for the SMTP server. The PROXY header is accepted from any peer, so the port must only be reachable through the proxy'
446
+ ),
441
447
  smtpServerAuthEnabled: formBoolean().description('Require SMTP authentication for incoming connections'),
442
448
  smtpServerPassword: Joi.string()
443
449
  .empty('')
@@ -489,7 +495,9 @@ const settingsSchema = {
489
495
  .empty('')
490
496
  .example('0.0.0.0')
491
497
  .description('IP address to bind the IMAP proxy to (empty = all interfaces)'),
492
- imapProxyServerProxy: formBoolean().description('Enable PROXY protocol support for the IMAP proxy'),
498
+ imapProxyServerProxy: formBoolean().description(
499
+ 'Enable PROXY protocol support for the IMAP proxy. The PROXY header is accepted from any peer, so the port must only be reachable through the proxy'
500
+ ),
493
501
  imapProxyServerPassword: Joi.string()
494
502
  .empty('')
495
503
  .allow(null)
@@ -624,9 +632,22 @@ const settingsSchema = {
624
632
  .description('How long a finished export is kept before it is deleted, in milliseconds (default: 24 hours)')
625
633
  };
626
634
 
635
+ // The per-account proxy. Covers every outbound connection made for the account, as the instance-wide
636
+ // proxy does for all of them (see getAccountHttpRoute() in lib/utils/network.js)
637
+ const accountProxySchema = settingsSchema.proxyUrl
638
+ .description(
639
+ 'Proxy for this account, used instead of the instance-wide proxy: its IMAP and SMTP connections and, for an OAuth2 account, its token requests and Gmail API or MS Graph API calls'
640
+ )
641
+ .label('AccountProxyURL');
642
+
643
+ // A message sender or recipient address. joi's default 64 octet local part limit is dropped, since
644
+ // real services issue longer addresses their own MX accepts (ClickUp task addresses run to 65 octets);
645
+ // the 254 overall cap joi applied before is kept, and domain label limits still apply.
646
+ const mailboxAddressSchema = Joi.string().email({ ignoreLength: true }).max(254);
647
+
627
648
  const addressSchema = Joi.object({
628
649
  name: Joi.string().trim().empty('').max(256).example('Some Name').description('Display name for the email address'),
629
- address: Joi.string().email({ ignoreLength: false }).example('user@example.com').required().description('Email address')
650
+ address: mailboxAddressSchema.example('user@example.com').required().description('Email address')
630
651
  })
631
652
  .description('Email address with optional display name')
632
653
  .label('EmailAddress');
@@ -1647,6 +1668,14 @@ const accountSchemas = {
1647
1668
  )
1648
1669
  };
1649
1670
 
1671
+ // The service account fields every gmailService app names, except one using the attached service
1672
+ // account, which the metadata server identifies
1673
+ const requiredUnlessMetadataServer = Joi.when('authMethod', {
1674
+ is: 'metadataServer',
1675
+ then: Joi.optional(),
1676
+ otherwise: Joi.required()
1677
+ });
1678
+
1650
1679
  const googleProjectIdSchema = Joi.string()
1651
1680
  .trim()
1652
1681
  .allow('', false, null)
@@ -1766,7 +1795,7 @@ const oauthCreateSchema = {
1766
1795
  .max(256)
1767
1796
  .when('provider', {
1768
1797
  is: 'gmailService',
1769
- then: Joi.required(),
1798
+ then: requiredUnlessMetadataServer,
1770
1799
  otherwise: Joi.optional().valid(false, null)
1771
1800
  })
1772
1801
  .example('7103296518315821565203')
@@ -1784,7 +1813,7 @@ const oauthCreateSchema = {
1784
1813
  .email()
1785
1814
  .when('provider', {
1786
1815
  is: 'gmailService',
1787
- then: Joi.required(),
1816
+ then: requiredUnlessMetadataServer,
1788
1817
  otherwise: Joi.optional().valid(false, null)
1789
1818
  })
1790
1819
  .example('name@project-123.iam.gserviceaccount.com')
@@ -1797,7 +1826,8 @@ const oauthCreateSchema = {
1797
1826
  .when('provider', {
1798
1827
  is: 'gmailService',
1799
1828
  then: Joi.when('authMethod', {
1800
- is: 'externalAccount',
1829
+ // a schema `is` is not required by default, so a missing authMethod would match
1830
+ is: Joi.valid('externalAccount', 'metadataServer').required(),
1801
1831
  then: Joi.optional().allow(''),
1802
1832
  otherwise: Joi.required()
1803
1833
  }),
@@ -1807,14 +1837,24 @@ const oauthCreateSchema = {
1807
1837
  .description('Service account private key in PEM format'),
1808
1838
 
1809
1839
  authMethod: Joi.string()
1810
- .valid('serviceKey', 'externalAccount')
1840
+ .valid('serviceKey', 'externalAccount', 'metadataServer')
1811
1841
  .when('provider', {
1812
1842
  is: 'gmailService',
1813
1843
  then: Joi.optional().default('serviceKey'),
1814
1844
  otherwise: Joi.optional().valid(false, null)
1815
1845
  })
1846
+ // The metadata server's token is the attached service account's own and cannot impersonate
1847
+ // a Workspace user, so it only serves an app that acts as the service account: Pub/Sub.
1848
+ // Joi.override replaces the allowed list instead of adding to it, so the refusal is one
1849
+ // error with its reason rather than a generic "must be one of" next to it
1850
+ .when('baseScopes', {
1851
+ is: Joi.exist().valid('pubsub'),
1852
+ otherwise: Joi.valid(Joi.override, 'serviceKey', 'externalAccount', false, null).messages({
1853
+ 'any.only': '{{#label}} must be one of [serviceKey, externalAccount]. metadataServer is only available to a Cloud Pub/Sub application'
1854
+ })
1855
+ })
1816
1856
  .example('externalAccount')
1817
- .description('How token requests for the Gmail service account are signed')
1857
+ .description('How the Gmail service account authenticates')
1818
1858
  .meta({ enumDescriptions: ENUM_DESCRIPTIONS.gmailAuthMethod }),
1819
1859
 
1820
1860
  externalAccount: Joi.string()
@@ -1961,7 +2001,7 @@ const oauthUpdateSchema = {
1961
2001
  .max(256)
1962
2002
  .when('provider', {
1963
2003
  is: 'gmailService',
1964
- then: Joi.required(),
2004
+ then: requiredUnlessMetadataServer,
1965
2005
  otherwise: Joi.optional().valid(false, null)
1966
2006
  })
1967
2007
  .description('OAuth2 Service Client ID'),
@@ -1979,7 +2019,7 @@ const oauthUpdateSchema = {
1979
2019
  .email()
1980
2020
  .when('provider', {
1981
2021
  is: 'gmailService',
1982
- then: Joi.required(),
2022
+ then: requiredUnlessMetadataServer,
1983
2023
  otherwise: Joi.optional().valid(false, null)
1984
2024
  })
1985
2025
  .example('name@project-123.iam.gserviceaccount.com')
@@ -1997,13 +2037,13 @@ const oauthUpdateSchema = {
1997
2037
  .description('OAuth2 Secret Service Key'),
1998
2038
 
1999
2039
  authMethod: Joi.string()
2000
- .valid('serviceKey', 'externalAccount')
2040
+ .valid('serviceKey', 'externalAccount', 'metadataServer')
2001
2041
  .when('provider', {
2002
2042
  is: 'gmailService',
2003
2043
  then: Joi.optional().default('serviceKey'),
2004
2044
  otherwise: Joi.forbidden()
2005
2045
  })
2006
- .description('How token requests for the Gmail service account are signed')
2046
+ .description('How the Gmail service account authenticates')
2007
2047
  .meta({ enumDescriptions: ENUM_DESCRIPTIONS.gmailAuthMethod }),
2008
2048
 
2009
2049
  externalAccount: Joi.string()
@@ -2233,8 +2273,8 @@ const outboxEntrySchema = Joi.object({
2233
2273
 
2234
2274
  messageId: Joi.string().max(996).example('<test123@example.com>').description('Message-ID header value'),
2235
2275
  envelope: Joi.object({
2236
- from: Joi.string().email().allow('').example('sender@example.com'),
2237
- to: Joi.array().items(Joi.string().email().required().example('recipient@example.com')).label('OutboxEnvelopeTo')
2276
+ from: mailboxAddressSchema.allow('').example('sender@example.com'),
2277
+ to: Joi.array().items(mailboxAddressSchema.required().example('recipient@example.com')).label('OutboxEnvelopeTo')
2238
2278
  })
2239
2279
  .description('SMTP envelope information')
2240
2280
  .label('OutboxEnvelope'),
@@ -2355,7 +2395,7 @@ const idempotencyKeySchema = Joi.string()
2355
2395
  .min(0)
2356
2396
  .max(1024)
2357
2397
  .optional()
2358
- .replace(/^\s*"\s*|\s*"\s*$|/g, '')
2398
+ .replace(/^\s*"\s*|\s*"\s*$/g, '')
2359
2399
  .replace(/\\([\\"])/g, '$1')
2360
2400
  .example('submit-12345')
2361
2401
  .description('Unique key to prevent duplicate processing of the same request')
@@ -2648,6 +2688,8 @@ module.exports = {
2648
2688
  settingsSchema,
2649
2689
  accountSchemas,
2650
2690
  addressSchema,
2691
+ mailboxAddressSchema,
2692
+ accountProxySchema,
2651
2693
  settingsQuerySchema,
2652
2694
  isHiddenSetting,
2653
2695
  imapSchema,
package/lib/tools.js CHANGED
@@ -56,6 +56,7 @@ const { getLocalAddress } = require('./utils/network');
56
56
 
57
57
  const { fetch: fetchCmd, Agent, RetryAgent, ProxyAgent, Dispatcher } = require('undici');
58
58
  const tls = require('tls');
59
+ const net = require('net');
59
60
  const { SocksClient } = require('socks');
60
61
  const { createWebhookLookup, WEBHOOK_EGRESS_POLICY } = require('./webhook-egress');
61
62
  const { readEnvValue } = require('./read-env-value');
@@ -247,9 +248,9 @@ function createSocksAgent(proxyUrl, agentOpts) {
247
248
  );
248
249
  }
249
250
 
250
- function buildFetchDispatcher(proxyUrl) {
251
+ function buildFetchDispatcher(proxyUrl, extraOpts) {
251
252
  if (!proxyUrl) {
252
- return new Agent(AGENT_OPTS);
253
+ return new Agent(Object.assign({}, AGENT_OPTS, extraOpts));
253
254
  }
254
255
 
255
256
  let scheme = new URL(proxyUrl).protocol.replace(/:$/, '').toLowerCase();
@@ -270,6 +271,54 @@ function installDispatchers(proxyUrl, existingWebhook) {
270
271
  httpAgent.proxyUrl = proxyUrl;
271
272
  }
272
273
 
274
+ // Dispatchers for the network route of one account (see getAccountHttpRoute() in lib/utils/network.js),
275
+ // shared by every account on the same route. An entry nobody has used for ROUTE_DISPATCHER_IDLE_MS is
276
+ // closed and dropped on the next miss. Not a size bound: a route in use keeps its warm sockets however
277
+ // many accounts each have their own proxy, and close() is graceful, so a request still in flight on a
278
+ // dropped entry finishes first.
279
+ const ROUTE_DISPATCHER_IDLE_MS = 60 * 60 * 1000;
280
+ const routeDispatchers = new Map();
281
+
282
+ /**
283
+ * Returns the { fetch, retry } dispatcher pair for a network route.
284
+ *
285
+ * @param {Object} [route] - { proxy, localAddress }, both optional
286
+ * @returns {Object} { fetch, retry } - the shared dispatchers when the route asks for nothing special
287
+ */
288
+ function dispatchersForRoute(route) {
289
+ let proxy = (route && route.proxy) || null;
290
+ // A local address only applies to a direct connection. With the instance-wide HTTP proxy in
291
+ // use the proxy makes the connection, the same way it does for IMAP and SMTP.
292
+ let localAddress = (!proxy && !httpAgent.proxyUrl && route && route.localAddress) || null;
293
+
294
+ if (!proxy && !localAddress) {
295
+ return { fetch: httpAgent.fetch, retry: httpAgent.retry };
296
+ }
297
+
298
+ let now = Date.now();
299
+ let key = proxy ? `proxy:${proxy}` : `local:${localAddress}`;
300
+ let entry = routeDispatchers.get(key);
301
+
302
+ if (!entry) {
303
+ for (let [staleKey, stale] of routeDispatchers) {
304
+ if (now - stale.used > ROUTE_DISPATCHER_IDLE_MS) {
305
+ routeDispatchers.delete(staleKey);
306
+ stale.fetch.close().catch(() => false);
307
+ }
308
+ }
309
+
310
+ // undici takes the source address as an Agent option (inside `connect` it is overwritten);
311
+ // the family keeps an IPv4 source address from being paired with an IPv6 destination
312
+ let fetchDispatcher = buildFetchDispatcher(proxy, localAddress && { localAddress, connect: { family: net.isIPv6(localAddress) ? 6 : 4 } });
313
+ entry = { fetch: fetchDispatcher, retry: new RetryAgent(fetchDispatcher, RETRY_OPTS) };
314
+ routeDispatchers.set(key, entry);
315
+ }
316
+
317
+ entry.used = now;
318
+ return entry;
319
+ }
320
+ httpAgent.forRoute = dispatchersForRoute;
321
+
273
322
  // The main thread resolves the proxy from settings before it spawns anything (reloadHttpProxyAgent()
274
323
  // in server.js) and hands the result to every worker in workerData, so a worker's dispatchers are
275
324
  // right from its first line of code and no worker has to sequence its startup behind a settings
@@ -2808,6 +2857,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2808
2857
  },
2809
2858
 
2810
2859
  httpAgent,
2860
+ ROUTE_DISPATCHER_IDLE_MS,
2811
2861
  reloadHttpProxyAgent,
2812
2862
  maybeReloadHttpProxyAgent,
2813
2863
  resolveHttpProxy,
@@ -8,7 +8,7 @@ const tokens = require('../tokens');
8
8
  const { redis } = require('../db');
9
9
  const getSecret = require('../get-secret');
10
10
  const { failAction, verifyAccountInfo, formatPartialSecretKey } = require('../tools');
11
- const { templateSchemas, accountIdSchema, tokenPermissionsSchema, formBoolean } = require('../schemas');
11
+ const { templateSchemas, accountIdSchema, tokenPermissionsSchema, formBoolean, mailboxAddressSchema } = require('../schemas');
12
12
  const tokenPermissionView = require('../token-permission-view');
13
13
  const { PRIVILEGED_SETTINGS_SUMMARY } = require('../privileged-settings');
14
14
  const { Account, accountExists, accountSummary } = require('../account');
@@ -1430,7 +1430,7 @@ return payload;`)
1430
1430
  .example('AAAAAQAACnA')
1431
1431
  .required()
1432
1432
  .description('Template ID'),
1433
- to: Joi.string().email().required().description('Recipient address'),
1433
+ to: mailboxAddressSchema.required().description('Recipient address'),
1434
1434
  params: Joi.object().description('Optional handlebars values').unknown()
1435
1435
  })
1436
1436
  }
@@ -343,6 +343,10 @@ function init(args) {
343
343
  let authData = await settings.get('authData');
344
344
  let totpEnabled = (await settings.get('totpEnabled')) || false;
345
345
 
346
+ // The hash is verified before the username is compared, so a wrong username costs the
347
+ // same PBKDF2 round as a wrong password and the response time does not tell them apart
348
+ let valid = authData && authData.password ? await verifyAdminPassword(authData.password, request.payload.password, request.logger) : false;
349
+
346
350
  if (authData && authData.user && authData.user !== request.payload.username) {
347
351
  request.logger.warn({ msg: 'Invalid username', username: request.payload.username, method: 'password', remoteAddress: request.app.ip });
348
352
  let err = new Error('Failed to authenticate');
@@ -351,7 +355,6 @@ function init(args) {
351
355
  }
352
356
 
353
357
  if (authData && authData.password) {
354
- let valid = await verifyAdminPassword(authData.password, request.payload.password, request.logger);
355
358
  if (!valid) {
356
359
  request.logger.warn({ msg: 'Invalid password', user: request.payload.username, method: 'password', remoteAddress: request.app.ip });
357
360
  let err = new Error('Failed to authenticate');
@@ -0,0 +1,64 @@
1
+ 'use strict';
2
+
3
+ // The authentication method of a gmailService app on the admin OAuth2 app pages: the render
4
+ // context for its tab selector, and the "Detect from this host" lookup offered beside the attached
5
+ // service account (metadataServer) method.
6
+
7
+ const Joi = require('joi');
8
+
9
+ const gcpMetadata = require('../oauth/gcp-metadata');
10
+
11
+ /**
12
+ * Render-context booleans for the gmailService authMethod tab selector. When `locked` is set the
13
+ * method is shown but cannot be switched - it is fixed once an app has been saved.
14
+ *
15
+ * @param {string} [authMethod] - the selected or stored method
16
+ * @param {boolean} [locked] - whether the method can no longer change
17
+ * @returns {Object}
18
+ */
19
+ function authMethodContext(authMethod, locked) {
20
+ return {
21
+ authMethodIsServiceKey: !authMethod || authMethod === 'serviceKey',
22
+ authMethodIsExternalAccount: authMethod === 'externalAccount',
23
+ authMethodIsMetadataServer: authMethod === 'metadataServer',
24
+ authMethodLocked: !!locked
25
+ };
26
+ }
27
+
28
+ function gmailServiceAuthRoutes({ server }) {
29
+ // Reads the attached service account and project from the metadata server, for the "Detect
30
+ // from this host" button on the new app form. Asks only the fixed metadata host (see
31
+ // lib/oauth/gcp-metadata.js), and only on an explicit click, never while rendering a page
32
+ server.route({
33
+ method: 'POST',
34
+ path: '/admin/config/oauth/metadata-probe',
35
+ async handler(request) {
36
+ try {
37
+ let identity = await gcpMetadata.describeAttachedIdentity();
38
+ return { success: true, serviceAccountEmail: identity.serviceAccountEmail, projectId: identity.projectId };
39
+ } catch (err) {
40
+ request.logger.info({ msg: 'Metadata server probe failed', code: err.code, status: err.statusCode, error: err.message });
41
+ return { success: false, error: err.message, code: err.code || null };
42
+ }
43
+ },
44
+ options: {
45
+ validate: {
46
+ options: {
47
+ stripUnknown: true,
48
+ abortEarly: false,
49
+ convert: true
50
+ },
51
+
52
+ async failAction(request, h /*, err*/) {
53
+ return h.response({ error: 'Invalid request' }).code(400).takeover();
54
+ },
55
+
56
+ payload: Joi.object({
57
+ crumb: Joi.string().optional()
58
+ })
59
+ }
60
+ }
61
+ });
62
+ }
63
+
64
+ module.exports = { authMethodContext, gmailServiceAuthRoutes };
@@ -3,8 +3,8 @@
3
3
  // Admin UI routes for OAuth2 application config (/admin/config/oauth*): listing apps,
4
4
  // per-app view/edit/delete, creating apps, adding accounts, provider subscriptions, and
5
5
  // app verification. Extracted verbatim from lib/routes-ui.js. AZURE_CLOUDS and the
6
- // authMethodContext/getPubSubAppsForSelect render helpers move with the routes (only the
7
- // OAuth app config pages use them).
6
+ // getPubSubAppsForSelect render helper move with the routes (only the OAuth app config pages use
7
+ // them); the gmailService authentication method pieces live in gmail-service-auth.js.
8
8
 
9
9
  const Joi = require('joi');
10
10
  const util = require('util');
@@ -15,8 +15,9 @@ const consts = require('../consts');
15
15
  const { redis } = require('../db');
16
16
  const getSecret = require('../get-secret');
17
17
  const { Account } = require('../account');
18
- const { oauth2Apps, OAUTH_PROVIDERS, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
18
+ const { oauth2Apps, OAUTH_PROVIDERS, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS, isAuthMethodLocked } = require('../oauth2-apps');
19
19
  const { verifyOAuth2App } = require('../oauth/verify-app');
20
+ const { authMethodContext, gmailServiceAuthRoutes } = require('./gmail-service-auth');
20
21
  const { isSendOnlyGmailApp } = require('../oauth/scope-checker');
21
22
  const { oauthCreateSchema, oauthUpdateSchema, accountIdSchema, formBoolean } = require('../schemas');
22
23
  const { throwAsBoom, adminUrl, submittedValues, windowedPageLinks } = require('./route-helpers');
@@ -52,16 +53,7 @@ const AZURE_CLOUDS = [
52
53
  function init(args) {
53
54
  const { server, call } = args;
54
55
 
55
- // Render-context booleans for the gmailService authMethod tab selector.
56
- // When `locked` is set the selector is shown but cannot be switched - the
57
- // authentication method is fixed once an app has been created.
58
- function authMethodContext(authMethod, locked) {
59
- return {
60
- authMethodIsServiceKey: !authMethod || authMethod === 'serviceKey',
61
- authMethodIsExternalAccount: authMethod === 'externalAccount',
62
- authMethodLocked: !!locked
63
- };
64
- }
56
+ gmailServiceAuthRoutes({ server });
65
57
 
66
58
  /**
67
59
  * View context for re-rendering the new or edit OAuth2 app form after a failed save, from the
@@ -123,7 +115,7 @@ function init(args) {
123
115
  hasClientSecret: !!appData.clientSecret,
124
116
  hasServiceKey: !!appData.serviceKey,
125
117
  hasExternalAccount: !!appData.externalAccount,
126
- ...authMethodContext(appData.authMethod, !!appData.serviceKey || !!appData.externalAccount)
118
+ ...authMethodContext(appData.authMethod, isAuthMethodLocked(appData))
127
119
  });
128
120
  } else {
129
121
  Object.assign(context, { actionCreate: true, ...authMethodContext(payload.authMethod) });
@@ -466,7 +458,7 @@ function init(args) {
466
458
  baseScopesPubsub: app.baseScopes === 'pubsub',
467
459
 
468
460
  appShowAuthMethod: app.provider === 'gmailService',
469
- authMethodIsExternalAccount: app.authMethod === 'externalAccount',
461
+ ...authMethodContext(app.authMethod),
470
462
 
471
463
  canAddServiceAccount,
472
464
 
@@ -856,7 +848,7 @@ function init(args) {
856
848
  hasServiceKey: !!appData.serviceKey,
857
849
  hasExternalAccount: !!appData.externalAccount,
858
850
 
859
- ...authMethodContext(appData.authMethod, !!appData.serviceKey || !!appData.externalAccount),
851
+ ...authMethodContext(appData.authMethod, isAuthMethodLocked(appData)),
860
852
 
861
853
  pubSubApps: await getPubSubAppsForSelect(values.pubSubApp),
862
854
 
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+
3
+ const { FALLBACK_POLL_INTERVAL } = require('../email-client/outlook-fallback-poll');
4
+
5
+ /**
6
+ * Adds the fields the account page renders for a Graph change subscription, in place
7
+ * @param {Object} subscription - The account's stored `outlookSubscription`
8
+ * @param {string} accountState - The account's connection state
9
+ * @returns {Object} The same subscription object
10
+ */
11
+ function formatOutlookSubscription(subscription, accountState) {
12
+ const state = subscription.state || {};
13
+ const expires = subscription.expirationDateTime;
14
+
15
+ subscription.subscriptionExpiresStr = expires ? expires.toISOString() : false;
16
+ subscription.isValid = state.state !== 'error' && expires && expires > new Date();
17
+
18
+ subscription.stateLabel = (state.state || '').replace(/^./, c => c.toUpperCase());
19
+ if ((state.state === 'created' && !expires) || expires < new Date()) {
20
+ subscription.stateLabel = 'Expired';
21
+ }
22
+
23
+ // See OutlookClient.reportSubscriptionFailure()
24
+ subscription.polling = state.state === 'error' && accountState === 'connected' && !!FALLBACK_POLL_INTERVAL;
25
+
26
+ // One severity for the badge and the alert: a failure the poller stands in for is a warning
27
+ if (subscription.isValid) {
28
+ subscription.variant = 'success';
29
+ } else {
30
+ subscription.variant = state.state === 'error' && !subscription.polling ? 'error' : 'warning';
31
+ }
32
+
33
+ return subscription;
34
+ }
35
+
36
+ module.exports = { formatOutlookSubscription };
@@ -20,6 +20,7 @@ const { redis } = require('../db');
20
20
  const { toolGrants } = require('../mcp/tools');
21
21
  const { Account, accountsExist, accountSummary, isAuthFailureDisabled, isAccessTokenInvalidated } = require('../account');
22
22
  const { REDIS_PREFIX, DEFAULT_PAGE_SIZE } = require('../consts');
23
+ const { formatOutlookSubscription } = require('./outlook-subscription-view');
23
24
  const { oauth2ProviderData } = require('../oauth2-apps');
24
25
  const exampleDocumentsPayloads = require('../payload-examples-documents.json');
25
26
 
@@ -224,20 +225,7 @@ function formatAccountData(account, gt) {
224
225
  account.oauth2.accessTokenInvalidated = isAccessTokenInvalidated(account.oauth2);
225
226
 
226
227
  if (account.outlookSubscription) {
227
- account.outlookSubscription.subscriptionExpiresStr = account.outlookSubscription.expirationDateTime
228
- ? account.outlookSubscription.expirationDateTime.toISOString()
229
- : false;
230
-
231
- let state = account.outlookSubscription.state || {};
232
-
233
- account.outlookSubscription.isValid =
234
- state.state !== 'error' && account.outlookSubscription.expirationDateTime && account.outlookSubscription.expirationDateTime > new Date();
235
-
236
- account.outlookSubscription.stateLabel = (state.state || '').replace(/^./, c => c.toUpperCase());
237
-
238
- if ((state.state === 'created' && !account.outlookSubscription.expirationDateTime) || account.outlookSubscription.expirationDateTime < new Date()) {
239
- account.outlookSubscription.stateLabel = 'Expired';
240
- }
228
+ formatOutlookSubscription(account.outlookSubscription, account.state);
241
229
  }
242
230
  }
243
231
 
@@ -9,7 +9,7 @@
9
9
  const Joi = require('joi');
10
10
  const { lists } = require('../lists');
11
11
  const settings = require('../settings');
12
- const { blocklistListIdSchema } = require('../schemas');
12
+ const { blocklistListIdSchema, mailboxAddressSchema } = require('../schemas');
13
13
  const { buildPagingView, resolveKnownAccounts, adminUrl } = require('./route-helpers');
14
14
  const { buildUnsubscribeUrl, getServiceSecret } = require('../tools');
15
15
  const consts = require('../consts');
@@ -201,7 +201,7 @@ function init(args) {
201
201
 
202
202
  payload: Joi.object({
203
203
  listId: blocklistListIdSchema,
204
- recipient: Joi.string().empty('').email().required().description('Email address to suppress'),
204
+ recipient: mailboxAddressSchema.empty('').required().description('Email address to suppress'),
205
205
  reason: Joi.string().empty('').max(256).default('block').description('Identifier for the blocking reason')
206
206
  })
207
207
  }
@@ -345,10 +345,39 @@ async function getLocalAddress(redis, protocol, account, hint) {
345
345
  }
346
346
  }
347
347
 
348
+ /**
349
+ * The network route for the HTTP traffic of an account: its provider API calls (Gmail API, MS Graph)
350
+ * and the token requests of any OAuth2 account. Mirrors how its IMAP connection is routed - the
351
+ * account's own proxy when it has one, otherwise the local address the IMAP address strategy picks
352
+ * for it, by the same strategy - so an account leaves the same way whichever protocol it speaks. An
353
+ * API account has no IMAP session, its API connection takes that role. The instance-wide proxy is not part of
354
+ * the route: the shared dispatchers already apply it.
355
+ *
356
+ * @param {Object} redis - Redis client
357
+ * @param {Object} accountData - account data with the decrypted `proxy`, or a pending setup record
358
+ * @returns {Promise<Object>} { proxy, localAddress }, each null when not set
359
+ */
360
+ async function getAccountHttpRoute(redis, accountData) {
361
+ if (accountData && accountData.proxy) {
362
+ return { proxy: accountData.proxy, localAddress: null };
363
+ }
364
+
365
+ // A setup that has not been assigned an id yet has nothing for the dedicated strategy to key on.
366
+ // Most instances configure no local addresses, and that one read is then all a route costs.
367
+ const configured = await settings.get('localAddresses');
368
+ if (!accountData || !accountData.account || !configured || !configured.length) {
369
+ return { proxy: null, localAddress: null };
370
+ }
371
+
372
+ const { localAddress } = await getLocalAddress(redis, 'imap', accountData.account);
373
+ return { proxy: null, localAddress: localAddress || null };
374
+ }
375
+
348
376
  module.exports = {
349
377
  resolvePublicInterfaces,
350
378
  updatePublicInterfaces,
351
379
  getLocalAddress,
380
+ getAccountHttpRoute,
352
381
  parseComparableIp,
353
382
  parseComparableCidr,
354
383
  matchIp,
@@ -1,6 +1,13 @@
1
1
  'use strict';
2
2
 
3
3
  const { DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('./consts');
4
+ const { readBodyCapped } = require('./egress-fetch');
5
+
6
+ // How much of a response body is read before the connection is dropped instead. The body is never
7
+ // used, it is read only so the pooled socket can be reused, and undici inflates a compressed one,
8
+ // so a receiver answering a POST with an endless or a bomb body would otherwise be buffered in
9
+ // memory until the delivery timeout
10
+ const MAX_DRAIN_BYTES = 1024 * 1024;
4
11
 
5
12
  /**
6
13
  * Builds the error for a redirect that was deliberately not followed.
@@ -77,16 +84,17 @@ async function sendWebhookRequest(fetchImpl, url, options) {
77
84
  throw err;
78
85
  }
79
86
 
80
- // Drain the body regardless of status so the socket can be reused.
87
+ // Drain the body regardless of status so the socket can be reused. A body past the cap has its
88
+ // stream cancelled instead, which closes the connection rather than returning it to the pool
81
89
  try {
82
- await res.text();
90
+ await readBodyCapped(res, MAX_DRAIN_BYTES);
83
91
  } catch (err) {
84
92
  if (isTimeoutError(err)) {
85
93
  // a body that never finishes is the same stall as a request that
86
94
  // never connects, so surface it instead of ignoring the drain error
87
95
  throwTimeout();
88
96
  }
89
- // ignore other drain errors
97
+ // ignore other drain errors, the oversized body included
90
98
  }
91
99
 
92
100
  // With redirect:'manual' undici hands back the 3xx itself (deliberately, unlike the browser
@@ -113,4 +121,4 @@ function isUnrecoverableWebhookError(err) {
113
121
  return !!err && (err.code === 'EEGRESSBLOCKED' || err.code === 'EREDIRECTNOTFOLLOWED');
114
122
  }
115
123
 
116
- module.exports = { sendWebhookRequest, isUnrecoverableWebhookError };
124
+ module.exports = { sendWebhookRequest, isUnrecoverableWebhookError, MAX_DRAIN_BYTES };