emailengine-app 2.84.1 → 2.85.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 (147) hide show
  1. package/.dockerignore +6 -0
  2. package/.ncurc.js +5 -3
  3. package/.prettierignore +5 -1
  4. package/.prettierrc.js +2 -0
  5. package/.release-please-manifest.json +1 -1
  6. package/CHANGELOG.md +61 -0
  7. package/Dockerfile +8 -2
  8. package/README.md +1 -1
  9. package/bin/emailengine.js +444 -403
  10. package/copy-static-files.sh +39 -14
  11. package/data/google-crawlers.json +1 -1
  12. package/data/public_suffix_list.dat +16562 -0
  13. package/docker-compose.yml +1 -1
  14. package/eslint.config.js +81 -99
  15. package/lib/account/own-account-key.js +42 -0
  16. package/lib/account-assignment.js +1 -33
  17. package/lib/account.js +68 -24
  18. package/lib/add-trackers.js +11 -4
  19. package/lib/api-reference/format.js +4 -3
  20. package/lib/api-routes/account-routes.js +244 -26
  21. package/lib/api-routes/blocklist-routes.js +23 -2
  22. package/lib/api-routes/delivery-test-routes.js +26 -3
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +37 -5
  25. package/lib/api-routes/mailbox-routes.js +41 -2
  26. package/lib/api-routes/message-routes.js +104 -4
  27. package/lib/api-routes/mint-bounds.js +11 -0
  28. package/lib/api-routes/oauth2-app-routes.js +48 -15
  29. package/lib/api-routes/outbox-routes.js +45 -11
  30. package/lib/api-routes/permission-map.js +12 -1
  31. package/lib/api-routes/route-helpers.js +125 -3
  32. package/lib/api-routes/settings-routes.js +23 -2
  33. package/lib/api-routes/submit-routes.js +338 -309
  34. package/lib/api-routes/template-routes.js +38 -2
  35. package/lib/api-routes/token-routes.js +142 -96
  36. package/lib/api-routes/webhook-route-routes.js +13 -2
  37. package/lib/auth-token.js +23 -10
  38. package/lib/bounce-detect.js +414 -210
  39. package/lib/consts.js +39 -4
  40. package/lib/create-imap-client.js +41 -2
  41. package/lib/email-client/base-client.js +30 -41
  42. package/lib/email-client/gmail-client.js +30 -18
  43. package/lib/email-client/imap/mailbox.js +13 -23
  44. package/lib/email-client/imap/response-metrics.js +75 -0
  45. package/lib/email-client/imap/subconnection.js +1 -1
  46. package/lib/email-client/imap-client.js +6 -3
  47. package/lib/email-client/message-builder.js +7 -2
  48. package/lib/email-client/notification-handler.js +1 -2
  49. package/lib/email-client/outlook/graph-api.js +17 -2
  50. package/lib/email-client/outlook-client.js +6 -3
  51. package/lib/email-client/smtp-pool-manager.js +6 -0
  52. package/lib/encrypt.js +9 -0
  53. package/lib/export.js +3 -1
  54. package/lib/gateway.js +2 -3
  55. package/lib/get-raw-email.js +4 -2
  56. package/lib/hapi-request-logger.js +107 -0
  57. package/lib/imap-proxy-auth.js +14 -1
  58. package/lib/imapproxy/imap-core/README.md +6 -5
  59. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  60. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  61. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  62. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  63. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  64. package/lib/mcp/listen.js +10 -1
  65. package/lib/mcp/tools.js +37 -8
  66. package/lib/notify-attachments.js +17 -0
  67. package/lib/oauth/external-account-config.js +3 -1
  68. package/lib/oauth/gmail.js +21 -48
  69. package/lib/oauth/mail-ru.js +5 -38
  70. package/lib/oauth/outlook-mailbox.js +35 -0
  71. package/lib/oauth/outlook.js +26 -44
  72. package/lib/oauth/state.js +24 -0
  73. package/lib/oauth2-apps.js +1 -1
  74. package/lib/pbkdf2-phc.js +19 -2
  75. package/lib/privileged-settings.js +6 -3
  76. package/lib/redis-scan-delete.js +15 -1
  77. package/lib/schemas.js +79 -33
  78. package/lib/settings.js +13 -1
  79. package/lib/smtp-auth.js +23 -0
  80. package/lib/sso.js +1 -1
  81. package/lib/swagger-options.js +1 -1
  82. package/lib/thread-diagnostics.js +46 -0
  83. package/lib/timezones.js +109 -0
  84. package/lib/token-permission-view.js +3 -3
  85. package/lib/tools.js +285 -66
  86. package/lib/totp.js +2 -5
  87. package/lib/translations.js +1 -2
  88. package/lib/ui-routes/account-routes.js +491 -491
  89. package/lib/ui-routes/account-setup.js +99 -0
  90. package/lib/ui-routes/admin-config-routes.js +98 -48
  91. package/lib/ui-routes/admin-entities-routes.js +113 -31
  92. package/lib/ui-routes/auth-routes.js +137 -62
  93. package/lib/ui-routes/connection-security-form.js +74 -0
  94. package/lib/ui-routes/form-lists.js +46 -0
  95. package/lib/ui-routes/internals-routes.js +5 -0
  96. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  97. package/lib/ui-routes/oauth-config-routes.js +133 -100
  98. package/lib/ui-routes/route-helpers.js +19 -3
  99. package/lib/ui-routes/sign-in-helpers.js +59 -0
  100. package/lib/ui-routes/tls-config-routes.js +58 -15
  101. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  102. package/lib/utils/back-off.js +82 -0
  103. package/lib/utils/map-concurrent.js +36 -0
  104. package/lib/utils/murmurhash3.js +66 -0
  105. package/lib/utils/network.js +28 -0
  106. package/lib/utils/provider-id.js +27 -0
  107. package/lib/utils/public-suffix.js +122 -0
  108. package/lib/utils/random-id.js +26 -0
  109. package/lib/utils/require-tls.js +33 -0
  110. package/lib/utils/version.js +74 -0
  111. package/lib/web-safe-html.js +5 -6
  112. package/lib/webhook-penalty.js +75 -0
  113. package/lib/webhook-routing.js +49 -2
  114. package/lib/webhooks.js +41 -6
  115. package/package.json +37 -39
  116. package/sbom.json +7980 -1
  117. package/server.js +659 -455
  118. package/static/js/ace/ace.js +1 -1
  119. package/static/js/ace/mode-handlebars.js +1 -1
  120. package/static/js/ace/mode-html.js +1 -1
  121. package/static/js/ace/mode-javascript.js +1 -1
  122. package/static/js/ace/mode-markdown.js +1 -1
  123. package/static/js/ace/worker-html.js +1 -1
  124. package/static/js/ace/worker-javascript.js +1 -1
  125. package/static/js/ace/worker-json.js +1 -1
  126. package/static/js/ee-client.js +5 -0
  127. package/static/licenses.html +191 -1016
  128. package/translations/messages.pot +70 -71
  129. package/views/account/security.hbs +10 -0
  130. package/views/accounts/account.hbs +11 -11
  131. package/views/accounts/edit.hbs +6 -2
  132. package/views/config/ai.hbs +1 -1
  133. package/views/config/security.hbs +2 -2
  134. package/views/config/service.hbs +3 -0
  135. package/views/internals/index.hbs +8 -0
  136. package/views/partials/gateway_form.hbs +3 -1
  137. package/views/partials/webhook_form.hbs +1 -1
  138. package/views/suppression-lists/index.hbs +1 -1
  139. package/workers/api.js +780 -585
  140. package/workers/export.js +1 -1
  141. package/workers/submit.js +1 -1
  142. package/workers/webhooks.js +54 -34
  143. package/config/test.toml +0 -46
  144. package/install.sh +0 -428
  145. package/setup-production.sh +0 -215
  146. package/systemd/emailengine.service +0 -97
  147. package/systemd/nginx-proxy.conf +0 -77
@@ -20,6 +20,7 @@ const { Account, authFailureDisabledAt, isOperatorDisabled } = require('../accou
20
20
  const { formatGmailWatch } = require('../account/account-state');
21
21
  const { SPECIAL_USE_PATH_FIELDS } = require('./special-use-paths');
22
22
  const { imapMaxIdleTimeFormSchema, imapMaxIdleTimeFormValue, applyImapMaxIdleTimeForm } = require('./imap-idle-field');
23
+ const { securityFormFields, securityFormValues, applySecurityForm } = require('./connection-security-form');
23
24
 
24
25
  const { Gateway } = require('../gateway');
25
26
  const { autodetectImapSettings, resolveAppPassword, getAppPassword } = require('../autodetect-imap-settings');
@@ -30,8 +31,6 @@ const {
30
31
  getServiceHostname,
31
32
  getSignedFormData,
32
33
  parseSignedFormData,
33
- claimFormNonce,
34
- releaseFormNonce,
35
34
  getLogs,
36
35
  verifyAccountInfo,
37
36
  flattenObjectKeys,
@@ -51,6 +50,7 @@ const {
51
50
  const {
52
51
  formatAccountData,
53
52
  identityErrorView,
53
+ renderRedirect,
54
54
  ACCOUNT_STATE_DISPLAY,
55
55
  adminUrl,
56
56
  accountSuggestions,
@@ -58,10 +58,13 @@ const {
58
58
  closedAfterConnectMessage,
59
59
  windowedPageLinks
60
60
  } = require('./route-helpers');
61
+ const { parseCustomHeaders } = require('./form-lists');
61
62
  const { webhooks: Webhooks } = require('../webhooks');
62
63
  const { accountQueueSummary } = require('../queue-browser');
63
64
  const { describeEffectiveRouting, isDeliverableRoute } = require('../webhook-routing');
64
65
  const { matchesExpectedIdentity, resolveExpectedIdentity } = require('../account/expected-identity');
66
+ const { OAUTH_NONCE_PATTERN } = require('../oauth/state');
67
+ const { completeAccountSetup } = require('./account-setup');
65
68
 
66
69
  const { REDIS_PREFIX, DEFAULT_PAGE_SIZE, NONCE_BYTES, MAX_FORM_TTL, MAX_FORM_PROBE_ATTEMPTS } = consts;
67
70
 
@@ -142,8 +145,354 @@ async function getMailboxListing(accountObject) {
142
145
  return mailboxes;
143
146
  }
144
147
 
145
- function init(args) {
146
- const { server, call } = args;
148
+ async function accountFormHandler(request, h) {
149
+ // Intentionally parsed WITHOUT requireNonce (unlike the IMAP-arm endpoints). This OAuth entry must
150
+ // keep accepting legacy / pre-upgrade re-auth blobs that carry no n/t - requiring a nonce here
151
+ // would 403 the account page's "Re-authenticate" button across a rolling upgrade and break
152
+ // still-circulating pre-v2.39 OAuth setup links. Replay safety is enforced downstream instead: the
153
+ // OAuth callback (workers/api.js) claims the form nonce atomically (SET NX before create) when one
154
+ // is present. Do NOT add requireNonce here without re-checking that compat impact.
155
+ const data = await parseSignedFormData(redis, request.payload, request.app.gt);
156
+
157
+ const oauth2App = await oauth2Apps.get(request.payload.type);
158
+
159
+ if (oauth2App && oauth2App.enabled) {
160
+ // prepare account entry
161
+
162
+ let accountData = {
163
+ account: data.account
164
+ };
165
+
166
+ for (let key of ['name', 'email', 'path']) {
167
+ if (data[key]) {
168
+ accountData[key] = data[key];
169
+ }
170
+ }
171
+
172
+ accountData.notifyFrom = data.notifyFrom || new Date().toISOString();
173
+
174
+ for (let key of ['redirectUrl', 'expectedEmail', 'n', 't']) {
175
+ if (!accountData._meta) {
176
+ accountData._meta = {};
177
+ }
178
+ accountData._meta[key] = data[key];
179
+ }
180
+
181
+ if (data.delegated) {
182
+ accountData.delegated = true;
183
+ } else {
184
+ accountData.copy = false;
185
+ }
186
+
187
+ accountData.oauth2 = {
188
+ provider: oauth2App.id
189
+ };
190
+
191
+ // throws if invalid or unknown app ID
192
+ const oAuth2Client = await oauth2Apps.getClient(oauth2App.id);
193
+
194
+ const nonce = data.n || crypto.randomBytes(NONCE_BYTES).toString('base64url');
195
+
196
+ // Validate nonce format (base64url, 21-22 chars; also accept base64 for backward compatibility)
197
+ if (!OAUTH_NONCE_PATTERN.test(nonce)) {
198
+ throw Boom.badRequest('Invalid nonce format. Please generate a new authentication URL.');
199
+ }
200
+
201
+ // store account data with atomic SET + EX
202
+ await redis.set(`${REDIS_PREFIX}account:add:${nonce}`, JSON.stringify(accountData), 'EX', Math.floor(MAX_FORM_TTL / 1000));
203
+
204
+ // Generate the url that will be used for the consent dialog.
205
+
206
+ let requestPayload = {
207
+ state: `account:add:${nonce}`
208
+ };
209
+
210
+ if (accountData.email) {
211
+ requestPayload.email = accountData.email;
212
+ }
213
+
214
+ // Service providers use client_credentials - no interactive authorization
215
+ if (SERVICE_ACCOUNT_PROVIDERS.has(oAuth2Client.provider)) {
216
+ throw Boom.badRequest('Application-only OAuth providers do not support interactive authorization');
217
+ }
218
+
219
+ let authorizeUrl = oAuth2Client.generateAuthUrl(requestPayload);
220
+
221
+ return h.redirect(authorizeUrl);
222
+ }
223
+
224
+ const expectedEmail = await resolveFormExpectation(data);
225
+
226
+ return h.view(
227
+ 'accounts/register/imap',
228
+ {
229
+ pageTitleFull: request.app.gt.gettext('Email Account Setup'),
230
+ values: {
231
+ data: request.payload.data,
232
+ sig: request.payload.sig,
233
+
234
+ // A pinned link fixes the address, so prefill from the expectation rather than from the
235
+ // editable hint and mark it read-only. Cosmetic - the endpoints below enforce it.
236
+ email: expectedEmail || data.email,
237
+ emailPinned: !!expectedEmail,
238
+ name: data.name
239
+ }
240
+ },
241
+ {
242
+ layout: 'public'
243
+ }
244
+ );
245
+ }
246
+
247
+ // Shared by this route's payload validation and its failAction re-render (same rationale as
248
+ // serverFormSchema below), so the re-rendered first page is built from the same schema that validated
249
+ // the submission rather than echoing the raw payload.
250
+ const firstPageSchema = Joi.object({
251
+ ...signedBlobFields,
252
+ name: Joi.string().empty('').max(256).example('John Smith').description('Account Name'),
253
+ 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')
255
+ });
256
+
257
+ // Shared IMAP/SMTP connection fields for the hosted form's /imap/test and /imap/server routes, so the
258
+ // two payload schemas (and their failAction re-renders) are built from one definition and cannot drift.
259
+ // The tri-state booleans list '0' as falsy (a string a non-browser client may submit symmetric with the
260
+ // truthy '1'); without it '0' would fail coercion and re-render a checkbox as checked.
261
+ const connectionFields = {
262
+ imap_auth_user: Joi.string().empty('').trim().max(1024).required(),
263
+ imap_auth_pass: Joi.string().empty('').max(1024).required(),
264
+ imap_host: Joi.string().hostname().required().example('imap.gmail.com').description('Hostname to connect to').label('IMAP host'),
265
+ imap_port: Joi.number()
266
+ .integer()
267
+ .min(1)
268
+ .max(64 * 1024)
269
+ .required()
270
+ .example(993)
271
+ .description('Service port number')
272
+ .label('IMAP port'),
273
+ imap_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 993').label('IMAP TLS'),
274
+ imap_disabled: formBoolean()
275
+ .default(false)
276
+ .example(true)
277
+ .description('Disable IMAP if you are using this email account to only send emails.')
278
+ .label('IMAP disabled'),
279
+ smtp_auth_user: Joi.string().empty('').trim().max(1024).required(),
280
+ smtp_auth_pass: Joi.string().empty('').max(1024).required(),
281
+ smtp_host: Joi.string().hostname().required().example('smtp.gmail.com').description('Hostname to connect to').label('SMTP host'),
282
+ smtp_port: Joi.number()
283
+ .integer()
284
+ .min(1)
285
+ .max(64 * 1024)
286
+ .required()
287
+ .example(465)
288
+ .description('Service port number')
289
+ .label('SMTP port'),
290
+ smtp_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('SMTP TLS')
291
+ };
292
+
293
+ // The names above, in declaration order, for the checking page's hidden inputs - so the field set
294
+ // it posts is the one this schema declares rather than a second copy written out in the template.
295
+ const connectionFieldNames = Object.keys(connectionFields);
296
+
297
+ // Values validated against the fields above, ignoring everything else the form values carry
298
+ // (the signed blob, the address, the typed password, the app-password hint).
299
+ const connectionFieldsSchema = Joi.object(connectionFields).unknown();
300
+
301
+ // Whether autodiscovery gave the form enough to configure an account without asking the visitor
302
+ // for anything more. Two decisions read it: the settings page auto-runs its connection check on
303
+ // load, and a setup link issued with skipServerSettings skips that page altogether. One answer,
304
+ // because the skip turns a wrong one into an account created from settings nobody looked at.
305
+ //
306
+ // Asked of the schema rather than of a hand-kept list of required names - the shape that has to
307
+ // be kept in sync by hand, and the reason rebuildFormValues above rebuilds from the schema too.
308
+ // So "complete" means exactly "the create endpoint would accept this": a field added or made
309
+ // required there moves both decisions with it, and a discovered value the schema rejects (an
310
+ // address literal where a hostname is required) falls back to the form rather than skipping
311
+ // ahead to a submit that would 400.
312
+ //
313
+ // `_source` is the part no schema can answer. The usernames and passwords are filled in from
314
+ // what the visitor typed whatever autodiscovery found, so without it a domain that resolved to
315
+ // nothing would look complete on the strength of the password alone.
316
+ const hasCompleteServerSettings = values => !!(values && values._source) && !connectionFieldsSchema.validate(values, { convert: true }).error;
317
+
318
+ // Rebuild safe re-render values from the SAME schema that validated the submission: convert coerces the
319
+ // tri-state TLS/disabled checkboxes to real booleans (so {{#if values.X}} cannot re-check a box from the
320
+ // string 'false'), and stripUnknown drops unexpected / prototype keys (and the appPassword_* hint fields)
321
+ // before they can reach the unescaped template sinks. Keys that FAILED validation are dropped too: Joi
322
+ // keeps the raw submitted value for a failed coercion (e.g. the string 'no' for a tri-state boolean, or
323
+ // an array from duplicated form fields), and rendering that raw value would re-check a cleared checkbox
324
+ // or corrupt the hidden data/sig inputs - a failed key re-renders empty instead. The named secret fields
325
+ // are then dropped so a plaintext credential is never echoed back into the HTML. `value` is null when
326
+ // request.payload is null (a bodyless POST), so fall back to {} before mutating.
327
+ const rebuildFormValues = (schema, payload, secretFields) => {
328
+ const { value, error } = schema.validate(payload, { convert: true, stripUnknown: true, abortEarly: false });
329
+ const values = value || {};
330
+ if (error && error.details) {
331
+ for (let detail of error.details) {
332
+ if (detail.path && detail.path.length) {
333
+ delete values[detail.path[0]];
334
+ }
335
+ }
336
+ }
337
+ for (let field of secretFields || []) {
338
+ delete values[field];
339
+ }
340
+ return values;
341
+ };
342
+
343
+ // Bound the number of outbound-probe requests per issued form blob, shared by the auth:false endpoints
344
+ // that drive outbound network from an attacker-controllable host/domain: POST /accounts/new/imap
345
+ // (email autodiscovery) and POST /accounts/new/imap/test (connection test). Both authorize by signature
346
+ // but do not consume the single-use nonce, so without this a leaked signed link is an unlimited
347
+ // SSRF/port-scan oracle. One shared counter per nonce means pivoting between the two endpoints cannot
348
+ // reset the cap. Fail open on a Redis error - the cap is defense-in-depth, not correctness.
349
+ const enforceFormProbeLimit = async (nonce, gt, logger) => {
350
+ let count = 0;
351
+ try {
352
+ const counted = await atomicIncrement(redis, `${REDIS_PREFIX}account:form:probe:${nonce}`, 1, Math.floor(MAX_FORM_TTL / 1000));
353
+ if (counted.success) {
354
+ count = counted.value;
355
+ }
356
+ } catch (err) {
357
+ logger.error({ msg: 'Failed to count outbound form probes', err });
358
+ }
359
+ if (count > MAX_FORM_PROBE_ATTEMPTS) {
360
+ // The cap is keyed on the nonce inside the signed blob, so reloading the same link keeps the
361
+ // same nonce and stays capped - the caller needs a freshly issued setup link.
362
+ //
363
+ // Reviewed, accepted (do not "fix" by removing the cap): for an API-issued link the end user
364
+ // cannot self-recover once exhausted and must go back to the integrator for a fresh link. This
365
+ // is bounded by the link's <=24h TTL, the account-creating submit itself does not draw from the
366
+ // budget, and the app-password hint memo (APP_PASSWORD_HINT_CACHE) keeps error re-renders from
367
+ // burning it on cosmetics. If this ever bites real users, tune MAX_FORM_PROBE_ATTEMPTS or scope
368
+ // the budget per-endpoint rather than dropping the SSRF/port-scan defense.
369
+ throw Boom.boomify(new Error(gt.gettext('Too many attempts for this setup link. Request a new setup link to continue.')), { statusCode: 429 });
370
+ }
371
+ };
372
+
373
+ // The authorization gate for every outbound-probe-driving call in this file: a valid signed blob
374
+ // WITH a nonce (requireNonce guarantees data.n) plus the shared per-nonce probe cap. Keep the two
375
+ // paired through this helper - a probe site that checks the signature but skips the cap silently
376
+ // reopens the unbounded-probe hole. Throws Boom 403/429; returns the parsed blob.
377
+ const authorizeSignedProbe = async (payload, gt, logger) => {
378
+ const data = await parseSignedFormData(redis, payload, gt, { requireNonce: true });
379
+ await enforceFormProbeLimit(data.n, gt, logger);
380
+ return data;
381
+ };
382
+
383
+ // Re-derive the app-password hint for a settings form that is being rendered from posted values
384
+ // rather than from a fresh autodiscovery result, and merge it into those values.
385
+ //
386
+ // serverFormSchema does not carry the appPassword_* fields (they feed unescaped template sinks),
387
+ // so stripUnknown drops them and they cannot be carried in a hidden input - echoing a
388
+ // client-controlled hint into the page was an XSS vector. The hint is therefore rebuilt here from
389
+ // the (trusted) email, out of a static table, never from the submitted payload.
390
+ //
391
+ // Shared by the failAction re-render and by the checking page's hand-off to the settings form, so
392
+ // a form reached either way shows the same "Application Password" label and instructions.
393
+ //
394
+ // Try the static domain table first: it is synchronous, needs no network, and covers the
395
+ // canonical provider domains, so a common-domain render costs no Redis round trips, no DNS, and
396
+ // no probe budget. Never throws - the hint is cosmetic and a failAction must not throw.
397
+ const applyAppPasswordHint = async (values, request, parsedBlob) => {
398
+ if (!values.email) {
399
+ return;
400
+ }
401
+
402
+ let appPassword = getAppPassword(values.email, false, request.app.gt);
403
+
404
+ // Custom-domain fallback (e.g. Google Workspace / M365 on their own domain) needs an MX
405
+ // lookup. failAction runs BEFORE the handler's signature gate, and the lookup drives outbound
406
+ // DNS, so gate it with the SAME machinery as the handler siblings, not a bare signature
407
+ // check: authorizeSignedProbe rejects a signature-only blob (e.g. a leaked tracking/
408
+ // unsubscribe blob) and one past its TTL, and bounds how many lookups one signed link can
409
+ // drive. Without it, any holder of any validly-signed blob could turn this render into an
410
+ // unbounded DNS oracle. On a normal validation-error re-render the nonce is not yet consumed
411
+ // (the create handler claims it only on success), so the hint still shows. values.data /
412
+ // values.sig are the schema-validated copies - rebuildFormValues drops them when malformed
413
+ // (e.g. duplicated fields).
414
+ if (!appPassword && values.data && values.sig) {
415
+ // Consult the per-domain memo BEFORE the probe/DNS work: a repeat re-submit of the same
416
+ // email must not re-run the MX lookup or draw the probe budget again.
417
+ const domain = values.email.split('@').pop().trim().toLowerCase();
418
+ const cached = getCachedAppPasswordHint(domain);
419
+ if (cached) {
420
+ appPassword = cached.value;
421
+ } else {
422
+ try {
423
+ if (parsedBlob) {
424
+ // Already parsed and signature-checked by the caller, so only the cap is left
425
+ // to apply - re-parsing would mean a second serviceSecret read and HMAC check
426
+ await enforceFormProbeLimit(parsedBlob.n, request.app.gt, request.logger);
427
+ } else {
428
+ await authorizeSignedProbe({ data: values.data, sig: values.sig }, request.app.gt, request.logger);
429
+ }
430
+ appPassword = await resolveAppPassword(values.email, request.app.gt);
431
+ // Cache the outcome (including a falsy "no hint" result) so subsequent renders for
432
+ // this domain are free.
433
+ setCachedAppPasswordHint(domain, appPassword);
434
+ } catch (err) {
435
+ // A rejected/expired blob, an exhausted probe cap, or a lookup failure must never
436
+ // break the render. Do NOT cache on failure - an exhausted probe cap or transient
437
+ // DNS error should not poison the hint for the whole TTL.
438
+ request.logger.debug({ msg: 'Failed to resolve app-password hint for form re-render', err });
439
+ }
440
+ }
441
+ }
442
+
443
+ if (appPassword) {
444
+ Object.assign(values, flattenObjectKeys({ appPassword }));
445
+ }
446
+ };
447
+
448
+ // The expectation that applies to a parsed form blob (lib/account/expected-identity.js owns the
449
+ // precedence and the lazy Redis fallback).
450
+ const resolveFormExpectation = data => resolveExpectedIdentity(redis, { account: data.account, blobExpectation: data.expectedEmail });
451
+
452
+ // Expected identity gate for the IMAP arm, mirroring the one the OAuth callback applies in
453
+ // workers/api.js.
454
+ //
455
+ // The evidence here is only the address typed into the form. Working credentials do not prove that
456
+ // the address belongs to the mailbox behind them, so this enforces "the account is registered under
457
+ // the expected address" and nothing stronger - which is exactly what the field documents. Without it
458
+ // the constraint would be trivially sidestepped by choosing the IMAP tab on a form that also offers
459
+ // OAuth2.
460
+ //
461
+ // Returns { expectedEmail, matched } rather than throwing so the caller can name the address that was
462
+ // actually used when it reports the rejection.
463
+ const checkExpectedIdentity = async (data, submittedEmail) => {
464
+ const expectedEmail = await resolveFormExpectation(data);
465
+ return { expectedEmail, matched: !expectedEmail || matchesExpectedIdentity(expectedEmail, [submittedEmail]) };
466
+ };
467
+
468
+ // Stop the flow with a way back rather than a redirect to the calling application: entering the wrong
469
+ // address is correctable, and the hosted form only ever redirects on success. The OAuth arm renders
470
+ // the same view (workers/api.js), differing only in where "try again" points.
471
+ //
472
+ // type=imap keeps the user on the arm they already chose: without it /accounts/new re-asks the
473
+ // provider question and offers OAuth apps they passed over. The signed blob is still unspent (the
474
+ // nonce is claimed only on success), so the link works, and the form it returns to prefills the
475
+ // pinned address read-only.
476
+ const renderIdentityError = (request, h, expectedEmail, actualEmail) =>
477
+ identityErrorView(request, h, {
478
+ expectedEmail,
479
+ actualEmail,
480
+ retryUrl: `/accounts/new?data=${encodeURIComponent(request.payload.data)}&sig=${encodeURIComponent(request.payload.sig)}&type=imap`
481
+ });
482
+
483
+ // Shared by this route's payload validation and its failAction re-render, so the re-rendered form
484
+ // is built from the same schema that validated the submission and cannot drift from it (unlike the
485
+ // earlier hand-maintained truthy Set, which had to be kept in sync by hand).
486
+ const serverFormSchema = Joi.object({
487
+ ...signedBlobFields,
488
+ name: Joi.string().empty('').max(256).example('John Smith').description('Account Name'),
489
+ tz: Joi.string().empty('').max(100).example('Europe/Tallinn').description('Optional timezone for autogenerated date strings'),
490
+ email: Joi.string().email().required().example('user@example.com').label('Email').description('Your account email'),
491
+ ...connectionFields
492
+ });
493
+
494
+ function registerGetAccounts(server, args) {
495
+ const { call } = args;
147
496
 
148
497
  server.route({
149
498
  method: 'GET',
@@ -296,15 +645,19 @@ function init(args) {
296
645
  }
297
646
  }
298
647
  });
648
+ }
649
+
650
+ // The data behind the account picker (views/partials/ui/account-picker.hbs), which every admin
651
+ // form that binds something to one account renders. A search endpoint rather than a list
652
+ // shipped with the page: an instance can hold far more accounts than a page could usefully
653
+ // carry, and the whole point of the control is that a person types part of what they are
654
+ // looking for.
655
+ //
656
+ // No auth options of its own: it inherits the admin surface's session default, exactly like the
657
+ // listing it is a narrower view of, and it exposes nothing that listing does not.
658
+ function registerGetAccountsSuggestions(server, args) {
659
+ const { call } = args;
299
660
 
300
- // The data behind the account picker (views/partials/ui/account-picker.hbs), which every admin
301
- // form that binds something to one account renders. A search endpoint rather than a list
302
- // shipped with the page: an instance can hold far more accounts than a page could usefully
303
- // carry, and the whole point of the control is that a person types part of what they are
304
- // looking for.
305
- //
306
- // No auth options of its own: it inherits the admin surface's session default, exactly like the
307
- // listing it is a narrower view of, and it exposes nothing that listing does not.
308
661
  server.route({
309
662
  method: 'GET',
310
663
  path: '/admin/accounts/suggestions',
@@ -338,7 +691,9 @@ function init(args) {
338
691
  }
339
692
  }
340
693
  });
694
+ }
341
695
 
696
+ function registerPostAccountsNew(server) {
342
697
  server.route({
343
698
  method: 'POST',
344
699
  path: '/admin/accounts/new',
@@ -400,112 +755,15 @@ function init(args) {
400
755
  }
401
756
  }
402
757
  });
758
+ }
403
759
 
404
- async function accountFormHandler(request, h) {
405
- // Intentionally parsed WITHOUT requireNonce (unlike the IMAP-arm endpoints). This OAuth entry must
406
- // keep accepting legacy / pre-upgrade re-auth blobs that carry no n/t - requiring a nonce here
407
- // would 403 the account page's "Re-authenticate" button across a rolling upgrade and break
408
- // still-circulating pre-v2.39 OAuth setup links. Replay safety is enforced downstream instead: the
409
- // OAuth callback (workers/api.js) claims the form nonce atomically (SET NX before create) when one
410
- // is present. Do NOT add requireNonce here without re-checking that compat impact.
411
- const data = await parseSignedFormData(redis, request.payload, request.app.gt);
412
-
413
- const oauth2App = await oauth2Apps.get(request.payload.type);
414
-
415
- if (oauth2App && oauth2App.enabled) {
416
- // prepare account entry
417
-
418
- let accountData = {
419
- account: data.account
420
- };
421
-
422
- for (let key of ['name', 'email', 'path']) {
423
- if (data[key]) {
424
- accountData[key] = data[key];
425
- }
426
- }
427
-
428
- accountData.notifyFrom = data.notifyFrom || new Date().toISOString();
429
-
430
- for (let key of ['redirectUrl', 'expectedEmail', 'n', 't']) {
431
- if (!accountData._meta) {
432
- accountData._meta = {};
433
- }
434
- accountData._meta[key] = data[key];
435
- }
436
-
437
- if (data.delegated) {
438
- accountData.delegated = true;
439
- } else {
440
- accountData.copy = false;
441
- }
442
-
443
- accountData.oauth2 = {
444
- provider: oauth2App.id
445
- };
446
-
447
- // throws if invalid or unknown app ID
448
- const oAuth2Client = await oauth2Apps.getClient(oauth2App.id);
449
-
450
- const nonce = data.n || crypto.randomBytes(NONCE_BYTES).toString('base64url');
451
-
452
- // Validate nonce format (base64url, 21-22 chars; also accept base64 for backward compatibility)
453
- if (!/^[A-Za-z0-9_\-+/]{21,22}={0,2}$/.test(nonce)) {
454
- throw Boom.badRequest('Invalid nonce format. Please generate a new authentication URL.');
455
- }
456
-
457
- // store account data with atomic SET + EX
458
- await redis.set(`${REDIS_PREFIX}account:add:${nonce}`, JSON.stringify(accountData), 'EX', Math.floor(MAX_FORM_TTL / 1000));
459
-
460
- // Generate the url that will be used for the consent dialog.
461
-
462
- let requestPayload = {
463
- state: `account:add:${nonce}`
464
- };
465
-
466
- if (accountData.email) {
467
- requestPayload.email = accountData.email;
468
- }
469
-
470
- // Service providers use client_credentials - no interactive authorization
471
- if (SERVICE_ACCOUNT_PROVIDERS.has(oAuth2Client.provider)) {
472
- throw Boom.badRequest('Application-only OAuth providers do not support interactive authorization');
473
- }
474
-
475
- let authorizeUrl = oAuth2Client.generateAuthUrl(requestPayload);
476
-
477
- return h.redirect(authorizeUrl);
478
- }
479
-
480
- const expectedEmail = await resolveFormExpectation(data);
481
-
482
- return h.view(
483
- 'accounts/register/imap',
484
- {
485
- pageTitleFull: request.app.gt.gettext('Email Account Setup'),
486
- values: {
487
- data: request.payload.data,
488
- sig: request.payload.sig,
489
-
490
- // A pinned link fixes the address, so prefill from the expectation rather than from the
491
- // editable hint and mark it read-only. Cosmetic - the endpoints below enforce it.
492
- email: expectedEmail || data.email,
493
- emailPinned: !!expectedEmail,
494
- name: data.name
495
- }
496
- },
497
- {
498
- layout: 'public'
499
- }
500
- );
501
- }
502
-
503
- // signedBlobFields (the base64url data + HMAC sig carried by every hosted-form page) is imported from
504
- // lib/schemas.js as signedFormBlobFields and spread into each schema below, so the security-relevant
505
- // field definitions cannot drift across the auth:false endpoints (or from the sibling unsubscribe-routes
506
- // copy). Both fields are required: every issuer signs unconditionally and every template renders the sig
507
- // hidden input, so a request without one is always hand-crafted.
760
+ // signedBlobFields (the base64url data + HMAC sig carried by every hosted-form page) is imported from
761
+ // lib/schemas.js as signedFormBlobFields and spread into each schema below, so the security-relevant
762
+ // field definitions cannot drift across the auth:false endpoints (or from the sibling unsubscribe-routes
763
+ // copy). Both fields are required: every issuer signs unconditionally and every template renders the sig
764
+ // hidden input, so a request without one is always hand-crafted.
508
765
 
766
+ function registerGetHostedAccountsNew(server) {
509
767
  server.route({
510
768
  method: 'GET',
511
769
  path: '/accounts/new',
@@ -565,7 +823,9 @@ function init(args) {
565
823
  }
566
824
  }
567
825
  });
826
+ }
568
827
 
828
+ function registerPostHostedAccountsNew(server) {
569
829
  server.route({
570
830
  method: 'POST',
571
831
  path: '/accounts/new',
@@ -604,256 +864,9 @@ function init(args) {
604
864
  }
605
865
  }
606
866
  });
867
+ }
607
868
 
608
- // Shared by this route's payload validation and its failAction re-render (same rationale as
609
- // serverFormSchema below), so the re-rendered first page is built from the same schema that validated
610
- // the submission rather than echoing the raw payload.
611
- const firstPageSchema = Joi.object({
612
- ...signedBlobFields,
613
- name: Joi.string().empty('').max(256).example('John Smith').description('Account Name'),
614
- email: Joi.string().email().required().example('user@example.com').label('Email').description('Your account email'),
615
- password: Joi.string().max(1024).min(1).required().example('secret').label('Password').description('Your account password')
616
- });
617
-
618
- // Shared IMAP/SMTP connection fields for the hosted form's /imap/test and /imap/server routes, so the
619
- // two payload schemas (and their failAction re-renders) are built from one definition and cannot drift.
620
- // The tri-state booleans list '0' as falsy (a string a non-browser client may submit symmetric with the
621
- // truthy '1'); without it '0' would fail coercion and re-render a checkbox as checked.
622
- const connectionFields = {
623
- imap_auth_user: Joi.string().empty('').trim().max(1024).required(),
624
- imap_auth_pass: Joi.string().empty('').max(1024).required(),
625
- imap_host: Joi.string().hostname().required().example('imap.gmail.com').description('Hostname to connect to').label('IMAP host'),
626
- imap_port: Joi.number()
627
- .integer()
628
- .min(1)
629
- .max(64 * 1024)
630
- .required()
631
- .example(993)
632
- .description('Service port number')
633
- .label('IMAP port'),
634
- imap_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 993').label('IMAP TLS'),
635
- imap_disabled: formBoolean()
636
- .default(false)
637
- .example(true)
638
- .description('Disable IMAP if you are using this email account to only send emails.')
639
- .label('IMAP disabled'),
640
- smtp_auth_user: Joi.string().empty('').trim().max(1024).required(),
641
- smtp_auth_pass: Joi.string().empty('').max(1024).required(),
642
- smtp_host: Joi.string().hostname().required().example('smtp.gmail.com').description('Hostname to connect to').label('SMTP host'),
643
- smtp_port: Joi.number()
644
- .integer()
645
- .min(1)
646
- .max(64 * 1024)
647
- .required()
648
- .example(465)
649
- .description('Service port number')
650
- .label('SMTP port'),
651
- smtp_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('SMTP TLS')
652
- };
653
-
654
- // The names above, in declaration order, for the checking page's hidden inputs - so the field set
655
- // it posts is the one this schema declares rather than a second copy written out in the template.
656
- const connectionFieldNames = Object.keys(connectionFields);
657
-
658
- // Values validated against the fields above, ignoring everything else the form values carry
659
- // (the signed blob, the address, the typed password, the app-password hint).
660
- const connectionFieldsSchema = Joi.object(connectionFields).unknown();
661
-
662
- // Whether autodiscovery gave the form enough to configure an account without asking the visitor
663
- // for anything more. Two decisions read it: the settings page auto-runs its connection check on
664
- // load, and a setup link issued with skipServerSettings skips that page altogether. One answer,
665
- // because the skip turns a wrong one into an account created from settings nobody looked at.
666
- //
667
- // Asked of the schema rather than of a hand-kept list of required names - the shape that has to
668
- // be kept in sync by hand, and the reason rebuildFormValues above rebuilds from the schema too.
669
- // So "complete" means exactly "the create endpoint would accept this": a field added or made
670
- // required there moves both decisions with it, and a discovered value the schema rejects (an
671
- // address literal where a hostname is required) falls back to the form rather than skipping
672
- // ahead to a submit that would 400.
673
- //
674
- // `_source` is the part no schema can answer. The usernames and passwords are filled in from
675
- // what the visitor typed whatever autodiscovery found, so without it a domain that resolved to
676
- // nothing would look complete on the strength of the password alone.
677
- const hasCompleteServerSettings = values => !!(values && values._source) && !connectionFieldsSchema.validate(values, { convert: true }).error;
678
-
679
- // Rebuild safe re-render values from the SAME schema that validated the submission: convert coerces the
680
- // tri-state TLS/disabled checkboxes to real booleans (so {{#if values.X}} cannot re-check a box from the
681
- // string 'false'), and stripUnknown drops unexpected / prototype keys (and the appPassword_* hint fields)
682
- // before they can reach the unescaped template sinks. Keys that FAILED validation are dropped too: Joi
683
- // keeps the raw submitted value for a failed coercion (e.g. the string 'no' for a tri-state boolean, or
684
- // an array from duplicated form fields), and rendering that raw value would re-check a cleared checkbox
685
- // or corrupt the hidden data/sig inputs - a failed key re-renders empty instead. The named secret fields
686
- // are then dropped so a plaintext credential is never echoed back into the HTML. `value` is null when
687
- // request.payload is null (a bodyless POST), so fall back to {} before mutating.
688
- const rebuildFormValues = (schema, payload, secretFields) => {
689
- const { value, error } = schema.validate(payload, { convert: true, stripUnknown: true, abortEarly: false });
690
- const values = value || {};
691
- if (error && error.details) {
692
- for (let detail of error.details) {
693
- if (detail.path && detail.path.length) {
694
- delete values[detail.path[0]];
695
- }
696
- }
697
- }
698
- for (let field of secretFields || []) {
699
- delete values[field];
700
- }
701
- return values;
702
- };
703
-
704
- // Bound the number of outbound-probe requests per issued form blob, shared by the auth:false endpoints
705
- // that drive outbound network from an attacker-controllable host/domain: POST /accounts/new/imap
706
- // (email autodiscovery) and POST /accounts/new/imap/test (connection test). Both authorize by signature
707
- // but do not consume the single-use nonce, so without this a leaked signed link is an unlimited
708
- // SSRF/port-scan oracle. One shared counter per nonce means pivoting between the two endpoints cannot
709
- // reset the cap. Fail open on a Redis error - the cap is defense-in-depth, not correctness.
710
- const enforceFormProbeLimit = async (nonce, gt, logger) => {
711
- let count = 0;
712
- try {
713
- const counted = await atomicIncrement(redis, `${REDIS_PREFIX}account:form:probe:${nonce}`, 1, Math.floor(MAX_FORM_TTL / 1000));
714
- if (counted.success) {
715
- count = counted.value;
716
- }
717
- } catch (err) {
718
- logger.error({ msg: 'Failed to count outbound form probes', err });
719
- }
720
- if (count > MAX_FORM_PROBE_ATTEMPTS) {
721
- // The cap is keyed on the nonce inside the signed blob, so reloading the same link keeps the
722
- // same nonce and stays capped - the caller needs a freshly issued setup link.
723
- //
724
- // Reviewed, accepted (do not "fix" by removing the cap): for an API-issued link the end user
725
- // cannot self-recover once exhausted and must go back to the integrator for a fresh link. This
726
- // is bounded by the link's <=24h TTL, the account-creating submit itself does not draw from the
727
- // budget, and the app-password hint memo (APP_PASSWORD_HINT_CACHE) keeps error re-renders from
728
- // burning it on cosmetics. If this ever bites real users, tune MAX_FORM_PROBE_ATTEMPTS or scope
729
- // the budget per-endpoint rather than dropping the SSRF/port-scan defense.
730
- throw Boom.boomify(new Error(gt.gettext('Too many attempts for this setup link. Request a new setup link to continue.')), { statusCode: 429 });
731
- }
732
- };
733
-
734
- // The authorization gate for every outbound-probe-driving call in this file: a valid signed blob
735
- // WITH a nonce (requireNonce guarantees data.n) plus the shared per-nonce probe cap. Keep the two
736
- // paired through this helper - a probe site that checks the signature but skips the cap silently
737
- // reopens the unbounded-probe hole. Throws Boom 403/429; returns the parsed blob.
738
- const authorizeSignedProbe = async (payload, gt, logger) => {
739
- const data = await parseSignedFormData(redis, payload, gt, { requireNonce: true });
740
- await enforceFormProbeLimit(data.n, gt, logger);
741
- return data;
742
- };
743
-
744
- // Re-derive the app-password hint for a settings form that is being rendered from posted values
745
- // rather than from a fresh autodiscovery result, and merge it into those values.
746
- //
747
- // serverFormSchema does not carry the appPassword_* fields (they feed unescaped template sinks),
748
- // so stripUnknown drops them and they cannot be carried in a hidden input - echoing a
749
- // client-controlled hint into the page was an XSS vector. The hint is therefore rebuilt here from
750
- // the (trusted) email, out of a static table, never from the submitted payload.
751
- //
752
- // Shared by the failAction re-render and by the checking page's hand-off to the settings form, so
753
- // a form reached either way shows the same "Application Password" label and instructions.
754
- //
755
- // Try the static domain table first: it is synchronous, needs no network, and covers the
756
- // canonical provider domains, so a common-domain render costs no Redis round trips, no DNS, and
757
- // no probe budget. Never throws - the hint is cosmetic and a failAction must not throw.
758
- const applyAppPasswordHint = async (values, request, parsedBlob) => {
759
- if (!values.email) {
760
- return;
761
- }
762
-
763
- let appPassword = getAppPassword(values.email, false, request.app.gt);
764
-
765
- // Custom-domain fallback (e.g. Google Workspace / M365 on their own domain) needs an MX
766
- // lookup. failAction runs BEFORE the handler's signature gate, and the lookup drives outbound
767
- // DNS, so gate it with the SAME machinery as the handler siblings, not a bare signature
768
- // check: authorizeSignedProbe rejects a signature-only blob (e.g. a leaked tracking/
769
- // unsubscribe blob) and one past its TTL, and bounds how many lookups one signed link can
770
- // drive. Without it, any holder of any validly-signed blob could turn this render into an
771
- // unbounded DNS oracle. On a normal validation-error re-render the nonce is not yet consumed
772
- // (the create handler claims it only on success), so the hint still shows. values.data /
773
- // values.sig are the schema-validated copies - rebuildFormValues drops them when malformed
774
- // (e.g. duplicated fields).
775
- if (!appPassword && values.data && values.sig) {
776
- // Consult the per-domain memo BEFORE the probe/DNS work: a repeat re-submit of the same
777
- // email must not re-run the MX lookup or draw the probe budget again.
778
- const domain = values.email.split('@').pop().trim().toLowerCase();
779
- const cached = getCachedAppPasswordHint(domain);
780
- if (cached) {
781
- appPassword = cached.value;
782
- } else {
783
- try {
784
- if (parsedBlob) {
785
- // Already parsed and signature-checked by the caller, so only the cap is left
786
- // to apply - re-parsing would mean a second serviceSecret read and HMAC check
787
- await enforceFormProbeLimit(parsedBlob.n, request.app.gt, request.logger);
788
- } else {
789
- await authorizeSignedProbe({ data: values.data, sig: values.sig }, request.app.gt, request.logger);
790
- }
791
- appPassword = await resolveAppPassword(values.email, request.app.gt);
792
- // Cache the outcome (including a falsy "no hint" result) so subsequent renders for
793
- // this domain are free.
794
- setCachedAppPasswordHint(domain, appPassword);
795
- } catch (err) {
796
- // A rejected/expired blob, an exhausted probe cap, or a lookup failure must never
797
- // break the render. Do NOT cache on failure - an exhausted probe cap or transient
798
- // DNS error should not poison the hint for the whole TTL.
799
- request.logger.debug({ msg: 'Failed to resolve app-password hint for form re-render', err });
800
- }
801
- }
802
- }
803
-
804
- if (appPassword) {
805
- Object.assign(values, flattenObjectKeys({ appPassword }));
806
- }
807
- };
808
-
809
- // The expectation that applies to a parsed form blob (lib/account/expected-identity.js owns the
810
- // precedence and the lazy Redis fallback).
811
- const resolveFormExpectation = data => resolveExpectedIdentity(redis, { account: data.account, blobExpectation: data.expectedEmail });
812
-
813
- // Expected identity gate for the IMAP arm, mirroring the one the OAuth callback applies in
814
- // workers/api.js.
815
- //
816
- // The evidence here is only the address typed into the form. Working credentials do not prove that
817
- // the address belongs to the mailbox behind them, so this enforces "the account is registered under
818
- // the expected address" and nothing stronger - which is exactly what the field documents. Without it
819
- // the constraint would be trivially sidestepped by choosing the IMAP tab on a form that also offers
820
- // OAuth2.
821
- //
822
- // Returns { expectedEmail, matched } rather than throwing so the caller can name the address that was
823
- // actually used when it reports the rejection.
824
- const checkExpectedIdentity = async (data, submittedEmail) => {
825
- const expectedEmail = await resolveFormExpectation(data);
826
- return { expectedEmail, matched: !expectedEmail || matchesExpectedIdentity(expectedEmail, [submittedEmail]) };
827
- };
828
-
829
- // Stop the flow with a way back rather than a redirect to the calling application: entering the wrong
830
- // address is correctable, and the hosted form only ever redirects on success. The OAuth arm renders
831
- // the same view (workers/api.js), differing only in where "try again" points.
832
- //
833
- // type=imap keeps the user on the arm they already chose: without it /accounts/new re-asks the
834
- // provider question and offers OAuth apps they passed over. The signed blob is still unspent (the
835
- // nonce is claimed only on success), so the link works, and the form it returns to prefills the
836
- // pinned address read-only.
837
- const renderIdentityError = (request, h, expectedEmail, actualEmail) =>
838
- identityErrorView(request, h, {
839
- expectedEmail,
840
- actualEmail,
841
- retryUrl: `/accounts/new?data=${encodeURIComponent(request.payload.data)}&sig=${encodeURIComponent(request.payload.sig)}&type=imap`
842
- });
843
-
844
- // have to use HTML redirect, otherwise samesite=strict cookies are not passed on
845
- const renderRedirect = (request, h, httpRedirectUrl) =>
846
- h.view(
847
- 'redirect',
848
- {
849
- pageTitleFull: request.app.gt.gettext('Email Account Setup'),
850
- httpRedirectUrl
851
- },
852
- {
853
- layout: 'public'
854
- }
855
- );
856
-
869
+ function registerPostHostedImap(server) {
857
870
  server.route({
858
871
  method: 'POST',
859
872
  path: '/accounts/new/imap',
@@ -998,7 +1011,9 @@ function init(args) {
998
1011
  }
999
1012
  }
1000
1013
  });
1014
+ }
1001
1015
 
1016
+ function registerPostHostedImapTest(server) {
1002
1017
  server.route({
1003
1018
  method: 'POST',
1004
1019
  path: '/accounts/new/imap/test',
@@ -1162,25 +1177,16 @@ function init(args) {
1162
1177
  }
1163
1178
  }
1164
1179
  });
1180
+ }
1165
1181
 
1166
- // Shared by this route's payload validation and its failAction re-render, so the re-rendered form
1167
- // is built from the same schema that validated the submission and cannot drift from it (unlike the
1168
- // earlier hand-maintained truthy Set, which had to be kept in sync by hand).
1169
- const serverFormSchema = Joi.object({
1170
- ...signedBlobFields,
1171
- name: Joi.string().empty('').max(256).example('John Smith').description('Account Name'),
1172
- tz: Joi.string().empty('').max(100).example('Europe/Tallinn').description('Optional timezone for autogenerated date strings'),
1173
- email: Joi.string().email().required().example('user@example.com').label('Email').description('Your account email'),
1174
- ...connectionFields
1175
- });
1176
-
1177
- // Where the checking page sends the user when the connection check did not pass: the ordinary
1178
- // server settings form, prefilled with everything that was discovered and typed, so the one wrong
1179
- // field can be corrected. Signature-gated like its siblings because it renders submitted values
1180
- // back into a page. Rendering it drives no outbound connection of its own, so the gate here is
1181
- // the signature and the nonce rather than authorizeSignedProbe; the one thing that can still
1182
- // reach the network is the app-password hint's MX lookup, which draws on the per-nonce probe
1183
- // budget itself and normally answers from the memo page 1 seeded.
1182
+ // Where the checking page sends the user when the connection check did not pass: the ordinary
1183
+ // server settings form, prefilled with everything that was discovered and typed, so the one wrong
1184
+ // field can be corrected. Signature-gated like its siblings because it renders submitted values
1185
+ // back into a page. Rendering it drives no outbound connection of its own, so the gate here is
1186
+ // the signature and the nonce rather than authorizeSignedProbe; the one thing that can still
1187
+ // reach the network is the app-password hint's MX lookup, which draws on the per-nonce probe
1188
+ // budget itself and normally answers from the memo page 1 seeded.
1189
+ function registerPostHostedImapSettings(server) {
1184
1190
  server.route({
1185
1191
  method: 'POST',
1186
1192
  path: '/accounts/new/imap/settings',
@@ -1240,6 +1246,10 @@ function init(args) {
1240
1246
  }
1241
1247
  }
1242
1248
  });
1249
+ }
1250
+
1251
+ function registerPostHostedImapServer(server, args) {
1252
+ const { call } = args;
1243
1253
 
1244
1254
  server.route({
1245
1255
  method: 'POST',
@@ -1298,57 +1308,14 @@ function init(args) {
1298
1308
 
1299
1309
  const accountObject = new Account({ redis, call, secret: await getSecret() });
1300
1310
 
1301
- // Claim the single-use nonce BEFORE creating the account so a concurrent double-submit or
1302
- // a replayed URL cannot create duplicate accounts (SET NX is atomic). parseSignedFormData
1303
- // already rejects a nonce that was fully consumed by an earlier successful submit.
1304
- // requireNonce:true above guarantees data.n and data.t are present.
1305
- // claimFormNonce/releaseFormNonce (lib/tools.js) encapsulate the SET NX + release so the IMAP
1306
- // arm and the OAuth callback (workers/api.js) share one copy of the double-spend semantics.
1307
- let claimed;
1308
- try {
1309
- claimed = await claimFormNonce(redis, data.n, data.t);
1310
- } catch (err) {
1311
- // A Redis failure here is not a consumed nonce. Report it as a retryable server error
1312
- // instead of misdiagnosing a valid setup URL as invalid or expired.
1313
- request.logger.error({ msg: 'Failed to claim nonce for an account form request', err });
1314
- throw Boom.boomify(new Error(request.app.gt.gettext('Temporary error, please try again')), { statusCode: 500 });
1315
- }
1316
- if (!claimed) {
1317
- // SET NX returned null: the nonce key already exists, so this URL was already used.
1318
- //
1319
- // Reviewed, accepted (do not "fix" server-side): the LOSING side of a legitimate concurrent
1320
- // double-submit lands here and sees this 403 even though the winning request created the
1321
- // account. The client-side formSubmitting latch (views/accounts/register/imap-server.hbs) is
1322
- // the primary guard; the residual is a no-JS double-click, and even then this is strictly
1323
- // better than the pre-hardening behavior (two duplicate accounts). A nicer UX (store the
1324
- // created account id under the nonce key and redirect the loser to success) is a possible
1325
- // future enhancement, not a bug.
1326
- throw Boom.boomify(new Error(request.app.gt.gettext('Invalid or expired account setup URL')), { statusCode: 403 });
1327
- }
1328
-
1329
- let result;
1330
- try {
1331
- result = await accountObject.create(accountData);
1332
- } catch (err) {
1333
- // Release the nonce so the user can fix the form and retry. Accepted residual: if
1334
- // Redis fails here too (it likely failed create() as well), the nonce stays consumed
1335
- // for its remaining TTL and the user needs a freshly issued link - the claim-BEFORE-
1336
- // create ordering is what makes the double-submit dedupe atomic, and this narrow
1337
- // crash window is the price of that.
1338
- await releaseFormNonce(redis, data.n, request.logger);
1339
- throw err;
1340
- }
1341
-
1342
- let httpRedirectUrl;
1343
- if (data.redirectUrl) {
1344
- const serviceUrl = await settings.get('serviceUrl');
1345
- const url = new URL(data.redirectUrl, serviceUrl);
1346
- url.searchParams.set('account', result.account);
1347
- url.searchParams.set('state', result.state);
1348
- httpRedirectUrl = url.href;
1349
- } else {
1350
- httpRedirectUrl = adminUrl`/admin/accounts/${result.account}`;
1351
- }
1311
+ // parseSignedFormData already rejects a nonce that was fully consumed by an earlier
1312
+ // successful submit, and requireNonce:true above guarantees data.n and data.t are present.
1313
+ const httpRedirectUrl = await completeAccountSetup(request, {
1314
+ accountObject,
1315
+ accountData,
1316
+ nonce: { n: data.n, t: data.t },
1317
+ redirectUrl: data.redirectUrl
1318
+ });
1352
1319
 
1353
1320
  return renderRedirect(request, h, httpRedirectUrl);
1354
1321
  },
@@ -1405,6 +1372,10 @@ function init(args) {
1405
1372
  }
1406
1373
  }
1407
1374
  });
1375
+ }
1376
+
1377
+ function registerGetAccountsByAccount(server, args) {
1378
+ const { call } = args;
1408
1379
 
1409
1380
  server.route({
1410
1381
  method: 'GET',
@@ -1721,6 +1692,10 @@ function init(args) {
1721
1692
  }
1722
1693
  }
1723
1694
  });
1695
+ }
1696
+
1697
+ function registerPostAccountsDelete(server, args) {
1698
+ const { call } = args;
1724
1699
 
1725
1700
  server.route({
1726
1701
  method: 'POST',
@@ -1771,6 +1746,10 @@ function init(args) {
1771
1746
  }
1772
1747
  }
1773
1748
  });
1749
+ }
1750
+
1751
+ function registerPostAccountsReconnect(server, args) {
1752
+ const { call } = args;
1774
1753
 
1775
1754
  server.route({
1776
1755
  method: 'POST',
@@ -1816,37 +1795,32 @@ function init(args) {
1816
1795
  }
1817
1796
  }
1818
1797
  });
1798
+ }
1799
+
1800
+ // Turns an account back on after the auth-failure safety net switched it off. The only admin
1801
+ // UI route that reaches the flag for a Gmail API or Outlook account: their IMAP card, and with
1802
+ // it the "Disable IMAP" checkbox an IMAP account is re-enabled through, is not rendered.
1803
+ //
1804
+ // Shares Account.resumeAfterAuthFailure() with PUT /v1/account/{account}/resume, so it lifts
1805
+ // nothing but the safety net's own disable and cannot be used to un-do an operator's deliberate
1806
+ // send-only switch.
1807
+ function registerPostAccountsResume(server, args) {
1808
+ const { call } = args;
1819
1809
 
1820
- // Turns an account back on after the auth-failure safety net switched it off. The only admin
1821
- // UI route that reaches the flag for a Gmail API or Outlook account: their IMAP card, and with
1822
- // it the "Disable IMAP" checkbox an IMAP account is re-enabled through, is not rendered.
1823
- //
1824
- // Lifts nothing but the safety net's own disable (see Account.clearAuthFailureDisable), so it
1825
- // cannot be used to un-do an operator's deliberate send-only switch.
1826
1810
  server.route({
1827
1811
  method: 'POST',
1828
1812
  path: '/admin/accounts/{account}/resume',
1829
1813
  async handler(request) {
1830
1814
  let account = request.params.account;
1831
1815
  try {
1832
- // clearAuthFailureDisable() needs nothing but the account hash, and the reconnect
1833
- // below is dispatched from this module's own channel
1834
- let accountObject = new Account({ redis, account });
1816
+ // Lifting the disable needs nothing but the account hash, and the reconnect is
1817
+ // dispatched over this module's own channel
1818
+ let accountObject = new Account({ redis, account, call });
1835
1819
 
1836
- if (!(await accountObject.clearAuthFailureDisable())) {
1820
+ if (!(await accountObject.resumeAfterAuthFailure())) {
1837
1821
  return { success: false, error: 'This account was not switched off by EmailEngine' };
1838
1822
  }
1839
1823
 
1840
- request.logger.info({ msg: 'Resumed an account that was switched off after authentication failures', account });
1841
-
1842
- try {
1843
- await call({ cmd: 'reconnect', account });
1844
- } catch (err) {
1845
- // The flag is already lifted, so the account is no longer parked. Losing the
1846
- // dispatch only delays the connection until the next periodic reconnect.
1847
- request.logger.error({ msg: 'Reconnect request failed', action: 'resume_account', account, err });
1848
- }
1849
-
1850
1824
  return { success: true };
1851
1825
  } catch (err) {
1852
1826
  request.logger.error({ msg: 'Failed to resume account', err, account });
@@ -1869,6 +1843,10 @@ function init(args) {
1869
1843
  }
1870
1844
  }
1871
1845
  });
1846
+ }
1847
+
1848
+ function registerPostAccountsSync(server, args) {
1849
+ const { call } = args;
1872
1850
 
1873
1851
  server.route({
1874
1852
  method: 'POST',
@@ -1907,6 +1885,10 @@ function init(args) {
1907
1885
  }
1908
1886
  }
1909
1887
  });
1888
+ }
1889
+
1890
+ function registerPostAccountsLogs(server, args) {
1891
+ const { call } = args;
1910
1892
 
1911
1893
  server.route({
1912
1894
  method: 'POST',
@@ -1954,7 +1936,9 @@ function init(args) {
1954
1936
  }
1955
1937
  }
1956
1938
  });
1939
+ }
1957
1940
 
1941
+ function registerPostAccountsLogsFlush(server) {
1958
1942
  server.route({
1959
1943
  method: 'POST',
1960
1944
  path: '/admin/accounts/{account}/logs-flush',
@@ -1990,7 +1974,9 @@ function init(args) {
1990
1974
  }
1991
1975
  }
1992
1976
  });
1977
+ }
1993
1978
 
1979
+ function registerGetAccountsLogsTxt(server) {
1994
1980
  server.route({
1995
1981
  method: 'GET',
1996
1982
  path: '/admin/accounts/{account}/logs.txt',
@@ -2013,6 +1999,10 @@ function init(args) {
2013
1999
  }
2014
2000
  }
2015
2001
  });
2002
+ }
2003
+
2004
+ function registerGetAccountsBrowse(server, args) {
2005
+ const { call } = args;
2016
2006
 
2017
2007
  server.route({
2018
2008
  method: 'GET',
@@ -2095,6 +2085,10 @@ function init(args) {
2095
2085
  }
2096
2086
  }
2097
2087
  });
2088
+ }
2089
+
2090
+ function registerGetAccountsEdit(server, args) {
2091
+ const { call } = args;
2098
2092
 
2099
2093
  server.route({
2100
2094
  method: 'GET',
@@ -2124,10 +2118,10 @@ function init(args) {
2124
2118
  // explicit request to keep the account off. Unchecked, the connection fields are
2125
2119
  // shown and the save writes `disabled: false`, which lifts the park.
2126
2120
  imap_disabled: (!accountData.imap && !accountData.oauth2) || isOperatorDisabled(accountData),
2127
- imap_tls_ignoreCertErrors: !!(accountData.imap && accountData.imap.tls && accountData.imap.tls.rejectUnauthorized === false),
2121
+ ...securityFormValues('imap', accountData.imap),
2128
2122
  imap_maxIdleTime: imapMaxIdleTimeFormValue(accountData.imap),
2129
2123
  smtp: !!accountData.smtp,
2130
- smtp_tls_ignoreCertErrors: !!(accountData.smtp && accountData.smtp.tls && accountData.smtp.tls.rejectUnauthorized === false),
2124
+ ...securityFormValues('smtp', accountData.smtp),
2131
2125
  oauth2: !!accountData.oauth2,
2132
2126
 
2133
2127
  imap_auth_pass: '',
@@ -2183,6 +2177,10 @@ function init(args) {
2183
2177
  }
2184
2178
  }
2185
2179
  });
2180
+ }
2181
+
2182
+ function registerPostAccountsEdit(server, args) {
2183
+ const { call } = args;
2186
2184
 
2187
2185
  server.route({
2188
2186
  method: 'POST',
@@ -2205,23 +2203,10 @@ function init(args) {
2205
2203
  webhooks: request.payload.webhooks
2206
2204
  };
2207
2205
 
2208
- updates.webhooksCustomHeaders = request.payload.customHeaders
2209
- .split(/[\r\n]+/)
2210
- .map(header => header.trim())
2211
- .filter(header => header)
2212
- .map(line => {
2213
- let sep = line.indexOf(':');
2214
- if (sep >= 0) {
2215
- return {
2216
- key: line.substring(0, sep).trim(),
2217
- value: line.substring(sep + 1).trim()
2218
- };
2219
- }
2220
- return {
2221
- key: line,
2222
- value: ''
2223
- };
2224
- });
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
+ }
2225
2210
 
2226
2211
  if (request.payload.imap) {
2227
2212
  let imapTls = (oldData.imap && oldData.imap.tls) || {};
@@ -2267,9 +2252,7 @@ function init(args) {
2267
2252
  // accounts, so like `secure` these only apply when it was submitted.
2268
2253
  // Written only when the effective state changes - an untouched form
2269
2254
  // save must not add new keys, as any imap diff forces a reconnect
2270
- if (request.payload.imap_tls_ignoreCertErrors !== (imapTls.rejectUnauthorized === false)) {
2271
- imapTls.rejectUnauthorized = !request.payload.imap_tls_ignoreCertErrors;
2272
- }
2255
+ applySecurityForm(request.payload, 'imap', oldData.imap, updateKeys, imapTls);
2273
2256
  if (request.payload.imap_disableIMAP4rev2 !== !!(oldData.imap && oldData.imap.disableIMAP4rev2)) {
2274
2257
  updateKeys.disableIMAP4rev2 = request.payload.imap_disableIMAP4rev2;
2275
2258
  }
@@ -2296,13 +2279,6 @@ function init(args) {
2296
2279
  smtpAuth.pass = request.payload.smtp_auth_pass;
2297
2280
  }
2298
2281
 
2299
- // written only when the effective state changes, and the tls object is
2300
- // skipped while empty - same as the IMAP flags, a no-op save must not
2301
- // modify the stored account
2302
- if (request.payload.smtp_tls_ignoreCertErrors !== (smtpTls.rejectUnauthorized === false)) {
2303
- smtpTls.rejectUnauthorized = !request.payload.smtp_tls_ignoreCertErrors;
2304
- }
2305
-
2306
2282
  updates.smtp = Object.assign(oldData.smtp || {}, {
2307
2283
  host: request.payload.smtp_host,
2308
2284
  port: request.payload.smtp_port,
@@ -2310,6 +2286,11 @@ function init(args) {
2310
2286
  auth: smtpAuth
2311
2287
  });
2312
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
+
2313
2294
  if (Object.keys(smtpTls).length) {
2314
2295
  updates.smtp.tls = smtpTls;
2315
2296
  }
@@ -2442,10 +2423,7 @@ function init(args) {
2442
2423
  .example(993)
2443
2424
  .description('Service port number'),
2444
2425
  imap_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 993'),
2445
- imap_tls_ignoreCertErrors: formBoolean()
2446
- .default(false)
2447
- .example(false)
2448
- .description('Allow connections to servers with invalid TLS certificates for this account'),
2426
+ ...securityFormFields('imap'),
2449
2427
  imap_disableIMAP4rev2: formBoolean().default(false).example(false).description('Do not use IMAP4rev2 even if the server supports it'),
2450
2428
  imap_disabled: formBoolean()
2451
2429
  .default(false)
@@ -2490,10 +2468,7 @@ function init(args) {
2490
2468
  .example(465)
2491
2469
  .description('Service port number'),
2492
2470
  smtp_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465'),
2493
- smtp_tls_ignoreCertErrors: formBoolean()
2494
- .default(false)
2495
- .example(false)
2496
- .description('Allow connections to servers with invalid TLS certificates for this account'),
2471
+ ...securityFormFields('smtp'),
2497
2472
 
2498
2473
  customHeaders: Joi.string()
2499
2474
  .allow('')
@@ -2506,4 +2481,29 @@ function init(args) {
2506
2481
  });
2507
2482
  }
2508
2483
 
2484
+ function init(args) {
2485
+ const { server } = args;
2486
+
2487
+ registerGetAccounts(server, args);
2488
+ registerGetAccountsSuggestions(server, args);
2489
+ registerPostAccountsNew(server);
2490
+ registerGetHostedAccountsNew(server);
2491
+ registerPostHostedAccountsNew(server);
2492
+ registerPostHostedImap(server);
2493
+ registerPostHostedImapTest(server);
2494
+ registerPostHostedImapSettings(server);
2495
+ registerPostHostedImapServer(server, args);
2496
+ registerGetAccountsByAccount(server, args);
2497
+ registerPostAccountsDelete(server, args);
2498
+ registerPostAccountsReconnect(server, args);
2499
+ registerPostAccountsResume(server, args);
2500
+ registerPostAccountsSync(server, args);
2501
+ registerPostAccountsLogs(server, args);
2502
+ registerPostAccountsLogsFlush(server);
2503
+ registerGetAccountsLogsTxt(server);
2504
+ registerGetAccountsBrowse(server, args);
2505
+ registerGetAccountsEdit(server, args);
2506
+ registerPostAccountsEdit(server, args);
2507
+ }
2508
+
2509
2509
  module.exports = init;