emailengine-app 2.89.0 → 2.91.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 (120) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +73 -0
  4. package/Dockerfile +7 -3
  5. package/ENVIRONMENT.md +24 -23
  6. package/README.md +1 -1
  7. package/bin/healthcheck.js +1 -1
  8. package/copy-static-files.sh +0 -8
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +1 -4
  11. package/lib/account/field-codec.js +396 -0
  12. package/lib/account-assignment.js +26 -9
  13. package/lib/account.js +196 -462
  14. package/lib/api-routes/account-routes.js +49 -6
  15. package/lib/api-routes/route-metadata.js +5 -2
  16. package/lib/api-routes/submit-routes.js +15 -2
  17. package/lib/api-token-auth.js +342 -274
  18. package/lib/arf-detect.js +174 -149
  19. package/lib/attachment-size.js +29 -0
  20. package/lib/autodetect-imap-settings.js +482 -296
  21. package/lib/consts.js +5 -5
  22. package/lib/db.js +1 -4
  23. package/lib/email-client/base-client.js +907 -780
  24. package/lib/email-client/gmail-client.js +557 -450
  25. package/lib/email-client/imap/cid-parts.js +61 -0
  26. package/lib/email-client/imap/mailbox.js +376 -422
  27. package/lib/email-client/imap/sync-operations.js +239 -178
  28. package/lib/email-client/imap-client.js +5 -5
  29. package/lib/email-client/message-builder.js +4 -5
  30. package/lib/email-client/new-message-steps.js +168 -2
  31. package/lib/email-client/outlook/graph-message.js +266 -0
  32. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  33. package/lib/email-client/outlook-client.js +652 -808
  34. package/lib/get-raw-email.js +338 -232
  35. package/lib/get-secret.js +1 -4
  36. package/lib/imapproxy/imap-server.js +5 -5
  37. package/lib/license-subscription.js +60 -0
  38. package/lib/load-env.js +48 -0
  39. package/lib/logger-consts.js +37 -1
  40. package/lib/logger.js +1 -4
  41. package/lib/mail-probe.js +157 -0
  42. package/lib/mcp/tools.js +244 -207
  43. package/lib/metric-values.js +76 -0
  44. package/lib/metrics.js +320 -0
  45. package/lib/oauth/gmail.js +39 -120
  46. package/lib/oauth/http-request.js +195 -0
  47. package/lib/oauth/mail-ru.js +33 -60
  48. package/lib/oauth/outlook.js +37 -137
  49. package/lib/oauth/pubsub/google.js +176 -117
  50. package/lib/oauth2-apps.js +440 -463
  51. package/lib/openapi/build-document.js +10 -10
  52. package/lib/read-env-value.js +31 -7
  53. package/lib/redis-backend-warnings.js +70 -0
  54. package/lib/route-descriptors.js +78 -0
  55. package/lib/schemas.js +10 -1
  56. package/lib/sentry-integrations.js +299 -0
  57. package/lib/sentry.js +75 -27
  58. package/lib/sso-routes.js +249 -0
  59. package/lib/sso.js +29 -6
  60. package/lib/tools.js +17 -28
  61. package/lib/ui-routes/account-edit-form.js +198 -0
  62. package/lib/ui-routes/account-page.js +241 -0
  63. package/lib/ui-routes/account-routes.js +46 -349
  64. package/lib/ui-routes/account-setup.js +1 -1
  65. package/lib/ui-routes/auth-routes.js +10 -10
  66. package/lib/ui-routes/provider-signin.js +187 -0
  67. package/lib/ui-routes/route-helpers.js +1 -1
  68. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  69. package/lib/ui-view-context.js +328 -0
  70. package/lib/utils/public-suffix.js +22 -101
  71. package/lib/web-safe-html.js +20 -7
  72. package/lib/worker-metrics.js +82 -0
  73. package/list-generate.js +2 -5
  74. package/package.json +28 -24
  75. package/sbom.json +360 -1030
  76. package/scripts/refresh-test-tokens.js +1 -1
  77. package/server.js +400 -677
  78. package/static/css/flyonui.css +1 -1
  79. package/static/css/public.css +55 -1
  80. package/static/css/src/app.tailwind.css +18 -0
  81. package/static/js/ee-client.js +2619 -645
  82. package/static/js/ui.js +12 -2
  83. package/static/licenses.html +224 -764
  84. package/translations/de.mo +0 -0
  85. package/translations/de.po +429 -390
  86. package/translations/en.mo +0 -0
  87. package/translations/en.po +342 -257
  88. package/translations/es.mo +0 -0
  89. package/translations/es.po +440 -395
  90. package/translations/et.mo +0 -0
  91. package/translations/et.po +425 -375
  92. package/translations/fr.mo +0 -0
  93. package/translations/fr.po +425 -383
  94. package/translations/it.mo +0 -0
  95. package/translations/it.po +441 -394
  96. package/translations/ja.mo +0 -0
  97. package/translations/ja.po +408 -335
  98. package/translations/messages.pot +188 -130
  99. package/translations/nl.mo +0 -0
  100. package/translations/nl.po +419 -382
  101. package/translations/pl.mo +0 -0
  102. package/translations/pl.po +425 -379
  103. package/translations/sv.mo +0 -0
  104. package/translations/sv.po +440 -388
  105. package/translations/tr.mo +0 -0
  106. package/translations/tr.po +441 -387
  107. package/views/account-identity-error.hbs +1 -1
  108. package/views/account-workspace-error.hbs +2 -2
  109. package/views/accounts/browse.hbs +19 -1
  110. package/views/accounts/register/imap-server.hbs +22 -7
  111. package/views/accounts/register/imap.hbs +3 -0
  112. package/views/accounts/register/index.hbs +1 -27
  113. package/views/accounts/register/provider-signin.hbs +58 -0
  114. package/views/oauth-scope-error.hbs +1 -1
  115. package/views/partials/provider_signin_button.hbs +30 -0
  116. package/views/queues/index.hbs +1 -1
  117. package/views/redirect.hbs +1 -1
  118. package/views/unsubscribe.hbs +6 -6
  119. package/workers/api.js +20 -451
  120. package/data/public_suffix_list.dat +0 -16698
@@ -17,13 +17,13 @@ const { redis } = require('../db');
17
17
  const getSecret = require('../get-secret');
18
18
  const capa = require('../capa');
19
19
  const { Account, authFailureDisabledAt, isOperatorDisabled } = require('../account');
20
- const { formatGmailWatch } = require('../account/account-state');
21
20
  const { SPECIAL_USE_PATH_FIELDS } = require('./special-use-paths');
22
- const { imapMaxIdleTimeFormSchema, imapMaxIdleTimeFormValue, applyImapMaxIdleTimeForm } = require('./imap-idle-field');
23
- const { securityFormFields, securityFormValues, applySecurityForm } = require('./connection-security-form');
21
+ const { imapMaxIdleTimeFormSchema, imapMaxIdleTimeFormValue } = require('./imap-idle-field');
22
+ const { securityFormFields, securityFormValues } = require('./connection-security-form');
24
23
 
25
24
  const { Gateway } = require('../gateway');
26
- const { autodetectImapSettings, resolveAppPassword, getAppPassword } = require('../autodetect-imap-settings');
25
+ const { resolveAppPassword, getAppPassword } = require('../autodetect-imap-settings');
26
+ const { listListedApps, renderProviderSignIn, microsoftSignInNotice, discoverServerSettings } = require('./provider-signin');
27
27
  const { atomicIncrement } = require('../redis-operations');
28
28
  const { OAUTH_REDIRECT_FORM_DIRECTIVES } = require('../security-headers');
29
29
  const { oauth2Apps, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
@@ -55,16 +55,14 @@ const {
55
55
  adminUrl,
56
56
  accountSuggestions,
57
57
  isClientError,
58
- closedAfterConnectMessage,
59
58
  windowedPageLinks
60
59
  } = require('./route-helpers');
61
- const { parseCustomHeaders } = require('./form-lists');
62
- const { webhooks: Webhooks } = require('../webhooks');
63
60
  const { accountQueueSummary } = require('../queue-browser');
64
- const { describeEffectiveRouting, isDeliverableRoute } = require('../webhook-routing');
65
61
  const { matchesExpectedIdentity, resolveExpectedIdentity } = require('../account/expected-identity');
66
62
  const { OAUTH_NONCE_PATTERN } = require('../oauth/state');
67
63
  const { completeAccountSetup } = require('./account-setup');
64
+ const { buildAccountEditUpdates } = require('./account-edit-form');
65
+ const { translateConnectionErrors, describeSmtpAuthMechanisms, buildGmailWatchView, buildAccountAlert, loadWebhookRouting } = require('./account-page');
68
66
 
69
67
  const { REDIS_PREFIX, DEFAULT_PAGE_SIZE, NONCE_BYTES, MAX_FORM_TTL, MAX_FORM_PROBE_ATTEMPTS } = consts;
70
68
 
@@ -204,13 +202,13 @@ async function accountFormHandler(request, h) {
204
202
  // Generate the url that will be used for the consent dialog.
205
203
 
206
204
  let requestPayload = {
207
- state: `account:add:${nonce}`
205
+ state: `account:add:${nonce}`,
206
+ // Prefills the provider's sign-in form. Falls back to the address the visitor typed before
207
+ // the sign-in page offered this application: only a hint, never stored, so it needs no
208
+ // signature. The providers' clients skip an empty one.
209
+ email: accountData.email || request.payload.loginHint
208
210
  };
209
211
 
210
- if (accountData.email) {
211
- requestPayload.email = accountData.email;
212
- }
213
-
214
212
  // Service providers use client_credentials - no interactive authorization
215
213
  if (SERVICE_ACCOUNT_PROVIDERS.has(oAuth2Client.provider)) {
216
214
  throw Boom.badRequest('Application-only OAuth providers do not support interactive authorization');
@@ -235,7 +233,11 @@ async function accountFormHandler(request, h) {
235
233
  // editable hint and mark it read-only. Cosmetic - the endpoints below enforce it.
236
234
  email: expectedEmail || data.email,
237
235
  emailPinned: !!expectedEmail,
238
- name: data.name
236
+ name: data.name,
237
+ // Reached through a setup link minted for IMAP (`type=imap` on the GET) rather than
238
+ // through the provider picker: the visitor was never offered a choice, and is not
239
+ // sent to one when autodiscovery recognizes an OAuth2 provider
240
+ skipSignIn: request.method === 'get'
239
241
  }
240
242
  },
241
243
  {
@@ -251,7 +253,10 @@ const firstPageSchema = Joi.object({
251
253
  ...signedBlobFields,
252
254
  name: Joi.string().empty('').max(256).example('John Smith').description('Account Name'),
253
255
  email: Joi.string().email().required().example('user@example.com').label('Email').description('Your account email'),
254
- password: Joi.string().max(1024).min(1).required().example('secret').label('Password').description('Your account password')
256
+ password: Joi.string().max(1024).min(1).required().example('secret').label('Password').description('Your account password'),
257
+ // Skips the OAuth2 sign-in page: the setup link was minted for IMAP, or the visitor was already
258
+ // offered the sign-in and chose IMAP. Client-set, and all it chooses is that page.
259
+ skipSignIn: formBoolean().default(false)
255
260
  });
256
261
 
257
262
  // Shared IMAP/SMTP connection fields for the hosted form's /imap/test and /imap/server routes, so the
@@ -715,7 +720,7 @@ function registerPostAccountsNew(server) {
715
720
  url.searchParams.append('sig', signature);
716
721
  }
717
722
 
718
- let oauth2apps = (await oauth2Apps.list(0, 100)).apps.filter(app => app.includeInListing);
723
+ let oauth2apps = await listListedApps();
719
724
 
720
725
  if (!oauth2apps.length) {
721
726
  url.searchParams.append('type', 'imap');
@@ -776,10 +781,7 @@ function registerGetHostedAccountsNew(server) {
776
781
  // throws if check fails
777
782
  await parseSignedFormData(redis, request.query, request.app.gt);
778
783
 
779
- let oauth2apps = (await oauth2Apps.list(0, 100)).apps.filter(app => app.includeInListing);
780
- oauth2apps.forEach(app => {
781
- app.providerData = oauth2ProviderData(app.provider, app.cloud);
782
- });
784
+ let oauth2apps = await listListedApps();
783
785
 
784
786
  return h.view(
785
787
  'accounts/register/index',
@@ -859,7 +861,8 @@ function registerPostHostedAccountsNew(server) {
859
861
  .example('imap')
860
862
  .description(
861
863
  'Display the form for the specified account type (either "imap" or an OAuth2 app ID) instead of allowing the user to choose'
862
- )
864
+ ),
865
+ loginHint: Joi.string().email().empty('').max(256).description('Address to prefill on the OAuth2 provider sign-in form')
863
866
  })
864
867
  }
865
868
  }
@@ -883,18 +886,7 @@ function registerPostHostedImap(server) {
883
886
  return renderIdentityError(request, h, expectedEmail, request.payload.email);
884
887
  }
885
888
 
886
- let serverSettings;
887
- try {
888
- // The password the user just typed is passed along because hosted Exchange refuses
889
- // to answer autodiscovery anonymously; it only ever reaches the autodiscovery host
890
- // named by the address domain's own DNS, and only after that host has asked for it
891
- serverSettings = await autodetectImapSettings(request.payload.email, request.app.gt, {
892
- user: request.payload.email,
893
- pass: request.payload.password
894
- });
895
- } catch (err) {
896
- request.logger.debug({ msg: 'Failed to resolve email server settings', email: request.payload.email, err });
897
- }
889
+ const serverSettings = await discoverServerSettings(request, data);
898
890
 
899
891
  let values = Object.assign(
900
892
  {
@@ -923,6 +915,11 @@ function registerPostHostedImap(server) {
923
915
  setCachedAppPasswordHint(request.payload.email.split('@').pop().trim().toLowerCase(), serverSettings.appPassword);
924
916
  }
925
917
 
918
+ const signIn = await renderProviderSignIn(request, h, serverSettings, values, data.n);
919
+ if (signIn.response) {
920
+ return signIn.response;
921
+ }
922
+
926
923
  // Nothing is left for the user to fill in: the settings page would auto-verify what is
927
924
  // already there and wait for a click. hasCompleteServerSettings() (above, beside
928
925
  // connectionFields) is what both that auto-verify and the skip below agree on.
@@ -955,7 +952,8 @@ function registerPostHostedImap(server) {
955
952
  // page says why rather than looking like a form that forgot its defaults
956
953
  autodetectFailed: !serverSettings,
957
954
  autodetectDomain: request.payload.email.split('@').pop(),
958
- autoTest: settingsComplete
955
+ autoTest: settingsComplete,
956
+ signInNotice: await microsoftSignInNotice(values, signIn.apps)
959
957
  },
960
958
  {
961
959
  layout: 'public'
@@ -983,7 +981,7 @@ function registerPostHostedImap(server) {
983
981
  });
984
982
  }
985
983
 
986
- await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't set up account. Try again.") });
984
+ await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't set up your account. Try again.") });
987
985
  request.logger.debug({ msg: 'Failed to process account', err });
988
986
 
989
987
  // Repopulate the form (crucially the signed data/sig blob) from what was submitted;
@@ -1064,86 +1062,7 @@ function registerPostHostedImapTest(server) {
1064
1062
  request.logger.child({ action: 'verify-account' })
1065
1063
  );
1066
1064
 
1067
- if (verifyResult) {
1068
- if (verifyResult.imap && verifyResult.imap.error && verifyResult.imap.code) {
1069
- // The same translation the SMTP branch below does for its codes: the raw
1070
- // socket or ImapFlow error text is not something the person at the form
1071
- // can act on. Closed-after-connect keeps the TLS hint the account state
1072
- // badge shows for it, because a wrong port/TLS pairing is the usual cause.
1073
- switch (verifyResult.imap.code) {
1074
- case 'ENOTFOUND':
1075
- case 'EAI_AGAIN':
1076
- verifyResult.imap.error = request.app.gt.gettext('Server hostname was not found');
1077
- break;
1078
- case 'AUTHENTICATIONFAILED':
1079
- verifyResult.imap.error = request.app.gt.gettext('Invalid username or password');
1080
- break;
1081
- case 'ETIMEDOUT':
1082
- case 'ETIMEOUT':
1083
- case 'GREETING_TIMEOUT':
1084
- verifyResult.imap.error = request.app.gt.gettext('Connection timed out');
1085
- break;
1086
- case 'ECONNREFUSED':
1087
- case 'ECONNRESET':
1088
- case 'EHOSTUNREACH':
1089
- case 'ENETUNREACH':
1090
- verifyResult.imap.error = request.app.gt.gettext('Could not connect to server');
1091
- break;
1092
- case 'ClosedAfterConnectTLS':
1093
- case 'ClosedAfterConnectText':
1094
- verifyResult.imap.error = closedAfterConnectMessage(verifyResult.imap.code, request.app.gt);
1095
- break;
1096
- case 'EPROTO':
1097
- case 'ERR_TLS_CERT_ALTNAME_INVALID':
1098
- case 'ERR_SSL_WRONG_VERSION_NUMBER':
1099
- case 'CERT_HAS_EXPIRED':
1100
- case 'DEPTH_ZERO_SELF_SIGNED_CERT':
1101
- case 'SELF_SIGNED_CERT_IN_CHAIN':
1102
- case 'UNABLE_TO_VERIFY_LEAF_SIGNATURE':
1103
- verifyResult.imap.error = request.app.gt.gettext('TLS protocol error');
1104
- break;
1105
- default:
1106
- if (/openssl|ssl routines/i.test(verifyResult.imap.error)) {
1107
- verifyResult.imap.error = request.app.gt.gettext('TLS protocol error');
1108
- }
1109
- break;
1110
- }
1111
- }
1112
-
1113
- if (verifyResult.smtp && verifyResult.smtp.error && verifyResult.smtp.code) {
1114
- switch (verifyResult.smtp.code) {
1115
- case 'EDNS':
1116
- verifyResult.smtp.error = request.app.gt.gettext('Server hostname was not found');
1117
- break;
1118
- case 'EAUTH':
1119
- verifyResult.smtp.error = request.app.gt.gettext('Invalid username or password');
1120
- break;
1121
- case 'ENOAUTH':
1122
- verifyResult.smtp.error = request.app.gt.gettext('Authentication credentials were not provided');
1123
- break;
1124
- case 'EOAUTH2':
1125
- verifyResult.smtp.error = request.app.gt.gettext('OAuth2 authentication failed');
1126
- break;
1127
- case 'ETLS':
1128
- verifyResult.smtp.error = request.app.gt.gettext('TLS protocol error');
1129
- break;
1130
- case 'ESOCKET':
1131
- if (/openssl/.test(verifyResult.smtp.error)) {
1132
- verifyResult.smtp.error = request.app.gt.gettext('TLS protocol error');
1133
- }
1134
- break;
1135
- case 'ETIMEDOUT':
1136
- verifyResult.smtp.error = request.app.gt.gettext('Connection timed out');
1137
- break;
1138
- case 'ECONNECTION':
1139
- verifyResult.smtp.error = request.app.gt.gettext('Could not connect to server');
1140
- break;
1141
- case 'EPROTOCOL':
1142
- verifyResult.smtp.error = request.app.gt.gettext('Unexpected server response');
1143
- break;
1144
- }
1145
- }
1146
- }
1065
+ translateConnectionErrors(verifyResult, request.app.gt);
1147
1066
 
1148
1067
  return verifyResult;
1149
1068
  } catch (err) {
@@ -1215,7 +1134,8 @@ function registerPostHostedImapSettings(server) {
1215
1134
  checkFailed: request.query.checkFailed,
1216
1135
  // The check just failed, so do not repeat it on load: the page opens on the fields
1217
1136
  // to correct rather than on a spinner about to give the same answer.
1218
- autoTest: false
1137
+ autoTest: false,
1138
+ signInNotice: await microsoftSignInNotice(values)
1219
1139
  },
1220
1140
  {
1221
1141
  layout: 'public'
@@ -1340,7 +1260,7 @@ function registerPostHostedImapServer(server, args) {
1340
1260
  });
1341
1261
  }
1342
1262
 
1343
- await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't set up account. Try again.") });
1263
+ await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't set up your account. Try again.") });
1344
1264
  request.logger.debug({ msg: 'Failed to process account', err });
1345
1265
 
1346
1266
  // Rebuild the re-render values from the SAME schema that just validated the submission
@@ -1359,7 +1279,8 @@ function registerPostHostedImapServer(server, args) {
1359
1279
  {
1360
1280
  pageTitleFull: request.app.gt.gettext('Email Account Setup'),
1361
1281
  errors,
1362
- values
1282
+ values,
1283
+ signInNotice: await microsoftSignInNotice(values)
1363
1284
  },
1364
1285
  {
1365
1286
  layout: 'public'
@@ -1448,52 +1369,7 @@ function registerGetAccountsByAccount(server, args) {
1448
1369
  }
1449
1370
 
1450
1371
  if (accountData.smtpServerEhlo && accountData.smtpServerEhlo.length) {
1451
- let smtpAuthMechanisms = [];
1452
- for (let i = accountData.smtpServerEhlo.length - 1; i >= 0; i--) {
1453
- let entry = accountData.smtpServerEhlo[i];
1454
- if (/^auth\b/i.test(entry)) {
1455
- let authEntries = entry.split(/\s+/).slice(1);
1456
- if (authEntries.length) {
1457
- smtpAuthMechanisms = smtpAuthMechanisms.concat(authEntries);
1458
- }
1459
- accountData.smtpServerEhlo.splice(i, 1);
1460
- }
1461
- }
1462
- accountData.smtpAuthMechanisms = Array.from(new Set(smtpAuthMechanisms));
1463
-
1464
- for (let i = accountData.smtpAuthMechanisms.length - 1; i >= 0; i--) {
1465
- let entry = accountData.smtpAuthMechanisms[i];
1466
- switch (entry.toUpperCase()) {
1467
- case 'LOGIN':
1468
- accountData.smtpAuthMechanisms[i] = {
1469
- auth: entry,
1470
- rfc: 'draft-murchison-sasl-login',
1471
- url: 'https://datatracker.ietf.org/doc/html/draft-murchison-sasl-login'
1472
- };
1473
- break;
1474
- case 'PLAIN':
1475
- accountData.smtpAuthMechanisms[i] = {
1476
- auth: entry,
1477
- rfc: 'RFC4616',
1478
- url: 'https://www.rfc-editor.org/rfc/rfc4616.html'
1479
- };
1480
- break;
1481
- case 'XOAUTH2':
1482
- accountData.smtpAuthMechanisms[i] = {
1483
- auth: entry,
1484
- rfc: 'xoauth2-protocol',
1485
- url: 'https://developers.google.com/gmail/imap/xoauth2-protocol#smtp_protocol_exchange'
1486
- };
1487
- break;
1488
- case 'OAUTHBEARER':
1489
- accountData.smtpAuthMechanisms[i] = {
1490
- auth: entry,
1491
- rfc: 'RFC7628',
1492
- url: 'https://www.rfc-editor.org/rfc/rfc7628.html'
1493
- };
1494
- break;
1495
- }
1496
- }
1372
+ accountData.smtpAuthMechanisms = describeSmtpAuthMechanisms(accountData.smtpServerEhlo);
1497
1373
  }
1498
1374
 
1499
1375
  // Stored entries outlive the logging switch - turning logging off does not clear what
@@ -1512,37 +1388,7 @@ function registerGetAccountsByAccount(server, args) {
1512
1388
  accountData.path = null;
1513
1389
  }
1514
1390
 
1515
- // State comes from the same derivation the API reports, so the page and the response
1516
- // cannot disagree about whether push is working. The reason and the failed request stay
1517
- // here and out of the API: both are text the provider wrote, and this page is behind an
1518
- // admin session. NB! a watch that is still armed but whose last renewal failed now
1519
- // reads Failed rather than Active - it used to show the expiry alone and hide the
1520
- // failure in a tooltip, which said nothing was wrong right up to the day it lapsed
1521
- let watchState = formatGmailWatch(accountData);
1522
- let gmailWatch = watchState
1523
- ? {
1524
- lastCheckStr: watchState.lastCheck,
1525
- expiresStr: watchState.expires || false,
1526
- active: watchState.state === 'active',
1527
- stateLabel: { active: 'Active', error: 'Failed', expired: 'Expired' }[watchState.state] || 'Unknown',
1528
- // The reason and the failed request are read straight off the record here and
1529
- // deliberately absent from the shared derivation: both carry text the
1530
- // provider wrote, including the operator's own Pub/Sub topic path, and this
1531
- // page is behind an admin session while the API field is not
1532
- error: accountData.watchFailure ? accountData.watchFailure.err || 'Failed to set up Gmail pubsub watch' : false
1533
- }
1534
- : false;
1535
-
1536
- // Not "watchFailure truthy means gmailWatch is": the derivation reports nothing for an
1537
- // account whose application has no Pub/Sub app, whatever record a previous one left
1538
- if (gmailWatch && accountData.watchFailure && accountData.watchFailure.req) {
1539
- gmailWatch.request = {
1540
- url: accountData.watchFailure.req.url,
1541
- status: accountData.watchFailure.req.status,
1542
- contentType: accountData.watchFailure.req.contentType,
1543
- response: accountData.watchFailure.req.response
1544
- };
1545
- }
1391
+ let gmailWatch = buildGmailWatchView(accountData);
1546
1392
 
1547
1393
  const canReadMail = (accountData.imap || accountData.oauth2) && !(accountData.imap && accountData.imap.disabled) && !DISABLE_MESSAGE_BROWSER;
1548
1394
 
@@ -1553,56 +1399,9 @@ function registerGetAccountsByAccount(server, args) {
1553
1399
  // API call.
1554
1400
  const disabledByAuthFailureAt = authFailureDisabledAt(accountData);
1555
1401
 
1556
- // Top-of-page alert for the account's primary problem, so a broken account is
1557
- // impossible to miss. Gated on the effective connection state (stateLabel.type) so a
1558
- // recovered account never shows a stale error; a stalled sync is surfaced separately
1559
- // because the account can otherwise be connected.
1560
- let accountAlert = null;
1561
- if (disabledByAuthFailureAt) {
1562
- // Ahead of the state alert: a parked account is not connecting at all, so why it
1563
- // was switched off is the more actionable of the two.
1564
- accountAlert = {
1565
- title: 'Syncing was switched off',
1566
- message:
1567
- 'EmailEngine stopped connecting this account after repeated authentication failures. Re-authenticating it turns syncing back on; "Resume syncing" retries with the stored credentials.',
1568
- timeLabel: 'Switched off',
1569
- time: disabledByAuthFailureAt
1570
- };
1571
- } else if (accountData.stateLabel && accountData.stateLabel.type === 'error') {
1572
- accountAlert = {
1573
- title: accountData.stateLabel.name,
1574
- message: accountData.stateLabel.error
1575
- };
1576
- } else if (accountData.syncError) {
1577
- accountAlert = {
1578
- title: 'Sync stalled',
1579
- path: accountData.syncError.path,
1580
- message: (accountData.syncError.error && (accountData.syncError.error.responseText || accountData.syncError.error.error)) || null
1581
- };
1582
- }
1402
+ let accountAlert = buildAccountAlert(accountData, disabledByAuthFailureAt);
1583
1403
 
1584
- const [webhookSettings, webhookRoutesList] = await Promise.all([
1585
- settings.getMulti('webhooksEnabled', 'webhooks', 'webhookEvents', 'inboxNewOnly', 'webhooksCustomHeaders'),
1586
- Webhooks.list(0, 1000)
1587
- ]);
1588
-
1589
- // The listing carries route metadata only, but the worker's delivery gate also
1590
- // requires a filter script, so the card needs the filter-presence markers for the
1591
- // routes it is about to present as delivering
1592
- const routeFilterInfo = await Webhooks.getFilterInfo(webhookRoutesList.webhooks.filter(isDeliverableRoute).map(route => route.id));
1593
-
1594
- const webhookRouting = describeEffectiveRouting({
1595
- webhooksEnabled: webhookSettings.webhooksEnabled,
1596
- globalWebhooks: webhookSettings.webhooks,
1597
- accountWebhooks: accountData.webhooks,
1598
- webhookEvents: webhookSettings.webhookEvents,
1599
- inboxNewOnly: webhookSettings.inboxNewOnly,
1600
- globalCustomHeaders: webhookSettings.webhooksCustomHeaders,
1601
- accountCustomHeaders: accountData.webhooksCustomHeaders,
1602
- // Non-deliverable routes were not probed; their hasFilter stays undefined, which
1603
- // describeEffectiveRouting() reads as "unknown" (and filters them out anyway)
1604
- routes: webhookRoutesList.webhooks.map(route => Object.assign({}, route, { hasFilter: routeFilterInfo.get(route.id) }))
1605
- });
1404
+ const webhookRouting = await loadWebhookRouting(accountData);
1606
1405
 
1607
1406
  return h.view(
1608
1407
  'accounts/account',
@@ -2021,7 +1820,8 @@ function registerGetAccountsBrowse(server, args) {
2021
1820
  request.cookieAuth.clear();
2022
1821
  }
2023
1822
  await request.flash({ type: 'info', message: `Sign in again to continue.` });
2024
- return h.redirect('/admin/login?next=' + encodeURIComponent(`/admin/accounts/${encodeURIComponent(request.params.account)}/browse`));
1823
+ // the query string carries a deep link (?message=), which has to survive the sign-in
1824
+ return h.redirect('/admin/login?next=' + encodeURIComponent(`${request.url.pathname}${request.url.search}`));
2025
1825
  }
2026
1826
 
2027
1827
  let accountObject = new Account({ redis, account: request.params.account, call, secret: await getSecret() });
@@ -2191,110 +1991,7 @@ function registerPostAccountsEdit(server, args) {
2191
1991
 
2192
1992
  let oldData = await accountObject.loadAccountData();
2193
1993
 
2194
- let updates = {
2195
- account: request.params.account,
2196
- name: request.payload.name || '',
2197
- email: request.payload.email,
2198
- // Empty clears the pin (Account.update hdel's it), which is the only way an operator
2199
- // can unblock a legitimate mailbox migration on a pinned account.
2200
- expectedEmail: request.payload.expectedEmail || null,
2201
- proxy: request.payload.proxy,
2202
- smtpEhloName: request.payload.smtpEhloName,
2203
- webhooks: request.payload.webhooks
2204
- };
2205
-
2206
- // Absent only from a request that did not render the field, keep the stored headers then
2207
- if (typeof request.payload.customHeaders === 'string') {
2208
- updates.webhooksCustomHeaders = parseCustomHeaders(request.payload.customHeaders);
2209
- }
2210
-
2211
- if (request.payload.imap) {
2212
- let imapTls = (oldData.imap && oldData.imap.tls) || {};
2213
-
2214
- let updateKeys = {};
2215
-
2216
- for (let key of ['host', 'port', 'disabled']) {
2217
- if (`imap_${key}` in request.payload) {
2218
- updateKeys[key] = request.payload[`imap_${key}`];
2219
- }
2220
- }
2221
-
2222
- // The special-use folder overrides. An empty input means "no override" and has to
2223
- // be written as null to unset one, while a field the form never showed must not be
2224
- // written at all: these inputs live inside the IMAP section, which is hidden for an
2225
- // account whose IMAP the operator switched off. The schema therefore allows the
2226
- // empty string instead of defaulting to null - a default is inserted by joi for
2227
- // every key the browser did not send, which made the presence check below always
2228
- // true, so an unrelated save (a rename, a new webhook URL) wiped every override set
2229
- // over PUT /v1/account/{account}. Same presence test imap_auth_user relies on.
2230
- for (const field of SPECIAL_USE_PATH_FIELDS) {
2231
- const payloadKey = `imap_${field.key}`;
2232
- if (!(payloadKey in request.payload)) {
2233
- continue;
2234
- }
2235
- const value = request.payload[payloadKey] || null;
2236
- // Written only when the effective value changes, like the TLS flags below: an
2237
- // untouched save must not add keys, because any imap diff forces a reconnect
2238
- if (value !== ((oldData.imap && oldData.imap[field.key]) || null)) {
2239
- updateKeys[field.key] = value;
2240
- }
2241
- }
2242
-
2243
- applyImapMaxIdleTimeForm(request.payload, oldData.imap, updateKeys);
2244
- if ('imap_auth_user' in request.payload) {
2245
- let imapAuth = Object.assign((oldData.imap && oldData.imap.auth) || {}, { user: request.payload.imap_auth_user });
2246
- if (request.payload.imap_auth_pass) {
2247
- imapAuth.pass = request.payload.imap_auth_pass;
2248
- }
2249
- updateKeys.auth = imapAuth;
2250
- updateKeys.secure = request.payload.imap_secure;
2251
- // The connection settings section is hidden for OAuth2 and disabled
2252
- // accounts, so like `secure` these only apply when it was submitted.
2253
- // Written only when the effective state changes - an untouched form
2254
- // save must not add new keys, as any imap diff forces a reconnect
2255
- applySecurityForm(request.payload, 'imap', oldData.imap, updateKeys, imapTls);
2256
- if (request.payload.imap_disableIMAP4rev2 !== !!(oldData.imap && oldData.imap.disableIMAP4rev2)) {
2257
- updateKeys.disableIMAP4rev2 = request.payload.imap_disableIMAP4rev2;
2258
- }
2259
- }
2260
-
2261
- // skipped while empty and absent from the stored account for the same
2262
- // reason as above - a no-op save must not introduce a tls:{} key
2263
- if (Object.keys(imapTls).length) {
2264
- updateKeys.tls = imapTls;
2265
- }
2266
-
2267
- updates.imap = Object.assign(oldData.imap || {}, updateKeys);
2268
-
2269
- if (request.payload.imap_resyncDelay) {
2270
- updates.imap.resyncDelay = request.payload.imap_resyncDelay;
2271
- }
2272
- }
2273
-
2274
- if (request.payload.smtp) {
2275
- let smtpAuth = Object.assign((oldData.smtp && oldData.smtp.auth) || {}, { user: request.payload.smtp_auth_user });
2276
- let smtpTls = (oldData.smtp && oldData.smtp.tls) || {};
2277
-
2278
- if (request.payload.smtp_auth_pass) {
2279
- smtpAuth.pass = request.payload.smtp_auth_pass;
2280
- }
2281
-
2282
- updates.smtp = Object.assign(oldData.smtp || {}, {
2283
- host: request.payload.smtp_host,
2284
- port: request.payload.smtp_port,
2285
- secure: request.payload.smtp_secure,
2286
- auth: smtpAuth
2287
- });
2288
-
2289
- // written only when the effective state changes, and the tls object is
2290
- // skipped while empty - same as the IMAP flags, a no-op save must not
2291
- // modify the stored account
2292
- applySecurityForm(request.payload, 'smtp', oldData.smtp, updates.smtp, smtpTls);
2293
-
2294
- if (Object.keys(smtpTls).length) {
2295
- updates.smtp.tls = smtpTls;
2296
- }
2297
- }
1994
+ let updates = buildAccountEditUpdates(request.params.account, request.payload, oldData);
2298
1995
 
2299
1996
  await accountObject.update(updates);
2300
1997
 
@@ -65,7 +65,7 @@ async function completeAccountSetup(request, { accountObject, accountData, nonce
65
65
  // A Redis failure is not a consumed nonce. Report it as a retryable server error
66
66
  // instead of misdiagnosing a valid setup URL as invalid or expired.
67
67
  request.logger.error({ msg: 'Failed to claim nonce for an account form request', err });
68
- throw Boom.boomify(new Error(gt.gettext('Temporary error, please try again')), { statusCode: 500 });
68
+ throw Boom.boomify(new Error(gt.gettext('A temporary error occurred. Try again.')), { statusCode: 500 });
69
69
  }
70
70
  if (!claimed) {
71
71
  // SET NX returned null: the nonce key already exists, so this URL was already used.
@@ -15,12 +15,12 @@ const { parentPort } = require('worker_threads');
15
15
  const pbkdf2 = require('../pbkdf2-phc');
16
16
  const { verifyAdminPassword, verifyCurrentPassword, setAdminPassword } = require('../admin-password');
17
17
  const { generateTotpSeed, verifyTotp, generateTotpUrl, generateTotpQrDataUrl } = require('../totp');
18
- const {
19
- generateRegistrationOptions,
20
- verifyRegistrationResponse,
21
- generateAuthenticationOptions,
22
- verifyAuthenticationResponse
23
- } = require('@simplewebauthn/server');
18
+ // Loaded on the first passkey request rather than with the admin UI: the library and its X.509 and
19
+ // ASN.1 dependencies are about 4.6 MB of heap and 70 ms of startup in the API worker, and they add
20
+ // tslib's helpers to globalThis and reflect-metadata's methods to Reflect, all for a feature many
21
+ // instances never use. A literal require(), so pkg still bundles it.
22
+ let webauthnModule;
23
+ const webauthn = () => (webauthnModule = webauthnModule || require('@simplewebauthn/server'));
24
24
 
25
25
  // The public key algorithms a passkey may be registered with: ES256 and RS256, which every
26
26
  // authenticator offers. The library's own list starts with EdDSA, and an Ed25519 passkey fails at
@@ -1105,7 +1105,7 @@ function registerPostAccountPasskeysRegisterOptions(server) {
1105
1105
  return h.response({ error: verified.message }).code(verified.statusCode);
1106
1106
  }
1107
1107
 
1108
- let options = await generateRegistrationOptions({
1108
+ let options = await webauthn().generateRegistrationOptions({
1109
1109
  rpName: 'EmailEngine',
1110
1110
  rpID: rpId,
1111
1111
  userName: user,
@@ -1185,7 +1185,7 @@ function registerPostAccountPasskeysRegisterVerify(server) {
1185
1185
  return h.response({ error: 'Challenge expired or invalid. Please try again.' }).code(400);
1186
1186
  }
1187
1187
 
1188
- let verification = await verifyRegistrationResponse({
1188
+ let verification = await webauthn().verifyRegistrationResponse({
1189
1189
  response: request.payload.credential,
1190
1190
  expectedChallenge: challenge,
1191
1191
  expectedOrigin: origin,
@@ -1331,7 +1331,7 @@ function registerPostPasskeyAuthOptions(server) {
1331
1331
  return h.response({ error: 'no_passkeys' }).code(400);
1332
1332
  }
1333
1333
 
1334
- let options = await generateAuthenticationOptions({
1334
+ let options = await webauthn().generateAuthenticationOptions({
1335
1335
  rpID: rpId,
1336
1336
  allowCredentials: allCredentials.map(c => ({
1337
1337
  id: c.id,
@@ -1405,7 +1405,7 @@ function registerPostPasskeyAuthVerify(server) {
1405
1405
  return h.response({ success: false, error: 'Authentication failed' }).code(400);
1406
1406
  }
1407
1407
 
1408
- let verification = await verifyAuthenticationResponse({
1408
+ let verification = await webauthn().verifyAuthenticationResponse({
1409
1409
  response: request.payload.credential,
1410
1410
  expectedChallenge: challenge,
1411
1411
  expectedOrigin: origin,