@jskit-ai/auth-web 0.2.11 → 0.2.12

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ - While the app has no account (`features.firstAccountSetupCode`), the registration form explains that the first account becomes the owner and asks for the setup code from the server's log or its hosting service, and sends it as `setupCode`. New message keys: `jskit.auth.login.firstAccount.explain` and `jskit.auth.login.field.setupCode`.
6
+ - Email confirmation on the sign-in page: "Confirm your email" has a field for the emailed link or its code, and in development, when the registration's answer carries the link, shows it with a button that confirms it. Opening the emailed link (`/auth/login?confirmation_token=...`) confirms it and takes the code out of the address. Confirming signs the person in and opens the requested page. A sign-in refused with `auth.login.emailUnconfirmed` opens "Confirm your email" instead of an error. New route `POST /api/register/confirm`, which writes the new session's cookies, limited by `config.auth.rateLimits.registerConfirm` (10 a minute); the register answer carries `confirmationUrl` when the provider gives it. New message keys: `jskit.auth.register.confirmed`, `jskit.auth.login.field.confirmationCode`, `jskit.auth.login.confirmEmail.confirm`, `.devLink`, `.useDevLink` and `jskit.auth.login.error.confirmRegistrationFailed`.
7
+ - The auth routes' rate limits apply, per client address: `login`, `register`, `loginOtpRequest` and `loginOtpVerify` 10 a minute; `registerConfirmationResend` and `passwordForgot` 5; `oauthStart`, `oauthComplete`, `passwordRecovery` and `passwordReset` 20; `devLoginAs` 30. A refused request answers 429 with `kernel.http.rateLimited` and `Retry-After`, and the login page shows it.
8
+ - `config.auth.rateLimits.<route>` changes a route's limit (`{ max, timeWindow }`, merged over the default) or removes it (`false`); an unknown route name or a malformed value stops startup. `AuthWebFeature` therefore requires `runtime.config`, which every installed runtime provides.
9
+
3
10
  ## 0.2.0 - 2026-10-29
4
11
 
5
12
  - Translation ready: every user-visible text is a message key with its English in `locales/en.json`, so an app translates it by supplying translation files only. With no translations, texts and behaviour are unchanged. See the guide "Translating a JSKIT app".
package/locales/en.json CHANGED
@@ -2,7 +2,8 @@
2
2
  "jskit": {
3
3
  "auth": {
4
4
  "register": {
5
- "confirmEmail": "Check your email to confirm the account before logging in."
5
+ "confirmEmail": "Check your email to confirm the account before logging in.",
6
+ "confirmed": "Your email is confirmed."
6
7
  },
7
8
  "login": {
8
9
  "title": {
@@ -33,13 +34,21 @@
33
34
  "email": "Email",
34
35
  "password": "Password",
35
36
  "confirmPassword": "Confirm password",
36
- "otpCode": "One-time code"
37
+ "otpCode": "One-time code",
38
+ "confirmationCode": "Confirmation link or code",
39
+ "setupCode": "Setup code"
37
40
  },
38
41
  "confirmEmail": {
39
42
  "message": "Please confirm your email address. After confirmation, you can sign in.",
40
43
  "goToMainScreen": "Go to main screen",
41
44
  "resend": "Resend confirmation email",
42
- "resent": "If an account exists for that email, a confirmation email has been sent."
45
+ "resent": "If an account exists for that email, a confirmation email has been sent.",
46
+ "confirm": "Confirm",
47
+ "devLink": "Development: no email is sent, so here is the confirmation link.",
48
+ "useDevLink": "Confirm with this link"
49
+ },
50
+ "firstAccount": {
51
+ "explain": "This app has no account yet. Its first account becomes its owner, so it needs the setup code the server wrote in its log when it started, or that its hosting service shows its owner."
43
52
  },
44
53
  "rememberedAccount": {
45
54
  "welcomeBack": "Welcome back, {name}",
@@ -74,6 +83,7 @@
74
83
  "otpRequestFailed": "Unable to request one-time code.",
75
84
  "emailRequiredForConfirmation": "Enter an email address before requesting confirmation.",
76
85
  "resendConfirmationFailed": "Unable to resend confirmation email.",
86
+ "confirmRegistrationFailed": "Unable to confirm the email address.",
77
87
  "oauthCompleteFailed": "Unable to complete OAuth sign-in.",
78
88
  "oauthProviderInvalid": "OAuth provider id is invalid.",
79
89
  "oauthReturnToInvalid": "OAuth return path is invalid.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-web",
3
- "version": "0.2.11",
3
+ "version": "0.2.12",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -28,10 +28,10 @@
28
28
  "@mdi/js": "^7.4.47"
29
29
  },
30
30
  "peerDependencies": {
31
- "@jskit-ai/auth-core": "0.2.8",
32
- "@jskit-ai/http-runtime": "0.2.8",
33
- "@jskit-ai/kernel": "0.2.8",
34
- "@jskit-ai/shell-web": "0.2.9",
31
+ "@jskit-ai/auth-core": "0.2.9",
32
+ "@jskit-ai/http-runtime": "0.2.9",
33
+ "@jskit-ai/kernel": "0.2.9",
34
+ "@jskit-ai/shell-web": "0.2.10",
35
35
  "@tanstack/vue-query": "^5.90.5",
36
36
  "pinia": "^4.0.3",
37
37
  "vue": "^3.5.44",
@@ -48,6 +48,7 @@
48
48
  "requires": [
49
49
  "auth.service",
50
50
  "runtime.actions",
51
+ "runtime.config",
51
52
  "runtime.env",
52
53
  "runtime.http"
53
54
  ]
@@ -0,0 +1,38 @@
1
+ import { pageLocation, pageWindow } from "../../browser.js";
2
+
3
+ // The query parameter of the link a registration's confirmation email carries.
4
+ const CONFIRMATION_TOKEN_PARAM = "confirmation_token";
5
+
6
+ /**
7
+ * The code in a pasted confirmation link, or the pasted text itself when it is
8
+ * the bare code.
9
+ * @param {unknown} input
10
+ */
11
+ function confirmationTokenFromInput(input) {
12
+ const text = String(input || "").trim();
13
+ try {
14
+ return String(new URL(text).searchParams.get(CONFIRMATION_TOKEN_PARAM) || "").trim() || text;
15
+ } catch {
16
+ return text;
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Takes the confirmation code out of the page's address, so reloading the page
22
+ * or sharing its address does not send it again; "" when there is none.
23
+ */
24
+ function takeConfirmationTokenFromLocation() {
25
+ const location = pageLocation();
26
+ if (!location) {
27
+ return "";
28
+ }
29
+ const url = new URL(location.href);
30
+ const token = String(url.searchParams.get(CONFIRMATION_TOKEN_PARAM) || "").trim();
31
+ if (token) {
32
+ url.searchParams.delete(CONFIRMATION_TOKEN_PARAM);
33
+ pageWindow()?.history.replaceState({}, "", `${url.pathname}${url.search}${url.hash}`);
34
+ }
35
+ return token;
36
+ }
37
+
38
+ export { CONFIRMATION_TOKEN_PARAM, confirmationTokenFromInput, takeConfirmationTokenFromLocation };
@@ -1,6 +1,7 @@
1
1
  import { mdiGoogle } from "@mdi/js";
2
2
  import { authRegisterCommand } from "@jskit-ai/auth-core/shared/commands/authRegisterCommand";
3
3
  import { authRegisterConfirmationResendCommand } from "@jskit-ai/auth-core/shared/commands/authRegisterConfirmationResendCommand";
4
+ import { authRegisterConfirmCommand } from "@jskit-ai/auth-core/shared/commands/authRegisterConfirmCommand";
4
5
  import { authLoginPasswordCommand } from "@jskit-ai/auth-core/shared/commands/authLoginPasswordCommand";
5
6
  import { authLoginOtpRequestCommand } from "@jskit-ai/auth-core/shared/commands/authLoginOtpRequestCommand";
6
7
  import { authLoginOtpVerifyCommand } from "@jskit-ai/auth-core/shared/commands/authLoginOtpVerifyCommand";
@@ -16,6 +17,7 @@ import { stripOAuthParamsFromLocation } from "./oauthCallbackUrl.js";
16
17
  import { completeOAuthPopupSignIn } from "../../runtime/popupOAuthLaunchClient.js";
17
18
  import { ensureCommandSectionValid } from "./validationHelpers.js";
18
19
  import { resolveRegisterCompletionState } from "./registerCompletion.js";
20
+ import { confirmationTokenFromInput, takeConfirmationTokenFromLocation } from "./confirmationLink.js";
19
21
  import { inactiveSessionMessage } from "../../runtime/inactiveSessionMessage.js";
20
22
  import { replacePage } from "../../browser.js";
21
23
  import { useJskitText } from "../../i18n.js";
@@ -160,6 +162,10 @@ export function useLoginViewActions({ state, validation, queryClient, errorRunti
160
162
  email: normalizedEmail,
161
163
  password: String(state.password.value || "")
162
164
  };
165
+ const setupCode = String(state.setupCode.value || "").trim();
166
+ if (setupCode) {
167
+ registerPayload.setupCode = setupCode;
168
+ }
163
169
  const invitationToken = String(state.invitationToken.value || "").trim();
164
170
  if (invitationToken) {
165
171
  registerPayload.invitation = {
@@ -183,7 +189,8 @@ export function useLoginViewActions({ state, validation, queryClient, errorRunti
183
189
  if (!registerCompletion.shouldCompleteLogin) {
184
190
  state.enterEmailConfirmationPendingState({
185
191
  emailAddress: normalizedEmail,
186
- message: registerCompletion.message
192
+ message: registerCompletion.message,
193
+ confirmationUrl: registerResult?.confirmationUrl
187
194
  });
188
195
  return;
189
196
  }
@@ -239,10 +246,21 @@ export function useLoginViewActions({ state, validation, queryClient, errorRunti
239
246
  };
240
247
  ensureCommandSectionValid(authLoginPasswordCommand, "body", loginPayload, t("jskit.auth.login.error.signInFailed"));
241
248
 
242
- const loginResult = await request(AUTH_PATHS.LOGIN, {
243
- method: "POST",
244
- body: loginPayload
245
- });
249
+ let loginResult;
250
+ try {
251
+ loginResult = await request(AUTH_PATHS.LOGIN, {
252
+ method: "POST",
253
+ body: loginPayload
254
+ });
255
+ } catch (error) {
256
+ // The right password for a registration still waiting for its email:
257
+ // show how to confirm it instead of a failed sign-in.
258
+ if (error?.code !== "auth.login.emailUnconfirmed") {
259
+ throw error;
260
+ }
261
+ state.enterEmailConfirmationPendingState({ emailAddress: normalizedEmail, message: serverMessage(error) });
262
+ return;
263
+ }
246
264
  state.applyRememberedAccountPreference({
247
265
  email: normalizedEmail,
248
266
  displayName: loginResult?.username || normalizedEmail,
@@ -303,6 +321,10 @@ export function useLoginViewActions({ state, validation, queryClient, errorRunti
303
321
  }
304
322
 
305
323
  async function submitAuth() {
324
+ if (state.isEmailConfirmationPending.value) {
325
+ await confirmRegistrationCode();
326
+ return;
327
+ }
306
328
  state.submitAttempted.value = true;
307
329
  clearTransientMessages();
308
330
  if (!validation.canSubmit.value) {
@@ -389,6 +411,9 @@ export function useLoginViewActions({ state, validation, queryClient, errorRunti
389
411
  body: resendPayload
390
412
  });
391
413
  const info = serverMessage(resendResult).trim() || t("jskit.auth.login.confirmEmail.resent");
414
+ if (resendResult?.confirmationUrl) {
415
+ state.confirmationUrl.value = resendResult.confirmationUrl;
416
+ }
392
417
  setInfoMessage(info, "auth-web.default-login-view:register-confirmation-resend");
393
418
  } catch (error) {
394
419
  setErrorMessage(serverMessage(error, t("jskit.auth.login.error.resendConfirmationFailed")));
@@ -397,6 +422,51 @@ export function useLoginViewActions({ state, validation, queryClient, errorRunti
397
422
  }
398
423
  }
399
424
 
425
+ /**
426
+ * Confirms a registration from its link's code, or from the whole link,
427
+ * which signs the person in, and opens the requested page.
428
+ * @param {unknown} codeOrLink
429
+ */
430
+ async function confirmRegistration(codeOrLink) {
431
+ const confirmPayload = { token: confirmationTokenFromInput(codeOrLink) };
432
+ state.registrationConfirmPending.value = true;
433
+ clearTransientMessages();
434
+ try {
435
+ ensureCommandSectionValid(
436
+ authRegisterConfirmCommand,
437
+ "body",
438
+ confirmPayload,
439
+ t("jskit.auth.login.error.confirmRegistrationFailed")
440
+ );
441
+ const confirmResult = await request(AUTH_PATHS.REGISTER_CONFIRM, {
442
+ method: "POST",
443
+ body: confirmPayload
444
+ });
445
+ state.applyRememberedAccountPreference({
446
+ email: confirmResult?.email,
447
+ displayName: confirmResult?.username || confirmResult?.email,
448
+ shouldRemember: state.rememberAccountOnDevice.value !== false
449
+ });
450
+ setInfoMessage(
451
+ serverMessage(confirmResult).trim() || t("jskit.auth.register.confirmed"),
452
+ "auth-web.default-login-view:register-confirmed"
453
+ );
454
+ await completeLogin();
455
+ } catch (error) {
456
+ setErrorMessage(serverMessage(error, t("jskit.auth.login.error.confirmRegistrationFailed")));
457
+ } finally {
458
+ state.registrationConfirmPending.value = false;
459
+ }
460
+ }
461
+
462
+ function confirmRegistrationCode() {
463
+ return confirmRegistration(state.confirmationCode.value);
464
+ }
465
+
466
+ function confirmRegistrationFromLink() {
467
+ return confirmRegistration(state.confirmationUrl.value);
468
+ }
469
+
400
470
  function oauthProviderButtonLabel(provider) {
401
471
  const providerLabel = String(provider?.label || provider?.id || t("jskit.auth.login.oauth.providerFallback"));
402
472
  if (state.isRegister.value) {
@@ -461,9 +531,15 @@ export function useLoginViewActions({ state, validation, queryClient, errorRunti
461
531
 
462
532
  async function initializeOnMounted() {
463
533
  state.applyRememberedAccountHint(readRememberedAccountHint());
534
+ // Opened from a registration's confirmation email.
535
+ const confirmationToken = takeConfirmationTokenFromLocation();
464
536
  state.loading.value = true;
465
537
  try {
466
538
  const session = await refreshSession();
539
+ if (confirmationToken) {
540
+ await confirmRegistration(confirmationToken);
541
+ return;
542
+ }
467
543
  const callbackHandled = await handleOAuthCallbackIfPresent();
468
544
  if (!callbackHandled && session?.authenticated) {
469
545
  replacePage(state.requestedReturnTo.value);
@@ -495,6 +571,8 @@ export function useLoginViewActions({ state, validation, queryClient, errorRunti
495
571
  submitAuth,
496
572
  requestOtpCode,
497
573
  resendRegisterConfirmationEmail,
574
+ confirmRegistrationCode,
575
+ confirmRegistrationFromLink,
498
576
  oauthProviderButtonLabel,
499
577
  oauthProviderIcon,
500
578
  startOAuthSignIn,
@@ -45,6 +45,8 @@ export function useLoginViewState({ placementContext }) {
45
45
  const password = ref("");
46
46
  const confirmPassword = ref("");
47
47
  const otpCode = ref("");
48
+ // The first account's setup code, asked for while a production server has no account.
49
+ const setupCode = ref("");
48
50
  const showPassword = ref(false);
49
51
  const showConfirmPassword = ref(false);
50
52
  const emailTouched = ref(false);
@@ -61,10 +63,15 @@ export function useLoginViewState({ placementContext }) {
61
63
  const loading = ref(false);
62
64
  const otpRequestPending = ref(false);
63
65
  const registerConfirmationResendPending = ref(false);
66
+ const registrationConfirmPending = ref(false);
64
67
  const errorMessage = ref("");
65
68
  const infoMessage = ref("");
66
69
  const pendingEmailConfirmationMessage = ref("");
67
70
  const pendingEmailConfirmationAddress = ref("");
71
+ // In development without an email sender, the confirmation link itself.
72
+ const confirmationUrl = ref("");
73
+ // A confirmation code or link the person types or pastes.
74
+ const confirmationCode = ref("");
68
75
  const invitationToken = ref(readWindowSearchParam("invitationToken") || readWindowSearchParam("inviteToken"));
69
76
 
70
77
  const isLogin = computed(() => mode.value === LOGIN_MODE);
@@ -80,6 +87,8 @@ export function useLoginViewState({ placementContext }) {
80
87
  const canUseOtp = computed(() => authCapabilities.value.features.otp.login === true);
81
88
  const canUseOAuth = computed(() => authCapabilities.value.features.oauthLogin.enabled === true);
82
89
  const canResendEmailConfirmation = computed(() => authCapabilities.value.features.emailConfirmation === true);
90
+ const canEnterConfirmationCode = computed(() => authCapabilities.value.features.emailConfirmationCode === true);
91
+ const needsFirstAccountSetupCode = computed(() => authCapabilities.value.features.firstAccountSetupCode === true);
83
92
  const showRememberedAccount = computed(
84
93
  () => (isLogin.value || isOtp.value) && useRememberedAccount.value && Boolean(rememberedAccount.value)
85
94
  );
@@ -151,6 +160,7 @@ export function useLoginViewState({ placementContext }) {
151
160
  password.value = "";
152
161
  confirmPassword.value = "";
153
162
  otpCode.value = "";
163
+ setupCode.value = "";
154
164
  showPassword.value = false;
155
165
  showConfirmPassword.value = false;
156
166
  }
@@ -238,6 +248,8 @@ export function useLoginViewState({ placementContext }) {
238
248
  if (resolvedMode !== EMAIL_CONFIRMATION_MODE) {
239
249
  pendingEmailConfirmationAddress.value = "";
240
250
  pendingEmailConfirmationMessage.value = "";
251
+ confirmationUrl.value = "";
252
+ confirmationCode.value = "";
241
253
  }
242
254
  clearTransientMessages();
243
255
  resetTransientValidationState();
@@ -252,10 +264,11 @@ export function useLoginViewState({ placementContext }) {
252
264
  }
253
265
  }
254
266
 
255
- function enterEmailConfirmationPendingState({ emailAddress = "", message = "" } = {}) {
267
+ function enterEmailConfirmationPendingState({ emailAddress = "", message = "", confirmationUrl: url = "" } = {}) {
256
268
  switchMode(EMAIL_CONFIRMATION_MODE);
257
269
  pendingEmailConfirmationAddress.value = normalizeEmailAddress(emailAddress);
258
270
  pendingEmailConfirmationMessage.value = String(message || "").trim();
271
+ confirmationUrl.value = String(url || "").trim();
259
272
  }
260
273
 
261
274
  function goToMainScreen() {
@@ -268,6 +281,7 @@ export function useLoginViewState({ placementContext }) {
268
281
  password,
269
282
  confirmPassword,
270
283
  otpCode,
284
+ setupCode,
271
285
  showPassword,
272
286
  showConfirmPassword,
273
287
  emailTouched,
@@ -284,10 +298,13 @@ export function useLoginViewState({ placementContext }) {
284
298
  loading,
285
299
  otpRequestPending,
286
300
  registerConfirmationResendPending,
301
+ registrationConfirmPending,
287
302
  errorMessage,
288
303
  infoMessage,
289
304
  pendingEmailConfirmationMessage,
290
305
  pendingEmailConfirmationAddress,
306
+ confirmationUrl,
307
+ confirmationCode,
291
308
  invitationToken,
292
309
  isLogin,
293
310
  isRegister,
@@ -300,6 +317,8 @@ export function useLoginViewState({ placementContext }) {
300
317
  canUseOtp,
301
318
  canUseOAuth,
302
319
  canResendEmailConfirmation,
320
+ canEnterConfirmationCode,
321
+ needsFirstAccountSetupCode,
303
322
  showRememberedAccount,
304
323
  rememberedAccountDisplayName,
305
324
  rememberedAccountMaskedEmail,
@@ -112,6 +112,9 @@ export function useLoginViewValidation({ state }) {
112
112
  if (emailErrorMessages.value.length > 0) {
113
113
  return false;
114
114
  }
115
+ if (state.isRegister.value && state.needsFirstAccountSetupCode.value && !String(state.setupCode.value || "").trim()) {
116
+ return false;
117
+ }
115
118
  if (state.isRegister.value || state.isLogin.value) {
116
119
  return passwordErrorMessages.value.length < 1 && confirmPasswordErrorMessages.value.length < 1;
117
120
  }
@@ -40,6 +40,14 @@ function useLoginView() {
40
40
  canUseOtp: state.canUseOtp,
41
41
  canUseOAuth: state.canUseOAuth,
42
42
  canResendEmailConfirmation: state.canResendEmailConfirmation,
43
+ canEnterConfirmationCode: state.canEnterConfirmationCode,
44
+ needsFirstAccountSetupCode: state.needsFirstAccountSetupCode,
45
+ setupCode: state.setupCode,
46
+ confirmationUrl: state.confirmationUrl,
47
+ confirmationCode: state.confirmationCode,
48
+ registrationConfirmPending: state.registrationConfirmPending,
49
+ confirmRegistrationCode: actions.confirmRegistrationCode,
50
+ confirmRegistrationFromLink: actions.confirmRegistrationFromLink,
43
51
  emailConfirmationMessage: state.emailConfirmationMessage,
44
52
  showRememberedAccount: state.showRememberedAccount,
45
53
  switchMode: state.switchMode,
@@ -54,6 +54,45 @@
54
54
  </p>
55
55
  </div>
56
56
 
57
+ <div v-if="confirmationUrl" class="email-confirmation-dev-link mb-5" data-testid="auth-confirmation-dev-link">
58
+ <p class="text-medium-emphasis mb-2">{{ t("jskit.auth.login.confirmEmail.devLink") }}</p>
59
+ <p class="email-confirmation-url mb-3">{{ confirmationUrl }}</p>
60
+ <v-btn
61
+ class="text-none"
62
+ variant="flat"
63
+ color="primary"
64
+ data-testid="auth-confirmation-dev-confirm"
65
+ :loading="registrationConfirmPending"
66
+ @click="confirmRegistrationFromLink"
67
+ >
68
+ {{ t("jskit.auth.login.confirmEmail.useDevLink") }}
69
+ </v-btn>
70
+ </div>
71
+
72
+ <div v-if="canEnterConfirmationCode" class="email-confirmation-code d-flex align-start ga-2 mb-5">
73
+ <v-text-field
74
+ v-model="confirmationCode"
75
+ data-testid="auth-confirmation-code"
76
+ :label="t('jskit.auth.login.field.confirmationCode')"
77
+ variant="outlined"
78
+ density="comfortable"
79
+ autocomplete="off"
80
+ hide-details="auto"
81
+ />
82
+ <v-btn
83
+ class="text-none mt-1"
84
+ variant="tonal"
85
+ color="primary"
86
+ size="large"
87
+ type="submit"
88
+ data-testid="auth-confirmation-submit"
89
+ :disabled="!confirmationCode.trim()"
90
+ :loading="registrationConfirmPending"
91
+ >
92
+ {{ t("jskit.auth.login.confirmEmail.confirm") }}
93
+ </v-btn>
94
+ </div>
95
+
57
96
  <div class="switch-row d-flex align-center justify-space-between ga-3">
58
97
  <v-btn class="text-none" variant="tonal" color="primary" @click="goToMainScreen">
59
98
  {{ t("jskit.auth.login.confirmEmail.goToMainScreen") }}
@@ -90,6 +129,23 @@
90
129
  </v-btn>
91
130
  </div>
92
131
 
132
+ <div
133
+ v-if="isRegister && needsFirstAccountSetupCode"
134
+ class="first-account-setup mb-4"
135
+ data-testid="auth-first-account-setup"
136
+ >
137
+ <p class="text-medium-emphasis mb-3">{{ t("jskit.auth.login.firstAccount.explain") }}</p>
138
+ <v-text-field
139
+ v-model="setupCode"
140
+ :label="t('jskit.auth.login.field.setupCode')"
141
+ variant="outlined"
142
+ density="comfortable"
143
+ autocomplete="off"
144
+ spellcheck="false"
145
+ hide-details="auto"
146
+ />
147
+ </div>
148
+
93
149
  <v-text-field
94
150
  v-if="!isLogin || canUsePasswordLogin"
95
151
  v-model="email"
@@ -259,6 +315,13 @@ const {
259
315
  canUseOtp,
260
316
  canUseOAuth,
261
317
  canResendEmailConfirmation,
318
+ canEnterConfirmationCode,
319
+ needsFirstAccountSetupCode,
320
+ setupCode,
321
+ confirmationUrl,
322
+ confirmationCode,
323
+ registrationConfirmPending,
324
+ confirmRegistrationFromLink,
262
325
  emailConfirmationMessage,
263
326
  showRememberedAccount,
264
327
  switchMode,
@@ -372,6 +435,25 @@ function toggleConfirmPasswordVisibility() {
372
435
  line-height: 1.5;
373
436
  }
374
437
 
438
+ .first-account-setup {
439
+ border-radius: 12px;
440
+ border: 1px solid rgba(var(--v-theme-warning), 0.5);
441
+ background: rgba(var(--v-theme-warning), 0.08);
442
+ padding: 16px;
443
+ }
444
+
445
+ .email-confirmation-dev-link {
446
+ border-radius: 12px;
447
+ border: 1px dashed rgba(var(--v-theme-on-surface), 0.34);
448
+ padding: 16px;
449
+ }
450
+
451
+ .email-confirmation-url {
452
+ font-family: monospace;
453
+ font-size: 0.85rem;
454
+ overflow-wrap: anywhere;
455
+ }
456
+
375
457
  .remembered-account {
376
458
  border-radius: 12px;
377
459
  border: 1px solid rgba(var(--v-theme-primary), 0.34);
@@ -6,6 +6,7 @@ const AuthWebFeature = defineFeature({
6
6
  domain: "auth",
7
7
  requires: {
8
8
  authService: "auth.service",
9
+ config: "runtime.config",
9
10
  env: "runtime.env",
10
11
  http: "runtime.http"
11
12
  },
@@ -15,11 +16,12 @@ const AuthWebFeature = defineFeature({
15
16
  /**
16
17
  * @param {object} capabilities
17
18
  * @param {import("@jskit-ai/auth-core/server/types").AuthService} capabilities.authService
19
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeConfig} capabilities.config
18
20
  * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} capabilities.env
19
21
  * @param {import("@jskit-ai/kernel/server/types").RuntimeHttp} capabilities.http
20
22
  */
21
- setup({ authService, env, http }) {
22
- const authWeb = createAuthWeb({ authService, env });
23
+ setup({ authService, config, env, http }) {
24
+ const authWeb = createAuthWeb({ authService, env, config });
23
25
  for (const route of authWeb.routes) {
24
26
  http.router.register(route.method, route.path, route, route.handler);
25
27
  }
@@ -0,0 +1,59 @@
1
+ import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
2
+
3
+ /**
4
+ * The auth routes' default rate limits, per client address. Sign-in also limits
5
+ * failed attempts per account, in the provider; these limits bound how fast one
6
+ * address can try anything at all.
7
+ */
8
+ const DEFAULT_AUTH_RATE_LIMITS = Object.freeze({
9
+ register: Object.freeze({ max: 10, timeWindow: "1 minute" }),
10
+ registerConfirmationResend: Object.freeze({ max: 5, timeWindow: "1 minute" }),
11
+ registerConfirm: Object.freeze({ max: 10, timeWindow: "1 minute" }),
12
+ login: Object.freeze({ max: 10, timeWindow: "1 minute" }),
13
+ loginOtpRequest: Object.freeze({ max: 10, timeWindow: "1 minute" }),
14
+ loginOtpVerify: Object.freeze({ max: 10, timeWindow: "1 minute" }),
15
+ oauthStart: Object.freeze({ max: 20, timeWindow: "1 minute" }),
16
+ oauthComplete: Object.freeze({ max: 20, timeWindow: "1 minute" }),
17
+ devLoginAs: Object.freeze({ max: 30, timeWindow: "1 minute" }),
18
+ passwordForgot: Object.freeze({ max: 5, timeWindow: "1 minute" }),
19
+ passwordRecovery: Object.freeze({ max: 20, timeWindow: "1 minute" }),
20
+ passwordReset: Object.freeze({ max: 20, timeWindow: "1 minute" })
21
+ });
22
+
23
+ /**
24
+ * Each auth route's rate limit: its default, with the fields the application's
25
+ * `config.auth.rateLimits.<route>` gives over it, or none when that is false.
26
+ * A route name the defaults do not have stops startup, so a misspelt override
27
+ * is never silently ignored.
28
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeConfig} config
29
+ * @returns {Readonly<Record<keyof typeof DEFAULT_AUTH_RATE_LIMITS, { max: number, timeWindow: string | number } | null>>}
30
+ */
31
+ function resolveAuthRateLimits(config) {
32
+ const configured = isRecord(config.auth) && config.auth.rateLimits !== undefined ? config.auth.rateLimits : {};
33
+ if (!isRecord(configured)) {
34
+ throw new Error("config.auth.rateLimits must be an object of route names.");
35
+ }
36
+ for (const name of Object.keys(configured)) {
37
+ if (!Object.hasOwn(DEFAULT_AUTH_RATE_LIMITS, name)) {
38
+ throw new Error(
39
+ `config.auth.rateLimits.${name} names no auth route. Use one of: ${Object.keys(DEFAULT_AUTH_RATE_LIMITS).join(", ")}.`
40
+ );
41
+ }
42
+ }
43
+ const limits = {};
44
+ for (const [name, defaultLimit] of Object.entries(DEFAULT_AUTH_RATE_LIMITS)) {
45
+ const override = configured[name];
46
+ if (override === false) {
47
+ limits[name] = null;
48
+ } else if (override === undefined) {
49
+ limits[name] = defaultLimit;
50
+ } else if (isRecord(override)) {
51
+ limits[name] = Object.freeze({ ...defaultLimit, ...override });
52
+ } else {
53
+ throw new Error(`config.auth.rateLimits.${name} must be { max, timeWindow } or false.`);
54
+ }
55
+ }
56
+ return Object.freeze(limits);
57
+ }
58
+
59
+ export { DEFAULT_AUTH_RATE_LIMITS, resolveAuthRateLimits };
@@ -1,4 +1,5 @@
1
1
  import { isDevAuthBootstrapEnabled, resolveDevAuthPolicyFromEnv } from "@jskit-ai/auth-core/server/devAuth";
2
+ import { resolveAuthRateLimits } from "./authRateLimits.js";
2
3
  import { AuthController } from "./controllers/AuthController.js";
3
4
  import { buildRoutes } from "./routes/authRoutes.js";
4
5
  import { AuthWebService } from "./services/AuthWebService.js";
@@ -11,15 +12,17 @@ import { AuthWebService } from "./services/AuthWebService.js";
11
12
  * @param {object} dependencies
12
13
  * @param {import("@jskit-ai/auth-core/server/types").AuthService} dependencies.authService
13
14
  * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
15
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeConfig} dependencies.config
14
16
  */
15
- function createAuthWeb({ authService, env }) {
17
+ function createAuthWeb({ authService, env, config }) {
16
18
  const service = new AuthWebService({
17
19
  authService,
18
20
  devAuthBootstrapEnabled: isDevAuthBootstrapEnabled(resolveDevAuthPolicyFromEnv(env))
19
21
  });
20
22
  const controller = new AuthController({ service });
21
23
  const routes = buildRoutes(controller, {
22
- includeDevLoginAs: service.isDevLoginAsAvailable()
24
+ includeDevLoginAs: service.isDevLoginAsAvailable(),
25
+ rateLimits: resolveAuthRateLimits(config)
23
26
  });
24
27
  return Object.freeze({
25
28
  controller,
@@ -1,6 +1,7 @@
1
1
  const AUTH_ACTION_IDS = Object.freeze({
2
2
  REGISTER: "auth.register",
3
3
  REGISTER_CONFIRMATION_RESEND: "auth.register.confirmation.resend",
4
+ REGISTER_CONFIRM: "auth.register.confirm",
4
5
  LOGIN_PASSWORD: "auth.login.password",
5
6
  LOGIN_OTP_REQUEST: "auth.login.otp.request",
6
7
  LOGIN_OTP_VERIFY: "auth.login.otp.verify",
@@ -26,7 +26,9 @@ class AuthController {
26
26
  requiresEmailConfirmation: true,
27
27
  message: "Check your email to confirm the account before logging in.",
28
28
  messageCode: "auth.register.confirmEmail",
29
- messageParams: {}
29
+ messageParams: {},
30
+ // In development without an email sender, the link to open instead.
31
+ ...(result.confirmationUrl ? { confirmationUrl: result.confirmationUrl } : {})
30
32
  });
31
33
  return;
32
34
  }
@@ -44,6 +46,21 @@ class AuthController {
44
46
  reply.code(200).send(result);
45
47
  }
46
48
 
49
+ /** Creates the account a registration waited to create, and signs the person in. */
50
+ async confirmRegistration(request, reply) {
51
+ const payload = request.body || {};
52
+ const result = await this.service.confirmRegistration(request, payload);
53
+ this.service.writeSessionCookies(reply, result.session);
54
+ reply.code(200).send({
55
+ ok: true,
56
+ email: result.actor.email,
57
+ username: result.actor.displayName,
58
+ message: "Your email is confirmed.",
59
+ messageCode: "auth.register.confirmed",
60
+ messageParams: {}
61
+ });
62
+ }
63
+
47
64
  async login(request, reply) {
48
65
  const payload = request.body || {};
49
66
  const result = await this.service.login(request, payload);
@@ -2,6 +2,7 @@ import { withStandardErrorResponses } from "@jskit-ai/http-runtime/shared/valida
2
2
  import {
3
3
  authRegisterCommand,
4
4
  authRegisterConfirmationResendCommand,
5
+ authRegisterConfirmCommand,
5
6
  authLoginPasswordCommand,
6
7
  authLoginOtpRequestCommand,
7
8
  authLoginOtpVerifyCommand,
@@ -15,12 +16,18 @@ import {
15
16
  authSessionReadCommand
16
17
  } from "@jskit-ai/auth-core/shared/commands";
17
18
  import { AUTH_PATHS } from "@jskit-ai/auth-core/shared/authPaths";
19
+ import { DEFAULT_AUTH_RATE_LIMITS } from "../authRateLimits.js";
18
20
 
19
21
  /**
22
+ * The auth routes, each limited per client address by its entry in
23
+ * `rateLimits` (none when that entry is null).
20
24
  * @param {import("../controllers/AuthController.js").AuthController} controller
21
- * @param {{ includeDevLoginAs?: boolean }} [options]
25
+ * @param {{
26
+ * includeDevLoginAs?: boolean,
27
+ * rateLimits?: ReturnType<typeof import("../authRateLimits.js").resolveAuthRateLimits>
28
+ * }} [options]
22
29
  */
23
- function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
30
+ function buildRoutes(controller, { includeDevLoginAs = false, rateLimits = DEFAULT_AUTH_RATE_LIMITS } = {}) {
24
31
  return [
25
32
  {
26
33
  path: AUTH_PATHS.REGISTER,
@@ -37,10 +44,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
37
44
  },
38
45
  { includeValidation400: true }
39
46
  ),
40
- rateLimit: {
41
- max: 10,
42
- timeWindow: "1 minute"
43
- },
47
+ rateLimit: rateLimits.register,
44
48
  handler: (request, reply) => controller.register(request, reply)
45
49
  },
46
50
  {
@@ -58,12 +62,27 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
58
62
  },
59
63
  { includeValidation400: true }
60
64
  ),
61
- rateLimit: {
62
- max: 5,
63
- timeWindow: "1 minute"
64
- },
65
+ rateLimit: rateLimits.registerConfirmationResend,
65
66
  handler: (request, reply) => controller.resendRegisterConfirmation(request, reply)
66
67
  },
68
+ {
69
+ path: AUTH_PATHS.REGISTER_CONFIRM,
70
+ method: "POST",
71
+ auth: "public",
72
+ meta: {
73
+ tags: ["auth"],
74
+ summary: "Confirm a registration's email with the code from its link"
75
+ },
76
+ body: authRegisterConfirmCommand.operation.body,
77
+ responses: withStandardErrorResponses(
78
+ {
79
+ 200: authRegisterConfirmCommand.operation.response
80
+ },
81
+ { includeValidation400: true }
82
+ ),
83
+ rateLimit: rateLimits.registerConfirm,
84
+ handler: (request, reply) => controller.confirmRegistration(request, reply)
85
+ },
67
86
  {
68
87
  path: AUTH_PATHS.LOGIN,
69
88
  method: "POST",
@@ -79,10 +98,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
79
98
  },
80
99
  { includeValidation400: true }
81
100
  ),
82
- rateLimit: {
83
- max: 10,
84
- timeWindow: "1 minute"
85
- },
101
+ rateLimit: rateLimits.login,
86
102
  handler: (request, reply) => controller.login(request, reply)
87
103
  },
88
104
  {
@@ -100,10 +116,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
100
116
  },
101
117
  { includeValidation400: true }
102
118
  ),
103
- rateLimit: {
104
- max: 10,
105
- timeWindow: "1 minute"
106
- },
119
+ rateLimit: rateLimits.loginOtpRequest,
107
120
  handler: (request, reply) => controller.requestOtpLogin(request, reply)
108
121
  },
109
122
  {
@@ -121,10 +134,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
121
134
  },
122
135
  { includeValidation400: true }
123
136
  ),
124
- rateLimit: {
125
- max: 10,
126
- timeWindow: "1 minute"
127
- },
137
+ rateLimit: rateLimits.loginOtpVerify,
128
138
  handler: (request, reply) => controller.verifyOtpLogin(request, reply)
129
139
  },
130
140
  {
@@ -144,10 +154,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
144
154
  },
145
155
  { includeValidation400: true }
146
156
  ),
147
- rateLimit: {
148
- max: 20,
149
- timeWindow: "1 minute"
150
- },
157
+ rateLimit: rateLimits.oauthStart,
151
158
  handler: (request, reply) => controller.oauthStart(request, reply)
152
159
  },
153
160
  {
@@ -165,10 +172,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
165
172
  },
166
173
  { includeValidation400: true }
167
174
  ),
168
- rateLimit: {
169
- max: 20,
170
- timeWindow: "1 minute"
171
- },
175
+ rateLimit: rateLimits.oauthComplete,
172
176
  handler: (request, reply) => controller.oauthComplete(request, reply)
173
177
  },
174
178
  ...(includeDevLoginAs ? [{
@@ -186,10 +190,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
186
190
  },
187
191
  { includeValidation400: true }
188
192
  ),
189
- rateLimit: {
190
- max: 30,
191
- timeWindow: "1 minute"
192
- },
193
+ rateLimit: rateLimits.devLoginAs,
193
194
  handler: (request, reply) => controller.devLoginAs(request, reply)
194
195
  }] : []),
195
196
  {
@@ -207,10 +208,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
207
208
  },
208
209
  { includeValidation400: true }
209
210
  ),
210
- rateLimit: {
211
- max: 5,
212
- timeWindow: "1 minute"
213
- },
211
+ rateLimit: rateLimits.passwordForgot,
214
212
  handler: (request, reply) => controller.requestPasswordReset(request, reply)
215
213
  },
216
214
  {
@@ -228,10 +226,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
228
226
  },
229
227
  { includeValidation400: true }
230
228
  ),
231
- rateLimit: {
232
- max: 20,
233
- timeWindow: "1 minute"
234
- },
229
+ rateLimit: rateLimits.passwordRecovery,
235
230
  handler: (request, reply) => controller.completePasswordRecovery(request, reply)
236
231
  },
237
232
  {
@@ -249,10 +244,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
249
244
  },
250
245
  { includeValidation400: true }
251
246
  ),
252
- rateLimit: {
253
- max: 20,
254
- timeWindow: "1 minute"
255
- },
247
+ rateLimit: rateLimits.passwordReset,
256
248
  handler: (request, reply) => controller.resetPassword(request, reply)
257
249
  },
258
250
  {
@@ -34,6 +34,13 @@ class AuthWebService {
34
34
  });
35
35
  }
36
36
 
37
+ async confirmRegistration(request, payload) {
38
+ return request.executeAction({
39
+ actionId: AUTH_ACTION_IDS.REGISTER_CONFIRM,
40
+ input: payload
41
+ });
42
+ }
43
+
37
44
  async login(request, payload) {
38
45
  return request.executeAction({
39
46
  actionId: AUTH_ACTION_IDS.LOGIN_PASSWORD,
@@ -0,0 +1,92 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import Fastify from "fastify";
4
+ import { ActionProvider } from "@jskit-ai/kernel/server/actions";
5
+ import { HttpProvider } from "@jskit-ai/kernel/server/http";
6
+ import { AppError, EventProvider } from "@jskit-ai/kernel/server/runtime";
7
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
8
+ import { createCapabilityRuntime } from "@jskit-ai/kernel/shared/capabilities";
9
+ import { AuthFeature } from "@jskit-ai/auth-core/server/providers/AuthFeature";
10
+ import { AuthWebFeature } from "../src/server/AuthWebFeature.js";
11
+ import { DEFAULT_AUTH_RATE_LIMITS, resolveAuthRateLimits } from "../src/server/authRateLimits.js";
12
+
13
+ /** An auth service whose every sign-in is a wrong password. */
14
+ function createRefusingAuthService() {
15
+ return {
16
+ async login() {
17
+ throw new AppError(401, "Invalid email or password.", { code: "auth.login.invalidCredentials" });
18
+ },
19
+ async authenticateRequest() {
20
+ return { authenticated: false };
21
+ },
22
+ getCapabilities() {
23
+ return { provider: { id: "local", label: "Local" }, features: {} };
24
+ },
25
+ writeSessionCookies() {},
26
+ clearSessionCookies() {}
27
+ };
28
+ }
29
+
30
+ async function startAuthWeb(t, config = {}) {
31
+ const app = Fastify();
32
+ const runtime = createCapabilityRuntime({
33
+ inputs: {
34
+ "auth.service": createRefusingAuthService(),
35
+ "runtime.config": config,
36
+ "runtime.env": { NODE_ENV: "test" },
37
+ "runtime.fastify": app,
38
+ "runtime.logger": silentLogger
39
+ },
40
+ providers: [EventProvider, ActionProvider, HttpProvider, AuthFeature, AuthWebFeature]
41
+ });
42
+ await runtime.start();
43
+ t.after(async () => {
44
+ await runtime.shutdown();
45
+ await app.close();
46
+ });
47
+ return app;
48
+ }
49
+
50
+ async function signInAttempts(app, count, remoteAddress = "203.0.113.7") {
51
+ const statuses = [];
52
+ let lastResponse = null;
53
+ for (let attempt = 0; attempt < count; attempt += 1) {
54
+ lastResponse = await app.inject({
55
+ method: "POST",
56
+ url: "/api/login",
57
+ remoteAddress,
58
+ payload: { email: "ada@example.com", password: `guess number ${attempt}` }
59
+ });
60
+ statuses.push(lastResponse.statusCode);
61
+ }
62
+ return { statuses, lastResponse };
63
+ }
64
+
65
+ test("25 rapid wrong-password sign-ins from one address are refused after the login limit", async (t) => {
66
+ const app = await startAuthWeb(t);
67
+ const { statuses, lastResponse } = await signInAttempts(app, 25);
68
+
69
+ const allowed = DEFAULT_AUTH_RATE_LIMITS.login.max;
70
+ assert.deepEqual(statuses.slice(0, allowed), Array(allowed).fill(401));
71
+ assert.deepEqual(statuses.slice(allowed), Array(25 - allowed).fill(429));
72
+ assert.equal(lastResponse.json().code, "kernel.http.rateLimited");
73
+ assert.ok(Number(lastResponse.headers["retry-after"]) > 0);
74
+ });
75
+
76
+ test("config.auth.rateLimits changes a route's limit, and false removes it", async (t) => {
77
+ const tighter = await startAuthWeb(t, { auth: { rateLimits: { login: { max: 3 } } } });
78
+ assert.deepEqual((await signInAttempts(tighter, 5)).statuses, [401, 401, 401, 429, 429]);
79
+
80
+ const unlimited = await startAuthWeb(t, { auth: { rateLimits: { login: false } } });
81
+ assert.deepEqual((await signInAttempts(unlimited, 15)).statuses, Array(15).fill(401));
82
+ });
83
+
84
+ test("a misspelt or malformed rate limit override stops startup", () => {
85
+ assert.throws(() => resolveAuthRateLimits({ auth: { rateLimits: { signIn: { max: 3 } } } }),
86
+ /config\.auth\.rateLimits\.signIn names no auth route/u);
87
+ assert.throws(() => resolveAuthRateLimits({ auth: { rateLimits: { login: 3 } } }),
88
+ /config\.auth\.rateLimits\.login must be \{ max, timeWindow \} or false/u);
89
+ assert.throws(() => resolveAuthRateLimits({ auth: { rateLimits: [] } }),
90
+ /config\.auth\.rateLimits must be an object/u);
91
+ assert.equal(resolveAuthRateLimits({}).login, DEFAULT_AUTH_RATE_LIMITS.login);
92
+ });
@@ -36,6 +36,11 @@ function createMinimalLoginViewState(requestedReturnTo = "/") {
36
36
  otpRequestPending: { value: false },
37
37
  registerConfirmationResendPending: { value: false },
38
38
  pendingEmailConfirmationAddress: { value: "" },
39
+ isEmailConfirmationPending: { value: false },
40
+ registrationConfirmPending: { value: false },
41
+ confirmationUrl: { value: "" },
42
+ confirmationCode: { value: "" },
43
+ setupCode: { value: "" },
39
44
  invitationToken: { value: "" },
40
45
  rememberAccountOnDevice: { value: true },
41
46
  oauthProviders: { value: [] },
@@ -342,3 +347,43 @@ test("OAuth buttons name their provider in the sign-in sentence", () => {
342
347
  state.isRegister.value = true;
343
348
  assert.equal(actions.oauthProviderButtonLabel(github), "Register with GitHub");
344
349
  });
350
+
351
+ for (const refusal of [
352
+ {
353
+ name: "the route's rate limit",
354
+ payload: { error: "Too many requests. Try again in 42 seconds.", code: "kernel.http.rateLimited", params: { count: 42 } }
355
+ },
356
+ {
357
+ name: "the account's failed sign-ins",
358
+ payload: {
359
+ error: "Too many failed sign-ins for this account. Try again in 2 minutes.",
360
+ code: "auth.local.login.locked",
361
+ params: { count: 2, retryAfterSeconds: 90 }
362
+ }
363
+ }
364
+ ]) {
365
+ test(`a sign-in refused by ${refusal.name} says how long to wait`, async (t) => {
366
+ clearAuthCsrfTokenCache();
367
+ t.after(clearAuthCsrfTokenCache);
368
+ const state = createMinimalLoginViewState("/");
369
+ const reports = [];
370
+ t.mock.method(globalThis, "fetch", async (url, options = {}) => {
371
+ if (url === "/api/session") {
372
+ return createJsonResponse({ authenticated: false, csrfToken: "csrf-a" });
373
+ }
374
+ assert.equal(`${options.method} ${url}`, "POST /api/login");
375
+ return createJsonResponse(refusal.payload, { status: 429 });
376
+ });
377
+ const actions = useLoginViewActions({
378
+ state,
379
+ validation: { canSubmit: { value: true } },
380
+ queryClient: { fetchQuery: ({ queryFn }) => queryFn() },
381
+ errorRuntime: { report: (entry) => reports.push(entry) }
382
+ });
383
+
384
+ await actions.submitAuth();
385
+
386
+ assert.equal(state.errorMessage.value, refusal.payload.error);
387
+ assert.equal(reports[0]?.message, refusal.payload.error);
388
+ });
389
+ }
@@ -16,6 +16,7 @@ function createFastifyStub() {
16
16
  addHook(name, handler) {
17
17
  this.hooks.push({ name, handler });
18
18
  },
19
+ async register() {},
19
20
  route(definition) {
20
21
  this.routes.push(definition);
21
22
  },
@@ -108,6 +109,7 @@ async function startAuthWeb({ env = {}, authService = null } = {}) {
108
109
  inputs: {
109
110
  "runtime.logger": silentLogger,
110
111
  "auth.service": authService || createAuthService(),
112
+ "runtime.config": {},
111
113
  "runtime.env": { NODE_ENV: "test", ...env },
112
114
  "runtime.fastify": fastify
113
115
  },
@@ -157,3 +159,65 @@ test("auth session route returns provider capabilities", async () => {
157
159
  assert.equal(reply.payload.authCapabilities.provider.id, "local");
158
160
  assert.equal(reply.payload.authCapabilities.features.password.register, true);
159
161
  });
162
+
163
+ test("registration confirmation: the register answer carries the development link, and confirming signs the person in", async () => {
164
+ const events = [];
165
+ const authService = {
166
+ ...createAuthService(events),
167
+ async register(input) {
168
+ return {
169
+ actor: null,
170
+ session: null,
171
+ requiresEmailConfirmation: true,
172
+ email: input.email,
173
+ confirmationUrl: "http://localhost:5173/auth/login?confirmation_token=dev-token"
174
+ };
175
+ },
176
+ async confirmRegistration(input) {
177
+ events.push({ type: "confirm", token: input.token });
178
+ return {
179
+ actor: { displayName: "Ada", email: "ada@example.com" },
180
+ session: { access_token: "confirm-a", refresh_token: "confirm-r" }
181
+ };
182
+ }
183
+ };
184
+ const { fastify } = await startAuthWeb({ authService });
185
+ const route = (url) => fastify.routes.find((entry) => entry.method === "POST" && entry.url === url);
186
+
187
+ const registerReply = createReplyStub();
188
+ await route("/api/register").handler(
189
+ { body: { email: "ada@example.com", password: "correct horse battery staple" } },
190
+ registerReply
191
+ );
192
+ assert.equal(registerReply.statusCode, 201);
193
+ assert.deepEqual(registerReply.payload, {
194
+ ok: true,
195
+ requiresEmailConfirmation: true,
196
+ message: "Check your email to confirm the account before logging in.",
197
+ messageCode: "auth.register.confirmEmail",
198
+ messageParams: {},
199
+ confirmationUrl: "http://localhost:5173/auth/login?confirmation_token=dev-token"
200
+ });
201
+
202
+ const confirmRoute = route("/api/register/confirm");
203
+ assert.deepEqual(confirmRoute.config.rateLimit, { max: 10, timeWindow: 60_000 });
204
+ const confirmReply = createReplyStub();
205
+ await confirmRoute.handler({ body: { token: "dev-token" } }, confirmReply);
206
+ assert.equal(confirmReply.statusCode, 200);
207
+ assert.deepEqual(confirmReply.payload, {
208
+ ok: true,
209
+ email: "ada@example.com",
210
+ username: "Ada",
211
+ message: "Your email is confirmed.",
212
+ messageCode: "auth.register.confirmed",
213
+ messageParams: {}
214
+ });
215
+ // Registering wrote no session; confirming wrote the new one.
216
+ assert.deepEqual(
217
+ events.filter((entry) => entry.type === "confirm" || (entry.type === "writeSession" && entry.session)),
218
+ [
219
+ { type: "confirm", token: "dev-token" },
220
+ { type: "writeSession", session: { access_token: "confirm-a", refresh_token: "confirm-r" } }
221
+ ]
222
+ );
223
+ });
@@ -53,7 +53,7 @@ async function openApp({ session = SIGNED_OUT, routes = {}, viewport = { width:
53
53
  const page = await browser.newPage({ baseURL: runtime.baseURL, viewport });
54
54
  page.setDefaultTimeout(15_000);
55
55
  page.setDefaultNavigationTimeout(60_000);
56
- const api = { session, requests: [], unexpected: [], errors: [], page };
56
+ const api = { session, routes, requests: [], unexpected: [], errors: [], page };
57
57
  page.on("pageerror", (error) => api.errors.push(error.message));
58
58
  await page.route("**/api/**", async (route) => {
59
59
  const request = route.request();
@@ -64,12 +64,13 @@ async function openApp({ session = SIGNED_OUT, routes = {}, viewport = { width:
64
64
  return;
65
65
  }
66
66
  api.requests.push({ key, search, body: request.postDataJSON(), csrf: request.headers()["csrf-token"] });
67
- if (!routes[key]) {
67
+ const answerFor = api.routes[key];
68
+ if (!answerFor) {
68
69
  api.unexpected.push(key);
69
70
  await route.fulfill({ status: 500, json: { error: `unexpected ${key}` } });
70
71
  return;
71
72
  }
72
- const answer = typeof routes[key] === "function" ? routes[key](request.postDataJSON()) : routes[key];
73
+ const answer = typeof answerFor === "function" ? answerFor(request.postDataJSON()) : answerFor;
73
74
  await route.fulfill(answer);
74
75
  });
75
76
  return api;
@@ -85,6 +86,11 @@ function reports(page) {
85
86
  return page.evaluate(() => window.authFixture.reports);
86
87
  }
87
88
 
89
+ // The page itself, not a sign-in page whose returnTo=/home also ends the address.
90
+ function waitForHome(page) {
91
+ return page.waitForURL((url) => url.pathname === "/home");
92
+ }
93
+
88
94
  async function signIn(page, email, password) {
89
95
  await page.getByLabel("Email").fill(email);
90
96
  await page.getByLabel("Password", { exact: true }).fill(password);
@@ -175,7 +181,7 @@ test("a signed-in visitor leaves the sign-in page, on opening it and when a sess
175
181
  await expect(page.getByTestId("auth-submit")).toBeVisible();
176
182
  api.session = SIGNED_IN;
177
183
  await page.evaluate(() => window.dispatchEvent(new Event("focus")));
178
- await page.waitForURL("**/home");
184
+ await waitForHome(page);
179
185
  await finish(api);
180
186
  });
181
187
 
@@ -259,7 +265,124 @@ test("register waits for email confirmation, and the other modes reach their req
259
265
  assert.deepEqual(api.requests.at(-1).body, { email: "ada@example.com", returnTo: "/home" });
260
266
  await page.getByLabel("One-time code").fill("123456");
261
267
  await page.getByTestId("auth-submit").click();
262
- await page.waitForURL("**/home");
268
+ await waitForHome(page);
269
+ await finish(api);
270
+ });
271
+
272
+ test("email confirmation: the development link, a pasted link after an unconfirmed sign-in, and the emailed link", options, async () => {
273
+ const session = {
274
+ ...SIGNED_OUT,
275
+ authCapabilities: { ...CAPABILITIES, features: { ...CAPABILITIES.features, emailConfirmationCode: true } }
276
+ };
277
+ const confirmations = [];
278
+ async function openConfirmingApp() {
279
+ const api = await openApp({ session });
280
+ Object.assign(api.routes, {
281
+ "POST /api/register": {
282
+ status: 201,
283
+ json: {
284
+ ok: true,
285
+ requiresEmailConfirmation: true,
286
+ message: "Check your email to confirm the account before logging in.",
287
+ messageCode: "auth.register.confirmEmail",
288
+ messageParams: {},
289
+ confirmationUrl: "http://localhost:5173/auth/login?confirmation_token=dev-token-1"
290
+ }
291
+ },
292
+ "POST /api/register/confirm": (body) => {
293
+ confirmations.push(body.token);
294
+ if (body.token === "expired-token") {
295
+ return {
296
+ status: 400,
297
+ json: {
298
+ error: "This confirmation link is invalid or has expired. Register again to get a new one.",
299
+ code: "auth.local.register.confirmationInvalid"
300
+ }
301
+ };
302
+ }
303
+ api.session = SIGNED_IN;
304
+ return { json: { ok: true, email: "ada@example.com", username: "Ada", message: "Your email is confirmed." } };
305
+ },
306
+ "POST /api/login": {
307
+ status: 403,
308
+ json: {
309
+ error: "Confirm your email address before signing in: open the link we emailed you, or ask for a new one.",
310
+ code: "auth.login.emailUnconfirmed"
311
+ }
312
+ }
313
+ });
314
+ return api;
315
+ }
316
+
317
+ // Registering in development shows the link, and its button confirms and signs in.
318
+ const registering = await openConfirmingApp();
319
+ await registering.page.goto("/auth/login?mode=register&returnTo=/home");
320
+ await registering.page.getByLabel("Email").fill("ada@example.com");
321
+ await registering.page.getByLabel("Password", { exact: true }).fill("Correct-horse-1");
322
+ await registering.page.getByLabel("Confirm password", { exact: true }).fill("Correct-horse-1");
323
+ await registering.page.getByTestId("auth-submit").click();
324
+ await expect(registering.page.getByTestId("auth-confirmation-dev-link")).toContainText("confirmation_token=dev-token-1");
325
+ await registering.page.getByTestId("auth-confirmation-dev-confirm").click();
326
+ await waitForHome(registering.page);
327
+ assert.deepEqual(confirmations, ["dev-token-1"]);
328
+ await finish(registering);
329
+
330
+ // Signing in before confirming opens "Confirm your email", where a pasted link confirms.
331
+ const signingIn = await openConfirmingApp();
332
+ await signingIn.page.goto("/auth/login?returnTo=/home");
333
+ await signIn(signingIn.page, "ada@example.com", "Correct-horse-1");
334
+ await expect(signingIn.page.getByText("Confirm your email", { exact: true })).toBeVisible();
335
+ await expect(signingIn.page.getByText("Confirm your email address before signing in")).toBeVisible();
336
+ await signingIn.page.getByLabel("Confirmation link or code").fill(
337
+ "http://localhost:5173/auth/login?confirmation_token=pasted-token-2"
338
+ );
339
+ await signingIn.page.getByLabel("Confirmation link or code").press("Enter");
340
+ await waitForHome(signingIn.page);
341
+ assert.deepEqual(confirmations.at(-1), "pasted-token-2");
342
+ await finish(signingIn);
343
+
344
+ // An emailed link confirms on opening; one that expired says so, and its code leaves the address.
345
+ const expired = await openConfirmingApp();
346
+ await expired.page.goto("/auth/login?confirmation_token=expired-token&returnTo=/home");
347
+ await expect.poll(async () => (await reports(expired.page)).at(-1)?.message)
348
+ .toBe("This confirmation link is invalid or has expired. Register again to get a new one.");
349
+ assert.equal(new URL(expired.page.url()).search, "?returnTo=%2Fhome");
350
+ await finish(expired);
351
+ const emailed = await openConfirmingApp();
352
+ await emailed.page.goto("/auth/login?confirmation_token=emailed-token-3&returnTo=/home");
353
+ await waitForHome(emailed.page);
354
+ assert.deepEqual(confirmations.slice(-2), ["expired-token", "emailed-token-3"]);
355
+ await finish(emailed);
356
+ });
357
+
358
+ test("while the app has no account, registering asks for the setup code and sends it", options, async () => {
359
+ const api = await openApp({
360
+ session: {
361
+ ...SIGNED_OUT,
362
+ authCapabilities: { ...CAPABILITIES, features: { ...CAPABILITIES.features, firstAccountSetupCode: true } }
363
+ },
364
+ routes: {
365
+ "POST /api/register": () => {
366
+ api.session = SIGNED_IN;
367
+ return { status: 201, json: { ok: true, requiresEmailConfirmation: false, username: "Ada" } };
368
+ }
369
+ }
370
+ });
371
+ const { page } = api;
372
+ await page.goto("/auth/login?mode=register&returnTo=/home");
373
+ await expect(page.getByTestId("auth-first-account-setup")).toContainText("This app has no account yet.");
374
+ await page.getByLabel("Email").fill("ada@example.com");
375
+ await page.getByLabel("Password", { exact: true }).fill("Correct-horse-1");
376
+ await page.getByLabel("Confirm password", { exact: true }).fill("Correct-horse-1");
377
+ await expect(page.getByTestId("auth-submit")).toBeDisabled();
378
+ await page.getByLabel("Setup code").fill("ABCDE-FGHJK-MNPQR-STVWX");
379
+ await page.getByTestId("auth-submit").click();
380
+ await waitForHome(page);
381
+ assert.deepEqual(api.requests.at(-1).body, {
382
+ email: "ada@example.com",
383
+ password: "Correct-horse-1",
384
+ setupCode: "ABCDE-FGHJK-MNPQR-STVWX"
385
+ });
263
386
  await finish(api);
264
387
  });
265
388