diff --git a/README.md b/README.md
index fe1a8d0..c323cc7 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,31 @@ 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 on 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.
+- Resetting a password keeps the account's passkeys, as most services do. Users are emailed whenever one is added, and after a suspected compromise they should review the list under **Settings → Security** and remove any they don't recognize.
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..7fc9bf2 100644
--- a/composer.json
+++ b/composer.json
@@ -37,9 +37,10 @@
}
},
"require": {
- "saucebase/core": "^2.0",
+ "saucebase/core": "^2.7",
"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..db434d4 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' => true,
'auth.enabled_socialite_providers' => [],
];
diff --git a/lang/en/auth.php b/lang/en/auth.php
index 8aab13b..6da4b80 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 in Settings → Security. Requires HTTPS on the APP_URL domain. Moving to another domain breaks every existing 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..5dbb428 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`, `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` |
| 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:passkeys` (10/min, own counter)
**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), `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.
@@ -84,6 +84,53 @@ 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` (on 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 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
+ 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.
+
+### 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.
@@ -184,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). 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/resources/js/lib/deviceName.test.ts b/resources/js/lib/deviceName.test.ts
new file mode 100644
index 0000000..fc34b07
--- /dev/null
+++ b/resources/js/lib/deviceName.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest';
+import { deviceName } from './deviceName';
+
+describe('deviceName', () => {
+ it.each([
+ [
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
+ 'Chrome on macOS',
+ ],
+ [
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15',
+ 'Safari on macOS',
+ ],
+ [
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0',
+ 'Edge on Windows',
+ ],
+ [
+ 'Mozilla/5.0 (X11; Linux x86_64; rv:131.0) Gecko/20100101 Firefox/131.0',
+ 'Firefox on Linux',
+ ],
+ [
+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1',
+ 'Safari on iPhone',
+ ],
+ [
+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/130.0.0.0 Mobile/15E148 Safari/604.1',
+ 'Chrome on iPhone',
+ ],
+ [
+ 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Mobile Safari/537.36',
+ 'Chrome on Android',
+ ],
+ [
+ 'Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
+ 'Chrome on ChromeOS',
+ ],
+ ])('names %s', (userAgent, expected) => {
+ expect(deviceName(userAgent)).toBe(expected);
+ });
+
+ it('falls back to whichever half it recognizes', () => {
+ expect(deviceName('Mozilla/5.0 (Windows NT 10.0) Unknown/1.0')).toBe(
+ 'Windows',
+ );
+ expect(deviceName('Firefox/131.0')).toBe('Firefox');
+ });
+
+ it('gives up on an agent it cannot read', () => {
+ expect(deviceName('curl/8.0')).toBeNull();
+ expect(deviceName('')).toBeNull();
+ });
+});
diff --git a/resources/js/lib/deviceName.ts b/resources/js/lib/deviceName.ts
new file mode 100644
index 0000000..8b0dd03
--- /dev/null
+++ b/resources/js/lib/deviceName.ts
@@ -0,0 +1,34 @@
+/**
+ * A default passkey name from the browser's user agent, e.g. "Chrome on macOS", so
+ * adding one doesn't stall on naming it. Order matters: Edge and Opera also say
+ * Chrome, Chrome also says Safari, and iOS also says Mac OS X.
+ */
+const browsers: Array<[RegExp, string]> = [
+ [/Edg(e|A|iOS)?\//, 'Edge'],
+ [/OPR\/|Opera/, 'Opera'],
+ [/Firefox\/|FxiOS\//, 'Firefox'],
+ [/Chrome\/|CriOS\//, 'Chrome'],
+ [/Safari\//, 'Safari'],
+];
+
+const systems: Array<[RegExp, string]> = [
+ [/iPhone/, 'iPhone'],
+ [/iPad/, 'iPad'],
+ [/Android/, 'Android'],
+ [/CrOS/, 'ChromeOS'],
+ [/Windows/, 'Windows'],
+ [/Mac OS X|Macintosh/, 'macOS'],
+ [/Linux/, 'Linux'],
+];
+
+const match = (list: Array<[RegExp, string]>, userAgent: string) =>
+ list.find(([pattern]) => pattern.test(userAgent))?.[1];
+
+export function deviceName(userAgent: string): string | null {
+ const browser = match(browsers, userAgent);
+ const system = match(systems, userAgent);
+
+ if (browser && system) return `${browser} on ${system}`;
+
+ return browser ?? system ?? null;
+}
diff --git a/resources/js/lib/passwordConfirmation.test.ts b/resources/js/lib/passwordConfirmation.test.ts
new file mode 100644
index 0000000..3f48141
--- /dev/null
+++ b/resources/js/lib/passwordConfirmation.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+import { confirmedFor, isConfirmed } from './passwordConfirmation';
+
+const now = 1_000_000_000_000;
+
+describe('isConfirmed', () => {
+ it('is not without a confirmation', () => {
+ expect(isConfirmed(null, now)).toBe(false);
+ expect(isConfirmed(undefined, now)).toBe(false);
+ });
+
+ it('is until shortly before the server stops trusting it', () => {
+ const until = now / 1000 + 600;
+
+ expect(isConfirmed(until, now)).toBe(true);
+ // The browser's clock may run behind the server's: ask a little early.
+ expect(isConfirmed(until, (until - 20) * 1000)).toBe(false);
+ expect(isConfirmed(until, (until + 1) * 1000)).toBe(false);
+ });
+});
+
+describe('confirmedFor', () => {
+ it('is the timeout from now, in seconds', () => {
+ expect(confirmedFor(10800, now)).toBe(now / 1000 + 10800);
+ });
+});
diff --git a/resources/js/lib/passwordConfirmation.ts b/resources/js/lib/passwordConfirmation.ts
new file mode 100644
index 0000000..e1bc835
--- /dev/null
+++ b/resources/js/lib/passwordConfirmation.ts
@@ -0,0 +1,16 @@
+/**
+ * Whether the session's password confirmation still holds, from the server's
+ * `password_confirmed_until` (unix seconds). Asks 30s early, since the browser's
+ * clock may run behind the server's.
+ */
+export function isConfirmed(
+ until: number | null | undefined,
+ now = Date.now(),
+): boolean {
+ return until != null && now / 1000 < until - 30;
+}
+
+/** Until when a confirmation made now holds: the server's `password_timeout` on. */
+export function confirmedFor(timeout: number, now = Date.now()): number {
+ return now / 1000 + timeout;
+}
diff --git a/resources/js/react/components/ConfirmIdentityDialog.tsx b/resources/js/react/components/ConfirmIdentityDialog.tsx
new file mode 100644
index 0000000..2df0dfa
--- /dev/null
+++ b/resources/js/react/components/ConfirmIdentityDialog.tsx
@@ -0,0 +1,182 @@
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { FieldError } from '@/components/ui/field';
+import { Input } from '@/components/ui/input';
+import { usePasskeyVerify } from '@laravel/passkeys/react';
+import { useHttp } from '@saucebase/react/hooks/useHttp';
+import { useT } from '@saucebase/react/i18n';
+import { KeyRound, Loader2, ShieldCheck } from 'lucide-react';
+import type { FormEvent } from 'react';
+
+/**
+ * Fresh proof before an account-changing action (adding or removing a passkey,
+ * changing the email): the password, or one of the user's passkeys. Either marks the
+ * session confirmed for `auth.password_timeout`, so the action runs straight after.
+ */
+export function ConfirmIdentityDialog({
+ open,
+ onOpenChange,
+ onConfirmed,
+ hasPasskeys = false,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onConfirmed: () => void;
+ /** Offer "Use a passkey" — only when the user has one to use. */
+ hasPasskeys?: boolean;
+}) {
+ const t = useT();
+ // Any failure besides a wrong password (throttled, expired session, offline)
+ // shows under the field rather than leaving the dialog silent.
+ const form = useHttp({ password: '' }, (message, http) =>
+ http.setError('password', t(message)),
+ );
+
+ const done = () => {
+ form.reset();
+ onOpenChange(false);
+ onConfirmed();
+ };
+
+ const submit = (event: FormEvent) => {
+ event.preventDefault();
+
+ // JSON, not an Inertia visit: a visit reloads the settings panel, and that
+ // reload races the passkey ceremony's challenge in the session.
+ form.post(route('password.confirm.store'), { onSuccess: done });
+ };
+
+ const {
+ verify,
+ isLoading: isVerifying,
+ errorInstance,
+ isSupported,
+ } = usePasskeyVerify({
+ routes: {
+ options: route('settings.passkeys.confirm.options'),
+ submit: route('settings.passkeys.confirm'),
+ },
+ onSuccess: done,
+ });
+
+ const passkeyError =
+ errorInstance?.name === 'UserCancelledError'
+ ? t('Passkey confirmation was cancelled.')
+ : errorInstance?.message;
+
+ const busy = form.processing || isVerifying;
+
+ // Same layout as the app's confirm dialog (DynamicDialog), plus the password.
+ return (
+
+ );
+}
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 && (
- {t('Your password and the accounts that can sign you in')}
+ {t(
+ 'Your password, passkeys and the accounts that can sign you in',
+ )}
+ {t(
+ 'Sign in with your fingerprint, face or screen lock instead of a password.',
+ )}
+
+ {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.')}
+
{t('Passkeys')}
+