emailengine-app 2.84.2 → 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 (86) hide show
  1. package/.ncurc.js +5 -3
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +33 -0
  6. package/Dockerfile +6 -0
  7. package/README.md +1 -1
  8. package/bin/emailengine.js +434 -408
  9. package/copy-static-files.sh +39 -14
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +16562 -0
  12. package/eslint.config.js +81 -99
  13. package/lib/account.js +36 -5
  14. package/lib/api-reference/format.js +4 -3
  15. package/lib/api-routes/account-routes.js +177 -12
  16. package/lib/api-routes/blocklist-routes.js +23 -2
  17. package/lib/api-routes/delivery-test-routes.js +26 -3
  18. package/lib/api-routes/export-routes.js +28 -2
  19. package/lib/api-routes/gateway-routes.js +28 -2
  20. package/lib/api-routes/mailbox-routes.js +41 -2
  21. package/lib/api-routes/message-routes.js +97 -3
  22. package/lib/api-routes/oauth2-app-routes.js +48 -15
  23. package/lib/api-routes/outbox-routes.js +45 -11
  24. package/lib/api-routes/permission-map.js +12 -1
  25. package/lib/api-routes/settings-routes.js +23 -2
  26. package/lib/api-routes/submit-routes.js +336 -309
  27. package/lib/api-routes/template-routes.js +38 -2
  28. package/lib/api-routes/token-routes.js +142 -96
  29. package/lib/api-routes/webhook-route-routes.js +13 -2
  30. package/lib/bounce-detect.js +397 -205
  31. package/lib/consts.js +5 -4
  32. package/lib/email-client/base-client.js +10 -31
  33. package/lib/email-client/gmail-client.js +9 -11
  34. package/lib/email-client/imap/mailbox.js +3 -19
  35. package/lib/email-client/imap/subconnection.js +1 -1
  36. package/lib/email-client/imap-client.js +1 -1
  37. package/lib/email-client/notification-handler.js +1 -2
  38. package/lib/gateway.js +2 -3
  39. package/lib/hapi-request-logger.js +107 -0
  40. package/lib/imapproxy/imap-core/README.md +6 -5
  41. package/lib/mcp/tools.js +37 -8
  42. package/lib/notify-attachments.js +17 -0
  43. package/lib/oauth/outlook-mailbox.js +35 -0
  44. package/lib/oauth/state.js +24 -0
  45. package/lib/oauth2-apps.js +1 -1
  46. package/lib/pbkdf2-phc.js +1 -1
  47. package/lib/schemas.js +1 -1
  48. package/lib/sso.js +1 -1
  49. package/lib/swagger-options.js +1 -1
  50. package/lib/thread-diagnostics.js +46 -0
  51. package/lib/timezones.js +109 -0
  52. package/lib/token-permission-view.js +3 -3
  53. package/lib/tools.js +40 -10
  54. package/lib/totp.js +2 -5
  55. package/lib/translations.js +1 -2
  56. package/lib/ui-routes/account-routes.js +475 -454
  57. package/lib/ui-routes/account-setup.js +99 -0
  58. package/lib/ui-routes/admin-config-routes.js +88 -10
  59. package/lib/ui-routes/admin-entities-routes.js +91 -7
  60. package/lib/ui-routes/auth-routes.js +90 -38
  61. package/lib/ui-routes/internals-routes.js +5 -0
  62. package/lib/ui-routes/oauth-config-routes.js +124 -82
  63. package/lib/ui-routes/route-helpers.js +19 -3
  64. package/lib/ui-routes/tls-config-routes.js +58 -15
  65. package/lib/utils/back-off.js +82 -0
  66. package/lib/utils/murmurhash3.js +66 -0
  67. package/lib/utils/public-suffix.js +122 -0
  68. package/lib/utils/random-id.js +26 -0
  69. package/lib/utils/version.js +74 -0
  70. package/lib/webhook-routing.js +27 -0
  71. package/lib/webhooks.js +41 -6
  72. package/package.json +27 -29
  73. package/sbom.json +7980 -1
  74. package/server.js +634 -441
  75. package/static/licenses.html +181 -1006
  76. package/translations/messages.pot +62 -63
  77. package/views/config/ai.hbs +1 -1
  78. package/views/config/security.hbs +2 -2
  79. package/views/config/service.hbs +3 -0
  80. package/views/internals/index.hbs +8 -0
  81. package/views/partials/webhook_form.hbs +1 -1
  82. package/views/suppression-lists/index.hbs +1 -1
  83. package/workers/api.js +738 -583
  84. package/workers/export.js +1 -1
  85. package/workers/submit.js +1 -1
  86. package/workers/webhooks.js +16 -32
@@ -31,8 +31,6 @@ const {
31
31
  getServiceHostname,
32
32
  getSignedFormData,
33
33
  parseSignedFormData,
34
- claimFormNonce,
35
- releaseFormNonce,
36
34
  getLogs,
37
35
  verifyAccountInfo,
38
36
  flattenObjectKeys,
@@ -52,6 +50,7 @@ const {
52
50
  const {
53
51
  formatAccountData,
54
52
  identityErrorView,
53
+ renderRedirect,
55
54
  ACCOUNT_STATE_DISPLAY,
56
55
  adminUrl,
57
56
  accountSuggestions,
@@ -64,6 +63,8 @@ const { webhooks: Webhooks } = require('../webhooks');
64
63
  const { accountQueueSummary } = require('../queue-browser');
65
64
  const { describeEffectiveRouting, isDeliverableRoute } = require('../webhook-routing');
66
65
  const { matchesExpectedIdentity, resolveExpectedIdentity } = require('../account/expected-identity');
66
+ const { OAUTH_NONCE_PATTERN } = require('../oauth/state');
67
+ const { completeAccountSetup } = require('./account-setup');
67
68
 
68
69
  const { REDIS_PREFIX, DEFAULT_PAGE_SIZE, NONCE_BYTES, MAX_FORM_TTL, MAX_FORM_PROBE_ATTEMPTS } = consts;
69
70
 
@@ -144,8 +145,354 @@ async function getMailboxListing(accountObject) {
144
145
  return mailboxes;
145
146
  }
146
147
 
147
- function init(args) {
148
- 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;
149
496
 
150
497
  server.route({
151
498
  method: 'GET',
@@ -298,15 +645,19 @@ function init(args) {
298
645
  }
299
646
  }
300
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;
301
660
 
302
- // The data behind the account picker (views/partials/ui/account-picker.hbs), which every admin
303
- // form that binds something to one account renders. A search endpoint rather than a list
304
- // shipped with the page: an instance can hold far more accounts than a page could usefully
305
- // carry, and the whole point of the control is that a person types part of what they are
306
- // looking for.
307
- //
308
- // No auth options of its own: it inherits the admin surface's session default, exactly like the
309
- // listing it is a narrower view of, and it exposes nothing that listing does not.
310
661
  server.route({
311
662
  method: 'GET',
312
663
  path: '/admin/accounts/suggestions',
@@ -340,7 +691,9 @@ function init(args) {
340
691
  }
341
692
  }
342
693
  });
694
+ }
343
695
 
696
+ function registerPostAccountsNew(server) {
344
697
  server.route({
345
698
  method: 'POST',
346
699
  path: '/admin/accounts/new',
@@ -402,112 +755,15 @@ function init(args) {
402
755
  }
403
756
  }
404
757
  });
758
+ }
405
759
 
406
- async function accountFormHandler(request, h) {
407
- // Intentionally parsed WITHOUT requireNonce (unlike the IMAP-arm endpoints). This OAuth entry must
408
- // keep accepting legacy / pre-upgrade re-auth blobs that carry no n/t - requiring a nonce here
409
- // would 403 the account page's "Re-authenticate" button across a rolling upgrade and break
410
- // still-circulating pre-v2.39 OAuth setup links. Replay safety is enforced downstream instead: the
411
- // OAuth callback (workers/api.js) claims the form nonce atomically (SET NX before create) when one
412
- // is present. Do NOT add requireNonce here without re-checking that compat impact.
413
- const data = await parseSignedFormData(redis, request.payload, request.app.gt);
414
-
415
- const oauth2App = await oauth2Apps.get(request.payload.type);
416
-
417
- if (oauth2App && oauth2App.enabled) {
418
- // prepare account entry
419
-
420
- let accountData = {
421
- account: data.account
422
- };
423
-
424
- for (let key of ['name', 'email', 'path']) {
425
- if (data[key]) {
426
- accountData[key] = data[key];
427
- }
428
- }
429
-
430
- accountData.notifyFrom = data.notifyFrom || new Date().toISOString();
431
-
432
- for (let key of ['redirectUrl', 'expectedEmail', 'n', 't']) {
433
- if (!accountData._meta) {
434
- accountData._meta = {};
435
- }
436
- accountData._meta[key] = data[key];
437
- }
438
-
439
- if (data.delegated) {
440
- accountData.delegated = true;
441
- } else {
442
- accountData.copy = false;
443
- }
444
-
445
- accountData.oauth2 = {
446
- provider: oauth2App.id
447
- };
448
-
449
- // throws if invalid or unknown app ID
450
- const oAuth2Client = await oauth2Apps.getClient(oauth2App.id);
451
-
452
- const nonce = data.n || crypto.randomBytes(NONCE_BYTES).toString('base64url');
453
-
454
- // Validate nonce format (base64url, 21-22 chars; also accept base64 for backward compatibility)
455
- if (!/^[A-Za-z0-9_\-+/]{21,22}={0,2}$/.test(nonce)) {
456
- throw Boom.badRequest('Invalid nonce format. Please generate a new authentication URL.');
457
- }
458
-
459
- // store account data with atomic SET + EX
460
- await redis.set(`${REDIS_PREFIX}account:add:${nonce}`, JSON.stringify(accountData), 'EX', Math.floor(MAX_FORM_TTL / 1000));
461
-
462
- // Generate the url that will be used for the consent dialog.
463
-
464
- let requestPayload = {
465
- state: `account:add:${nonce}`
466
- };
467
-
468
- if (accountData.email) {
469
- requestPayload.email = accountData.email;
470
- }
471
-
472
- // Service providers use client_credentials - no interactive authorization
473
- if (SERVICE_ACCOUNT_PROVIDERS.has(oAuth2Client.provider)) {
474
- throw Boom.badRequest('Application-only OAuth providers do not support interactive authorization');
475
- }
476
-
477
- let authorizeUrl = oAuth2Client.generateAuthUrl(requestPayload);
478
-
479
- return h.redirect(authorizeUrl);
480
- }
481
-
482
- const expectedEmail = await resolveFormExpectation(data);
483
-
484
- return h.view(
485
- 'accounts/register/imap',
486
- {
487
- pageTitleFull: request.app.gt.gettext('Email Account Setup'),
488
- values: {
489
- data: request.payload.data,
490
- sig: request.payload.sig,
491
-
492
- // A pinned link fixes the address, so prefill from the expectation rather than from the
493
- // editable hint and mark it read-only. Cosmetic - the endpoints below enforce it.
494
- email: expectedEmail || data.email,
495
- emailPinned: !!expectedEmail,
496
- name: data.name
497
- }
498
- },
499
- {
500
- layout: 'public'
501
- }
502
- );
503
- }
504
-
505
- // signedBlobFields (the base64url data + HMAC sig carried by every hosted-form page) is imported from
506
- // lib/schemas.js as signedFormBlobFields and spread into each schema below, so the security-relevant
507
- // field definitions cannot drift across the auth:false endpoints (or from the sibling unsubscribe-routes
508
- // copy). Both fields are required: every issuer signs unconditionally and every template renders the sig
509
- // 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.
510
765
 
766
+ function registerGetHostedAccountsNew(server) {
511
767
  server.route({
512
768
  method: 'GET',
513
769
  path: '/accounts/new',
@@ -567,7 +823,9 @@ function init(args) {
567
823
  }
568
824
  }
569
825
  });
826
+ }
570
827
 
828
+ function registerPostHostedAccountsNew(server) {
571
829
  server.route({
572
830
  method: 'POST',
573
831
  path: '/accounts/new',
@@ -606,256 +864,9 @@ function init(args) {
606
864
  }
607
865
  }
608
866
  });
867
+ }
609
868
 
610
- // Shared by this route's payload validation and its failAction re-render (same rationale as
611
- // serverFormSchema below), so the re-rendered first page is built from the same schema that validated
612
- // the submission rather than echoing the raw payload.
613
- const firstPageSchema = Joi.object({
614
- ...signedBlobFields,
615
- name: Joi.string().empty('').max(256).example('John Smith').description('Account Name'),
616
- email: Joi.string().email().required().example('user@example.com').label('Email').description('Your account email'),
617
- password: Joi.string().max(1024).min(1).required().example('secret').label('Password').description('Your account password')
618
- });
619
-
620
- // Shared IMAP/SMTP connection fields for the hosted form's /imap/test and /imap/server routes, so the
621
- // two payload schemas (and their failAction re-renders) are built from one definition and cannot drift.
622
- // The tri-state booleans list '0' as falsy (a string a non-browser client may submit symmetric with the
623
- // truthy '1'); without it '0' would fail coercion and re-render a checkbox as checked.
624
- const connectionFields = {
625
- imap_auth_user: Joi.string().empty('').trim().max(1024).required(),
626
- imap_auth_pass: Joi.string().empty('').max(1024).required(),
627
- imap_host: Joi.string().hostname().required().example('imap.gmail.com').description('Hostname to connect to').label('IMAP host'),
628
- imap_port: Joi.number()
629
- .integer()
630
- .min(1)
631
- .max(64 * 1024)
632
- .required()
633
- .example(993)
634
- .description('Service port number')
635
- .label('IMAP port'),
636
- imap_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 993').label('IMAP TLS'),
637
- imap_disabled: formBoolean()
638
- .default(false)
639
- .example(true)
640
- .description('Disable IMAP if you are using this email account to only send emails.')
641
- .label('IMAP disabled'),
642
- smtp_auth_user: Joi.string().empty('').trim().max(1024).required(),
643
- smtp_auth_pass: Joi.string().empty('').max(1024).required(),
644
- smtp_host: Joi.string().hostname().required().example('smtp.gmail.com').description('Hostname to connect to').label('SMTP host'),
645
- smtp_port: Joi.number()
646
- .integer()
647
- .min(1)
648
- .max(64 * 1024)
649
- .required()
650
- .example(465)
651
- .description('Service port number')
652
- .label('SMTP port'),
653
- smtp_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('SMTP TLS')
654
- };
655
-
656
- // The names above, in declaration order, for the checking page's hidden inputs - so the field set
657
- // it posts is the one this schema declares rather than a second copy written out in the template.
658
- const connectionFieldNames = Object.keys(connectionFields);
659
-
660
- // Values validated against the fields above, ignoring everything else the form values carry
661
- // (the signed blob, the address, the typed password, the app-password hint).
662
- const connectionFieldsSchema = Joi.object(connectionFields).unknown();
663
-
664
- // Whether autodiscovery gave the form enough to configure an account without asking the visitor
665
- // for anything more. Two decisions read it: the settings page auto-runs its connection check on
666
- // load, and a setup link issued with skipServerSettings skips that page altogether. One answer,
667
- // because the skip turns a wrong one into an account created from settings nobody looked at.
668
- //
669
- // Asked of the schema rather than of a hand-kept list of required names - the shape that has to
670
- // be kept in sync by hand, and the reason rebuildFormValues above rebuilds from the schema too.
671
- // So "complete" means exactly "the create endpoint would accept this": a field added or made
672
- // required there moves both decisions with it, and a discovered value the schema rejects (an
673
- // address literal where a hostname is required) falls back to the form rather than skipping
674
- // ahead to a submit that would 400.
675
- //
676
- // `_source` is the part no schema can answer. The usernames and passwords are filled in from
677
- // what the visitor typed whatever autodiscovery found, so without it a domain that resolved to
678
- // nothing would look complete on the strength of the password alone.
679
- const hasCompleteServerSettings = values => !!(values && values._source) && !connectionFieldsSchema.validate(values, { convert: true }).error;
680
-
681
- // Rebuild safe re-render values from the SAME schema that validated the submission: convert coerces the
682
- // tri-state TLS/disabled checkboxes to real booleans (so {{#if values.X}} cannot re-check a box from the
683
- // string 'false'), and stripUnknown drops unexpected / prototype keys (and the appPassword_* hint fields)
684
- // before they can reach the unescaped template sinks. Keys that FAILED validation are dropped too: Joi
685
- // keeps the raw submitted value for a failed coercion (e.g. the string 'no' for a tri-state boolean, or
686
- // an array from duplicated form fields), and rendering that raw value would re-check a cleared checkbox
687
- // or corrupt the hidden data/sig inputs - a failed key re-renders empty instead. The named secret fields
688
- // are then dropped so a plaintext credential is never echoed back into the HTML. `value` is null when
689
- // request.payload is null (a bodyless POST), so fall back to {} before mutating.
690
- const rebuildFormValues = (schema, payload, secretFields) => {
691
- const { value, error } = schema.validate(payload, { convert: true, stripUnknown: true, abortEarly: false });
692
- const values = value || {};
693
- if (error && error.details) {
694
- for (let detail of error.details) {
695
- if (detail.path && detail.path.length) {
696
- delete values[detail.path[0]];
697
- }
698
- }
699
- }
700
- for (let field of secretFields || []) {
701
- delete values[field];
702
- }
703
- return values;
704
- };
705
-
706
- // Bound the number of outbound-probe requests per issued form blob, shared by the auth:false endpoints
707
- // that drive outbound network from an attacker-controllable host/domain: POST /accounts/new/imap
708
- // (email autodiscovery) and POST /accounts/new/imap/test (connection test). Both authorize by signature
709
- // but do not consume the single-use nonce, so without this a leaked signed link is an unlimited
710
- // SSRF/port-scan oracle. One shared counter per nonce means pivoting between the two endpoints cannot
711
- // reset the cap. Fail open on a Redis error - the cap is defense-in-depth, not correctness.
712
- const enforceFormProbeLimit = async (nonce, gt, logger) => {
713
- let count = 0;
714
- try {
715
- const counted = await atomicIncrement(redis, `${REDIS_PREFIX}account:form:probe:${nonce}`, 1, Math.floor(MAX_FORM_TTL / 1000));
716
- if (counted.success) {
717
- count = counted.value;
718
- }
719
- } catch (err) {
720
- logger.error({ msg: 'Failed to count outbound form probes', err });
721
- }
722
- if (count > MAX_FORM_PROBE_ATTEMPTS) {
723
- // The cap is keyed on the nonce inside the signed blob, so reloading the same link keeps the
724
- // same nonce and stays capped - the caller needs a freshly issued setup link.
725
- //
726
- // Reviewed, accepted (do not "fix" by removing the cap): for an API-issued link the end user
727
- // cannot self-recover once exhausted and must go back to the integrator for a fresh link. This
728
- // is bounded by the link's <=24h TTL, the account-creating submit itself does not draw from the
729
- // budget, and the app-password hint memo (APP_PASSWORD_HINT_CACHE) keeps error re-renders from
730
- // burning it on cosmetics. If this ever bites real users, tune MAX_FORM_PROBE_ATTEMPTS or scope
731
- // the budget per-endpoint rather than dropping the SSRF/port-scan defense.
732
- throw Boom.boomify(new Error(gt.gettext('Too many attempts for this setup link. Request a new setup link to continue.')), { statusCode: 429 });
733
- }
734
- };
735
-
736
- // The authorization gate for every outbound-probe-driving call in this file: a valid signed blob
737
- // WITH a nonce (requireNonce guarantees data.n) plus the shared per-nonce probe cap. Keep the two
738
- // paired through this helper - a probe site that checks the signature but skips the cap silently
739
- // reopens the unbounded-probe hole. Throws Boom 403/429; returns the parsed blob.
740
- const authorizeSignedProbe = async (payload, gt, logger) => {
741
- const data = await parseSignedFormData(redis, payload, gt, { requireNonce: true });
742
- await enforceFormProbeLimit(data.n, gt, logger);
743
- return data;
744
- };
745
-
746
- // Re-derive the app-password hint for a settings form that is being rendered from posted values
747
- // rather than from a fresh autodiscovery result, and merge it into those values.
748
- //
749
- // serverFormSchema does not carry the appPassword_* fields (they feed unescaped template sinks),
750
- // so stripUnknown drops them and they cannot be carried in a hidden input - echoing a
751
- // client-controlled hint into the page was an XSS vector. The hint is therefore rebuilt here from
752
- // the (trusted) email, out of a static table, never from the submitted payload.
753
- //
754
- // Shared by the failAction re-render and by the checking page's hand-off to the settings form, so
755
- // a form reached either way shows the same "Application Password" label and instructions.
756
- //
757
- // Try the static domain table first: it is synchronous, needs no network, and covers the
758
- // canonical provider domains, so a common-domain render costs no Redis round trips, no DNS, and
759
- // no probe budget. Never throws - the hint is cosmetic and a failAction must not throw.
760
- const applyAppPasswordHint = async (values, request, parsedBlob) => {
761
- if (!values.email) {
762
- return;
763
- }
764
-
765
- let appPassword = getAppPassword(values.email, false, request.app.gt);
766
-
767
- // Custom-domain fallback (e.g. Google Workspace / M365 on their own domain) needs an MX
768
- // lookup. failAction runs BEFORE the handler's signature gate, and the lookup drives outbound
769
- // DNS, so gate it with the SAME machinery as the handler siblings, not a bare signature
770
- // check: authorizeSignedProbe rejects a signature-only blob (e.g. a leaked tracking/
771
- // unsubscribe blob) and one past its TTL, and bounds how many lookups one signed link can
772
- // drive. Without it, any holder of any validly-signed blob could turn this render into an
773
- // unbounded DNS oracle. On a normal validation-error re-render the nonce is not yet consumed
774
- // (the create handler claims it only on success), so the hint still shows. values.data /
775
- // values.sig are the schema-validated copies - rebuildFormValues drops them when malformed
776
- // (e.g. duplicated fields).
777
- if (!appPassword && values.data && values.sig) {
778
- // Consult the per-domain memo BEFORE the probe/DNS work: a repeat re-submit of the same
779
- // email must not re-run the MX lookup or draw the probe budget again.
780
- const domain = values.email.split('@').pop().trim().toLowerCase();
781
- const cached = getCachedAppPasswordHint(domain);
782
- if (cached) {
783
- appPassword = cached.value;
784
- } else {
785
- try {
786
- if (parsedBlob) {
787
- // Already parsed and signature-checked by the caller, so only the cap is left
788
- // to apply - re-parsing would mean a second serviceSecret read and HMAC check
789
- await enforceFormProbeLimit(parsedBlob.n, request.app.gt, request.logger);
790
- } else {
791
- await authorizeSignedProbe({ data: values.data, sig: values.sig }, request.app.gt, request.logger);
792
- }
793
- appPassword = await resolveAppPassword(values.email, request.app.gt);
794
- // Cache the outcome (including a falsy "no hint" result) so subsequent renders for
795
- // this domain are free.
796
- setCachedAppPasswordHint(domain, appPassword);
797
- } catch (err) {
798
- // A rejected/expired blob, an exhausted probe cap, or a lookup failure must never
799
- // break the render. Do NOT cache on failure - an exhausted probe cap or transient
800
- // DNS error should not poison the hint for the whole TTL.
801
- request.logger.debug({ msg: 'Failed to resolve app-password hint for form re-render', err });
802
- }
803
- }
804
- }
805
-
806
- if (appPassword) {
807
- Object.assign(values, flattenObjectKeys({ appPassword }));
808
- }
809
- };
810
-
811
- // The expectation that applies to a parsed form blob (lib/account/expected-identity.js owns the
812
- // precedence and the lazy Redis fallback).
813
- const resolveFormExpectation = data => resolveExpectedIdentity(redis, { account: data.account, blobExpectation: data.expectedEmail });
814
-
815
- // Expected identity gate for the IMAP arm, mirroring the one the OAuth callback applies in
816
- // workers/api.js.
817
- //
818
- // The evidence here is only the address typed into the form. Working credentials do not prove that
819
- // the address belongs to the mailbox behind them, so this enforces "the account is registered under
820
- // the expected address" and nothing stronger - which is exactly what the field documents. Without it
821
- // the constraint would be trivially sidestepped by choosing the IMAP tab on a form that also offers
822
- // OAuth2.
823
- //
824
- // Returns { expectedEmail, matched } rather than throwing so the caller can name the address that was
825
- // actually used when it reports the rejection.
826
- const checkExpectedIdentity = async (data, submittedEmail) => {
827
- const expectedEmail = await resolveFormExpectation(data);
828
- return { expectedEmail, matched: !expectedEmail || matchesExpectedIdentity(expectedEmail, [submittedEmail]) };
829
- };
830
-
831
- // Stop the flow with a way back rather than a redirect to the calling application: entering the wrong
832
- // address is correctable, and the hosted form only ever redirects on success. The OAuth arm renders
833
- // the same view (workers/api.js), differing only in where "try again" points.
834
- //
835
- // type=imap keeps the user on the arm they already chose: without it /accounts/new re-asks the
836
- // provider question and offers OAuth apps they passed over. The signed blob is still unspent (the
837
- // nonce is claimed only on success), so the link works, and the form it returns to prefills the
838
- // pinned address read-only.
839
- const renderIdentityError = (request, h, expectedEmail, actualEmail) =>
840
- identityErrorView(request, h, {
841
- expectedEmail,
842
- actualEmail,
843
- retryUrl: `/accounts/new?data=${encodeURIComponent(request.payload.data)}&sig=${encodeURIComponent(request.payload.sig)}&type=imap`
844
- });
845
-
846
- // have to use HTML redirect, otherwise samesite=strict cookies are not passed on
847
- const renderRedirect = (request, h, httpRedirectUrl) =>
848
- h.view(
849
- 'redirect',
850
- {
851
- pageTitleFull: request.app.gt.gettext('Email Account Setup'),
852
- httpRedirectUrl
853
- },
854
- {
855
- layout: 'public'
856
- }
857
- );
858
-
869
+ function registerPostHostedImap(server) {
859
870
  server.route({
860
871
  method: 'POST',
861
872
  path: '/accounts/new/imap',
@@ -1000,7 +1011,9 @@ function init(args) {
1000
1011
  }
1001
1012
  }
1002
1013
  });
1014
+ }
1003
1015
 
1016
+ function registerPostHostedImapTest(server) {
1004
1017
  server.route({
1005
1018
  method: 'POST',
1006
1019
  path: '/accounts/new/imap/test',
@@ -1164,25 +1177,16 @@ function init(args) {
1164
1177
  }
1165
1178
  }
1166
1179
  });
1180
+ }
1167
1181
 
1168
- // Shared by this route's payload validation and its failAction re-render, so the re-rendered form
1169
- // is built from the same schema that validated the submission and cannot drift from it (unlike the
1170
- // earlier hand-maintained truthy Set, which had to be kept in sync by hand).
1171
- const serverFormSchema = Joi.object({
1172
- ...signedBlobFields,
1173
- name: Joi.string().empty('').max(256).example('John Smith').description('Account Name'),
1174
- tz: Joi.string().empty('').max(100).example('Europe/Tallinn').description('Optional timezone for autogenerated date strings'),
1175
- email: Joi.string().email().required().example('user@example.com').label('Email').description('Your account email'),
1176
- ...connectionFields
1177
- });
1178
-
1179
- // Where the checking page sends the user when the connection check did not pass: the ordinary
1180
- // server settings form, prefilled with everything that was discovered and typed, so the one wrong
1181
- // field can be corrected. Signature-gated like its siblings because it renders submitted values
1182
- // back into a page. Rendering it drives no outbound connection of its own, so the gate here is
1183
- // the signature and the nonce rather than authorizeSignedProbe; the one thing that can still
1184
- // reach the network is the app-password hint's MX lookup, which draws on the per-nonce probe
1185
- // 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) {
1186
1190
  server.route({
1187
1191
  method: 'POST',
1188
1192
  path: '/accounts/new/imap/settings',
@@ -1242,6 +1246,10 @@ function init(args) {
1242
1246
  }
1243
1247
  }
1244
1248
  });
1249
+ }
1250
+
1251
+ function registerPostHostedImapServer(server, args) {
1252
+ const { call } = args;
1245
1253
 
1246
1254
  server.route({
1247
1255
  method: 'POST',
@@ -1300,57 +1308,14 @@ function init(args) {
1300
1308
 
1301
1309
  const accountObject = new Account({ redis, call, secret: await getSecret() });
1302
1310
 
1303
- // Claim the single-use nonce BEFORE creating the account so a concurrent double-submit or
1304
- // a replayed URL cannot create duplicate accounts (SET NX is atomic). parseSignedFormData
1305
- // already rejects a nonce that was fully consumed by an earlier successful submit.
1306
- // requireNonce:true above guarantees data.n and data.t are present.
1307
- // claimFormNonce/releaseFormNonce (lib/tools.js) encapsulate the SET NX + release so the IMAP
1308
- // arm and the OAuth callback (workers/api.js) share one copy of the double-spend semantics.
1309
- let claimed;
1310
- try {
1311
- claimed = await claimFormNonce(redis, data.n, data.t);
1312
- } catch (err) {
1313
- // A Redis failure here is not a consumed nonce. Report it as a retryable server error
1314
- // instead of misdiagnosing a valid setup URL as invalid or expired.
1315
- request.logger.error({ msg: 'Failed to claim nonce for an account form request', err });
1316
- throw Boom.boomify(new Error(request.app.gt.gettext('Temporary error, please try again')), { statusCode: 500 });
1317
- }
1318
- if (!claimed) {
1319
- // SET NX returned null: the nonce key already exists, so this URL was already used.
1320
- //
1321
- // Reviewed, accepted (do not "fix" server-side): the LOSING side of a legitimate concurrent
1322
- // double-submit lands here and sees this 403 even though the winning request created the
1323
- // account. The client-side formSubmitting latch (views/accounts/register/imap-server.hbs) is
1324
- // the primary guard; the residual is a no-JS double-click, and even then this is strictly
1325
- // better than the pre-hardening behavior (two duplicate accounts). A nicer UX (store the
1326
- // created account id under the nonce key and redirect the loser to success) is a possible
1327
- // future enhancement, not a bug.
1328
- throw Boom.boomify(new Error(request.app.gt.gettext('Invalid or expired account setup URL')), { statusCode: 403 });
1329
- }
1330
-
1331
- let result;
1332
- try {
1333
- result = await accountObject.create(accountData);
1334
- } catch (err) {
1335
- // Release the nonce so the user can fix the form and retry. Accepted residual: if
1336
- // Redis fails here too (it likely failed create() as well), the nonce stays consumed
1337
- // for its remaining TTL and the user needs a freshly issued link - the claim-BEFORE-
1338
- // create ordering is what makes the double-submit dedupe atomic, and this narrow
1339
- // crash window is the price of that.
1340
- await releaseFormNonce(redis, data.n, request.logger);
1341
- throw err;
1342
- }
1343
-
1344
- let httpRedirectUrl;
1345
- if (data.redirectUrl) {
1346
- const serviceUrl = await settings.get('serviceUrl');
1347
- const url = new URL(data.redirectUrl, serviceUrl);
1348
- url.searchParams.set('account', result.account);
1349
- url.searchParams.set('state', result.state);
1350
- httpRedirectUrl = url.href;
1351
- } else {
1352
- httpRedirectUrl = adminUrl`/admin/accounts/${result.account}`;
1353
- }
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
+ });
1354
1319
 
1355
1320
  return renderRedirect(request, h, httpRedirectUrl);
1356
1321
  },
@@ -1407,6 +1372,10 @@ function init(args) {
1407
1372
  }
1408
1373
  }
1409
1374
  });
1375
+ }
1376
+
1377
+ function registerGetAccountsByAccount(server, args) {
1378
+ const { call } = args;
1410
1379
 
1411
1380
  server.route({
1412
1381
  method: 'GET',
@@ -1723,6 +1692,10 @@ function init(args) {
1723
1692
  }
1724
1693
  }
1725
1694
  });
1695
+ }
1696
+
1697
+ function registerPostAccountsDelete(server, args) {
1698
+ const { call } = args;
1726
1699
 
1727
1700
  server.route({
1728
1701
  method: 'POST',
@@ -1773,6 +1746,10 @@ function init(args) {
1773
1746
  }
1774
1747
  }
1775
1748
  });
1749
+ }
1750
+
1751
+ function registerPostAccountsReconnect(server, args) {
1752
+ const { call } = args;
1776
1753
 
1777
1754
  server.route({
1778
1755
  method: 'POST',
@@ -1818,37 +1795,32 @@ function init(args) {
1818
1795
  }
1819
1796
  }
1820
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;
1821
1809
 
1822
- // Turns an account back on after the auth-failure safety net switched it off. The only admin
1823
- // UI route that reaches the flag for a Gmail API or Outlook account: their IMAP card, and with
1824
- // it the "Disable IMAP" checkbox an IMAP account is re-enabled through, is not rendered.
1825
- //
1826
- // Lifts nothing but the safety net's own disable (see Account.clearAuthFailureDisable), so it
1827
- // cannot be used to un-do an operator's deliberate send-only switch.
1828
1810
  server.route({
1829
1811
  method: 'POST',
1830
1812
  path: '/admin/accounts/{account}/resume',
1831
1813
  async handler(request) {
1832
1814
  let account = request.params.account;
1833
1815
  try {
1834
- // clearAuthFailureDisable() needs nothing but the account hash, and the reconnect
1835
- // below is dispatched from this module's own channel
1836
- 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 });
1837
1819
 
1838
- if (!(await accountObject.clearAuthFailureDisable())) {
1820
+ if (!(await accountObject.resumeAfterAuthFailure())) {
1839
1821
  return { success: false, error: 'This account was not switched off by EmailEngine' };
1840
1822
  }
1841
1823
 
1842
- request.logger.info({ msg: 'Resumed an account that was switched off after authentication failures', account });
1843
-
1844
- try {
1845
- await call({ cmd: 'reconnect', account });
1846
- } catch (err) {
1847
- // The flag is already lifted, so the account is no longer parked. Losing the
1848
- // dispatch only delays the connection until the next periodic reconnect.
1849
- request.logger.error({ msg: 'Reconnect request failed', action: 'resume_account', account, err });
1850
- }
1851
-
1852
1824
  return { success: true };
1853
1825
  } catch (err) {
1854
1826
  request.logger.error({ msg: 'Failed to resume account', err, account });
@@ -1871,6 +1843,10 @@ function init(args) {
1871
1843
  }
1872
1844
  }
1873
1845
  });
1846
+ }
1847
+
1848
+ function registerPostAccountsSync(server, args) {
1849
+ const { call } = args;
1874
1850
 
1875
1851
  server.route({
1876
1852
  method: 'POST',
@@ -1909,6 +1885,10 @@ function init(args) {
1909
1885
  }
1910
1886
  }
1911
1887
  });
1888
+ }
1889
+
1890
+ function registerPostAccountsLogs(server, args) {
1891
+ const { call } = args;
1912
1892
 
1913
1893
  server.route({
1914
1894
  method: 'POST',
@@ -1956,7 +1936,9 @@ function init(args) {
1956
1936
  }
1957
1937
  }
1958
1938
  });
1939
+ }
1959
1940
 
1941
+ function registerPostAccountsLogsFlush(server) {
1960
1942
  server.route({
1961
1943
  method: 'POST',
1962
1944
  path: '/admin/accounts/{account}/logs-flush',
@@ -1992,7 +1974,9 @@ function init(args) {
1992
1974
  }
1993
1975
  }
1994
1976
  });
1977
+ }
1995
1978
 
1979
+ function registerGetAccountsLogsTxt(server) {
1996
1980
  server.route({
1997
1981
  method: 'GET',
1998
1982
  path: '/admin/accounts/{account}/logs.txt',
@@ -2015,6 +1999,10 @@ function init(args) {
2015
1999
  }
2016
2000
  }
2017
2001
  });
2002
+ }
2003
+
2004
+ function registerGetAccountsBrowse(server, args) {
2005
+ const { call } = args;
2018
2006
 
2019
2007
  server.route({
2020
2008
  method: 'GET',
@@ -2097,6 +2085,10 @@ function init(args) {
2097
2085
  }
2098
2086
  }
2099
2087
  });
2088
+ }
2089
+
2090
+ function registerGetAccountsEdit(server, args) {
2091
+ const { call } = args;
2100
2092
 
2101
2093
  server.route({
2102
2094
  method: 'GET',
@@ -2185,6 +2177,10 @@ function init(args) {
2185
2177
  }
2186
2178
  }
2187
2179
  });
2180
+ }
2181
+
2182
+ function registerPostAccountsEdit(server, args) {
2183
+ const { call } = args;
2188
2184
 
2189
2185
  server.route({
2190
2186
  method: 'POST',
@@ -2485,4 +2481,29 @@ function init(args) {
2485
2481
  });
2486
2482
  }
2487
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
+
2488
2509
  module.exports = init;