From 2cb037b1149ee9ed74b4cec543e3c796601c6f0d Mon Sep 17 00:00:00 2001 From: roble Date: Mon, 16 Nov 2026 08:58:57 +0000 Subject: [PATCH 01/13] chore: alias dev as 3.10.x-dev, past the v3.9.0 release Co-Authored-By: Claude Opus 5.5 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 145857d..3a9973a 100644 --- a/composer.json +++ b/composer.json @@ -24,7 +24,7 @@ "aliases": {} }, "branch-alias": { - "dev-dev": "3.9.x-dev" + "dev-dev": "3.10.x-dev" } }, "autoload": { From f65164d548941c72ab3efaa42b21193d5035732d Mon Sep 17 00:00:00 2001 From: roble Date: Mon, 16 Nov 2026 11:35:21 +0000 Subject: [PATCH 02/13] chore: name the demo's admin account for the installer Co-Authored-By: Claude Opus 5.5 --- composer.json | 1 + 1 file changed, 1 insertion(+) diff --git a/composer.json b/composer.json index 3a9973a..c0ea681 100644 --- a/composer.json +++ b/composer.json @@ -12,6 +12,7 @@ ], "extra": { "saucebase": { + "demo_account": "chef@saucebase.dev (admin)", "frameworks": [ "vue", "react" From 44969195efad84c4c6d5abcdd556a761ba622507 Mon Sep 17 00:00:00 2001 From: roble Date: Mon, 16 Nov 2026 11:37:48 +0000 Subject: [PATCH 03/13] chore: alias dev as 3.x-dev, so it never falls behind a minor release Co-Authored-By: Claude Opus 5.5 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index c0ea681..8166fe9 100644 --- a/composer.json +++ b/composer.json @@ -25,7 +25,7 @@ "aliases": {} }, "branch-alias": { - "dev-dev": "3.10.x-dev" + "dev-dev": "3.x-dev" } }, "autoload": { From 4cc980f944c41882e66d45d105db40f406209fda Mon Sep 17 00:00:00 2001 From: roble Date: Mon, 16 Nov 2026 12:20:50 +0000 Subject: [PATCH 04/13] Revert "chore: name the demo's admin account for the installer" This reverts commit f65164d548941c72ab3efaa42b21193d5035732d. Demo accounts move to the seeders that create them (#[DemoAccount]). Co-Authored-By: Claude Opus 5.5 --- composer.json | 1 - 1 file changed, 1 deletion(-) diff --git a/composer.json b/composer.json index 8166fe9..221d304 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,6 @@ ], "extra": { "saucebase": { - "demo_account": "chef@saucebase.dev (admin)", "frameworks": [ "vue", "react" From 41e53437126d38c0ca546d16f2c6fb23d1b73860 Mon Sep 17 00:00:00 2001 From: roble Date: Mon, 16 Nov 2026 12:29:50 +0000 Subject: [PATCH 05/13] feat: the demo seeder declares its accounts (#[DemoAccount]) The installer and modules:seed name the featured ones; a test checks the seeder creates every account it declares. Co-Authored-By: Claude Opus 5.5 --- database/seeders/ShowcaseAuthDatabaseSeeder.php | 3 +++ tests/Feature/ShowcaseStaffTest.php | 8 ++++++++ 2 files changed, 11 insertions(+) diff --git a/database/seeders/ShowcaseAuthDatabaseSeeder.php b/database/seeders/ShowcaseAuthDatabaseSeeder.php index 39e7183..a841ba2 100644 --- a/database/seeders/ShowcaseAuthDatabaseSeeder.php +++ b/database/seeders/ShowcaseAuthDatabaseSeeder.php @@ -4,8 +4,11 @@ use App\Models\User; use Illuminate\Database\Seeder; +use Saucebase\Core\Attributes\DemoAccount; use Spatie\Permission\Models\Role; +#[DemoAccount('chef@saucebase.dev', 'admin, sees everything', featured: true)] +#[DemoAccount('support@saucebase.dev', 'support staff: users and impersonation')] class ShowcaseAuthDatabaseSeeder extends Seeder { /** diff --git a/tests/Feature/ShowcaseStaffTest.php b/tests/Feature/ShowcaseStaffTest.php index 6e17ea0..88a5335 100644 --- a/tests/Feature/ShowcaseStaffTest.php +++ b/tests/Feature/ShowcaseStaffTest.php @@ -7,6 +7,7 @@ use Illuminate\Support\Facades\Hash; use Modules\Auth\Database\Seeders\DatabaseSeeder; use Modules\Auth\Database\Seeders\ShowcaseAuthDatabaseSeeder; +use Saucebase\Core\Testing\AssertsDemoAccounts; use Tests\TestCase; /** @@ -15,6 +16,7 @@ */ class ShowcaseStaffTest extends TestCase { + use AssertsDemoAccounts; use RefreshDatabase; public function test_the_demo_adds_a_staff_account_for_this_module_only(): void @@ -42,4 +44,10 @@ public function test_demo_accounts_use_the_configured_demo_password(): void $this->assertTrue(Hash::check('not-the-old-default', User::where('email', 'support@saucebase.dev')->value('password'))); } + + /** The accounts the seeder declares (#[DemoAccount]) are the ones it creates. */ + public function test_every_declared_demo_account_is_created(): void + { + $this->assertDemoAccountsSeeded(ShowcaseAuthDatabaseSeeder::class); + } } From fd12f79af6e2f58a933c0934cf9138c91e429f61 Mon Sep 17 00:00:00 2001 From: roble Date: Thu, 19 Nov 2026 09:11:05 +0000 Subject: [PATCH 06/13] fix: a failed social sign-in sends the guest back to login, not a 500 The guest branch of the callback caught only SocialiteException, so a cancelled authorisation or a stale state (InvalidStateException) or a provider error was a 500. It now reports it and returns to login with the generic error, as the linking branch already did. Co-Authored-By: Claude Opus 5.5 --- src/Http/Controllers/SocialiteController.php | 6 ++++++ tests/Feature/SocialiteCallbackTest.php | 14 ++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/Http/Controllers/SocialiteController.php b/src/Http/Controllers/SocialiteController.php index 8fa9035..0fde131 100644 --- a/src/Http/Controllers/SocialiteController.php +++ b/src/Http/Controllers/SocialiteController.php @@ -46,6 +46,12 @@ public function callback(Request $request, string $provider): RedirectResponse } catch (SocialiteException $e) { Toast::error($e->getMessage()); + return redirect()->route('login'); + } catch (\Exception $e) { + // A cancelled sign-in, a stale state or the provider failing: as in the linking flow above. + Toast::error(trans('auth::socialite.error')); + report($e); + return redirect()->route('login'); } diff --git a/tests/Feature/SocialiteCallbackTest.php b/tests/Feature/SocialiteCallbackTest.php index d596d63..a4f8f81 100644 --- a/tests/Feature/SocialiteCallbackTest.php +++ b/tests/Feature/SocialiteCallbackTest.php @@ -12,6 +12,7 @@ use Illuminate\Support\Facades\Notification; use Laravel\Socialite\Facades\Socialite; use Laravel\Socialite\Two\AbstractProvider; +use Laravel\Socialite\Two\InvalidStateException; use Laravel\Socialite\Two\User as SocialiteUser; use Mockery\MockInterface; use Modules\Auth\Models\SocialAccount; @@ -62,6 +63,19 @@ private function mockSocialiteDriver(SocialiteUser $socialiteUser): void ); } + /** A cancelled sign-in or a stale state comes back as an error from Socialite: the guest is told, not shown a 500. */ + public function test_a_failed_provider_callback_sends_the_guest_back_to_login(): void + { + $this->enableGithub(); + Socialite::shouldReceive('driver')->with('github')->andReturn( + \Mockery::mock(AbstractProvider::class, fn (MockInterface $mock) => $mock->shouldReceive('user')->andThrow(new InvalidStateException)), + ); + + $this->get(route('auth.socialite.callback', ['provider' => 'github']))->assertRedirect(route('login')); + + $this->assertGuest(); + } + public function test_social_callback_does_not_create_user_when_registration_is_disabled(): void { $settings = $this->enableGithub(); From d54935b01f6c4a9018795f1b38aa9a358b9221ce Mon Sep 17 00:00:00 2001 From: roble Date: Thu, 19 Nov 2026 12:34:22 +0000 Subject: [PATCH 07/13] fix: a magic link takes over an unverified account for the inbox owner Pre-hijack: anyone can register someone else's address with their own password. The link proves the inbox, so a magic sign-in to an unverified account verifies it and clears its password and remember token (as Better Auth's fix for CVE-2026-67327). Changing a user's email voids their outstanding links, so an old link can never verify an address it never reached. Co-Authored-By: Claude Opus 5.5 --- src/Http/Controllers/MagicLinkController.php | 11 +++++ src/Providers/AuthServiceProvider.php | 9 ++++ tests/Feature/MagicLinkTest.php | 51 ++++++++++++++++++++ 3 files changed, 71 insertions(+) diff --git a/src/Http/Controllers/MagicLinkController.php b/src/Http/Controllers/MagicLinkController.php index fe91e00..ce29f8c 100644 --- a/src/Http/Controllers/MagicLinkController.php +++ b/src/Http/Controllers/MagicLinkController.php @@ -101,6 +101,17 @@ public function authenticate(Request $request, string $token): \Symfony\Componen return redirect()->route('login')->with('error', __('auth::auth.magic-link-expired')); } + // The link proves the inbox. An unverified account may have been registered by someone + // else with this address (pre-hijack): it becomes the inbox owner's, and nothing set + // before that proof still opens it. Their other sessions end with sc-714. + if ($user->email_verified_at === null) { + $user->forceFill([ + 'email_verified_at' => now(), + 'password' => null, + 'remember_token' => Str::random(60), + ])->save(); + } + $this->signIn($request, $user); $intended = $request->query('intended'); diff --git a/src/Providers/AuthServiceProvider.php b/src/Providers/AuthServiceProvider.php index 58f33fb..26144c1 100644 --- a/src/Providers/AuthServiceProvider.php +++ b/src/Providers/AuthServiceProvider.php @@ -11,6 +11,7 @@ use Illuminate\Support\Facades\RateLimiter; use Inertia\Inertia; use Laravel\Passkeys\Passkeys; +use Modules\Auth\Models\MagicLinkToken; use Modules\Auth\Policies\UserPolicy; use Modules\Auth\Services\SocialiteService; use Modules\Auth\Settings\AuthSettings; @@ -37,6 +38,14 @@ public function boot(): void Gate::policy(User::class, UserPolicy::class); + // A magic link proves the inbox it was sent to. A new address voids the old links, + // or one would sign in (and verify) an address it never reached. Every writer counts. + User::updated(function (User $user): void { + if ($user->wasChanged('email')) { + MagicLinkToken::query()->where('user_id', $user->getKey())->delete(); + } + }); + // `throttle:passkeys`: its own counter, so a sign-in (two requests) does not // share the per-address budget of password and magic-link sign-in. Keyed by // user, falling back to the address for guests. diff --git a/tests/Feature/MagicLinkTest.php b/tests/Feature/MagicLinkTest.php index 2a5c0ad..0f64a41 100644 --- a/tests/Feature/MagicLinkTest.php +++ b/tests/Feature/MagicLinkTest.php @@ -2,6 +2,7 @@ namespace Modules\Auth\Tests\Feature; +use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Str; @@ -93,6 +94,56 @@ public function test_user_can_authenticate_with_valid_token(): void $response->assertRedirect(route('dashboard')); } + /** + * Pre-hijack: anyone can register someone else's address with a password of their own. + * The link proves the inbox, so the account is the inbox owner's: verified, and nothing + * set before that proof (the password, remember-me) still opens it. + */ + public function test_a_magic_link_to_an_unverified_account_verifies_it_and_drops_its_password(): void + { + $user = User::factory()->unverified()->create(['password' => bcrypt('attackers-password')]); + $rememberToken = $user->remember_token; + $plainToken = Str::random(64); + MagicLinkToken::create(['user_id' => $user->id, 'token' => hash('sha256', $plainToken), 'expires_at' => now()->addMinutes(15)]); + + $this->get(route('magic-link.authenticate', $plainToken)); + + $user->refresh(); + $this->assertAuthenticatedAs($user); + $this->assertNotNull($user->email_verified_at); + $this->assertNull($user->password); + $this->assertNotSame($rememberToken, $user->remember_token); + } + + /** + * A link proves the inbox it was sent to. Once the address changes, an older link would + * vouch for the new one (and verify it), so changing the email voids outstanding links. + */ + public function test_changing_the_email_voids_outstanding_magic_links(): void + { + $user = User::factory()->create(); + $plainToken = Str::random(64); + MagicLinkToken::create(['user_id' => $user->id, 'token' => hash('sha256', $plainToken), 'expires_at' => now()->addMinutes(15)]); + + $user->forceFill(['email' => 'victim@example.com', 'email_verified_at' => null])->save(); + $this->get(route('magic-link.authenticate', $plainToken)); + + $this->assertGuest(); + $this->assertNull($user->fresh()->email_verified_at); + } + + /** A verified account's own password stays: it was set by the inbox owner. */ + public function test_a_magic_link_keeps_a_verified_accounts_password(): void + { + $user = User::factory()->create(['password' => bcrypt('my-password')]); + $plainToken = Str::random(64); + MagicLinkToken::create(['user_id' => $user->id, 'token' => hash('sha256', $plainToken), 'expires_at' => now()->addMinutes(15)]); + + $this->get(route('magic-link.authenticate', $plainToken)); + + $this->assertTrue(password_verify('my-password', $user->fresh()->password)); + } + public function test_returning_user_receives_login_notification_after_magic_link_authentication(): void { Notification::fake(); From 3f2b2051c9820cdf809a4e280997fcc8cf9c574a Mon Sep 17 00:00:00 2001 From: roble Date: Thu, 19 Nov 2026 12:34:22 +0000 Subject: [PATCH 08/13] feat: an invitation lets its address sign up while sign-up is closed With core's RegistrationInvite holding an address, the register routes open, the page passes by_invitation to the form (email fixed, social providers hidden; modal too), any other address is refused while sign-up is closed, and the account starts verified. Requires core ^3.1. Co-Authored-By: Claude Opus 5.5 --- composer.json | 2 +- .../saucebase-auth-development/SKILL.md | 3 + .../js/react/components/RegisterForm.tsx | 22 ++++++- resources/js/react/pages/Register.tsx | 9 ++- resources/js/vue/components/RegisterForm.vue | 18 +++++- resources/js/vue/pages/Register.vue | 8 ++- src/Http/Controllers/RegisterController.php | 13 ++++- .../Middleware/EnsureRegistrationEnabled.php | 4 +- src/Http/Requests/RegisterRequest.php | 9 ++- tests/Feature/RegisterTest.php | 57 +++++++++++++++++++ 10 files changed, 130 insertions(+), 15 deletions(-) diff --git a/composer.json b/composer.json index 221d304..bb0a27e 100644 --- a/composer.json +++ b/composer.json @@ -40,7 +40,7 @@ } }, "require": { - "saucebase/core": "^3.0", + "saucebase/core": "^3.1", "laravel/socialite": "^5.31", "stechstudio/filament-impersonate": "^5.6.1", "laravel/passkeys": "^0.2.1" diff --git a/resources/boost/skills/saucebase-auth-development/SKILL.md b/resources/boost/skills/saucebase-auth-development/SKILL.md index 27625db..64273fa 100644 --- a/resources/boost/skills/saucebase-auth-development/SKILL.md +++ b/resources/boost/skills/saucebase-auth-development/SKILL.md @@ -152,6 +152,8 @@ Uses `stechstudio/filament-impersonate`. Session stores history at `impersonatio `MagicLinkController::authenticate()` hashes the incoming token and consumes it in one atomic `UPDATE` (unused and unexpired only), so a link works once even under concurrent clicks, then logs in the user and redirects to the intended URL or home. +The link proves the inbox, so a magic sign-in to an **unverified** account marks it verified and clears its password and remember token. Anyone can register someone else's address with a password of their own (pre-hijack), and that password must not outlive the owner's proof. A verified account keeps its password. The attacker's open sessions end only once sc-714 adds `AuthenticateSession`. Changing a user's email (any writer: `User::updated` in `AuthServiceProvider`) deletes their outstanding magic links, since a link proves only the inbox it reached. + `AuthSettings` is auto-discovered from `src/Settings`, with defaults installed from `database/settings`. Magic links are disabled by default, with a 15-minute expiry once switched on. Administrators manage both values through the `AuthenticationSettings` @@ -245,3 +247,4 @@ npx playwright test --project="@auth*" # E2E - Magic link authenticate route is outside both guest and auth middleware groups (link is clicked from email client) - `modal_enabled` is presentation only. Turning it off does not change what the routes do, only how they are reached — the canonical URLs work either way, which is why there is no separate modal route. - `registration_enabled` closes both signup paths: `EnsureRegistrationEnabled` 404s the register routes, and `SocialiteService::handleCallback()` throws `registrationDisabled()` rather than creating a new user (existing users still sign in). Login is deliberately not toggleable — disabling it would lock out admins. +- **An invitation opens closed sign-up for one address.** Core's `RegistrationInvite` (session) is set by the inviting module (tenancy's invitation page). While it holds an address, `EnsureRegistrationEnabled` lets the register routes through, the page gets `by_invitation: {email}` and passes it to `RegisterForm` as `invitedEmail` (a modal's props are not `usePage()`'s; email fixed, providers hidden), `RegisterRequest` refuses any other address while sign-up is closed, and the account starts verified (the invitation reached that inbox). Registering forgets it. Social sign-up for invitees is not covered (`registrationDisabled()` still applies). diff --git a/resources/js/react/components/RegisterForm.tsx b/resources/js/react/components/RegisterForm.tsx index 57ba6e2..80a9f5d 100644 --- a/resources/js/react/components/RegisterForm.tsx +++ b/resources/js/react/components/RegisterForm.tsx @@ -21,14 +21,19 @@ interface RegisterFormProps { * modal sitting on top of wherever the visitor just landed. */ modal?: boolean; + /** Arrived from an invitation: the account is for this address, fixed. */ + invitedEmail?: string; } -export default function RegisterForm({ modal }: RegisterFormProps) { +export default function RegisterForm({ + modal, + invitedEmail, +}: RegisterFormProps) { const t = useT(); const [showPassword, setShowPassword] = useState(false); const { data, setData, post, processing, errors } = useForm({ name: '', - email: '', + email: invitedEmail ?? '', password: '', password_confirmation: '', terms: false, @@ -58,7 +63,17 @@ export default function RegisterForm({ modal }: RegisterFormProps) { return ( <> - + {/* An invitation is for its address; a provider could sign up another one. */} + {invitedEmail ? ( +

+ {t('You were invited as :email.', { email: invitedEmail })} +

+ ) : ( + + )}
setData('email', e.target.value)} /> diff --git a/resources/js/react/pages/Register.tsx b/resources/js/react/pages/Register.tsx index b79d377..e2ee1d8 100644 --- a/resources/js/react/pages/Register.tsx +++ b/resources/js/react/pages/Register.tsx @@ -6,10 +6,13 @@ import AuthCardLayout from '../layouts/AuthCardLayout'; interface RegisterProps { modal?: boolean; + /** Reached from an invitation: the address the account is for. */ + by_invitation?: { email: string } | null; } /** Registration, as a page or a modal. See `Login.tsx` for the reasoning. */ -export default function Register({ modal }: RegisterProps) { +export default function Register({ modal, by_invitation }: RegisterProps) { + const invitedEmail = by_invitation?.email; const t = useT(); const settings = useSettings(); @@ -21,7 +24,7 @@ export default function Register({ modal }: RegisterProps) { app: settings.general.site_name, })} > - + ); } @@ -40,7 +43,7 @@ export default function Register({ modal }: RegisterProps) {

- + ); diff --git a/resources/js/vue/components/RegisterForm.vue b/resources/js/vue/components/RegisterForm.vue index 2137633..4e44cdd 100644 --- a/resources/js/vue/components/RegisterForm.vue +++ b/resources/js/vue/components/RegisterForm.vue @@ -15,6 +15,8 @@ const props = defineProps<{ * of this form — see `AuthLink`. */ modal?: boolean; + /** Arrived from an invitation: the account is for this address, fixed. */ + invitedEmail?: string; }>(); const currentModal = useModal(); @@ -32,8 +34,10 @@ function handleSuccess(): void { const page = usePage(); const termsError = computed(() => page.props.errors?.terms); +const invitedEmail = computed(() => props.invitedEmail); + const nameRef = ref(''); -const emailRef = ref(''); +const emailRef = ref(invitedEmail.value ?? ''); const passwordRef = ref(''); const termsRef = ref(false); @@ -47,7 +51,16 @@ const canSubmit = computed( diff --git a/src/Http/Controllers/RegisterController.php b/src/Http/Controllers/RegisterController.php index d51e0a7..80cc1c3 100644 --- a/src/Http/Controllers/RegisterController.php +++ b/src/Http/Controllers/RegisterController.php @@ -11,6 +11,7 @@ use InertiaUI\Modal\Modal; use Modules\Auth\Http\Requests\RegisterRequest; use Saucebase\Core\Facades\Home; +use Saucebase\Core\RegistrationInvite; use Saucebase\Core\Toast; class RegisterController extends Controller @@ -20,7 +21,11 @@ class RegisterController extends Controller */ public function create(): Response|Modal { - return $this->pageOrModal('Auth::Register'); + $invited = RegistrationInvite::email(); + + return $this->pageOrModal('Auth::Register', [ + 'by_invitation' => $invited === null ? null : ['email' => $invited], + ]); } /** @@ -33,6 +38,12 @@ public function store(RegisterRequest $request): RedirectResponse $data = $request->only(['name', 'email', 'password']); $user = User::create($data); + // The invitation reached this inbox: the address is proven, and the invite is used up. + if (RegistrationInvite::allows($user->email)) { + $user->forceFill(['email_verified_at' => now()])->save(); + RegistrationInvite::forget(); + } + event(new Registered($user)); Auth::login($user); diff --git a/src/Http/Middleware/EnsureRegistrationEnabled.php b/src/Http/Middleware/EnsureRegistrationEnabled.php index a8155d6..e82b463 100644 --- a/src/Http/Middleware/EnsureRegistrationEnabled.php +++ b/src/Http/Middleware/EnsureRegistrationEnabled.php @@ -5,6 +5,7 @@ use Closure; use Illuminate\Http\Request; use Modules\Auth\Settings\AuthSettings; +use Saucebase\Core\RegistrationInvite; class EnsureRegistrationEnabled { @@ -12,7 +13,8 @@ public function __construct(private readonly AuthSettings $settings) {} public function handle(Request $request, Closure $next): mixed { - abort_unless($this->settings->registration_enabled, 404); + // Closed sign-up still lets an invited address in; RegisterRequest holds it to that address. + abort_unless($this->settings->registration_enabled || RegistrationInvite::email() !== null, 404); return $next($request); } diff --git a/src/Http/Requests/RegisterRequest.php b/src/Http/Requests/RegisterRequest.php index 21efbdb..13eed3b 100644 --- a/src/Http/Requests/RegisterRequest.php +++ b/src/Http/Requests/RegisterRequest.php @@ -7,6 +7,8 @@ use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\Rules; +use Modules\Auth\Settings\AuthSettings; +use Saucebase\Core\RegistrationInvite; class RegisterRequest extends FormRequest { @@ -27,7 +29,12 @@ public function rules(): array { return [ 'name' => 'required|string|max:255', - 'email' => 'required|string|email|max:255|unique:'.User::class, + 'email' => ['required', 'string', 'email', 'max:255', 'unique:'.User::class, function (string $attribute, string $email, \Closure $fail): void { + // Sign-up is closed: only the address the invitation was sent to. + if (! app(AuthSettings::class)->registration_enabled && ! RegistrationInvite::allows($email)) { + $fail(__('Use the address the invitation was sent to.')); + } + }], 'password' => ['required', Rules\Password::defaults()], 'terms' => ['accepted'], ]; diff --git a/tests/Feature/RegisterTest.php b/tests/Feature/RegisterTest.php index f49b10b..6035698 100644 --- a/tests/Feature/RegisterTest.php +++ b/tests/Feature/RegisterTest.php @@ -9,6 +9,7 @@ use Modules\Auth\Notifications\LoginNotification; use Modules\Auth\Notifications\WelcomeNotification; use Modules\Auth\Settings\AuthSettings; +use Saucebase\Core\RegistrationInvite; use Tests\TestCase; class RegisterTest extends TestCase @@ -44,6 +45,62 @@ public function test_user_cannot_register_when_registration_is_disabled(): void $this->assertDatabaseMissing('users', ['email' => 'test@example.com']); } + // ── Invited while sign-up is closed (RegistrationInvite, set by e.g. tenancy) ── + + /** @return array */ + private function signUp(string $email): array + { + return ['name' => 'Ana', 'email' => $email, 'password' => 'password123', 'terms' => true]; + } + + public function test_an_invited_guest_reaches_the_closed_register_page_with_their_address(): void + { + $this->disableRegistration(); + + $this->withSession(['saucebase.registration_invite' => 'ana@example.com']) + ->get(route('register')) + ->assertOk() + ->assertInertia(fn ($page) => $page->where('by_invitation.email', 'ana@example.com')); + } + + /** The invitation came to that inbox, so the account starts verified and the invite is used up. */ + public function test_an_invited_guest_registers_their_address_verified(): void + { + $this->disableRegistration(); + RegistrationInvite::allow('ana@example.com'); + + $this->post(route('register'), $this->signUp('Ana@example.com'))->assertRedirect(); + + $this->assertNotNull(User::where('email', 'ana@example.com')->sole()->email_verified_at); + $this->assertNull(RegistrationInvite::email()); + } + + /** An invitation for one address opens sign-up for that address only. */ + public function test_an_invited_guest_cannot_register_another_address(): void + { + $this->disableRegistration(); + RegistrationInvite::allow('ana@example.com'); + + $this->post(route('register'), $this->signUp('someone@else.com'))->assertInvalid('email'); + + $this->assertDatabaseMissing('users', ['email' => 'someone@else.com']); + } + + /** With sign-up open, an invited address still starts verified; anyone else signs up as usual. */ + public function test_with_sign_up_open_only_the_invited_address_starts_verified(): void + { + RegistrationInvite::allow('ana@example.com'); + + $this->post(route('register'), $this->signUp('bob@example.com'))->assertRedirect(); + + $this->assertNull(User::where('email', 'bob@example.com')->sole()->email_verified_at); + } + + public function test_the_register_page_has_no_invitation_without_one(): void + { + $this->get(route('register'))->assertInertia(fn ($page) => $page->where('by_invitation', null)); + } + private function disableRegistration(): void { $settings = app(AuthSettings::class); From 40028eeef91e8878be995cffa5e9047e1322d3f2 Mon Sep 17 00:00:00 2001 From: roble Date: Thu, 19 Nov 2026 21:34:00 +0000 Subject: [PATCH 09/13] fix: a user without a password can set one Co-Authored-By: Claude Opus 5.5 --- .../saucebase-auth-development/SKILL.md | 2 +- resources/js/react/pages/SettingsSecurity.tsx | 29 +++++++++---- resources/js/vue/pages/SettingsSecurity.vue | 16 +++++++- src/Http/Requests/UpdatePasswordRequest.php | 10 ++++- tests/Feature/PasswordUpdateTest.php | 41 +++++++++++++++++++ 5 files changed, 84 insertions(+), 14 deletions(-) diff --git a/resources/boost/skills/saucebase-auth-development/SKILL.md b/resources/boost/skills/saucebase-auth-development/SKILL.md index 64273fa..8db9e41 100644 --- a/resources/boost/skills/saucebase-auth-development/SKILL.md +++ b/resources/boost/skills/saucebase-auth-development/SKILL.md @@ -238,7 +238,7 @@ npx playwright test --project="@auth*" # E2E ## Gotchas - `LoginRequest::validateCredentials()` validates without logging in — the controller handles `Auth::login()` separately -- Social sign-ups get **no** password (`users.password` is nullable), so `disconnectProvider()` refuses to remove their only provider until they add one; a made-up password let them lock themselves out (sc-1132). They are **not** marked verified: signing in with a provider is not proof of the address, and nobody has confirmed it (sc-713) +- Social sign-ups get **no** password (`users.password` is nullable), so `disconnectProvider()` refuses to remove their only provider until they add one (the Security panel's password form asks for no current password while `has_password` is false, and `UpdatePasswordRequest` excludes it); a made-up password let them lock themselves out (sc-1132). They are **not** marked verified: signing in with a provider is not proof of the address, and nobody has confirmed it (sc-713) - `SocialAccount::provider_token` and `provider_refresh_token` are cast `encrypted` and `$hidden`: they let the app act on the provider as the user. `1000_00_00_000007` encrypts rows stored before the cast (sc-1132) - A guest's social sign-in never links to an existing **unverified** account with the same email (`SocialiteException::unverifiedAccount()`): anyone can register with someone else's address, and linking would hand that account, and whoever knows its password, to the provider's owner. They sign in as before and connect the provider from Settings (sc-1130) - Socialite redirect/callback routes are outside both guest and auth middleware groups diff --git a/resources/js/react/pages/SettingsSecurity.tsx b/resources/js/react/pages/SettingsSecurity.tsx index 236730a..b847d34 100644 --- a/resources/js/react/pages/SettingsSecurity.tsx +++ b/resources/js/react/pages/SettingsSecurity.tsx @@ -499,7 +499,12 @@ export default function SettingsSecurity({ {/* Password */}
-

{t('Update Password')}

+ {/* Signed up through a provider: there is no password yet to give. */} +

+ {user.has_password + ? t('Update Password') + : t('Set a password')} +

{t( 'Ensure your account is using a long, random password to stay secure.', @@ -517,13 +522,17 @@ export default function SettingsSecurity({ > {({ errors }) => ( <> - + {user.has_password && ( + + )} - {t('Update Password')} + {user.has_password + ? t('Update Password') + : t('Set a password')}

diff --git a/resources/js/vue/pages/SettingsSecurity.vue b/resources/js/vue/pages/SettingsSecurity.vue index eb655c7..f383dd4 100644 --- a/resources/js/vue/pages/SettingsSecurity.vue +++ b/resources/js/vue/pages/SettingsSecurity.vue @@ -444,7 +444,14 @@ const initiateDisconnect = async (provider: string) => {
-

{{ $t('Update Password') }}

+ +

+ {{ + props.user.has_password + ? $t('Update Password') + : $t('Set a password') + }} +

{{ $t( @@ -463,6 +470,7 @@ const initiateDisconnect = async (provider: string) => { :reset-on-success="true" > {

diff --git a/src/Http/Requests/UpdatePasswordRequest.php b/src/Http/Requests/UpdatePasswordRequest.php index 2fb5a2b..46b6ff9 100644 --- a/src/Http/Requests/UpdatePasswordRequest.php +++ b/src/Http/Requests/UpdatePasswordRequest.php @@ -5,15 +5,20 @@ use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rules\Password; +use STS\FilamentImpersonate\ImpersonateManager; class UpdatePasswordRequest extends FormRequest { /** * Determine if the user is authorized to make this request. */ + /** + * A first password is refused while impersonating, as adding a passkey is: it would + * outlive the impersonation as a way back into the account. + */ public function authorize(): bool { - return true; + return $this->user()?->getAuthPassword() || ! app(ImpersonateManager::class)->isImpersonating(); } /** @@ -24,7 +29,8 @@ public function authorize(): bool public function rules(): array { return [ - 'current_password' => ['required', 'current_password'], + // A user who signed up through a provider has none to give, so none is asked. + 'current_password' => $this->user()?->getAuthPassword() ? ['required', 'current_password'] : ['exclude'], 'password' => ['required', Password::defaults(), 'confirmed'], ]; } diff --git a/tests/Feature/PasswordUpdateTest.php b/tests/Feature/PasswordUpdateTest.php index ffb4270..5eebfac 100644 --- a/tests/Feature/PasswordUpdateTest.php +++ b/tests/Feature/PasswordUpdateTest.php @@ -6,6 +6,7 @@ use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Notification; use Modules\Auth\Notifications\PasswordChangedNotification; +use STS\FilamentImpersonate\ImpersonateManager; use Tests\TestCase; class PasswordUpdateTest extends TestCase @@ -28,6 +29,46 @@ public function test_user_can_update_password_with_correct_current_password(): v $this->assertTrue(Hash::check('newpassword123', $user->fresh()->getAuthPassword())); } + /** Signed up through a provider: there is no current password to give, so none is asked. */ + public function test_a_user_without_a_password_can_set_one(): void + { + Notification::fake(); + $user = $this->createUser(); + $user->forceFill(['password' => null])->save(); + + $this->actingAs($user)->put(route('settings.profile.password.update'), [ + 'password' => 'newpassword123', + 'password_confirmation' => 'newpassword123', + ])->assertSessionHasNoErrors(); + + $this->assertTrue(Hash::check('newpassword123', $user->fresh()->getAuthPassword())); + } + + /** Like adding a passkey: a password set while impersonating would outlive the impersonation. */ + public function test_a_first_password_cannot_be_set_while_impersonating(): void + { + $user = $this->createUser(); + $user->forceFill(['password' => null])->save(); + + $this->actingAs($user) + ->withSession([ImpersonateManager::SESSION_KEY => $this->createUser()->id]) + ->put(route('settings.profile.password.update'), ['password' => 'newpassword123', 'password_confirmation' => 'newpassword123']) + ->assertForbidden(); + + $this->assertNull($user->fresh()->password); + } + + /** Having one, it is still the proof asked for. */ + public function test_a_user_with_a_password_must_give_it(): void + { + $user = $this->createUser(); + + $this->actingAs($user)->put(route('settings.profile.password.update'), [ + 'password' => 'newpassword123', + 'password_confirmation' => 'newpassword123', + ])->assertSessionHasErrors('current_password'); + } + public function test_password_changed_notification_is_sent(): void { Notification::fake(); From 3ccf3a79b0f7b10e20379a09a6abe301bfb9e7ac Mon Sep 17 00:00:00 2001 From: roble Date: Fri, 20 Nov 2026 21:06:19 +0000 Subject: [PATCH 10/13] fix: a magic link's proof drops providers and passkeys set before it `verified` lets an unverified user through, so whoever registered someone else's address could connect a provider or add a passkey; both outlived the owner's proof. Cleared with the password, in one transaction. Co-Authored-By: Claude Opus 5.5 --- .../skills/saucebase-auth-development/SKILL.md | 4 +++- src/Http/Controllers/MagicLinkController.php | 18 ++++++++++++------ tests/Feature/MagicLinkTest.php | 18 ++++++++++++++++++ 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/resources/boost/skills/saucebase-auth-development/SKILL.md b/resources/boost/skills/saucebase-auth-development/SKILL.md index 8db9e41..29ce18c 100644 --- a/resources/boost/skills/saucebase-auth-development/SKILL.md +++ b/resources/boost/skills/saucebase-auth-development/SKILL.md @@ -152,7 +152,9 @@ Uses `stechstudio/filament-impersonate`. Session stores history at `impersonatio `MagicLinkController::authenticate()` hashes the incoming token and consumes it in one atomic `UPDATE` (unused and unexpired only), so a link works once even under concurrent clicks, then logs in the user and redirects to the intended URL or home. -The link proves the inbox, so a magic sign-in to an **unverified** account marks it verified and clears its password and remember token. Anyone can register someone else's address with a password of their own (pre-hijack), and that password must not outlive the owner's proof. A verified account keeps its password. The attacker's open sessions end only once sc-714 adds `AuthenticateSession`. Changing a user's email (any writer: `User::updated` in `AuthServiceProvider`) deletes their outstanding magic links, since a link proves only the inbox it reached. +The link proves the inbox, so a magic sign-in to an **unverified** account marks it verified and clears, in one transaction, its password, remember token, connected providers and passkeys. Anyone can register someone else's address with a password of their own (pre-hijack) and, since `verified` lets an unverified user through, connect a provider or add a passkey too: none of it may outlive the owner's proof. A genuine social sign-up is unverified too (sc-713), so it loses its provider link at that proof and reconnects from Settings. A verified account keeps all of them. The attacker's open sessions end only once sc-714 adds `AuthenticateSession`. + +Changing a user's email through an Eloquent save deletes their outstanding magic links (`User::updated` in `AuthServiceProvider`), since a link proves only the inbox it reached. Query-builder and mass updates fire no model events and leave the links valid: such a write must delete the user's `MagicLinkToken` rows itself. `ProfileController::updateInfo()` saves the address, voids the links and drops the verification in one transaction. `AuthSettings` is auto-discovered from `src/Settings`, with defaults installed from `database/settings`. Magic links are disabled by default, with a 15-minute diff --git a/src/Http/Controllers/MagicLinkController.php b/src/Http/Controllers/MagicLinkController.php index ce29f8c..c282e46 100644 --- a/src/Http/Controllers/MagicLinkController.php +++ b/src/Http/Controllers/MagicLinkController.php @@ -7,6 +7,7 @@ use Illuminate\Http\Request; use Illuminate\Routing\Controllers\HasMiddleware; use Illuminate\Routing\Controllers\Middleware; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use Inertia\Inertia; use Inertia\Response; @@ -103,13 +104,18 @@ public function authenticate(Request $request, string $token): \Symfony\Componen // The link proves the inbox. An unverified account may have been registered by someone // else with this address (pre-hijack): it becomes the inbox owner's, and nothing set - // before that proof still opens it. Their other sessions end with sc-714. + // before that proof still opens it: password, remember-me, a connected provider or a + // passkey (`verified` lets an unverified user add both). Their other sessions end with sc-714. if ($user->email_verified_at === null) { - $user->forceFill([ - 'email_verified_at' => now(), - 'password' => null, - 'remember_token' => Str::random(60), - ])->save(); + DB::transaction(function () use ($user): void { + $user->forceFill([ + 'email_verified_at' => now(), + 'password' => null, + 'remember_token' => Str::random(60), + ])->save(); + $user->socialAccounts()->delete(); + $user->passkeys()->delete(); + }); } $this->signIn($request, $user); diff --git a/tests/Feature/MagicLinkTest.php b/tests/Feature/MagicLinkTest.php index 0f64a41..f3c3ede 100644 --- a/tests/Feature/MagicLinkTest.php +++ b/tests/Feature/MagicLinkTest.php @@ -115,6 +115,24 @@ public function test_a_magic_link_to_an_unverified_account_verifies_it_and_drops $this->assertNotSame($rememberToken, $user->remember_token); } + /** + * Before the proof, whoever registered the address could also connect their own provider + * account or add a passkey (`verified` lets an unverified user through): neither outlives it. + */ + public function test_a_magic_link_to_an_unverified_account_drops_its_providers_and_passkeys(): void + { + $user = User::factory()->unverified()->create(); + $user->socialAccounts()->create(['provider' => 'github', 'provider_id' => 'attackers-github']); + $user->passkeys()->create(['name' => 'Attacker', 'credential_id' => 'abc', 'credential' => []]); + $plainToken = Str::random(64); + MagicLinkToken::create(['user_id' => $user->id, 'token' => hash('sha256', $plainToken), 'expires_at' => now()->addMinutes(15)]); + + $this->get(route('magic-link.authenticate', $plainToken)); + + $this->assertSame(0, $user->socialAccounts()->count()); + $this->assertSame(0, $user->passkeys()->count()); + } + /** * A link proves the inbox it was sent to. Once the address changes, an older link would * vouch for the new one (and verify it), so changing the email voids outstanding links. From b83875b94f68b2edfd1da08c12591e4a3d6351b6 Mon Sep 17 00:00:00 2001 From: roble Date: Fri, 20 Nov 2026 21:06:19 +0000 Subject: [PATCH 11/13] fix: a malformed sign-up email is a validation error, not a 500 Co-Authored-By: Claude Opus 5.5 --- src/Http/Requests/RegisterRequest.php | 3 ++- tests/Feature/RegisterTest.php | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/Http/Requests/RegisterRequest.php b/src/Http/Requests/RegisterRequest.php index 13eed3b..53fce55 100644 --- a/src/Http/Requests/RegisterRequest.php +++ b/src/Http/Requests/RegisterRequest.php @@ -29,7 +29,8 @@ public function rules(): array { return [ 'name' => 'required|string|max:255', - 'email' => ['required', 'string', 'email', 'max:255', 'unique:'.User::class, function (string $attribute, string $email, \Closure $fail): void { + // bail: the invitation check below takes a string. + 'email' => ['bail', 'required', 'string', 'email', 'max:255', 'unique:'.User::class, function (string $attribute, string $email, \Closure $fail): void { // Sign-up is closed: only the address the invitation was sent to. if (! app(AuthSettings::class)->registration_enabled && ! RegistrationInvite::allows($email)) { $fail(__('Use the address the invitation was sent to.')); diff --git a/tests/Feature/RegisterTest.php b/tests/Feature/RegisterTest.php index 6035698..79f7a9e 100644 --- a/tests/Feature/RegisterTest.php +++ b/tests/Feature/RegisterTest.php @@ -48,6 +48,15 @@ public function test_user_cannot_register_when_registration_is_disabled(): void // ── Invited while sign-up is closed (RegistrationInvite, set by e.g. tenancy) ── /** @return array */ + /** A malformed address is a validation error, not a 500 from the invitation check. */ + public function test_an_email_that_is_not_a_string_is_a_validation_error(): void + { + $this->post(route('register'), [...$this->signUp(''), 'email' => ['ana@example.com']]) + ->assertSessionHasErrors('email'); + + $this->assertGuest(); + } + private function signUp(string $email): array { return ['name' => 'Ana', 'email' => $email, 'password' => 'password123', 'terms' => true]; From 3247bb5ecffb4cbfdd87643a2fe3cf080c3596b9 Mon Sep 17 00:00:00 2001 From: roble Date: Fri, 20 Nov 2026 21:06:19 +0000 Subject: [PATCH 12/13] fix: an email change is saved, its links voided and its verification dropped together Co-Authored-By: Claude Opus 5.5 --- src/Http/Controllers/ProfileController.php | 15 ++++++++++----- tests/Feature/ProfileTest.php | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/Http/Controllers/ProfileController.php b/src/Http/Controllers/ProfileController.php index a0db810..df3eb8c 100644 --- a/src/Http/Controllers/ProfileController.php +++ b/src/Http/Controllers/ProfileController.php @@ -3,6 +3,7 @@ namespace Modules\Auth\Http\Controllers; use Illuminate\Http\RedirectResponse; +use Illuminate\Support\Facades\DB; use Illuminate\Validation\ValidationException; use Modules\Auth\Http\Requests\UpdateProfileAvatarRequest; use Modules\Auth\Http\Requests\UpdateProfileInfoRequest; @@ -42,12 +43,16 @@ public function updateInfo(UpdateProfileInfoRequest $request): RedirectResponse ]); } - $user->update($request->validated()); + // One change: the new address, its old links voided (`User::updated`) and its + // verification dropped. A failure in any part keeps the old address as it was. + DB::transaction(function () use ($user, $request): void { + $user->update($request->validated()); - // A new address has not been confirmed, whatever the old one had earned. - if ($user->wasChanged('email')) { - $user->forceFill(['email_verified_at' => null])->save(); - } + // A new address has not been confirmed, whatever the old one had earned. + if ($user->wasChanged('email')) { + $user->forceFill(['email_verified_at' => null])->save(); + } + }); Toast::success(__('Profile updated successfully!')); diff --git a/tests/Feature/ProfileTest.php b/tests/Feature/ProfileTest.php index 1a3e927..a79ba27 100644 --- a/tests/Feature/ProfileTest.php +++ b/tests/Feature/ProfileTest.php @@ -90,6 +90,26 @@ public function test_changing_the_email_clears_the_verified_timestamp(): void $this->assertNull($user->fresh()->email_verified_at); } + /** The new address and its unverified state are one change: a failure keeps neither. */ + public function test_a_failed_email_change_keeps_the_old_address(): void + { + $user = $this->createUser(); + $user->forceFill(['email_verified_at' => now()])->save(); + $email = $user->email; + User::updated(fn () => throw new \RuntimeException('lock wait timeout')); + + $this->withoutExceptionHandling(); + try { + $this->actingAs($user)->patch(route('settings.profile.update-info'), [ + 'name' => $user->name, + 'email' => 'moved@example.com', + ]); + } catch (\RuntimeException) { + } + + $this->assertSame($email, User::find($user->id)->email); + } + public function test_keeping_the_same_email_keeps_the_verified_timestamp(): void { $user = $this->createUser(); From b9acc4c565a3b84a83a3e5ef23dfdfe18a7d2587 Mon Sep 17 00:00:00 2001 From: roble Date: Fri, 20 Nov 2026 21:16:36 +0000 Subject: [PATCH 13/13] fix: a magic link verifies nothing if the address changed while it opened Co-Authored-By: Claude Opus 5.5 --- .../saucebase-auth-development/SKILL.md | 2 +- src/Http/Controllers/MagicLinkController.php | 24 ++++++++++++++--- tests/Feature/MagicLinkTest.php | 27 +++++++++++++++++++ 3 files changed, 48 insertions(+), 5 deletions(-) diff --git a/resources/boost/skills/saucebase-auth-development/SKILL.md b/resources/boost/skills/saucebase-auth-development/SKILL.md index 29ce18c..1b59104 100644 --- a/resources/boost/skills/saucebase-auth-development/SKILL.md +++ b/resources/boost/skills/saucebase-auth-development/SKILL.md @@ -152,7 +152,7 @@ Uses `stechstudio/filament-impersonate`. Session stores history at `impersonatio `MagicLinkController::authenticate()` hashes the incoming token and consumes it in one atomic `UPDATE` (unused and unexpired only), so a link works once even under concurrent clicks, then logs in the user and redirects to the intended URL or home. -The link proves the inbox, so a magic sign-in to an **unverified** account marks it verified and clears, in one transaction, its password, remember token, connected providers and passkeys. Anyone can register someone else's address with a password of their own (pre-hijack) and, since `verified` lets an unverified user through, connect a provider or add a passkey too: none of it may outlive the owner's proof. A genuine social sign-up is unverified too (sc-713), so it loses its provider link at that proof and reconnects from Settings. A verified account keeps all of them. The attacker's open sessions end only once sc-714 adds `AuthenticateSession`. +The link proves the inbox, so a magic sign-in to an **unverified** account marks it verified and clears, in one transaction, its password, remember token, connected providers and passkeys. Anyone can register someone else's address with a password of their own (pre-hijack) and, since `verified` lets an unverified user through, connect a provider or add a passkey too: none of it may outlive the owner's proof. A genuine social sign-up is unverified too (sc-713), so it loses its provider link at that proof and reconnects from Settings. A verified account keeps all of them. The account is locked and read again for that: if its address changed, or the link was voided, since the link was opened, it verifies nothing and signs no one in. The attacker's open sessions end only once sc-714 adds `AuthenticateSession`. Changing a user's email through an Eloquent save deletes their outstanding magic links (`User::updated` in `AuthServiceProvider`), since a link proves only the inbox it reached. Query-builder and mass updates fire no model events and leave the links valid: such a write must delete the user's `MagicLinkToken` rows itself. `ProfileController::updateInfo()` saves the address, voids the links and drops the verification in one transaction. diff --git a/src/Http/Controllers/MagicLinkController.php b/src/Http/Controllers/MagicLinkController.php index c282e46..4a055f8 100644 --- a/src/Http/Controllers/MagicLinkController.php +++ b/src/Http/Controllers/MagicLinkController.php @@ -107,15 +107,31 @@ public function authenticate(Request $request, string $token): \Symfony\Componen // before that proof still opens it: password, remember-me, a connected provider or a // passkey (`verified` lets an unverified user add both). Their other sessions end with sc-714. if ($user->email_verified_at === null) { - DB::transaction(function () use ($user): void { - $user->forceFill([ + $proved = DB::transaction(function () use ($user, $record): bool { + // Read again under lock: an address changed since the link was opened is not + // the inbox it reached. A change of address voids its links as it commits. + $locked = User::lockForUpdate()->find($user->getKey()); + + if ($locked?->email !== $user->email || ! MagicLinkToken::whereKey($record->getKey())->exists()) { + return false; + } + + $locked->forceFill([ 'email_verified_at' => now(), 'password' => null, 'remember_token' => Str::random(60), ])->save(); - $user->socialAccounts()->delete(); - $user->passkeys()->delete(); + $locked->socialAccounts()->delete(); + $locked->passkeys()->delete(); + + return true; }); + + if (! $proved) { + return redirect()->route('login')->with('error', __('auth::auth.magic-link-expired')); + } + + $user->refresh(); } $this->signIn($request, $user); diff --git a/tests/Feature/MagicLinkTest.php b/tests/Feature/MagicLinkTest.php index f3c3ede..9fcd59e 100644 --- a/tests/Feature/MagicLinkTest.php +++ b/tests/Feature/MagicLinkTest.php @@ -133,6 +133,33 @@ public function test_a_magic_link_to_an_unverified_account_drops_its_providers_a $this->assertSame(0, $user->passkeys()->count()); } + /** + * The address changes while the link is being opened: the change commits after the + * account is read but before it is verified. The link reached the old inbox only, so the + * new address stays unverified and nobody is signed in. + */ + public function test_an_address_changed_while_the_link_opens_is_not_verified_by_it(): void + { + $user = User::factory()->unverified()->create(['email' => 'old@example.com']); + $plainToken = Str::random(64); + MagicLinkToken::create(['user_id' => $user->id, 'token' => hash('sha256', $plainToken), 'expires_at' => now()->addMinutes(15)]); + + $changed = false; + User::retrieved(function (User $retrieved) use (&$changed): void { + if (! $changed) { + $changed = true; + // Another request's change of address, committed: its links go with it. + User::whereKey($retrieved->id)->update(['email' => 'new@example.com']); + MagicLinkToken::where('user_id', $retrieved->id)->delete(); + } + }); + + $this->get(route('magic-link.authenticate', $plainToken))->assertRedirect(route('login')); + + $this->assertGuest(); + $this->assertNull($user->fresh()->email_verified_at); + } + /** * A link proves the inbox it was sent to. Once the address changes, an older link would * vouch for the new one (and verify it), so changing the email voids outstanding links.