emailengine-app 2.79.6 → 2.79.8

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 (109) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +32 -0
  3. package/DOCKER_DEPLOYMENT.md +2 -0
  4. package/bin/emailengine.js +29 -13
  5. package/config/default.toml +13 -3
  6. package/data/google-crawlers.json +7 -1
  7. package/docker-compose.yml +12 -3
  8. package/install.sh +2 -0
  9. package/lib/api-routes/account-routes.js +14 -3
  10. package/lib/api-routes/mailbox-routes.js +4 -1
  11. package/lib/api-routes/message-routes.js +6 -5
  12. package/lib/api-routes/outbox-routes.js +7 -4
  13. package/lib/api-routes/settings-routes.js +34 -25
  14. package/lib/api-routes/stats-routes.js +8 -1
  15. package/lib/api-routes/submit-routes.js +2 -1
  16. package/lib/api-routes/template-routes.js +3 -2
  17. package/lib/bounce-detect.js +45 -0
  18. package/lib/consts.js +9 -3
  19. package/lib/egress-filter.js +39 -4
  20. package/lib/email-client/base-client.js +274 -24
  21. package/lib/email-client/gmail/gmail-api.js +15 -7
  22. package/lib/email-client/gmail-client.js +121 -64
  23. package/lib/email-client/imap/mailbox.js +18 -59
  24. package/lib/email-client/imap-client.js +53 -29
  25. package/lib/email-client/notification-handler.js +11 -2
  26. package/lib/email-client/outlook/graph-api.js +106 -90
  27. package/lib/email-client/outlook-client.js +222 -106
  28. package/lib/generate-text-preview.js +10 -5
  29. package/lib/headers-rewriter.js +1 -1
  30. package/lib/llm-pre-process.js +4 -1
  31. package/lib/mcp/json-schema.js +50 -2
  32. package/lib/outbox.js +22 -5
  33. package/lib/passkeys.js +39 -7
  34. package/lib/pre-process.js +4 -1
  35. package/lib/rewrite-text-nodes.js +12 -1
  36. package/lib/schemas.js +27 -5
  37. package/lib/settings.js +19 -1
  38. package/lib/sso.js +60 -7
  39. package/lib/submit-progress.js +29 -0
  40. package/lib/templates.js +11 -0
  41. package/lib/tools.js +115 -53
  42. package/lib/ui-routes/account-routes.js +79 -12
  43. package/lib/ui-routes/admin-config-routes.js +7 -21
  44. package/lib/ui-routes/admin-entities-routes.js +42 -12
  45. package/lib/ui-routes/auth-routes.js +242 -87
  46. package/lib/ui-routes/dashboard-routes.js +1 -1
  47. package/lib/ui-routes/internals-routes.js +2 -0
  48. package/lib/ui-routes/mcp-consent-routes.js +5 -2
  49. package/lib/ui-routes/network-config-routes.js +12 -3
  50. package/lib/ui-routes/oauth-config-routes.js +12 -1
  51. package/lib/ui-routes/route-helpers.js +41 -6
  52. package/lib/ui-routes/settings-page.js +10 -0
  53. package/lib/ui-routes/suppression-list-routes.js +16 -5
  54. package/lib/ui-routes/unsubscribe-routes.js +22 -3
  55. package/lib/webhooks.js +14 -2
  56. package/package.json +17 -17
  57. package/sbom.json +1 -1
  58. package/server.js +63 -35
  59. package/static/css/flyonui.css +1 -1
  60. package/static/css/src/app.tailwind.css +55 -0
  61. package/static/js/app.js +4 -35
  62. package/static/js/passkey-register.js +50 -1
  63. package/static/js/public.js +128 -0
  64. package/static/js/ui.js +183 -6
  65. package/static/licenses.html +371 -770
  66. package/translations/messages.pot +66 -66
  67. package/views/account/passkeys.hbs +141 -0
  68. package/views/account/password.hbs +11 -0
  69. package/views/account/security.hbs +318 -326
  70. package/views/accounts/account.hbs +90 -115
  71. package/views/accounts/register/imap-server.hbs +18 -12
  72. package/views/config/ai.hbs +2 -0
  73. package/views/config/branding.hbs +2 -0
  74. package/views/config/document-store/index.hbs +6 -6
  75. package/views/config/email-processing.hbs +2 -0
  76. package/views/config/imap-proxy.hbs +2 -0
  77. package/views/config/license.hbs +4 -1
  78. package/views/config/logging.hbs +3 -1
  79. package/views/config/mcp.hbs +2 -0
  80. package/views/config/network.hbs +2 -0
  81. package/views/config/oauth/app.hbs +3 -3
  82. package/views/config/oauth/edit.hbs +1 -1
  83. package/views/config/oauth/new.hbs +1 -1
  84. package/views/config/security.hbs +2 -0
  85. package/views/config/service.hbs +2 -0
  86. package/views/config/smtp.hbs +2 -0
  87. package/views/config/webhooks.hbs +9 -6
  88. package/views/error.hbs +6 -0
  89. package/views/layout/app.hbs +6 -3
  90. package/views/layout/login.hbs +1 -1
  91. package/views/layout/prompt.hbs +1 -1
  92. package/views/layout/public.hbs +1 -1
  93. package/views/legal.hbs +1 -1
  94. package/views/partials/filter_editor_js.hbs +1 -1
  95. package/views/partials/gateway_js.hbs +7 -6
  96. package/views/partials/oauth_form.hbs +5 -5
  97. package/views/partials/ui/btn.hbs +8 -2
  98. package/views/partials/ui/confirm-modal.hbs +2 -3
  99. package/views/partials/ui/empty-state.hbs +25 -0
  100. package/views/partials/ui/env-managed-alert.hbs +19 -0
  101. package/views/partials/webhook_form.hbs +1 -1
  102. package/views/partials/webhooks_editor_functions.hbs +5 -5
  103. package/views/unsubscribe.hbs +6 -0
  104. package/workers/api.js +193 -81
  105. package/workers/imap.js +32 -3
  106. package/workers/smtp.js +7 -0
  107. package/workers/submit.js +25 -1
  108. package/workers/webhooks.js +13 -17
  109. package/lib/reconnection-manager.js +0 -106
@@ -10,6 +10,7 @@
10
10
 
11
11
  const Joi = require('joi');
12
12
  const crypto = require('crypto');
13
+ const { parentPort } = require('worker_threads');
13
14
  const pbkdf2 = require('@phc/pbkdf2');
14
15
  const QRCode = require('qrcode');
15
16
  const { generateTotpSeed, verifyTotp, generateTotpUrl } = require('../totp');
@@ -52,6 +53,96 @@ async function oidcForcedActive(h) {
52
53
  return !!(sso.OIDC_FORCED && sso.USE_OIDC_AUTH && (await h.validateOidcConfig()));
53
54
  }
54
55
 
56
+ // Authenticator transports recorded at registration, turned into the wording and icon the
57
+ // passkey list shows for each entry. 'internal' outranks 'hybrid' because a platform
58
+ // authenticator that can additionally be driven from a phone is still, to the person
59
+ // reading the list, the passkey living on that computer. The icon class is emitted whole
60
+ // and safelisted in app.tailwind.css with the other server-driven icons - this file is not
61
+ // scanned by Tailwind - so that the wording and the icon stay one mapping in one place.
62
+ const SECURITY_KEY_TRANSPORTS = ['usb', 'nfc', 'ble'];
63
+
64
+ function describePasskeyDevice(transports) {
65
+ let list = Array.isArray(transports) ? transports : [];
66
+
67
+ if (list.includes('internal')) {
68
+ return { label: 'Built-in authenticator', icon: 'icon-[tabler--fingerprint]' };
69
+ }
70
+ if (list.includes('hybrid')) {
71
+ return { label: 'Phone or tablet', icon: 'icon-[tabler--device-mobile]' };
72
+ }
73
+ if (list.some(transport => SECURITY_KEY_TRANSPORTS.includes(transport))) {
74
+ return { label: 'Security key', icon: 'icon-[tabler--usb]' };
75
+ }
76
+ return { label: 'Passkey', icon: 'icon-[tabler--key]' };
77
+ }
78
+
79
+ // Normalizes a stored timestamp into the ISO string the client-side .relative-time
80
+ // formatter parses. A value that does not parse becomes null so the cell renders as
81
+ // "unknown" rather than as an empty gap.
82
+ function passkeyTimestamp(value) {
83
+ let date = value ? new Date(value) : null;
84
+ return date && !isNaN(date.getTime()) ? date.toISOString() : null;
85
+ }
86
+
87
+ // Single place that knows how a failed password check is interpreted: an absent password and a
88
+ // verify() that throws (which happens only on a malformed stored hash, never on a wrong password)
89
+ // are both failures, never a pass. Sign-in, the password change and both passkey registration
90
+ // steps all come through here, so a change to how the account password is checked - a KDF swap,
91
+ // a dummy verify to flatten timing - lands in one place.
92
+ async function verifyAdminPassword(hash, password, logger) {
93
+ if (!password) {
94
+ return false;
95
+ }
96
+ try {
97
+ return await pbkdf2.verify(hash, password);
98
+ } catch (err) {
99
+ logger.error({ msg: 'Failed to verify password hash', err });
100
+ return false;
101
+ }
102
+ }
103
+
104
+ // The current-password check behind the security page's step-down actions (the password change
105
+ // and switching the second factor off). A live session alone is not supposed to reveal the
106
+ // password, and unthrottled the field let a hijacked session guess it at full speed, so the
107
+ // check is rate limited the way the login form is: keyed on the account rather than the address
108
+ // because the caller is already authenticated as it, and with the login form's per-username
109
+ // budget. Owns the limiter and the warn logs; the caller decides how to report the failure.
110
+ //
111
+ // @returns {Promise<{ ok: true } | { ok: false, reason: 'rateLimited' | 'invalid' }>}
112
+ async function verifyCurrentPassword(request, h, authData, password) {
113
+ let rateLimit = await h.checkRateLimit(`password:verify:${authData.user || 'admin'}`, 1, 10, 60);
114
+ if (!rateLimit.success) {
115
+ request.logger.warn({ msg: 'Rate limited', rateLimit, remoteAddress: request.app.ip });
116
+ return { ok: false, reason: 'rateLimited' };
117
+ }
118
+
119
+ if (!(await verifyAdminPassword(authData.password, password, request.logger))) {
120
+ request.logger.warn({ msg: 'Invalid current password', remoteAddress: request.app.ip });
121
+ return { ok: false, reason: 'invalid' };
122
+ }
123
+
124
+ return { ok: true };
125
+ }
126
+
127
+ // View model for the security page's passkey list. Only the fields the list renders are
128
+ // exposed - the stored credential also carries the public key, the signature counter and
129
+ // the owning user, none of which belong in a template context.
130
+ async function listPasskeysForView(username) {
131
+ let credentials = await passkeys.listCredentials(username);
132
+
133
+ return credentials.map(credential => {
134
+ let device = describePasskeyDevice(credential.transports);
135
+ return {
136
+ id: credential.id,
137
+ name: credential.name,
138
+ deviceLabel: device.label,
139
+ deviceIcon: device.icon,
140
+ createdAt: passkeyTimestamp(credential.createdAt),
141
+ lastUsedAt: passkeyTimestamp(credential.lastUsedAt)
142
+ };
143
+ });
144
+ }
145
+
55
146
  function init(args) {
56
147
  const { server } = args;
57
148
 
@@ -206,14 +297,7 @@ function init(args) {
206
297
  }
207
298
 
208
299
  if (authData && authData.password) {
209
- let valid;
210
- try {
211
- valid = await pbkdf2.verify(authData.password, request.payload.password);
212
- } catch (E) {
213
- // verify() only throws on a malformed stored hash, not on a wrong password
214
- request.logger.error({ msg: 'Failed to verify password hash', err: E });
215
- valid = false;
216
- }
300
+ let valid = await verifyAdminPassword(authData.password, request.payload.password, request.logger);
217
301
  if (!valid) {
218
302
  request.logger.warn({ msg: 'Invalid password', user: request.payload.username, method: 'password', remoteAddress: request.app.ip });
219
303
  let err = new Error('Failed to authenticate');
@@ -482,7 +566,9 @@ function init(args) {
482
566
  {
483
567
  pageTitle: 'Login',
484
568
  menuLogin: true,
485
- errors
569
+ errors,
570
+ // the hidden next input, so a retry still lands where the login started
571
+ values: { next: request.payload.next }
486
572
  },
487
573
  {
488
574
  layout: 'login'
@@ -518,7 +604,8 @@ function init(args) {
518
604
  {
519
605
  pageTitle: 'Login',
520
606
  menuLogin: true,
521
- errors
607
+ errors,
608
+ values: { next: request.payload.next }
522
609
  },
523
610
  {
524
611
  layout: 'login'
@@ -558,13 +645,16 @@ function init(args) {
558
645
  return h.redirect(`/admin`);
559
646
  }
560
647
 
648
+ // Single read for everything the page renders from - serviceUrl feeds both the TOTP
649
+ // label and the passkey registration gate
650
+ let { totpEnabled, totpSeed, serviceUrl } = await settings.getMulti('totpEnabled', 'totpSeed', 'serviceUrl');
651
+
561
652
  let totp = {
562
- enabled: (await settings.get('totpEnabled')) || false
653
+ enabled: totpEnabled || false
563
654
  };
564
655
 
565
656
  let username = (request.auth && request.auth.credentials && request.auth.credentials.user) || 'admin';
566
657
 
567
- let totpSeed = await settings.get('totpSeed');
568
658
  if (!totpSeed) {
569
659
  totpSeed = generateTotpSeed();
570
660
  await settings.set('totpSeed', totpSeed);
@@ -572,10 +662,8 @@ function init(args) {
572
662
 
573
663
  if (!totp.enabled) {
574
664
  // create QR code
575
- const serviceUrl = (await settings.get('serviceUrl')) || '';
576
-
577
665
  let otpauth_url = generateTotpUrl(totpSeed, {
578
- label: serviceUrl.replace(/^https?:\/\/|\/$/g, ''),
666
+ label: (serviceUrl || '').replace(/^https?:\/\/|\/$/g, ''),
579
667
  issuer: 'EmailEngine'
580
668
  });
581
669
 
@@ -586,20 +674,9 @@ function init(args) {
586
674
  }
587
675
  }
588
676
 
589
- let registeredPasskeys = await passkeys.listCredentials(username);
590
- for (let pk of registeredPasskeys) {
591
- try {
592
- pk.createdAtFormatted = new Date(pk.createdAt).toLocaleDateString('en-US', {
593
- year: 'numeric',
594
- month: 'short',
595
- day: 'numeric'
596
- });
597
- } catch (err) {
598
- pk.createdAtFormatted = pk.createdAt;
599
- }
600
- }
601
-
602
- let serviceUrl = await settings.get('serviceUrl');
677
+ // A count, not the list: this page summarizes passkeys and links to the page that
678
+ // manages them, so one SCARD replaces fetching every credential hash.
679
+ let passkeyCount = await passkeys.countCredentials(username);
603
680
 
604
681
  return h.view(
605
682
  'account/security',
@@ -612,7 +689,7 @@ function init(args) {
612
689
  username,
613
690
 
614
691
  totp,
615
- passkeys: registeredPasskeys,
692
+ passkeyCount,
616
693
  serviceUrl,
617
694
  providers: await ssoProviders(h),
618
695
  okta: {
@@ -640,6 +717,59 @@ function init(args) {
640
717
  }
641
718
  });
642
719
 
720
+ // Passkeys get a page of their own, the way the password does: the security page above is an
721
+ // inventory of ways into the account, and a credential list that grows to MAX_PASSKEYS_PER_USER
722
+ // rows would take it over. Registering needs an account password, so an instance without one
723
+ // has nothing to show here.
724
+ server.route({
725
+ method: 'GET',
726
+ path: '/admin/account/passkeys',
727
+ async handler(request, h) {
728
+ if (request.auth.artifacts && request.auth.artifacts.provider) {
729
+ return h.redirect(`/admin`);
730
+ }
731
+
732
+ let authData = await settings.get('authData');
733
+ if (!authData || !authData.password) {
734
+ return h.redirect('/admin/account/security');
735
+ }
736
+
737
+ let username = (request.auth && request.auth.credentials && request.auth.credentials.user) || 'admin';
738
+
739
+ // The RP ID is what the page names as the hostname the passkeys are bound to: it is
740
+ // derived from the Service URL on every ceremony, so a changed host silently strands
741
+ // every registered passkey, and the page is where that gets explained
742
+ let [registeredPasskeys, { rpId, origin: serviceUrl }] = await Promise.all([listPasskeysForView(username), passkeys.getRpConfig()]);
743
+
744
+ // Both reasons registration would fail are known here, so the button is disabled with
745
+ // the reason on it instead of letting the ceremony run into a server error.
746
+ let passkeyBlockReason = null;
747
+ if (!serviceUrl) {
748
+ passkeyBlockReason = 'Set a Service URL in configuration before registering passkeys';
749
+ } else if (registeredPasskeys.length >= consts.MAX_PASSKEYS_PER_USER) {
750
+ passkeyBlockReason = `Maximum of ${consts.MAX_PASSKEYS_PER_USER} passkeys reached - remove one to register another`;
751
+ }
752
+
753
+ return h.view(
754
+ 'account/passkeys',
755
+ {
756
+ pageTitle: 'Passkeys',
757
+ menuAccountSecurity: true,
758
+ activePassword: false,
759
+ disableAuthWarning: true,
760
+
761
+ passkeys: registeredPasskeys,
762
+ passkeyBlockReason,
763
+ serviceUrl,
764
+ rpId
765
+ },
766
+ {
767
+ layout: 'app'
768
+ }
769
+ );
770
+ }
771
+ });
772
+
643
773
  server.route({
644
774
  method: 'POST',
645
775
  path: '/admin/account/tfa/enable',
@@ -714,6 +844,22 @@ function init(args) {
714
844
  }
715
845
 
716
846
  try {
847
+ // Switching the second factor off is a step down that a live session alone should
848
+ // not be able to take - the password change and passkey registration both ask for
849
+ // the password again, and so does this, through the same rate-limited check as
850
+ // the password change because it is the same guess-the-password surface.
851
+ let authData = await settings.get('authData');
852
+ if (authData && authData.password) {
853
+ let verified = await verifyCurrentPassword(request, h, authData, request.payload.password);
854
+ if (!verified.ok) {
855
+ await request.flash({
856
+ type: 'danger',
857
+ message: verified.reason === 'rateLimited' ? `Rate limited, please wait and try again` : `Invalid password`
858
+ });
859
+ return h.redirect(`/admin/account/security`);
860
+ }
861
+ }
862
+
717
863
  await settings.set('totpEnabled', false);
718
864
  await settings.set('totpSeed', false);
719
865
 
@@ -737,11 +883,12 @@ function init(args) {
737
883
  await request.flash({ type: 'danger', message: `Couldn't disable two-factor auth. Try again.` });
738
884
  request.logger.error({ msg: 'Failed to disable 2FA', err });
739
885
 
740
- return h.redirect('/admin').takeover();
886
+ return h.redirect('/admin/account/security').takeover();
741
887
  },
742
888
 
743
889
  payload: Joi.object({
744
- type: Joi.string().valid('totp').description('The type of the two-factor authentication method').required()
890
+ type: Joi.string().valid('totp').description('The type of the two-factor authentication method').required(),
891
+ password: Joi.string().max(256).required().label('Current password')
745
892
  })
746
893
  }
747
894
  }
@@ -831,20 +978,6 @@ function init(args) {
831
978
  return h.response({ error: 'Account password must be configured before registering passkeys' }).code(403);
832
979
  }
833
980
 
834
- if (!request.payload.password) {
835
- return h.response({ error: 'Current password is required' }).code(403);
836
- }
837
- let valid;
838
- try {
839
- valid = await pbkdf2.verify(authData.password, request.payload.password);
840
- } catch (err) {
841
- request.logger.error({ msg: 'Failed to verify password for passkey registration', err });
842
- valid = false;
843
- }
844
- if (!valid) {
845
- return h.response({ error: 'Invalid password' }).code(403);
846
- }
847
-
848
981
  let { rpId, origin } = await passkeys.getRpConfig();
849
982
  if (!rpId || !origin) {
850
983
  return h.response({ error: 'Service URL must be configured before registering passkeys' }).code(400);
@@ -857,6 +990,12 @@ function init(args) {
857
990
  return h.response({ error: 'Maximum number of passkeys reached' }).code(400);
858
991
  }
859
992
 
993
+ // Last, because it is the expensive check: the request is refused for a missing
994
+ // Service URL or a full list without paying for a PBKDF2 verification first
995
+ if (!(await verifyAdminPassword(authData.password, request.payload.password, request.logger))) {
996
+ return h.response({ error: 'Invalid password' }).code(403);
997
+ }
998
+
860
999
  let options = await generateRegistrationOptions({
861
1000
  rpName: 'EmailEngine',
862
1001
  rpID: rpId,
@@ -873,7 +1012,7 @@ function init(args) {
873
1012
  }
874
1013
  });
875
1014
 
876
- let challengeId = await passkeys.storeChallenge(options.challenge);
1015
+ let challengeId = await passkeys.storeChallenge(options.challenge, passkeys.CHALLENGE_REGISTER);
877
1016
 
878
1017
  return h.response({ challengeId, options }).code(200);
879
1018
  } catch (err) {
@@ -911,7 +1050,23 @@ function init(args) {
911
1050
  return h.response({ error: 'Service URL must be configured' }).code(400);
912
1051
  }
913
1052
 
914
- let challenge = await passkeys.consumeChallenge(request.payload.challengeId);
1053
+ let authData = await settings.get('authData');
1054
+ if (!authData || !authData.password) {
1055
+ return h.response({ error: 'Account password must be configured before registering passkeys' }).code(403);
1056
+ }
1057
+
1058
+ // The password is confirmed again here, not only when the options were issued:
1059
+ // this is the request that stores a permanent credential, and a check one hop
1060
+ // upstream is only as good as the binding between the two hops. Belt and braces
1061
+ // over the challenge namespacing - a future third way to obtain a registration
1062
+ // challenge would otherwise reopen the bypass. Checked before the challenge is
1063
+ // consumed, so a mistyped password does not burn the nonce and force the whole
1064
+ // ceremony to be repeated.
1065
+ if (!(await verifyAdminPassword(authData.password, request.payload.password, request.logger))) {
1066
+ return h.response({ error: 'Invalid password' }).code(403);
1067
+ }
1068
+
1069
+ let challenge = await passkeys.consumeChallenge(request.payload.challengeId, passkeys.CHALLENGE_REGISTER);
915
1070
  if (!challenge) {
916
1071
  return h.response({ error: 'Challenge expired or invalid. Please try again.' }).code(400);
917
1072
  }
@@ -930,11 +1085,6 @@ function init(args) {
930
1085
  let { credential } = verification.registrationInfo;
931
1086
  let user = (request.auth && request.auth.credentials && request.auth.credentials.user) || 'admin';
932
1087
 
933
- let authData = await settings.get('authData');
934
- if (!authData || !authData.password) {
935
- return h.response({ error: 'Account password must be configured before registering passkeys' }).code(403);
936
- }
937
-
938
1088
  let saved = await passkeys.saveCredentialIfUnderLimit(
939
1089
  {
940
1090
  id: credential.id,
@@ -974,6 +1124,7 @@ function init(args) {
974
1124
  },
975
1125
  payload: Joi.object({
976
1126
  challengeId: Joi.string().hex().length(64).required(),
1127
+ password: Joi.string().max(256).allow('', null).optional().label('Current password'),
977
1128
  name: Joi.string().max(100).empty('').default('Unnamed passkey'),
978
1129
  credential: passkeyCredentialSchema
979
1130
  })
@@ -1009,7 +1160,7 @@ function init(args) {
1009
1160
  await request.flash({ type: 'danger', message: 'Failed to remove passkey' });
1010
1161
  request.logger.error({ msg: 'Failed to delete passkey', err });
1011
1162
  }
1012
- return h.redirect('/admin/account/security');
1163
+ return h.redirect('/admin/account/passkeys');
1013
1164
  },
1014
1165
  options: {
1015
1166
  validate: {
@@ -1022,7 +1173,7 @@ function init(args) {
1022
1173
  async failAction(request, h, err) {
1023
1174
  await request.flash({ type: 'danger', message: 'Failed to remove passkey' });
1024
1175
  request.logger.debug({ msg: 'Failed to delete passkey', err });
1025
- return h.redirect('/admin/account/security').takeover();
1176
+ return h.redirect('/admin/account/passkeys').takeover();
1026
1177
  },
1027
1178
 
1028
1179
  payload: Joi.object({
@@ -1070,7 +1221,7 @@ function init(args) {
1070
1221
  userVerification: 'required'
1071
1222
  });
1072
1223
 
1073
- let challengeId = await passkeys.storeChallenge(options.challenge);
1224
+ let challengeId = await passkeys.storeChallenge(options.challenge, passkeys.CHALLENGE_AUTH);
1074
1225
 
1075
1226
  return h.response({ challengeId, options }).code(200);
1076
1227
  } catch (err) {
@@ -1120,7 +1271,7 @@ function init(args) {
1120
1271
  return h.response({ success: false, error: 'Authentication failed' }).code(400);
1121
1272
  }
1122
1273
 
1123
- let challenge = await passkeys.consumeChallenge(request.payload.challengeId);
1274
+ let challenge = await passkeys.consumeChallenge(request.payload.challengeId, passkeys.CHALLENGE_AUTH);
1124
1275
  if (!challenge) {
1125
1276
  request.logger.warn({ msg: 'Passkey auth failed: challenge expired or invalid', method: 'passkey', remoteAddress: request.app.ip });
1126
1277
  return h.response({ success: false, error: 'Challenge expired or invalid. Please try again.' }).code(400);
@@ -1159,7 +1310,7 @@ function init(args) {
1159
1310
  return h.response({ success: false, error: 'Authentication failed' }).code(400);
1160
1311
  }
1161
1312
 
1162
- await passkeys.updateCounter(storedCredential.id, verification.authenticationInfo.newCounter);
1313
+ await passkeys.recordAuthentication(storedCredential.id, verification.authenticationInfo.newCounter);
1163
1314
 
1164
1315
  setAdminSession(request, {
1165
1316
  user,
@@ -1230,7 +1381,9 @@ function init(args) {
1230
1381
  activePassword: true,
1231
1382
  disableAuthWarning: true,
1232
1383
 
1233
- username
1384
+ username,
1385
+ // the form warns that a password change removes these
1386
+ passkeyCount: await passkeys.countCredentials(username)
1234
1387
  },
1235
1388
  {
1236
1389
  layout: 'app'
@@ -1251,30 +1404,11 @@ function init(args) {
1251
1404
  let authData = await settings.get('authData');
1252
1405
  let hasExistingPassword = !!(authData && authData.password);
1253
1406
  if (hasExistingPassword) {
1254
- // The current-password field is a password check like the login form's, and
1255
- // unthrottled it let a hijacked session guess the password at full speed - the
1256
- // one thing a session alone is not supposed to reveal. Keyed on the account
1257
- // rather than the address because the caller is already authenticated as it,
1258
- // and the same budget as the login form's per-username limiter.
1259
- let rateLimit = await h.checkRateLimit(`password:verify:${authData.user || 'admin'}`, 1, 10, 60);
1260
- if (!rateLimit.success) {
1261
- request.logger.warn({ msg: 'Rate limited', rateLimit, remoteAddress: request.app.ip });
1262
- let err = new Error('Rate limited, please wait and try again');
1263
- err.details = { password0: err.message };
1264
- throw err;
1265
- }
1266
-
1267
- let valid;
1268
- try {
1269
- valid = await pbkdf2.verify(authData.password, request.payload.password0);
1270
- } catch (E) {
1271
- // verify() only throws on a malformed stored hash, not on a wrong password
1272
- request.logger.error({ msg: 'Failed to verify password hash', err: E });
1273
- valid = false;
1274
- }
1275
- if (!valid) {
1276
- request.logger.warn({ msg: 'Invalid current password', remoteAddress: request.app.ip });
1277
- let err = new Error('Failed to verify current password');
1407
+ let verified = await verifyCurrentPassword(request, h, authData, request.payload.password0);
1408
+ if (!verified.ok) {
1409
+ let err = new Error(
1410
+ verified.reason === 'rateLimited' ? 'Rate limited, please wait and try again' : 'Failed to verify current password'
1411
+ );
1278
1412
  err.details = { password0: err.message };
1279
1413
  throw err;
1280
1414
  }
@@ -1293,9 +1427,14 @@ function init(args) {
1293
1427
 
1294
1428
  await settings.set('authData', authData);
1295
1429
 
1430
+ // Every passkey goes with the old password: registering one takes the password,
1431
+ // so a passkey that outlived a password change could be one registered by whoever
1432
+ // had the old password. The form warns about this while passkeys exist, and the
1433
+ // flash below says how many went.
1434
+ let clearedPasskeys = 0;
1296
1435
  try {
1297
- await passkeys.deleteAllCredentials(authData.user || 'admin');
1298
- request.logger.info({ msg: 'All passkeys cleared after password change', user: authData.user || 'admin' });
1436
+ clearedPasskeys = await passkeys.deleteAllCredentials(authData.user || 'admin');
1437
+ request.logger.info({ msg: 'All passkeys cleared after password change', user: authData.user || 'admin', cleared: clearedPasskeys });
1299
1438
  } catch (passkeyErr) {
1300
1439
  request.logger.error({ msg: 'Failed to clear passkeys after password change', err: passkeyErr });
1301
1440
  }
@@ -1306,6 +1445,16 @@ function init(args) {
1306
1445
  user: authData.user,
1307
1446
  passwordVersion: authData.passwordVersion
1308
1447
  });
1448
+
1449
+ // Only this API worker's server got the default strategy above. With
1450
+ // EENGINE_WORKERS_API > 1 the other workers decided at boot that the instance
1451
+ // is open (settings.isInstanceSecured() was false then) and would keep serving
1452
+ // /admin without a login until restarted, so the same settings broadcast the
1453
+ // network config page uses tells every API worker to apply it (workers/api.js
1454
+ // handles the authData key). The value is a marker, not the credential.
1455
+ if (parentPort) {
1456
+ parentPort.postMessage({ cmd: 'settings', data: { authData: true } });
1457
+ }
1309
1458
  } else {
1310
1459
  request.cookieAuth.set('passwordVersion', authData.passwordVersion);
1311
1460
  }
@@ -1320,7 +1469,12 @@ function init(args) {
1320
1469
  return h.redirect('/admin');
1321
1470
  }
1322
1471
 
1323
- await request.flash({ type: 'info', message: `Password updated` });
1472
+ await request.flash({
1473
+ type: 'info',
1474
+ message: clearedPasskeys
1475
+ ? `Password updated and ${clearedPasskeys} registered passkey${clearedPasskeys === 1 ? '' : 's'} removed`
1476
+ : `Password updated`
1477
+ });
1324
1478
 
1325
1479
  return h.redirect('/admin/account/password');
1326
1480
  } catch (err) {
@@ -1338,7 +1492,8 @@ function init(args) {
1338
1492
  disableAuthWarning: true,
1339
1493
  errors: err.details,
1340
1494
 
1341
- username
1495
+ username,
1496
+ passkeyCount: await passkeys.countCredentials(username)
1342
1497
  },
1343
1498
  {
1344
1499
  layout: 'app'
@@ -98,7 +98,7 @@ function init(args) {
98
98
  color: typeof stats.redisPing !== 'number' ? 'warning' : stats.redisPing < ALLOWED_REDIS_LATENCY ? 'success' : 'danger',
99
99
  icon: 'icon-[tabler--clock]',
100
100
  comment: 'How many milliseconds does it take to run a Redis command',
101
- value: typeof stats.redisPing !== 'number' ? '\u2013' : nrFormatter.format(stats.redisPing / 1000000)
101
+ value: typeof stats.redisPing !== 'number' ? '-' : nrFormatter.format(stats.redisPing / 1000000)
102
102
  }
103
103
  },
104
104
  {
@@ -240,6 +240,8 @@ function init(args) {
240
240
  let killed = await call({ cmd: 'kill-thread', thread: request.payload.thread });
241
241
  if (killed) {
242
242
  await request.flash({ type: 'info', message: `Worker stopped` });
243
+ } else {
244
+ await request.flash({ type: 'danger', message: `Requested worker thread was not found` });
243
245
  }
244
246
 
245
247
  return h.redirect('/admin/internals');
@@ -7,7 +7,7 @@
7
7
  // Nothing reachable before the human clicks ever redirects off this origin. RFC 6749 4.1.2.1
8
8
  // only forbids redirecting when the client or the redirect_uri cannot be validated, and an
9
9
  // earlier revision of this file followed that literally: a validated-but-malformed request
10
- // (wrong response_type, a code_challenge_method other than S256, a resource naming another
10
+ // (wrong response_type, a code_challenge_method missing or other than S256, a resource naming another
11
11
  // server) bounced straight back to the client's address with ?error=. Client registration is
12
12
  // open and unauthenticated, so anyone could register their own https redirect_uri and turn that
13
13
  // into a no-interaction redirect off the admin origin - an open redirector aimed by whoever
@@ -173,7 +173,10 @@ async function init(args) {
173
173
  return renderError(h, `This client asked for an unsupported response type ("${request.query.response_type}"). Only "code" is supported.`);
174
174
  }
175
175
 
176
- if (request.query.code_challenge_method && request.query.code_challenge_method !== 'S256') {
176
+ // An absent method is not S256: RFC 7636 defaults it to "plain", which the token
177
+ // endpoint refuses - so a client that omits it would clear consent and only fail at
178
+ // the exchange, where nobody is looking. Required explicitly, the reason renders here.
179
+ if (request.query.code_challenge_method !== 'S256') {
177
180
  return renderError(h, 'This client asked for an unsupported PKCE method. Only "S256" is supported.');
178
181
  }
179
182
 
@@ -13,7 +13,7 @@ const { parentPort } = require('worker_threads');
13
13
  const settings = require('../settings');
14
14
  const { redis } = require('../db');
15
15
  const { REDIS_PREFIX } = require('../consts');
16
- const { failAction, getServiceHostname } = require('../tools');
16
+ const { failAction, getServiceHostname, reloadTlsServers } = require('../tools');
17
17
  const { ADDRESS_STRATEGIES, settingsSchema } = require('../schemas');
18
18
  const { updatePublicInterfaces } = require('../utils/network');
19
19
  const { getServerStatus, cachedTemplates } = require('./route-helpers');
@@ -362,9 +362,18 @@ function init(args) {
362
362
  path: '/admin/config/smtp/certificate',
363
363
  async handler(request, h) {
364
364
  try {
365
+ // What is installed before provisioning, so the reload below fires only when a new
366
+ // certificate actually arrived and repeated clicks do not keep restarting both
367
+ // servers.
368
+ let existingCertificateData = await h.getCertificate();
369
+
365
370
  let certificateData = await h.getCertificate(true);
366
371
  if (!certificateData) {
367
- throw new Error(`Failed to provision a ceritifcate`);
372
+ throw new Error(`Failed to provision a certificate`);
373
+ }
374
+
375
+ if (certificateData.fingerprint && certificateData.fingerprint !== (existingCertificateData && existingCertificateData.fingerprint)) {
376
+ await reloadTlsServers(call, request.logger, { domain: certificateData.domain });
368
377
  }
369
378
 
370
379
  return {
@@ -376,7 +385,7 @@ function init(args) {
376
385
  label: certificateData.label
377
386
  };
378
387
  } catch (err) {
379
- request.logger.error({ msg: 'Failed to request syncing', err });
388
+ request.logger.error({ msg: 'Failed to provision a certificate', err });
380
389
  return {
381
390
  success: false,
382
391
  error: err.message
@@ -18,7 +18,7 @@ const { Account } = require('../account');
18
18
  const { oauth2Apps, OAUTH_PROVIDERS, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
19
19
  const { verifyOAuth2App } = require('../oauth/verify-app');
20
20
  const { oauthCreateSchema, oauthUpdateSchema, accountIdSchema } = require('../schemas');
21
- const { throwAsBoom, adminUrl } = require('./route-helpers');
21
+ const { throwAsBoom, adminUrl, submittedValues } = require('./route-helpers');
22
22
 
23
23
  const { DEFAULT_PAGE_SIZE } = consts;
24
24
 
@@ -758,6 +758,11 @@ function init(args) {
758
758
  return entry;
759
759
  }),
760
760
 
761
+ // The submitted fields, not the stored app: without them the new-app form
762
+ // loses its provider on a validation error and the next submit is bounced
763
+ // to /admin
764
+ values: submittedValues(request, 'clientSecret', 'serviceKey'),
765
+
761
766
  authorityCommon: request.payload.authority === 'common',
762
767
  authorityOrganizations: request.payload.authority === 'organizations',
763
768
  authorityConsumers: request.payload.authority === 'consumers',
@@ -830,6 +835,8 @@ function init(args) {
830
835
  return entry;
831
836
  }),
832
837
 
838
+ values: submittedValues(request, 'clientSecret', 'serviceKey'),
839
+
833
840
  authorityCommon: request.payload.authority === 'common',
834
841
  authorityOrganizations: request.payload.authority === 'organizations',
835
842
  authorityConsumers: request.payload.authority === 'consumers',
@@ -1015,6 +1022,8 @@ function init(args) {
1015
1022
  return entry;
1016
1023
  }),
1017
1024
 
1025
+ values: submittedValues(request, 'clientSecret', 'serviceKey'),
1026
+
1018
1027
  authorityCommon: request.payload.authority === 'common',
1019
1028
  authorityOrganizations: request.payload.authority === 'organizations',
1020
1029
  authorityConsumers: request.payload.authority === 'consumers',
@@ -1098,6 +1107,8 @@ function init(args) {
1098
1107
  return entry;
1099
1108
  }),
1100
1109
 
1110
+ values: submittedValues(request, 'clientSecret', 'serviceKey'),
1111
+
1101
1112
  authorityCommon: request.payload.authority === 'common',
1102
1113
  authorityOrganizations: request.payload.authority === 'organizations',
1103
1114
  authorityConsumers: request.payload.authority === 'consumers',