From f963a0edcf533ee3fc54a6666195350d345af5f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 18:04:12 +0000 Subject: [PATCH 1/3] feat: add passkey sign-in Users can add passkeys from the Security settings panel and sign in with them from the login page, built on laravel/passkeys and @laravel/passkeys. - New `passkeys_enabled` setting (off by default), toggled from the Authentication admin page; `EnsurePasskeysEnabled` 404s the routes. - The module registers its own routes (`Passkeys::ignoreRoutes()`), so passkey sign-in goes through `signIn()` and lands on Home like the other methods. - Adding a passkey is refused while impersonating and always emails the owner. Removing one stays available after the feature is switched off. - WebAuthn verification failures come back as 422s, not 500s. - `user.patch` adds `PasskeyAuthenticatable` / `PasskeyUser`; the module ships the `passkeys` table migration. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UZbdiAqJ7Pghg8hbk8mZ2W --- README.md | 18 +- composer.json | 3 +- ...000_00_00_000006_create_passkeys_table.php | 37 ++ ...0001_01_01_000013_create_auth_settings.php | 1 + lang/en/auth.php | 17 + package.json | 3 + patches/user.patch | 12 +- .../saucebase-auth-development/SKILL.md | 50 +- resources/js/react/components/LoginForm.tsx | 6 + .../react/components/PasskeyLoginButton.tsx | 69 +++ resources/js/react/pages/SettingsSecurity.tsx | 219 ++++++++- resources/js/types/page-props.d.ts | 1 + resources/js/vue/components/LoginForm.vue | 10 + .../js/vue/components/PasskeyLoginButton.vue | 57 +++ resources/js/vue/pages/SettingsSecurity.vue | 221 ++++++++- routes/web.php | 29 ++ src/Filament/Pages/AuthenticationSettings.php | 10 + src/Http/Controllers/PasskeyController.php | 101 ++++ .../Controllers/PasskeyLoginController.php | 72 +++ src/Http/Middleware/EnsurePasskeysEnabled.php | 19 + .../PasskeyAddedNotification.php | 62 +++ src/Providers/AuthServiceProvider.php | 12 + src/Settings/AuthSettings.php | 3 + src/Settings/SecuritySection.php | 19 +- tests/Feature/AuthSettingsTest.php | 1 + .../AuthenticationSettingsPageTest.php | 4 + tests/Feature/PasskeyTest.php | 430 ++++++++++++++++++ tests/e2e/tests/passkeys/passkeys.spec.ts | 93 ++++ 28 files changed, 1551 insertions(+), 28 deletions(-) create mode 100644 database/migrations/1000_00_00_000006_create_passkeys_table.php create mode 100644 resources/js/react/components/PasskeyLoginButton.tsx create mode 100644 resources/js/vue/components/PasskeyLoginButton.vue create mode 100644 src/Http/Controllers/PasskeyController.php create mode 100644 src/Http/Controllers/PasskeyLoginController.php create mode 100644 src/Http/Middleware/EnsurePasskeysEnabled.php create mode 100644 src/Notifications/PasskeyAddedNotification.php create mode 100644 tests/Feature/PasskeyTest.php create mode 100644 tests/e2e/tests/passkeys/passkeys.spec.ts diff --git a/README.md b/README.md index fe1a8d0..364b09f 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ -Sign-in for Saucebase: login, registration, social login, magic links, password reset and user admin. +Sign-in for Saucebase: login, registration, social login, magic links, passkeys, password reset and user admin. A module for [Saucebase](https://github.com/saucebase-dev/saucebase), the AI-ready Laravel SaaS kit. Modules are Composer packages you add to a Saucebase app; once installed, the code is yours to change. @@ -18,6 +18,7 @@ A module for [Saucebase](https://github.com/saucebase-dev/saucebase), the AI-rea - **Login and registration**, as a page or a modal over the current page - **Social login** with Google and GitHub built in, and any other Socialite provider you add; users link and unlink accounts themselves - **Magic links**: sign in from an emailed link, no password +- **Passkeys**: sign in with a fingerprint, face or screen lock, through [Laravel Passkeys](https://github.com/laravel/passkeys) - **Password reset and email verification** - **Profile and security settings** in the settings modal - **Login alerts**: an email when someone signs in to the account @@ -48,21 +49,30 @@ Then make yourself an admin with `php artisan auth:make-admin`. If a patch doesn't apply, because your file has changed, make its change by hand: -**`user.patch`** adds the `Sociable` trait to your user model, for social login and connected accounts: +**`user.patch`** adds the `Sociable` trait to your user model, for social login and connected accounts, and the `PasskeyAuthenticatable` trait with its `PasskeyUser` contract, for passkeys: ```php // app/Models/User.php +use Laravel\Passkeys\Contracts\PasskeyUser; +use Laravel\Passkeys\PasskeyAuthenticatable; use Modules\Auth\Traits\Sociable; -class User extends Authenticatable +class User extends Authenticatable implements PasskeyUser { + use PasskeyAuthenticatable; use Sociable; } ``` ## Configuration -Most settings are in the admin panel, under **Settings → Authentication**: open or close registration, login as a modal, magic links and how long they last, login alerts, and which social providers are on. +Most settings are in the admin panel, under **Settings → Authentication**: open or close registration, login as a modal, magic links and how long they last, passkeys, login alerts, and which social providers are on. + +**Passkeys** are off by default. They are bound to the host in `APP_URL` and only work over HTTPS (or on `localhost`): + +- Changing the app's domain makes every passkey stop working, and users have to add new ones. +- Serving the app on several subdomains? Publish the package config (`php artisan vendor:publish --tag=passkeys-config`), set `relying_party_id` to the parent domain and list every origin in `allowed_origins`. +- Passkeys derive a user handle from `APP_KEY`. Set `PASSKEYS_USER_HANDLE_SECRET` before rotating the key. Social login needs keys from [Google](https://console.cloud.google.com/apis/credentials) or [GitHub](https://github.com/settings/developers). Add them to `.env`: diff --git a/composer.json b/composer.json index b0f72c6..2ad3948 100644 --- a/composer.json +++ b/composer.json @@ -39,7 +39,8 @@ "require": { "saucebase/core": "^2.0", "laravel/socialite": "^5.31", - "stechstudio/filament-impersonate": "^5.6.1" + "stechstudio/filament-impersonate": "^5.6.1", + "laravel/passkeys": "^0.2.1" }, "minimum-stability": "stable" } diff --git a/database/migrations/1000_00_00_000006_create_passkeys_table.php b/database/migrations/1000_00_00_000006_create_passkeys_table.php new file mode 100644 index 0000000..70ea497 --- /dev/null +++ b/database/migrations/1000_00_00_000006_create_passkeys_table.php @@ -0,0 +1,37 @@ +id(); + $table->foreignId('user_id')->index()->constrained()->cascadeOnDelete(); + $table->string('name'); + $table->string('credential_id')->unique(); + $table->json('credential'); + $table->timestamp('last_used_at')->nullable(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('passkeys'); + } +}; diff --git a/database/settings/0001_01_01_000013_create_auth_settings.php b/database/settings/0001_01_01_000013_create_auth_settings.php index 9052df8..6107004 100644 --- a/database/settings/0001_01_01_000013_create_auth_settings.php +++ b/database/settings/0001_01_01_000013_create_auth_settings.php @@ -12,6 +12,7 @@ public function up(): void 'auth.magic_link_enabled' => false, 'auth.magic_link_expiry' => 15, 'auth.login_notification_enabled' => false, + 'auth.passkeys_enabled' => false, 'auth.enabled_socialite_providers' => [], ]; diff --git a/lang/en/auth.php b/lang/en/auth.php index 8aab13b..d17c14a 100644 --- a/lang/en/auth.php +++ b/lang/en/auth.php @@ -30,6 +30,23 @@ 'enabled' => 'Open sign-in and sign-up in a modal', 'help' => 'Links on the site open sign-in and registration over the current page. Their URLs still work on their own, so a typed, bookmarked or shared link lands on the full page.', ], + 'passkeys' => [ + 'title' => 'Passkeys', + 'description' => 'Let users sign in with a passkey stored on their device or password manager.', + 'enabled' => 'Enable passkeys', + 'help' => 'Users add passkeys from their Security settings. The site must be served over HTTPS from the host in APP_URL; changing that host invalidates every passkey.', + 'added' => 'Passkey added.', + 'removed' => 'Passkey removed.', + 'impersonating' => 'Passkeys cannot be added while impersonating a user.', + ], + 'passkey-added-notification' => [ + 'subject' => 'A passkey was added to your :app account', + 'greeting' => 'Hello :name,', + 'notice' => 'A passkey named ":passkey" was just added to your :app account. It can be used to sign in without a password.', + 'recognized' => 'If this was you, no action is needed.', + 'action' => 'Review your passkeys', + 'unrecognized' => "If you don't recognize this passkey, remove it and reset your password immediately.", + ], 'notifications' => [ 'title' => 'Notifications', 'description' => 'Configure security notifications sent to users.', diff --git a/package.json b/package.json index 2d9094d..3db6fdb 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,9 @@ "name": "@saucebase/auth", "private": true, "type": "module", + "dependencies": { + "@laravel/passkeys": "^0.4.0" + }, "devDependencies": { "@faker-js/faker": "^10.6.0" } diff --git a/patches/user.patch b/patches/user.patch index 5f01725..e6b8bfd 100644 --- a/patches/user.patch +++ b/patches/user.patch @@ -1,10 +1,18 @@ --- a/app/Models/User.php +++ b/app/Models/User.php -@@ -11,2 +11,3 @@ +@@ -10,2 +10,5 @@ use Illuminate\Notifications\Notifiable; ++use Laravel\Passkeys\Contracts\PasskeyUser; ++use Laravel\Passkeys\PasskeyAuthenticatable; +use Modules\Auth\Traits\Sociable; use Saucebase\Core\Settings\LocalizationSettings; -@@ -25,2 +26,3 @@ +@@ -17,3 +20,3 @@ + +-class User extends Authenticatable implements FilamentUser, HasLocalePreference, HasMedia ++class User extends Authenticatable implements FilamentUser, HasLocalePreference, HasMedia, PasskeyUser + // , MustVerifyEmail +@@ -24,2 +27,4 @@ use Notifiable; ++ use PasskeyAuthenticatable; + use Sociable; diff --git a/resources/boost/skills/saucebase-auth-development/SKILL.md b/resources/boost/skills/saucebase-auth-development/SKILL.md index e1d2c86..ceb5b62 100644 --- a/resources/boost/skills/saucebase-auth-development/SKILL.md +++ b/resources/boost/skills/saucebase-auth-development/SKILL.md @@ -7,28 +7,28 @@ description: Work on the Auth module (modules/auth) — login, registration, mag Paths are relative to `modules/auth/` unless they say otherwise. Commands run from the application root. -Authentication, registration, magic link (passwordless), password reset, email verification, OAuth (Socialite), and user impersonation. +Authentication, registration, magic link (passwordless), passkeys (WebAuthn, via `laravel/passkeys`), password reset, email verification, OAuth (Socialite), and user impersonation. ## Key Files | Layer | Files | |-------|-------| -| Controllers | `LoginController`, `RegisterController`, `SocialiteController`, `ForgotPasswordController`, `ResetPasswordController`, `VerifyEmailController`, `EmailVerificationNotificationController`, `EmailVerificationPromptController`, `PasswordController`, `ProfileController`, `ReimpersonateController`, `MagicLinkController` | -| Models | `SocialAccount` (provider, tokens, avatar, last_login_at), `MagicLinkToken` (hashed token, expires_at, used_at) | +| Controllers | `LoginController`, `RegisterController`, `SocialiteController`, `ForgotPasswordController`, `ResetPasswordController`, `VerifyEmailController`, `EmailVerificationNotificationController`, `EmailVerificationPromptController`, `PasswordController`, `ProfileController`, `ReimpersonateController`, `MagicLinkController`, `PasskeyLoginController`, `PasskeyController` | +| Models | `SocialAccount` (provider, tokens, avatar, last_login_at), `MagicLinkToken` (hashed token, expires_at, used_at), `Laravel\Passkeys\Passkey` (the package's; table shipped by this module) | | Service | `SocialiteService` — all OAuth logic (find/create user, link/disconnect accounts) | | Requests | `LoginRequest` (credential validation + rate limiting), `RegisterRequest` (password hashing in `passedValidation`), `UpdateProfileInfoRequest`, `UpdateProfileAvatarRequest`, `UpdatePasswordRequest` | | Exceptions | `AuthException` (credentials, throttle), `SocialiteException` (disconnect, account linking, provider validation, registration disabled) | | Listeners | `AssignUserRole` (Registered), `UpdateUserLastLogin` (Login), `Impersonation` (`EnterImpersonation` — session history), `SendLoginNotification` (`ReturningUserAuthenticated`), `SendWelcomeNotification` (Registered) | -| Notifications | `WelcomeNotification` (Registered), `MagicLinkNotification` (passwordless login link with configured expiry), `LoginNotification` (new sign-in, only when `login_notification_enabled`) | +| Notifications | `WelcomeNotification` (Registered), `MagicLinkNotification` (passwordless login link with configured expiry), `LoginNotification` (new sign-in, only when `login_notification_enabled`), `PasskeyAddedNotification` (always, when a passkey is added) | | Events | `ReturningUserAuthenticated` — dispatched by password, magic-link and social sign-in, not by registration | -| Middleware | `EnsureRegistrationEnabled`, `EnsureMagicLinkEnabled`, `EnsureSocialiteProviderEnabled` — each 404s its routes while the setting is off | -| Settings | `AuthSettings` (`registration_enabled`, `modal_enabled`, `magic_link_enabled`, `magic_link_expiry`, `login_notification_enabled`, `enabled_socialite_providers`) | +| Middleware | `EnsureRegistrationEnabled`, `EnsureMagicLinkEnabled`, `EnsurePasskeysEnabled`, `EnsureSocialiteProviderEnabled` — each 404s its routes while the setting is off | +| Settings | `AuthSettings` (`registration_enabled`, `modal_enabled`, `magic_link_enabled`, `magic_link_expiry`, `login_notification_enabled`, `passkeys_enabled`, `enabled_socialite_providers`) | | Settings sections | `ProfileSection` (order 10, `Auth::SettingsProfile`), `SecuritySection` (order 15, `Auth::SettingsSecurity`) — panels in core's settings modal | -| Trait | `Sociable` — added to User model (socialAccounts relation, connected_providers, disconnect) | +| Trait | `Sociable` — added to User model (socialAccounts relation, connected_providers, disconnect); `user.patch` also adds the package's `PasskeyAuthenticatable` + `PasskeyUser` | | Filament | `AuthPlugin`, `AuthenticationSettings`, `UserResource` (list, create, view, edit), `UserForm`, `UsersTable` | | Pages | `Login`, `Register`, `ForgotPassword`, `ResetPassword`, `VerifyEmail`, `MagicLink`, `SettingsProfile` + `SettingsSecurity` (settings modal panels) | | Layout | `AuthCardLayout` — card with logo, status alerts, page transitions | -| Component | `SocialiteProviders` — Google/GitHub buttons with divider, `PageHeader` — title with optional back link | +| Component | `SocialiteProviders` — Google/GitHub buttons with divider, `PasskeyLoginButton` — passkey sign-in under the login form, `PageHeader` — title with optional back link | ## Frontend @@ -36,7 +36,7 @@ Pages, layouts and components live under `resources/js/`. The module's `resource ## Routes -**Guest routes** (`/auth/*`): login (GET/POST), register (GET/POST), forgot-password (GET/POST, throttle:6,1), reset-password/{token} (GET, signed), reset-password (POST, throttle:6,1), magic-link (GET/POST, throttle:5,1) +**Guest routes** (`/auth/*`): login (GET/POST), register (GET/POST), forgot-password (GET/POST, throttle:6,1), reset-password/{token} (GET, signed), reset-password (POST, throttle:6,1), magic-link (GET/POST, throttle:5,1), `auth.passkeys.options` — passkeys/options (GET) and `auth.passkeys.login` — passkeys/login (POST), both JSON, throttle:6,1 **Auth routes** (`/auth/*`): logout (POST — a GET logout is reachable from any other site's markup), verify-email (GET), verify-email/{id}/{hash} (GET, signed), email/verification-notification (POST, throttle:6,1), password (PUT) @@ -44,7 +44,7 @@ Pages, layouts and components live under `resources/js/`. The module's `resource **Magic Link** (outside guest/auth groups): `magic-link.authenticate` — `/auth/magic-link/{token}` (GET) — must be accessible from email clients -**Account settings** (`/settings/*`, middleware `auth`, `verified`): `settings.profile` (redirects to the `#settings/profile` fragment), `settings.profile.update-info` (PATCH), `settings.profile.update-avatar` (POST), `settings.profile.delete-avatar` (DELETE), `settings.profile.password.update` (PUT) +**Account settings** (`/settings/*`, middleware `auth`, `verified`): `settings.profile` (redirects to the `#settings/profile` fragment), `settings.profile.update-info` (PATCH), `settings.profile.update-avatar` (POST), `settings.profile.delete-avatar` (DELETE), `settings.profile.password.update` (PUT), `settings.passkeys.options` (GET, JSON) and `settings.passkeys.store` (POST, JSON) behind the setting and throttle:6,1, `settings.passkeys.destroy` — `/settings/passkeys/{passkeyId}` (DELETE, not behind the setting) The routes are grouped under `settings.profile.*` for history; password and socialite disconnect are rendered by the **Security** panel, not Profile. @@ -84,6 +84,34 @@ Login, register, magic link, socialite and verification redirect to can send a new account to onboarding. The welcome email links to `route('home')`, which is resolved when clicked. +### Passkeys +Built on `laravel/passkeys` (server) and `@laravel/passkeys` (browser client, Vue and React hooks). +Both are pre-1.0, so pin and expect upgrade work. The module calls `Passkeys::ignoreRoutes()` +in `AuthServiceProvider::register()` and registers its own routes, so they sit behind +`passkeys_enabled` (off by default) and sign in through `Controller::signIn()` like every +other method — the login notification and welcome-back toast included — then answer +`{redirect: intended(Home::url(..., login))}`. The client calls them with `fetch`, so they +answer JSON and the login button follows the redirect with a full page load (the session was +regenerated). The package's own Actions (`GenerateVerificationOptions`, `VerifyPasskey`, +`GenerateRegistrationOptions`, `StorePasskey`, `DeletePasskey`) and FormRequests do the +WebAuthn work; tests stub `VerifyPasskey`/`StorePasskey`. + +- The sign-in challenge names no account, so it reveals nothing about which emails exist. +- **Adding** a passkey is refused (403) while impersonating, and the panel hides the form + (`can_add_passkeys`): it would outlive the impersonation as a way back into the account. +- Adding one always emails the owner (`PasskeyAddedNotification`), the mitigation for a + passkey planted from a hijacked session. There is no re-authentication step before adding + one: many users have no password to confirm. +- **Removing** is not behind the setting, and the Security panel lists passkeys while the user + still has some, so a passkey added before the feature was switched off can still be removed. + Removal is scoped to the user's own relation (404 otherwise). The route parameter is + `passkeyId`, not `passkey`: the package binds `{passkey}` globally to any user's passkey. +- Passkeys don't count as a login method for `SocialiteService::disconnectProvider()`, and + nothing stops a user removing their last passkey; forgot-password is the way back in. +- The `passkeys` table migration is shipped by this module (the package only publishes one). +- Passkeys are bound to the relying party ID (the host in `APP_URL`) and need HTTPS or + `localhost`. Changing the domain invalidates every passkey. + ### Rate Limiting `LoginRequest::ensureIsNotRateLimited()` — 5 attempts per `email|ip` key. Fires `Lockout` event, throws `AuthException::throttle($seconds)`. Cleared on success. Covered in PHP (`LoginTest`), not e2e: Playwright workers share one IP, so a lockout there leaks into other login tests. @@ -184,7 +212,7 @@ php artisan test --testsuite=Modules --filter='^Modules\\Auth\\Tests' # PHPUnit npx playwright test --project="@auth*" # E2E ``` -**E2E coverage**: login (basic, errors, security (CSRF), social, modal, logout), register (basic, errors), forgot-password (basic, errors), verify-email, profile (avatar, socialite settings under the Security panel). Page objects in `tests/e2e/pages/`; specs import the shared `test` fixture from `@e2e/fixtures`. +**E2E coverage**: login (basic, errors, security (CSRF), social, modal, logout), register (basic, errors), forgot-password (basic, errors), verify-email, profile (avatar, socialite settings under the Security panel), passkeys (add, sign in, remove — Chromium's virtual authenticator, so Chromium only). Page objects in `tests/e2e/pages/`; specs import the shared `test` fixture from `@e2e/fixtures`. ## Gotchas diff --git a/resources/js/react/components/LoginForm.tsx b/resources/js/react/components/LoginForm.tsx index 3734c8c..e2b29ec 100644 --- a/resources/js/react/components/LoginForm.tsx +++ b/resources/js/react/components/LoginForm.tsx @@ -9,10 +9,12 @@ import { useT } from '@saucebase/react/i18n'; import { Eye, EyeOff } from 'lucide-react'; import { useState } from 'react'; import AuthLink from './AuthLink'; +import PasskeyLoginButton from './PasskeyLoginButton'; import SocialiteProviders from './SocialiteProviders'; type AuthProps = { magic_link_enabled?: boolean; + passkeys_enabled?: boolean; registration_enabled?: boolean; }; @@ -173,6 +175,10 @@ export default function LoginForm({ modal }: LoginFormProps) { {t('Log in')} + {auth.passkeys_enabled && ( + + )} +

{auth.magic_link_enabled && ( { + window.location.assign(response.redirect ?? '/'); + }, + }); + + if (!isSupported) { + return null; + } + + // Closing the browser's own prompt is a choice, not something to report. + const error = + errorInstance?.name === 'UserCancelledError' + ? null + : errorInstance?.message; + + return ( +

+ + {error && ( + + {error} + + )} +
+ ); +} diff --git a/resources/js/react/pages/SettingsSecurity.tsx b/resources/js/react/pages/SettingsSecurity.tsx index 8d23245..812d837 100644 --- a/resources/js/react/pages/SettingsSecurity.tsx +++ b/resources/js/react/pages/SettingsSecurity.tsx @@ -3,10 +3,11 @@ import { Field, FieldError, FieldLabel } from '@/components/ui/field'; import { Input } from '@/components/ui/input'; import { Separator } from '@/components/ui/separator'; import { Form, router, usePage } from '@inertiajs/react'; +import { usePasskeyRegister } from '@laravel/passkeys/react'; import { formatDateTime } from '@saucebase/core/lib/dates'; import { useDialog } from '@saucebase/react/hooks/useDialog'; import { useT, useTranslation } from '@saucebase/react/i18n'; -import { Eye, EyeOff, Loader2 } from 'lucide-react'; +import { Eye, EyeOff, KeyRound, Loader2 } from 'lucide-react'; import { useMemo, useState } from 'react'; import { providerIcons } from '../components/providerIcons'; @@ -15,6 +16,14 @@ type SocialiteProvider = { label: string; }; +type Passkey = { + id: number; + name: string; + authenticator: string | null; + last_used_at: string | null; + created_at: string; +}; + type SocialAccount = { provider: string; last_login_at: string; @@ -27,6 +36,8 @@ interface SettingsSecurityProps { social_accounts?: SocialAccount[]; }; available_providers?: SocialiteProvider[]; + passkeys?: Passkey[]; + can_add_passkeys?: boolean; } /** @@ -93,8 +104,8 @@ function PasswordField({ } /** - * How the signed-in user proves who they are: their password, and the social - * accounts that can sign them in without one. + * How the signed-in user proves who they are: their password, their passkeys, + * and the social accounts that can sign them in without one. * * Split out of the profile panel because these are credentials rather than a * description of a person — a different question to answer, in a different frame @@ -103,12 +114,92 @@ function PasswordField({ export default function SettingsSecurity({ user, available_providers, + passkeys = [], + can_add_passkeys, }: SettingsSecurityProps) { const { t, locale } = useTranslation(); const page = usePage(); const { confirm } = useDialog(); const [isDisconnecting, setIsDisconnecting] = useState(null); + const [passkeyName, setPasskeyName] = useState(''); + const [isRemovingPasskey, setIsRemovingPasskey] = useState( + null, + ); + + const passkeysEnabled = !!( + page.props.auth as { passkeys_enabled?: boolean } + )?.passkeys_enabled; + + /** + * The ceremony runs over `fetch`, outside Inertia, so nothing reloads the + * panel by itself. A page reload does: the modal refreshes the active + * section after any Inertia visit, and the reload also delivers the toast. + */ + const { + register, + isLoading: isAddingPasskey, + errorInstance: addPasskeyError, + isSupported: passkeysSupported, + } = usePasskeyRegister({ + routes: { + options: route('settings.passkeys.options'), + submit: route('settings.passkeys.store'), + }, + onSuccess: () => { + setPasskeyName(''); + router.reload(); + }, + }); + + // Closing the browser's own prompt is a choice, not something to report. + const addPasskeyErrorMessage = + addPasskeyError?.name === 'UserCancelledError' + ? null + : addPasskeyError?.message; + + /** + * Shown while the feature is on, and also while the user still holds + * passkeys after it was switched off — otherwise they could never remove + * them. + */ + const showPasskeys = passkeysEnabled || passkeys.length > 0; + + const canAddPasskey = + passkeysEnabled && passkeysSupported && can_add_passkeys !== false; + + const addPasskey = (event: React.FormEvent) => { + event.preventDefault(); + + const name = passkeyName.trim(); + + if (name === '') return; + + void register(name); + }; + + const removePasskey = async (passkey: Passkey) => { + const confirmed = await confirm({ + title: t('Remove Passkey'), + description: t( + 'You will no longer be able to sign in with ":name". If it is your only way in, you will need to reset your password to get back into your account.', + { name: passkey.name }, + ), + confirmLabel: t('Remove'), + cancelLabel: t('Cancel'), + variant: 'destructive', + align: 'left', + }); + + if (!confirmed) return; + + setIsRemovingPasskey(passkey.id); + + router.delete(route('settings.passkeys.destroy', passkey.id), { + preserveUrl: true, + onFinish: () => setIsRemovingPasskey(null), + }); + }; const enabledProviders = useMemo(() => { const auth = page.props.auth as { @@ -191,7 +282,9 @@ export default function SettingsSecurity({ return (

- {t('Your password and the accounts that can sign you in')} + {t( + 'Your password, passkeys and the accounts that can sign you in', + )}

{/* Password */} @@ -252,6 +345,124 @@ export default function SettingsSecurity({
+ {/* Passkeys */} + {showPasskeys && ( + <> + + +
+
+

{t('Passkeys')}

+

+ {t( + 'Sign in with your fingerprint, face or screen lock instead of a password.', + )} +

+
+ + {passkeys.length > 0 ? ( +
+ {passkeys.map((passkey) => ( +
+
+ +
+

+ {passkey.name} +

+

+ {passkey.authenticator && + `${passkey.authenticator} · `} + {t('Last used')}:{' '} + {passkey.last_used_at + ? formatDateTime( + passkey.last_used_at, + locale, + ) + : t('Never')} +

+
+
+ + +
+ ))} +
+ ) : ( +

+ {t('No passkeys yet.')} +

+ )} + + {canAddPasskey && ( +
+
+ + setPasskeyName(event.target.value) + } + /> + +
+ {addPasskeyErrorMessage && ( + + {addPasskeyErrorMessage} + + )} +
+ )} +
+ + )} + {/* Connected accounts */} {hasSocialiteProviders && ( <> diff --git a/resources/js/types/page-props.d.ts b/resources/js/types/page-props.d.ts index 086481f..abcd635 100644 --- a/resources/js/types/page-props.d.ts +++ b/resources/js/types/page-props.d.ts @@ -6,6 +6,7 @@ declare module '@inertiajs/core' { user: User | null; last_social_provider?: string | null; magic_link_enabled?: boolean; + passkeys_enabled?: boolean; registration_enabled?: boolean; modal_enabled?: boolean; socialite_providers?: Array<{ diff --git a/resources/js/vue/components/LoginForm.vue b/resources/js/vue/components/LoginForm.vue index 3fa8d4d..c89c7ad 100644 --- a/resources/js/vue/components/LoginForm.vue +++ b/resources/js/vue/components/LoginForm.vue @@ -7,6 +7,7 @@ import { Form } from '@inertiajs/vue3'; import { useModal } from '@inertiaui/modal-vue'; import { computed, ref } from 'vue'; import AuthLink from './AuthLink.vue'; +import PasskeyLoginButton from './PasskeyLoginButton.vue'; import SocialiteProviders from './SocialiteProviders.vue'; const props = defineProps<{ @@ -28,6 +29,9 @@ function handleSuccess(): void { const emailRef = ref(''); +// Bound only so the passkey button can read it; the form still posts the box. +const remember = ref(false); + // compute forgot password url so the link updates as user types const forgotUrl = computed(() => route('password.request', { email: emailRef.value }), @@ -74,6 +78,7 @@ const forgotUrl = computed(() => @@ -105,6 +110,11 @@ const forgotUrl = computed(() => {{ $t('Log in') }} + +

+import { Button } from '@/components/ui/button'; +import { FieldError } from '@/components/ui/field'; +import { usePasskeyVerify } from '@laravel/passkeys/vue'; +import { KeyRound, Loader2 } from '@lucide/vue'; +import { computed } from 'vue'; + +const props = defineProps<{ + /** Read when the ceremony starts, so it follows the remember-me box. */ + remember?: boolean; +}>(); + +/** + * Signs in with a passkey instead of the email and password above it. + * + * The client talks to the server with `fetch`, not Inertia, and the session is + * regenerated on success — so the redirect is a full page load rather than an + * Inertia visit. That also takes the auth modal down with the page behind it. + */ +const { verify, isLoading, errorInstance, isSupported } = usePasskeyVerify({ + remember: () => props.remember ?? false, + routes: { + options: route('auth.passkeys.options'), + submit: route('auth.passkeys.login'), + }, + onSuccess: (response) => { + window.location.assign(response.redirect ?? '/'); + }, +}); + +/** Closing the browser's own prompt is a choice, not something to report. */ +const error = computed(() => + errorInstance.value?.name === 'UserCancelledError' + ? null + : errorInstance.value?.message, +); + + + diff --git a/resources/js/vue/pages/SettingsSecurity.vue b/resources/js/vue/pages/SettingsSecurity.vue index 1406675..2ba574d 100644 --- a/resources/js/vue/pages/SettingsSecurity.vue +++ b/resources/js/vue/pages/SettingsSecurity.vue @@ -1,12 +1,15 @@ + + diff --git a/resources/js/vue/pages/SettingsProfile.vue b/resources/js/vue/pages/SettingsProfile.vue index 9c123af..8774c4d 100644 --- a/resources/js/vue/pages/SettingsProfile.vue +++ b/resources/js/vue/pages/SettingsProfile.vue @@ -5,20 +5,67 @@ import InputField from '@/components/ui/input/InputField.vue'; import { useDialog } from '@saucebase/vue/composables/useDialog'; import type { User } from '@/types'; import { getInitials } from '@saucebase/core/lib/initials'; +import type { PendingVisit } from '@inertiajs/core'; import { Form, router, usePage } from '@inertiajs/vue3'; import { Camera, Loader2, Trash2 } from '@lucide/vue'; import { trans } from 'laravel-vue-i18n'; import { computed, ref, watch } from 'vue'; +import ConfirmIdentityDialog from '../components/ConfirmIdentityDialog.vue'; +import { confirmedFor, isConfirmed } from '../../lib/passwordConfirmation'; const props = defineProps<{ user: User & { has_uploaded_avatar?: boolean; }; + password_confirmed_until?: number | null; + password_timeout: number; + has_passkeys?: boolean; }>(); const page = usePage(); const { confirm } = useDialog(); +/** + * Every security alert goes to the email, so moving it needs fresh proof; the name + * does not. When the session has none, the save waits for the dialog, then resends. + */ +const profileForm = ref<{ submit: () => void } | null>(null); +const confirmedUntil = ref(props.password_confirmed_until ?? null); + +watch( + () => props.password_confirmed_until, + (until) => (confirmedUntil.value = until ?? null), +); +const confirmingIdentity = ref(false); + +const beforeProfileSave = (visit: PendingVisit) => { + const email = + visit.data instanceof FormData + ? visit.data.get('email') + : visit.data.email; + + if (isConfirmed(confirmedUntil.value) || email === props.user?.email) { + return true; + } + + confirmingIdentity.value = true; + + return false; +}; + +const onIdentityConfirmed = () => { + confirmedUntil.value = confirmedFor(props.password_timeout); + profileForm.value?.submit(); +}; + +/** The confirmation ran out on the server first: ask, then the dialog resends. */ +const onProfileError = (errors: Record) => { + if (!errors.confirm_identity) return; + + confirmedUntil.value = null; + confirmingIdentity.value = true; +}; + const avatarFile = ref(null); const isUpdatingAvatar = ref(false); const isRemovingAvatar = ref(false); @@ -176,11 +223,14 @@ const removeAvatar = async () => {

{ + + diff --git a/resources/js/vue/pages/SettingsSecurity.vue b/resources/js/vue/pages/SettingsSecurity.vue index 2ba574d..5cd94c9 100644 --- a/resources/js/vue/pages/SettingsSecurity.vue +++ b/resources/js/vue/pages/SettingsSecurity.vue @@ -9,10 +9,13 @@ import { useLocalization } from '@saucebase/vue/composables/useLocalization'; import { formatDateTime } from '@saucebase/core/lib/dates'; import { Form, router, usePage } from '@inertiajs/vue3'; import { usePasskeyRegister } from '@laravel/passkeys/vue'; -import { KeyRound, Loader2 } from '@lucide/vue'; +import { KeyRound, Loader2, Trash2 } from '@lucide/vue'; import { trans } from 'laravel-vue-i18n'; -import { computed, ref } from 'vue'; +import { computed, ref, watch } from 'vue'; +import ConfirmIdentityDialog from '../components/ConfirmIdentityDialog.vue'; import { providerIcons } from '../components/providerIcons'; +import { deviceName } from '../../lib/deviceName'; +import { confirmedFor, isConfirmed } from '../../lib/passwordConfirmation'; type SocialiteProvider = { name: string; @@ -47,6 +50,8 @@ const props = defineProps<{ available_providers?: SocialiteProvider[]; passkeys?: Passkey[]; can_add_passkeys?: boolean; + password_confirmed_until?: number | null; + password_timeout: number; }>(); const page = usePage(); @@ -125,6 +130,32 @@ const showPasskeys = computed( const passkeyName = ref(''); const isRemovingPasskey = ref(null); +/** + * Adding or removing a passkey needs fresh proof (`password.confirm` on the routes). + * Ask first when the session has none, then run the action the user chose. + */ +const confirmedUntil = ref(props.password_confirmed_until ?? null); +const confirmingIdentity = ref(false); +let afterConfirmation: (() => void) | null = null; + +watch( + () => props.password_confirmed_until, + (until) => (confirmedUntil.value = until ?? null), +); + +const withConfirmation = (action: () => void) => { + if (isConfirmed(confirmedUntil.value)) return action(); + + afterConfirmation = action; + confirmingIdentity.value = true; +}; + +const onIdentityConfirmed = () => { + confirmedUntil.value = confirmedFor(props.password_timeout); + afterConfirmation?.(); + afterConfirmation = null; +}; + /** * The ceremony runs over `fetch`, outside Inertia, so nothing reloads the panel * by itself. A page reload does: the modal refreshes the active section after @@ -132,7 +163,7 @@ const isRemovingPasskey = ref(null); */ const { register, - isLoading: isAddingPasskey, + isLoading: isRegistering, errorInstance: addPasskeyError, isSupported: passkeysSupported, } = usePasskeyRegister({ @@ -141,11 +172,41 @@ const { submit: route('settings.passkeys.store'), }, onSuccess: () => { - passkeyName.value = ''; + isRefreshingPasskeys.value = true; router.reload(); }, }); +/** + * The toast lands with the reload, but the list only with the section refresh + * after it, a moment later. Stay busy until the new list arrives, so the gap + * doesn't read as a failure. + */ +const isRefreshingPasskeys = ref(false); + +watch( + () => props.passkeys, + () => { + if (!isRefreshingPasskeys.value) return; + + isRefreshingPasskeys.value = false; + passkeyName.value = ''; + }, +); + +const isAddingPasskey = computed( + () => isRegistering.value || isRefreshingPasskeys.value, +); + +/** + * A plain `Error` is a failed request, a 423 among them when the confirmation ran + * out early: ask again next time rather than keep trusting it. The package's own + * errors (cancelled, already registered) say nothing about the confirmation. + */ +watch(addPasskeyError, (error) => { + if (error?.name === 'Error') confirmedUntil.value = null; +}); + /** Closing the browser's own prompt is a choice, not something to report. */ const addPasskeyErrorMessage = computed(() => addPasskeyError.value?.name === 'UserCancelledError' @@ -160,12 +221,16 @@ const canAddPasskey = computed( props.can_add_passkeys !== false, ); +/** "Chrome on macOS": the placeholder, and the name when the field is left empty. */ +const defaultPasskeyName = + typeof navigator === 'undefined' ? null : deviceName(navigator.userAgent); + const addPasskey = () => { - const name = passkeyName.value.trim(); + const name = passkeyName.value.trim() || defaultPasskeyName; - if (name === '') return; + if (!name) return; - void register(name); + withConfirmation(() => void register(name)); }; const removePasskey = async (passkey: Passkey) => { @@ -176,6 +241,7 @@ const removePasskey = async (passkey: Passkey) => { { name: passkey.name }, ), confirmLabel: trans('Remove'), + icon: Trash2, cancelLabel: trans('Cancel'), variant: 'destructive', align: 'left', @@ -183,10 +249,21 @@ const removePasskey = async (passkey: Passkey) => { if (!confirmed) return; + withConfirmation(() => deletePasskey(passkey)); +}; + +const deletePasskey = (passkey: Passkey) => { isRemovingPasskey.value = passkey.id; router.delete(route('settings.passkeys.destroy', passkey.id), { preserveUrl: true, + // The confirmation ran out on the server first: ask, then try again. + onError: (errors) => { + if (!errors.confirm_identity) return; + + confirmedUntil.value = null; + withConfirmation(() => deletePasskey(passkey)); + }, onFinish: () => { isRemovingPasskey.value = null; }, @@ -310,62 +387,6 @@ const initiateDisconnect = async (provider: string) => {

-
-
-
- -
-

- {{ passkey.name }} -

-

- - {{ $t('Last used') }}: - {{ - passkey.last_used_at - ? formatDateTime( - passkey.last_used_at, - language, - ) - : $t('Never') - }} -

-
-
- - -
-
-

- {{ $t('No passkeys yet.') }} -

-
{ name="passkey_name" :aria-label="$t('Passkey name')" :placeholder=" + defaultPasskeyName ?? $t('Name this passkey, e.g. Work laptop') " maxlength="255" - required + :required="!defaultPasskeyName" data-testid="passkey-name-input" />
+ + @@ -491,5 +588,11 @@ const initiateDisconnect = async (provider: string) => { + + diff --git a/routes/web.php b/routes/web.php index 9696a22..ce98c83 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,6 +1,8 @@ group(function (): void { + Route::middleware([EnsurePasskeysEnabled::class, 'throttle:passkeys'])->group(function (): void { Route::get('passkeys/options', [PasskeyLoginController::class, 'options']) ->name('auth.passkeys.options'); @@ -157,17 +159,39 @@ Route::put('profile/password', [PasswordController::class, 'update']) ->name('settings.profile.password.update'); - Route::middleware([EnsurePasskeysEnabled::class, 'throttle:6,1'])->group(function (): void { + /* + * Fresh proof before adding or removing a passkey or changing the email: + * the password, or one of the user's passkeys (the package's own + * confirmation controller). `password.confirm` sends anything it stops + * here, which opens the Security panel where the dialog lives. + */ + Route::get('confirm-password', [ConfirmPasswordController::class, 'show']) + ->name('password.confirm'); + + Route::post('confirm-password', [ConfirmPasswordController::class, 'store']) + ->middleware('throttle:6,1') + ->name('password.confirm.store'); + + Route::middleware([EnsurePasskeysEnabled::class, 'throttle:passkeys'])->group(function (): void { + Route::get('passkeys/confirm/options', [PasskeyConfirmationController::class, 'index']) + ->name('settings.passkeys.confirm.options'); + + Route::post('passkeys/confirm', [PasskeyConfirmationController::class, 'store']) + ->name('settings.passkeys.confirm'); + Route::get('passkeys/options', [PasskeyController::class, 'options']) + ->middleware('password.confirm') ->name('settings.passkeys.options'); Route::post('passkeys', [PasskeyController::class, 'store']) + ->middleware('password.confirm') ->name('settings.passkeys.store'); }); // Not behind the setting: a passkey added before the feature was // switched off can still be removed, like a disabled social provider. Route::delete('passkeys/{passkeyId}', [PasskeyController::class, 'destroy']) + ->middleware('password.confirm') ->whereNumber('passkeyId') ->name('settings.passkeys.destroy'); }); diff --git a/src/Http/Controllers/ConfirmPasswordController.php b/src/Http/Controllers/ConfirmPasswordController.php new file mode 100644 index 0000000..281ac60 --- /dev/null +++ b/src/Http/Controllers/ConfirmPasswordController.php @@ -0,0 +1,45 @@ +header('X-Inertia')) { + return back()->withErrors(['confirm_identity' => __('Confirm it\'s you to continue.')]); + } + + return redirect()->to(SettingsSection::url('security')); + } + + /** + * The dialog posts over JSON: an Inertia visit would reload the panel and race + * the passkey ceremony's challenge in the session. + */ + public function store(Request $request): RedirectResponse|Response + { + $request->validate([ + 'password' => ['required', 'string', 'current_password'], + ]); + + $request->session()->passwordConfirmed(); + + return $request->wantsJson() ? response()->noContent() : back(); + } +} diff --git a/src/Http/Controllers/PasskeyController.php b/src/Http/Controllers/PasskeyController.php index 08e32c2..d4c63bb 100644 --- a/src/Http/Controllers/PasskeyController.php +++ b/src/Http/Controllers/PasskeyController.php @@ -5,6 +5,7 @@ use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Support\Facades\DB; use Laravel\Passkeys\Actions\DeletePasskey; use Laravel\Passkeys\Actions\GenerateRegistrationOptions; use Laravel\Passkeys\Actions\StorePasskey; @@ -55,18 +56,25 @@ public function store(PasskeyRegistrationRequest $request, StorePasskey $store): $user = $request->user(); - try { - $passkey = $store( - $user, - $request->string('name')->toString(), - $request->credential(), - $request->registrationOptions(), - ); - } catch (WebauthnException) { - throw InvalidPasskeyException::make('Unable to register passkey. Please try again.'); - } - - $user->notify(new PasskeyAddedNotification($passkey->name)); + // One transaction: if the alert can't be queued, the passkey is not kept + // either, so a passkey never exists without its owner being told. Queued + // before the commit, even on a connection set to wait for it. + $passkey = DB::transaction(function () use ($request, $store, $user) { + try { + $passkey = $store( + $user, + $request->string('name')->toString(), + $request->credential(), + $request->registrationOptions(), + ); + } catch (WebauthnException) { + throw InvalidPasskeyException::make('Unable to register passkey. Please try again.'); + } + + $user->notify((new PasskeyAddedNotification($passkey->name))->beforeCommit()); + + return $passkey; + }); Toast::success(__('auth::auth.passkeys.added')); diff --git a/src/Http/Controllers/ProfileController.php b/src/Http/Controllers/ProfileController.php index 116de9f..a0db810 100644 --- a/src/Http/Controllers/ProfileController.php +++ b/src/Http/Controllers/ProfileController.php @@ -3,8 +3,10 @@ namespace Modules\Auth\Http\Controllers; use Illuminate\Http\RedirectResponse; +use Illuminate\Validation\ValidationException; use Modules\Auth\Http\Requests\UpdateProfileAvatarRequest; use Modules\Auth\Http\Requests\UpdateProfileInfoRequest; +use Modules\Auth\Support\PasswordConfirmation; use Saucebase\Core\Settings\SettingsSection; use Saucebase\Core\Toast; @@ -30,6 +32,16 @@ public function updateInfo(UpdateProfileInfoRequest $request): RedirectResponse { $user = auth()->user(); + // The email is where every security alert goes, so moving it needs the same + // fresh proof as adding a passkey. The name does not. + if ($request->validated('email') !== $user->email && ! PasswordConfirmation::isRecent()) { + throw ValidationException::withMessages([ + 'email' => __('Confirm it\'s you before changing your email.'), + // The panel reopens its dialog on this one. + 'confirm_identity' => __('Confirm it\'s you to continue.'), + ]); + } + $user->update($request->validated()); // A new address has not been confirmed, whatever the old one had earned. diff --git a/src/Listeners/ForgetPasswordConfirmation.php b/src/Listeners/ForgetPasswordConfirmation.php new file mode 100644 index 0000000..1b8fe09 --- /dev/null +++ b/src/Listeners/ForgetPasswordConfirmation.php @@ -0,0 +1,19 @@ +forget('auth.password_confirmed_at'); + } +} diff --git a/src/Notifications/LoginNotification.php b/src/Notifications/LoginNotification.php index 0e11fb8..6d54db9 100644 --- a/src/Notifications/LoginNotification.php +++ b/src/Notifications/LoginNotification.php @@ -8,6 +8,7 @@ use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; use Illuminate\Support\Str; +use Saucebase\Core\Support\Markdown; class LoginNotification extends Notification implements ShouldQueue { @@ -58,7 +59,7 @@ public function toMail(object $notifiable): MailMessage 'ip' => $this->ipAddress ?? $unknown, ])) ->line(__('auth::auth.login-notification.device-details', [ - 'device' => $this->userAgent ?? $unknown, + 'device' => $this->userAgent !== null ? Markdown::escape($this->userAgent) : $unknown, ])) ->line(__('auth::auth.login-notification.recognized')) ->action(__('auth::auth.login-notification.action'), route('password.request')) diff --git a/src/Notifications/PasskeyAddedNotification.php b/src/Notifications/PasskeyAddedNotification.php index 472fbf1..3e2a0b7 100644 --- a/src/Notifications/PasskeyAddedNotification.php +++ b/src/Notifications/PasskeyAddedNotification.php @@ -3,9 +3,11 @@ namespace Modules\Auth\Notifications; use Illuminate\Bus\Queueable; +use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; use Saucebase\Core\Settings\SettingsSection; +use Saucebase\Core\Support\Markdown; /** * Tells the owner a passkey was added to their account. @@ -14,14 +16,25 @@ * planted from a hijacked session would otherwise be a silent, standing way in. * Always sent; there is no setting to turn it off. */ -class PasskeyAddedNotification extends Notification +class PasskeyAddedNotification extends Notification implements ShouldQueue { use Queueable; + /** A mail server hiccup should not cost the owner the alert. */ + public int $tries = 3; + public function __construct( public string $passkeyName, ) {} + /** + * @return list + */ + public function backoff(): array + { + return [60, 300]; + } + /** * Get the notification's delivery channels. * @@ -42,7 +55,7 @@ public function toMail(object $notifiable): MailMessage return (new MailMessage) ->subject(__('auth::auth.passkey-added-notification.subject', ['app' => $appName])) ->greeting(__('auth::auth.passkey-added-notification.greeting', ['name' => $notifiable->name])) - ->line(__('auth::auth.passkey-added-notification.notice', ['app' => $appName, 'passkey' => $this->passkeyName])) + ->line(__('auth::auth.passkey-added-notification.notice', ['app' => $appName, 'passkey' => Markdown::escape($this->passkeyName)])) ->line(__('auth::auth.passkey-added-notification.recognized')) ->action(__('auth::auth.passkey-added-notification.action'), SettingsSection::url('security')) ->line(__('auth::auth.passkey-added-notification.unrecognized')); diff --git a/src/Providers/AuthServiceProvider.php b/src/Providers/AuthServiceProvider.php index 54f5a15..58f33fb 100644 --- a/src/Providers/AuthServiceProvider.php +++ b/src/Providers/AuthServiceProvider.php @@ -4,8 +4,11 @@ use App\Models\User; use Filament\Facades\Filament; +use Illuminate\Cache\RateLimiting\Limit; +use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Gate; +use Illuminate\Support\Facades\RateLimiter; use Inertia\Inertia; use Laravel\Passkeys\Passkeys; use Modules\Auth\Policies\UserPolicy; @@ -34,6 +37,12 @@ public function boot(): void Gate::policy(User::class, UserPolicy::class); + // `throttle:passkeys`: its own counter, so a sign-in (two requests) does not + // share the per-address budget of password and magic-link sign-in. Keyed by + // user, falling back to the address for guests. + RateLimiter::for('passkeys', fn (Request $request): Limit => Limit::perMinute(10) + ->by((string) ($request->user()?->getAuthIdentifier() ?? $request->ip()))); + // Every impersonate button asks the same question the controllers do. Impersonate::configureUsing(fn (Impersonate $action) => $action ->authorize(fn (User $record): bool => Gate::allows('impersonate', $record))); diff --git a/src/Settings/ProfileSection.php b/src/Settings/ProfileSection.php index b9cd879..6c648aa 100644 --- a/src/Settings/ProfileSection.php +++ b/src/Settings/ProfileSection.php @@ -2,6 +2,7 @@ namespace Modules\Auth\Settings; +use Modules\Auth\Support\PasswordConfirmation; use Saucebase\Core\Settings\SettingsSection; /** @@ -55,6 +56,8 @@ public function props(): array 'last_login_at' => $user->last_login_at, 'has_uploaded_avatar' => $user->hasMedia('avatars'), ], + ...PasswordConfirmation::props(), + 'has_passkeys' => $user->passkeys()->exists(), ]; } } diff --git a/src/Settings/SecuritySection.php b/src/Settings/SecuritySection.php index 7fb6c6c..0f94063 100644 --- a/src/Settings/SecuritySection.php +++ b/src/Settings/SecuritySection.php @@ -2,6 +2,7 @@ namespace Modules\Auth\Settings; +use Modules\Auth\Support\PasswordConfirmation; use Saucebase\Core\Settings\SettingsSection; use STS\FilamentImpersonate\ImpersonateManager; @@ -69,6 +70,7 @@ public function props(): array ]) ->all(), 'can_add_passkeys' => ! app(ImpersonateManager::class)->isImpersonating(), + ...PasswordConfirmation::props(), ]; } } diff --git a/src/Support/PasswordConfirmation.php b/src/Support/PasswordConfirmation.php new file mode 100644 index 0000000..94dee74 --- /dev/null +++ b/src/Support/PasswordConfirmation.php @@ -0,0 +1,39 @@ + 0 ? $confirmedAt + static::timeout() : null; + } + + public static function timeout(): int + { + return (int) config('auth.password_timeout', 10800); + } + + /** For a panel: until when, not whether, so one left open asks again. */ + public static function props(): array + { + return [ + 'password_confirmed_until' => static::until(), + 'password_timeout' => static::timeout(), + ]; + } +} diff --git a/tests/Feature/AuthSettingsTest.php b/tests/Feature/AuthSettingsTest.php index 02eaed8..a352b35 100644 --- a/tests/Feature/AuthSettingsTest.php +++ b/tests/Feature/AuthSettingsTest.php @@ -19,6 +19,6 @@ public function test_fresh_install_has_authentication_defaults(): void $this->assertFalse($settings->magic_link_enabled); $this->assertSame(15, $settings->magic_link_expiry); $this->assertFalse($settings->login_notification_enabled); - $this->assertFalse($settings->passkeys_enabled); + $this->assertTrue($settings->passkeys_enabled); } } diff --git a/tests/Feature/AuthenticationSettingsPageTest.php b/tests/Feature/AuthenticationSettingsPageTest.php index 4161dc5..116b4cc 100644 --- a/tests/Feature/AuthenticationSettingsPageTest.php +++ b/tests/Feature/AuthenticationSettingsPageTest.php @@ -33,7 +33,7 @@ public function test_administrator_can_load_authentication_settings_form(): void 'magic_link_enabled' => false, 'magic_link_expiry' => 15, 'login_notification_enabled' => false, - 'passkeys_enabled' => false, + 'passkeys_enabled' => true, ]); } @@ -50,7 +50,7 @@ public function test_administrator_can_save_authentication_settings(): void 'magic_link_enabled' => false, 'magic_link_expiry' => 30, 'login_notification_enabled' => true, - 'passkeys_enabled' => true, + 'passkeys_enabled' => false, ]) ->call('save') ->assertHasNoFormErrors() @@ -62,7 +62,7 @@ public function test_administrator_can_save_authentication_settings(): void $this->assertFalse($settings->magic_link_enabled); $this->assertSame(30, $settings->magic_link_expiry); $this->assertTrue($settings->login_notification_enabled); - $this->assertTrue($settings->passkeys_enabled); + $this->assertFalse($settings->passkeys_enabled); } public function test_administrator_can_disable_all_socialite_providers(): void diff --git a/tests/Feature/ConfirmIdentityTest.php b/tests/Feature/ConfirmIdentityTest.php new file mode 100644 index 0000000..3564457 --- /dev/null +++ b/tests/Feature/ConfirmIdentityTest.php @@ -0,0 +1,180 @@ +actingAs($this->createUser()) + ->post(route('password.confirm.store'), ['password' => 'password']) + ->assertSessionHasNoErrors() + ->assertRedirect(); + + $this->assertNotNull(session('auth.password_confirmed_at')); + } + + public function test_a_wrong_password_does_not(): void + { + $this->actingAs($this->createUser()) + ->post(route('password.confirm.store'), ['password' => 'wrong']) + ->assertSessionHasErrors('password'); + + $this->assertNull(session('auth.password_confirmed_at')); + } + + /** The dialog confirms over JSON: an Inertia visit would reload the panel mid-ceremony. */ + public function test_the_dialog_confirms_over_json(): void + { + $this->actingAs($this->createUser()) + ->postJson(route('password.confirm.store'), ['password' => 'password']) + ->assertNoContent(); + + $this->assertNotNull(session('auth.password_confirmed_at')); + + $this->postJson(route('password.confirm.store'), ['password' => 'wrong']) + ->assertUnprocessable() + ->assertJsonValidationErrors('password'); + } + + public function test_the_confirm_page_sends_the_user_to_the_security_panel(): void + { + $this->actingAs($this->createUser()) + ->get(route('password.confirm')) + ->assertRedirect(SettingsSection::url('security')); + } + + public function test_changing_the_email_needs_a_recent_confirmation(): void + { + $user = $this->createUser(); + + $this->actingAs($user) + ->patch(route('settings.profile.update-info'), ['name' => $user->name, 'email' => 'attacker@example.com']) + ->assertSessionHasErrors(['email', 'confirm_identity']); + + $this->assertNotSame('attacker@example.com', $user->fresh()->email); + } + + public function test_changing_only_the_name_needs_none(): void + { + $user = $this->createUser(); + + $this->actingAs($user) + ->patch(route('settings.profile.update-info'), ['name' => 'New Name', 'email' => $user->email]) + ->assertSessionHasNoErrors(); + + $this->assertSame('New Name', $user->fresh()->name); + } + + public function test_a_confirmed_session_can_change_the_email(): void + { + $user = $this->createUser(); + + $this->actingAs($user) + ->withSession(['auth.password_confirmed_at' => time()]) + ->patch(route('settings.profile.update-info'), ['name' => $user->name, 'email' => 'moved@example.com']) + ->assertSessionHasNoErrors(); + + $this->assertSame('moved@example.com', $user->fresh()->email); + } + + public function test_a_confirmation_expires(): void + { + $user = $this->createUser(); + + $this->actingAs($user) + ->withSession(['auth.password_confirmed_at' => time() - config('auth.password_timeout') - 1]) + ->patch(route('settings.profile.update-info'), ['name' => $user->name, 'email' => 'moved@example.com']) + ->assertSessionHasErrors('email'); + } + + /** + * Until when, not whether: a panel left open past the timeout must ask again + * rather than trust what it was told when it loaded. + */ + public function test_the_panels_say_until_when_the_session_is_confirmed(): void + { + $this->actingAs($this->createUser()); + + foreach ([SecuritySection::class, ProfileSection::class] as $section) { + $props = app($section)->props(); + + $this->assertNull($props['password_confirmed_until']); + $this->assertSame(config('auth.password_timeout'), $props['password_timeout']); + } + + $confirmedAt = time() - 60; + session(['auth.password_confirmed_at' => $confirmedAt]); + + foreach ([SecuritySection::class, ProfileSection::class] as $section) { + $this->assertSame( + $confirmedAt + config('auth.password_timeout'), + app($section)->props()['password_confirmed_until'], + ); + } + } + + /** + * Where `password.confirm` sends a stopped Inertia visit (removing a passkey): + * back to the panel with an error it reopens the dialog on, not off the page. + */ + public function test_a_stopped_visit_goes_back_asking_to_confirm(): void + { + $this->actingAs($this->createUser()) + ->from('/dashboard') + ->get(route('password.confirm'), [ + 'X-Inertia' => 'true', + 'X-Inertia-Version' => (string) app(HandleInertiaRequests::class)->version(request()), + ]) + ->assertRedirect('/dashboard') + ->assertSessionHasErrors('confirm_identity'); + } + + /** The email dialog offers "Use a passkey" only to someone who has one. */ + public function test_the_profile_panel_says_whether_the_user_has_passkeys(): void + { + $user = $this->createUser(); + $this->actingAs($user); + + $this->assertFalse(app(ProfileSection::class)->props()['has_passkeys']); + + $user->passkeys()->create(['name' => 'Laptop', 'credential_id' => 'abc', 'credential' => []]); + + $this->assertTrue(app(ProfileSection::class)->props()['has_passkeys']); + } + + /** + * The confirmation is a session timestamp, and impersonation swaps the user inside + * the same session: a password confirmed as the impersonated user must not vouch + * for the admin after leaving, nor the admin's for the user. + */ + public function test_impersonating_forgets_the_confirmation(): void + { + [$admin, $user] = [$this->createUser(), $this->createUser()]; + + session()->put('auth.password_confirmed_at', time()); + event(new EnterImpersonation($admin, $user)); + $this->assertFalse(session()->has('auth.password_confirmed_at')); + + session()->put('auth.password_confirmed_at', time()); + event(new LeaveImpersonation($admin, $user)); + $this->assertFalse(session()->has('auth.password_confirmed_at')); + } +} diff --git a/tests/Feature/NotificationMarkdownInjectionTest.php b/tests/Feature/NotificationMarkdownInjectionTest.php new file mode 100644 index 0000000..9f25f87 --- /dev/null +++ b/tests/Feature/NotificationMarkdownInjectionTest.php @@ -0,0 +1,51 @@ + + */ + public static function notifications(): array + { + return [ + 'passkey name' => [fn (): Notification => new PasskeyAddedNotification(self::PAYLOAD)], + 'login user agent' => [fn (): Notification => new LoginNotification(CarbonImmutable::now(), '203.0.113.10', self::PAYLOAD)], + ]; + } + + #[DataProvider('notifications')] + public function test_user_controlled_text_renders_as_plain_text(callable $make): void + { + $html = (string) $make()->toMail(User::factory()->create())->render(); + + $this->assertStringNotContainsString('evil.example"', $html); + $this->assertStringNotContainsString(' + response.url().includes('/settings/profile/info'), + ); + await page + .getByTestId('confirm-identity-password') + .fill(credentials.user.password); + await page.getByTestId('confirm-identity-submit').click(); + await saved; + + await expect(dialog).toBeHidden(); + await page.reload(); + await expect(page.locator('input[name="email"]')).toHaveValue(email); + }); + + test('cancelling leaves the email as it was', async ({ + page, + loginAs, + credentials, + }) => { + await loginAs(credentials.user); + await page.goto('/dashboard#settings/profile'); + await expect(page.getByTestId('settings-profile-panel')).toBeVisible(); + + await page.locator('input[name="email"]').fill('elsewhere@example.com'); + await page.getByTestId('submit-profile-info').click(); + await page.getByTestId('confirm-identity-cancel').click(); + await expect(page.getByTestId('confirm-identity-dialog')).toBeHidden(); + + await page.reload(); + await expect(page.locator('input[name="email"]')).toHaveValue( + credentials.user.email, + ); + }); +}); diff --git a/tests/e2e/tests/passkeys/passkeys.spec.ts b/tests/e2e/tests/passkeys/passkeys.spec.ts index bd3fe8e..a061850 100644 --- a/tests/e2e/tests/passkeys/passkeys.spec.ts +++ b/tests/e2e/tests/passkeys/passkeys.spec.ts @@ -22,18 +22,43 @@ async function addVirtualAuthenticator(page: Page) { }); } -/** Passkeys ship switched off, so the disabled cases need no setup. */ +/** The password step, asked before a passkey is added or removed. */ +async function confirmIdentity(page: Page, password: string) { + const dialog = page.getByTestId('confirm-identity-dialog'); + + await expect(dialog).toBeVisible(); + await page.getByTestId('confirm-identity-password').fill(password); + await page.getByTestId('confirm-identity-submit').click(); + await expect(dialog).toBeHidden(); +} + +/** Passkeys ship switched on; the disabled case switches them off and back. */ test.describe('Passkeys', () => { test.describe.configure({ mode: 'serial' }); test('the passkey button is hidden while the feature is off', async ({ page, + laravel, }) => { - const loginPage = new LoginPage(page); - await loginPage.goto(); - await loginPage.expectToBeVisible(); + await laravel.query('UPDATE settings SET payload = ? WHERE name = ?', [ + 'false', + 'passkeys_enabled', + ]); - await expect(page.getByTestId('passkey-login-button')).toHaveCount(0); + try { + const loginPage = new LoginPage(page); + await loginPage.goto(); + await loginPage.expectToBeVisible(); + + await expect(page.getByTestId('passkey-login-button')).toHaveCount( + 0, + ); + } finally { + await laravel.query( + 'UPDATE settings SET payload = ? WHERE name = ?', + ['true', 'passkeys_enabled'], + ); + } }); test('adds a passkey, signs in with it and removes it', async ({ @@ -44,11 +69,6 @@ test.describe('Passkeys', () => { }) => { const name = `E2E passkey ${Date.now()}`; - await laravel.query('UPDATE settings SET payload = ? WHERE name = ?', [ - 'true', - 'passkeys_enabled', - ]); - try { await addVirtualAuthenticator(page); @@ -58,6 +78,7 @@ test.describe('Passkeys', () => { await page.getByTestId('passkey-name-input').fill(name); await page.getByTestId('add-passkey').click(); + await confirmIdentity(page, credentials.user.password); // The ceremony, the store and the panel reload are three round trips. await expect( @@ -80,14 +101,12 @@ test.describe('Passkeys', () => { .filter({ hasText: name }); await passkey.getByTestId('remove-passkey').click(); await page.getByTestId('confirm-dialog-confirm').click(); + // A passkey sign-in is a new session: removing asks again. + await confirmIdentity(page, credentials.user.password); await expect(passkey).toHaveCount(0, { timeout: 15_000 }); } finally { await laravel.query('DELETE FROM passkeys WHERE name = ?', [name]); - await laravel.query( - 'UPDATE settings SET payload = ? WHERE name = ?', - ['false', 'passkeys_enabled'], - ); } }); }); From 173acd8cb766428e270ed7771351c9fd64bf23c3 Mon Sep 17 00:00:00 2001 From: roble Date: Thu, 29 Oct 2026 21:38:44 +0000 Subject: [PATCH 3/3] fix: let a passkey confirm the session after the feature is switched off Removing a passkey stays available with passkeys off, but its confirmation routes sat behind the setting, so a user with no password could not prove it was them. Also document the confirmation flow in the auth skill. Co-Authored-By: Claude Opus 5.5 --- .../saucebase-auth-development/SKILL.md | 35 ++++++++++++++----- routes/web.php | 6 +++- tests/Feature/PasskeyTest.php | 16 +++++++++ 3 files changed, 48 insertions(+), 9 deletions(-) diff --git a/resources/boost/skills/saucebase-auth-development/SKILL.md b/resources/boost/skills/saucebase-auth-development/SKILL.md index d24a74a..5dbb428 100644 --- a/resources/boost/skills/saucebase-auth-development/SKILL.md +++ b/resources/boost/skills/saucebase-auth-development/SKILL.md @@ -13,7 +13,7 @@ Authentication, registration, magic link (passwordless), passkeys (WebAuthn, via | Layer | Files | |-------|-------| -| Controllers | `LoginController`, `RegisterController`, `SocialiteController`, `ForgotPasswordController`, `ResetPasswordController`, `VerifyEmailController`, `EmailVerificationNotificationController`, `EmailVerificationPromptController`, `PasswordController`, `ProfileController`, `ReimpersonateController`, `MagicLinkController`, `PasskeyLoginController`, `PasskeyController` | +| Controllers | `LoginController`, `RegisterController`, `SocialiteController`, `ForgotPasswordController`, `ResetPasswordController`, `VerifyEmailController`, `EmailVerificationNotificationController`, `EmailVerificationPromptController`, `PasswordController`, `ProfileController`, `ReimpersonateController`, `MagicLinkController`, `PasskeyLoginController`, `PasskeyController`, `ConfirmPasswordController` | | Models | `SocialAccount` (provider, tokens, avatar, last_login_at), `MagicLinkToken` (hashed token, expires_at, used_at), `Laravel\Passkeys\Passkey` (the package's; table shipped by this module) | | Service | `SocialiteService` — all OAuth logic (find/create user, link/disconnect accounts) | | Requests | `LoginRequest` (credential validation + rate limiting), `RegisterRequest` (password hashing in `passedValidation`), `UpdateProfileInfoRequest`, `UpdateProfileAvatarRequest`, `UpdatePasswordRequest` | @@ -44,7 +44,7 @@ Pages, layouts and components live under `resources/js/`. The module's `resource **Magic Link** (outside guest/auth groups): `magic-link.authenticate` — `/auth/magic-link/{token}` (GET) — must be accessible from email clients -**Account settings** (`/settings/*`, middleware `auth`, `verified`): `settings.profile` (redirects to the `#settings/profile` fragment), `settings.profile.update-info` (PATCH), `settings.profile.update-avatar` (POST), `settings.profile.delete-avatar` (DELETE), `settings.profile.password.update` (PUT), `settings.passkeys.options` (GET, JSON) and `settings.passkeys.store` (POST, JSON) behind the setting and `throttle:passkeys`, `settings.passkeys.destroy` — `/settings/passkeys/{passkeyId}` (DELETE, not behind the setting) +**Account settings** (`/settings/*`, middleware `auth`, `verified`): `settings.profile` (redirects to the `#settings/profile` fragment), `settings.profile.update-info` (PATCH), `settings.profile.update-avatar` (POST), `settings.profile.delete-avatar` (DELETE), `settings.profile.password.update` (PUT), `password.confirm` — `/settings/confirm-password` (GET, where Laravel's `password.confirm` middleware sends what it stops) and `password.confirm.store` (POST, `throttle:6,1`), `settings.passkeys.confirm.options` (GET) and `settings.passkeys.confirm` (POST) — confirm with a passkey, `throttle:passkeys`, not behind the setting, `settings.passkeys.options` (GET, JSON) and `settings.passkeys.store` (POST, JSON) behind the setting, `throttle:passkeys` and `password.confirm`, `settings.passkeys.destroy` — `/settings/passkeys/{passkeyId}` (DELETE, `password.confirm`, not behind the setting) The routes are grouped under `settings.profile.*` for history; password and socialite disconnect are rendered by the **Security** panel, not Profile. @@ -99,11 +99,12 @@ WebAuthn work; tests stub `VerifyPasskey`/`StorePasskey`. - The sign-in challenge names no account, so it reveals nothing about which emails exist. - **Adding** a passkey is refused (403) while impersonating, and the panel hides the form (`can_add_passkeys`): it would outlive the impersonation as a way back into the account. -- Adding one always emails the owner (`PasskeyAddedNotification`), the mitigation for a - passkey planted from a hijacked session. There is no re-authentication step before adding - one: many users have no password to confirm. -- **Removing** is not behind the setting, and the Security panel lists passkeys while the user - still has some, so a passkey added before the feature was switched off can still be removed. +- Adding or removing one needs a recent confirmation (`password.confirm`); see below. Adding + one also emails the owner (`PasskeyAddedNotification`), queued with `beforeCommit()` in the + same transaction as the passkey, so a queue failure keeps no passkey. +- **Removing** is not behind the setting, nor is confirming with a passkey, and the Security + panel lists passkeys while the user still has some: a passkey added before the feature was + switched off can still be removed, by a user with no password too. Removal is scoped to the user's own relation (404 otherwise). The route parameter is `passkeyId`, not `passkey`: the package binds `{passkey}` globally to any user's passkey. - Passkeys don't count as a login method for `SocialiteService::disconnectProvider()`, and @@ -112,6 +113,24 @@ WebAuthn work; tests stub `VerifyPasskey`/`StorePasskey`. - Passkeys are bound to the relying party ID (the host in `APP_URL`) and need HTTPS or `localhost`. Changing the domain invalidates every passkey. +### Confirming it's you +Adding or removing a passkey, and changing the email, need fresh proof: Laravel's +`password.confirm` and `auth.password_timeout`, the same `auth.password_confirmed_at` session key. + +- `ConfirmIdentityDialog` (Vue and React) takes the password (`password.confirm.store`) or a + passkey (the package's `PasskeyConfirmationController`). It posts over JSON through core's + `useHttp`, never as an Inertia visit: a visit reloads the panel and overwrites the passkey + challenge in the session. +- The panels get `password_confirmed_until` and `password_timeout` (`PasswordConfirmation::props()`), + never a boolean, and ask again 30s early (`lib/passwordConfirmation.ts`). An email change is + checked in `ProfileController`, since a route middleware can't tell it from a name change. +- When the server still refuses: `confirm_identity` comes back as a validation error (email + change, and `ConfirmPasswordController::show()` for a stopped Inertia visit), and the panel + reopens the dialog and retries. A failed add only marks the session unconfirmed: the + passkeys client keeps no status code. +- `ForgetPasswordConfirmation` drops the confirmation on entering and leaving impersonation, + so one account's password never vouches for another. + ### Rate Limiting `LoginRequest::ensureIsNotRateLimited()` — 5 attempts per `email|ip` key. Fires `Lockout` event, throws `AuthException::throttle($seconds)`. Cleared on success. Covered in PHP (`LoginTest`), not e2e: Playwright workers share one IP, so a lockout there leaks into other login tests. @@ -212,7 +231,7 @@ php artisan test --testsuite=Modules --filter='^Modules\\Auth\\Tests' # PHPUnit npx playwright test --project="@auth*" # E2E ``` -**E2E coverage**: login (basic, errors, security (CSRF), social, modal, logout), register (basic, errors), forgot-password (basic, errors), verify-email, profile (avatar, socialite settings under the Security panel), passkeys (add, sign in, remove — Chromium's virtual authenticator, so Chromium only). Page objects in `tests/e2e/pages/`; specs import the shared `test` fixture from `@e2e/fixtures`. +**E2E coverage**: login (basic, errors, security (CSRF), social, modal, logout), register (basic, errors), forgot-password (basic, errors), verify-email, profile (avatar, socialite settings under the Security panel), passkeys (add, sign in, remove, each confirmed — Chromium's virtual authenticator, so Chromium only), confirm-identity (email change). Page objects in `tests/e2e/pages/`; specs import the shared `test` fixture from `@e2e/fixtures`. ## Gotchas diff --git a/routes/web.php b/routes/web.php index ce98c83..45cf2d8 100644 --- a/routes/web.php +++ b/routes/web.php @@ -172,13 +172,17 @@ ->middleware('throttle:6,1') ->name('password.confirm.store'); - Route::middleware([EnsurePasskeysEnabled::class, 'throttle:passkeys'])->group(function (): void { + // Not behind the setting, like removal below: with the feature off, a + // user with no password can still prove it's them to remove a passkey. + Route::middleware('throttle:passkeys')->group(function (): void { Route::get('passkeys/confirm/options', [PasskeyConfirmationController::class, 'index']) ->name('settings.passkeys.confirm.options'); Route::post('passkeys/confirm', [PasskeyConfirmationController::class, 'store']) ->name('settings.passkeys.confirm'); + }); + Route::middleware([EnsurePasskeysEnabled::class, 'throttle:passkeys'])->group(function (): void { Route::get('passkeys/options', [PasskeyController::class, 'options']) ->middleware('password.confirm') ->name('settings.passkeys.options'); diff --git a/tests/Feature/PasskeyTest.php b/tests/Feature/PasskeyTest.php index 85303f6..f541adc 100644 --- a/tests/Feature/PasskeyTest.php +++ b/tests/Feature/PasskeyTest.php @@ -411,6 +411,22 @@ public function test_a_passkey_can_be_removed_after_the_feature_is_switched_off( $this->assertModelMissing($passkey); } + /** + * Removing still needs fresh proof after the feature is off, and a user with no + * password can only give it with a passkey. + */ + public function test_a_passkey_still_confirms_the_session_after_the_feature_is_switched_off(): void + { + $user = $this->createUser(); + $this->createPasskey($user); + + $this->setPasskeysEnabled(false); + + $this->actingAs($user) + ->getJson(route('settings.passkeys.confirm.options')) + ->assertOk(); + } + public function test_a_user_cannot_remove_another_users_passkey(): void { $passkey = $this->createPasskey($this->createUser());