emailengine-app 2.82.2 → 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 (55) hide show
  1. package/.ncurc.js +8 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +18 -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 +11 -2
  16. package/lib/enum-descriptions.js +3 -1
  17. package/lib/imapproxy/imap-core/README.md +1 -0
  18. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +11 -1
  19. package/lib/imapproxy/proxy-handoff.js +6 -3
  20. package/lib/imapproxy/response-error.js +14 -1
  21. package/lib/oauth/gcp-metadata.js +222 -0
  22. package/lib/oauth/gmail.js +115 -20
  23. package/lib/oauth/mail-ru.js +10 -4
  24. package/lib/oauth/outlook.js +11 -4
  25. package/lib/oauth/token-fetch.js +4 -2
  26. package/lib/oauth/verify-app.js +120 -32
  27. package/lib/oauth2-apps.js +46 -12
  28. package/lib/schemas.js +60 -18
  29. package/lib/tools.js +52 -2
  30. package/lib/ui-routes/admin-entities-routes.js +2 -2
  31. package/lib/ui-routes/auth-routes.js +4 -1
  32. package/lib/ui-routes/gmail-service-auth.js +64 -0
  33. package/lib/ui-routes/oauth-config-routes.js +8 -16
  34. package/lib/ui-routes/suppression-list-routes.js +2 -2
  35. package/lib/utils/network.js +29 -0
  36. package/lib/webhook-request.js +12 -4
  37. package/lib/webhook-routing.js +34 -11
  38. package/package.json +11 -11
  39. package/sbom.json +1 -1
  40. package/server.js +8 -2
  41. package/static/css/flyonui.css +1 -1
  42. package/static/js/app.js +2 -1
  43. package/static/js/ui.js +6 -1
  44. package/static/licenses.html +18 -28
  45. package/translations/messages.pot +73 -73
  46. package/views/accounts/edit.hbs +1 -1
  47. package/views/config/imap-proxy.hbs +1 -1
  48. package/views/config/network.hbs +7 -5
  49. package/views/config/oauth/app.hbs +2 -0
  50. package/views/config/smtp.hbs +1 -1
  51. package/views/config/tls.hbs +2 -2
  52. package/views/config/webhooks.hbs +1 -1
  53. package/views/partials/oauth_form.hbs +116 -27
  54. package/workers/api.js +4 -2
  55. package/workers/webhooks.js +18 -7
@@ -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
 
@@ -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.0",
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",