emailengine-app 2.82.2 → 2.83.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 (70) hide show
  1. package/.ncurc.js +8 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +29 -0
  4. package/data/google-crawlers.json +1 -1
  5. package/lib/account.js +16 -3
  6. package/lib/api-reference/format.js +1 -1
  7. package/lib/api-routes/account-routes.js +8 -6
  8. package/lib/api-routes/blocklist-routes.js +4 -4
  9. package/lib/api-routes/export-routes.js +5 -5
  10. package/lib/api-routes/oauth2-app-routes.js +8 -2
  11. package/lib/api-routes/route-helpers.js +34 -0
  12. package/lib/api-routes/submit-routes.js +6 -5
  13. package/lib/bounce-detect.js +4 -2
  14. package/lib/egress-filter.js +8 -3
  15. package/lib/email-client/gmail-client.js +3 -1
  16. package/lib/email-client/imap-client.js +2 -1
  17. package/lib/email-client/outlook-client.js +11 -2
  18. package/lib/enum-descriptions.js +3 -1
  19. package/lib/imapproxy/imap-core/README.md +1 -0
  20. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +11 -1
  21. package/lib/imapproxy/proxy-handoff.js +6 -3
  22. package/lib/imapproxy/response-error.js +14 -1
  23. package/lib/oauth/gcp-metadata.js +259 -0
  24. package/lib/oauth/gmail.js +121 -20
  25. package/lib/oauth/mail-ru.js +10 -4
  26. package/lib/oauth/outlook.js +11 -4
  27. package/lib/oauth/token-fetch.js +4 -2
  28. package/lib/oauth/verify-app.js +126 -32
  29. package/lib/oauth2-apps.js +67 -13
  30. package/lib/schemas.js +60 -18
  31. package/lib/swagger-options.js +2 -3
  32. package/lib/tools.js +52 -2
  33. package/lib/ui-routes/admin-entities-routes.js +2 -2
  34. package/lib/ui-routes/auth-routes.js +4 -1
  35. package/lib/ui-routes/gmail-service-auth.js +64 -0
  36. package/lib/ui-routes/oauth-config-routes.js +22 -31
  37. package/lib/ui-routes/oauth-form-context.js +19 -0
  38. package/lib/ui-routes/suppression-list-routes.js +2 -2
  39. package/lib/utils/network.js +29 -0
  40. package/lib/webhook-request.js +12 -4
  41. package/lib/webhook-routing.js +34 -11
  42. package/package.json +11 -11
  43. package/sbom.json +1 -1
  44. package/server.js +8 -2
  45. package/static/css/flyonui.css +1 -1
  46. package/static/js/app.js +2 -1
  47. package/static/js/ui.js +6 -1
  48. package/static/licenses.html +18 -28
  49. package/translations/messages.pot +73 -73
  50. package/views/accounts/account.hbs +0 -5
  51. package/views/accounts/edit.hbs +1 -1
  52. package/views/config/imap-proxy.hbs +1 -1
  53. package/views/config/network.hbs +7 -5
  54. package/views/config/oauth/app.hbs +2 -0
  55. package/views/config/oauth/edit.hbs +0 -10
  56. package/views/config/oauth/new.hbs +0 -10
  57. package/views/config/smtp.hbs +1 -1
  58. package/views/config/tls.hbs +2 -2
  59. package/views/config/webhooks.hbs +1 -1
  60. package/views/partials/oauth_form.hbs +493 -906
  61. package/views/partials/oauth_graph_endpoints.hbs +12 -0
  62. package/views/partials/oauth_pubsub_app_select.hbs +11 -20
  63. package/views/partials/oauth_scope_presets.hbs +21 -0
  64. package/views/partials/ui/choice-tab.hbs +23 -0
  65. package/views/partials/ui/choice-tabs.hbs +32 -0
  66. package/views/partials/ui/radio.hbs +2 -2
  67. package/views/partials/ui/secret-field.hbs +2 -1
  68. package/views/partials/ui/tabs.hbs +1 -2
  69. package/workers/api.js +4 -2
  70. package/workers/webhooks.js +18 -7
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,11 +15,13 @@ 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');
24
+ const { baseScopesContext } = require('./oauth-form-context');
23
25
 
24
26
  const { DEFAULT_PAGE_SIZE } = consts;
25
27
 
@@ -52,16 +54,7 @@ const AZURE_CLOUDS = [
52
54
  function init(args) {
53
55
  const { server, call } = args;
54
56
 
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
- }
57
+ gmailServiceAuthRoutes({ server });
65
58
 
66
59
  /**
67
60
  * View context for re-rendering the new or edit OAuth2 app form after a failed save, from the
@@ -96,9 +89,7 @@ function init(args) {
96
89
 
97
90
  pubSubApps: await getPubSubAppsForSelect(payload.pubSubApp),
98
91
 
99
- baseScopesApi: payload.baseScopes === 'api',
100
- baseScopesImap: payload.baseScopes === 'imap' || !payload.baseScopes,
101
- baseScopesPubsub: payload.baseScopes === 'pubsub',
92
+ ...baseScopesContext(payload.baseScopes),
102
93
 
103
94
  azureClouds: structuredClone(AZURE_CLOUDS).map(entry => {
104
95
  entry.selected = payload.cloud === entry.id;
@@ -123,7 +114,7 @@ function init(args) {
123
114
  hasClientSecret: !!appData.clientSecret,
124
115
  hasServiceKey: !!appData.serviceKey,
125
116
  hasExternalAccount: !!appData.externalAccount,
126
- ...authMethodContext(appData.authMethod, !!appData.serviceKey || !!appData.externalAccount)
117
+ ...authMethodContext(appData.authMethod, isAuthMethodLocked(appData))
127
118
  });
128
119
  } else {
129
120
  Object.assign(context, { actionCreate: true, ...authMethodContext(payload.authMethod) });
@@ -461,12 +452,10 @@ function init(args) {
461
452
 
462
453
  app,
463
454
 
464
- baseScopesApi: app.baseScopes === 'api',
465
- baseScopesImap: app.baseScopes === 'imap' || !app.baseScopes,
466
- baseScopesPubsub: app.baseScopes === 'pubsub',
455
+ ...baseScopesContext(app.baseScopes),
467
456
 
468
457
  appShowAuthMethod: app.provider === 'gmailService',
469
- authMethodIsExternalAccount: app.authMethod === 'externalAccount',
458
+ ...authMethodContext(app.authMethod),
470
459
 
471
460
  canAddServiceAccount,
472
461
 
@@ -661,9 +650,13 @@ function init(args) {
661
650
  method: 'GET',
662
651
  path: '/admin/config/oauth/new',
663
652
  async handler(request, h) {
664
- let { provider } = request.query;
653
+ let { provider, baseScopes } = request.query;
665
654
  let providerData = oauth2ProviderData(provider);
666
655
 
656
+ // A Pub/Sub app is a gmailService app with the pubsub base scope, and the Gmail API forms link
657
+ // here to create one, preselected. Any other provider keeps the IMAP default
658
+ let preselectPubsub = provider === 'gmailService' && baseScopes === 'pubsub';
659
+
667
660
  let serviceUrl = await settings.get('serviceUrl');
668
661
  let defaultRedirectUrl = `${serviceUrl}/oauth`;
669
662
  if (provider === 'outlook') {
@@ -682,9 +675,7 @@ function init(args) {
682
675
  providerData,
683
676
  defaultRedirectUrl,
684
677
 
685
- baseScopesImap: true,
686
- baseScopesApi: false,
687
- baseScopesPubsub: false,
678
+ ...baseScopesContext(preselectPubsub ? 'pubsub' : 'imap'),
688
679
 
689
680
  ...authMethodContext('serviceKey'),
690
681
 
@@ -700,7 +691,8 @@ function init(args) {
700
691
  values: {
701
692
  provider,
702
693
  redirectUrl: defaultRedirectUrl,
703
- authMethod: 'serviceKey'
694
+ authMethod: 'serviceKey',
695
+ enabled: true
704
696
  },
705
697
 
706
698
  authorityCommon: true
@@ -728,7 +720,8 @@ function init(args) {
728
720
  .empty('')
729
721
  .valid(...Object.keys(OAUTH_PROVIDERS))
730
722
  .label('Provider')
731
- .required()
723
+ .required(),
724
+ baseScopes: Joi.string().empty('').valid('pubsub').label('Base scopes')
732
725
  })
733
726
  }
734
727
  }
@@ -856,15 +849,13 @@ function init(args) {
856
849
  hasServiceKey: !!appData.serviceKey,
857
850
  hasExternalAccount: !!appData.externalAccount,
858
851
 
859
- ...authMethodContext(appData.authMethod, !!appData.serviceKey || !!appData.externalAccount),
852
+ ...authMethodContext(appData.authMethod, isAuthMethodLocked(appData)),
860
853
 
861
854
  pubSubApps: await getPubSubAppsForSelect(values.pubSubApp),
862
855
 
863
856
  values,
864
857
 
865
- baseScopesApi: values.baseScopes === 'api',
866
- baseScopesImap: values.baseScopes === 'imap' || !values.baseScopes,
867
- baseScopesPubsub: values.baseScopes === 'pubsub',
858
+ ...baseScopesContext(values.baseScopes),
868
859
 
869
860
  azureClouds: structuredClone(AZURE_CLOUDS).map(entry => {
870
861
  entry.selected = values.cloud === entry.id;
@@ -0,0 +1,19 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Render-context booleans for the OAuth2 app form's base scope radios and the sections they reveal,
5
+ * shared by the create, edit and app pages and their validation re-renders. A missing scope is an
6
+ * app stored before base scopes existed, which used IMAP and SMTP.
7
+ *
8
+ * @param {string} [baseScopes] - 'imap', 'api' or 'pubsub'
9
+ * @returns {{baseScopesApi: boolean, baseScopesImap: boolean, baseScopesPubsub: boolean}}
10
+ */
11
+ function baseScopesContext(baseScopes) {
12
+ return {
13
+ baseScopesApi: baseScopes === 'api',
14
+ baseScopesImap: baseScopes === 'imap' || !baseScopes,
15
+ baseScopesPubsub: baseScopes === 'pubsub'
16
+ };
17
+ }
18
+
19
+ module.exports = { baseScopesContext };
@@ -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 };
@@ -30,15 +30,35 @@ function eventAllowed(webhookEvents, eventName) {
30
30
  return events.includes('*') || events.includes(eventName);
31
31
  }
32
32
 
33
- // The custom headers of one delivery, later lists overriding earlier ones. A custom route carries
34
- // its own headers and nothing else: the global and account-level headers belong to the default
35
- // target, and letting them ride along sent an account's secrets to an operator-defined endpoint
36
- // and let an account override the route's own Authorization.
37
- function deliveryCustomHeaders(customRoute, globalHeaders, accountHeaders) {
38
- let lists = customRoute ? [customRoute.customHeaders] : [globalHeaders, accountHeaders];
33
+ // Which custom header lists travel with a delivery, by the configuration level whose target won
34
+ // (`source`, from resolveTargetUrl), in the order they are merged (later lists override earlier):
35
+ //
36
+ // - A custom route carries its own headers and nothing else. The global and account-level headers
37
+ // belong to the default target, and letting them ride along sent an account's secrets to an
38
+ // operator-defined endpoint and let an account override the route's own Authorization.
39
+ // - The global headers go to the global target only. They typically hold the credential of the
40
+ // operator's own receiver, and the per-account URL is settable by an account-scoped API token,
41
+ // so sending them along to an account's URL handed that credential to whoever set the URL.
42
+ // - An account's headers accompany its deliveries to whichever default target they go to: an
43
+ // account identifying itself to the global receiver is what the account-level list is for.
44
+ //
45
+ // The worker reads this to decide which lists to load, deliveryCustomHeaders() to merge them and
46
+ // describeEffectiveRouting() to count them, so the rule lives in one place.
47
+ const HEADER_LEVELS = {
48
+ route: ['route'],
49
+ global: ['global', 'account'],
50
+ account: ['account']
51
+ };
52
+
53
+ function headerLevels(source) {
54
+ return HEADER_LEVELS[source] || [];
55
+ }
56
+
57
+ // The custom headers of one delivery. `headers` maps a level name to its header list.
58
+ function deliveryCustomHeaders(source, lists) {
39
59
  let headers = {};
40
- for (let list of lists) {
41
- for (let header of [].concat(list || [])) {
60
+ for (let level of headerLevels(source)) {
61
+ for (let header of [].concat(lists[level] || [])) {
42
62
  if (header && header.key) {
43
63
  headers[header.key] = header.value;
44
64
  }
@@ -66,8 +86,11 @@ function describeEffectiveRouting(opts) {
66
86
 
67
87
  let { url, source } = resolveTargetUrl(null, opts.accountWebhooks, opts.globalWebhooks);
68
88
 
69
- let globalHeaders = [].concat(opts.globalCustomHeaders || []).length;
70
- let accountHeaders = [].concat(opts.accountCustomHeaders || []).length;
89
+ // Only the lists that travel to the winning target are counted, so an account that overrides
90
+ // the URL is shown its own headers alone
91
+ let levels = headerLevels(source);
92
+ let globalHeaders = levels.includes('global') ? [].concat(opts.globalCustomHeaders || []).length : 0;
93
+ let accountHeaders = levels.includes('account') ? [].concat(opts.accountCustomHeaders || []).length : 0;
71
94
 
72
95
  let customHeadersLabel = null;
73
96
  if (globalHeaders && accountHeaders) {
@@ -107,4 +130,4 @@ function describeEffectiveRouting(opts) {
107
130
  };
108
131
  }
109
132
 
110
- module.exports = { resolveTargetUrl, isDeliverableRoute, eventAllowed, describeEffectiveRouting, deliveryCustomHeaders, isRouteMappingMissing };
133
+ module.exports = { resolveTargetUrl, isDeliverableRoute, eventAllowed, describeEffectiveRouting, headerLevels, deliveryCustomHeaders, isRouteMappingMissing };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "emailengine-app",
3
- "version": "2.82.2",
3
+ "version": "2.83.1",
4
4
  "private": false,
5
5
  "productTitle": "EmailEngine",
6
6
  "description": "Email Sync Engine",
@@ -69,25 +69,25 @@
69
69
  "@postalsys/email-text-tools": "2.4.18",
70
70
  "@postalsys/gettext": "4.1.1",
71
71
  "@postalsys/joi-messages": "1.3.1",
72
- "@postalsys/templates": "2.0.3",
73
- "@sentry/node-core": "10.76.0",
72
+ "@postalsys/templates": "2.0.4",
73
+ "@sentry/node-core": "10.76.1",
74
74
  "@simplewebauthn/server": "14.0.3",
75
75
  "@zone-eu/mailsplit": "5.4.20",
76
76
  "@zone-eu/wild-config": "1.7.7",
77
77
  "bullmq": "6.3.11",
78
78
  "compare-versions": "6.1.1",
79
- "dotenv": "18.0.5",
79
+ "dotenv": "18.0.6",
80
80
  "encoding-japanese": "2.4.0",
81
81
  "exponential-backoff": "3.1.3",
82
82
  "fast-xml-parser": "5.11.2",
83
83
  "gettext-parser": "7.0.1",
84
- "handlebars": "4.7.9",
84
+ "handlebars": "4.7.10",
85
85
  "hapi-pino": "13.0.0",
86
86
  "he": "1.2.0",
87
87
  "html-to-text": "10.0.1",
88
88
  "ical.js": "2.2.1",
89
89
  "iconv-lite": "0.7.3",
90
- "imapflow": "2.2.5",
90
+ "imapflow": "2.3.0",
91
91
  "ioredfour": "1.4.4",
92
92
  "ioredis": "6.0.0",
93
93
  "ipaddr.js": "2.5.0",
@@ -95,33 +95,33 @@
95
95
  "libbase64": "1.3.2",
96
96
  "libmime": "5.4.7",
97
97
  "libqp": "2.1.2",
98
- "mailparser": "3.9.36",
98
+ "mailparser": "3.9.37",
99
99
  "marked": "15.0.12",
100
100
  "minimist": "1.2.8",
101
101
  "murmurhash": "2.0.1",
102
102
  "nanoid": "3.3.20",
103
- "nodemailer": "10.0.15",
103
+ "nodemailer": "10.0.16",
104
104
  "pino": "10.3.1",
105
105
  "prom-client": "15.1.3",
106
106
  "psl": "1.15.0",
107
107
  "pubface": "1.1.18",
108
108
  "punycode.js": "2.3.1",
109
109
  "qrcode-generator": "2.0.4",
110
- "smtp-server": "3.19.17",
110
+ "smtp-server": "3.19.18",
111
111
  "socks": "2.8.10",
112
112
  "timezones-list": "3.1.0",
113
113
  "undici": "7.30.0"
114
114
  },
115
115
  "devDependencies": {
116
116
  "@eslint/js": "10.0.1",
117
- "@iconify-json/tabler": "1.2.41",
117
+ "@iconify-json/tabler": "1.2.42",
118
118
  "@iconify/tailwind4": "1.2.3",
119
119
  "@playwright/test": "1.63.0",
120
120
  "@postalsys/ee-client": "1.8.1",
121
121
  "@simplewebauthn/browser": "14.0.0",
122
122
  "@tailwindcss/cli": "4.3.3",
123
123
  "ace-builds": "1.44.0",
124
- "acorn": "8.18.0",
124
+ "acorn": "8.19.0",
125
125
  "acorn-walk": "8.3.5",
126
126
  "chai": "4.5.0",
127
127
  "eerawlog": "1.5.5",