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,249 @@
1
+ 'use strict';
2
+
3
+ // The admin SSO strategies (Okta through @hapi/bell's built-in provider, generic OIDC through a
4
+ // custom bell provider built by lib/sso.js) and their callback routes. Moved out of workers/api.js,
5
+ // which cannot be required from a test, so that the bell registration can be exercised on a real
6
+ // hapi server (test/sso-routes-test.js). Everything the registration reads from the worker is
7
+ // passed in.
8
+
9
+ const sso = require('./sso');
10
+ const { setAdminSession } = require('./tools');
11
+
12
+ /**
13
+ * @typedef {Object} SsoContext
14
+ * @property {boolean} secureCookie Whether the cookies are marked Secure
15
+ * @property {() => Promise<string>} getCookiePassword Password bell seals its state cookie with
16
+ * @property {() => Promise<URL>} getServiceRedirectUrl The public base URL the callbacks live under
17
+ * @property {() => Promise<number>} sessionPasswordVersion Stamped into the session, see workers/api.js
18
+ * @property {Object} logger
19
+ */
20
+
21
+ // A sign-in the IdP denied, or the user cancelled, comes back as an unauthenticated try-mode
22
+ // request. It gets the same flash-and-redirect the allow-list denial in the OIDC handler
23
+ // uses, so the user lands on the login form with a way to try again rather than on the
24
+ // generic error page with bell's raw message. The reason goes to the log only. ?sso_denied=1
25
+ // stops a forced instance from auto-redirecting straight back into the flow.
26
+ async function ssoFailureRedirect(request, h, method) {
27
+ request.logger.warn({
28
+ msg: 'SSO login failed',
29
+ method,
30
+ reason: (request.auth.error && request.auth.error.message) || 'unknown',
31
+ remoteAddress: request.app.ip
32
+ });
33
+ await request.flash({ type: 'danger', message: 'Single sign-on failed or was cancelled. Please try again' });
34
+ return h.redirect('/admin/login?sso_denied=1');
35
+ }
36
+
37
+ // The redirect URL is captured at strategy registration; the validators re-read it from settings
38
+ // so an origin change after startup (which would break the registered callback URL) disables the
39
+ // SSO button instead of failing mid-flow.
40
+ function originGuard(ctx, redirectUrl) {
41
+ return async () => (await ctx.getServiceRedirectUrl()).origin === redirectUrl.origin;
42
+ }
43
+
44
+ /**
45
+ * Registers the Okta strategy and its /admin/login/okta callback.
46
+ *
47
+ * @param {Object} server hapi server with @hapi/bell registered
48
+ * @param {SsoContext} ctx
49
+ * @param {{ baseUrl: string, clientId: string, clientSecret: string }} okta
50
+ */
51
+ async function registerOktaAuth(server, ctx, okta) {
52
+ let redirectUrl = await ctx.getServiceRedirectUrl();
53
+
54
+ server.decorate('toolkit', 'validateOktaConfig', originGuard(ctx, redirectUrl));
55
+
56
+ server.auth.strategy('okta', 'bell', {
57
+ provider: 'okta',
58
+ config: {
59
+ uri: okta.baseUrl
60
+ },
61
+ password: await ctx.getCookiePassword(),
62
+ isSecure: ctx.secureCookie,
63
+ location: redirectUrl.origin,
64
+
65
+ clientId: okta.clientId,
66
+ clientSecret: okta.clientSecret
67
+ });
68
+
69
+ server.route({
70
+ method: ['GET', 'POST'],
71
+ path: '/admin/login/okta',
72
+ async handler(request, h) {
73
+ if (!request.auth.isAuthenticated) {
74
+ return ssoFailureRedirect(request, h, 'okta');
75
+ }
76
+
77
+ let profile = (request.auth.credentials && request.auth.credentials.profile) || {};
78
+
79
+ // The same minimal shape the OIDC branch below stores, for the same reasons: the
80
+ // full bell credentials carry the access and refresh tokens, the callback query
81
+ // and the raw userinfo document, none of which the session validator reads, and
82
+ // all of which would sit in the browser's cookie for the life of the session.
83
+ setAdminSession(request, {
84
+ provider: 'okta',
85
+ profile: {
86
+ id: profile.id,
87
+ username: profile.username,
88
+ displayName: profile.displayName,
89
+ email: profile.email
90
+ },
91
+ passwordVersion: await ctx.sessionPasswordVersion()
92
+ });
93
+
94
+ request.logger.info({ msg: 'Admin login successful', user: profile.username || 'unknown', method: 'okta', remoteAddress: request.app.ip });
95
+ return h.redirect('/admin');
96
+ },
97
+ options: {
98
+ auth: {
99
+ mode: 'try',
100
+ strategy: 'okta'
101
+ }
102
+ }
103
+ });
104
+ }
105
+
106
+ /**
107
+ * Registers the generic OIDC strategy and its /admin/login/oidc callback.
108
+ *
109
+ * @param {Object} server hapi server with @hapi/bell registered
110
+ * @param {SsoContext} ctx
111
+ * @param {Object} oidc
112
+ * @param {Object} oidc.allowList parseAllowList() result
113
+ * @param {Object} oidc.allowGroups parseGroupList() result
114
+ * @param {() => Promise<Object>} [oidc.fetchDiscovery] Defaults to sso.fetchOidcDiscovery
115
+ * @param {() => Promise<Object>} [oidc.retryDiscovery] Defaults to sso.retryDiscovery
116
+ * @returns {Promise<{ retry: Promise<void>|null }>} The background retry, when the first discovery failed. Wrapped
117
+ * in an object because an async function returning the promise itself would hand the caller its result.
118
+ */
119
+ async function registerOidcAuth(server, ctx, oidc) {
120
+ let { logger } = ctx;
121
+ let fetchDiscovery = oidc.fetchDiscovery || (() => sso.fetchOidcDiscovery());
122
+ let retryDiscovery =
123
+ oidc.retryDiscovery ||
124
+ (() =>
125
+ sso.retryDiscovery({
126
+ onError: (err, attempt) => logger.debug({ msg: 'OIDC discovery retry failed', issuer: sso.OIDC_ISSUER, attempt, err })
127
+ }));
128
+
129
+ let redirectUrl = await ctx.getServiceRedirectUrl();
130
+ let originUnchanged = originGuard(ctx, redirectUrl);
131
+
132
+ // The discovery document the strategy reads its endpoints from on every sign-in (bell takes
133
+ // functions for them). The strategy and its callback route are registered right away, whether
134
+ // or not discovery has succeeded yet, so nothing is ever added to the route table after the
135
+ // server has started. A failure to fetch the document (IdP outage or misconfig) must NOT take
136
+ // EmailEngine down - password and passkey login plus the REST API have to keep working - so
137
+ // SSO simply stays switched off until a later attempt succeeds: while this is null
138
+ // validateOidcConfig() offers no login button and does not trigger OIDC_FORCED, and a sign-in
139
+ // started anyway fails back to the login form.
140
+ let oidcDiscovery = null;
141
+
142
+ // Registered unconditionally so the login/security views can call it; returns
143
+ // false when discovery failed or the serviceUrl origin drifted from startup.
144
+ server.decorate('toolkit', 'validateOidcConfig', async () => !!oidcDiscovery && (await originUnchanged()));
145
+
146
+ // RP-initiated logout URL for the /admin/logout handler. Returns null unless
147
+ // OIDC_LOGOUT is enabled and the IdP advertised an end_session_endpoint.
148
+ // post_logout_redirect_uri is only sent when OIDC_POST_LOGOUT_REDIRECT_URI is
149
+ // configured (and registered at the IdP); otherwise the IdP shows its own
150
+ // logged-out page, so logout needs no IdP-side configuration.
151
+ server.decorate('toolkit', 'oidcLogoutUrl', idToken => {
152
+ if (!sso.OIDC_LOGOUT || !oidcDiscovery || !oidcDiscovery.end_session_endpoint) {
153
+ return null;
154
+ }
155
+ return sso.buildLogoutUrl(oidcDiscovery.end_session_endpoint, {
156
+ idToken,
157
+ clientId: sso.OIDC_CLIENT_ID,
158
+ postLogoutRedirectUri: sso.OIDC_POST_LOGOUT_REDIRECT_URI || undefined
159
+ });
160
+ });
161
+
162
+ server.auth.strategy('oidc', 'bell', {
163
+ provider: sso.buildOidcBellProvider(() => oidcDiscovery),
164
+ password: await ctx.getCookiePassword(),
165
+ isSecure: ctx.secureCookie,
166
+ location: redirectUrl.origin,
167
+
168
+ clientId: sso.OIDC_CLIENT_ID,
169
+ clientSecret: sso.OIDC_CLIENT_SECRET
170
+ });
171
+
172
+ server.route({
173
+ method: ['GET', 'POST'],
174
+ path: '/admin/login/oidc',
175
+ async handler(request, h) {
176
+ if (!request.auth.isAuthenticated) {
177
+ return ssoFailureRedirect(request, h, 'oidc');
178
+ }
179
+
180
+ let profile = (request.auth.credentials && request.auth.credentials.profile) || {};
181
+
182
+ // Enforce the optional email/group allow-lists before establishing the session.
183
+ if (!sso.isAuthorized(profile, oidc.allowList, oidc.allowGroups)) {
184
+ request.logger.warn({
185
+ msg: 'OIDC login denied by allow-list',
186
+ user: profile.username || profile.email || 'unknown',
187
+ groups: profile.groups,
188
+ method: 'oidc',
189
+ remoteAddress: request.app.ip
190
+ });
191
+ await request.flash({ type: 'danger', message: 'Your account is not authorized to access this admin panel' });
192
+ // ?sso_denied=1 stops a forced instance from auto-redirecting back into the
193
+ // OIDC flow before the user can see the error.
194
+ return h.redirect('/admin/login?sso_denied=1');
195
+ }
196
+
197
+ // Store only the minimal profile - not the full bell credentials. OIDC
198
+ // access/refresh tokens (e.g. Keycloak JWTs) can push the iron-sealed
199
+ // `ee` cookie past the ~4KB browser limit and cause a silent login loop.
200
+ // Group names are kept so the per-request authorization re-check works;
201
+ // the id_token is kept only as the logout id_token_hint (RP-initiated logout).
202
+ setAdminSession(request, {
203
+ provider: 'oidc',
204
+ profile: {
205
+ id: profile.id,
206
+ username: profile.username,
207
+ displayName: profile.displayName,
208
+ email: profile.email,
209
+ // Carried so the per-request isAuthorized() re-check enforces email
210
+ // verification the same way the login gate above does.
211
+ emailVerified: profile.emailVerified,
212
+ groups: profile.groups
213
+ },
214
+ passwordVersion: await ctx.sessionPasswordVersion(),
215
+ idToken: (request.auth.artifacts && request.auth.artifacts.id_token) || null
216
+ });
217
+
218
+ request.logger.info({ msg: 'Admin login successful', user: profile.username || 'unknown', method: 'oidc', remoteAddress: request.app.ip });
219
+ return h.redirect('/admin');
220
+ },
221
+ options: {
222
+ auth: {
223
+ mode: 'try',
224
+ strategy: 'oidc'
225
+ }
226
+ }
227
+ });
228
+
229
+ oidcDiscovery = await fetchDiscovery().catch(err => {
230
+ logger.error({ msg: 'OIDC SSO disabled for now: discovery failed, retrying in the background', issuer: sso.OIDC_ISSUER, err });
231
+ return null;
232
+ });
233
+
234
+ if (oidcDiscovery) {
235
+ return { retry: null };
236
+ }
237
+
238
+ // Deliberately not awaited by the caller - this runs for as long as the IdP is unreachable.
239
+ // A later success brings SSO up in place, with no restart and no route added after start.
240
+ let retry = retryDiscovery()
241
+ .then(retriedDoc => {
242
+ oidcDiscovery = retriedDoc;
243
+ logger.info({ msg: 'OIDC SSO enabled after retrying discovery', issuer: sso.OIDC_ISSUER });
244
+ })
245
+ .catch(err => logger.error({ msg: 'OIDC SSO disabled: discovery retry failed', issuer: sso.OIDC_ISSUER, err }));
246
+ return { retry };
247
+ }
248
+
249
+ module.exports = { registerOktaAuth, registerOidcAuth };
package/lib/sso.js CHANGED
@@ -363,22 +363,45 @@ function buildLogoutUrl(endSessionEndpoint, options) {
363
363
  return url.toString();
364
364
  }
365
365
 
366
- // Build a @hapi/bell custom OAuth2 provider from a validated discovery document.
367
- function buildOidcBellProvider(discoveryDoc, options) {
366
+ /**
367
+ * Builds a @hapi/bell custom OAuth2 provider for the OIDC identity provider.
368
+ *
369
+ * The endpoints are read from the discovery document on every sign-in rather than fixed when the
370
+ * strategy is registered (bell takes functions for them since 13.2), so the strategy and its
371
+ * callback route can be registered at boot before discovery has succeeded. Until a document is
372
+ * available a sign-in fails with an error instead of reaching an IdP endpoint; the login button is
373
+ * not offered then anyway (validateOidcConfig()).
374
+ *
375
+ * @param {() => Object|null} getDocument Returns the current validated discovery document, null while
376
+ * discovery has not succeeded
377
+ * @param {Object} [options]
378
+ * @param {string} [options.scopes] Scope override
379
+ * @param {string} [options.groupsClaim] Claim the groups are read from
380
+ */
381
+ function buildOidcBellProvider(getDocument, options) {
368
382
  options = options || {};
369
383
  let scopes = parseScopes(options.scopes || OIDC_SCOPES);
370
384
  let groupsClaim = options.groupsClaim || OIDC_GROUPS_CLAIM;
371
- let userinfoEndpoint = discoveryDoc.userinfo_endpoint;
385
+
386
+ let endpoint = name => {
387
+ let doc = getDocument();
388
+ if (!doc || !doc[name]) {
389
+ let err = new Error('OIDC discovery document is not available yet');
390
+ err.code = 'OidcDiscoveryUnavailable';
391
+ throw err;
392
+ }
393
+ return doc[name];
394
+ };
372
395
 
373
396
  return {
374
397
  protocol: 'oauth2',
375
398
  useParamsAuth: true,
376
399
  pkce: 'S256',
377
- auth: discoveryDoc.authorization_endpoint,
378
- token: discoveryDoc.token_endpoint,
400
+ auth: () => endpoint('authorization_endpoint'),
401
+ token: () => endpoint('token_endpoint'),
379
402
  scope: scopes,
380
403
  profile: async (credentials, params, get) => {
381
- let userinfo = await get(userinfoEndpoint);
404
+ let userinfo = await get(endpoint('userinfo_endpoint'));
382
405
  credentials.profile = mapUserinfoProfile(userinfo, groupsClaim);
383
406
  }
384
407
  };
package/lib/tools.js CHANGED
@@ -2,8 +2,6 @@
2
2
 
3
3
  'use strict';
4
4
 
5
- // Before anything that makes an HTTP request, see the module
6
- require('./net-tos-guard');
7
5
  const { accountDataKey } = require('./redis-keys');
8
6
  const { filterEmptyObjectValues } = require('./utils/filter-empty');
9
7
 
@@ -275,7 +273,10 @@ function buildFetchDispatcher(proxyUrl, extraOpts) {
275
273
  if (SOCKS_SCHEMES.has(scheme)) {
276
274
  return createSocksAgent(proxyUrl, AGENT_OPTS);
277
275
  }
278
- return new ProxyAgent(Object.assign({}, AGENT_OPTS, { uri: proxyUrl }));
276
+ // proxyTunnel: undici 8 forwards a plain http:// request to the proxy in absolute form instead
277
+ // of tunnelling it, which is what undici 7 did and what proxies set up for EmailEngine have seen
278
+ // for every request since. A proxy that only allows CONNECT would refuse the forwarded form
279
+ return new ProxyAgent(Object.assign({}, AGENT_OPTS, { uri: proxyUrl, proxyTunnel: true }));
279
280
  }
280
281
 
281
282
  // Swaps the shared dispatchers over to `proxyUrl` (null for direct connections). The new fetch
@@ -777,7 +778,7 @@ async function maybeReloadTlsCertificates(call, logger, keys, context) {
777
778
 
778
779
  // The public keys license files are verified against. runPrechecks() below carries the same three,
779
780
  // encoded; a key added to one list has to be added to the other, or a license that passes here fails
780
- // the API worker's precheck and every API route answers with an error (test/license-keys-test.js
781
+ // the API worker's precheck and every API route answers with an error (test/license-subscription-test.js
781
782
  // checks that the two lists agree).
782
783
  const LICENSE_VERIFY_KEYS = [
783
784
  // main-key-1
@@ -0,0 +1,198 @@
1
+ 'use strict';
2
+
3
+ // The account update the admin account edit form (POST /admin/accounts/{account}/edit in
4
+ // account-routes.js) asks for, built from the validated payload and the stored account. Pure, so
5
+ // test/account-edit-form-test.js covers it without a route.
6
+ //
7
+ // The rule that runs through all of it: an untouched form save must not add or change keys,
8
+ // because any imap diff forces a reconnect. So a value is written only when the effective state
9
+ // changes, and a field the form did not show is not written at all.
10
+ //
11
+ // The stored connection objects are copied before anything is applied to them: the update is
12
+ // built on the copy, so the loaded account is left as it was.
13
+
14
+ const { SPECIAL_USE_PATH_FIELDS } = require('./special-use-paths');
15
+ const { applyImapMaxIdleTimeForm } = require('./imap-idle-field');
16
+ const { applySecurityForm } = require('./connection-security-form');
17
+ const { parseCustomHeaders } = require('./form-lists');
18
+
19
+ // A copy of a stored connection object deep enough for the form to apply its changes to: the
20
+ // only nested objects it writes into are `auth` and `tls`
21
+ function copyConnection(stored) {
22
+ if (!stored) {
23
+ return stored;
24
+ }
25
+ let copy = Object.assign({}, stored);
26
+ for (let key of ['auth', 'tls']) {
27
+ if (copy[key] && typeof copy[key] === 'object') {
28
+ copy[key] = Object.assign({}, copy[key]);
29
+ }
30
+ }
31
+ return copy;
32
+ }
33
+
34
+ /**
35
+ * The account-level fields of the update.
36
+ *
37
+ * @param {String} account - account ID
38
+ * @param {Object} payload - the validated form payload
39
+ * @returns {Object} the update, without the connection sections
40
+ */
41
+ function buildBaseUpdates(account, payload) {
42
+ let updates = {
43
+ account,
44
+ name: payload.name || '',
45
+ email: payload.email,
46
+ // Empty clears the pin (Account.update hdel's it), which is the only way an operator
47
+ // can unblock a legitimate mailbox migration on a pinned account.
48
+ expectedEmail: payload.expectedEmail || null,
49
+ proxy: payload.proxy,
50
+ smtpEhloName: payload.smtpEhloName,
51
+ webhooks: payload.webhooks
52
+ };
53
+
54
+ // Absent only from a request that did not render the field, keep the stored headers then
55
+ if (typeof payload.customHeaders === 'string') {
56
+ updates.webhooksCustomHeaders = parseCustomHeaders(payload.customHeaders);
57
+ }
58
+
59
+ return updates;
60
+ }
61
+
62
+ /**
63
+ * The `imap` object of the update, for a payload whose IMAP section was submitted.
64
+ *
65
+ * @param {Object} payload - the validated form payload
66
+ * @param {Object} [storedImap] - the stored `imap` object
67
+ * @returns {Object} the stored object with the submitted changes applied
68
+ */
69
+ function buildImapUpdates(payload, storedImap) {
70
+ let imap = copyConnection(storedImap);
71
+ let imapTls = (imap && imap.tls) || {};
72
+
73
+ let updateKeys = {};
74
+
75
+ for (let key of ['host', 'port', 'disabled']) {
76
+ // The form always submits the disabled checkbox, and a stored account that never had the key
77
+ // is enabled just like one that stores `false`, so `disabled` is written only when the
78
+ // effective state changes. Unchecking it on a parked account still writes `false`, which
79
+ // lifts the park
80
+ if (`imap_${key}` in payload && (key !== 'disabled' || !payload.imap_disabled !== !(imap && imap.disabled))) {
81
+ updateKeys[key] = payload[`imap_${key}`];
82
+ }
83
+ }
84
+
85
+ // The special-use folder overrides. An empty input means "no override" and has to
86
+ // be written as null to unset one, while a field the form never showed must not be
87
+ // written at all: these inputs live inside the IMAP section, which is hidden for an
88
+ // account whose IMAP the operator switched off. The schema therefore allows the
89
+ // empty string instead of defaulting to null - a default is inserted by joi for
90
+ // every key the browser did not send, which made the presence check below always
91
+ // true, so an unrelated save (a rename, a new webhook URL) wiped every override set
92
+ // over PUT /v1/account/{account}. Same presence test imap_auth_user relies on.
93
+ for (const field of SPECIAL_USE_PATH_FIELDS) {
94
+ const payloadKey = `imap_${field.key}`;
95
+ if (!(payloadKey in payload)) {
96
+ continue;
97
+ }
98
+ const value = payload[payloadKey] || null;
99
+ // Written only when the effective value changes, like the TLS flags below: an
100
+ // untouched save must not add keys, because any imap diff forces a reconnect
101
+ if (value !== ((imap && imap[field.key]) || null)) {
102
+ updateKeys[field.key] = value;
103
+ }
104
+ }
105
+
106
+ applyImapMaxIdleTimeForm(payload, imap, updateKeys);
107
+ if ('imap_auth_user' in payload) {
108
+ let imapAuth = Object.assign((imap && imap.auth) || {}, { user: payload.imap_auth_user });
109
+ if (payload.imap_auth_pass) {
110
+ imapAuth.pass = payload.imap_auth_pass;
111
+ }
112
+ updateKeys.auth = imapAuth;
113
+ updateKeys.secure = payload.imap_secure;
114
+ // The connection settings section is hidden for OAuth2 and disabled
115
+ // accounts, so like `secure` these only apply when it was submitted.
116
+ // Written only when the effective state changes - an untouched form
117
+ // save must not add new keys, as any imap diff forces a reconnect
118
+ applySecurityForm(payload, 'imap', imap, updateKeys, imapTls);
119
+ if (payload.imap_disableIMAP4rev2 !== !!(imap && imap.disableIMAP4rev2)) {
120
+ updateKeys.disableIMAP4rev2 = payload.imap_disableIMAP4rev2;
121
+ }
122
+ }
123
+
124
+ // skipped while empty and absent from the stored account for the same
125
+ // reason as above - a no-op save must not introduce a tls:{} key
126
+ if (Object.keys(imapTls).length) {
127
+ updateKeys.tls = imapTls;
128
+ }
129
+
130
+ let updated = Object.assign(imap || {}, updateKeys);
131
+
132
+ if (payload.imap_resyncDelay) {
133
+ updated.resyncDelay = payload.imap_resyncDelay;
134
+ }
135
+
136
+ return updated;
137
+ }
138
+
139
+ /**
140
+ * The `smtp` object of the update, for a payload whose SMTP section was submitted.
141
+ *
142
+ * @param {Object} payload - the validated form payload
143
+ * @param {Object} [storedSmtp] - the stored `smtp` object
144
+ * @returns {Object} the stored object with the submitted changes applied
145
+ */
146
+ function buildSmtpUpdates(payload, storedSmtp) {
147
+ let smtp = copyConnection(storedSmtp);
148
+ let smtpAuth = Object.assign((smtp && smtp.auth) || {}, { user: payload.smtp_auth_user });
149
+ let smtpTls = (smtp && smtp.tls) || {};
150
+
151
+ if (payload.smtp_auth_pass) {
152
+ smtpAuth.pass = payload.smtp_auth_pass;
153
+ }
154
+
155
+ let updated = Object.assign(smtp || {}, {
156
+ host: payload.smtp_host,
157
+ port: payload.smtp_port,
158
+ secure: payload.smtp_secure,
159
+ auth: smtpAuth
160
+ });
161
+
162
+ // written only when the effective state changes, and the tls object is
163
+ // skipped while empty - same as the IMAP flags, a no-op save must not
164
+ // modify the stored account. When an SMTP object is stored, `updated` IS `smtp` (Object.assign
165
+ // wrote into the copy), so the comparison already sees the submitted host, port and auth; the
166
+ // security fields it reads are not among them. Without one, the comparison sees undefined.
167
+ applySecurityForm(payload, 'smtp', smtp, updated, smtpTls);
168
+
169
+ if (Object.keys(smtpTls).length) {
170
+ updated.tls = smtpTls;
171
+ }
172
+
173
+ return updated;
174
+ }
175
+
176
+ /**
177
+ * The whole update the form asks for.
178
+ *
179
+ * @param {String} account - account ID
180
+ * @param {Object} payload - the validated form payload
181
+ * @param {Object} oldData - the stored account
182
+ * @returns {Object} the update for Account.update()
183
+ */
184
+ function buildAccountEditUpdates(account, payload, oldData) {
185
+ let updates = buildBaseUpdates(account, payload);
186
+
187
+ if (payload.imap) {
188
+ updates.imap = buildImapUpdates(payload, oldData.imap);
189
+ }
190
+
191
+ if (payload.smtp) {
192
+ updates.smtp = buildSmtpUpdates(payload, oldData.smtp);
193
+ }
194
+
195
+ return updates;
196
+ }
197
+
198
+ module.exports = { buildAccountEditUpdates, buildBaseUpdates, buildImapUpdates, buildSmtpUpdates };