emailengine-app 2.88.0 → 2.90.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 (79) hide show
  1. package/.ncurc.js +36 -45
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +58 -0
  4. package/Dockerfile +5 -1
  5. package/bin/healthcheck.js +1 -1
  6. package/copy-static-files.sh +0 -8
  7. package/data/google-crawlers.json +1 -1
  8. package/encrypt.js +1 -4
  9. package/lib/account/field-codec.js +396 -0
  10. package/lib/account.js +158 -453
  11. package/lib/api-routes/account-routes.js +42 -6
  12. package/lib/api-routes/route-metadata.js +5 -2
  13. package/lib/api-routes/submit-routes.js +15 -2
  14. package/lib/api-token-auth.js +342 -274
  15. package/lib/arf-detect.js +174 -149
  16. package/lib/attachment-size.js +29 -0
  17. package/lib/autodetect-imap-settings.js +83 -234
  18. package/lib/consts.js +1 -5
  19. package/lib/db.js +1 -4
  20. package/lib/email-client/base-client.js +907 -780
  21. package/lib/email-client/gmail-client.js +557 -450
  22. package/lib/email-client/imap/cid-parts.js +61 -0
  23. package/lib/email-client/imap/mailbox.js +376 -422
  24. package/lib/email-client/imap/sync-operations.js +239 -178
  25. package/lib/email-client/new-message-steps.js +168 -2
  26. package/lib/email-client/outlook/graph-message.js +266 -0
  27. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  28. package/lib/email-client/outlook-client.js +652 -808
  29. package/lib/get-raw-email.js +338 -232
  30. package/lib/get-secret.js +1 -4
  31. package/lib/license-subscription.js +77 -11
  32. package/lib/load-env.js +48 -0
  33. package/lib/logger.js +1 -4
  34. package/lib/mcp/tools.js +244 -207
  35. package/lib/metric-values.js +76 -0
  36. package/lib/metrics.js +320 -0
  37. package/lib/node-version.js +99 -12
  38. package/lib/oauth/gmail.js +39 -120
  39. package/lib/oauth/http-request.js +195 -0
  40. package/lib/oauth/mail-ru.js +24 -58
  41. package/lib/oauth/outlook.js +37 -137
  42. package/lib/oauth/pubsub/google.js +176 -117
  43. package/lib/oauth2-apps.js +440 -463
  44. package/lib/openapi/build-document.js +10 -10
  45. package/lib/read-env-value.js +1 -1
  46. package/lib/route-descriptors.js +78 -0
  47. package/lib/schemas.js +10 -1
  48. package/lib/sentry-integrations.js +299 -0
  49. package/lib/sentry.js +75 -27
  50. package/lib/settings.js +4 -1
  51. package/lib/sso-routes.js +249 -0
  52. package/lib/sso.js +29 -6
  53. package/lib/tools.js +5 -4
  54. package/lib/ui-routes/account-edit-form.js +198 -0
  55. package/lib/ui-routes/account-page.js +241 -0
  56. package/lib/ui-routes/account-routes.js +12 -318
  57. package/lib/ui-routes/auth-routes.js +10 -10
  58. package/lib/ui-routes/dashboard-routes.js +4 -0
  59. package/lib/ui-view-context.js +328 -0
  60. package/lib/utils/public-suffix.js +22 -101
  61. package/lib/web-safe-html.js +70 -13
  62. package/lib/worker-metrics.js +82 -0
  63. package/list-generate.js +57 -23
  64. package/package.json +34 -33
  65. package/sbom.json +380 -1612
  66. package/scripts/refresh-test-tokens.js +1 -1
  67. package/server.js +351 -707
  68. package/static/css/flyonui.css +1 -1
  69. package/static/css/src/app.tailwind.css +18 -0
  70. package/static/js/ee-client.js +2619 -645
  71. package/static/js/ui.js +12 -2
  72. package/static/licenses.html +1055 -969
  73. package/translations/messages.pot +71 -60
  74. package/views/accounts/browse.hbs +19 -1
  75. package/views/dashboard.hbs +9 -0
  76. package/views/upgrade.hbs +25 -0
  77. package/workers/api.js +20 -451
  78. package/data/public_suffix_list.dat +0 -16597
  79. package/lib/net-tos-guard.js +0 -42
@@ -0,0 +1,241 @@
1
+ 'use strict';
2
+
3
+ // Helpers of the account pages and the hosted setup form in lib/ui-routes/account-routes.js, kept apart so they can be
4
+ // tested without registering the routes and so the route module stays inside its size budget.
5
+ // Everything here is pure except loadWebhookRouting(), which reads the settings and routes the
6
+ // account page's webhook card describes.
7
+
8
+ const settings = require('../settings');
9
+ const { webhooks: Webhooks } = require('../webhooks');
10
+ const { describeEffectiveRouting, isDeliverableRoute } = require('../webhook-routing');
11
+ const { formatGmailWatch } = require('../account/account-state');
12
+ const { closedAfterConnectMessage } = require('./route-helpers');
13
+
14
+ // The SASL mechanisms the account page links to a specification, by upper-cased name
15
+ const SMTP_AUTH_INFO = {
16
+ LOGIN: { rfc: 'draft-murchison-sasl-login', url: 'https://datatracker.ietf.org/doc/html/draft-murchison-sasl-login' },
17
+ PLAIN: { rfc: 'RFC4616', url: 'https://www.rfc-editor.org/rfc/rfc4616.html' },
18
+ XOAUTH2: { rfc: 'xoauth2-protocol', url: 'https://developers.google.com/gmail/imap/xoauth2-protocol#smtp_protocol_exchange' },
19
+ OAUTHBEARER: { rfc: 'RFC7628', url: 'https://www.rfc-editor.org/rfc/rfc7628.html' }
20
+ };
21
+
22
+ /**
23
+ * Moves the AUTH lines out of an SMTP server's EHLO extension list and describes the mechanisms
24
+ * they name. The lines are read last to first, a repeated mechanism keeps its first place, and a
25
+ * known one becomes `{ auth, rfc, url }` while an unknown one stays a plain name.
26
+ *
27
+ * @param {string[]} smtpServerEhlo - EHLO extension lines, modified in place
28
+ * @returns {Array<string|Object>} the mechanisms
29
+ */
30
+ function describeSmtpAuthMechanisms(smtpServerEhlo) {
31
+ let smtpAuthMechanisms = [];
32
+ for (let i = smtpServerEhlo.length - 1; i >= 0; i--) {
33
+ let entry = smtpServerEhlo[i];
34
+ if (/^auth\b/i.test(entry)) {
35
+ let authEntries = entry.split(/\s+/).slice(1);
36
+ if (authEntries.length) {
37
+ smtpAuthMechanisms = smtpAuthMechanisms.concat(authEntries);
38
+ }
39
+ smtpServerEhlo.splice(i, 1);
40
+ }
41
+ }
42
+
43
+ return Array.from(new Set(smtpAuthMechanisms)).map(entry => {
44
+ let info = Object.hasOwn(SMTP_AUTH_INFO, entry.toUpperCase()) ? SMTP_AUTH_INFO[entry.toUpperCase()] : null;
45
+ return info ? { auth: entry, rfc: info.rfc, url: info.url } : entry;
46
+ });
47
+ }
48
+
49
+ /**
50
+ * The Gmail watch card of the account page, or false when the account has no watch to report.
51
+ *
52
+ * State comes from the same derivation the API reports, so the page and the response cannot
53
+ * disagree about whether push is working. The reason and the failed request stay here and out of
54
+ * the API: both are text the provider wrote, and this page is behind an admin session. NB! a watch
55
+ * that is still armed but whose last renewal failed now reads Failed rather than Active - it used
56
+ * to show the expiry alone and hide the failure in a tooltip, which said nothing was wrong right
57
+ * up to the day it lapsed
58
+ *
59
+ * @param {Object} accountData - the formatted account record
60
+ * @returns {Object|false}
61
+ */
62
+ function buildGmailWatchView(accountData) {
63
+ let watchState = formatGmailWatch(accountData);
64
+ let gmailWatch = watchState
65
+ ? {
66
+ lastCheckStr: watchState.lastCheck,
67
+ expiresStr: watchState.expires || false,
68
+ active: watchState.state === 'active',
69
+ stateLabel: { active: 'Active', error: 'Failed', expired: 'Expired' }[watchState.state] || 'Unknown',
70
+ // The reason and the failed request are read straight off the record here and
71
+ // deliberately absent from the shared derivation: both carry text the
72
+ // provider wrote, including the operator's own Pub/Sub topic path, and this
73
+ // page is behind an admin session while the API field is not
74
+ error: accountData.watchFailure ? accountData.watchFailure.err || 'Failed to set up Gmail pubsub watch' : false
75
+ }
76
+ : false;
77
+
78
+ // Not "watchFailure truthy means gmailWatch is": the derivation reports nothing for an
79
+ // account whose application has no Pub/Sub app, whatever record a previous one left
80
+ if (gmailWatch && accountData.watchFailure && accountData.watchFailure.req) {
81
+ gmailWatch.request = {
82
+ url: accountData.watchFailure.req.url,
83
+ status: accountData.watchFailure.req.status,
84
+ contentType: accountData.watchFailure.req.contentType,
85
+ response: accountData.watchFailure.req.response
86
+ };
87
+ }
88
+
89
+ return gmailWatch;
90
+ }
91
+
92
+ /**
93
+ * Top-of-page alert for the account's primary problem, so a broken account is impossible to
94
+ * miss. Gated on the effective connection state (stateLabel.type) so a recovered account never
95
+ * shows a stale error; a stalled sync is surfaced separately because the account can otherwise
96
+ * be connected.
97
+ *
98
+ * @param {Object} accountData - the formatted account record
99
+ * @param {string|null} disabledByAuthFailureAt - when the auth-failure safety net parked it
100
+ * @returns {Object|null}
101
+ */
102
+ function buildAccountAlert(accountData, disabledByAuthFailureAt) {
103
+ if (disabledByAuthFailureAt) {
104
+ // Ahead of the state alert: a parked account is not connecting at all, so why it
105
+ // was switched off is the more actionable of the two.
106
+ return {
107
+ title: 'Syncing was switched off',
108
+ message:
109
+ 'EmailEngine stopped connecting this account after repeated authentication failures. Re-authenticating it turns syncing back on; "Resume syncing" retries with the stored credentials.',
110
+ timeLabel: 'Switched off',
111
+ time: disabledByAuthFailureAt
112
+ };
113
+ }
114
+
115
+ if (accountData.stateLabel && accountData.stateLabel.type === 'error') {
116
+ return {
117
+ title: accountData.stateLabel.name,
118
+ message: accountData.stateLabel.error
119
+ };
120
+ }
121
+
122
+ if (accountData.syncError) {
123
+ return {
124
+ title: 'Sync stalled',
125
+ path: accountData.syncError.path,
126
+ message: (accountData.syncError.error && (accountData.syncError.error.responseText || accountData.syncError.error.error)) || null
127
+ };
128
+ }
129
+
130
+ return null;
131
+ }
132
+
133
+ /**
134
+ * The webhook routing card of the account page: where this account's events go.
135
+ *
136
+ * @param {Object} accountData - the formatted account record
137
+ * @returns {Promise<Object>} describeEffectiveRouting() output
138
+ */
139
+ async function loadWebhookRouting(accountData) {
140
+ const [webhookSettings, webhookRoutesList] = await Promise.all([
141
+ settings.getMulti('webhooksEnabled', 'webhooks', 'webhookEvents', 'inboxNewOnly', 'webhooksCustomHeaders'),
142
+ Webhooks.list(0, 1000)
143
+ ]);
144
+
145
+ // The listing carries route metadata only, but the worker's delivery gate also
146
+ // requires a filter script, so the card needs the filter-presence markers for the
147
+ // routes it is about to present as delivering
148
+ const routeFilterInfo = await Webhooks.getFilterInfo(webhookRoutesList.webhooks.filter(isDeliverableRoute).map(route => route.id));
149
+
150
+ return describeEffectiveRouting({
151
+ webhooksEnabled: webhookSettings.webhooksEnabled,
152
+ globalWebhooks: webhookSettings.webhooks,
153
+ accountWebhooks: accountData.webhooks,
154
+ webhookEvents: webhookSettings.webhookEvents,
155
+ inboxNewOnly: webhookSettings.inboxNewOnly,
156
+ globalCustomHeaders: webhookSettings.webhooksCustomHeaders,
157
+ accountCustomHeaders: accountData.webhooksCustomHeaders,
158
+ // Non-deliverable routes were not probed; their hasFilter stays undefined, which
159
+ // describeEffectiveRouting() reads as "unknown" (and filters them out anyway)
160
+ routes: webhookRoutesList.webhooks.map(route => Object.assign({}, route, { hasFilter: routeFilterInfo.get(route.id) }))
161
+ });
162
+ }
163
+
164
+ // The messages the hosted form's connection check shows for an IMAP error code. Built per call
165
+ // with the request's translator, and every message is a literal gettext() call so string
166
+ // extraction finds it. The raw socket or ImapFlow error text is not something the person at the
167
+ // form can act on. Closed-after-connect keeps the TLS hint the account state badge shows for it,
168
+ // because a wrong port/TLS pairing is the usual cause.
169
+ const IMAP_ERROR_MESSAGES = gt => ({
170
+ ENOTFOUND: gt.gettext('Server hostname was not found'),
171
+ EAI_AGAIN: gt.gettext('Server hostname was not found'),
172
+ AUTHENTICATIONFAILED: gt.gettext('Invalid username or password'),
173
+ ETIMEDOUT: gt.gettext('Connection timed out'),
174
+ ETIMEOUT: gt.gettext('Connection timed out'),
175
+ GREETING_TIMEOUT: gt.gettext('Connection timed out'),
176
+ ECONNREFUSED: gt.gettext('Could not connect to server'),
177
+ ECONNRESET: gt.gettext('Could not connect to server'),
178
+ EHOSTUNREACH: gt.gettext('Could not connect to server'),
179
+ ENETUNREACH: gt.gettext('Could not connect to server'),
180
+ ClosedAfterConnectTLS: closedAfterConnectMessage('ClosedAfterConnectTLS', gt),
181
+ ClosedAfterConnectText: closedAfterConnectMessage('ClosedAfterConnectText', gt),
182
+ EPROTO: gt.gettext('TLS protocol error'),
183
+ ERR_TLS_CERT_ALTNAME_INVALID: gt.gettext('TLS protocol error'),
184
+ ERR_SSL_WRONG_VERSION_NUMBER: gt.gettext('TLS protocol error'),
185
+ CERT_HAS_EXPIRED: gt.gettext('TLS protocol error'),
186
+ DEPTH_ZERO_SELF_SIGNED_CERT: gt.gettext('TLS protocol error'),
187
+ SELF_SIGNED_CERT_IN_CHAIN: gt.gettext('TLS protocol error'),
188
+ UNABLE_TO_VERIFY_LEAF_SIGNATURE: gt.gettext('TLS protocol error')
189
+ });
190
+
191
+ // The same for the nodemailer error codes of the SMTP check
192
+ const SMTP_ERROR_MESSAGES = gt => ({
193
+ EDNS: gt.gettext('Server hostname was not found'),
194
+ EAUTH: gt.gettext('Invalid username or password'),
195
+ ENOAUTH: gt.gettext('Authentication credentials were not provided'),
196
+ EOAUTH2: gt.gettext('OAuth2 authentication failed'),
197
+ ETLS: gt.gettext('TLS protocol error'),
198
+ ETIMEDOUT: gt.gettext('Connection timed out'),
199
+ ECONNECTION: gt.gettext('Could not connect to server'),
200
+ EPROTOCOL: gt.gettext('Unexpected server response')
201
+ });
202
+
203
+ // Replaces `result.error` with the message for `result.code`. An unlisted code keeps its text
204
+ // unless `fallback` says the text describes a TLS failure.
205
+ function translateCheckError(result, messages, fallback, gt) {
206
+ if (Object.hasOwn(messages, result.code)) {
207
+ result.error = messages[result.code];
208
+ } else if (fallback(result)) {
209
+ result.error = gt.gettext('TLS protocol error');
210
+ }
211
+ }
212
+
213
+ // An unlisted IMAP code still reads as TLS when the text comes from OpenSSL, in any case
214
+ const imapTlsFallback = result => /openssl|ssl routines/i.test(result.error);
215
+
216
+ // Only an SMTP socket error is checked for OpenSSL text, and case-sensitively
217
+ const smtpTlsFallback = result => result.code === 'ESOCKET' && /openssl/.test(result.error);
218
+
219
+ /**
220
+ * Translates the error codes of a connection check (verifyAccountInfo) into messages the person
221
+ * at the hosted form can act on. Modifies the result in place; a side is only translated when it
222
+ * carries both an error and a code.
223
+ *
224
+ * @param {Object} verifyResult - `{ imap, smtp }` as verifyAccountInfo returns it, or a falsy value
225
+ * @param {Object} gt - the request's translator
226
+ */
227
+ function translateConnectionErrors(verifyResult, gt) {
228
+ if (!verifyResult) {
229
+ return;
230
+ }
231
+
232
+ if (verifyResult.imap && verifyResult.imap.error && verifyResult.imap.code) {
233
+ translateCheckError(verifyResult.imap, IMAP_ERROR_MESSAGES(gt), imapTlsFallback, gt);
234
+ }
235
+
236
+ if (verifyResult.smtp && verifyResult.smtp.error && verifyResult.smtp.code) {
237
+ translateCheckError(verifyResult.smtp, SMTP_ERROR_MESSAGES(gt), smtpTlsFallback, gt);
238
+ }
239
+ }
240
+
241
+ module.exports = { translateConnectionErrors, describeSmtpAuthMechanisms, buildGmailWatchView, buildAccountAlert, loadWebhookRouting };
@@ -17,10 +17,9 @@ 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
25
  const { autodetectImapSettings, resolveAppPassword, getAppPassword } = require('../autodetect-imap-settings');
@@ -55,16 +54,14 @@ const {
55
54
  adminUrl,
56
55
  accountSuggestions,
57
56
  isClientError,
58
- closedAfterConnectMessage,
59
57
  windowedPageLinks
60
58
  } = require('./route-helpers');
61
- const { parseCustomHeaders } = require('./form-lists');
62
- const { webhooks: Webhooks } = require('../webhooks');
63
59
  const { accountQueueSummary } = require('../queue-browser');
64
- const { describeEffectiveRouting, isDeliverableRoute } = require('../webhook-routing');
65
60
  const { matchesExpectedIdentity, resolveExpectedIdentity } = require('../account/expected-identity');
66
61
  const { OAUTH_NONCE_PATTERN } = require('../oauth/state');
67
62
  const { completeAccountSetup } = require('./account-setup');
63
+ const { buildAccountEditUpdates } = require('./account-edit-form');
64
+ const { translateConnectionErrors, describeSmtpAuthMechanisms, buildGmailWatchView, buildAccountAlert, loadWebhookRouting } = require('./account-page');
68
65
 
69
66
  const { REDIS_PREFIX, DEFAULT_PAGE_SIZE, NONCE_BYTES, MAX_FORM_TTL, MAX_FORM_PROBE_ATTEMPTS } = consts;
70
67
 
@@ -1064,86 +1061,7 @@ function registerPostHostedImapTest(server) {
1064
1061
  request.logger.child({ action: 'verify-account' })
1065
1062
  );
1066
1063
 
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
- }
1064
+ translateConnectionErrors(verifyResult, request.app.gt);
1147
1065
 
1148
1066
  return verifyResult;
1149
1067
  } catch (err) {
@@ -1448,52 +1366,7 @@ function registerGetAccountsByAccount(server, args) {
1448
1366
  }
1449
1367
 
1450
1368
  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
- }
1369
+ accountData.smtpAuthMechanisms = describeSmtpAuthMechanisms(accountData.smtpServerEhlo);
1497
1370
  }
1498
1371
 
1499
1372
  // Stored entries outlive the logging switch - turning logging off does not clear what
@@ -1512,37 +1385,7 @@ function registerGetAccountsByAccount(server, args) {
1512
1385
  accountData.path = null;
1513
1386
  }
1514
1387
 
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
- }
1388
+ let gmailWatch = buildGmailWatchView(accountData);
1546
1389
 
1547
1390
  const canReadMail = (accountData.imap || accountData.oauth2) && !(accountData.imap && accountData.imap.disabled) && !DISABLE_MESSAGE_BROWSER;
1548
1391
 
@@ -1553,56 +1396,9 @@ function registerGetAccountsByAccount(server, args) {
1553
1396
  // API call.
1554
1397
  const disabledByAuthFailureAt = authFailureDisabledAt(accountData);
1555
1398
 
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
- }
1399
+ let accountAlert = buildAccountAlert(accountData, disabledByAuthFailureAt);
1583
1400
 
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
- });
1401
+ const webhookRouting = await loadWebhookRouting(accountData);
1606
1402
 
1607
1403
  return h.view(
1608
1404
  'accounts/account',
@@ -2021,7 +1817,8 @@ function registerGetAccountsBrowse(server, args) {
2021
1817
  request.cookieAuth.clear();
2022
1818
  }
2023
1819
  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`));
1820
+ // the query string carries a deep link (?message=), which has to survive the sign-in
1821
+ return h.redirect('/admin/login?next=' + encodeURIComponent(`${request.url.pathname}${request.url.search}`));
2025
1822
  }
2026
1823
 
2027
1824
  let accountObject = new Account({ redis, account: request.params.account, call, secret: await getSecret() });
@@ -2191,110 +1988,7 @@ function registerPostAccountsEdit(server, args) {
2191
1988
 
2192
1989
  let oldData = await accountObject.loadAccountData();
2193
1990
 
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
- }
1991
+ let updates = buildAccountEditUpdates(request.params.account, request.payload, oldData);
2298
1992
 
2299
1993
  await accountObject.update(updates);
2300
1994