diff --git a/.env.example b/.env.example index 6741b38..8714d91 100644 --- a/.env.example +++ b/.env.example @@ -4,8 +4,23 @@ APP_KEY= APP_DEBUG=true APP_URL=http://localhost:8000 -# A proxy in front of the app (tailscale serve, a load balancer), believed -# about HTTPS and the visitor's address: comma-separated addresses, or *. +# Who builds the pages: "inertia" (the React app in resources/js, served by +# Laravel) or "headless" (the TanStack Start or Nuxt kit, which passes +# everything under /backend on to Laravel from its own origin). Headless, +# Laravel renders no pages and answers JSON, and APP_URL is the frontend's +# address, such as http://localhost:3000. See docs/headless-api.md. +# APP_FRONTEND=headless + +# Where a headless frontend's pages are, for Keyring's redirects and emailed +# links. Unset, it's APP_URL, which on one origin it is. It may have a path, +# such as https://example.com/app. +# FRONTEND_URL=http://localhost:3000 + +# A proxy in front of the app (tailscale serve, a load balancer, a headless +# frontend's server), believed about HTTPS, the host, the path prefix and the +# visitor's address: comma-separated addresses, or *. Unset, headless mode +# trusts a proxy on this machine (127.0.0.1,::1) and Inertia mode none, so in +# headless mode anything on loopback that forwards to Laravel is trusted. # TRUSTED_PROXIES=127.0.0.1 APP_LOCALE=en diff --git a/README.md b/README.md index a48c7be..1a1022f 100644 --- a/README.md +++ b/README.md @@ -364,6 +364,12 @@ Each link signs the browser out first, then signs in or starts the sign in as on +## Headless frontends + +The same backend serves frontends Laravel doesn't serve, such as a TanStack Start or Nuxt app on one origin that passes everything under `/backend` on to Laravel. Set `APP_FRONTEND=headless` and `APP_URL` to the frontend's address: Laravel then renders no pages, the app's pages and Keyring's answer JSON requests with their name and props, `GET /api/me` has the shared props, and Keyring sends users to the frontend's pages. [docs/headless-api.md](docs/headless-api.md) lists the settings and every endpoint with its JSON. Inertia stays the default, and Inertia visits get what they always have. + +Headless mode needs Keyring 0.4 or later, and the headless kits `@keyringjs/keyring` 0.2 or later, neither released yet. Until they are, `composer.json` stays on Keyring `^0.3`, which runs the Inertia app but not headless mode. + ## What changed from Laravel's starter kit The app started as Laravel's React starter kit, with Fortify taken out and Keyring put in: diff --git a/app/Demo/DemoLocationController.php b/app/Demo/DemoLocationController.php index 534e324..fc8d405 100644 --- a/app/Demo/DemoLocationController.php +++ b/app/Demo/DemoLocationController.php @@ -3,9 +3,11 @@ namespace App\Demo; use App\Http\Controllers\Controller; +use App\Support\Frontend; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Validation\Rule; +use Symfony\Component\HttpFoundation\Response; class DemoLocationController extends Controller { @@ -13,9 +15,9 @@ class DemoLocationController extends Controller * The login page's "Pretend to be in" picker. It only puts this browser * somewhere else for the next sign in: what happens then is up to the * NewCountry and ImpossibleTravel signals. Only there with - * KEYRING_LOCATOR=demo. + * KEYRING_LOCATOR=demo. A JSON request gets a 204 with the cookie. */ - public function __invoke(Request $request): RedirectResponse + public function __invoke(Request $request): RedirectResponse|Response { abort_unless(DemoLocator::enabled(), 404); @@ -23,6 +25,12 @@ public function __invoke(Request $request): RedirectResponse 'place' => ['required', 'string', Rule::in(array_keys(DemoLocator::PLACES))], ])['place']; - return back()->withCookie(cookie(DemoLocator::COOKIE, $place, 60 * 24 * 30)); + $cookie = cookie(DemoLocator::COOKIE, $place, 60 * 24 * 30); + + if (Frontend::wantsJson($request)) { + return response()->noContent()->withCookie($cookie); + } + + return back()->withCookie($cookie); } } diff --git a/app/Http/Controllers/DashboardController.php b/app/Http/Controllers/DashboardController.php index 605c536..09d9ca1 100644 --- a/app/Http/Controllers/DashboardController.php +++ b/app/Http/Controllers/DashboardController.php @@ -3,15 +3,14 @@ namespace App\Http\Controllers; use App\Demo\DemoProps; // @monorepo-only -use Inertia\Inertia; -use Inertia\Response; +use App\Http\Responses\PageResponse; class DashboardController extends Controller { - public function __invoke(): Response + public function __invoke(): PageResponse { - $page = Inertia::render('dashboard'); - $page->with('demoSettings', DemoProps::settings()); // @monorepo-only + $page = new PageResponse('dashboard'); + $page = $page->with('demoSettings', DemoProps::settings()); // @monorepo-only return $page; } diff --git a/app/Http/Controllers/MeController.php b/app/Http/Controllers/MeController.php new file mode 100644 index 0000000..c67476c --- /dev/null +++ b/app/Http/Controllers/MeController.php @@ -0,0 +1,29 @@ +sharedProps($request)), headers: [ + 'Cache-Control' => 'no-store, private', + ]); + } +} diff --git a/app/Http/Controllers/Settings/ProfileController.php b/app/Http/Controllers/Settings/ProfileController.php index 6ad54c5..78792d5 100644 --- a/app/Http/Controllers/Settings/ProfileController.php +++ b/app/Http/Controllers/Settings/ProfileController.php @@ -4,24 +4,27 @@ use App\Http\Controllers\Controller; use App\Http\Requests\Settings\ProfileUpdateRequest; +use App\Http\Responses\PageResponse; +use App\Support\Frontend; use Illuminate\Contracts\Auth\MustVerifyEmail; +use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Inertia\Inertia; -use Inertia\Response; use Keyring\Changes\EmailChanges; +use Symfony\Component\HttpFoundation\Response; class ProfileController extends Controller { /** * Show the user's profile settings page. */ - public function edit(Request $request, EmailChanges $changes): Response + public function edit(Request $request, EmailChanges $changes): PageResponse { $pending = $changes->pending($request->user()); - return Inertia::render('settings/profile', [ + return new PageResponse('settings/profile', [ 'mustVerifyEmail' => $request->user() instanceof MustVerifyEmail, 'pendingEmail' => $pending === null ? null : [ 'email' => $pending->value, @@ -35,11 +38,18 @@ public function edit(Request $request, EmailChanges $changes): Response /** * Update the user's name. The email address is protected by Keyring and * changes through its confirmed flow (POST /user/email) instead. + * + * A JSON request gets the status in the body, as Keyring's own changes + * answer, instead of a toast flashed for the next page. */ - public function update(ProfileUpdateRequest $request): RedirectResponse + public function update(ProfileUpdateRequest $request): RedirectResponse|JsonResponse { $request->user()->update($request->validated()); + if (Frontend::wantsJson($request)) { + return new JsonResponse(['status' => 'profile-updated', 'message' => __('Profile updated.')]); + } + Inertia::flash('toast', ['type' => 'success', 'message' => __('Profile updated.')]); return to_route('profile.edit'); @@ -47,9 +57,10 @@ public function update(ProfileUpdateRequest $request): RedirectResponse /** * Delete the user's account. Keyring removes their sign-in methods, - * devices and sessions along with it. + * devices and sessions along with it. A JSON request gets a 204, as + * signing out does, and the frontend goes to its own front page. */ - public function destroy(Request $request): RedirectResponse + public function destroy(Request $request): RedirectResponse|Response { $user = $request->user(); @@ -60,6 +71,10 @@ public function destroy(Request $request): RedirectResponse $request->session()->invalidate(); $request->session()->regenerateToken(); + if (Frontend::wantsJson($request)) { + return response()->noContent(); + } + return redirect('/'); } } diff --git a/app/Http/Controllers/Settings/SecurityController.php b/app/Http/Controllers/Settings/SecurityController.php index 5147fb2..8424800 100644 --- a/app/Http/Controllers/Settings/SecurityController.php +++ b/app/Http/Controllers/Settings/SecurityController.php @@ -3,10 +3,9 @@ namespace App\Http\Controllers\Settings; use App\Http\Controllers\Controller; +use App\Http\Responses\PageResponse; use Illuminate\Http\Request; use Illuminate\Support\Arr; -use Inertia\Inertia; -use Inertia\Response; use Keyring\Contracts\Enrollable; use Keyring\Devices\DeviceManager; use Keyring\Facades\Keyring; @@ -25,12 +24,14 @@ class SecurityController extends Controller * This is also where Keyring sends people who have something to do * first: set up a second factor (keyring.enrollment_url) or choose a new * password (keyring.password_change_url). The page says which. + * + * A headless frontend loads the same props as JSON (PageResponse). */ - public function edit(Request $request, DeviceManager $devices, Sessions $sessions, SessionAssurance $assurance): Response + public function edit(Request $request, DeviceManager $devices, Sessions $sessions, SessionAssurance $assurance): PageResponse { $user = $request->user(); - return Inertia::render('settings/security', [ + return new PageResponse('settings/security', [ 'authenticators' => $user->keyring->all() ->reject(fn (Authenticator $authenticator) => $authenticator->isVirtual()) ->map(fn (Authenticator $authenticator) => [ diff --git a/app/Http/Controllers/WelcomeController.php b/app/Http/Controllers/WelcomeController.php index c55e27f..0dbbc5e 100644 --- a/app/Http/Controllers/WelcomeController.php +++ b/app/Http/Controllers/WelcomeController.php @@ -3,15 +3,14 @@ namespace App\Http\Controllers; use App\Demo\DemoProps; // @monorepo-only -use Inertia\Inertia; -use Inertia\Response; +use App\Http\Responses\PageResponse; class WelcomeController extends Controller { - public function __invoke(): Response + public function __invoke(): PageResponse { - $page = Inertia::render('welcome'); - $page->with('demoAccounts', DemoProps::accounts()); // @monorepo-only + $page = new PageResponse('welcome'); + $page = $page->with('demoAccounts', DemoProps::accounts()); // @monorepo-only return $page; } diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php index ef30ab6..df0f4be 100644 --- a/app/Http/Middleware/HandleInertiaRequests.php +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -39,15 +39,31 @@ public function share(Request $request): array { return [ ...parent::share($request), - 'name' => config('app.name'), - 'auth' => [ - 'user' => $request->user(), - ], + ...$this->sharedProps($request), // Keyring flashes a status key after changes ("device-revoked"...) - // and "was this you?" alerts after signing in. + // and "was this you?" alerts after signing in, for the next page. + // A headless frontend gets both in the JSON answers themselves + // instead (docs/headless-api.md), so /api/me leaves them out. 'status' => fn () => $request->session()->get('status'), 'statusMessage' => fn () => Keyring::statusMessage($request->session()->get('status')), 'keyringAlerts' => fn () => $request->session()->get('keyring.alerts', []), + ]; + } + + /** + * The app's own shared props, other than the flashed ones: what a + * headless frontend's layout gets, resolved, from GET /api/me + * (MeController). + * + * @return array + */ + public function sharedProps(Request $request): array + { + return [ + 'name' => config('app.name'), + 'auth' => [ + 'user' => $request->user(), + ], // A recovery code has been used, so it's time to make a new set. 'replaceRecoveryCodes' => fn () => (bool) $request->user()?->keyring->shouldReplaceRecoveryCodes(), 'demoLocation' => fn () => DemoProps::location($request), // @monorepo-only diff --git a/app/Http/Responses/PageResponse.php b/app/Http/Responses/PageResponse.php new file mode 100644 index 0000000..27b1995 --- /dev/null +++ b/app/Http/Responses/PageResponse.php @@ -0,0 +1,100 @@ + $props + */ + public function __construct( + public string $page, + public array $props = [], + ) {} + + /** + * The same page, with one more prop. + */ + public function with(string $key, mixed $value): self + { + return new self($this->page, [...$this->props, $key => $value]); + } + + /** + * @param Request $request + */ + public function toResponse($request): Response + { + if (Frontend::wantsJson($request)) { + return new JsonResponse(['page' => $this->page, 'props' => (object) $this->resolvedProps()], headers: [ + 'Cache-Control' => 'no-store, private', + ]); + } + + abort_if(Frontend::headless(), 404); + + return Inertia::render($this->page, $this->props)->toResponse($request); + } + + /** + * The props for the JSON answer, closures called. + * + * @return array + */ + private function resolvedProps(): array + { + $props = []; + + foreach ($this->props as $key => $prop) { + // Inertia::always() only says to send it every time, which a + // JSON answer does anyway. + $prop = $prop instanceof AlwaysProp ? $prop() : value($prop); + + foreach ([DeferProp::class, LiveProp::class, MergeProp::class, OnceProp::class, OptionalProp::class, ScrollProp::class, ProvidesInertiaProperty::class, ProvidesInertiaProperties::class] as $wrapper) { + if ($prop instanceof $wrapper) { + throw new LogicException("The [{$key}] prop of the [{$this->page}] page is ".class_basename($prop).', which only an Inertia visit can honour, so it can\'t be sent as JSON: pass the value, or a closure that returns it.'); + } + } + + $props[$key] = $prop; + } + + return $props; + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index bab9a43..b2cd065 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -4,6 +4,7 @@ use Carbon\CarbonImmutable; use Illuminate\Http\Middleware\TrustProxies; +use Illuminate\Http\Request; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; use Illuminate\Support\ServiceProvider; @@ -28,6 +29,17 @@ public function boot(): void if ($proxies = config('app.trusted_proxies')) { TrustProxies::at($proxies === '*' ? '*' : explode(',', $proxies)); + + // Only the headers a headless frontend's proxy sets (see + // docs/headless-api.md), not Laravel's default X-Forwarded-Port + // and AWS ELB header: the port comes with the host, as in + // X-Forwarded-Host: localhost:3000. + TrustProxies::withHeaders( + Request::HEADER_X_FORWARDED_FOR | + Request::HEADER_X_FORWARDED_HOST | + Request::HEADER_X_FORWARDED_PROTO | + Request::HEADER_X_FORWARDED_PREFIX + ); } } diff --git a/app/Providers/KeyringServiceProvider.php b/app/Providers/KeyringServiceProvider.php index 56a92fd..f1f8f63 100644 --- a/app/Providers/KeyringServiceProvider.php +++ b/app/Providers/KeyringServiceProvider.php @@ -9,6 +9,7 @@ use App\Actions\Keyring\UpdateUserPassword; use App\Actions\Keyring\ValidateEmailChange; use App\Notifications\Keyring as Notifications; +use App\Support\Frontend; use Illuminate\Auth\Notifications\ResetPassword; use Illuminate\Auth\Notifications\VerifyEmail; use Illuminate\Contracts\Foundation\Application; @@ -150,7 +151,16 @@ public function boot(): void // Keyring's pages already match the starter kit's names (auth/login, // auth/challenge...). Step-up confirmation reuses the challenge page. + // In headless mode Laravel renders none of them ('pages' => false in + // config/keyring.php): a JSON request gets each page's name and + // props, and anything else a 404. Keyring::page('confirm', 'auth/challenge'); + + // Emailed links open the frontend's pages, at Keyring's paths. On + // one origin FRONTEND_URL is APP_URL, where they start anyway. + if (Frontend::headless()) { + Keyring::linkRootUsing(fn () => config('app.frontend_url')); + } } /** diff --git a/app/Support/Frontend.php b/app/Support/Frontend.php new file mode 100644 index 0000000..ac98996 --- /dev/null +++ b/app/Support/Frontend.php @@ -0,0 +1,29 @@ +expectsJson() && ! $request->hasHeader('X-Inertia'); + } +} diff --git a/config/app.php b/config/app.php index 9f41276..bdae3f7 100644 --- a/config/app.php +++ b/config/app.php @@ -67,6 +67,29 @@ 'timezone' => 'UTC', + /* + |-------------------------------------------------------------------------- + | Frontend + |-------------------------------------------------------------------------- + | + | Who builds the pages. "inertia" (the default) is the React app in + | resources/js, served by Laravel. "headless" is a frontend Laravel + | doesn't serve, such as the TanStack Start or Nuxt kit, on one origin: + | its server passes everything under a prefix such as /backend on to + | Laravel. Laravel then renders no pages: a page request that isn't JSON + | gets a 404, and Keyring sends users to the frontend's own pages. See + | docs/headless-api.md. + | + | "frontend_url" is where the frontend's pages are, which on one origin + | is APP_URL itself. Unset or empty, it's APP_URL. It may have a path, + | such as https://example.com/app, when the frontend's pages are there. + | + */ + + 'frontend' => env('APP_FRONTEND') ?: 'inertia', + + 'frontend_url' => rtrim((string) (env('FRONTEND_URL') ?: env('APP_URL', 'http://localhost')), '/'), + /* |-------------------------------------------------------------------------- | Trusted Proxies @@ -76,9 +99,18 @@ | is only believed about the visitor's address and HTTPS when it's listed | here: comma-separated addresses, or * for any. | + | A headless frontend's server is that proxy, and trusting it is how + | Laravel learns the browser's address and the frontend's host, scheme + | and prefix (X-Forwarded-For, -Host, -Proto, -Prefix), which are the only + | headers it's believed about (AppServiceProvider): the port has to come + | in -Host, as in localhost:3000. Unset or empty, headless mode trusts a + | proxy on this machine (127.0.0.1 and ::1), so anything on loopback that + | forwards requests to Laravel is trusted, and Inertia mode trusts none. + | The proxy must set X-Forwarded-For itself, never pass on the browser's. + | */ - 'trusted_proxies' => env('TRUSTED_PROXIES'), + 'trusted_proxies' => env('TRUSTED_PROXIES') ?: (env('APP_FRONTEND') === 'headless' ? '127.0.0.1,::1' : null), /* |-------------------------------------------------------------------------- diff --git a/config/cors.php b/config/cors.php new file mode 100644 index 0000000..99dc847 --- /dev/null +++ b/config/cors.php @@ -0,0 +1,37 @@ + [], + + 'allowed_methods' => [], + + 'allowed_origins' => [], + + 'allowed_origins_patterns' => [], + + 'allowed_headers' => [], + + 'exposed_headers' => [], + + 'max_age' => 0, + + 'supports_credentials' => false, + +]; diff --git a/config/keyring.php b/config/keyring.php index ca4fade..4d19a3a 100644 --- a/config/keyring.php +++ b/config/keyring.php @@ -7,6 +7,14 @@ use Keyring\Devices\NullLocator; use Keyring\Features; +// APP_FRONTEND=headless: the pages are a frontend's that Laravel doesn't +// serve (config/app.php), so Keyring renders none of them and sends users +// to the frontend's pages, at FRONTEND_URL. +$headless = env('APP_FRONTEND') === 'headless'; +$frontend = fn (string $path): string => $headless + ? rtrim((string) (env('FRONTEND_URL') ?: env('APP_URL', 'http://localhost')), '/').$path + : $path; + return [ /* @@ -15,7 +23,8 @@ |-------------------------------------------------------------------------- | | The guard Keyring signs users in to, the attribute they sign in with, - | and where they go once they have. + | and where they go once they have. A headless frontend's dashboard is + | at FRONTEND_URL, and comes back to it as the "redirect" of a sign in. | */ @@ -23,7 +32,20 @@ 'username' => 'email', - 'home' => '/dashboard', + 'home' => $frontend('/dashboard'), + + /* + |-------------------------------------------------------------------------- + | Pages + |-------------------------------------------------------------------------- + | + | Whether Laravel renders Keyring's pages (login, challenge...). Off in + | headless mode: the frontend builds them from the JSON each page route + | answers, and a page request that isn't JSON gets a 404. + | + */ + + 'pages' => ! $headless, /* |-------------------------------------------------------------------------- @@ -82,10 +104,15 @@ | */ - 'enrollment_url' => '/settings/security', + 'enrollment_url' => $frontend('/settings/security'), - // The pages anyone can open stay open to them meanwhile. - 'enrollment_except' => ['home', 'well-known.passkeys'], + // The pages anyone can open stay open to them meanwhile. The security + // page itself is let through by its path, which Keyring takes from + // enrollment_url. In headless mode that's the frontend's path, which + // needn't be Laravel's (FRONTEND_URL can have a path of its own), so + // the security page's JSON is listed by name, with GET /api/me, which + // the frontend's layout needs on every page. + 'enrollment_except' => ['home', 'well-known.passkeys', ...($headless ? ['security.edit', 'api.me'] : [])], /* |-------------------------------------------------------------------------- @@ -112,7 +139,14 @@ | */ - 'password_change_url' => '/settings/security', + 'password_change_url' => $frontend('/settings/security'), + + // As for enrollment: in headless mode the security page's JSON and + // GET /api/me are let through by name. Both only read, and the security + // page is what an Inertia user is held on anyway. Anything listed here + // stays open to whoever has the compromised password, so keep it to + // pages like these. + 'password_change_except' => $headless ? ['security.edit', 'api.me'] : [], /* |-------------------------------------------------------------------------- diff --git a/docs/headless-api.md b/docs/headless-api.md new file mode 100644 index 0000000..b8228f9 --- /dev/null +++ b/docs/headless-api.md @@ -0,0 +1,397 @@ +# Headless API + +The same Laravel app serves two kinds of starter kit: + +- `inertia-react`: the React app in `resources/js`, which Laravel serves. This is the default. +- Headless kits, such as a TanStack Start or Nuxt app: a frontend Laravel doesn't serve, calling Laravel with `fetch` and the browser's session cookie. + +This page is what the headless kits are built from: how to switch the backend over, how to call it, and every endpoint with its JSON. Keyring's own guide to this setup is [Headless Frontends](https://github.com/keyringphp/keyring/blob/main/docs/headless.md). Read its [One Origin](https://github.com/keyringphp/keyring/blob/main/docs/headless.md#one-origin), [Pages as JSON](https://github.com/keyringphp/keyring/blob/main/docs/headless.md#pages-as-json) and [Where Each Answer Goes](https://github.com/keyringphp/keyring/blob/main/docs/headless.md#where-each-answer-goes) sections alongside this one. + +- [Requirements](#requirements) +- [The Layout](#the-layout) +- [Environment Variables](#environment-variables) +- [What Headless Mode Changes](#what-headless-mode-changes) +- [Calling Laravel](#calling-laravel) +- [Answers Every Route Can Give](#answers-every-route-can-give) +- [Endpoints](#endpoints) + - [GET /api/me](#get-apime) + - [The App's Pages](#the-apps-pages) + - [Writes](#writes) + - [Keyring's Routes](#keyrings-routes) +- [Statuses and Alerts](#statuses-and-alerts) +- [A Frontend Under a Path](#a-frontend-under-a-path) +- [What Doesn't Work Headless](#what-doesnt-work-headless) + +## Requirements + +Headless mode needs Keyring 0.4 or later (`keyring/keyring`), and the headless kits need `@keyringjs/keyring` 0.2 or later. Neither is released yet: until they are, `composer.json` stays on Keyring `^0.3`, which runs the Inertia app but not headless mode, and the kits are built against Keyring's development branch. From 0.4 Keyring has what the kits use: + +- the `pages` option, and its pages answered as JSON with `{"page", "props"}`; +- `page` in the answers that send the browser to one of its pages, such as the `423`'s `"page": "confirm"`; +- the `password_change_except` option, like `enrollment_except`; +- the `alerts` of a sign in in the answer that completes it; +- a `422` naming the login page when a sign in has run out, and a JSON `email-verified` answer from the verification link; +- a `401` with the `sign-in-to-verify` status for a verification link opened signed out. + +`@keyringjs/keyring` 0.2 has the headless entry points (`react-headless`, `vue-headless`, `headless`) and `configureRequests()`. + +## The Layout + +The headless kits use Keyring's "one origin" layout. The frontend's server is the only thing the browser talks to, and it passes everything under `/backend` on to Laravel: + +| The Browser Asks For | Served By | +| --------------------------------------------------- | ----------------------------------------- | +| `https://example.com/dashboard` | the frontend, its `dashboard` page | +| `https://example.com/login` | the frontend, its `login` page | +| `https://example.com/backend/dashboard` | Laravel, `/dashboard`, as JSON | +| `https://example.com/backend/login` | Laravel, `/login`, as JSON | +| `https://example.com/backend/api/me` | Laravel, `/api/me` | +| `https://example.com/.well-known/passkey-endpoints` | Laravel, `/.well-known/passkey-endpoints` | + +The proxy strips `/backend` and sets `X-Forwarded-For` (the address it saw, never one the browser sent), `X-Forwarded-Host` (the browser's `Host`, port included, such as `localhost:3000`), `X-Forwarded-Proto` and `X-Forwarded-Prefix: /backend`. Laravel believes those four from the proxy and nothing else: `X-Forwarded-Port` is ignored, so a frontend on a port other than 80 or 443 needs the port in `X-Forwarded-Host`, or the URLs in Keyring's answers leave it out. Keyring's guide has a Nitro example. Never pass the frontend's own paths, such as `/login` or `/reset-password/{token}`, on to Laravel: in headless mode Laravel answers a page visit with a `404`. + +One path outside `/backend` goes to Laravel too: `/.well-known/passkey-endpoints`, where password managers look up the page for adding and managing passkeys. Pass it on as it is, without stripping or adding anything. Laravel answers it with the frontend's security page, `{FRONTEND_URL}/settings/security`. It's a well-known URL, so it stays at the origin's root even when the frontend is [under a path](#a-frontend-under-a-path). + +Every request is same-origin, so there's no CORS: `config/cors.php` allows no other origin, so no other site can read `/api/me` or any other answer with the user's cookies. `SESSION_DOMAIN` stays empty, and passkeys need no settings: the relying party is `APP_URL`'s host, which is the frontend's. + +## Environment Variables + +A headless kit's `.env.example` sets these on top of the app's own: + +| Variable | Inertia | Headless | | +| ----------------------- | ----------------------- | ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `APP_FRONTEND` | `inertia` (the default) | `headless` | Picks the mode. Anything but `headless` is Inertia. | +| `APP_URL` | `http://localhost:8000` | the frontend's address, such as `http://localhost:3000` | Emailed links and the passkey relying party come from it, so on one origin it's the frontend's. | +| `FRONTEND_URL` | unused | defaults to `APP_URL` | Where the frontend's pages are: `home`, `enrollment_url` and `password_change_url` start with it, and so do emailed links. Only set it when it isn't `APP_URL`. It may have a path (see [A Frontend Under a Path](#a-frontend-under-a-path)). | +| `TRUSTED_PROXIES` | unset: none | defaults to `127.0.0.1,::1` | The frontend's server, which Laravel believes about the browser's address, host, scheme and prefix. Set it to the server's address when the frontend runs on another machine. | +| `SESSION_DOMAIN` | `null` | `null` | Leave it empty on one origin. | +| `SESSION_SECURE_COOKIE` | | `false` over plain HTTP, `true` in production | Safari refuses a `Secure` cookie from `http://localhost`. | + +Left at its default, `TRUSTED_PROXIES` trusts anything on loopback that forwards requests to Laravel, not only the frontend's server: anything else running on the same machine can set the forwarded headers too. An empty value counts as unset, for `FRONTEND_URL` and `TRUSTED_PROXIES` both. + +Nothing else changes. In particular, there's no Sanctum: see [Calling Laravel](#calling-laravel). + +## What Headless Mode Changes + +`APP_FRONTEND=headless` sets: + +| Setting | Inertia | Headless | +| -------------------------------- | -------------------------------- | ---------------------------------------------------- | +| `keyring.pages` | `true` | `false` | +| `keyring.home` | `/dashboard` | `{FRONTEND_URL}/dashboard` | +| `keyring.enrollment_url` | `/settings/security` | `{FRONTEND_URL}/settings/security` | +| `keyring.password_change_url` | `/settings/security` | `{FRONTEND_URL}/settings/security` | +| `keyring.enrollment_except` | `home`, `well-known.passkeys` | the same, plus `security.edit` and `api.me` | +| `keyring.password_change_except` | none | `security.edit` and `api.me` | +| `app.trusted_proxies` | `TRUSTED_PROXIES` | `TRUSTED_PROXIES`, or `127.0.0.1,::1` | +| Emailed links | start at `APP_URL` | start at `FRONTEND_URL` (`Keyring::linkRootUsing()`) | +| `/.well-known/passkey-endpoints` | Laravel's security page | `{FRONTEND_URL}/settings/security` | +| `GET /settings` | redirects to `/settings/profile` | `404`: the frontend sends `/settings` on itself | + +And Laravel stops rendering pages. The app's pages and Keyring's answer JSON requests with `{"page": ..., "props": ...}`. A request that isn't JSON is still sent on first where anyone would be: a guest's gets a `302` to `/login`, and a held user's a `302` to `{FRONTEND_URL}/settings/security`. Any other request that isn't JSON, an Inertia visit included, gets a `404`. + +While a user is held, to add a second factor or to choose a new password, Keyring only lets through its own routes it needs for that, the routes listed in `enrollment_except` or `password_change_except`, and the route whose path is the path of `enrollment_url` or `password_change_url`. In headless mode those URLs are the frontend's, so the frontend's security page has to be at `{FRONTEND_URL}/settings/security`, where Keyring sends the user. The JSON that page loads from Laravel is let through by its route name, `security.edit`, along with `GET /api/me`. Both only read, and the security page is the one an Inertia user is held on anyway. Nothing else of the app's is let through during a password hold: Keyring warns that anything listed stays open to whoever has the compromised password. + +## Calling Laravel + +Every request goes to `/backend/...` with: + +``` +Accept: application/json +X-Requested-With: XMLHttpRequest +``` + +and the browser's cookies, which a same-origin `fetch()` sends by default. In `@keyringjs/keyring` 0.2, `json()` sends both headers. Point it at Laravel with `configureRequests({ baseUrl: '/backend' })`. + +All of these routes, the app's and Keyring's, are `web` routes: the session, CSRF protection and Keyring's session middleware run on every one. That's why there's no Sanctum. It's only needed for routes in the `api` group, and there are none. + +**CSRF.** Laravel checks every write (`POST`, `PUT`, `PATCH`, `DELETE`). A browser's own `fetch()` on one origin sends `Sec-Fetch-Site: same-origin`, which passes on its own. The `XSRF-TOKEN` cookie's value sent back as `X-XSRF-TOKEN` passes too, which is what `json()` and axios do, and what a request from the frontend's server needs if it ever writes. Every response from Laravel sets the cookie, so `GET /backend/api/me` is enough to get one. A write with neither gets a `419`. + +**On the server.** A page rendered on the frontend's server calls Laravel directly, not through `/backend`. Pass on the browser's `Cookie`, `User-Agent` and `Accept-Language`, set the same `X-Forwarded-*` headers the proxy sets, and hand any `Set-Cookie` from Laravel back to the browser. Keyring's guide explains why each one matters. Only read on the server (`/api/me`, the pages): send sign ins and other writes from the browser, so Keyring's rate limits and risk signals see the user's own address. + +**Caching.** `/api/me` and every page's JSON, the app's and Keyring's, are sent with `Cache-Control: no-store, private`. Don't cache a page the frontend rendered with them either, in the frontend's own route rules or in a CDN: it would show the next visitor the first one's account. + +## Answers Every Route Can Give + +| Status | Body | What It Means | What to Do | +| ------ | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | +| `401` | `{"message": "Unauthenticated."}` | Not signed in. | Go to the login page, keeping where the user was in `?redirect=`. | +| `401` | `{"status": "signed-out", "message": "...", "page": "login", "redirect": "..."}` | Keyring ended the session (revoked, timed out, signed out elsewhere). | The same. | +| `403` | `{"status": "enroll-first", "message": "...", "redirect": "{FRONTEND_URL}/settings/security"}` | The account needs a second factor first. | Go to `/settings/security`. | +| `403` | `{"status": "change-password", "message": "...", "redirect": "{FRONTEND_URL}/settings/security"}` | The account has to choose a new password first. | Go to `/settings/security`. | +| `403` | `{"message": "Your email address is not verified."}` | Only with `KEYRING_REVEAL_TAKEN=true`: a signed-in user whose address isn't verified, on a `verified` route. | Go to the `verify-email` page. | +| `419` | `{"message": "CSRF token mismatch."}` | A write without a same-origin `fetch()` or the token. | Fetch the token and retry. | +| `422` | `{"message": "...", "errors": {"field": ["..."]}}` | Validation failed. | Show the errors on the form. | +| `423` | `{"message": "...", "page": "confirm", "redirect": "https://example.com/backend/confirm"}` | The route needs a recent verification (step-up). | Go to the frontend's confirm page with `?redirect=` set to the current page, and come back once confirming answers `authenticated`. | + +By default registration hides who has an account, and an unverified address never gets a signed-in session (Keyring signs it in only once the address is verified), so a `verified` route answers it with the first `401`. With `KEYRING_REVEAL_TAKEN=true`, new users are signed in before they verify, and a `verified` route answers them with the `403` above instead. + +URLs in Keyring's answers, such as the `423`'s `redirect`, are built from the forwarded headers, so they're Laravel's (`/backend/...`). `home`, `enrollment_url` and `password_change_url` are the frontend's. Go by `page` when there is one, then by the status, never by the URL. + +## Endpoints + +Paths are Laravel's: the browser adds `/backend`. + +### GET /api/me + +The props every Inertia page gets as shared props, for the frontend's layout. Guests get it too, with `auth.user` null. It's let through while the user is held, to add a second factor or to change their password. It never has the flashed status or alerts: see [Statuses and Alerts](#statuses-and-alerts). + +When Keyring ends the session (revoked, timed out, signed out elsewhere), the next call answers the `401` `signed-out` from [Answers Every Route Can Give](#answers-every-route-can-give) once, and the ones after it `200` as a guest. A layout loader that calls `/api/me` has to handle that `401` too: treat it as signed out, and send the user to the login page with its message if they were on a page that needs a session. + +```json +{ + "name": "Laravel", + "auth": { + "user": { + "id": 1, + "name": "Taylor", + "email": "taylor@example.com", + "email_verified_at": "2026-11-26T19:16:15.000000Z", + "created_at": "2026-11-26T19:16:15.000000Z", + "updated_at": "2026-11-26T19:16:15.000000Z" + } + }, + "replaceRecoveryCodes": false, + "sidebarOpen": true +} +``` + +| Key | | +| ---------------------- | ---------------------------------------------------------------- | +| `name` | `APP_NAME`. | +| `auth.user` | The signed-in user, or `null`. | +| `replaceRecoveryCodes` | A recovery code has been used: time to make a new set. | +| `sidebarOpen` | From the `sidebar_state` cookie, which the frontend sets itself. | + + + +In this repository, with the demo, there's also `demoLocation`: `null` unless `KEYRING_LOCATOR=demo`, and then `{"current": "london", "places": {"london": {"city": "London", "country": "GB"}, "paris": ..., "new-york": ..., "tokyo": ...}}`, for the login page's location picker. + + + +### The App's Pages + +A JSON request for one of the app's pages, one that isn't an Inertia visit, gets its name and props, the same props the Inertia page gets: + +```json +{ "page": "dashboard", "props": { ... } } +``` + +`props` is always an object, `{}` when the page has none. + +**`GET /`**, page `welcome`. Anyone. No props. + +**`GET /dashboard`**, page `dashboard`. Signed in, verified, with a second factor. No props. + + + +In this repository the demo adds props to both. The welcome page has `demoAccounts`: + +```json +{ + "page": "welcome", + "props": { + "demoAccounts": { + "password": "password", + "totpSecret": "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP", + "recoveryCode": "demo-code-aaaa-aaaa-aaaa-aaaa-aa", + "totpQr": "..." + } + } +} +``` + +And the dashboard has `demoSettings`: + +```json +{ + "page": "dashboard", + "props": { + "demoSettings": { + "locator": null, + "breachCheck": { "signIns": false, "newPasswords": false }, + "emailPreviews": false + } + } +} +``` + +`locator` is `null`, `"demo"`, `"cloudflare"` or `"other"`. `emailPreviews` is true while running locally, when Laravel serves the `/emails` gallery. + + + +**`GET /settings/profile`**, page `settings/profile`. Signed in, with a second factor. + +```json +{ + "page": "settings/profile", + "props": { + "mustVerifyEmail": true, + "pendingEmail": { + "email": "new@example.com", + "confirmed": false, + "needsCurrentConfirmation": true, + "expiresAt": "2026-11-27T19:16:15+00:00" + } + } +} +``` + +`pendingEmail` is `null` without an email change waiting. Start one with Keyring's `POST /user/email`, and cancel it with `DELETE /user/email`. + +**`GET /settings/security`**, page `settings/security`. Signed in and verified, and a verification in the last 15 minutes (`423` otherwise). Reachable while held. + +```json +{ + "page": "settings/security", + "props": { + "authenticators": [ + { + "factor": "totp", + "id": "01m8...", + "name": "1Password", + "createdAt": "2026-...", + "lastUsedAt": null, + "isDefault": false + }, + { + "factor": "recovery", + "id": "01m8...", + "name": "Recovery codes", + "createdAt": "2026-...", + "lastUsedAt": null, + "remaining": 10, + "replace": false, + "isDefault": false + } + ], + "enrollable": ["passkey", "security-key", "totp", "recovery"], + "devices": [ + { + "id": "...", + "name": null, + "description": "Firefox on macOS", + "ip": "203.0.113.7", + "location": null, + "lastActiveAt": "2026-...", + "trusted": true, + "current": true, + "sessions": 1 + } + ], + "sessions": [ + { + "id": "<64 hex characters>", + "name": "Firefox on macOS", + "ip": "203.0.113.7", + "device": "...", + "remembered": false, + "signedInAt": "2026-...", + "lastActiveAt": "2026-...", + "expiresAt": "2026-...", + "current": true + } + ], + "activity": [ + { + "id": "01m8...", + "type": "signed_in", + "severity": "info", + "factor": null, + "meta": { "factors": ["password", "totp"] }, + "device": "Firefox on macOS", + "ip": "203.0.113.7", + "at": "2026-..." + } + ], + "assurance": "AAL2", + "hasSecondFactor": true, + "mustChangePassword": false + } +} +``` + +Each authenticator is what its factor's `present()` gives, plus `isDefault`: passkeys and security keys add their own keys, and recovery codes add `remaining` and `replace`. `sessions[].id` is the handle for `DELETE /user/sessions/{id}`, never the session's own ID. `activity[].id` is a ULID string. `activity[].meta` only has `factors`, `name`, `count`, `remaining`, `reason`, `reasons` and `resource`, when the entry has them, and an entry with none of them has `"meta": []`, an empty array rather than `{}`. `enrollable` lists the factors the user can add. `assurance` is `AAL1`, `AAL2` or `AAL3`. Keyring has `GET /user/devices` and `GET /user/sessions` too, for refreshing those lists after a change without reloading the page, but no route lists sign-in methods or activity: reload the page for those. + + + +In this repository `enrollable` has `email-code` too, which the demo registers. + + + +**`GET /settings/appearance`**, page `settings/appearance`. Signed in, verified, with a second factor. No props: the theme is kept in the browser, so the frontend's appearance page only needs this to check the user may see it. + +### Writes + +**`PATCH /settings/profile`**, signed in, with a second factor. Body `{"name": "Taylor"}`. + +```json +{ "status": "profile-updated", "message": "Profile updated." } +``` + +A bad name is a `422` on `name`. The email address only changes through Keyring's `POST /user/email`. + +**`DELETE /settings/profile`**, signed in, verified, with a second factor and a verification in the last 15 minutes (`423` otherwise). Deletes the account and its sign-in methods, devices and sessions, and signs out. Answers `204`. Go to the front page, and clear anything the frontend kept. + + + +**`POST /demo-location`**, only in this repository. Anyone, with `KEYRING_LOCATOR=demo` (a `404` otherwise). Body `{"place": "tokyo"}`, one of `london`, `paris`, `new-york` and `tokyo`. Answers `204` and sets the `demo_location` cookie, which the next sign in is located by. + + + +### Keyring's Routes + +Keyring's routes have no prefix here: `/login`, `/login/challenge`, `/confirm`, `/user/password` and so on, as in Keyring's [route list](https://github.com/keyringphp/keyring/blob/main/docs/sign-in-flow.md#routes). Every one answers JSON. Its pages answer with `{"page", "props"}` like the app's, with `Cache-Control: no-store, private`, and a page visit gets a `404`: + +| Page | Path | The Frontend's Route | +| -------------------- | -------------------------------------------------- | ------------------------------------ | +| `login` | `/login` | `/login` | +| `register` | `/register` | `/register` | +| `forgot-password` | `/forgot-password` | `/forgot-password` | +| `reset-password` | `/reset-password/{token}` | `/reset-password/{token}`, emailed | +| `verify-email` | `/email/verify` | `/email/verify` | +| `email-verification` | `/email/verify/{id}/{hash}` | `/email/verify/{id}/{hash}`, emailed | +| `email-change` | `/email-changes/{change}/{confirm,revert}/{token}` | the same, emailed | +| `device-report` | `/devices/{device}/report` | the same, emailed | +| `challenge` | `/login/challenge/{factor?}` | `/login/challenge` | +| `confirm` | `/confirm/{factor?}` | `/confirm` | + +The pages emailed links open have to be at exactly those paths on the frontend: emailed links start at `FRONTEND_URL` and keep Keyring's paths. Send them with the headers Keyring's guide lists (`Referrer-Policy: no-referrer`, `Cache-Control: no-store`, `X-Frame-Options: DENY`), and load them in the browser, not on the server. Each page loads its props from Laravel with the link's own path and query under `/backend`: a signed link's signature only covers Keyring's path and query, so it holds there, and a bad or expired one is a `403`. The `url` those pages post to is Laravel's path without `/backend`, so put `/backend` in front of it (`configureRequests({ baseUrl: '/backend' })` does). + +Signing in answers `{"status": "authenticated", "redirect": "{FRONTEND_URL}/dashboard", "alerts": [...]}`, or a `202` `challenge` with `"page": "challenge"` when another factor is needed. A challenge with no sign in waiting, because the frontend's challenge page was opened on its own or the sign in ran out, answers a `422` with `"page": "login"` and the reason on the `email` field, for the `GET` that loads the page and the `POST` that answers it alike. Keyring's `guest` routes, such as `/login`, redirect a signed-in request instead of answering it, so check `GET /api/me` before showing them. + +## Statuses and Alerts + +Keyring answers every JSON request with its status in the body, so what an Inertia page reads from the session comes back in the response itself: `password-updated`, `device-revoked`, `email-change-requested`, new recovery codes, and the rest. That includes the two that used to only go to the session: + +- **"Was this you?" alerts.** The `200` `authenticated` that completes a sign in, after a password, a challenge, a passkey or registering, has them as `alerts`: `[{"type": "second_factor_failed", "factor": "totp", "at": "2026-...", "ip": "203.0.113.7"}]`, with the types in `keyring.security_log.alerts`, or `[]`. Keep them, in a store or the next route's state, and show them once on the page the user goes to, as the Inertia app's dashboard shows its "Was this you?" banner. A step-up confirmation's answer has no `alerts`. +- **`sign-in-to-verify`.** An emailed verification link opened signed out answers `401` with `{"status": "sign-in-to-verify", "message": "...", "page": "login", "redirect": "..."}`. Nothing is flashed for it, so the login page's props have `"status": null` afterwards: keep the message from the `401` and show it on the login page. Signing in then verifies the address. + +Keyring still flashes the alerts to the session as well, for apps whose next page reads it, so `/api/me` doesn't return them, or they'd show twice. It returns no status either. + +The Inertia app's toast after saving the profile is flashed with `Inertia::flash()`. A JSON request gets that message in the body instead. + +## A Frontend Under a Path + +`FRONTEND_URL` may have a path of its own, such as `https://example.com/app`, when the frontend's pages are under it. A trailing `/` is dropped. Then: + +- `home`, `enrollment_url` and `password_change_url` are `https://example.com/app/dashboard` and `https://example.com/app/settings/security`, and `/.well-known/passkey-endpoints` answers with the security page there. The proxy still passes that one on from the origin's root, `https://example.com/.well-known/passkey-endpoints`, not from under `/app`. +- Emailed links start at `https://example.com/app`, at Keyring's paths: `https://example.com/app/reset-password/{token}`. A signed link is signed over Keyring's path and query, without `/app`, so the frontend leaves `/app` off the path it sends on to Laravel, as it leaves off `/backend`. +- The holds still let the security page's JSON and `/api/me` through, by route name, although Laravel's `/settings/security` isn't the frontend's `/app/settings/security`. + +Keep `APP_URL` the origin, `https://example.com`, since the passkey relying party and origin come from it. The proxy's `X-Forwarded-Prefix` is whatever Laravel is under, such as `/app/backend`. + +Only put the frontend under a path on an origin you fully control. The session cookie and the CSRF check go by the origin, not the path: anything else on `https://example.com`, such as another app under `/blog`, gets the user's session cookie with its requests to Laravel, and its writes pass as same-origin. + +## What Doesn't Work Headless + +- **Coming back after signing in, confirming or enrolling.** Keyring only remembers pages Laravel served, and its JSON answers have no `continue` to go back to after enrolling. Keep the page the user was going to in the frontend, in `?redirect=`, and only follow a path that starts with a single `/`. +- **`GET /settings`.** It's a `404` in headless mode: the frontend sends its own `/settings` on to its profile page. + + + +- **The `/emails` gallery and `php artisan example:links`.** These are Laravel's pages or redirect to them. The gallery is at Laravel's address while running locally. + + + +- **Bearer tokens and mobile apps.** Keyring signs in session guards only. diff --git a/phpunit.xml b/phpunit.xml index 86dd605..9a1c732 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -19,6 +19,9 @@ + + + diff --git a/routes/settings.php b/routes/settings.php index a11a12e..561a728 100644 --- a/routes/settings.php +++ b/routes/settings.php @@ -2,10 +2,16 @@ use App\Http\Controllers\Settings\ProfileController; use App\Http\Controllers\Settings\SecurityController; +use App\Http\Responses\PageResponse; +use App\Support\Frontend; use Illuminate\Support\Facades\Route; Route::middleware(['auth'])->group(function () { - Route::redirect('settings', '/settings/profile'); + // Only the Inertia app's: in headless mode /settings is the frontend's + // to send on, and Laravel's redirect would leave out the /backend prefix. + if (! Frontend::headless()) { + Route::redirect('settings', '/settings/profile'); + } Route::get('settings/profile', [ProfileController::class, 'edit'])->name('profile.edit'); Route::patch('settings/profile', [ProfileController::class, 'update'])->name('profile.update'); @@ -19,10 +25,17 @@ Route::delete('settings/profile', [ProfileController::class, 'destroy'])->name('profile.destroy'); }); - Route::inertia('settings/appearance', 'settings/appearance')->name('appearance.edit'); + // No props: the theme is kept in the browser. A headless frontend gets + // {"page": "settings/appearance", "props": {}}, and a 404 for anything + // but JSON, like every other page. + Route::get('settings/appearance', fn () => new PageResponse('settings/appearance'))->name('appearance.edit'); }); -Route::get('.well-known/passkey-endpoints', fn () => response()->json([ - 'enroll' => route('security.edit'), - 'manage' => route('security.edit'), -]))->name('well-known.passkeys'); +// Where a password manager sends people to add or manage a passkey: the +// frontend's security page in headless mode, which only works when the +// frontend passes /.well-known/passkey-endpoints on to Laravel. +Route::get('.well-known/passkey-endpoints', function () { + $page = Frontend::headless() ? config('app.frontend_url').'/settings/security' : route('security.edit'); + + return response()->json(['enroll' => $page, 'manage' => $page]); +})->name('well-known.passkeys'); diff --git a/routes/web.php b/routes/web.php index 9481128..83ab343 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,6 +1,7 @@ name('dashboard'); }); +// The shared props every Inertia page gets, for a headless frontend's +// layout (docs/headless-api.md). A web route like the rest, with the session +// and CSRF protection, so no Sanctum: on one origin the frontend calls it +// with the browser's cookies. Guests get it too, with no user. +Route::get('api/me', MeController::class)->name('api.me'); + require __DIR__.'/settings.php'; require __DIR__.'/demo.php'; // @monorepo-only diff --git a/tests/Feature/Demo/DemoHeadlessTest.php b/tests/Feature/Demo/DemoHeadlessTest.php new file mode 100644 index 0000000..62ebb68 --- /dev/null +++ b/tests/Feature/Demo/DemoHeadlessTest.php @@ -0,0 +1,80 @@ +getJson(route('home')) + ->assertOk() + ->assertJson(fn (AssertableJson $json) => $json + ->where('page', 'welcome') + ->has('props.demoAccounts', fn (AssertableJson $accounts) => $accounts + ->where('password', 'password') + ->where('totpSecret', DemoSeeder::TOTP_SECRET) + ->where('recoveryCode', DemoSeeder::RECOVERY_CODES[0]) + ->where('totpQr', fn (string $svg) => str_starts_with($svg, 'actingAs(User::factory()->withSecondFactor()->create()) + ->getJson(route('dashboard')) + ->assertOk() + ->assertExactJson([ + 'page' => 'dashboard', + 'props' => [ + 'demoSettings' => [ + 'locator' => null, + 'breachCheck' => ['signIns' => false, 'newPasswords' => false], + 'emailPreviews' => false, + ], + ], + ]); + } + + public function test_api_me_has_the_demo_locations() + { + $this->getJson(route('api.me'))->assertOk()->assertJsonPath('demoLocation', null); + + config(['keyring.devices.locator' => DemoLocator::class]); + + $this->withCredentials() + ->withCookie(DemoLocator::COOKIE, 'tokyo') + ->getJson(route('api.me')) + ->assertJsonPath('demoLocation.current', 'tokyo') + ->assertJsonPath('demoLocation.places.tokyo', ['city' => 'Tokyo', 'country' => 'JP']); + } + + public function test_the_location_picker_answers_204_with_the_cookie() + { + config(['keyring.devices.locator' => DemoLocator::class]); + + $this->postJson(route('demo-location'), ['place' => 'tokyo']) + ->assertNoContent() + ->assertCookie(DemoLocator::COOKIE, 'tokyo'); + + $this->postJson(route('demo-location'), ['place' => 'atlantis']) + ->assertUnprocessable(); + } + + public function test_the_location_picker_is_a_404_without_the_demo_locator() + { + $this->postJson(route('demo-location'), ['place' => 'tokyo'])->assertNotFound(); + } +} diff --git a/tests/Feature/Headless/BehindTheFrontendTest.php b/tests/Feature/Headless/BehindTheFrontendTest.php new file mode 100644 index 0000000..2b8df0e --- /dev/null +++ b/tests/Feature/Headless/BehindTheFrontendTest.php @@ -0,0 +1,109 @@ +reportLink(); + + $this->assertStringStartsWith('https://app.example.test/devices/', $link); + + $this->throughTheFrontend($this->pathOf($link)) + ->assertOk() + ->assertJsonPath('page', 'device-report') + ->assertJsonPath('props.device', fn (string $device) => $device !== ''); + } + + public function test_a_signed_emailed_link_with_a_bad_signature_is_refused() + { + $link = $this->reportLink(); + + $this->throughTheFrontend(preg_replace('/signature=[0-9a-f]+/', 'signature='.str_repeat('0', 64), $this->pathOf($link))) + ->assertForbidden(); + } + + /** + * The address that made the request is the browser's, as the proxy saw + * it, so Keyring's rate limits and risk signals count the user's own. + */ + public function test_a_proxy_on_loopback_is_trusted() + { + $this->throughTheFrontend('/api/me', from: '127.0.0.1')->assertOk(); + + $this->assertSame('203.0.113.9', request()->ip()); + $this->assertSame('https://app.example.test/backend', request()->root()); + } + + public function test_a_proxy_on_ipv6_loopback_is_trusted() + { + $this->throughTheFrontend('/api/me', from: '::1')->assertOk(); + + $this->assertSame('203.0.113.9', request()->ip()); + } + + /** + * Anyone else who reaches Laravel can't say where a request came from: + * their own address is the one that counts. + */ + public function test_any_other_address_is_not_trusted() + { + $this->throughTheFrontend('/api/me', from: '198.51.100.20')->assertOk(); + + $this->assertSame('198.51.100.20', request()->ip()); + $this->assertSame(rtrim(config('app.url'), '/'), request()->root()); + } + + /** + * A link's path and query, which the frontend's page sends on to + * Laravel as they are. + */ + private function pathOf(string $url): string + { + return parse_url($url, PHP_URL_PATH).'?'.parse_url($url, PHP_URL_QUERY); + } + + private function reportLink(): string + { + // Signing in is what makes a device. + $user = User::factory()->create(); + $this->postJson(route('login.store'), ['email' => $user->email, 'password' => 'password'])->assertOk(); + $this->postJson(route('logout'))->assertNoContent(); + + return Device::query()->sole()->revokeUrl(); + } + + private function throughTheFrontend(string $path, string $from = '127.0.0.1'): TestResponse + { + return $this->withServerVariables(['REMOTE_ADDR' => $from]) + ->withHeaders([ + 'X-Forwarded-For' => '203.0.113.9', + 'X-Forwarded-Host' => 'app.example.test', + 'X-Forwarded-Proto' => 'https', + 'X-Forwarded-Prefix' => '/backend', + ]) + ->getJson($path); + } +} diff --git a/tests/Feature/Headless/FrontendUnderAPathTest.php b/tests/Feature/Headless/FrontendUnderAPathTest.php new file mode 100644 index 0000000..b9ee3bd --- /dev/null +++ b/tests/Feature/Headless/FrontendUnderAPathTest.php @@ -0,0 +1,116 @@ +headlessEnv['FRONTEND_URL'] = 'https://app.example.test/app/'; + + $this->headlessSetUp(); + } + + public function test_keyring_sends_users_under_the_path() + { + $this->assertSame('https://app.example.test/app', config('app.frontend_url')); + $this->assertSame('https://app.example.test/app/dashboard', config('keyring.home')); + $this->assertSame('https://app.example.test/app/settings/security', config('keyring.enrollment_url')); + $this->assertSame('https://app.example.test/app/settings/security', config('keyring.password_change_url')); + + $this->getJson(route('well-known.passkeys'))->assertJsonPath('enroll', 'https://app.example.test/app/settings/security'); + } + + public function test_signing_in_goes_to_the_dashboard_under_the_path() + { + $user = User::factory()->create(); + + $this->postJson(route('login.store'), ['email' => $user->email, 'password' => 'password']) + ->assertOk() + ->assertJsonPath('redirect', 'https://app.example.test/app/dashboard'); + } + + /** + * Keyring lets through the route at enrollment_url's path, which here + * is the frontend's and not Laravel's, so the security page's JSON is + * let through by name instead. + */ + public function test_someone_without_a_second_factor_still_reaches_the_security_page() + { + $this->actingAs(User::factory()->create())->withAssurance(Assurance::AAL1); + + $this->getJson(route('dashboard')) + ->assertForbidden() + ->assertJson(['status' => 'enroll-first', 'redirect' => 'https://app.example.test/app/settings/security']); + + $this->getJson(route('security.edit'))->assertOk()->assertJsonPath('props.hasSecondFactor', false); + $this->getJson(route('api.me'))->assertOk(); + } + + public function test_someone_held_to_change_their_password_still_reaches_the_security_page() + { + $user = User::factory()->withSecondFactor()->create(); + Keyring::requirePasswordChange($user, 'Reported phished.'); + + $this->actingAs($user)->withAssurance(Assurance::AAL2); + + $this->getJson(route('dashboard')) + ->assertForbidden() + ->assertJson(['status' => 'change-password', 'redirect' => 'https://app.example.test/app/settings/security']); + + $this->getJson(route('security.edit'))->assertOk()->assertJsonPath('props.mustChangePassword', true); + $this->getJson(route('api.me'))->assertOk()->assertJsonPath('auth.user.id', $user->id); + } + + public function test_emailed_links_start_under_the_path() + { + Notification::fake(); + $user = User::factory()->create(); + + $this->postJson(route('password.email'), ['email' => $user->email])->assertOk(); + + Notification::assertSentTo($user, ResetPassword::class, fn (ResetPassword $notification) => str_starts_with( + $notification->toMail($user)->actionUrl, + 'https://app.example.test/app/reset-password/', + )); + } + + /** + * A signed link is signed over Keyring's path, without the frontend's, + * which the frontend leaves off when it asks Laravel. + */ + public function test_a_signed_link_holds_without_the_path() + { + $user = User::factory()->create(); + $this->postJson(route('login.store'), ['email' => $user->email, 'password' => 'password'])->assertOk(); + $this->postJson(route('logout'))->assertNoContent(); + + $link = Device::query()->sole()->revokeUrl(); + + $this->assertStringStartsWith('https://app.example.test/app/devices/', $link); + + $this->getJson(substr($link, strlen('https://app.example.test/app'))) + ->assertOk() + ->assertJsonPath('page', 'device-report'); + } +} diff --git a/tests/Feature/Headless/HeadlessKeyringConformanceTest.php b/tests/Feature/Headless/HeadlessKeyringConformanceTest.php new file mode 100644 index 0000000..3292a47 --- /dev/null +++ b/tests/Feature/Headless/HeadlessKeyringConformanceTest.php @@ -0,0 +1,32 @@ +headlessSetUp(); + } + + protected function tearDown(): void + { + $this->headlessTearDown(); + } + + public function test_the_checks_run_headless() + { + $this->assertSame('headless', config('app.frontend')); + $this->assertFalse(config('keyring.pages')); + } +} diff --git a/tests/Feature/Headless/HeadlessModeTest.php b/tests/Feature/Headless/HeadlessModeTest.php new file mode 100644 index 0000000..7ff9b44 --- /dev/null +++ b/tests/Feature/Headless/HeadlessModeTest.php @@ -0,0 +1,499 @@ +assertSame('headless', config('app.frontend')); + $this->assertSame('https://app.example.test', config('app.frontend_url')); + $this->assertFalse(config('keyring.pages')); + $this->assertSame('https://app.example.test/dashboard', config('keyring.home')); + $this->assertSame('https://app.example.test/settings/security', config('keyring.enrollment_url')); + $this->assertSame('https://app.example.test/settings/security', config('keyring.password_change_url')); + $this->assertContains('api.me', config('keyring.enrollment_except')); + $this->assertContains('security.edit', config('keyring.enrollment_except')); + $this->assertSame(['security.edit', 'api.me'], config('keyring.password_change_except')); + $this->assertSame('127.0.0.1,::1', config('app.trusted_proxies')); + } + + public function test_password_managers_are_sent_to_the_frontends_security_page() + { + $this->getJson(route('well-known.passkeys'))->assertExactJson([ + 'enroll' => 'https://app.example.test/settings/security', + 'manage' => 'https://app.example.test/settings/security', + ]); + } + + public function test_emailed_links_open_the_frontend() + { + Notification::fake(); + $user = User::factory()->create(); + + $this->postJson(route('password.email'), ['email' => $user->email])->assertOk(); + + Notification::assertSentTo($user, ResetPassword::class, fn (ResetPassword $notification) => str_starts_with( + $notification->toMail($user)->actionUrl, + 'https://app.example.test/reset-password/', + )); + } + + public function test_the_verification_email_opens_the_frontend() + { + Notification::fake(); + + $this->postJson(route('register.store'), [ + 'name' => 'Taylor', + 'email' => 'taylor@example.com', + 'password' => 'a-long-new-passphrase', + 'password_confirmation' => 'a-long-new-passphrase', + ])->assertSuccessful(); + + $user = User::query()->where('email', 'taylor@example.com')->sole(); + + Notification::assertSentTo($user, VerifyEmail::class, fn (VerifyEmail $notification) => str_starts_with( + $notification->toMail($user)->actionUrl, + 'https://app.example.test/email/verify/'.$user->id.'/', + )); + } + + /** + * Anything but JSON is a 404, an Inertia visit included: there's no + * Inertia app to answer. + */ + public function test_an_inertia_visit_gets_a_404() + { + $inertia = [ + 'X-Inertia' => 'true', + 'X-Inertia-Version' => (string) (new HandleInertiaRequests)->version(Request::create('/')), + 'X-Requested-With' => 'XMLHttpRequest', + 'Accept' => 'text/html, application/xhtml+xml', + ]; + + $this->withHeaders($inertia)->get(route('home'))->assertNotFound(); + $this->withHeaders($inertia)->get(route('login'))->assertNotFound(); + + $this->actingAs(User::factory()->withSecondFactor()->create()); + + $this->withHeaders($inertia)->get(route('dashboard'))->assertNotFound(); + } + + /** + * A request that isn't JSON from a guest or a held user is sent on, + * as Laravel and Keyring send anyone: a guest to /login, a held user to + * the frontend's security page. Only the rest get the 404. + */ + public function test_a_page_visit_from_a_guest_or_a_held_user_is_redirected() + { + $this->get(route('dashboard'))->assertRedirect(route('login')); + + $this->actingAs(User::factory()->create())->withAssurance(Assurance::AAL1) + ->get(route('dashboard')) + ->assertRedirect('https://app.example.test/settings/security'); + } + + /** + * Only the security page's JSON and /api/me are let through a hold, so + * a held user can't write anything else, nor see the other settings + * (the security page itself still asks for a recent verification). + */ + public function test_a_user_held_to_add_a_second_factor_can_only_read_the_security_page_and_api_me() + { + $user = User::factory()->create(); + $this->actingAs($user)->withAssurance(Assurance::AAL1); + + $this->patchJson(route('profile.update'), ['name' => 'Mallory']) + ->assertForbidden() + ->assertJsonPath('status', 'enroll-first'); + $this->deleteJson(route('profile.destroy')) + ->assertForbidden() + ->assertJsonPath('status', 'enroll-first'); + $this->getJson(route('appearance.edit')) + ->assertForbidden() + ->assertJsonPath('status', 'enroll-first'); + $this->getJson(route('security.edit'))->assertOk(); + $this->getJson(route('api.me'))->assertOk(); + + $this->assertNotSame('Mallory', $user->refresh()->name); + } + + public function test_a_user_held_to_change_their_password_can_only_read_the_security_page_and_api_me() + { + $user = User::factory()->withSecondFactor()->create(); + Keyring::requirePasswordChange($user, 'Reported phished.'); + $this->actingAs($user)->withAssurance(Assurance::AAL2); + + $this->patchJson(route('profile.update'), ['name' => 'Mallory']) + ->assertForbidden() + ->assertJsonPath('status', 'change-password'); + $this->getJson(route('appearance.edit')) + ->assertForbidden() + ->assertJsonPath('status', 'change-password'); + $this->getJson(route('security.edit'))->assertOk(); + $this->getJson(route('api.me'))->assertOk(); + + $this->assertNotSame('Mallory', $user->refresh()->name); + } + + /** + * When Keyring ends the session, /api/me says so once with the + * signed-out 401, then answers as it does for any guest. + */ + public function test_api_me_answers_signed_out_once_when_keyring_ends_the_session() + { + $user = User::factory()->create(); + $this->postJson(route('login.store'), ['email' => $user->email, 'password' => 'password'])->assertOk(); + $this->getJson(route('api.me'))->assertOk()->assertJsonPath('auth.user.id', $user->id); + + // Two hours unused ends a session. + $this->travel(3)->hours(); + + $this->getJson(route('api.me')) + ->assertUnauthorized() + ->assertJsonPath('status', 'signed-out') + ->assertJsonPath('page', 'login'); + + $this->getJson(route('api.me'))->assertOk()->assertJsonPath('auth.user', null); + } + + public function test_the_apps_pages_only_answer_json() + { + $this->get(route('home'))->assertNotFound(); + $this->getJson(route('home'))->assertOk()->assertJsonPath('page', 'welcome'); + + $this->actingAs(User::factory()->withSecondFactor()->create()); + + $this->get(route('dashboard'))->assertNotFound(); + $this->getJson(route('dashboard'))->assertOk()->assertJsonPath('page', 'dashboard'); + } + + /** + * The props are the signed-in user's, so nothing may keep them, as + * Keyring keeps nothing of its own pages. + */ + public function test_the_apps_pages_and_api_me_are_never_cached() + { + $this->getJson(route('home'))->assertHeader('Cache-Control', 'no-store, private'); + $this->getJson(route('api.me'))->assertHeader('Cache-Control', 'no-store, private'); + + $this->actingAs(User::factory()->withSecondFactor()->create()); + + $this->getJson(route('dashboard'))->assertHeader('Cache-Control', 'no-store, private'); + $this->getJson(route('profile.edit'))->assertHeader('Cache-Control', 'no-store, private'); + $this->getJson(route('api.me'))->assertHeader('Cache-Control', 'no-store, private'); + $this->getJson(route('login'))->assertHeader('Cache-Control', 'no-store, private'); + } + + /** + * The appearance page has no props, since the theme is kept in the + * browser, but it answers like every other page. /settings is the + * Inertia app's redirect, which a headless frontend does itself. + */ + public function test_the_appearance_page_answers_json_and_settings_has_no_redirect() + { + $this->actingAs(User::factory()->withSecondFactor()->create()); + + $this->get(route('appearance.edit'))->assertNotFound(); + // An object, not an array: assertExactJson can't tell {} from []. + $this->assertSame( + '{"page":"settings\\/appearance","props":{}}', + $this->getJson(route('appearance.edit'))->assertOk()->getContent(), + ); + + $this->get('/settings')->assertNotFound(); + $this->getJson('/settings')->assertNotFound(); + } + + /** + * Laravel's default CORS config answers api/* for any origin. No other + * origin may read /api/me, since it says who's signed in. + */ + public function test_no_other_origin_may_read_api_me() + { + $this->actingAs(User::factory()->withSecondFactor()->create()); + + $this->withHeader('Origin', 'https://elsewhere.example') + ->getJson(route('api.me')) + ->assertOk() + ->assertHeaderMissing('Access-Control-Allow-Origin') + ->assertHeaderMissing('Access-Control-Allow-Credentials'); + + $this->withHeaders(['Origin' => 'https://elsewhere.example', 'Access-Control-Request-Method' => 'GET']) + ->options(route('api.me')) + ->assertHeaderMissing('Access-Control-Allow-Origin'); + } + + public function test_keyrings_pages_only_answer_json() + { + $this->get(route('login'))->assertNotFound(); + + $this->getJson(route('login')) + ->assertOk() + ->assertExactJson(['page' => 'login', 'props' => ['canResetPassword' => true, 'canRegister' => true, 'status' => null]]); + + $this->getJson(route('register'))->assertOk()->assertJsonPath('page', 'register'); + $this->getJson(route('password.request'))->assertOk()->assertJsonPath('page', 'forgot-password'); + } + + /** + * A sign in sends the user to the frontend's dashboard, and the + * dashboard to the frontend's security page until they have a second + * factor. Laravel's own security page shares that path, so its JSON + * gets through, as does /api/me for the layout. + */ + public function test_signing_in_goes_to_the_frontend() + { + $user = User::factory()->create(); + + $this->postJson(route('login.store'), ['email' => $user->email, 'password' => 'password']) + ->assertOk() + ->assertExactJson(['status' => 'authenticated', 'redirect' => 'https://app.example.test/dashboard', 'alerts' => []]); + + $this->getJson(route('dashboard')) + ->assertForbidden() + ->assertJson(['status' => 'enroll-first', 'redirect' => 'https://app.example.test/settings/security']); + + $this->getJson(route('api.me'))->assertOk()->assertJsonPath('auth.user.id', $user->id); + $this->getJson(route('security.edit'))->assertOk()->assertJsonPath('props.hasSecondFactor', false); + } + + /** + * A sign in answers with its "was this you?" alerts, so a headless + * frontend has them without reading the session. Here the second sign + * in, from a browser the account already knows, got a code wrong first. + */ + public function test_a_sign_in_answers_with_its_was_this_you_alerts() + { + $user = User::factory()->withSecondFactor()->create(); + $secret = $user->keyring->all()->firstWhere('factor', 'totp')->secret; + // The code for the clock as the test has moved it. + $code = fn () => app(Google2FA::class)->oathTotp($secret, intdiv(now()->getTimestamp(), 30)); + + $this->postJson(route('login.store'), ['email' => $user->email, 'password' => 'password'])->assertStatus(202); + + $device = $this->postJson(route('keyring.login.verify', 'totp'), ['code' => $code()]) + ->assertOk() + ->assertExactJson(['status' => 'authenticated', 'redirect' => 'https://app.example.test/dashboard', 'alerts' => []]) + ->getCookie($name = app(DeviceManager::class)->cookie()); + + $this->assertNotNull($device); + $this->postJson(route('logout'))->assertNoContent(); + + $this->travel(1)->minutes(); + + // fetch() sends the browser's cookies with JSON requests. + $this->withCredentials()->withCookie($name, $device->getValue()) + ->postJson(route('login.store'), ['email' => $user->email, 'password' => 'password']) + ->assertStatus(202); + $this->postJson(route('keyring.login.verify', 'totp'), ['code' => '000000'])->assertUnprocessable(); + + $alerts = $this->postJson(route('keyring.login.verify', 'totp'), ['code' => $code()]) + ->assertOk() + ->assertJsonPath('status', 'authenticated') + ->assertJsonPath('redirect', 'https://app.example.test/dashboard') + ->assertJsonPath('alerts.0.type', 'second_factor_failed') + ->assertJsonPath('alerts.0.factor', 'totp') + ->json('alerts'); + + $this->assertCount(1, $alerts); + $this->assertSame(['type', 'factor', 'at', 'ip'], array_keys($alerts[0])); + + // Not handed over a second time: /api/me has no flashed fields. + $this->getJson(route('api.me'))->assertOk()->assertJsonMissingPath('keyringAlerts')->assertJsonMissingPath('status'); + } + + /** + * Opening the emailed verification link signed out answers the status + * with its 401, and flashes nothing for the login page to find. + */ + public function test_a_verification_link_opened_signed_out_answers_sign_in_to_verify() + { + $user = User::factory()->unverified()->create(); + $link = URL::temporarySignedRoute('verification.verify', now()->addHour(), ['id' => $user->id, 'hash' => sha1($user->email)], absolute: false); + + $this->getJson($link) + ->assertUnauthorized() + ->assertExactJson([ + 'status' => 'sign-in-to-verify', + 'message' => __('keyring::status.sign-in-to-verify'), + 'page' => 'login', + 'redirect' => route('login'), + ]); + + $this->getJson(route('login'))->assertOk()->assertJsonPath('props.status', null); + } + + /** + * A challenge with no sign in waiting, such as the frontend's challenge + * page opened on its own or after the sign in expired, names the login + * page with the reason on the email field, rather than redirecting. + */ + public function test_a_challenge_with_no_pending_sign_in_names_the_login_page() + { + foreach ([fn () => $this->getJson(route('keyring.login.challenge')), fn () => $this->postJson(route('keyring.login.verify', 'totp'), ['code' => '123456'])] as $request) { + $request() + ->assertUnprocessable() + ->assertJsonPath('page', 'login') + ->assertJsonValidationErrors('email'); + } + } + + /** + * Where registration hides who has an account, an unverified address + * never gets a signed-in session, so a verified route answers 401. With + * KEYRING_REVEAL_TAKEN=true it does, and Laravel answers 403. + */ + public function test_an_unverified_address_gets_a_401_or_with_reveal_taken_a_403() + { + $user = User::factory()->unverified()->withSecondFactor()->create(); + + // Signing in is refused as if the password were wrong, so there's + // no session, and a verified route answers Laravel's plain 401. + $this->postJson(route('login.store'), ['email' => $user->email, 'password' => 'password']) + ->assertUnprocessable() + ->assertJsonValidationErrors('email'); + $this->assertGuest(); + $this->getJson(route('dashboard')) + ->assertUnauthorized() + ->assertExactJson(['message' => 'Unauthenticated.']); + + config(['keyring.registration.reveal_taken' => true]); + + $this->actingAs($user)->getJson(route('dashboard')) + ->assertForbidden() + ->assertJsonPath('message', 'Your email address is not verified.'); + } + + /** + * The frontend's server passes the browser's requests on, and Laravel + * trusts it (127.0.0.1) to say which host, scheme and prefix they were + * for, so the URLs in Keyring's answers are the browser's. + */ + public function test_urls_are_built_from_the_frontends_forwarded_headers() + { + $this->actingAs(User::factory()->withSecondFactor()->create())->freshAt(now()->subHour()) + ->withServerVariables(['REMOTE_ADDR' => '127.0.0.1']) + ->withHeaders([ + 'X-Forwarded-For' => '203.0.113.9', + 'X-Forwarded-Host' => 'app.example.test', + 'X-Forwarded-Proto' => 'https', + 'X-Forwarded-Prefix' => '/backend', + ]) + ->getJson(route('security.edit', absolute: false)) + ->assertStatus(423) + ->assertJsonPath('redirect', 'https://app.example.test/backend/confirm'); + } + + /** + * The port comes with the forwarded host, as a frontend on + * localhost:3000 sends it: no X-Forwarded-Port needed. + */ + public function test_the_port_comes_from_the_forwarded_host() + { + $this->withServerVariables(['REMOTE_ADDR' => '127.0.0.1']) + ->withHeaders([ + 'X-Forwarded-For' => '203.0.113.9', + 'X-Forwarded-Host' => 'localhost:3000', + 'X-Forwarded-Proto' => 'http', + 'X-Forwarded-Prefix' => '/backend', + ]) + ->getJson('/api/me') + ->assertOk(); + + $this->assertSame('http://localhost:3000/backend', request()->root()); + $this->assertSame('203.0.113.9', request()->ip()); + } + + /** + * Laravel trusts only the four headers the frontend's proxy sets, so an + * X-Forwarded-Port, even from the trusted proxy, is ignored. + */ + public function test_x_forwarded_port_is_ignored_even_from_the_trusted_proxy() + { + $this->withServerVariables(['REMOTE_ADDR' => '127.0.0.1']) + ->withHeaders([ + 'X-Forwarded-Host' => 'app.example.test', + 'X-Forwarded-Proto' => 'https', + 'X-Forwarded-Port' => '8443', + 'X-Forwarded-Prefix' => '/backend', + ]) + ->getJson('/api/me') + ->assertOk(); + + $this->assertSame('https://app.example.test/backend', request()->root()); + $this->assertSame(443, request()->getPort()); + } + + public function test_writes_need_the_csrf_token_or_a_same_origin_fetch() + { + $this->enforceCsrf(); + + $user = User::factory()->withSecondFactor()->create(); + $this->actingAs($user)->withSession(['_token' => 'the-token']); + + // A form posted from another site, or a fetch() without the header. + $this->patchJson(route('profile.update'), ['name' => 'Mallory'])->assertStatus(419); + $this->withHeader('Sec-Fetch-Site', 'cross-site')->patchJson(route('profile.update'), ['name' => 'Mallory'])->assertStatus(419); + $this->withHeader('Sec-Fetch-Site', 'same-site')->patchJson(route('profile.update'), ['name' => 'Mallory'])->assertStatus(419); + $this->flushHeaders()->postJson(route('logout'))->assertStatus(419); + $this->assertSame($user->name, $user->refresh()->name); + + // The browser's own fetch() on one origin. + $this->withHeader('Sec-Fetch-Site', 'same-origin') + ->patchJson(route('profile.update'), ['name' => 'Taylor']) + ->assertOk(); + + // The XSRF-TOKEN cookie's value as a header, as the browser package's + // json() and axios send it. + $this->flushHeaders() + ->withHeader('X-XSRF-TOKEN', Crypt::encrypt(CookieValuePrefix::create('XSRF-TOKEN', Crypt::getKey()).'the-token', false)) + ->patchJson(route('profile.update'), ['name' => 'Otwell']) + ->assertOk(); + + $this->assertSame('Otwell', $user->refresh()->name); + } + + public function test_reads_set_the_xsrf_token_cookie() + { + $this->getJson(route('api.me'))->assertOk()->assertCookie('XSRF-TOKEN'); + } + + /** + * Laravel skips the CSRF check under test. Put it back. + */ + private function enforceCsrf(): void + { + $this->app->bind(PreventRequestForgery::class, fn ($app) => new class($app, $app['encrypter']) extends PreventRequestForgery + { + protected function runningUnitTests() + { + return false; + } + }); + } +} diff --git a/tests/Feature/Headless/KeyringPagesTest.php b/tests/Feature/Headless/KeyringPagesTest.php new file mode 100644 index 0000000..ce16389 --- /dev/null +++ b/tests/Feature/Headless/KeyringPagesTest.php @@ -0,0 +1,116 @@ + false): a JSON + * request gets the page's name and props, and anything else a 404. + */ +class KeyringPagesTest extends TestCase +{ + use RefreshDatabase, RunsHeadless; + + /** + * Every page Keyring renders, by the name it answers with. + */ + private const array PAGES = [ + 'login', 'register', 'forgot-password', 'reset-password', 'verify-email', + 'email-verification', 'email-change', 'device-report', 'challenge', 'confirm', + ]; + + /** + * How to reach each page: the state it needs, then its URL. + * + * @return array + */ + public static function pages(): array + { + return [ + 'login' => ['login', fn () => route('login')], + 'register' => ['register', fn () => route('register')], + 'forgot-password' => ['forgot-password', fn () => route('password.request')], + 'reset-password' => ['reset-password', fn () => route('password.reset', ['token' => 'the-token', 'email' => 'taylor@example.com'])], + // Only an app that says when an address is taken signs in an + // unverified user (KEYRING_REVEAL_TAKEN), so only it has these. + 'verify-email' => ['verify-email', function (self $test) { + config(['keyring.registration.reveal_taken' => true]); + $test->actingAs(User::factory()->unverified()->create()); + + return route('verification.notice'); + }], + 'email-verification' => ['email-verification', function (self $test) { + config(['keyring.registration.reveal_taken' => true]); + $test->actingAs($user = User::factory()->unverified()->create()); + + return URL::temporarySignedRoute('verification.verify', now()->addHour(), ['id' => $user->id, 'hash' => sha1($user->email)], absolute: false); + }], + 'email-change' => ['email-change', function (self $test) { + Notification::fake(); + $user = User::factory()->withSecondFactor()->create(); + + $test->actingAs($user)->withAssurance(Assurance::AAL2) + ->postJson(route('keyring.email.store'), ['email' => 'new@example.com']) + ->assertOk(); + + $change = app(EmailChanges::class)->pending($user); + + return route('keyring.email.confirm', ['change' => $change->getKey(), 'token' => 'the-token']); + }], + 'device-report' => ['device-report', function (self $test) { + // Signing in is what makes a device. + $user = User::factory()->create(); + $test->postJson(route('login.store'), ['email' => $user->email, 'password' => 'password'])->assertOk(); + $test->postJson(route('logout'))->assertNoContent(); + + return Device::query()->sole()->revokeUrl(); + }], + 'challenge' => ['challenge', function (self $test) { + $user = User::factory()->withSecondFactor()->create(); + $test->postJson(route('login.store'), ['email' => $user->email, 'password' => 'password'])->assertStatus(202); + + return route('keyring.login.challenge'); + }], + 'confirm' => ['confirm', function (self $test) { + $test->actingAs(User::factory()->withSecondFactor()->create()); + + return route('keyring.confirm.challenge'); + }], + ]; + } + + public function test_every_page_is_covered() + { + $this->assertEqualsCanonicalizing(self::PAGES, array_column(self::pages(), 0)); + } + + /** + * @param Closure(self): string $url + */ + #[DataProvider('pages')] + public function test_the_page_answers_json_and_nothing_else(string $page, Closure $url) + { + $url = $url($this); + + $this->getJson($url) + ->assertOk() + ->assertExactJsonStructure(['page', 'props']) + ->assertJsonPath('page', $page) + ->assertHeader('Cache-Control', 'no-store, private'); + + // The props are always an object, even when there are none. + $this->assertStringContainsString('"props":{', $this->getJson($url)->getContent()); + + $this->get($url)->assertNotFound(); + } +} diff --git a/tests/Feature/Headless/MeTest.php b/tests/Feature/Headless/MeTest.php new file mode 100644 index 0000000..6408b2d --- /dev/null +++ b/tests/Feature/Headless/MeTest.php @@ -0,0 +1,127 @@ +getJson(route('api.me')) + ->assertOk() + ->assertJson(fn (AssertableJson $json) => $json + ->where('name', config('app.name')) + ->where('auth', ['user' => null]) + ->where('replaceRecoveryCodes', false) + ->where('sidebarOpen', true) + ->missing('status') + ->missing('statusMessage') + ->missing('keyringAlerts') + ->etc()); + } + + public function test_a_signed_in_user_gets_themselves() + { + $user = User::factory()->withSecondFactor()->create(['name' => 'Taylor', 'email' => 'taylor@example.com']); + + $this->actingAs($user)->getJson(route('api.me')) + ->assertOk() + ->assertJson(fn (AssertableJson $json) => $json + ->where('name', config('app.name')) + ->has('auth.user', fn (AssertableJson $user) => $user + ->where('name', 'Taylor') + ->where('email', 'taylor@example.com') + ->whereType('id', 'integer') + ->whereType('email_verified_at', 'string') + ->missing('password') + ->missing('remember_token') + ->etc()) + ->where('replaceRecoveryCodes', false) + ->where('sidebarOpen', true) + ->etc()); + } + + /** + * Keyring flashes statuses and alerts for the next page as well as + * answering them, so reading them here too would show them twice. + */ + public function test_it_leaves_out_what_keyring_flashed() + { + $this->actingAs(User::factory()->withSecondFactor()->create()) + ->withSession(['status' => 'device-revoked', 'keyring.alerts' => [['type' => 'second_factor_failed']]]) + ->getJson(route('api.me')) + ->assertOk() + ->assertJsonMissingPath('status') + ->assertJsonMissingPath('statusMessage') + ->assertJsonMissingPath('keyringAlerts'); + } + + public function test_it_has_the_sidebar_cookie() + { + $this->withCredentials() + ->withUnencryptedCookie('sidebar_state', 'false') + ->getJson(route('api.me')) + ->assertJsonPath('sidebarOpen', false); + } + + /** + * Every page sends someone without a second factor to add one, but the + * page they're sent to needs its layout. + */ + public function test_it_answers_someone_who_still_has_to_add_a_second_factor() + { + $this->actingAs(User::factory()->create())->withAssurance(Assurance::AAL1) + ->getJson(route('api.me')) + ->assertOk() + ->assertJsonPath('auth.user.email', fn (string $email) => $email !== ''); + } + + /** + * Keyring's password hold answers every route but the password change + * page with a 403, and headless mode lets this one through + * (password_change_except), since the frontend's layout needs it. + * Nothing else is. + */ + public function test_it_answers_someone_held_until_they_change_their_password() + { + $user = User::factory()->withSecondFactor()->create(); + Keyring::requirePasswordChange($user, 'Reported phished.'); + + $this->actingAs($user)->withAssurance(Assurance::AAL2) + ->getJson(route('dashboard')) + ->assertForbidden() + ->assertJsonPath('status', 'change-password'); + + $this->getJson(route('api.me'))->assertOk()->assertJsonPath('auth.user.id', $user->id); + $this->getJson(route('security.edit'))->assertOk()->assertJsonPath('props.mustChangePassword', true); + $this->getJson(route('profile.edit'))->assertForbidden()->assertJsonPath('status', 'change-password'); + $this->getJson(route('keyring.devices.index'))->assertForbidden()->assertJsonPath('status', 'change-password'); + } + + public function test_it_says_when_to_make_new_recovery_codes() + { + $user = User::factory()->withSecondFactor()->create(); + $codes = Authenticator::factory()->recoveryCodes()->for($user, 'authenticatable')->create(); + + $this->actingAs($user)->getJson(route('api.me'))->assertJsonPath('replaceRecoveryCodes', false); + + $codes->forceFill(['meta' => [...$codes->meta ?? [], RecoveryCodes::USED_AT => now()->getTimestamp()]])->save(); + + $this->actingAs($user->fresh())->getJson(route('api.me'))->assertJsonPath('replaceRecoveryCodes', true); + } +} diff --git a/tests/Feature/Headless/PageResponseTest.php b/tests/Feature/Headless/PageResponseTest.php new file mode 100644 index 0000000..387834c --- /dev/null +++ b/tests/Feature/Headless/PageResponseTest.php @@ -0,0 +1,62 @@ + 'value', + 'lazy' => fn () => ['count' => 2], + 'always' => Inertia::always(fn () => 'kept'), + ]))->toResponse($this->jsonRequest()); + + $this->assertSame( + '{"page":"dashboard","props":{"plain":"value","lazy":{"count":2},"always":"kept"}}', + $response->getContent(), + ); + } + + /** + * @return array + */ + public static function wrappers(): array + { + return [ + 'defer' => [fn () => Inertia::defer(fn () => 1)], + 'optional' => [fn () => Inertia::optional(fn () => 1)], + 'merge' => [fn () => Inertia::merge([1])], + 'deep merge' => [fn () => Inertia::deepMerge([1])], + 'once' => [fn () => Inertia::once(fn () => 1)], + 'scroll' => [fn () => Inertia::scroll([1])], + 'a closure returning one' => [fn () => fn () => Inertia::defer(fn () => 1)], + ]; + } + + #[DataProvider('wrappers')] + public function test_inertia_only_props_are_refused(\Closure $wrapper) + { + $this->expectException(LogicException::class); + $this->expectExceptionMessage('The [items] prop of the [dashboard] page is'); + + (new PageResponse('dashboard', ['items' => $wrapper()]))->toResponse($this->jsonRequest()); + } + + private function jsonRequest(): Request + { + return Request::create('/dashboard', server: ['HTTP_ACCEPT' => 'application/json']); + } +} diff --git a/tests/Feature/Headless/PagesAsJsonTest.php b/tests/Feature/Headless/PagesAsJsonTest.php new file mode 100644 index 0000000..1a840c0 --- /dev/null +++ b/tests/Feature/Headless/PagesAsJsonTest.php @@ -0,0 +1,198 @@ +assertSame('inertia', config('app.frontend')); + $this->assertTrue(config('keyring.pages')); + $this->assertSame('/dashboard', config('keyring.home')); + $this->assertSame('/settings/security', config('keyring.enrollment_url')); + $this->assertSame('/settings/security', config('keyring.password_change_url')); + } + + public function test_the_welcome_page_and_the_dashboard_answer_with_their_names() + { + $this->getJson(route('home')) + ->assertOk() + ->assertJson(fn (AssertableJson $json) => $json->where('page', 'welcome')->has('props')); + + $this->actingAs(User::factory()->withSecondFactor()->create()) + ->getJson(route('dashboard')) + ->assertOk() + ->assertJson(fn (AssertableJson $json) => $json->where('page', 'dashboard')->has('props')); + } + + public function test_the_appearance_page_has_no_props() + { + // An object, not an array: assertExactJson can't tell {} from []. + $this->assertSame( + '{"page":"settings\\/appearance","props":{}}', + $this->actingAs(User::factory()->withSecondFactor()->create()) + ->getJson(route('appearance.edit')) + ->assertOk() + ->getContent(), + ); + + $this->get(route('appearance.edit')) + ->assertOk() + ->assertInertia(fn (Assert $page) => $page->component('settings/appearance')); + } + + public function test_the_profile_page_has_the_pending_email_change() + { + $user = User::factory()->withSecondFactor()->create(); + + $this->actingAs($user)->getJson(route('profile.edit')) + ->assertOk() + ->assertExactJson(['page' => 'settings/profile', 'props' => ['mustVerifyEmail' => true, 'pendingEmail' => null]]); + + Notification::fake(); + + $this->withAssurance(Assurance::AAL2) + ->postJson(route('keyring.email.store'), ['email' => 'new@example.com']) + ->assertOk() + ->assertJsonPath('status', 'email-change-requested'); + + $this->getJson(route('profile.edit')) + ->assertOk() + ->assertJsonPath('props.pendingEmail.email', 'new@example.com') + ->assertJsonPath('props.pendingEmail.confirmed', false) + ->assertJsonStructure(['props' => ['pendingEmail' => ['email', 'confirmed', 'needsCurrentConfirmation', 'expiresAt']]]); + } + + public function test_the_security_page_has_everything_the_inertia_page_gets() + { + $user = User::factory()->create(); + $totp = Authenticator::factory()->totp()->for($user, 'authenticatable')->create(['name' => '1Password']); + + $this->actingAs($user)->withAssurance(Assurance::AAL2) + ->getJson(route('security.edit')) + ->assertOk() + ->assertJsonPath('page', 'settings/security') + ->assertJsonPath('props.authenticators.0.id', $totp->id) + ->assertJsonPath('props.authenticators.0.name', '1Password') + ->assertJsonPath('props.assurance', 'AAL2') + ->assertJsonPath('props.hasSecondFactor', true) + ->assertJsonPath('props.mustChangePassword', false) + ->assertJsonCount(1, 'props.sessions') + ->assertJsonPath('props.sessions.0.current', true) + ->assertJsonStructure(['props' => ['authenticators', 'enrollable', 'devices', 'sessions', 'activity']]); + } + + public function test_guests_get_a_401() + { + $this->getJson(route('dashboard'))->assertUnauthorized()->assertExactJson(['message' => 'Unauthenticated.']); + $this->getJson(route('profile.edit'))->assertUnauthorized(); + $this->getJson(route('security.edit'))->assertUnauthorized(); + $this->patchJson(route('profile.update'), ['name' => 'Someone'])->assertUnauthorized(); + $this->deleteJson(route('profile.destroy'))->assertUnauthorized(); + } + + public function test_the_security_page_needs_a_recent_verification() + { + $user = User::factory()->withSecondFactor()->create(); + + $this->actingAs($user)->freshAt(now()->subHour()) + ->getJson(route('security.edit')) + ->assertStatus(423) + ->assertJsonPath('redirect', route('keyring.confirm.challenge')); + } + + public function test_someone_without_a_second_factor_is_sent_to_add_one_but_can_reach_the_security_page() + { + $user = User::factory()->create(); + + $this->actingAs($user)->withAssurance(Assurance::AAL1) + ->getJson(route('profile.edit')) + ->assertForbidden() + ->assertJson(['status' => 'enroll-first', 'redirect' => '/settings/security']); + + $this->getJson(route('security.edit')) + ->assertOk() + ->assertJsonPath('props.hasSecondFactor', false); + } + + public function test_the_name_is_updated_with_a_status_in_the_body() + { + $user = User::factory()->withSecondFactor()->create(); + + $this->actingAs($user) + ->patchJson(route('profile.update'), ['name' => 'Test User']) + ->assertOk() + ->assertExactJson(['status' => 'profile-updated', 'message' => 'Profile updated.']); + + $this->assertSame('Test User', $user->refresh()->name); + + $this->patchJson(route('profile.update'), ['name' => '']) + ->assertUnprocessable() + ->assertJsonValidationErrors('name'); + } + + public function test_deleting_the_account_needs_a_recent_verification() + { + $user = User::factory()->withSecondFactor()->create(); + + $this->actingAs($user)->freshAt(now()->subHour()) + ->deleteJson(route('profile.destroy')) + ->assertStatus(423) + ->assertJsonPath('redirect', route('keyring.confirm.challenge')); + + $this->assertNotNull($user->fresh()); + } + + public function test_deleting_the_account_answers_204() + { + $user = User::factory()->withSecondFactor()->create(); + + $this->actingAs($user)->withAssurance(Assurance::AAL2) + ->deleteJson(route('profile.destroy')) + ->assertNoContent(); + + $this->assertGuest(); + $this->assertNull($user->fresh()); + } + + /** + * An Inertia visit sends X-Requested-With too, so it would count as JSON + * if it weren't told apart by its X-Inertia header. + */ + public function test_inertia_visits_still_get_the_inertia_page() + { + $this->actingAs(User::factory()->withSecondFactor()->create()); + + $version = app(HandleInertiaRequests::class)->version(Request::create('/')); + + $this->withHeaders(['X-Inertia' => 'true', 'X-Inertia-Version' => (string) $version, 'X-Requested-With' => 'XMLHttpRequest']) + ->get(route('dashboard')) + ->assertOk() + ->assertHeader('X-Inertia', 'true') + ->assertJsonPath('component', 'dashboard') + ->assertJsonPath('props.auth.user.email', fn (string $email) => $email !== '') + ->assertJsonMissingPath('page'); + + $this->flushHeaders()->get(route('dashboard')) + ->assertOk() + ->assertInertia(fn (Assert $page) => $page->component('dashboard')->has('keyringAlerts')->has('status')); + } +} diff --git a/tests/Feature/Headless/RunsHeadless.php b/tests/Feature/Headless/RunsHeadless.php new file mode 100644 index 0000000..b5ae617 --- /dev/null +++ b/tests/Feature/Headless/RunsHeadless.php @@ -0,0 +1,86 @@ + + */ + protected array $headlessEnv = [ + 'APP_FRONTEND' => 'headless', + 'FRONTEND_URL' => 'https://app.example.test', + 'TRUSTED_PROXIES' => '', + ]; + + /** + * What each variable was before, null when it wasn't set. + * + * @var array + */ + private array $envBeforeHeadless = []; + + protected function setUp(): void + { + foreach ($this->headlessEnv as $key => $value) { + $this->envBeforeHeadless[$key] = [ + 'env' => $_ENV[$key] ?? null, + 'server' => $_SERVER[$key] ?? null, + 'getenv' => getenv($key), + ]; + + $_ENV[$key] = $_SERVER[$key] = $value; + putenv("{$key}={$value}"); + } + + // The app has to boot with them, so they're set first. If booting + // fails, PHPUnit skips tearDown(), so they're put back here, or + // they'd leak into the next tests in this process. + try { + parent::setUp(); + } catch (Throwable $e) { + $this->restoreEnvBeforeHeadless(); + + throw $e; + } + } + + protected function tearDown(): void + { + try { + parent::tearDown(); + } finally { + $this->restoreEnvBeforeHeadless(); + } + } + + private function restoreEnvBeforeHeadless(): void + { + foreach ($this->envBeforeHeadless as $key => $before) { + if ($before['env'] === null) { + unset($_ENV[$key]); + } else { + $_ENV[$key] = $before['env']; + } + + if ($before['server'] === null) { + unset($_SERVER[$key]); + } else { + $_SERVER[$key] = $before['server']; + } + + putenv($before['getenv'] === false ? $key : "{$key}={$before['getenv']}"); + } + + $this->envBeforeHeadless = []; + } +} diff --git a/tests/Feature/Headless/RunsHeadlessTest.php b/tests/Feature/Headless/RunsHeadlessTest.php new file mode 100644 index 0000000..bdef64f --- /dev/null +++ b/tests/Feature/Headless/RunsHeadlessTest.php @@ -0,0 +1,44 @@ +setUp(); + } + }; + + try { + $case->boot(); + $this->fail('Booting should have failed.'); + } catch (RuntimeException $e) { + $this->assertSame('The app failed to boot.', $e->getMessage()); + } + + $this->assertSame($before, getenv('APP_FRONTEND')); + $this->assertSame($before === false ? null : $before, $_ENV['APP_FRONTEND'] ?? null); + $this->assertSame('inertia', config('app.frontend')); + } +} diff --git a/tests/Feature/TrustedProxiesTest.php b/tests/Feature/TrustedProxiesTest.php new file mode 100644 index 0000000..5188ad1 --- /dev/null +++ b/tests/Feature/TrustedProxiesTest.php @@ -0,0 +1,33 @@ +assertNull(config('app.trusted_proxies')); + + $this->withServerVariables(['REMOTE_ADDR' => '127.0.0.1']) + ->withHeaders([ + 'X-Forwarded-For' => '203.0.113.9', + 'X-Forwarded-Host' => 'app.example.test', + 'X-Forwarded-Proto' => 'https', + 'X-Forwarded-Prefix' => '/backend', + ]) + ->get(route('home')) + ->assertOk(); + + $this->assertSame('127.0.0.1', request()->ip()); + $this->assertSame(rtrim(config('app.url'), '/'), request()->root()); + } +}