Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

</div>

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.

Expand All @@ -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
Expand Down Expand Up @@ -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`:

Expand Down
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
},
"minimum-stability": "stable"
}
37 changes: 37 additions & 0 deletions database/migrations/1000_00_00_000006_create_passkeys_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
* The table `laravel/passkeys` reads and writes. The package only publishes its
* migration, so the module ships its own copy rather than asking every install to
* publish it.
*/
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('passkeys', function (Blueprint $table) {
$table->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');
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -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' => [],
];

Expand Down
17 changes: 17 additions & 0 deletions lang/en/auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.',

Check warning on line 37 in lang/en/auth.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 157 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_auth&issues=AaGJhKPhOI6mDQYyfE1I&open=AaGJhKPhOI6mDQYyfE1I&pullRequest=64
'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.',

Check warning on line 45 in lang/en/auth.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 132 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_auth&issues=AaGD-vaaenZt-0YAtjOJ&open=AaGD-vaaenZt-0YAtjOJ&pullRequest=64
'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.',
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
"name": "@saucebase/auth",
"private": true,
"type": "module",
"dependencies": {
"@laravel/passkeys": "^0.4.0"
},
"devDependencies": {
"@faker-js/faker": "^10.6.0"
}
Expand Down
12 changes: 10 additions & 2 deletions patches/user.patch
Original file line number Diff line number Diff line change
@@ -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;

69 changes: 58 additions & 11 deletions resources/boost/skills/saucebase-auth-development/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,44 +7,44 @@ 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

Pages, layouts and components live under `resources/js/`. The module's `resources/js/app` entry registers its icons, actions and global components with `registerIcon()`, `registerAction()` and `registerGlobalComponent()` in `setup()`.

## 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)

**Socialite** (outside guest/auth groups): `auth.socialite.redirect` (GET), `auth.socialite.callback` (GET), `auth.socialite.disconnect` (DELETE, auth)

**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.
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand Down
Loading
Loading