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/.ncurc.js CHANGED
@@ -15,7 +15,7 @@ module.exports = {
15
15
  // `pino` is capped harder than the rest, at 'patch', because the break arrived in a MINOR and a
16
16
  // major cap would not have stopped it. See its entry below.
17
17
  target: name =>
18
- name === 'pino'
18
+ ['pino', '@playwright/test'].includes(name)
19
19
  ? 'patch'
20
20
  : ['nanoid', 'gettext-parser', 'xgettext-template', 'chai', 'undici', 'marked', '@sentry/node-core', 'he'].includes(name)
21
21
  ? 'minor'
@@ -31,6 +31,13 @@ module.exports = {
31
31
  // pino reaches it whenever a logger is constructed. Lift only once a pino
32
32
  // release guards the getCallSites path, or pkg ships position info for
33
33
  // snapshotted scripts, and only with a binary built and run to prove it.
34
+ // @playwright/test - held on 1.63.x (dev only, the e2e tier). Under 1.64.0 the busy-state spec
35
+ // (test/e2e/pages-ui-busy-state.spec.js) hangs: it answers a form's navigation
36
+ // POST with route.fulfill({ status: 204 }) so the page stays put, and after that
37
+ // click 1.64 never resolves a locator assertion on the same page (toBeDisabled
38
+ // times out with "Received: undefined" while the page snapshot shows the button).
39
+ // Same spec passes in 3.8 s on 1.63.0; nothing in the 1.64 release notes covers
40
+ // it. Lift once a 1.64.x or later passes that spec unchanged.
34
41
  // nanoid - 4.x dropped the CommonJS require export (ESM-only)
35
42
  // gettext-parser - 8.x is ESM-only
36
43
  // xgettext-template - 6.x is ESM-only (translation build tool)
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.82.2"
2
+ ".": "2.83.1"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.83.1](https://github.com/postalsys/emailengine/compare/v2.83.0...v2.83.1) (2026-10-08)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * ask a service account app's purpose before its authentication method ([42ac521](https://github.com/postalsys/emailengine/commit/42ac521021fabe8976fd86f13da6e8c6d1707ac3))
9
+ * close the attached service account review findings ([d567ad8](https://github.com/postalsys/emailengine/commit/d567ad866f90e0ced6b2b1d8fa722e7a74d6ac25))
10
+ * drop the beta label from the export API ([21df0b0](https://github.com/postalsys/emailengine/commit/21df0b0e4ad5bb1ef18ce3eb916fa77e9028075d))
11
+ * keep the OAuth2 app routes inside their size budget ([8a72c20](https://github.com/postalsys/emailengine/commit/8a72c20188aad62d7cb32401d98869c1ed96a75a))
12
+ * rework the OAuth2 app form around what each app connects with ([a000412](https://github.com/postalsys/emailengine/commit/a000412ecc2c233f9fb4cc50fe8486904692a8ba))
13
+
14
+ ## [2.83.0](https://github.com/postalsys/emailengine/compare/v2.82.2...v2.83.0) (2026-10-08)
15
+
16
+
17
+ ### Features
18
+
19
+ * **oauth2:** authenticate Cloud Pub/Sub apps as the attached Google Cloud service account ([0b3e433](https://github.com/postalsys/emailengine/commit/0b3e43345c905b5f8afa5eea716bd56ec703d60b))
20
+
21
+
22
+ ### Bug Fixes
23
+
24
+ * accept sender and recipient addresses with a local part over 64 octets ([96e813d](https://github.com/postalsys/emailengine/commit/96e813dae325648e954b607276471e87789cf3cd))
25
+ * **deps:** update imapflow to 2.3.0 ([a2a0097](https://github.com/postalsys/emailengine/commit/a2a00970ba93a88bdd3da337eb225ec192b569a4))
26
+ * **deps:** update imapflow, nodemailer, mailparser, smtp-server and templates ([27b1690](https://github.com/postalsys/emailengine/commit/27b169034c5743303daca354f0b30c1805d8a0e9))
27
+ * label the local address strategies by the traffic they cover ([a116220](https://github.com/postalsys/emailengine/commit/a1162205bb3365ac997b5d5830631eb643fbf375))
28
+ * route API account HTTP traffic through the account proxy and local address ([a3884e1](https://github.com/postalsys/emailengine/commit/a3884e15e6c7e7cf747f515ebb647785d01007e8))
29
+ * **security:** keep the global webhook headers off account-level targets, and close the other findings of the 2026-10-06 review ([8b89a61](https://github.com/postalsys/emailengine/commit/8b89a612b85f0d645d16fde56452719a4dd68f6a))
30
+ * show the TLS page's Check reachability and Request buttons as busy while they run ([173b72c](https://github.com/postalsys/emailengine/commit/173b72c5712ff89bc167630334241803b4c1d844))
31
+
3
32
  ## [2.82.2](https://github.com/postalsys/emailengine/compare/v2.82.1...v2.82.2) (2026-10-05)
4
33
 
5
34
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-10-02T14:46:13.000000",
2
+ "creationTime": "2026-10-07T14:46:45.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
package/lib/account.js CHANGED
@@ -35,6 +35,7 @@ const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountSt
35
35
  const { decodeStoredMailboxEntry } = require('./email-client/imap/listing-diff');
36
36
  const { readImapData } = require('./account/imap-data');
37
37
  const { isTransientCredentialError, credentialErrorStatus } = require('./email-client/credential-errors');
38
+ const { getAccountHttpRoute } = require('./utils/network');
38
39
 
39
40
  // Shared Lock instance to prevent Redis connection leak (one subscriber per Lock instance)
40
41
  // Previously, each Account created its own Lock, causing ~30k connections with 30k accounts
@@ -1631,7 +1632,10 @@ class Account {
1631
1632
  try {
1632
1633
  let oauth2App = await oauth2Apps.get(accountData.oauth2.provider);
1633
1634
  if (oauth2App && oauth2App.provider !== 'gmailService') {
1634
- let oauthClient = await oauth2Apps.getClient(accountData.oauth2.provider, { logger: this.logger });
1635
+ let oauthClient = await oauth2Apps.getClient(accountData.oauth2.provider, {
1636
+ logger: this.logger,
1637
+ route: await this.getHttpRoute(accountData)
1638
+ });
1635
1639
  if (oauthClient && typeof oauthClient.revokeToken === 'function') {
1636
1640
  await oauthClient.revokeToken(token);
1637
1641
  }
@@ -2457,7 +2461,10 @@ class Account {
2457
2461
  return accountData;
2458
2462
  }
2459
2463
 
2460
- const oAuth2Client = await oauth2Apps.getClient(accountData.oauth2.provider, oauth2Opts);
2464
+ const oAuth2Client = await oauth2Apps.getClient(
2465
+ accountData.oauth2.provider,
2466
+ Object.assign({}, oauth2Opts, { route: await this.getHttpRoute(accountData) })
2467
+ );
2461
2468
 
2462
2469
  let r = await oAuth2Client.refreshToken({
2463
2470
  refreshToken: accountData.oauth2.refreshToken,
@@ -2684,6 +2691,11 @@ class Account {
2684
2691
  return false;
2685
2692
  }
2686
2693
 
2694
+ // The network route for this account's HTTP traffic, see getAccountHttpRoute()
2695
+ getHttpRoute(accountData) {
2696
+ return getAccountHttpRoute(this.redis, accountData);
2697
+ }
2698
+
2687
2699
  async oauth2Request(url, method, payload, options) {
2688
2700
  let accountData = await this.loadAccountData(this.account);
2689
2701
  if (!accountData.oauth2 || !accountData.oauth2.auth || !accountData.oauth2.auth.user || !accountData.oauth2.provider) {
@@ -2693,7 +2705,8 @@ class Account {
2693
2705
  }
2694
2706
 
2695
2707
  let oAuth2Client = await oauth2Apps.getClient(accountData.oauth2.provider, {
2696
- logger: this.logger
2708
+ logger: this.logger,
2709
+ route: await this.getHttpRoute(accountData)
2697
2710
  });
2698
2711
 
2699
2712
  const tokenData = await this.getActiveAccessTokenData();
@@ -60,7 +60,7 @@ function formatDescription(text) {
60
60
  .join('</p><p class="mt-2">');
61
61
  }
62
62
 
63
- // URL segment for a tag name: "Export (Beta)" -> "export-beta"
63
+ // URL segment for a tag name: "Multi Message Actions" -> "multi-message-actions"
64
64
  function slugify(value) {
65
65
  return String(value || '')
66
66
  .toLowerCase()
@@ -31,7 +31,9 @@ const {
31
31
  ACCOUNT_DISPLAY_STATES,
32
32
  apiResponses,
33
33
  ENUM_DESCRIPTIONS,
34
- apiBoolean
34
+ apiBoolean,
35
+ mailboxAddressSchema,
36
+ accountProxySchema
35
37
  } = require('../schemas');
36
38
 
37
39
  const { REDIS_PREFIX, MAX_FORM_TTL, NONCE_BYTES, MCP_MAX_PAGE_SIZE, OUTLOOK_SYNC_MAX_LOOKBACK } = require('../consts');
@@ -340,7 +342,7 @@ async function init(args) {
340
342
  notifyFrom: accountSchemas.notifyFrom.default('now'),
341
343
  syncFrom: accountSchemas.syncFrom,
342
344
 
343
- proxy: settingsSchema.proxyUrl,
345
+ proxy: accountProxySchema,
344
346
  smtpEhloName: settingsSchema.smtpEhloName,
345
347
 
346
348
  imapIndexer: accountSchemas.imapIndexer,
@@ -509,7 +511,7 @@ async function init(args) {
509
511
  notifyFrom: accountSchemas.notifyFrom,
510
512
  syncFrom: accountSchemas.syncFrom,
511
513
 
512
- proxy: settingsSchema.proxyUrl,
514
+ proxy: accountProxySchema,
513
515
  smtpEhloName: settingsSchema.smtpEhloName,
514
516
 
515
517
  imap: Joi.object(imapUpdateSchema)
@@ -1016,7 +1018,7 @@ async function init(args) {
1016
1018
  })
1017
1019
  .example('https://myservice.com/imap/webhooks')
1018
1020
  .description('Account-specific webhook URL'),
1019
- proxy: settingsSchema.proxyUrl,
1021
+ proxy: accountProxySchema,
1020
1022
  smtpEhloName: settingsSchema.smtpEhloName,
1021
1023
 
1022
1024
  counters: accountCountersSchema,
@@ -1284,7 +1286,7 @@ async function init(args) {
1284
1286
  })
1285
1287
  .example('https://myservice.com/imap/webhooks')
1286
1288
  .description('Account-specific webhook URL'),
1287
- proxy: settingsSchema.proxyUrl,
1289
+ proxy: accountProxySchema,
1288
1290
  smtpEhloName: settingsSchema.smtpEhloName,
1289
1291
 
1290
1292
  imap: Joi.object(imapSchema).description('IMAP configuration').label('IMAPResponse'),
@@ -1583,7 +1585,7 @@ async function init(args) {
1583
1585
  signatures: Joi.array()
1584
1586
  .items(
1585
1587
  Joi.object({
1586
- address: Joi.string().email().example('user@example.com').description('Email address associated with the signature').required(),
1588
+ address: mailboxAddressSchema.example('user@example.com').description('Email address associated with the signature').required(),
1587
1589
  signature: Joi.string().example('<div>Best regards,</div>').description('Signature HTML code').required()
1588
1590
  }).label('SignatureResponseItem')
1589
1591
  )
@@ -8,7 +8,7 @@ const getSecret = require('../get-secret');
8
8
  const { lists } = require('../lists');
9
9
  const { failAction } = require('../tools');
10
10
  const { handleError } = require('./route-helpers');
11
- const { accountIdSchema, blocklistListIdSchema, apiResponses, apiBoolean } = require('../schemas');
11
+ const { accountIdSchema, blocklistListIdSchema, apiResponses, apiBoolean, mailboxAddressSchema } = require('../schemas');
12
12
  const { IMPACT } = require('./operation-impact');
13
13
  const { MCP_MAX_PAGE_SIZE } = require('../consts');
14
14
 
@@ -160,7 +160,7 @@ async function init(args) {
160
160
  addresses: Joi.array()
161
161
  .items(
162
162
  Joi.object({
163
- recipient: Joi.string().email().example('user@example.com').description('Listed email address').required(),
163
+ recipient: mailboxAddressSchema.example('user@example.com').description('Listed email address').required(),
164
164
  account: accountIdSchema.required(),
165
165
  messageId: Joi.string().example('<test123@example.com>').description('Message ID'),
166
166
  source: Joi.string().example('api').description('Which mechanism was used to add the entry'),
@@ -252,7 +252,7 @@ async function init(args) {
252
252
 
253
253
  payload: Joi.object({
254
254
  account: accountIdSchema.required(),
255
- recipient: Joi.string().empty('').email().example('user@example.com').description('Email address to add to the list').required(),
255
+ recipient: mailboxAddressSchema.empty('').example('user@example.com').description('Email address to add to the list').required(),
256
256
  reason: Joi.string().empty('').default('block').example('unsubscribe').description('Identifier for the blocking reason')
257
257
  }).label('BlocklistListAddPayload')
258
258
  },
@@ -325,7 +325,7 @@ async function init(args) {
325
325
  }).label('BlocklistListRequest'),
326
326
 
327
327
  query: Joi.object({
328
- recipient: Joi.string().empty('').email().example('user@example.com').description('Email address to remove from the list').required()
328
+ recipient: mailboxAddressSchema.empty('').example('user@example.com').description('Email address to remove from the list').required()
329
329
  }).label('RecipientQuery')
330
330
  },
331
331
 
@@ -34,7 +34,7 @@ async function init(args) {
34
34
  options: {
35
35
  description: 'Create export',
36
36
  notes: ['Creates a new bulk message export job. The export runs asynchronously and notifies via webhook when complete.', BEHAVIOR.BACKGROUND_JOB],
37
- tags: ['api', 'Export (Beta)'],
37
+ tags: ['api', 'Export'],
38
38
 
39
39
  plugins: {
40
40
  openapi: {
@@ -94,7 +94,7 @@ async function init(args) {
94
94
  options: {
95
95
  description: 'Get export status',
96
96
  notes: 'Returns the status and progress of an export job.',
97
- tags: ['api', 'Export (Beta)'],
97
+ tags: ['api', 'Export'],
98
98
 
99
99
  plugins: {
100
100
  openapi: {
@@ -158,7 +158,7 @@ async function init(args) {
158
158
  options: {
159
159
  description: 'Download export file',
160
160
  notes: 'Downloads the completed export file as gzip-compressed NDJSON.',
161
- tags: ['api', 'Export (Beta)'],
161
+ tags: ['api', 'Export'],
162
162
 
163
163
  plugins: {
164
164
  openapi: {
@@ -208,7 +208,7 @@ async function init(args) {
208
208
  options: {
209
209
  description: 'Delete export',
210
210
  notes: 'Cancels a pending export or deletes a completed export. Removes both Redis data and the export file.',
211
- tags: ['api', 'Export (Beta)'],
211
+ tags: ['api', 'Export'],
212
212
 
213
213
  plugins: {
214
214
  openapi: {
@@ -264,7 +264,7 @@ async function init(args) {
264
264
  options: {
265
265
  description: 'List exports',
266
266
  notes: 'Lists all exports for an account with pagination.',
267
- tags: ['api', 'Export (Beta)'],
267
+ tags: ['api', 'Export'],
268
268
 
269
269
  plugins: {
270
270
  openapi: {
@@ -18,7 +18,7 @@ const {
18
18
  apiBoolean,
19
19
  formBoolean
20
20
  } = require('../schemas');
21
- const { handleError, throwNotFound, flattenOAuthAppMeta, MASKED } = require('./route-helpers');
21
+ const { handleError, throwNotFound, flattenOAuthAppMeta, assertNoAttachedIdentity, MASKED } = require('./route-helpers');
22
22
  const { ENCRYPTED_APP_KEYS, MCP_MAX_PAGE_SIZE } = require('../consts');
23
23
  const { IMPACT } = require('./operation-impact');
24
24
 
@@ -37,7 +37,9 @@ const oauth2AppExtraFields = {
37
37
  .meta({ enumDescriptions: ENUM_DESCRIPTIONS.appBaseScopes })
38
38
  .label('AppBaseScopes'),
39
39
  pubSubApp: oauthCreateSchema.pubSubApp.description('Cloud Pub/Sub app ID used for Gmail change notifications').label('AppPubSubApp'),
40
- authMethod: Joi.string().example('serviceKey').description('Authentication method for Gmail service accounts'),
40
+ authMethod: Joi.string()
41
+ .example('serviceKey')
42
+ .description('Authentication method for Gmail service accounts: serviceKey, externalAccount or metadataServer'),
41
43
  cloud: Joi.string().example('global').description('Azure cloud type for Outlook OAuth2 applications'),
42
44
  tenant: Joi.string()
43
45
  .example('f8cdef31-a31e-4b4a-93e4-5f571e91255a')
@@ -343,6 +345,7 @@ async function init(args) {
343
345
 
344
346
  async handler(request) {
345
347
  try {
348
+ assertNoAttachedIdentity(request, request.payload.authMethod, 'create');
346
349
  let result = await oauth2Apps.create(request.payload);
347
350
  return await applyPubSubUpdates(result);
348
351
  } catch (err) {
@@ -410,6 +413,9 @@ async function init(args) {
410
413
  );
411
414
  }
412
415
 
416
+ let storedApp = await oauth2Apps.get(request.params.app);
417
+ assertNoAttachedIdentity(request, storedApp && storedApp.authMethod, 'modify');
418
+
413
419
  let result = await oauth2Apps.update(request.params.app, request.payload);
414
420
  return await applyPubSubUpdates(result);
415
421
  } catch (err) {
@@ -408,8 +408,42 @@ function assertNoPrivilegedSettings(request, keys, verb = 'change') {
408
408
  throw Boom.forbidden(`A token with restricted permissions can not ${verb} ${privileged.join(', ')}`);
409
409
  }
410
410
 
411
+ /**
412
+ * Refuses an OAuth2 application that would authenticate as the instance's own cloud identity, when
413
+ * the credential creating it is narrowed.
414
+ *
415
+ * Every other service-account app acts with a credential its creator supplied. `authMethod:
416
+ * 'metadataServer'` supplies none: the app runs as the service account attached to the VM, GKE
417
+ * workload or Cloud Run service EmailEngine is on, and its Pub/Sub setup then creates and adopts
418
+ * topics and subscriptions in whatever project the payload names. That identity belongs to whoever
419
+ * deployed the instance, the same trust that keeps the metadata host an environment value rather
420
+ * than an app field, so a token narrowed to `oauth2` may manage applications but not lend itself
421
+ * the deployment's identity. The admin interface and an unrestricted token still create these apps.
422
+ *
423
+ * Creating one is not the only way in: an update of a saved app re-runs its Pub/Sub setup as that same
424
+ * identity, so moving the project, topic or subscription of an existing attached service account app
425
+ * lends it just the same. Any update of such an app is refused, not only one naming those fields: an
426
+ * allow-list of harmless fields would be one more list to keep right, and the admin interface and an
427
+ * unrestricted token remain. A saved app's method is pinned (isAuthMethodLocked() in
428
+ * lib/oauth2-apps.js), so the stored one is what an update checks.
429
+ *
430
+ * @param {Object} request - the Hapi request
431
+ * @param {string} [authMethod] - the method of the app being created (the payload's) or modified (the stored one's)
432
+ * @param {string} verb - 'create' or 'modify', for the refusal message
433
+ */
434
+ function assertNoAttachedIdentity(request, authMethod, verb) {
435
+ if (authMethod !== 'metadataServer' || !isRestrictedCredential(request)) {
436
+ return;
437
+ }
438
+
439
+ throw Boom.forbidden(
440
+ `A token with restricted permissions can not ${verb} an application that uses the attached service account (metadataServer). Use the admin interface or an unrestricted token`
441
+ );
442
+ }
443
+
411
444
  module.exports = {
412
445
  handleError,
446
+ assertNoAttachedIdentity,
413
447
  logApiError,
414
448
  throwNotFound,
415
449
  assertNoPrivilegedSettings,
@@ -14,6 +14,7 @@ const {
14
14
  documentStoreSchema,
15
15
  fromAddressSchema,
16
16
  addressSchema,
17
+ mailboxAddressSchema,
17
18
  idempotencyKeySchema,
18
19
  headerTimeoutSchema,
19
20
  accountIdSchema,
@@ -69,7 +70,7 @@ const dsnSchema = Joi.object({
69
70
  .example(['failure', 'delay'])
70
71
  .description('Defines the conditions under which a DSN response should be sent')
71
72
  .label('DsnNotify'),
72
- recipient: Joi.string().trim().empty('').email().example('bounces@example.com').description('The email address the DSN should be sent (ORCPT)')
73
+ recipient: mailboxAddressSchema.trim().empty('').example('bounces@example.com').description('The email address the DSN should be sent (ORCPT)')
73
74
  }).description('Request DSN notifications');
74
75
 
75
76
  // Refused for a token that carries a `permissions` record, see assertNoNetworkOverride() - the
@@ -225,8 +226,8 @@ async function init(args) {
225
226
  reference: messageReferenceSchema,
226
227
 
227
228
  envelope: Joi.object({
228
- from: Joi.string().email().allow('').example('sender@example.com'),
229
- to: Joi.array().items(Joi.string().email().required().example('recipient@example.com')).single().label('SmtpEnvelopeTo')
229
+ from: mailboxAddressSchema.allow('').example('sender@example.com'),
230
+ to: Joi.array().items(mailboxAddressSchema.required().example('recipient@example.com')).single().label('SmtpEnvelopeTo')
230
231
  })
231
232
  .description('An optional object specifying the SMTP envelope used during email transmission')
232
233
  .meta({ usage: FIELD_USAGE.messageEnvelope })
@@ -629,8 +630,8 @@ async function init(args) {
629
630
 
630
631
  payload: Joi.object({
631
632
  envelope: Joi.object({
632
- from: Joi.string().email().allow('').example('sender@example.com'),
633
- to: Joi.array().items(Joi.string().email().required().example('recipient@example.com')).single().label('DraftSmtpEnvelopeTo')
633
+ from: mailboxAddressSchema.allow('').example('sender@example.com'),
634
+ to: Joi.array().items(mailboxAddressSchema.required().example('recipient@example.com')).single().label('DraftSmtpEnvelopeTo')
634
635
  })
635
636
  .description(
636
637
  'An optional object specifying the SMTP envelope used during email transmission. Only used when the message is delivered over SMTP'
@@ -698,7 +698,9 @@ async function bounceDetect(sourceStream) {
698
698
  * Match pattern like:
699
699
  * The following message to <user@example.com> was undeliverable
700
700
  */
701
- let m = text.match(/The following message to <([^>@]+@[^>]+)> was undeliverable/);
701
+ // Bounded classes that exclude '<' and whitespace, like the "host said" matcher above: an
702
+ // unterminated address would otherwise be scanned to the end of the text at every anchor
703
+ let m = text.match(/The following message to <([^<>@\s]{1,256}@[^<>\s]{1,256})> was undeliverable/);
702
704
  if (m) {
703
705
  result.recipient = m[1];
704
706
  }
@@ -773,7 +775,7 @@ async function bounceDetect(sourceStream) {
773
775
  * ...
774
776
  * Remote host said: response message
775
777
  */
776
- let m = text.match(/Your message could not be delivered to the following address:\s+<([^>@]+@[^>]+)>/);
778
+ let m = text.match(/Your message could not be delivered to the following address:\s+<([^<>@\s]{1,256}@[^<>\s]{1,256})>/);
777
779
  if (m) {
778
780
  result.recipient = result.recipient || m[1];
779
781
 
@@ -13,9 +13,14 @@ const ipaddr = require('ipaddr.js');
13
13
  // service and which no real webhook receiver lives on.
14
14
  //
15
15
  // Scope: this is a guardrail against misconfiguration and mistakes, not a boundary against a
16
- // hostile operator. Anyone who can set a webhook target can generally also author fn/map scripts,
17
- // which lib/sub-script.js runs with full server privileges and hands an unfiltered fetch. Do not
18
- // treat the policy as tenant isolation.
16
+ // hostile operator. An operator who can author fn/map scripts has lib/sub-script.js running them
17
+ // with full server privileges and an unfiltered fetch, so the policy adds nothing against them.
18
+ // Who it does bound is an account-scoped API token: such a token can set its account's webhook
19
+ // URL and custom headers but author no script, so for it the policy is the only limit on where a
20
+ // delivery is sent. An instance that hands account tokens to parties it does not trust with its
21
+ // network position should run the `private` policy; the default keeps the loopback and private
22
+ // ranges open because a receiver on the same host or network is the ordinary self-hosted setup.
23
+ // Do not treat the policy as tenant isolation.
19
24
  const POLICY_OFF = 'off';
20
25
  const POLICY_LINK_LOCAL = 'link-local';
21
26
  const POLICY_PRIVATE = 'private';
@@ -2046,7 +2046,9 @@ class GmailClient extends BaseClient {
2046
2046
  let accountData = await this.accountObject.loadAccountData(this.account, false);
2047
2047
  this.oAuth2Client = await oauth2Apps.getClient(accountData.oauth2.provider, {
2048
2048
  logger: this.logger,
2049
- logRaw: this.options.logRaw
2049
+ logRaw: this.options.logRaw,
2050
+ // bound for the connection, like the proxy of an IMAP session: a change applies on reconnect
2051
+ route: await this.accountObject.getHttpRoute(accountData)
2050
2052
  });
2051
2053
  return this.oAuth2Client;
2052
2054
  }
@@ -3326,7 +3326,8 @@ class IMAPClient extends BaseClient {
3326
3326
  if (oauth2App && !this.oAuth2Client) {
3327
3327
  this.oAuth2Client = await oauth2Apps.getClient(accountData.oauth2.provider, {
3328
3328
  logger: this.logger,
3329
- logRaw: this.options.logRaw
3329
+ logRaw: this.options.logRaw,
3330
+ route: await this.accountObject.getHttpRoute(accountData)
3330
3331
  });
3331
3332
  }
3332
3333
 
@@ -308,6 +308,10 @@ class OutlookClient extends BaseClient {
308
308
 
309
309
  await this.getClient(true);
310
310
  await this.prepareDelegatedAccount();
311
+ if (this.delegatedAccountObject) {
312
+ // the delegate is only known now, and its token decides the route
313
+ await this.getClient(true);
314
+ }
311
315
 
312
316
  let accountData = await this.accountObject.loadAccountData();
313
317
 
@@ -3130,10 +3134,15 @@ class OutlookClient extends BaseClient {
3130
3134
  if (this.oAuth2Client && !force) {
3131
3135
  return this.oAuth2Client;
3132
3136
  }
3133
- let accountData = await (this.delegatedAccountObject || this.accountObject).loadAccountData();
3137
+ let accountObject = this.delegatedAccountObject || this.accountObject;
3138
+ let accountData = await accountObject.loadAccountData();
3134
3139
  this.oAuth2Client = await oauth2Apps.getClient(accountData.oauth2?.provider || accountData._app?.id, {
3135
3140
  logger: this.logger,
3136
- logRaw: this.options.logRaw
3141
+ logRaw: this.options.logRaw,
3142
+ // bound for the connection, like the proxy of an IMAP session: a change applies on
3143
+ // reconnect. The route of the account whose token is used, so a delegated mailbox is
3144
+ // reached the same way that token is refreshed.
3145
+ route: await accountObject.getHttpRoute(accountData)
3137
3146
  });
3138
3147
  return this.oAuth2Client;
3139
3148
  }
@@ -227,7 +227,9 @@ const ENUM_DESCRIPTIONS = {
227
227
 
228
228
  gmailAuthMethod: {
229
229
  serviceKey: 'Sign token requests with an uploaded service account key',
230
- externalAccount: 'Sign token requests through Workload Identity Federation, with no key to store'
230
+ externalAccount: 'Sign token requests through Workload Identity Federation, with no key to store',
231
+ metadataServer:
232
+ 'Use the service account attached to the Google Cloud VM, GKE workload or Cloud Run service EmailEngine runs on, read from the metadata server. Cloud Pub/Sub applications only, and not available to a token with restricted permissions'
231
233
  }
232
234
  };
233
235
 
@@ -32,6 +32,7 @@ means re-applying these.
32
32
  | `31f6a590` | 2026-07-26 | Fix the dead teardown guard in the notification listener |
33
33
  | `74856cf6` | 2026-09-02 | Drop the built-in self-signed key/certificate pair from `tls-options.js`; a listener with TLS and no certificate is refused at startup instead of served with a key that ships in every copy |
34
34
  | `2db748fc` | 2026-09-28 | Cap list nesting depth in the parser and guard the debug-log compile; check the command state before accepting a literal and cap literal count/bytes per command; `maxConnections`; error listener and timeout while waiting for the PROXY header; hand bytes pipelined after LOGIN to the proxy (`unbind()` returns `head` and `closed`); lazy indexer load in `imap-tools.js`; indexer `drain` wait and quoted-printable decoding fixes; removed the unused root `memory-notifier.js` |
35
+ | `8b89a612` | 2026-10-07 | `AUTHENTICATE PLAIN` answers an `onAuth` error that names no IMAP response with `NO [TEMPFAIL]` the way LOGIN does, instead of reflecting its message as BAD |
35
36
 
36
37
  Earlier local changes (`09085d12`, `0a389560`, `7e2e94f3`, `04c2aa90`, `1d6df05e`, `612d9f96`,
37
38
  `13edec58`, `2e0bf1ce`, `b9a3e06c`, `b58a827e`, `1813f089`) are maintenance: dependency swaps
@@ -74,6 +74,13 @@ function authenticate(connection, token, requireClientToken, callback) {
74
74
  connection.session,
75
75
  (err, response) => {
76
76
  if (err) {
77
+ // An error naming its IMAP response is answered as that response. Anything else is
78
+ // an internal fault whose message belongs in the log and not on the wire, and that
79
+ // is answered the way LOGIN answers it - handing the error back would send its text
80
+ // as BAD and count it against the connection's bad-command budget
81
+ if (err.response) {
82
+ return callback(null, err);
83
+ }
77
84
  connection._server.logger.info(
78
85
  {
79
86
  err,
@@ -88,7 +95,10 @@ function authenticate(connection, token, requireClientToken, callback) {
88
95
  'PLAIN',
89
96
  err.message
90
97
  );
91
- return callback(err);
98
+ return callback(null, {
99
+ response: 'NO',
100
+ code: 'TEMPFAIL'
101
+ });
92
102
  }
93
103
 
94
104
  if (!response || !response.user) {
@@ -6,7 +6,7 @@
6
6
 
7
7
  const { PassThrough } = require('stream');
8
8
  const { imapHandler } = require('./imap-core/index.js');
9
- const { isImapResponseError, toImapResponseError } = require('./response-error');
9
+ const { isImapResponseError, toImapResponseError, faultResponseError } = require('./response-error');
10
10
 
11
11
  class PassThroughLogger extends PassThrough {
12
12
  constructor(opts = {}) {
@@ -52,14 +52,17 @@ class PassThroughLogger extends PassThrough {
52
52
  */
53
53
  function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, metrics, logRaw }) {
54
54
  // A refusal or a temporary failure the client is told to retry is a warning and reaches the
55
- // client as the IMAP response it carries; anything else is a proxy fault
55
+ // client as the IMAP response it carries; anything else is a proxy fault, logged here and
56
+ // answered with a generic response so its text never reaches the client. Handing the fault
57
+ // itself to imap-core sent that text as BAD, which also counted against the connection's
58
+ // bad-command budget.
56
59
  const loginFailure = (err, fields, messages) => {
57
60
  if (isImapResponseError(err)) {
58
61
  serverLogger.warn(Object.assign({ msg: messages.response }, fields, { err }));
59
62
  return toImapResponseError(err);
60
63
  }
61
64
  serverLogger.error(Object.assign({ msg: messages.fault }, fields, { err }));
62
- return err;
65
+ return faultResponseError();
63
66
  };
64
67
 
65
68
  // Wires the two legs together once imap-core hands over the client socket
@@ -30,4 +30,17 @@ function toImapResponseError(err) {
30
30
  return error;
31
31
  }
32
32
 
33
- module.exports = { isImapResponseError, toImapResponseError };
33
+ /**
34
+ * The response an internal proxy fault is answered with. The fault's own text (an upstream or a
35
+ * Redis error, a configuration problem) belongs in the log and not on the wire: a client that has
36
+ * not logged in is told that the service is temporarily unavailable, with RFC 5530's code for it.
37
+ *
38
+ * @returns {Error} A new error carrying the response line to send
39
+ */
40
+ function faultResponseError() {
41
+ let error = new Error('[UNAVAILABLE] Temporary failure, try again later');
42
+ error.response = 'NO';
43
+ return error;
44
+ }
45
+
46
+ module.exports = { isImapResponseError, toImapResponseError, faultResponseError };