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 ( + + +
+
+ +
+ + {t("Confirm it's you")} + + {t( + 'This changes how you sign in. Confirm your password to continue.', + )} + + + + + form.setData('password', event.target.value) + } + type="password" + name="password" + className="mt-4" + autoComplete="current-password" + aria-label={t('Password')} + placeholder={t('Password')} + disabled={busy} + data-testid="confirm-identity-password" + /> + {form.errors.password && ( + + {form.errors.password} + + )} + + {hasPasskeys && isSupported && ( + <> + + {passkeyError && ( + + {passkeyError} + + )} + + )} + +

+ {t( + 'No password? Sign out and use "Forgot password" to set one.', + )} +

+
+
+
+ + +
+
+
+
+ ); +} 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/SettingsProfile.tsx b/resources/js/react/pages/SettingsProfile.tsx index 3e6a786..aaf8335 100644 --- a/resources/js/react/pages/SettingsProfile.tsx +++ b/resources/js/react/pages/SettingsProfile.tsx @@ -3,24 +3,77 @@ import { Button } from '@/components/ui/button'; import { Field, FieldError, FieldLabel } from '@/components/ui/field'; import { Input } from '@/components/ui/input'; import type { User } from '@/types'; +import type { FormComponentRef, PendingVisit } from '@inertiajs/core'; import { Form, router, usePage } from '@inertiajs/react'; import { getInitials } from '@saucebase/core/lib/initials'; import { useDialog } from '@saucebase/react/hooks/useDialog'; import { useT } from '@saucebase/react/i18n'; import { Camera, Loader2, Trash2 } from 'lucide-react'; -import { useState, type ChangeEvent } from 'react'; +import { useEffect, useRef, useState, type ChangeEvent } from 'react'; +import { confirmedFor, isConfirmed } from '../../lib/passwordConfirmation'; +import { ConfirmIdentityDialog } from '../components/ConfirmIdentityDialog'; interface SettingsProfileProps { user: User & { has_uploaded_avatar?: boolean; }; + password_confirmed_until?: number | null; + password_timeout: number; + has_passkeys?: boolean; } -export default function SettingsProfile({ user }: SettingsProfileProps) { +export default function SettingsProfile({ + user, + password_confirmed_until = null, + password_timeout, + has_passkeys = false, +}: SettingsProfileProps) { const t = useT(); 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 = useRef(null); + // A ref, not state: the resend below runs before a state update would land. + const confirmedUntil = useRef(password_confirmed_until); + const [confirmingIdentity, setConfirmingIdentity] = useState(false); + + useEffect(() => { + confirmedUntil.current = password_confirmed_until; + }, [password_confirmed_until]); + + const beforeProfileSave = (visit: PendingVisit) => { + const email = + visit.data instanceof FormData + ? visit.data.get('email') + : visit.data.email; + + if (isConfirmed(confirmedUntil.current) || email === user?.email) { + return true; + } + + setConfirmingIdentity(true); + + return false; + }; + + const onIdentityConfirmed = () => { + confirmedUntil.current = confirmedFor(password_timeout); + profileForm.current?.submit(); + }; + + /** The confirmation ran out on the server first: ask, then the dialog resends. */ + const onProfileError = (errors: Record) => { + if (!errors.confirm_identity) return; + + confirmedUntil.current = null; + setConfirmingIdentity(true); + }; + const [avatarPreview, setAvatarPreview] = useState(null); const [isUpdatingAvatar, setIsUpdatingAvatar] = useState(false); const [isRemovingAvatar, setIsRemovingAvatar] = useState(false); @@ -153,11 +206,14 @@ export default function SettingsProfile({ user }: SettingsProfileProps) {
{({ errors }) => ( <> @@ -223,6 +279,13 @@ export default function SettingsProfile({ user }: SettingsProfileProps) { )}
+ + ); } diff --git a/resources/js/react/pages/SettingsSecurity.tsx b/resources/js/react/pages/SettingsSecurity.tsx index 8d23245..45e0413 100644 --- a/resources/js/react/pages/SettingsSecurity.tsx +++ b/resources/js/react/pages/SettingsSecurity.tsx @@ -3,11 +3,15 @@ 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 { useMemo, useState } from 'react'; +import { Eye, EyeOff, KeyRound, Loader2, Trash2 } from 'lucide-react'; +import { useEffect, useMemo, useRef, useState } from 'react'; +import { deviceName } from '../../lib/deviceName'; +import { confirmedFor, isConfirmed } from '../../lib/passwordConfirmation'; +import { ConfirmIdentityDialog } from '../components/ConfirmIdentityDialog'; import { providerIcons } from '../components/providerIcons'; type SocialiteProvider = { @@ -15,6 +19,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 +39,10 @@ interface SettingsSecurityProps { social_accounts?: SocialAccount[]; }; available_providers?: SocialiteProvider[]; + passkeys?: Passkey[]; + can_add_passkeys?: boolean; + password_confirmed_until?: number | null; + password_timeout: number; } /** @@ -93,8 +109,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 +119,164 @@ function PasswordField({ export default function SettingsSecurity({ user, available_providers, + passkeys = [], + can_add_passkeys, + password_confirmed_until = null, + password_timeout, }: 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, + ); + + /** + * Adding or removing a passkey needs fresh proof (`password.confirm` on the + * routes). Ask first when the session has none, then run the chosen action. + */ + // A ref, not state: a retry runs inside the handler that just cleared it. + const confirmedUntil = useRef(password_confirmed_until); + const [confirmingIdentity, setConfirmingIdentity] = useState(false); + const afterConfirmation = useRef<(() => void) | null>(null); + + useEffect(() => { + confirmedUntil.current = password_confirmed_until; + }, [password_confirmed_until]); + + const withConfirmation = (action: () => void) => { + if (isConfirmed(confirmedUntil.current)) return action(); + + afterConfirmation.current = action; + setConfirmingIdentity(true); + }; + + const onIdentityConfirmed = () => { + confirmedUntil.current = confirmedFor(password_timeout); + afterConfirmation.current?.(); + afterConfirmation.current = null; + }; + + /** + * 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, setIsRefreshingPasskeys] = useState(false); + + useEffect(() => { + setIsRefreshingPasskeys((refreshing) => { + if (refreshing) setPasskeyName(''); + + return false; + }); + }, [passkeys]); + + 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: isRegistering, + errorInstance: addPasskeyError, + isSupported: passkeysSupported, + } = usePasskeyRegister({ + routes: { + options: route('settings.passkeys.options'), + submit: route('settings.passkeys.store'), + }, + onSuccess: () => { + setIsRefreshingPasskeys(true); + router.reload(); + }, + }); + + /** + * 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 it. + */ + useEffect(() => { + if (addPasskeyError?.name === 'Error') confirmedUntil.current = null; + }, [addPasskeyError]); + + // 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 isAddingPasskey = isRegistering || isRefreshingPasskeys; + + /** "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 = (event: React.FormEvent) => { + event.preventDefault(); + + const name = passkeyName.trim() || defaultPasskeyName; + + if (!name) return; + + withConfirmation(() => 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'), + icon: Trash2, + cancelLabel: t('Cancel'), + variant: 'destructive', + align: 'left', + }); + + if (!confirmed) return; + + withConfirmation(() => deletePasskey(passkey)); + }; + + const deletePasskey = (passkey: Passkey) => { + setIsRemovingPasskey(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.current = null; + withConfirmation(() => deletePasskey(passkey)); + }, + onFinish: () => setIsRemovingPasskey(null), + }); + }; const enabledProviders = useMemo(() => { const auth = page.props.auth as { @@ -191,7 +359,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 +422,146 @@ export default function SettingsSecurity({
+ {/* Passkeys */} + {showPasskeys && ( + <> + + +
+
+

{t('Passkeys')}

+

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

+
+ + {canAddPasskey && ( +
+
+ + setPasskeyName(event.target.value) + } + /> + +
+ {addPasskeyErrorMessage && ( + + {addPasskeyErrorMessage} + + )} +
+ )} + + {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.')} +

+
+ )} +
+ + )} + {/* Connected accounts */} {hasSocialiteProviders && ( <> @@ -367,6 +677,13 @@ export default function SettingsSecurity({ )} + + 0} + onConfirmed={onIdentityConfirmed} + /> ); } 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/ConfirmIdentityDialog.vue b/resources/js/vue/components/ConfirmIdentityDialog.vue new file mode 100644 index 0000000..92383db --- /dev/null +++ b/resources/js/vue/components/ConfirmIdentityDialog.vue @@ -0,0 +1,177 @@ + + + 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/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 1406675..5cd94c9 100644 --- a/resources/js/vue/pages/SettingsSecurity.vue +++ b/resources/js/vue/pages/SettingsSecurity.vue @@ -1,24 +1,38 @@