From 9871a20bc61b41f82ab751232e2ae0fde902ea1c Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:03:28 +0000 Subject: [PATCH 01/36] fix(kits): resolve a local path before trusting it, so a ?redirect= like /.//elsewhere.example is turned down --- kits/nuxt/README.md | 2 +- kits/nuxt/app/keyring/navigate.test.ts | 17 +++++++ kits/nuxt/app/lib/guards.test.ts | 16 ++++++ kits/nuxt/app/lib/local-path.ts | 49 +++++++++++++++---- kits/tanstack-start/README.md | 2 +- .../src/keyring/navigate.test.ts | 17 +++++++ kits/tanstack-start/src/lib/local-path.ts | 49 +++++++++++++++---- kits/tanstack-start/src/routes/guards.test.ts | 16 ++++++ 8 files changed, 148 insertions(+), 20 deletions(-) diff --git a/kits/nuxt/README.md b/kits/nuxt/README.md index a3b46a3..eedba38 100644 --- a/kits/nuxt/README.md +++ b/kits/nuxt/README.md @@ -221,7 +221,7 @@ Every page starts with `GET /api/me` (`app/middleware/01.me.global.ts`), on the Pages render on the server, so a form can be sent before Vue has taken it over. Every form has `method="post"` (`app/forms.test.ts` checks), so one sent that early never puts what was typed, a password included, in the address. Anything typed into a field before then is kept: hydrating a field with `v-model` would empty it, so `app/plugins/typed-before-hydration.client.ts` notes what's typed until the app has hydrated, and gives it back. And a field with `autofocus` only takes the focus as it mounts when nobody's typing in another field, so the rest of a password typed before then doesn't land in the email field. -`?redirect=` only ever holds a path on this site, one that starts with a single `/` and has no control characters (`app/lib/local-path.ts`). A `redirect` in Keyring's answers is followed by its path only, under the same rule. +`?redirect=` only ever holds a path on this site, one that starts with a single `/` and has no control characters (`app/lib/local-path.ts`). It's resolved the way the browser reads it before it's followed, and what's followed is that resolved path, which has to start with a single `/` too, so `/.//elsewhere.example` and `/x/..//elsewhere.example` (both `//elsewhere.example` once resolved) are turned down. A `redirect` in Keyring's answers is followed by its path only, under the same rule. Signing out (`app/keyring/sign-out.ts`) only leaves the page once `POST /logout` has worked, and forgets the sign-in alerts and the held page kept for the user. When it fails, the reason shows in a toast (or beside the button, on the verify-email pages). diff --git a/kits/nuxt/app/keyring/navigate.test.ts b/kits/nuxt/app/keyring/navigate.test.ts index 0c6d4f3..73b430c 100644 --- a/kits/nuxt/app/keyring/navigate.test.ts +++ b/kits/nuxt/app/keyring/navigate.test.ts @@ -125,4 +125,21 @@ describe('local paths', () => { expect(localPath(42)).toBeUndefined(); expect(localPath(undefined)).toBeUndefined(); }); + + test('a path that only resolves to another site', () => { + expect(localPath('/.//evil.example')).toBeUndefined(); + expect(localPath('/x/..//evil.example')).toBeUndefined(); + expect(localPath('/.\\/evil.example')).toBeUndefined(); + expect(localPath('/./\\evil.example')).toBeUndefined(); + expect(localPath('/%2e//evil.example')).toBeUndefined(); + expect(localPath('/.//evil.example\t')).toBeUndefined(); + }); + + test('the path as the browser reads it', () => { + expect(localPath('/settings/../dashboard')).toBe('/dashboard'); + expect(localPath('/./settings/profile?x=1#y')).toBe( + '/settings/profile?x=1#y', + ); + expect(localPath('/a\\b')).toBe('/a/b'); + }); }); diff --git a/kits/nuxt/app/lib/guards.test.ts b/kits/nuxt/app/lib/guards.test.ts index f40ad83..a1e7473 100644 --- a/kits/nuxt/app/lib/guards.test.ts +++ b/kits/nuxt/app/lib/guards.test.ts @@ -118,4 +118,20 @@ describe('pages for guests', () => { await guard(guest, me(true), '/login?redirect=%2F%2Fevil.example'), ).toBe('/dashboard'); }); + + test('never to a ?redirect= that resolves to another site', async () => { + for (const redirect of [ + '/.//evil.example', + '/x/..//evil.example', + '/.\\/evil.example', + ]) { + expect( + await guard( + guest, + me(true), + `/login?${new URLSearchParams({ redirect })}`, + ), + ).toBe('/dashboard'); + } + }); }); diff --git a/kits/nuxt/app/lib/local-path.ts b/kits/nuxt/app/lib/local-path.ts index 10142d8..6c6414b 100644 --- a/kits/nuxt/app/lib/local-path.ts +++ b/kits/nuxt/app/lib/local-path.ts @@ -1,16 +1,47 @@ +const origin = 'http://frontend.invalid'; + /** * A path on this site, or undefined: one that starts with a single "/", - * without control characters. Anyone can send a link with - * ?redirect=https://elsewhere.example, or "//elsewhere.example", or - * "/\elsewhere.example", which browsers all read as another site. They do - * the same with "//elsewhere.example", since they drop tabs and + * without control characters, as the browser reads it. Anyone can send a + * link with ?redirect=https://elsewhere.example, or "//elsewhere.example", + * or "/\elsewhere.example", which browsers all read as another site. They + * do the same with "//elsewhere.example", since they drop tabs and * newlines from a URL before reading it. + * + * A path that starts well can still resolve to one that doesn't: + * "/.//elsewhere.example" and "/x/..//elsewhere.example" both have the path + * "//elsewhere.example". So the value is resolved first, and what's + * returned is that resolved path (its query and fragment kept), checked + * again. */ export function localPath(value: unknown): string | undefined { - return typeof value === 'string' && - /^\/(?![/\\])/.test(value) && + if ( + typeof value !== 'string' || + !startsLocal(value) || // eslint-disable-next-line no-control-regex - !/[\u0000-\u001f\u007f]/.test(value) - ? value - : undefined; + /[\u0000-\u001f\u007f]/.test(value) + ) { + return undefined; + } + + let url: URL; + + try { + url = new URL(value, origin); + } catch { + return undefined; + } + + if (url.origin !== origin) { + return undefined; + } + + const path = url.pathname + url.search + url.hash; + + return startsLocal(path) ? path : undefined; +} + +/** Starts with one "/", not "//" or "/\". */ +function startsLocal(path: string): boolean { + return /^\/(?![/\\])/.test(path); } diff --git a/kits/tanstack-start/README.md b/kits/tanstack-start/README.md index 5be559c..4afeccc 100644 --- a/kits/tanstack-start/README.md +++ b/kits/tanstack-start/README.md @@ -194,7 +194,7 @@ The root route loads `GET /api/me` for every page, on the server and in the brow Pages render on the server, so a form can be sent before React has taken it over. Every form has `method="post"` (`src/forms.test.ts` checks), so one sent that early never puts what was typed, a password included, in the address. -`?redirect=` only ever holds a path on this site, one that starts with a single `/` and has no control characters (`src/lib/local-path.ts`). A `redirect` in Keyring's answers is followed by its path only, under the same rule. +`?redirect=` only ever holds a path on this site, one that starts with a single `/` and has no control characters (`src/lib/local-path.ts`). It's resolved the way the browser reads it before it's followed, and what's followed is that resolved path, which has to start with a single `/` too, so `/.//elsewhere.example` and `/x/..//elsewhere.example` (both `//elsewhere.example` once resolved) are turned down. A `redirect` in Keyring's answers is followed by its path only, under the same rule. Signing out (`src/keyring/sign-out.ts`) only leaves the page once `POST /logout` has worked, and forgets the sign-in alerts and the held page kept for the user. When it fails, the reason shows in a toast (or beside the button, on the verify-email pages). diff --git a/kits/tanstack-start/src/keyring/navigate.test.ts b/kits/tanstack-start/src/keyring/navigate.test.ts index f7a1067..e0ede33 100644 --- a/kits/tanstack-start/src/keyring/navigate.test.ts +++ b/kits/tanstack-start/src/keyring/navigate.test.ts @@ -125,4 +125,21 @@ describe('local paths', () => { expect(localPath(42)).toBeUndefined(); expect(localPath(undefined)).toBeUndefined(); }); + + test('a path that only resolves to another site', () => { + expect(localPath('/.//evil.example')).toBeUndefined(); + expect(localPath('/x/..//evil.example')).toBeUndefined(); + expect(localPath('/.\\/evil.example')).toBeUndefined(); + expect(localPath('/./\\evil.example')).toBeUndefined(); + expect(localPath('/%2e//evil.example')).toBeUndefined(); + expect(localPath('/.//evil.example\t')).toBeUndefined(); + }); + + test('the path as the browser reads it', () => { + expect(localPath('/settings/../dashboard')).toBe('/dashboard'); + expect(localPath('/./settings/profile?x=1#y')).toBe( + '/settings/profile?x=1#y', + ); + expect(localPath('/a\\b')).toBe('/a/b'); + }); }); diff --git a/kits/tanstack-start/src/lib/local-path.ts b/kits/tanstack-start/src/lib/local-path.ts index 10142d8..6c6414b 100644 --- a/kits/tanstack-start/src/lib/local-path.ts +++ b/kits/tanstack-start/src/lib/local-path.ts @@ -1,16 +1,47 @@ +const origin = 'http://frontend.invalid'; + /** * A path on this site, or undefined: one that starts with a single "/", - * without control characters. Anyone can send a link with - * ?redirect=https://elsewhere.example, or "//elsewhere.example", or - * "/\elsewhere.example", which browsers all read as another site. They do - * the same with "//elsewhere.example", since they drop tabs and + * without control characters, as the browser reads it. Anyone can send a + * link with ?redirect=https://elsewhere.example, or "//elsewhere.example", + * or "/\elsewhere.example", which browsers all read as another site. They + * do the same with "//elsewhere.example", since they drop tabs and * newlines from a URL before reading it. + * + * A path that starts well can still resolve to one that doesn't: + * "/.//elsewhere.example" and "/x/..//elsewhere.example" both have the path + * "//elsewhere.example". So the value is resolved first, and what's + * returned is that resolved path (its query and fragment kept), checked + * again. */ export function localPath(value: unknown): string | undefined { - return typeof value === 'string' && - /^\/(?![/\\])/.test(value) && + if ( + typeof value !== 'string' || + !startsLocal(value) || // eslint-disable-next-line no-control-regex - !/[\u0000-\u001f\u007f]/.test(value) - ? value - : undefined; + /[\u0000-\u001f\u007f]/.test(value) + ) { + return undefined; + } + + let url: URL; + + try { + url = new URL(value, origin); + } catch { + return undefined; + } + + if (url.origin !== origin) { + return undefined; + } + + const path = url.pathname + url.search + url.hash; + + return startsLocal(path) ? path : undefined; +} + +/** Starts with one "/", not "//" or "/\". */ +function startsLocal(path: string): boolean { + return /^\/(?![/\\])/.test(path); } diff --git a/kits/tanstack-start/src/routes/guards.test.ts b/kits/tanstack-start/src/routes/guards.test.ts index 599d1d9..ece6ce5 100644 --- a/kits/tanstack-start/src/routes/guards.test.ts +++ b/kits/tanstack-start/src/routes/guards.test.ts @@ -117,4 +117,20 @@ describe('pages for guests', () => { ), ).toBe('/dashboard'); }); + + test('never to a ?redirect= that resolves to another site', async () => { + for (const redirect of [ + '/.//evil.example', + '/x/..//evil.example', + '/.\\/evil.example', + ]) { + expect( + await guard( + Guest, + { me: me(true) }, + `/login?${new URLSearchParams({ redirect })}`, + ), + ).toBe('/dashboard'); + } + }); }); From f586dccb574fc6540840149f6c8a80da1fc3d59d Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:04:39 +0000 Subject: [PATCH 02/36] fix(nuxt): collapse a leading slash and backslash too, so /\elsewhere.example/backend/x is never read with that host --- kits/nuxt/server/lib/incoming.test.ts | 46 +++++++++++++++++++++++++++ kits/nuxt/server/lib/incoming.ts | 5 +-- 2 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 kits/nuxt/server/lib/incoming.test.ts diff --git a/kits/nuxt/server/lib/incoming.test.ts b/kits/nuxt/server/lib/incoming.test.ts new file mode 100644 index 0000000..8c5aba8 --- /dev/null +++ b/kits/nuxt/server/lib/incoming.test.ts @@ -0,0 +1,46 @@ +import { createEvent, type H3Event } from 'h3'; +import { IncomingMessage, ServerResponse } from 'node:http'; +import { Socket } from 'node:net'; +import { describe, expect, test } from 'vite-plus/test'; +import { incomingUrl, requestPath } from './incoming'; + +/** A request as h3 hands it over, with `url` as its request line's target. */ +function request(url: string): H3Event { + const req = new IncomingMessage(new Socket()); + req.url = url; + req.method = 'GET'; + req.headers = { host: 'localhost:3765' }; + + return createEvent(req, new ServerResponse(req)); +} + +describe("the request line's path", () => { + test('is read as a path on this server', () => { + expect(requestPath(request('/backend/user?x=1'))).toBe('/backend/user'); + expect(incomingUrl(request('/backend/user?x=1')).href).toBe( + 'http://localhost:3765/backend/user?x=1', + ); + }); + + test('never names another host, however its slashes start', () => { + for (const target of [ + '//evil.example/backend/x', + '/\\evil.example/backend/x', + '/\\/evil.example/backend/x', + ]) { + const url = incomingUrl(request(target)); + + expect(url.host).toBe('localhost:3765'); + expect(url.pathname).toBe('/evil.example/backend/x'); + expect(requestPath(request(target))).toBe( + '/evil.example/backend/x', + ); + } + }); + + test('an absolute target counts by its path only', () => { + expect( + incomingUrl(request('http://evil.example/backend/x?y=1')).href, + ).toBe('http://localhost:3765/backend/x?y=1'); + }); +}); diff --git a/kits/nuxt/server/lib/incoming.ts b/kits/nuxt/server/lib/incoming.ts index b8398e6..84d6f89 100644 --- a/kits/nuxt/server/lib/incoming.ts +++ b/kits/nuxt/server/lib/incoming.ts @@ -97,8 +97,9 @@ function pathOf(req: IncomingMessage): string { } } - // "//elsewhere" would otherwise be read as a host. - return target.replace(/^\/{2,}/, '/'); + // "//elsewhere" would otherwise be read as a host, and so would + // "/\elsewhere": a URL parser reads a backslash as a slash. + return target.replace(/^[/\\]{2,}/, '/'); } /** From fae3e7cb8a0896dc3b6634c7a228c15672c09b23 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:15:52 +0000 Subject: [PATCH 03/36] test(nuxt): check the pages emailed links open get their route rules at any case and with a trailing slash --- kits/nuxt/README.md | 2 +- kits/nuxt/test/build.test.mjs | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/kits/nuxt/README.md b/kits/nuxt/README.md index eedba38..78d8dd5 100644 --- a/kits/nuxt/README.md +++ b/kits/nuxt/README.md @@ -215,7 +215,7 @@ Keyring's routes have no prefix in this backend, so the pages are at Keyring's o | `/devices/{device}/report` | emailed | | `/dashboard`, `/settings/*` | need a session: a guest goes to `/login?redirect=` | -The pages emailed links open are sent with `Referrer-Policy: no-referrer` and `Cache-Control: no-store`, and render only in the browser (`ssr: false`), their route rules in `nuxt.config.ts`, so the request that checks the link comes from the user's own address. Their address, with its token, never goes into another page's `?redirect=`. A link Laravel turns down (a `403`, `404` or `410`) says the link doesn't work. Any other failure, such as no answer or a `429`, says to try again. Keep analytics, session replay and error reporters off these pages. +The pages emailed links open are sent with `Referrer-Policy: no-referrer` and `Cache-Control: no-store`, and render only in the browser (`ssr: false`), their route rules in `nuxt.config.ts`, so the request that checks the link comes from the user's own address. Vue Router matches a path whatever its case, and Nuxt folds the case of the route rules to match, so `/Reset-Password/` gets the same rules (`test/build.test.mjs` checks). To make routes case-sensitive, set `router.options.sensitive` in `nuxt.config.ts`, where Nuxt reads it for the route rules too, not only in `app/router.options.ts`. Their address, with its token, never goes into another page's `?redirect=`. A link Laravel turns down (a `403`, `404` or `410`) says the link doesn't work. Any other failure, such as no answer or a `429`, says to try again. Keep analytics, session replay and error reporters off these pages. Every page starts with `GET /api/me` (`app/middleware/01.me.global.ts`), on the server and in the browser, on every visit. When Keyring has ended the session, that answers a `401` `signed-out` once: a page that needs a session sends the user to the login page with Keyring's message. Each signed-in page also loads its own JSON from Laravel in its middleware (`loadPage()` in `app/lib/page.ts`), every time it's visited, as an Inertia visit does, so Laravel decides whether the user may see it: a `403` `enroll-first` or `change-password` goes to `/settings/security`, with Keyring's reason, and a `423` to `/confirm` and back. Anything else that fails, `/api/me` included, shows Nuxt's error page (`app/error.vue`), rather than an empty form: in the browser too, where the middleware throws it as a fatal error (`app/lib/load-failed.ts`), since Nuxt otherwise only cancels the navigation and shows nothing. On the server, a page that sends the browser elsewhere answers a `302` straight away (`app/lib/redirect.ts`), without rendering, or reading from Laravel for, the page it sends it to. When the browser takes over a page the server rendered, the middleware doesn't run again: what it loaded came with the page. diff --git a/kits/nuxt/test/build.test.mjs b/kits/nuxt/test/build.test.mjs index eac31c4..4a8867b 100644 --- a/kits/nuxt/test/build.test.mjs +++ b/kits/nuxt/test/build.test.mjs @@ -183,9 +183,22 @@ void describe('the built server', () => { assert.equal(response.headers.get('x-powered-by'), null); }); + // Vue Router matches a path whatever its case, and Nuxt folds the case + // of the route rules to match, so /Reset-Password/ opens the + // page with its rules too, never rendered on the server without them. void test('renders the pages emailed links open in the browser only, with no referrer', async () => { - for (const route of emailedLinkRoutes) { + const paths = emailedLinkRoutes.flatMap((route) => { const path = route.replaceAll('*', 'x'); + + return [ + path, + path.replace(/(?<=\/)[a-z]/g, (letter) => letter.toUpperCase()), + path.toUpperCase(), + `${path}/`, + ]; + }); + + for (const path of paths) { const { response, body } = await get(path); assert.equal(response.status, 200, path); From 51195e0c1a026ef8eac52b91072ee85b25ce7812 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:06:23 +0000 Subject: [PATCH 04/36] fix(kits): recognise an emailed link opened with a trailing slash or at another case --- kits/nuxt/app/lib/emailed-links.test.ts | 13 ++++++ kits/nuxt/app/lib/emailed-links.ts | 15 +++++-- .../src/lib/emailed-links.test.ts | 42 +++++++++++++++++++ kits/tanstack-start/src/lib/emailed-links.ts | 20 +++++---- 4 files changed, 80 insertions(+), 10 deletions(-) create mode 100644 kits/tanstack-start/src/lib/emailed-links.test.ts diff --git a/kits/nuxt/app/lib/emailed-links.test.ts b/kits/nuxt/app/lib/emailed-links.test.ts index 0694e57..0551590 100644 --- a/kits/nuxt/app/lib/emailed-links.test.ts +++ b/kits/nuxt/app/lib/emailed-links.test.ts @@ -13,6 +13,19 @@ describe('the pages emailed links open', () => { } }); + test('with a trailing slash, or at another case', () => { + for (const path of [ + '/reset-password/token/', + '/email/verify/1/hash/', + '/email-changes/1/confirm/token/', + '/devices/1/report/', + '/Reset-Password/token', + '/DEVICES/1/Report/', + ]) { + expect(isEmailedLink(path), path).toBe(true); + } + }); + test('and no others', () => { for (const path of [ '/reset-password', diff --git a/kits/nuxt/app/lib/emailed-links.ts b/kits/nuxt/app/lib/emailed-links.ts index 1ea849e..439990b 100644 --- a/kits/nuxt/app/lib/emailed-links.ts +++ b/kits/nuxt/app/lib/emailed-links.ts @@ -11,11 +11,20 @@ export const emailedLinkRoutes = [ '/devices/*/report', ] as const; +/** + * The same, matched whatever their case, as Vue Router matches the routes + * (and Nuxt the route rules). + */ const emailedLinks = emailedLinkRoutes.map( - (route) => new RegExp(`^${route.replaceAll('*', '[^/]+')}$`), + (route) => new RegExp(`^${route.replaceAll('*', '[^/]+')}$`, 'i'), ); -/** Whether a path (without its query) is a page an emailed link opens. */ +/** + * Whether a path (without its query) is a page an emailed link opens, with + * or without a trailing slash, which the router opens the page with too. + */ export function isEmailedLink(pathname: string): boolean { - return emailedLinks.some((pattern) => pattern.test(pathname)); + const path = pathname.replace(/\/+$/, ''); + + return emailedLinks.some((pattern) => pattern.test(path)); } diff --git a/kits/tanstack-start/src/lib/emailed-links.test.ts b/kits/tanstack-start/src/lib/emailed-links.test.ts new file mode 100644 index 0000000..0551590 --- /dev/null +++ b/kits/tanstack-start/src/lib/emailed-links.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, test } from 'vite-plus/test'; +import { isEmailedLink } from './emailed-links'; + +describe('the pages emailed links open', () => { + test('are these, at Keyring’s paths', () => { + for (const path of [ + '/reset-password/token', + '/email/verify/1/hash', + '/email-changes/1/confirm/token', + '/devices/1/report', + ]) { + expect(isEmailedLink(path), path).toBe(true); + } + }); + + test('with a trailing slash, or at another case', () => { + for (const path of [ + '/reset-password/token/', + '/email/verify/1/hash/', + '/email-changes/1/confirm/token/', + '/devices/1/report/', + '/Reset-Password/token', + '/DEVICES/1/Report/', + ]) { + expect(isEmailedLink(path), path).toBe(true); + } + }); + + test('and no others', () => { + for (const path of [ + '/reset-password', + '/reset-password/token/more', + '/email/verify', + '/email/verify/1', + '/devices/1', + '/devices/1/report/x', + '/dashboard', + ]) { + expect(isEmailedLink(path), path).toBe(false); + } + }); +}); diff --git a/kits/tanstack-start/src/lib/emailed-links.ts b/kits/tanstack-start/src/lib/emailed-links.ts index 1b9dd25..729cae1 100644 --- a/kits/tanstack-start/src/lib/emailed-links.ts +++ b/kits/tanstack-start/src/lib/emailed-links.ts @@ -1,15 +1,21 @@ /** * The paths of the pages emailed links open, at Keyring's paths. Their - * address holds the link's token or signature. + * address holds the link's token or signature. Matched whatever their case, + * as the router matches its routes. */ const emailedLinks = [ - /^\/reset-password\/[^/]+$/, - /^\/email\/verify\/[^/]+\/[^/]+$/, - /^\/email-changes\/[^/]+\/[^/]+\/[^/]+$/, - /^\/devices\/[^/]+\/report$/, + /^\/reset-password\/[^/]+$/i, + /^\/email\/verify\/[^/]+\/[^/]+$/i, + /^\/email-changes\/[^/]+\/[^/]+\/[^/]+$/i, + /^\/devices\/[^/]+\/report$/i, ]; -/** Whether a path (without its query) is a page an emailed link opens. */ +/** + * Whether a path (without its query) is a page an emailed link opens, with + * or without a trailing slash, which the router opens the page with too. + */ export function isEmailedLink(pathname: string): boolean { - return emailedLinks.some((pattern) => pattern.test(pathname)); + const path = pathname.replace(/\/+$/, ''); + + return emailedLinks.some((pattern) => pattern.test(path)); } From 7ff5c0bdf924e1d8dda46671ef01bad7cf01e671 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:08:15 +0000 Subject: [PATCH 05/36] fix(kits): require the production settings whenever node_env isn't development or test, and warn at start-up when no proxy is trusted --- kits/nuxt/README.md | 2 + kits/nuxt/server/lib/config.ts | 26 ++++++++++- kits/nuxt/server/lib/proxy.test.ts | 13 +++++- kits/nuxt/server/plugins/settings.ts | 10 ++++- kits/nuxt/test/build.test.mjs | 4 ++ kits/tanstack-start/README.md | 6 ++- kits/tanstack-start/src/server.ts | 19 +++++--- kits/tanstack-start/src/server/config.ts | 47 +++++++++++++++++--- kits/tanstack-start/src/server/proxy.test.ts | 46 ++++++++++++++++--- 9 files changed, 151 insertions(+), 22 deletions(-) diff --git a/kits/nuxt/README.md b/kits/nuxt/README.md index 78d8dd5..e76faf4 100644 --- a/kits/nuxt/README.md +++ b/kits/nuxt/README.md @@ -172,6 +172,8 @@ Under `nuxt dev`, Nitro runs the server in a worker behind a proxy of its own, o A missing `LARAVEL_URL` or `FRONTEND_URL`, or a bad `FRONTEND_TRUSTED_PROXIES`, stops the production server as it starts (`server/plugins/settings.ts`), not on its first request. That's any build, however it's started and whatever `NODE_ENV` says: only `nuxt dev` has the defaults. +The production server warns as it starts when `FRONTEND_TRUSTED_PROXIES` is empty. Behind a reverse proxy on the same host, every request then comes from `127.0.0.1`, so every visitor is that one address to Laravel and they all share Keyring's rate limits. Set it whenever a proxy is in front; the warning is safe to ignore only when browsers connect to `npm start` directly. + Behind nginx on the same machine, say, set `FRONTEND_TRUSTED_PROXIES=127.0.0.1`, and have nginx set `X-Forwarded-For $proxy_add_x_forwarded_for` (the address nginx saw goes on the end, which is the one that counts). Caddy's `reverse_proxy` sets it itself. Without `FRONTEND_URL`, a trusted proxy's `X-Forwarded-Proto` and `X-Forwarded-Host` count too, their rightmost value: set `X-Forwarded-Proto $scheme` and `X-Forwarded-Host $http_host`. Nitro has no cap of its own on a request body, so set one in front too (nginx's `client_max_body_size`), as the proxy only holds 10 MiB. ## Security headers diff --git a/kits/nuxt/server/lib/config.ts b/kits/nuxt/server/lib/config.ts index 77165e4..d786c3c 100644 --- a/kits/nuxt/server/lib/config.ts +++ b/kits/nuxt/server/lib/config.ts @@ -19,7 +19,9 @@ let options: ProxyOptions | undefined; * nginx or Caddy, whose X-Forwarded-For (and, without FRONTEND_URL, * X-Forwarded-Proto and X-Forwarded-Host) are believed. Addresses or CIDR * ranges, separated by commas. Empty by default: no forwarded header the - * browser sends counts. + * browser sends counts. Behind a proxy, set it: otherwise every visitor + * is the proxy's address to Laravel, and they all share Keyring's rate + * limits (trustedProxiesWarning()). * * Production is any build `nuxt build` made, however it's started (`npm * start`, or .output/server/index.mjs itself), never NODE_ENV, which only @@ -54,6 +56,28 @@ export function readOptions( }; } +/** + * What to warn about as a production server starts with no + * FRONTEND_TRUSTED_PROXIES, or undefined. Behind a reverse proxy on the + * same host (nginx, Caddy), every request then comes from 127.0.0.1, so + * every visitor is that one address to Laravel, and they all share + * Keyring's rate limits. + */ +export function trustedProxiesWarning( + options: ProxyOptions, +): string | undefined { + if (options.trustedProxies.rules.length > 0) { + return undefined; + } + + return ( + 'FRONTEND_TRUSTED_PROXIES is empty, so forwarded addresses are ignored. ' + + "Behind a reverse proxy, every visitor shows up as the proxy's address " + + "and they all share Keyring's rate limits: set it to the proxy's " + + 'address, such as 127.0.0.1 for one on this host.' + ); +} + function frontendOrigin(value: string): URL { const url = new URL(value); diff --git a/kits/nuxt/server/lib/proxy.test.ts b/kits/nuxt/server/lib/proxy.test.ts index cadfebb..0007b66 100644 --- a/kits/nuxt/server/lib/proxy.test.ts +++ b/kits/nuxt/server/lib/proxy.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, test } from 'vite-plus/test'; import { buildForDev } from '../../test/nuxt'; -import { readOptions } from './config'; +import { readOptions, trustedProxiesWarning } from './config'; import { clientAddress, downstreamHeaders, @@ -642,4 +642,15 @@ describe('settings', () => { readOptions({ FRONTEND_URL: 'ftp://example.com' }), ).toThrow(TypeError); }); + + test('warns when no proxy is trusted, since every visitor would share one address', () => { + expect(trustedProxiesWarning(readOptions({}))).toMatch( + /FRONTEND_TRUSTED_PROXIES is empty.*rate limits/, + ); + expect( + trustedProxiesWarning( + readOptions({ FRONTEND_TRUSTED_PROXIES: '127.0.0.1' }), + ), + ).toBeUndefined(); + }); }); diff --git a/kits/nuxt/server/plugins/settings.ts b/kits/nuxt/server/plugins/settings.ts index 2551557..c32b06a 100644 --- a/kits/nuxt/server/plugins/settings.ts +++ b/kits/nuxt/server/plugins/settings.ts @@ -1,5 +1,5 @@ import { defineNitroPlugin } from 'nitropack/runtime'; -import { proxyOptions } from '../lib/config'; +import { proxyOptions, trustedProxiesWarning } from '../lib/config'; /** * In a production build (`nuxt build`), however it's started: @@ -7,6 +7,8 @@ import { proxyOptions } from '../lib/config'; * - A missing LARAVEL_URL or FRONTEND_URL (or a bad * FRONTEND_TRUSTED_PROXIES) stops the server as it starts, not on its * first request. + * - An empty FRONTEND_TRUSTED_PROXIES is warned about: behind a reverse + * proxy, every visitor would share Keyring's rate limits. * - It listens on localhost unless HOST (or NITRO_HOST) says otherwise, * where Nitro's own default is every interface. Plugins run before * Nitro's node server reads HOST, so this holds when @@ -18,7 +20,11 @@ export default defineNitroPlugin(() => { return; } - proxyOptions(); + const warning = trustedProxiesWarning(proxyOptions()); + + if (warning) { + console.warn(`[keyring] ${warning}`); + } if (!process.env.NITRO_HOST && !process.env.HOST) { process.env.HOST = 'localhost'; diff --git a/kits/nuxt/test/build.test.mjs b/kits/nuxt/test/build.test.mjs index 4a8867b..4861899 100644 --- a/kits/nuxt/test/build.test.mjs +++ b/kits/nuxt/test/build.test.mjs @@ -119,6 +119,10 @@ void describe('the built server', () => { assert.match(origin, /^http:\/\/(127\.0\.0\.1|\[::1\]):\d+$/); }); + void test('warns as it starts that no proxy is trusted', () => { + assert.match(frontend.output(), /FRONTEND_TRUSTED_PROXIES is empty/); + }); + void test('stops at once without LARAVEL_URL and FRONTEND_URL, whatever NODE_ENV says', async () => { const { server, output } = start({ NODE_ENV: 'development' }); const [code] = await once(server, 'exit'); diff --git a/kits/tanstack-start/README.md b/kits/tanstack-start/README.md index 4afeccc..299f6e3 100644 --- a/kits/tanstack-start/README.md +++ b/kits/tanstack-start/README.md @@ -146,9 +146,13 @@ Laravel believes those four headers from loopback only (`TRUSTED_PROXIES` defaul | -------------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `LARAVEL_URL` | `http://127.0.0.1:8000` | Where Laravel is, from this server: `php artisan serve`'s address. Required in production. | | `FRONTEND_TRUSTED_PROXIES` | empty | Proxies in front of this server, such as nginx or Caddy, as addresses or CIDR ranges separated by commas. Only a trusted proxy's `X-Forwarded-For`, `X-Forwarded-Proto` and `X-Forwarded-Host` are believed: the browser's address is the rightmost one in `X-Forwarded-For` that isn't a trusted proxy (`ip:port` and `[v6]:port` entries count as their address). An entry that isn't an address, such as `unknown`, stops the walk there, and the last trusted hop's address is used, never what's to its left. Left empty, no forwarded header anyone sends counts, and the browser's address is the socket's. An entry that's neither an address nor a range stops the server. | -| `FRONTEND_URL` | none | This app's own address, such as `https://example.com` (Laravel's `APP_URL`). `X-Forwarded-Host` and `X-Forwarded-Proto` always come from it, so a forged `Host` never reaches Laravel. Required in production. Without it (in development), they come from the request, or a trusted proxy. | +| `FRONTEND_URL` | none | This app's own address, such as `https://example.com` (Laravel's `APP_URL`). `X-Forwarded-Host` and `X-Forwarded-Proto` always come from it, so a forged `Host` never reaches Laravel. Required in production. Without it (in development and tests), they come from the request, or a trusted proxy. | | `HOST`, `PORT` | `localhost`, `3000` | Where `npm start` listens. `npm start` runs with `NODE_ENV=production` unless it's set. The dev server listens on `localhost:3000`, or `FRONTEND_PORT`. | +A missing `LARAVEL_URL` or `FRONTEND_URL`, or a bad `FRONTEND_TRUSTED_PROXIES`, stops the production server as it starts (`src/server.ts`), not on its first request. Production is any `NODE_ENV` but `development` and `test`, unset included: only the dev server and the tests have the defaults. + +The production server warns as it starts when `FRONTEND_TRUSTED_PROXIES` is empty. Behind a reverse proxy on the same host, every request then comes from `127.0.0.1`, so every visitor is that one address to Laravel and they all share Keyring's rate limits. Set it whenever a proxy is in front; the warning is safe to ignore only when browsers connect to `npm start` directly. + Behind nginx on the same machine, say, set `FRONTEND_TRUSTED_PROXIES=127.0.0.1`, and have nginx set `X-Forwarded-For $proxy_add_x_forwarded_for` (the address nginx saw goes on the end, which is the one that counts). Caddy's `reverse_proxy` sets it itself. Without `FRONTEND_URL`, a trusted proxy's `X-Forwarded-Proto` and `X-Forwarded-Host` count too, their rightmost value: set `X-Forwarded-Proto $scheme` and `X-Forwarded-Host $http_host`. ## Security headers diff --git a/kits/tanstack-start/src/server.ts b/kits/tanstack-start/src/server.ts index ab276bf..3ee210e 100644 --- a/kits/tanstack-start/src/server.ts +++ b/kits/tanstack-start/src/server.ts @@ -1,12 +1,21 @@ import handler from '@tanstack/react-start/server-entry'; -import { proxyOptions } from './server/config'; +import { + isProduction, + proxyOptions, + trustedProxiesWarning, +} from './server/config'; import { laravelPath, proxyToLaravel } from './server/proxy'; import { withDocumentHeaders } from './server/security-headers'; -// In production, a missing LARAVEL_URL or FRONTEND_URL stops the server as -// it starts, not on its first request. -if (process.env.NODE_ENV === 'production') { - proxyOptions(); +// In production (any NODE_ENV but development or test), a missing +// LARAVEL_URL or FRONTEND_URL stops the server as it starts, not on its +// first request, and an empty FRONTEND_TRUSTED_PROXIES is warned about. +if (isProduction()) { + const warning = trustedProxiesWarning(proxyOptions()); + + if (warning) { + console.warn(`[keyring] ${warning}`); + } } /** diff --git a/kits/tanstack-start/src/server/config.ts b/kits/tanstack-start/src/server/config.ts index 6d07b6a..c38e1ad 100644 --- a/kits/tanstack-start/src/server/config.ts +++ b/kits/tanstack-start/src/server/config.ts @@ -8,18 +8,24 @@ let options: ProxyOptions | undefined; * * - LARAVEL_URL: where Laravel is, from this server. Laravel has to trust * this server as a proxy, which it does from loopback in headless mode, - * so run both on one host. Required in production. Elsewhere it defaults - * to http://127.0.0.1:8000, where `php artisan serve` listens. + * so run both on one host. Required in production. In development and + * tests it defaults to http://127.0.0.1:8000, where `php artisan serve` + * listens. * - FRONTEND_URL: this frontend's own address, such as https://example.com * (Laravel's APP_URL on one origin). X-Forwarded-Host and -Proto are * always taken from it, never from the request, so a forged Host can't - * reach Laravel. Required in production. Elsewhere, without it, they - * come from the request (or a trusted proxy). + * reach Laravel. Required in production. In development and tests, + * without it, they come from the request (or a trusted proxy). * - FRONTEND_TRUSTED_PROXIES: proxies in front of this server, such as * nginx or Caddy, whose X-Forwarded-For (and, without FRONTEND_URL, * X-Forwarded-Proto and X-Forwarded-Host) are believed. Addresses or CIDR * ranges, separated by commas. Empty by default: no forwarded header the - * browser sends counts. + * browser sends counts. Behind a proxy, set it: otherwise every visitor + * is the proxy's address to Laravel, and they all share Keyring's rate + * limits (trustedProxiesWarning()). + * + * Production is any NODE_ENV but `development` and `test`, unset included: + * the defaults are for `vp dev` and the tests alone. */ export function proxyOptions( env: Record = process.env, @@ -32,7 +38,7 @@ export function proxyOptions( export function readOptions( env: Record, ): ProxyOptions { - const production = env.NODE_ENV === 'production'; + const production = isProduction(env); for (const name of ['LARAVEL_URL', 'FRONTEND_URL']) { if (production && !env[name]) { @@ -50,6 +56,35 @@ export function readOptions( }; } +/** Whether NODE_ENV is anything but `development` or `test`. */ +export function isProduction( + env: Record = process.env, +): boolean { + return env.NODE_ENV !== 'development' && env.NODE_ENV !== 'test'; +} + +/** + * What to warn about as a production server starts with no + * FRONTEND_TRUSTED_PROXIES, or undefined. Behind a reverse proxy on the + * same host (nginx, Caddy), every request then comes from 127.0.0.1, so + * every visitor is that one address to Laravel, and they all share + * Keyring's rate limits. + */ +export function trustedProxiesWarning( + options: ProxyOptions, +): string | undefined { + if (options.trustedProxies.rules.length > 0) { + return undefined; + } + + return ( + 'FRONTEND_TRUSTED_PROXIES is empty, so forwarded addresses are ignored. ' + + "Behind a reverse proxy, every visitor shows up as the proxy's address " + + "and they all share Keyring's rate limits: set it to the proxy's " + + 'address, such as 127.0.0.1 for one on this host.' + ); +} + function frontendOrigin(value: string): URL { const url = new URL(value); diff --git a/kits/tanstack-start/src/server/proxy.test.ts b/kits/tanstack-start/src/server/proxy.test.ts index 96dd1ce..2d04a55 100644 --- a/kits/tanstack-start/src/server/proxy.test.ts +++ b/kits/tanstack-start/src/server/proxy.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from 'vite-plus/test'; -import { readOptions } from './config'; +import { readOptions, trustedProxiesWarning } from './config'; import { clientAddress, downstreamHeaders, @@ -621,16 +621,50 @@ describe('settings', () => { ).toBe('https://example.com/'); }); - test('elsewhere they have defaults', () => { - const settings = readOptions({}); + test('so does any NODE_ENV but development and test, unset included', () => { + for (const NODE_ENV of [undefined, '', 'staging', 'prod']) { + expect(() => readOptions({ NODE_ENV }), NODE_ENV).toThrow( + /LARAVEL_URL/, + ); + expect( + () => + readOptions({ + NODE_ENV, + LARAVEL_URL: 'http://127.0.0.1:8000', + }), + NODE_ENV, + ).toThrow(/FRONTEND_URL/); + } + }); + + test('in development and tests they have defaults', () => { + for (const NODE_ENV of ['development', 'test']) { + const settings = readOptions({ NODE_ENV }); - expect(settings.laravelUrl).toBe('http://127.0.0.1:8000'); - expect(settings.frontendOrigin).toBeUndefined(); + expect(settings.laravelUrl).toBe('http://127.0.0.1:8000'); + expect(settings.frontendOrigin).toBeUndefined(); + } }); test('FRONTEND_URL must be an http or https URL', () => { expect(() => - readOptions({ FRONTEND_URL: 'ftp://example.com' }), + readOptions({ + NODE_ENV: 'development', + FRONTEND_URL: 'ftp://example.com', + }), ).toThrow(TypeError); }); + + test('warns when no proxy is trusted, since every visitor would share one address', () => { + const env = { NODE_ENV: 'development' }; + + expect(trustedProxiesWarning(readOptions(env))).toMatch( + /FRONTEND_TRUSTED_PROXIES is empty.*rate limits/, + ); + expect( + trustedProxiesWarning( + readOptions({ ...env, FRONTEND_TRUSTED_PROXIES: '127.0.0.1' }), + ), + ).toBeUndefined(); + }); }); From 18620a1b352d83441b8379d0fb98932aa8512983 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:08:48 +0000 Subject: [PATCH 06/36] fix(kits): look up keyring's pages by their own names only, never a name every object has --- kits/nuxt/app/keyring/navigate.test.ts | 11 +++++++++++ kits/nuxt/app/keyring/navigate.ts | 19 ++++++++++++++++--- kits/nuxt/app/lib/router-adapter.ts | 3 ++- .../src/keyring/navigate.test.ts | 11 +++++++++++ kits/tanstack-start/src/keyring/navigate.ts | 19 ++++++++++++++++--- .../tanstack-start/src/lib/router-adapter.tsx | 3 ++- 6 files changed, 58 insertions(+), 8 deletions(-) diff --git a/kits/nuxt/app/keyring/navigate.test.ts b/kits/nuxt/app/keyring/navigate.test.ts index 73b430c..5836d7a 100644 --- a/kits/nuxt/app/keyring/navigate.test.ts +++ b/kits/nuxt/app/keyring/navigate.test.ts @@ -105,6 +105,17 @@ describe('where an answer goes', () => { test('an answer that names nowhere stays put', () => { expect(targetFor(to({}), '/login')).toBeNull(); }); + + test("a page that's only a name objects have stays put", () => { + for (const page of [ + 'constructor', + '__proto__', + 'toString', + 'hasOwnProperty', + ]) { + expect(targetFor(to({ page }), '/login'), page).toBeNull(); + } + }); }); describe('local paths', () => { diff --git a/kits/nuxt/app/keyring/navigate.ts b/kits/nuxt/app/keyring/navigate.ts index 5a6593a..01e043b 100644 --- a/kits/nuxt/app/keyring/navigate.ts +++ b/kits/nuxt/app/keyring/navigate.ts @@ -32,6 +32,17 @@ export const pages: Record = { confirm: '/confirm', }; +/** + * The route for one of Keyring's pages, by its name, or undefined: only + * `pages`' own names count, never one an object has from its prototype + * (`constructor`, `__proto__`), whatever an answer says. + */ +export function pagePath(name: string | null | undefined): string | undefined { + return typeof name === 'string' && Object.hasOwn(pages, name) + ? pages[name] + : undefined; +} + const HOME = '/dashboard'; /** The statuses of the 403s that hold a user on Settings → Security. */ @@ -74,12 +85,14 @@ export function targetFor(to: Destination, here: string): string | null { return back ?? HOME; } - if (to.page && pages[to.page]) { + const page = pagePath(to.page); + + if (page) { const next = comeBackTo(to, here, back); return next - ? `${pages[to.page]}?${new URLSearchParams({ redirect: next })}` - : pages[to.page]; + ? `${page}?${new URLSearchParams({ redirect: next })}` + : page; } if (to.redirect) { diff --git a/kits/nuxt/app/lib/router-adapter.ts b/kits/nuxt/app/lib/router-adapter.ts index 86d62b8..0e2bfe1 100644 --- a/kits/nuxt/app/lib/router-adapter.ts +++ b/kits/nuxt/app/lib/router-adapter.ts @@ -27,6 +27,7 @@ import type { import { toUrl } from '@keyringjs/ui-vue/lib/url'; import { carryOver, + pagePath, pages, targetFor, useKeyringNavigate, @@ -502,7 +503,7 @@ export function useFlashed() { /** Go to this frontend's page for one of Keyring's, by its name. */ function goToPage(router: VueRouter, page: string): void { - if (!pages[page]) { + if (!pagePath(page)) { fail(`No page here for Keyring's "${page}".`); return; diff --git a/kits/tanstack-start/src/keyring/navigate.test.ts b/kits/tanstack-start/src/keyring/navigate.test.ts index e0ede33..9b00949 100644 --- a/kits/tanstack-start/src/keyring/navigate.test.ts +++ b/kits/tanstack-start/src/keyring/navigate.test.ts @@ -105,6 +105,17 @@ describe('where an answer goes', () => { test('an answer that names nowhere stays put', () => { expect(targetFor(to({}), '/login')).toBeNull(); }); + + test("a page that's only a name objects have stays put", () => { + for (const page of [ + 'constructor', + '__proto__', + 'toString', + 'hasOwnProperty', + ]) { + expect(targetFor(to({ page }), '/login'), page).toBeNull(); + } + }); }); describe('local paths', () => { diff --git a/kits/tanstack-start/src/keyring/navigate.ts b/kits/tanstack-start/src/keyring/navigate.ts index 86ba74f..7f9715e 100644 --- a/kits/tanstack-start/src/keyring/navigate.ts +++ b/kits/tanstack-start/src/keyring/navigate.ts @@ -32,6 +32,17 @@ export const pages: Record = { confirm: '/confirm', }; +/** + * The route for one of Keyring's pages, by its name, or undefined: only + * `pages`' own names count, never one an object has from its prototype + * (`constructor`, `__proto__`), whatever an answer says. + */ +export function pagePath(name: string | null | undefined): string | undefined { + return typeof name === 'string' && Object.hasOwn(pages, name) + ? pages[name] + : undefined; +} + const HOME = '/dashboard'; /** The statuses of the 403s that hold a user on Settings → Security. */ @@ -65,12 +76,14 @@ export function targetFor(to: Destination, here: string): string | null { return back ?? HOME; } - if (to.page && pages[to.page]) { + const page = pagePath(to.page); + + if (page) { const next = comeBackTo(to, here, back); return next - ? `${pages[to.page]}?${new URLSearchParams({ redirect: next })}` - : pages[to.page]; + ? `${page}?${new URLSearchParams({ redirect: next })}` + : page; } if (to.redirect) { diff --git a/kits/tanstack-start/src/lib/router-adapter.tsx b/kits/tanstack-start/src/lib/router-adapter.tsx index dd0827c..975df68 100644 --- a/kits/tanstack-start/src/lib/router-adapter.tsx +++ b/kits/tanstack-start/src/lib/router-adapter.tsx @@ -35,6 +35,7 @@ import { toUrl } from '@keyringjs/ui-react/lib/url'; import { localPath } from '@/lib/local-path'; import { carryOver, + pagePath, pages, targetFor, useKeyringNavigate, @@ -447,7 +448,7 @@ export function useFlashed(): Flash | null { /** Go to this frontend's page for one of Keyring's, by its name. */ function goToPage(router: AnyRouter, page: string): void { - if (!pages[page]) { + if (!pagePath(page)) { fail(`No page here for Keyring's "${page}".`); return; From b966cad117363ace608952dd40e95521332fa156 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:09:18 +0000 Subject: [PATCH 07/36] fix(tanstack): keep a sign in's alerts in the browser only, never in the server's module state --- kits/tanstack-start/src/keyring/notices.test.tsx | 16 +++++++++++++++- kits/tanstack-start/src/keyring/notices.ts | 9 ++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/kits/tanstack-start/src/keyring/notices.test.tsx b/kits/tanstack-start/src/keyring/notices.test.tsx index 7202c36..a026115 100644 --- a/kits/tanstack-start/src/keyring/notices.test.tsx +++ b/kits/tanstack-start/src/keyring/notices.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import { act } from 'react'; import { createRoot } from 'react-dom/client'; -import { afterEach, describe, expect, test } from 'vite-plus/test'; +import { afterEach, describe, expect, test, vi } from 'vite-plus/test'; import { clearAlerts, noticeCookie, @@ -100,6 +100,20 @@ describe('sign-in alerts', () => { second.unmount(); }); + test("are never kept on the server, where they would be every visitor's", async () => { + vi.stubGlobal('window', undefined); + + try { + rememberAlerts([alert]); + } finally { + vi.unstubAllGlobals(); + } + + const page = await mount(); + expect(page.seen.at(-1)).toEqual([]); + page.unmount(); + }); + test('are forgotten on sign out', async () => { rememberAlerts([alert]); clearAlerts(); diff --git a/kits/tanstack-start/src/keyring/notices.ts b/kits/tanstack-start/src/keyring/notices.ts index f1f1e42..bcf98b6 100644 --- a/kits/tanstack-start/src/keyring/notices.ts +++ b/kits/tanstack-start/src/keyring/notices.ts @@ -282,8 +282,15 @@ const noAlerts: SignInAlert[] = []; let alerts: SignInAlert[] = noAlerts; const listeners = new Set<() => void>(); -/** Keep a sign in's alerts until the next page shows them. */ +/** + * Keep a sign in's alerts until the next page shows them. Browser only: on + * the server, this module's state would be every visitor's. + */ export function rememberAlerts(value: unknown): void { + if (typeof window === 'undefined') { + return; + } + alerts = Array.isArray(value) ? (value as SignInAlert[]) : noAlerts; listeners.forEach((listener) => listener()); } From 3db1e6f79309937c636653fd42d9ee04885edd24 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:15:10 +0000 Subject: [PATCH 08/36] fix(ui): only follow an enrollment's continue to a page on this site, and say why the qr code's svg is safe to render raw --- .github/workflows/kits.yml | 1 + README.md | 2 +- kits/inertia-react/kit.json | 1 + kits/tanstack-start/README.md | 2 +- kits/tanstack-start/vite.config.ts | 5 +++- .../components/keyring/sign-in-methods.tsx | 9 ++++-- packages/ui-react/src/lib/url.test.ts | 30 +++++++++++++++++++ packages/ui-react/src/lib/url.ts | 22 ++++++++++++++ .../components/keyring/ConfirmCodeDialog.vue | 7 ++++- .../src/components/keyring/SignInMethods.vue | 4 ++- packages/ui-vue/src/lib/url.test.ts | 30 +++++++++++++++++++ packages/ui-vue/src/lib/url.ts | 22 ++++++++++++++ resources/js/lib/url.ts | 22 ++++++++++++++ 13 files changed, 150 insertions(+), 7 deletions(-) create mode 100644 packages/ui-react/src/lib/url.test.ts create mode 100644 packages/ui-vue/src/lib/url.test.ts diff --git a/.github/workflows/kits.yml b/.github/workflows/kits.yml index a5cf3ad..31b94fc 100644 --- a/.github/workflows/kits.yml +++ b/.github/workflows/kits.yml @@ -86,6 +86,7 @@ jobs: run: node --test bin/ - run: npm run build - run: npm test + # Its tests run packages/ui-react's too. - name: TanStack Start kit run: | npm test -w kits/tanstack-start diff --git a/README.md b/README.md index 0fe832c..460e63d 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ An exported kit gets the package back in its own source, with the imports rewrit `@keyringjs/ui-vue` is the same for Vue kits, the Nuxt kit's for now: `@keyringjs/ui-react`'s primitives, app components, layouts, Keyring's settings components and the challenge's factors, written for Vue with [shadcn-vue](https://www.shadcn-vue.com) on Reka UI, with the same markup and classes, so it matches the same screenshots. Its files have Vue's names, and are imported with their extension (`@keyringjs/ui-vue/components/InputError.vue`, `@keyringjs/ui-vue/composables/useAppearance`, `@keyringjs/ui-vue/button`). Its adapter, `@keyringjs/ui-vue/adapter`, is the part of Inertia's Vue API the components use (`Link`, `Form`, `usePage()`, `router`), which an app provides with `provideAdapter()`, and its components import Keyring's helpers from `@keyringjs/keyring/vue`, which the Nuxt kit points at its headless entry (see [its README](kits/nuxt/README.md#shared-components)). The Nuxt kit's export gets them in `frontend/app`. -What stays in the Inertia app: the pages, `pages.test.tsx`, the toaster (`resources/js/components/ui/sonner.tsx`, which shows Inertia's flashed toasts), `toUrl()` (`resources/js/lib/url.ts`), the header layout and its header, and the delete-account card. `components.json` (and the `paths` in `tsconfig.json`) point shadcn's CLI at the package, so `npx shadcn add ` writes new primitives to `packages/ui-react/src/components/ui`. An exported kit gets the usual `components.json` back, pointing at its own `resources/js/components/ui`. +What stays in the Inertia app: the pages, `pages.test.tsx`, the toaster (`resources/js/components/ui/sonner.tsx`, which shows Inertia's flashed toasts), `toUrl()` and `sameOriginUrl()` (`resources/js/lib/url.ts`, which the export keeps in place of the package's own `lib/url.ts`, so the two have to match), the header layout and its header, and the delete-account card. `components.json` (and the `paths` in `tsconfig.json`) point shadcn's CLI at the package, so `npx shadcn add ` writes new primitives to `packages/ui-react/src/components/ui`. An exported kit gets the usual `components.json` back, pointing at its own `resources/js/components/ui`. ## The demo diff --git a/kits/inertia-react/kit.json b/kits/inertia-react/kit.json index 4879b7d..297f6d7 100644 --- a/kits/inertia-react/kit.json +++ b/kits/inertia-react/kit.json @@ -79,6 +79,7 @@ "packages/ui-react/src/types/", "packages/ui-react/src/routes/", "packages/ui-react/src/lib/url.ts", + "packages/ui-react/src/lib/url.test.ts", "packages/ui-react/src/demo/" ], "unformatted": ["packages/ui-react/src/components/ui/"], diff --git a/kits/tanstack-start/README.md b/kits/tanstack-start/README.md index 299f6e3..d6cae32 100644 --- a/kits/tanstack-start/README.md +++ b/kits/tanstack-start/README.md @@ -103,7 +103,7 @@ The checks, from `kits/tanstack-start`: ```bash npm run types:check npm run build -npm test +npm test # this kit's tests, and packages/ui-react's ``` Lint and format run from the root, with `npm run check`. CI runs all three in the monorepo job, then exports the kit and runs the export's checks (see [The export](#the-export)). The browser tests run against this kit with `npm run test:browser:tanstack` (see the root README's "Browser tests"). diff --git a/kits/tanstack-start/vite.config.ts b/kits/tanstack-start/vite.config.ts index 6d3fcfd..60ae7fe 100644 --- a/kits/tanstack-start/vite.config.ts +++ b/kits/tanstack-start/vite.config.ts @@ -72,7 +72,10 @@ export default defineConfig({ ], }, test: { - include: ['src/**/*.test.{ts,tsx}'], + include: [ + 'src/**/*.test.{ts,tsx}', + '../../packages/ui-react/src/**/*.test.{ts,tsx}', // @monorepo-only + ], }, // `npm run check`, with the same rules as the backend's. // In the monorepo, the root's config runs it instead. // @monorepo-only diff --git a/packages/ui-react/src/components/keyring/sign-in-methods.tsx b/packages/ui-react/src/components/keyring/sign-in-methods.tsx index 4d479a8..1ebf314 100644 --- a/packages/ui-react/src/components/keyring/sign-in-methods.tsx +++ b/packages/ui-react/src/components/keyring/sign-in-methods.tsx @@ -53,6 +53,7 @@ import { Label } from '@keyringjs/ui-react/label'; import { Spinner } from '@keyringjs/ui-react/spinner'; import { run } from '@keyringjs/ui-react/keyring/actions'; import { Ago, Details } from '@keyringjs/ui-react/components/keyring/details'; +import { sameOriginUrl } from '@keyringjs/ui-react/lib/url'; /** * A sign-in method as Keyring's factors present it (name, hint, when it was @@ -366,7 +367,8 @@ export default function SignInMethods({ recovery={recovery} signOutOthers={alsoSignOut} onClose={() => { - const continueTo = recovery?.continue; + // Only ever a page on this site, whoever gave it. + const continueTo = sameOriginUrl(recovery?.continue); setRecovery(null); if (continueTo) { @@ -626,7 +628,10 @@ function ConfirmCodeDialog({
{ + test('is kept, as the browser reads it', () => { + expect(sameOriginUrl('/dashboard?x=1')).toBe( + `${window.location.origin}/dashboard?x=1`, + ); + expect(sameOriginUrl(`${window.location.origin}/settings`)).toBe( + `${window.location.origin}/settings`, + ); + }); + + test('and nothing else', () => { + for (const value of [ + 'https://evil.example/dashboard', + '//evil.example', + '/\\evil.example', + '/\t/evil.example', + 'javascript:alert(1)', + 'data:text/html,hi', + '', + null, + undefined, + ]) { + expect(sameOriginUrl(value), String(value)).toBeUndefined(); + } + }); +}); diff --git a/packages/ui-react/src/lib/url.ts b/packages/ui-react/src/lib/url.ts index 746bba1..746d33f 100644 --- a/packages/ui-react/src/lib/url.ts +++ b/packages/ui-react/src/lib/url.ts @@ -3,3 +3,25 @@ import type { InertiaLinkProps } from '@keyringjs/ui-react/adapter'; export function toUrl(url: NonNullable): string { return typeof url === 'string' ? url : url.url; } + +/** + * `value` as a URL on this page's origin, or undefined: never another + * site, or a `javascript:` URL. For a full page load to a URL an answer + * gave, such as an enrollment's `continue`, so that doesn't rest on every + * caller having checked it. Browser only. + */ +export function sameOriginUrl( + value: string | null | undefined, +): string | undefined { + if (!value || typeof window === 'undefined') { + return undefined; + } + + try { + const url = new URL(value, window.location.href); + + return url.origin === window.location.origin ? url.href : undefined; + } catch { + return undefined; + } +} diff --git a/packages/ui-vue/src/components/keyring/ConfirmCodeDialog.vue b/packages/ui-vue/src/components/keyring/ConfirmCodeDialog.vue index 8540db8..026c34a 100644 --- a/packages/ui-vue/src/components/keyring/ConfirmCodeDialog.vue +++ b/packages/ui-vue/src/components/keyring/ConfirmCodeDialog.vue @@ -90,7 +90,12 @@ function onOpenChange(open: boolean) { v-if="isTotp && pending" class="grid justify-items-center gap-3" > - +
{ + test('is kept, as the browser reads it', () => { + expect(sameOriginUrl('/dashboard?x=1')).toBe( + `${window.location.origin}/dashboard?x=1`, + ); + expect(sameOriginUrl(`${window.location.origin}/settings`)).toBe( + `${window.location.origin}/settings`, + ); + }); + + test('and nothing else', () => { + for (const value of [ + 'https://evil.example/dashboard', + '//evil.example', + '/\\evil.example', + '/\t/evil.example', + 'javascript:alert(1)', + 'data:text/html,hi', + '', + null, + undefined, + ]) { + expect(sameOriginUrl(value), String(value)).toBeUndefined(); + } + }); +}); diff --git a/packages/ui-vue/src/lib/url.ts b/packages/ui-vue/src/lib/url.ts index acea753..cbe5e12 100644 --- a/packages/ui-vue/src/lib/url.ts +++ b/packages/ui-vue/src/lib/url.ts @@ -3,3 +3,25 @@ import type { InertiaLinkProps } from '@keyringjs/ui-vue/adapter'; export function toUrl(url: NonNullable): string { return typeof url === 'string' ? url : url.url; } + +/** + * `value` as a URL on this page's origin, or undefined: never another + * site, or a `javascript:` URL. For a full page load to a URL an answer + * gave, such as an enrollment's `continue`, so that doesn't rest on every + * caller having checked it. Browser only. + */ +export function sameOriginUrl( + value: string | null | undefined, +): string | undefined { + if (!value || typeof window === 'undefined') { + return undefined; + } + + try { + const url = new URL(value, window.location.href); + + return url.origin === window.location.origin ? url.href : undefined; + } catch { + return undefined; + } +} diff --git a/resources/js/lib/url.ts b/resources/js/lib/url.ts index 91222c3..77a8363 100644 --- a/resources/js/lib/url.ts +++ b/resources/js/lib/url.ts @@ -3,3 +3,25 @@ import type { InertiaLinkProps } from '@inertiajs/react'; export function toUrl(url: NonNullable): string { return typeof url === 'string' ? url : url.url; } + +/** + * `value` as a URL on this page's origin, or undefined: never another + * site, or a `javascript:` URL. For a full page load to a URL an answer + * gave, such as an enrollment's `continue`, so that doesn't rest on every + * caller having checked it. Browser only. + */ +export function sameOriginUrl( + value: string | null | undefined, +): string | undefined { + if (!value || typeof window === 'undefined') { + return undefined; + } + + try { + const url = new URL(value, window.location.href); + + return url.origin === window.location.origin ? url.href : undefined; + } catch { + return undefined; + } +} From a05374a03e93bb6d72ac877276e572c474c43a78 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:24:25 +0000 Subject: [PATCH 09/36] fix(proxies): trim each trusted proxy and drop the empty ones --- app/Providers/AppServiceProvider.php | 27 +++++++++- config/app.php | 5 +- .../Headless/TrustedProxiesListTest.php | 52 +++++++++++++++++++ 3 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 tests/Feature/Headless/TrustedProxiesListTest.php diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 6664330..f241aa5 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -37,8 +37,8 @@ public function boot(): void DevCommands::artisan('serve --tries=0', 'server'); } - if ($proxies = config('app.trusted_proxies')) { - TrustProxies::at($proxies === '*' ? '*' : explode(',', $proxies)); + if ($proxies = $this->trustedProxies()) { + TrustProxies::at($proxies); // Only the headers a headless frontend's proxy sets (see // docs/headless-api.md), not Laravel's default X-Forwarded-Port @@ -53,6 +53,29 @@ public function boot(): void } } + /** + * TRUSTED_PROXIES as TrustProxies takes it: "*", or the addresses + * between its commas, each trimmed, without empty ones. Null when it + * names none. + * + * @return '*'|list|null + */ + protected function trustedProxies(): string|array|null + { + $proxies = trim((string) config('app.trusted_proxies')); + + if ($proxies === '*') { + return '*'; + } + + $list = array_values(array_filter( + array_map(trim(...), explode(',', $proxies)), + fn (string $proxy) => $proxy !== '', + )); + + return $list === [] ? null : $list; + } + /** * Configure default behaviors for production-ready applications. */ diff --git a/config/app.php b/config/app.php index bdae3f7..a5f9bc7 100644 --- a/config/app.php +++ b/config/app.php @@ -97,7 +97,8 @@ | | A proxy in front of the app, like `tailscale serve` or a load balancer, | is only believed about the visitor's address and HTTPS when it's listed - | here: comma-separated addresses, or * for any. + | here: comma-separated addresses (spaces around them are fine), 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 @@ -106,6 +107,8 @@ | 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. + | That default is for the frontend's server reaching Laravel on the same + | host, so keep Laravel's port reachable by it alone, or pin this. | The proxy must set X-Forwarded-For itself, never pass on the browser's. | */ diff --git a/tests/Feature/Headless/TrustedProxiesListTest.php b/tests/Feature/Headless/TrustedProxiesListTest.php new file mode 100644 index 0000000..54b2534 --- /dev/null +++ b/tests/Feature/Headless/TrustedProxiesListTest.php @@ -0,0 +1,52 @@ +headlessEnv['TRUSTED_PROXIES'] = ' 198.51.100.20 , , 127.0.0.1 '; + + $this->headlessSetUp(); + } + + public function test_each_listed_proxy_is_trusted_with_the_spaces_around_it_trimmed() + { + $this->forwardedFrom('198.51.100.20')->assertOk(); + $this->assertSame('203.0.113.9', request()->ip()); + } + + public function test_the_last_listed_proxy_is_trusted_too() + { + $this->forwardedFrom('127.0.0.1')->assertOk(); + $this->assertSame('203.0.113.9', request()->ip()); + } + + public function test_an_address_that_isnt_listed_is_not_trusted() + { + $this->forwardedFrom('::1')->assertOk(); + $this->assertSame('::1', request()->ip()); + } + + private function forwardedFrom(string $address): TestResponse + { + return $this->withServerVariables(['REMOTE_ADDR' => $address]) + ->withHeaders(['X-Forwarded-For' => '203.0.113.9']) + ->getJson('/api/me'); + } +} From 20951605b43387f795883108f366e97f5bce7895 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:24:25 +0000 Subject: [PATCH 10/36] fix(hosts): only answer for app_url's host and a headless frontend's --- app/Support/Frontend.php | 31 ++++++++++ bootstrap/app.php | 6 ++ tests/Feature/Headless/TrustHostsTest.php | 72 +++++++++++++++++++++++ tests/Feature/TrustHostsTest.php | 60 +++++++++++++++++++ 4 files changed, 169 insertions(+) create mode 100644 tests/Feature/Headless/TrustHostsTest.php create mode 100644 tests/Feature/TrustHostsTest.php diff --git a/app/Support/Frontend.php b/app/Support/Frontend.php index ac98996..9b5be84 100644 --- a/app/Support/Frontend.php +++ b/app/Support/Frontend.php @@ -26,4 +26,35 @@ public static function wantsJson(Request $request): bool { return $request->expectsJson() && ! $request->hasHeader('X-Inertia'); } + + /** + * The hosts Laravel answers for (TrustHosts, bootstrap/app.php), as + * patterns: APP_URL's, and in headless mode FRONTEND_URL's, exactly, + * without their subdomains. A request for any other host is refused + * before a link is built from it. Requests a headless frontend's server + * passes on carry the browser's host in X-Forwarded-Host, which counts + * here only from a trusted proxy (config/app.php). + * + * @return list + */ + public static function trustedHosts(): array + { + $urls = [config('app.url')]; + + if (self::headless()) { + $urls[] = config('app.frontend_url'); + } + + $hosts = []; + + foreach ($urls as $url) { + $host = is_string($url) ? parse_url($url, PHP_URL_HOST) : null; + + if (is_string($host) && $host !== '') { + $hosts[] = '^'.preg_quote(strtolower($host)).'$'; + } + } + + return array_values(array_unique($hosts)); + } } diff --git a/bootstrap/app.php b/bootstrap/app.php index ba5cf4c..8271cdf 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -2,6 +2,7 @@ use App\Http\Middleware\HandleAppearance; use App\Http\Middleware\HandleInertiaRequests; +use App\Support\Frontend; use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; @@ -17,6 +18,11 @@ ->withMiddleware(function (Middleware $middleware): void { $middleware->encryptCookies(except: ['appearance', 'sidebar_state']); + // Only APP_URL's host, and a headless frontend's, so no link url() + // builds can follow a Host header someone made up. Laravel skips + // this check locally and in the PHP tests. + $middleware->trustHosts(at: fn () => Frontend::trustedHosts(), subdomains: false); + $middleware->web(append: [ HandleAppearance::class, HandleInertiaRequests::class, diff --git a/tests/Feature/Headless/TrustHostsTest.php b/tests/Feature/Headless/TrustHostsTest.php new file mode 100644 index 0000000..0e3be7f --- /dev/null +++ b/tests/Feature/Headless/TrustHostsTest.php @@ -0,0 +1,72 @@ +headlessSetUp(); + + $this->app->bind(TrustHosts::class, fn ($app) => new class($app) extends TrustHosts + { + protected function shouldSpecifyTrustedHosts() + { + return true; + } + }); + } + + protected function tearDown(): void + { + // Symfony keeps the trusted hosts for every request after. + Request::setTrustedHosts([]); + + $this->headlessTearDown(); + } + + public function test_app_url_and_the_frontends_host_are_trusted() + { + $this->assertContains('^app\.example\.test$', Frontend::trustedHosts()); + $this->assertContains('^'.preg_quote((string) parse_url(config('app.url'), PHP_URL_HOST)).'$', Frontend::trustedHosts()); + } + + public function test_the_frontends_host_passed_on_by_its_server_is_answered() + { + $this->throughTheFrontend('app.example.test')->assertOk(); + } + + public function test_a_made_up_host_passed_on_by_the_frontends_server_is_refused() + { + $this->throughTheFrontend('evil.example')->assertBadRequest(); + } + + private function throughTheFrontend(string $host): TestResponse + { + return $this->withServerVariables(['REMOTE_ADDR' => '127.0.0.1']) + ->withHeaders([ + 'X-Forwarded-For' => '203.0.113.9', + 'X-Forwarded-Host' => $host, + 'X-Forwarded-Proto' => 'https', + 'X-Forwarded-Prefix' => '/backend', + ]) + ->getJson('/api/me'); + } +} diff --git a/tests/Feature/TrustHostsTest.php b/tests/Feature/TrustHostsTest.php new file mode 100644 index 0000000..0eb24da --- /dev/null +++ b/tests/Feature/TrustHostsTest.php @@ -0,0 +1,60 @@ +app->bind(TrustHosts::class, fn ($app) => new class($app) extends TrustHosts + { + protected function shouldSpecifyTrustedHosts() + { + return true; + } + }); + } + + protected function tearDown(): void + { + // Symfony keeps the trusted hosts for every request after. + Request::setTrustedHosts([]); + + parent::tearDown(); + } + + public function test_only_app_urls_host_is_trusted_in_inertia_mode() + { + config(['app.url' => 'https://example.com', 'app.frontend_url' => 'https://elsewhere.example']); + + $this->assertSame(['^example\.com$'], Frontend::trustedHosts()); + } + + public function test_the_app_answers_at_its_own_host() + { + $host = parse_url(config('app.url'), PHP_URL_HOST); + + $this->get("https://{$host}/login")->assertOk(); + } + + public function test_a_made_up_host_is_refused() + { + $this->get('https://evil.example/login')->assertBadRequest(); + $this->get('https://sub.'.parse_url(config('app.url'), PHP_URL_HOST).'/login')->assertBadRequest(); + } +} From 774d18c952c2f2044d99e927a6447fc94e7f6821 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:24:25 +0000 Subject: [PATCH 11/36] fix(headers): send keyring's security headers with the app's own pages --- bootstrap/app.php | 5 +++++ tests/Feature/SecurityHeadersTest.php | 32 +++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 tests/Feature/SecurityHeadersTest.php diff --git a/bootstrap/app.php b/bootstrap/app.php index 8271cdf..fbf63b9 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -8,6 +8,7 @@ use Illuminate\Foundation\Configuration\Middleware; use Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets; use Illuminate\Http\Request; +use Keyring\Http\Middleware\AddSecurityHeaders; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( @@ -23,10 +24,14 @@ // this check locally and in the PHP tests. $middleware->trustHosts(at: fn () => Frontend::trustedHosts(), subdomains: false); + // Keyring's security headers on the app's own pages too, as its own + // routes have them: no framing (X-Frame-Options: DENY), nosniff, a + // same-origin Referrer-Policy, no caching and an opener policy. $middleware->web(append: [ HandleAppearance::class, HandleInertiaRequests::class, AddLinkHeadersForPreloadedAssets::class, + AddSecurityHeaders::class, ]); }) ->withExceptions(function (Exceptions $exceptions): void { diff --git a/tests/Feature/SecurityHeadersTest.php b/tests/Feature/SecurityHeadersTest.php new file mode 100644 index 0000000..b93cc6f --- /dev/null +++ b/tests/Feature/SecurityHeadersTest.php @@ -0,0 +1,32 @@ +get(route('home')) + ->assertOk() + ->assertHeader('X-Frame-Options', 'DENY') + ->assertHeader('X-Content-Type-Options', 'nosniff') + ->assertHeader('Referrer-Policy', 'same-origin') + ->assertHeader('Cross-Origin-Opener-Policy', 'same-origin-allow-popups'); + } + + public function test_keyrings_pages_still_get_them() + { + $this->get(route('login')) + ->assertOk() + ->assertHeader('X-Frame-Options', 'DENY'); + } +} From 0e4f1f3b3e7d5cb58b8079bbb20c52dde8a367b2 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:24:25 +0000 Subject: [PATCH 12/36] fix(appearance): only let light, dark or system reach the page's inline script --- app/Http/Middleware/HandleAppearance.php | 19 +++++++++- resources/views/app.blade.php | 2 +- tests/Feature/AppearanceTest.php | 47 ++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 tests/Feature/AppearanceTest.php diff --git a/app/Http/Middleware/HandleAppearance.php b/app/Http/Middleware/HandleAppearance.php index 1a01684..8127772 100644 --- a/app/Http/Middleware/HandleAppearance.php +++ b/app/Http/Middleware/HandleAppearance.php @@ -16,8 +16,25 @@ class HandleAppearance */ public function handle(Request $request, Closure $next): Response { - View::share('appearance', $request->cookie('appearance') ?? 'system'); + View::share('appearance', self::appearance($request)); return $next($request); } + + /** + * The appearance the browser's cookie asks for: light, dark or system. + * The cookie isn't encrypted (bootstrap/app.php), so anyone can set it + * to anything, and anything else is system. + * + * @return 'light'|'dark'|'system' + */ + public static function appearance(Request $request): string + { + $appearance = $request->cookie('appearance'); + + return match ($appearance) { + 'light', 'dark' => $appearance, + default => 'system', + }; + } } diff --git a/resources/views/app.blade.php b/resources/views/app.blade.php index 595ea95..c58de56 100644 --- a/resources/views/app.blade.php +++ b/resources/views/app.blade.php @@ -7,7 +7,7 @@ {{-- Inline script to detect system dark mode preference and apply it immediately --}} ', 'system'], + 'another case' => ['DARK', 'system'], + ]; + } + + #[DataProvider('cookies')] + public function test_the_page_only_ever_gets_light_dark_or_system(string $cookie, string $appearance) + { + $html = $this->withUnencryptedCookie('appearance', $cookie)->get(route('home'))->assertOk()->getContent(); + + $this->assertStringContainsString("const appearance = '{$appearance}';", $html); + $this->assertStringNotContainsString('alert(1)', $html); + } + + public function test_dark_marks_the_page_dark_before_it_paints() + { + $this->withUnencryptedCookie('appearance', 'dark')->get(route('home'))->assertSee('', false); + $this->withUnencryptedCookie('appearance', 'nonsense')->get(route('home'))->assertDontSee('class="dark"', false); + } +} From 50fa72e72c7ea28e7fbc5712599bf5c0202e7099 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:24:25 +0000 Subject: [PATCH 13/36] fix(mail): build the password reset link from app_url, or fail, never from the request --- app/Notifications/Keyring/LaravelMail.php | 20 ++++++++++++++++- tests/Feature/Emails/KeyringEmailsTest.php | 26 ++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/app/Notifications/Keyring/LaravelMail.php b/app/Notifications/Keyring/LaravelMail.php index 478f51d..1224bab 100644 --- a/app/Notifications/Keyring/LaravelMail.php +++ b/app/Notifications/Keyring/LaravelMail.php @@ -7,6 +7,7 @@ use Illuminate\Auth\Notifications\ResetPassword; use Illuminate\Contracts\Auth\CanResetPassword; use Illuminate\Notifications\Messages\MailMessage; +use LogicException; /** * Laravel's own email verification and password reset emails, which Keyring @@ -34,16 +35,33 @@ public static function verifyEmail(object $notifiable, string $url): MailMessage /** * Laravel only hands over the token, so the link is built the way its * own email does: with Keyring's callback, or the password.reset route. + * That route's link starts at APP_URL, never at the host the request + * that asked for the email came in on, which whoever sent it chose. */ public static function resetPassword(CanResetPassword $notifiable, #[\SensitiveParameter] string $token): MailMessage { $url = ResetPassword::$createUrlCallback !== null ? (ResetPassword::$createUrlCallback)($notifiable, $token) - : url(route('password.reset', ['token' => $token, 'email' => $notifiable->getEmailForPasswordReset()], false)); + : self::appUrl().route('password.reset', ['token' => $token, 'email' => $notifiable->getEmailForPasswordReset()], false); return (new MailMessage)->subject(__('Reset your password'))->action(__('Reset password'), $url)->view(['html' => 'emails.keyring.reset-password', 'text' => 'emails.keyring.text.reset-password'], [ 'url' => $url, 'minutes' => (int) config('auth.passwords.'.config('auth.defaults.passwords').'.expire', 60), ]); } + + /** + * APP_URL, without its trailing slash. An app without one has no + * address to send anyone back to, so it's an error, not a guess. + */ + private static function appUrl(): string + { + $url = rtrim((string) config('app.url'), '/'); + + if (! is_string(parse_url($url, PHP_URL_HOST))) { + throw new LogicException('APP_URL has to be set to build the password reset link.'); + } + + return $url; + } } diff --git a/tests/Feature/Emails/KeyringEmailsTest.php b/tests/Feature/Emails/KeyringEmailsTest.php index 8c5dd7b..4a73ba6 100644 --- a/tests/Feature/Emails/KeyringEmailsTest.php +++ b/tests/Feature/Emails/KeyringEmailsTest.php @@ -22,6 +22,7 @@ use Keyring\Notifications\SecondFactorFailed; use Keyring\Notifications\SecurityNotice; use Keyring\Notifications\SuspiciousActivity; +use LogicException; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\Mime\Email; use Tests\TestCase; @@ -263,6 +264,31 @@ public function test_the_password_reset_email_uses_the_apps_template() $this->assertStringContainsString(route('password.reset', ['token' => 'a-token', 'email' => 'nora@example.com']), $rendered['text']); } + /** + * Without Keyring's callback, the link is the password.reset route at + * APP_URL, whatever host the request that sent it came in on. + */ + public function test_the_password_reset_link_without_keyrings_callback_starts_at_app_url() + { + $callback = ResetPassword::$createUrlCallback; + ResetPassword::$createUrlCallback = null; + + try { + $this->get('http://evil.example/login'); + + $mail = (new ResetPassword('a-token'))->toMail((new User)->forceFill(['email' => 'nora@example.com'])); + + $this->assertSame(rtrim(config('app.url'), '/').'/reset-password/a-token?email=nora%40example.com', $mail->actionUrl); + + config(['app.url' => '']); + + $this->expectException(LogicException::class); + (new ResetPassword('a-token'))->toMail((new User)->forceFill(['email' => 'nora@example.com'])); + } finally { + ResetPassword::$createUrlCallback = $callback; + } + } + public function test_the_inbox_preview_line_says_what_happened() { $notice = $this->render((new PasswordChanged(when: 'now'))->toMail(new User))['html']; From a100f5989d326d6981b3d2e6ab3672b8bbed0bb4 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:24:33 +0000 Subject: [PATCH 14/36] docs: keep laravel's port for the kit alone, and turn debug off in production --- .env.example | 4 +++- README.md | 4 ++++ docs/headless-api.md | 4 +++- kits/inertia-react/README.md | 6 ++++++ kits/nuxt/README.md | 4 ++-- kits/tanstack-start/README.md | 4 ++-- 6 files changed, 20 insertions(+), 6 deletions(-) diff --git a/.env.example b/.env.example index 8714d91..b91fad2 100644 --- a/.env.example +++ b/.env.example @@ -1,6 +1,7 @@ APP_NAME="Keyring Example" APP_ENV=local APP_KEY= +# For local work only: on a server, APP_ENV=production and APP_DEBUG=false. APP_DEBUG=true APP_URL=http://localhost:8000 @@ -20,7 +21,8 @@ APP_URL=http://localhost:8000 # 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. +# headless mode anything on loopback that forwards to Laravel is trusted: keep +# Laravel's port reachable by the frontend's server only, or pin this. # TRUSTED_PROXIES=127.0.0.1 APP_LOCALE=en diff --git a/README.md b/README.md index 460e63d..4cc6bea 100644 --- a/README.md +++ b/README.md @@ -220,6 +220,8 @@ Passkeys need a secure context. `http://localhost` counts, so open the app as `l Emails (codes, email change links, security notices) go to `storage/logs/laravel.log`. `composer dev` shows that log as it's written. +On a server, set `APP_ENV=production` and `APP_DEBUG=false`: `.env.example` turns debug on for local work, and with it an error shows its message, file and stack trace to whoever caused it. Laravel only answers for `APP_URL`'s host (and, headless, `FRONTEND_URL`'s): a request with any other `Host` gets a `400`, so no link it builds can follow a made-up one. Laravel skips that check when `APP_ENV` is `local`. + To see how they look, open `http://localhost:8000/emails` while running locally: a gallery of every email the app sends, Keyring's and Laravel's verification and password reset emails, each with sample content (see [Emails](#emails)). @@ -364,6 +366,8 @@ Each link signs the browser out first, then signs in or starts the sign in as on 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, Laravel trusts a proxy on loopback by default (`TRUSTED_PROXIES` is `127.0.0.1,::1`), since that's how the frontend's server on the same host passes on the browser's host, scheme and address. Anything else that reaches Laravel's port from loopback is believed too, so Laravel's port must only be reachable by the frontend's server (listening on `127.0.0.1`, with no tunnel or published port in front of it), or `TRUSTED_PROXIES` should be pinned to the address the frontend's server connects from. + 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. diff --git a/docs/headless-api.md b/docs/headless-api.md index 77f6d0e..397ff69 100644 --- a/docs/headless-api.md +++ b/docs/headless-api.md @@ -67,7 +67,9 @@ A headless kit's `.env.example` sets these on top of the app's own: | `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. +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. The default is there because the frontend's server reaches Laravel over loopback on the same host, and Laravel has to believe it about the browser's host and address. So make Laravel's port reachable by the frontend's server only (listen on `127.0.0.1`, and keep it off the network), or pin `TRUSTED_PROXIES` to the address the frontend's server connects from. An empty value counts as unset, for `FRONTEND_URL` and `TRUSTED_PROXIES` both, and spaces around the commas are fine. + +Laravel only answers for `APP_URL`'s host and `FRONTEND_URL`'s (Laravel's `TrustHosts`, in `bootstrap/app.php`), as the frontend's server passes it on in `X-Forwarded-Host`. A request for any other host is refused with a `400`, so no link Laravel builds can follow a made-up `Host`. Laravel skips that check when `APP_ENV` is `local`, and in the PHP tests. Nothing else changes. In particular, there's no Sanctum: see [Calling Laravel](#calling-laravel). diff --git a/kits/inertia-react/README.md b/kits/inertia-react/README.md index b9d9b77..3972fcf 100644 --- a/kits/inertia-react/README.md +++ b/kits/inertia-react/README.md @@ -34,3 +34,9 @@ composer dev Either way you get a `.env` with an app key and a migrated SQLite database. `php artisan db:seed` adds a test user, `test@example.com` with the password `password`, who is asked to add a second factor at their first sign in. `APP_URL` in `.env` has to be the address you open the app at: Keyring builds the passkey origin and every emailed link from it. `laravel new my-app` sets it (to `http://my-app.test` under Herd or Valet, `http://localhost:8000` otherwise), and `composer create-project` sets `http://localhost:8000`, where `composer dev` serves. After `laravel new .`, or to serve the app anywhere else, set it yourself. + +## In production + +- In `.env`: `APP_ENV=production` and `APP_DEBUG=false`. `.env.example` turns debug on for local work, and with it any error page shows the exception's message, file, stack trace and the request to whoever caused it. +- `APP_URL` as the site's `https://` address, such as `https://example.com`, and `SESSION_SECURE_COOKIE=true`. Passkeys need a secure origin, Keyring builds every emailed link from `APP_URL`, and Laravel only answers for `APP_URL`'s host: a request with any other `Host` gets a `400`. +- `TRUSTED_PROXIES`, when a load balancer or reverse proxy is in front, as its addresses, never `*`: only then is it believed about HTTPS and the visitor's address. diff --git a/kits/nuxt/README.md b/kits/nuxt/README.md index e76faf4..5db6467 100644 --- a/kits/nuxt/README.md +++ b/kits/nuxt/README.md @@ -159,7 +159,7 @@ The proxy is `server/lib/proxy.ts`, run by Nitro's server middleware (`server/mi - passes Laravel's status, headers and every `Set-Cookie` back unchanged, with `Cache-Control: no-store, private`; - passes redirects back for the browser to follow, never following them itself. -Laravel believes those four headers from loopback only (`TRUSTED_PROXIES` defaults to `127.0.0.1,::1` in headless mode), so run this server and Laravel on the same host. Anything else on that host can set them too. +Laravel believes those four headers from loopback only (`TRUSTED_PROXIES` defaults to `127.0.0.1,::1` in headless mode), so run this server and Laravel on the same host. Anything else on that host can set them too, and so can anything that reaches Laravel's port through a tunnel or proxy of its own on that host: keep Laravel's port reachable by this server only (listening on `127.0.0.1`, never on the network), or pin `TRUSTED_PROXIES` to the address this server connects from. Laravel also only answers for `APP_URL`'s host and `FRONTEND_URL`'s, so a made-up `X-Forwarded-Host` gets a `400`, not links to it. Under `nuxt dev`, Nitro runs the server in a worker behind a proxy of its own, on a local socket with no address, and that proxy only says who the browser is when the browser hasn't said so itself. So in development the browser's address is loopback's: the dev server listens on `localhost` only. Keep it that way: don't start it with `--host`, or share it through a tunnel (ngrok, Cloudflare Tunnel, `tailscale serve` and the like), since every visitor would reach Laravel as loopback, and share one address in its rate limits and security log. The production server always reads the socket. @@ -255,7 +255,7 @@ Build once with `npm run build`, then run Laravel behind your PHP server, its qu - In Laravel's `.env`: `APP_ENV=production` and `APP_DEBUG=false`. In headless mode every answer, an error's included, goes straight to the browser through `/backend`: with `APP_DEBUG=true`, an exception's message, file and stack trace are in its JSON for anyone to read. - `APP_URL` and `FRONTEND_URL`, in Laravel's `.env` and this app's environment, as the site's `https://` address, such as `https://example.com`. Passkeys need a secure origin, and Keyring builds every emailed link from `APP_URL`. Set `SESSION_SECURE_COOKIE=true` too, so the session cookie is only sent over HTTPS. This app's own cookies (`__Host-keyring_notice`, `__Host-keyring_intended`) are Secure whenever `FRONTEND_URL` is `https://`. - `LARAVEL_URL`, where this app reaches Laravel, on loopback, such as `http://127.0.0.1:8000`. -- Trusted proxies on both sides. Laravel believes the forwarded headers from loopback only (`TRUSTED_PROXIES` is `127.0.0.1,::1` in headless mode), which is this app's server: leave it, or set it to the addresses this server connects from, never `*`. In front of this app, set `FRONTEND_TRUSTED_PROXIES` to your load balancer or reverse proxy's addresses (see [One origin](#one-origin)), so the browser's own address reaches Laravel's rate limits and security log, and leave it empty when browsers connect to `npm start` directly. +- Trusted proxies on both sides. Laravel believes the forwarded headers from loopback only (`TRUSTED_PROXIES` is `127.0.0.1,::1` in headless mode), which is this app's server: leave it, or set it to the addresses this server connects from, never `*`. Laravel's port must only be reachable by this app's server: have your PHP server listen on `127.0.0.1`, and never publish that port or put a tunnel in front of it, or pin `TRUSTED_PROXIES`. In front of this app, set `FRONTEND_TRUSTED_PROXIES` to your load balancer or reverse proxy's addresses (see [One origin](#one-origin)), so the browser's own address reaches Laravel's rate limits and security log, and leave it empty when browsers connect to `npm start` directly. - `HOST`, when a proxy on another machine connects to this app: the built server listens on `localhost` unless told otherwise, `npm start` or not. diff --git a/kits/tanstack-start/README.md b/kits/tanstack-start/README.md index d6cae32..2cadda1 100644 --- a/kits/tanstack-start/README.md +++ b/kits/tanstack-start/README.md @@ -140,7 +140,7 @@ The proxy is `src/server/proxy.ts`, called from the server entry (`src/server.ts - passes Laravel's status, headers and every `Set-Cookie` back unchanged, with `Cache-Control: no-store, private`; - passes redirects back for the browser to follow, never following them itself. -Laravel believes those four headers from loopback only (`TRUSTED_PROXIES` defaults to `127.0.0.1,::1` in headless mode), so run this server and Laravel on the same host. Anything else on that host can set them too. +Laravel believes those four headers from loopback only (`TRUSTED_PROXIES` defaults to `127.0.0.1,::1` in headless mode), so run this server and Laravel on the same host. Anything else on that host can set them too, and so can anything that reaches Laravel's port through a tunnel or proxy of its own on that host: keep Laravel's port reachable by this server only (listening on `127.0.0.1`, never on the network), or pin `TRUSTED_PROXIES` to the address this server connects from. Laravel also only answers for `APP_URL`'s host and `FRONTEND_URL`'s, so a made-up `X-Forwarded-Host` gets a `400`, not links to it. | Variable | Default | | | -------------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -228,7 +228,7 @@ Build once with `npm run build`, then run Laravel behind your PHP server, its qu - In Laravel's `.env`: `APP_ENV=production` and `APP_DEBUG=false`. In headless mode every answer, an error's included, goes straight to the browser through `/backend`: with `APP_DEBUG=true`, an exception's message, file and stack trace are in its JSON for anyone to read. - `APP_URL` and `FRONTEND_URL`, in Laravel's `.env` and this app's environment, as the site's `https://` address, such as `https://example.com`. Passkeys need a secure origin, and Keyring builds every emailed link from `APP_URL`. Set `SESSION_SECURE_COOKIE=true` too, so the session cookie is only sent over HTTPS. This app's own cookies (`__Host-keyring_notice`, `__Host-keyring_intended`) are Secure whenever `FRONTEND_URL` is `https://`. - `LARAVEL_URL`, where this app reaches Laravel, on loopback, such as `http://127.0.0.1:8000`. -- Trusted proxies on both sides. Laravel believes the forwarded headers from loopback only (`TRUSTED_PROXIES` is `127.0.0.1,::1` in headless mode), which is this app's server: leave it, or set it to the addresses this server connects from, never `*`. In front of this app, set `FRONTEND_TRUSTED_PROXIES` to your load balancer or reverse proxy's addresses (see [One origin](#one-origin)), so the browser's own address reaches Laravel's rate limits and security log, and leave it empty when browsers connect to `npm start` directly. +- Trusted proxies on both sides. Laravel believes the forwarded headers from loopback only (`TRUSTED_PROXIES` is `127.0.0.1,::1` in headless mode), which is this app's server: leave it, or set it to the addresses this server connects from, never `*`. Laravel's port must only be reachable by this app's server: have your PHP server listen on `127.0.0.1`, and never publish that port or put a tunnel in front of it, or pin `TRUSTED_PROXIES`. In front of this app, set `FRONTEND_TRUSTED_PROXIES` to your load balancer or reverse proxy's addresses (see [One origin](#one-origin)), so the browser's own address reaches Laravel's rate limits and security log, and leave it empty when browsers connect to `npm start` directly. From a9a4c07964f2f348610a341416b473c57e674e12 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 16:29:19 +0000 Subject: [PATCH 15/36] fix(export): refuse unreleasable lockfiles, unknown monorepo-only tags, escaping symlinks and kit.json paths, and scan every file's bytes --- README.md | 10 +- bin/export-kit.mjs | 251 ++++++++++++++++++++++++++++--- bin/export-kit.test.mjs | 319 +++++++++++++++++++++++++++++++++++++++- 3 files changed, 554 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 4cc6bea..c659de0 100644 --- a/README.md +++ b/README.md @@ -140,13 +140,13 @@ The output is what the kit's repository gets: a complete Laravel app with no wor 1. Copies every file git tracks, as it is in the working tree (clean, unless `--allow-dirty`; untracked files never come along), except `kits/`, `packages/`, `bin/`, `.github/` and the kit's `exclude` list. Symlinks stay symlinks. 2. Inlines the workspace packages the kit uses: copies their files (minus the entry's `exclude`) into the app, rewrites imports of them (`@keyringjs/ui-react/button` becomes `@/components/ui/button` again), and adds their dependencies to the `package.json` of the app they're inlined into. 3. Copies the kit's own files over the result. -4. Leaves out text tagged monorepo-only: a line whose comment (`//`, `#`, `/*`, `|\*\/)/; +// The tag itself, wherever it is: what's left of it after the export +// stripped what it recognised is a tag it didn't. +const TAG = '@monorepo-only'; + export class ExportError extends Error {} function fail(message) { @@ -94,6 +105,33 @@ function matches(file, entry) { return entry.endsWith('/') ? file.startsWith(entry) : file === entry; } +/** + * Refuses a kit.json path that could reach outside the export or the + * repository: absolute (POSIX, Windows or UNC), with a `..` segment, or in + * `.git`. A trailing slash (a directory) is fine. + */ +export function checkRelativePath(value, label) { + if (typeof value !== 'string' || value === '') { + fail(`${label} has to be a path`); + } + + if (/^[\\/]|^[a-z]:/i.test(value)) { + fail(`${label} has to be relative, not ${value}`); + } + + const segments = value.split(/[\\/]/); + + if (segments.includes('..')) { + fail(`${label} can't have a .. in it: ${value}`); + } + + if (segments.some((segment) => segment.toLowerCase() === '.git')) { + fail(`${label} can't be in .git: ${value}`); + } + + return value; +} + /** RFC 7396 JSON merge patch, keeping the target's key order. */ export function mergePatch(target, patch) { if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) { @@ -282,6 +320,17 @@ function isWorkspace(root, workspace) { ); } +/** `file` in `out`, refusing anything that would land outside it. */ +function inside(out, file) { + const target = path.resolve(out, file); + + if (!target.startsWith(out + path.sep)) { + fail(`${file} would be written outside the export`); + } + + return target; +} + function copyFile(from, to) { fs.mkdirSync(path.dirname(to), { recursive: true }); fs.rmSync(to, { force: true }); @@ -322,8 +371,9 @@ function run(command, args, cwd, log = console.log) { } /** - * Lists the files whose path or text still contains any of `names`, with - * the name. Binary files and symlinks are only checked by their path. + * Lists the files whose path, contents or symlink target still contains + * any of `names`, with the name. A binary file is searched for each name's + * UTF-8 bytes, so a name in an image's or font's metadata counts too. */ function findLeftovers(out, files, names) { const leftovers = []; @@ -336,21 +386,30 @@ function findLeftovers(out, files, names) { } const target = path.join(out, file); + const stat = lstat(target); + + if (stat?.isSymbolicLink()) { + const link = fs.readlinkSync(target); + + for (const name of names) { + if (link.includes(name)) { + leftovers.push( + `${file} (${name}, in its symlink's target)`, + ); + } + } - if (lstat(target)?.isFile() !== true) { continue; } - const buffer = fs.readFileSync(target); - - if (!isText(buffer)) { + if (stat?.isFile() !== true) { continue; } - const text = buffer.toString('utf8'); + const buffer = fs.readFileSync(target); for (const name of names) { - if (text.includes(name)) { + if (buffer.includes(Buffer.from(name, 'utf8'))) { leftovers.push(`${file} (${name})`); } } @@ -359,6 +418,90 @@ function findLeftovers(out, files, names) { return leftovers; } +/** + * The symlinks among `files`, each with whether it stays inside `out`: + * relative, and resolving to a path under it. An absolute target never + * does, since the export is unpacked somewhere else. + */ +function symlinksIn(out, files) { + const links = []; + + for (const file of files) { + const target = path.join(out, file); + + if (lstat(target)?.isSymbolicLink() !== true) { + continue; + } + + const link = fs.readlinkSync(target); + const resolved = path.resolve(path.dirname(target), link); + + links.push({ + file, + link, + inside: + !path.isAbsolute(link) && resolved.startsWith(out + path.sep), + }); + } + + return links; +} + +/** + * What keeps an npm lockfile from being released as it is: a package that's + * a link or a `file:` path (a local checkout, or a workspace), or one + * downloaded from a registry without the `integrity` hash npm checks it + * against. Packages bundled inside another (`inBundle`) come with it. + */ +export function unreleasableLockEntries(lock) { + const problems = []; + + for (const [key, entry] of Object.entries(lock.packages ?? {})) { + if (key === '' || entry.inBundle) { + continue; + } + + const resolved = + typeof entry.resolved === 'string' ? entry.resolved : ''; + const version = typeof entry.version === 'string' ? entry.version : ''; + + if (entry.link) { + problems.push(`${key} (a link to ${resolved || 'a local path'})`); + } else if ( + resolved.startsWith('file:') || + version.startsWith('file:') + ) { + problems.push(`${key} (a local file: package)`); + } else if (/^https?:/i.test(resolved)) { + if (typeof entry.integrity !== 'string' || entry.integrity === '') { + problems.push(`${key} (no integrity for ${resolved})`); + } + } else if (resolved !== '' && !/^git\+|^git:/.test(resolved)) { + problems.push(`${key} (resolved to a local path, ${resolved})`); + } else if (resolved === '' && key.startsWith('node_modules/')) { + problems.push(`${key} (not resolved from anywhere)`); + } + } + + // The dependencies of lockfile v1, which npm 7+ still writes alongside. + const walk = (dependencies, prefix) => { + for (const [name, entry] of Object.entries(dependencies ?? {})) { + const version = + typeof entry.version === 'string' ? entry.version : ''; + + if (version.startsWith('file:') || version.startsWith('link:')) { + problems.push(`${prefix}${name} (a local ${version})`); + } + + walk(entry.dependencies, `${prefix}${name} > `); + } + }; + + walk(lock.dependencies, ''); + + return problems; +} + /** * A lockfile for one workspace of the monorepo as a project of its own, * from the monorepo's: what's installed for the workspace itself (under @@ -482,6 +625,18 @@ export function exportKit({ fail(`kits/${kitName}/kit.json says its name is "${kit.name}"`); } + for (const [index, entry] of kit.copy.entries()) { + checkRelativePath(entry.to, `copy[${index}].to`); + } + + for (const [index, entry] of kit.inline.entries()) { + checkRelativePath(entry.to, `inline[${index}].to`); + } + + if (kit.readme !== undefined) { + checkRelativePath(kit.readme, 'readme'); + } + const out = path.resolve(outArg); if ( @@ -580,7 +735,7 @@ export function exportKit({ fail(`inline: ${file} would overwrite the app's ${target}`); } - copyFile(path.join(root, file), path.join(out, target)); + copyFile(path.join(root, file), inside(out, target)); written.add(target); if ( @@ -637,7 +792,7 @@ export function exportKit({ ? entry.to + file.slice(entry.from.length) : entry.to; - copyFile(path.join(root, file), path.join(out, target)); + copyFile(path.join(root, file), inside(out, target)); written.add(target); } } @@ -777,9 +932,14 @@ export function exportKit({ // in a template literal, in an unquoted CSS url(), or in prose. Nor may // anything mention what the kit forbids, in its text or its path: what // it excluded, which whatever still reaches for would break without. - const exported = [...written].filter( - (file) => !/\.lock$|-lock\.json$/.test(file), - ); + // + // Only the lockfiles step 8 rewrites wait until then: until npm and + // composer have trimmed them, they still list what the kit removed. + const lockfiles = [ + 'composer.lock', + ...apps.map((app) => `${app}package-lock.json`), + ]; + const exported = [...written].filter((file) => !lockfiles.includes(file)); const leftovers = findLeftovers(out, exported, workspaceNames); if (leftovers.length > 0) { @@ -799,12 +959,46 @@ export function exportKit({ ); } + // A tag in a comment stripMonorepoOnly doesn't recognise (Blade's + // {{-- --}}, an ini file's ;, SQL's --) keeps its line, monorepo-only + // text and all, so any tag still there stops the export. + const tagged = findLeftovers(out, [...written], [TAG]).filter( + (leftover) => !leftover.endsWith('in its path)'), + ); + + if (tagged.length > 0) { + fail( + `these files still have ${TAG} in them, in a comment the export ` + + "doesn't recognise (only //, #, /*, diff --git a/app/Http/Middleware/TrustHosts.php b/app/Http/Middleware/TrustHosts.php new file mode 100644 index 0000000..6de17f0 --- /dev/null +++ b/app/Http/Middleware/TrustHosts.php @@ -0,0 +1,56 @@ +shouldSpecifyTrustedHosts() || $request->is(self::HEALTH_PATH)) { + return $next($request); + } + + Request::setTrustedHosts(array_filter($this->hosts())); + + try { + // Checked now, while a made-up host still gets a 400 here, + // rather than wherever the host is first read. + $request->getHost(); + + return $next($request); + } finally { + // Symfony keeps trusted hosts in static properties, which + // outlive the request under Octane. The next request's + // TrustProxies reads its host before this runs, and has to + // read it unchecked, or a headless frontend's Host would be + // refused there. + Request::setTrustedHosts([]); + } + } +} diff --git a/app/Support/Frontend.php b/app/Support/Frontend.php index 9b5be84..389711b 100644 --- a/app/Support/Frontend.php +++ b/app/Support/Frontend.php @@ -5,6 +5,7 @@ namespace App\Support; use Illuminate\Http\Request; +use LogicException; /** * Who builds the pages: the Inertia app Laravel serves, or a headless @@ -35,24 +36,32 @@ public static function wantsJson(Request $request): bool * passes on carry the browser's host in X-Forwarded-Host, which counts * here only from a trusted proxy (config/app.php). * + * A URL without a host, such as an empty APP_URL or one without its + * scheme (example.com), throws rather than leaving the list empty, + * which would trust every host. + * * @return list + * + * @throws LogicException */ public static function trustedHosts(): array { - $urls = [config('app.url')]; + $urls = ['APP_URL' => config('app.url')]; if (self::headless()) { - $urls[] = config('app.frontend_url'); + $urls['FRONTEND_URL'] = config('app.frontend_url'); } $hosts = []; - foreach ($urls as $url) { + foreach ($urls as $name => $url) { $host = is_string($url) ? parse_url($url, PHP_URL_HOST) : null; - if (is_string($host) && $host !== '') { - $hosts[] = '^'.preg_quote(strtolower($host)).'$'; + if (! is_string($host) || $host === '') { + throw new LogicException("{$name} has to be a full URL, such as https://example.com, for Laravel to know which hosts to answer for."); } + + $hosts[] = '^'.preg_quote(strtolower($host)).'$'; } return array_values(array_unique($hosts)); diff --git a/bootstrap/app.php b/bootstrap/app.php index fbf63b9..45da024 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -2,11 +2,14 @@ use App\Http\Middleware\HandleAppearance; use App\Http\Middleware\HandleInertiaRequests; +use App\Http\Middleware\TrustHosts; use App\Support\Frontend; use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; use Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets; +use Illuminate\Http\Middleware\TrustHosts as LaravelTrustHosts; +use Illuminate\Http\Middleware\TrustProxies; use Illuminate\Http\Request; use Keyring\Http\Middleware\AddSecurityHeaders; @@ -21,8 +24,13 @@ // Only APP_URL's host, and a headless frontend's, so no link url() // builds can follow a Host header someone made up. Laravel skips - // this check locally and in the PHP tests. + // this check locally and in the PHP tests, and the app's own + // TrustHosts skips the health check at /up. It runs after + // TrustProxies, not in Laravel's place before it, so the host it + // checks is a trusted proxy's X-Forwarded-Host: the frontend's. $middleware->trustHosts(at: fn () => Frontend::trustedHosts(), subdomains: false); + $middleware->replace(LaravelTrustHosts::class, []); + $middleware->replace(TrustProxies::class, [TrustProxies::class, TrustHosts::class]); // Keyring's security headers on the app's own pages too, as its own // routes have them: no framing (X-Frame-Options: DENY), nosniff, a diff --git a/docs/headless-api.md b/docs/headless-api.md index 397ff69..42697d4 100644 --- a/docs/headless-api.md +++ b/docs/headless-api.md @@ -69,7 +69,7 @@ A headless kit's `.env.example` sets these on top of the app's own: 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. The default is there because the frontend's server reaches Laravel over loopback on the same host, and Laravel has to believe it about the browser's host and address. So make Laravel's port reachable by the frontend's server only (listen on `127.0.0.1`, and keep it off the network), or pin `TRUSTED_PROXIES` to the address the frontend's server connects from. An empty value counts as unset, for `FRONTEND_URL` and `TRUSTED_PROXIES` both, and spaces around the commas are fine. -Laravel only answers for `APP_URL`'s host and `FRONTEND_URL`'s (Laravel's `TrustHosts`, in `bootstrap/app.php`), as the frontend's server passes it on in `X-Forwarded-Host`. A request for any other host is refused with a `400`, so no link Laravel builds can follow a made-up `Host`. Laravel skips that check when `APP_ENV` is `local`, and in the PHP tests. +Laravel only answers for `APP_URL`'s host and `FRONTEND_URL`'s (`app/Http/Middleware/TrustHosts.php`, run after `TrustProxies` in `bootstrap/app.php`), as the frontend's server passes it on in `X-Forwarded-Host`; the `Host` header that server sends, Laravel's own address, doesn't count, and neither does `X-Forwarded-Host` from an untrusted address. A request for any other host is refused with a `400`, so no link Laravel builds can follow a made-up `Host`. Both have to be full URLs: one without a host, such as `example.com`, makes every request fail rather than trusting every host. The health check at `/up` answers at any host. Laravel skips the host check when `APP_ENV` is `local`, and in the PHP tests. Nothing else changes. In particular, there's no Sanctum: see [Calling Laravel](#calling-laravel). diff --git a/kits/inertia-react/README.md b/kits/inertia-react/README.md index 3972fcf..0f62c4b 100644 --- a/kits/inertia-react/README.md +++ b/kits/inertia-react/README.md @@ -38,5 +38,5 @@ Either way you get a `.env` with an app key and a migrated SQLite database. `php ## In production - In `.env`: `APP_ENV=production` and `APP_DEBUG=false`. `.env.example` turns debug on for local work, and with it any error page shows the exception's message, file, stack trace and the request to whoever caused it. -- `APP_URL` as the site's `https://` address, such as `https://example.com`, and `SESSION_SECURE_COOKIE=true`. Passkeys need a secure origin, Keyring builds every emailed link from `APP_URL`, and Laravel only answers for `APP_URL`'s host: a request with any other `Host` gets a `400`. +- `APP_URL` as the site's `https://` address, such as `https://example.com`, and `SESSION_SECURE_COOKIE=true`. Passkeys need a secure origin, Keyring builds every emailed link from `APP_URL`, and Laravel only answers for `APP_URL`'s host: a request with any other `Host` gets a `400`, except the health check at `/up`, which a load balancer can call by the server's address. An `APP_URL` without its scheme, such as `example.com`, makes every request fail. - `TRUSTED_PROXIES`, when a load balancer or reverse proxy is in front, as its addresses, never `*`: only then is it believed about HTTPS and the visitor's address. diff --git a/kits/nuxt/README.md b/kits/nuxt/README.md index 5db6467..e82edd0 100644 --- a/kits/nuxt/README.md +++ b/kits/nuxt/README.md @@ -253,7 +253,7 @@ Tab titles end with the app's name, `APP_NAME` from `/api/me`. Build once with `npm run build`, then run Laravel behind your PHP server, its queue worker, and this app with `npm start` (from `frontend/`), on the same host, with these set: - In Laravel's `.env`: `APP_ENV=production` and `APP_DEBUG=false`. In headless mode every answer, an error's included, goes straight to the browser through `/backend`: with `APP_DEBUG=true`, an exception's message, file and stack trace are in its JSON for anyone to read. -- `APP_URL` and `FRONTEND_URL`, in Laravel's `.env` and this app's environment, as the site's `https://` address, such as `https://example.com`. Passkeys need a secure origin, and Keyring builds every emailed link from `APP_URL`. Set `SESSION_SECURE_COOKIE=true` too, so the session cookie is only sent over HTTPS. This app's own cookies (`__Host-keyring_notice`, `__Host-keyring_intended`) are Secure whenever `FRONTEND_URL` is `https://`. +- `APP_URL` and `FRONTEND_URL`, in Laravel's `.env` and this app's environment, as the site's `https://` address, such as `https://example.com`. Passkeys need a secure origin, Keyring builds every emailed link from `APP_URL`, and Laravel only answers for those two hosts: a request with any other gets a `400`, except the health check at `/up`, which a load balancer can call by the server's address, and a URL without its scheme, such as `example.com`, makes every request fail. Set `SESSION_SECURE_COOKIE=true` too, so the session cookie is only sent over HTTPS. This app's own cookies (`__Host-keyring_notice`, `__Host-keyring_intended`) are Secure whenever `FRONTEND_URL` is `https://`. - `LARAVEL_URL`, where this app reaches Laravel, on loopback, such as `http://127.0.0.1:8000`. - Trusted proxies on both sides. Laravel believes the forwarded headers from loopback only (`TRUSTED_PROXIES` is `127.0.0.1,::1` in headless mode), which is this app's server: leave it, or set it to the addresses this server connects from, never `*`. Laravel's port must only be reachable by this app's server: have your PHP server listen on `127.0.0.1`, and never publish that port or put a tunnel in front of it, or pin `TRUSTED_PROXIES`. In front of this app, set `FRONTEND_TRUSTED_PROXIES` to your load balancer or reverse proxy's addresses (see [One origin](#one-origin)), so the browser's own address reaches Laravel's rate limits and security log, and leave it empty when browsers connect to `npm start` directly. - `HOST`, when a proxy on another machine connects to this app: the built server listens on `localhost` unless told otherwise, `npm start` or not. diff --git a/kits/tanstack-start/README.md b/kits/tanstack-start/README.md index 2cadda1..5237640 100644 --- a/kits/tanstack-start/README.md +++ b/kits/tanstack-start/README.md @@ -226,7 +226,7 @@ Tab titles end with the app's name, `APP_NAME` from `/api/me`. Build once with `npm run build`, then run Laravel behind your PHP server, its queue worker, and this app with `npm start` (from `frontend/`), on the same host, with these set: - In Laravel's `.env`: `APP_ENV=production` and `APP_DEBUG=false`. In headless mode every answer, an error's included, goes straight to the browser through `/backend`: with `APP_DEBUG=true`, an exception's message, file and stack trace are in its JSON for anyone to read. -- `APP_URL` and `FRONTEND_URL`, in Laravel's `.env` and this app's environment, as the site's `https://` address, such as `https://example.com`. Passkeys need a secure origin, and Keyring builds every emailed link from `APP_URL`. Set `SESSION_SECURE_COOKIE=true` too, so the session cookie is only sent over HTTPS. This app's own cookies (`__Host-keyring_notice`, `__Host-keyring_intended`) are Secure whenever `FRONTEND_URL` is `https://`. +- `APP_URL` and `FRONTEND_URL`, in Laravel's `.env` and this app's environment, as the site's `https://` address, such as `https://example.com`. Passkeys need a secure origin, Keyring builds every emailed link from `APP_URL`, and Laravel only answers for those two hosts: a request with any other gets a `400`, except the health check at `/up`, which a load balancer can call by the server's address, and a URL without its scheme, such as `example.com`, makes every request fail. Set `SESSION_SECURE_COOKIE=true` too, so the session cookie is only sent over HTTPS. This app's own cookies (`__Host-keyring_notice`, `__Host-keyring_intended`) are Secure whenever `FRONTEND_URL` is `https://`. - `LARAVEL_URL`, where this app reaches Laravel, on loopback, such as `http://127.0.0.1:8000`. - Trusted proxies on both sides. Laravel believes the forwarded headers from loopback only (`TRUSTED_PROXIES` is `127.0.0.1,::1` in headless mode), which is this app's server: leave it, or set it to the addresses this server connects from, never `*`. Laravel's port must only be reachable by this app's server: have your PHP server listen on `127.0.0.1`, and never publish that port or put a tunnel in front of it, or pin `TRUSTED_PROXIES`. In front of this app, set `FRONTEND_TRUSTED_PROXIES` to your load balancer or reverse proxy's addresses (see [One origin](#one-origin)), so the browser's own address reaches Laravel's rate limits and security log, and leave it empty when browsers connect to `npm start` directly. diff --git a/tests/Feature/Headless/TrustHostsTest.php b/tests/Feature/Headless/TrustHostsTest.php index 0e3be7f..6e91719 100644 --- a/tests/Feature/Headless/TrustHostsTest.php +++ b/tests/Feature/Headless/TrustHostsTest.php @@ -2,11 +2,12 @@ namespace Tests\Feature\Headless; +use App\Http\Middleware\TrustHosts; use App\Support\Frontend; use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Http\Middleware\TrustHosts; use Illuminate\Http\Request; use Illuminate\Testing\TestResponse; +use LogicException; use Tests\TestCase; /** @@ -58,15 +59,55 @@ public function test_a_made_up_host_passed_on_by_the_frontends_server_is_refused $this->throughTheFrontend('evil.example')->assertBadRequest(); } - private function throughTheFrontend(string $host): TestResponse + public function test_the_frontends_server_reaching_laravel_by_its_address_is_answered() { - return $this->withServerVariables(['REMOTE_ADDR' => '127.0.0.1']) + // As a kit's server forwards /backend: to Laravel's own address, + // with the browser's host in X-Forwarded-Host. + $this->throughTheFrontend('app.example.test', 'http://127.0.0.1:8001')->assertOk(); + $this->throughTheFrontend('app.example.test', 'http://localhost:8001')->assertOk(); + } + + public function test_a_made_up_host_passed_on_to_laravels_address_is_refused() + { + $this->throughTheFrontend('evil.example', 'http://127.0.0.1:8001')->assertBadRequest(); + } + + public function test_the_forwarded_host_counts_only_from_a_trusted_proxy() + { + $this->throughTheFrontend('app.example.test', 'http://127.0.0.1:8001', peer: '203.0.113.5')->assertBadRequest(); + } + + public function test_the_frontends_requests_are_answered_after_others() + { + // Symfony keeps the trusted hosts in static properties, which + // outlive a request under Octane, as they do between these: the + // next request's TrustProxies reads the Host header before the + // host check runs. + $this->getJson('/api/me')->assertOk(); + $this->throughTheFrontend('app.example.test', 'http://127.0.0.1:8001')->assertOk(); + $this->throughTheFrontend('evil.example', 'http://127.0.0.1:8001')->assertBadRequest(); + $this->throughTheFrontend('app.example.test', 'http://127.0.0.1:8001')->assertOk(); + } + + public function test_a_frontend_url_without_a_host_throws() + { + config(['app.frontend_url' => 'app.example.test']); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('FRONTEND_URL'); + + Frontend::trustedHosts(); + } + + private function throughTheFrontend(string $host, string $laravel = '', string $peer = '127.0.0.1'): TestResponse + { + return $this->withServerVariables(['REMOTE_ADDR' => $peer]) ->withHeaders([ 'X-Forwarded-For' => '203.0.113.9', 'X-Forwarded-Host' => $host, 'X-Forwarded-Proto' => 'https', 'X-Forwarded-Prefix' => '/backend', ]) - ->getJson('/api/me'); + ->getJson($laravel.'/api/me'); } } diff --git a/tests/Feature/TrustHostsTest.php b/tests/Feature/TrustHostsTest.php index 0eb24da..c915777 100644 --- a/tests/Feature/TrustHostsTest.php +++ b/tests/Feature/TrustHostsTest.php @@ -2,10 +2,11 @@ namespace Tests\Feature; +use App\Http\Middleware\TrustHosts; use App\Support\Frontend; use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Http\Middleware\TrustHosts; use Illuminate\Http\Request; +use LogicException; use Tests\TestCase; /** @@ -57,4 +58,47 @@ public function test_a_made_up_host_is_refused() $this->get('https://evil.example/login')->assertBadRequest(); $this->get('https://sub.'.parse_url(config('app.url'), PHP_URL_HOST).'/login')->assertBadRequest(); } + + public function test_the_app_still_answers_at_its_own_host_after_refusing_one() + { + // Symfony keeps the trusted hosts in static properties, which + // outlive a request under Octane, as they do between these. + $host = parse_url(config('app.url'), PHP_URL_HOST); + + $this->get('https://evil.example/login')->assertBadRequest(); + $this->get("https://{$host}/login")->assertOk(); + $this->get('https://evil.example/login')->assertBadRequest(); + } + + public function test_the_health_check_answers_at_any_host() + { + // A load balancer calls it by the server's address. + $this->get('http://10.0.0.5/up')->assertOk(); + $this->get('http://10.0.0.5/login')->assertBadRequest(); + } + + public function test_an_app_url_without_a_host_throws_rather_than_trusting_every_host() + { + foreach (['', 'example.com', '/'] as $url) { + config(['app.url' => $url]); + + try { + Frontend::trustedHosts(); + + $this->fail("APP_URL={$url} was accepted."); + } catch (LogicException $e) { + $this->assertStringContainsString('APP_URL', $e->getMessage()); + } + } + } + + public function test_a_request_is_refused_when_app_url_has_no_host() + { + config(['app.url' => 'example.com']); + + $this->withoutExceptionHandling(); + $this->expectException(LogicException::class); + + $this->get('https://example.com/login'); + } } From 599bf3ed24e8fc4107a988a9e16583276f322525 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 17:09:19 +0000 Subject: [PATCH 19/36] fix(ui): check a continue on this site before visiting it without recovery codes too --- kits/inertia-react/kit.json | 1 + .../keyring/sign-in-methods.test.tsx | 118 ++++++++++++++++++ .../components/keyring/sign-in-methods.tsx | 9 +- .../components/keyring/SignInMethods.test.ts | 97 ++++++++++++++ .../src/components/keyring/SignInMethods.vue | 9 +- 5 files changed, 228 insertions(+), 6 deletions(-) create mode 100644 packages/ui-react/src/components/keyring/sign-in-methods.test.tsx create mode 100644 packages/ui-vue/src/components/keyring/SignInMethods.test.ts diff --git a/kits/inertia-react/kit.json b/kits/inertia-react/kit.json index 297f6d7..e4bb226 100644 --- a/kits/inertia-react/kit.json +++ b/kits/inertia-react/kit.json @@ -80,6 +80,7 @@ "packages/ui-react/src/routes/", "packages/ui-react/src/lib/url.ts", "packages/ui-react/src/lib/url.test.ts", + "packages/ui-react/src/components/keyring/sign-in-methods.test.tsx", "packages/ui-react/src/demo/" ], "unformatted": ["packages/ui-react/src/components/ui/"], diff --git a/packages/ui-react/src/components/keyring/sign-in-methods.test.tsx b/packages/ui-react/src/components/keyring/sign-in-methods.test.tsx new file mode 100644 index 0000000..06fef24 --- /dev/null +++ b/packages/ui-react/src/components/keyring/sign-in-methods.test.tsx @@ -0,0 +1,118 @@ +// @vitest-environment happy-dom +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { + afterEach, + beforeEach, + describe, + expect, + test, + vi, +} from 'vite-plus/test'; +import SignInMethods from '@keyringjs/ui-react/components/keyring/sign-in-methods'; + +const keyring = vi.hoisted(() => ({ + enroll: vi.fn(), +})); + +const router = vi.hoisted(() => ({ + visit: vi.fn(), + reload: vi.fn(), + delete: vi.fn(), + flushAll: vi.fn(), +})); + +vi.mock('@keyringjs/keyring/react', async (importOriginal) => ({ + ...(await importOriginal()), + enroll: keyring.enroll, + supportsWebAuthn: () => true, +})); + +vi.mock('@keyringjs/ui-react/adapter', async (importOriginal) => ({ + ...(await importOriginal()), + router, +})); + +( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } +).IS_REACT_ACT_ENVIRONMENT = true; + +let container: HTMLDivElement; +let root: Root; + +beforeEach(() => { + container = document.createElement('div'); + document.body.append(container); + root = createRoot(container); +}); + +afterEach(() => { + act(() => root.unmount()); + container.remove(); + vi.clearAllMocks(); +}); + +/** Adds a passkey from the Add menu, which answers with `continue`. */ +async function addPasskey(answer: { + recoveryCodes?: string[] | null; + continue?: string; +}) { + const calls = keyring.enroll.mock.calls.length; + keyring.enroll.mockResolvedValue({ message: '', ...answer }); + + await act(async () => { + root.render( + , + ); + }); + + const add = [...container.querySelectorAll('button')].find( + (button) => button.textContent?.trim() === 'Add', + )!; + + await act(async () => { + add.dispatchEvent( + new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }), + ); + }); + + const item = [...document.querySelectorAll('[role="menuitem"]')].find( + (element) => element.textContent?.includes('Passkey'), + ) as HTMLElement; + + await act(async () => { + item.click(); + }); + + expect(keyring.enroll).toHaveBeenCalledTimes(calls + 1); +} + +describe('an enrollment with no recovery codes', () => { + test('carries on to a continue on this site', async () => { + await addPasskey({ recoveryCodes: null, continue: '/billing?x=1' }); + + expect(router.visit).toHaveBeenCalledWith( + `${window.location.origin}/billing?x=1`, + ); + expect(router.reload).not.toHaveBeenCalled(); + }); + + test('never follows a continue to another site, and reloads instead', async () => { + for (const value of [ + 'https://evil.example/x', + '//evil.example', + 'javascript:alert(1)', + ]) { + await addPasskey({ recoveryCodes: null, continue: value }); + } + + expect(router.visit).not.toHaveBeenCalled(); + expect(router.reload).toHaveBeenCalledTimes(3); + }); +}); diff --git a/packages/ui-react/src/components/keyring/sign-in-methods.tsx b/packages/ui-react/src/components/keyring/sign-in-methods.tsx index 1ebf314..c1afbcc 100644 --- a/packages/ui-react/src/components/keyring/sign-in-methods.tsx +++ b/packages/ui-react/src/components/keyring/sign-in-methods.tsx @@ -135,12 +135,15 @@ export default function SignInMethods({ // saved, with a full page load, since that page may not be an Inertia // one. An emailed code gets `continue` too, with no codes, though it // isn't a second factor, so visiting it sends them straight back here - // as a reload would, keeping the toast. + // as a reload would, keeping the toast. Either way, only ever a page on + // this site, whoever gave it. function showCodesOrReload(codes?: string[] | null, continueTo?: string) { + const onThisSite = sameOriginUrl(continueTo); + if (codes) { setRecovery({ codes, continue: continueTo }); - } else if (continueTo) { - router.visit(continueTo); + } else if (onThisSite) { + router.visit(onThisSite); } else { router.reload(); } diff --git a/packages/ui-vue/src/components/keyring/SignInMethods.test.ts b/packages/ui-vue/src/components/keyring/SignInMethods.test.ts new file mode 100644 index 0000000..6e64899 --- /dev/null +++ b/packages/ui-vue/src/components/keyring/SignInMethods.test.ts @@ -0,0 +1,97 @@ +// @vitest-environment happy-dom +import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'; +import { afterEach, describe, expect, test, vi } from 'vite-plus/test'; +import SignInMethods from '@keyringjs/ui-vue/components/keyring/SignInMethods.vue'; + +const keyring = vi.hoisted(() => ({ + enroll: vi.fn(), +})); + +const router = vi.hoisted(() => ({ + visit: vi.fn(), + reload: vi.fn(), + delete: vi.fn(), + flushAll: vi.fn(), +})); + +vi.mock('@keyringjs/keyring/vue', async (importOriginal) => ({ + ...(await importOriginal()), + enroll: keyring.enroll, + supportsWebAuthn: () => true, +})); + +vi.mock('@keyringjs/ui-vue/adapter', async (importOriginal) => ({ + ...(await importOriginal()), + router, +})); + +let wrapper: VueWrapper | undefined; + +afterEach(() => { + wrapper?.unmount(); + wrapper = undefined; + document.body.innerHTML = ''; + vi.clearAllMocks(); +}); + +/** Adds a passkey from the Add menu, which answers with `continue`. */ +async function addPasskey(answer: { + recoveryCodes?: string[] | null; + continue?: string; +}) { + wrapper?.unmount(); + keyring.enroll.mockResolvedValue({ message: '', ...answer }); + + wrapper = mount(SignInMethods, { + attachTo: document.body, + props: { + authenticators: [], + enrollable: ['passkey'], + hasSecondFactor: false, + otherSessions: 0, + mustChangePassword: false, + }, + }); + await flushPromises(); + + const add = wrapper + .findAll('button') + .find((button) => button.text().trim() === 'Add')!; + + await add.trigger('keydown', { key: 'Enter' }); + await flushPromises(); + + const item = [...document.querySelectorAll('[role="menuitem"]')].find( + (element) => element.textContent?.includes('Passkey'), + ) as HTMLElement; + + item.click(); + await flushPromises(); + + expect(keyring.enroll).toHaveBeenCalledOnce(); + keyring.enroll.mockClear(); +} + +describe('an enrollment with no recovery codes', () => { + test('carries on to a continue on this site', async () => { + await addPasskey({ recoveryCodes: null, continue: '/billing?x=1' }); + + expect(router.visit).toHaveBeenCalledWith( + `${window.location.origin}/billing?x=1`, + ); + expect(router.reload).not.toHaveBeenCalled(); + }); + + test('never follows a continue to another site, and reloads instead', async () => { + for (const value of [ + 'https://evil.example/x', + '//evil.example', + 'javascript:alert(1)', + ]) { + await addPasskey({ recoveryCodes: null, continue: value }); + } + + expect(router.visit).not.toHaveBeenCalled(); + expect(router.reload).toHaveBeenCalledTimes(3); + }); +}); diff --git a/packages/ui-vue/src/components/keyring/SignInMethods.vue b/packages/ui-vue/src/components/keyring/SignInMethods.vue index a175f2d..8764d41 100644 --- a/packages/ui-vue/src/components/keyring/SignInMethods.vue +++ b/packages/ui-vue/src/components/keyring/SignInMethods.vue @@ -106,12 +106,15 @@ const offered = computed(() => // method, the page they were going to, and carries on there once the codes // are saved, with a full page load. An emailed code gets `continue` too, // with no codes, though it isn't a second factor, so visiting it sends -// them straight back here as a reload would, keeping the toast. +// them straight back here as a reload would, keeping the toast. Either +// way, only ever a page on this site, whoever gave it. function showCodesOrReload(codes?: string[] | null, continueTo?: string) { + const onThisSite = sameOriginUrl(continueTo); + if (codes) { recovery.value = { codes, continue: continueTo }; - } else if (continueTo) { - router.visit(continueTo); + } else if (onThisSite) { + router.visit(onThisSite); } else { router.reload(); } From be85295918833081dc11e4214db8fef4de416640 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 17:09:47 +0000 Subject: [PATCH 20/36] fix(demo): let the email gallery frame its emails from the same site --- routes/demo.php | 5 ++++- tests/Feature/Demo/EmailGalleryTest.php | 9 ++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/routes/demo.php b/routes/demo.php index 4c2a0ac..2434f3b 100644 --- a/routes/demo.php +++ b/routes/demo.php @@ -27,7 +27,10 @@ Route::get('emails', fn () => view('demo.email-gallery', ['groups' => $gallery->groups()])) ->name('emails.index'); - Route::get('emails/{type}', fn (string $type) => $gallery->sample($type)->render()) + // The gallery shows each one in an iframe, which the security headers + // (X-Frame-Options: DENY) would block, but they keep a page's own. + Route::get('emails/{type}', fn (string $type) => response($gallery->sample($type)->render()) + ->header('X-Frame-Options', 'SAMEORIGIN')) ->whereIn('type', $gallery->types()) ->name('emails.show'); diff --git a/tests/Feature/Demo/EmailGalleryTest.php b/tests/Feature/Demo/EmailGalleryTest.php index 057ee14..64a5cc6 100644 --- a/tests/Feature/Demo/EmailGalleryTest.php +++ b/tests/Feature/Demo/EmailGalleryTest.php @@ -49,7 +49,14 @@ public function test_the_gallery_pages_while_running_locally() ->assertSeeInOrder(EmailGallery::GROUPS) ->assertSee('data-email="new_device"', false); - $this->get('/emails/new_device')->assertOk()->assertSee('', false); + $this->get('/emails')->assertHeader('X-Frame-Options', 'DENY'); + + // The gallery's iframes show them, from the same site only. + $this->get('/emails/new_device') + ->assertOk() + ->assertSee('', false) + ->assertHeader('X-Frame-Options', 'SAMEORIGIN') + ->assertHeader('X-Content-Type-Options', 'nosniff'); $this->get('/emails/new_device/text') ->assertOk() From 28b86390d7ef2ad0b63f12d85e62253c7c67d766 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 17:14:49 +0000 Subject: [PATCH 21/36] fix(tanstack): treat a built server as production whatever node_env says, and test the built server --- .github/workflows/kits.yml | 5 +- kits/tanstack-start/README.md | 2 + kits/tanstack-start/src/server.ts | 3 +- kits/tanstack-start/src/server/config.ts | 18 ++- kits/tanstack-start/src/server/proxy.test.ts | 13 +- kits/tanstack-start/test/build.test.mjs | 157 +++++++++++++++++++ 6 files changed, 190 insertions(+), 8 deletions(-) create mode 100644 kits/tanstack-start/test/build.test.mjs diff --git a/.github/workflows/kits.yml b/.github/workflows/kits.yml index 9e5fd99..39e0458 100644 --- a/.github/workflows/kits.yml +++ b/.github/workflows/kits.yml @@ -91,12 +91,15 @@ jobs: run: node --test bin/ - run: npm run build - run: npm test - # Its tests run packages/ui-react's too. + # Its tests run packages/ui-react's too. After the build, + # test/build.test.mjs checks how the built server starts and + # what it passes on to Laravel. - name: TanStack Start kit run: | npm test -w kits/tanstack-start npm run types:check -w kits/tanstack-start npm run build -w kits/tanstack-start + node --test kits/tanstack-start/test/build.test.mjs # Its tests run packages/ui-vue's too, and its typecheck the # shared components it imports; vue-tsc checks the rest. # test:build builds it, then checks what the built server sends. diff --git a/kits/tanstack-start/README.md b/kits/tanstack-start/README.md index 5237640..b810e54 100644 --- a/kits/tanstack-start/README.md +++ b/kits/tanstack-start/README.md @@ -80,6 +80,7 @@ npm run check # lint and format (Vite+), in frontend/ npm run types:check npm run build npm test # the proxy, the guards, where answers go, notices +node --test frontend/test/build.test.mjs # after the build: how the built server starts and what it sends on composer ci:check # all of those, then Pint, PHPStan and the PHP tests ``` @@ -104,6 +105,7 @@ The checks, from `kits/tanstack-start`: npm run types:check npm run build npm test # this kit's tests, and packages/ui-react's +node --test test/build.test.mjs # after the build: how the built server starts and what it sends on ``` Lint and format run from the root, with `npm run check`. CI runs all three in the monorepo job, then exports the kit and runs the export's checks (see [The export](#the-export)). The browser tests run against this kit with `npm run test:browser:tanstack` (see the root README's "Browser tests"). diff --git a/kits/tanstack-start/src/server.ts b/kits/tanstack-start/src/server.ts index 3ee210e..88a0aef 100644 --- a/kits/tanstack-start/src/server.ts +++ b/kits/tanstack-start/src/server.ts @@ -7,7 +7,8 @@ import { import { laravelPath, proxyToLaravel } from './server/proxy'; import { withDocumentHeaders } from './server/security-headers'; -// In production (any NODE_ENV but development or test), a missing +// In production (a built server, or any NODE_ENV but development or test, +// see isProduction()), a missing // LARAVEL_URL or FRONTEND_URL stops the server as it starts, not on its // first request, and an empty FRONTEND_TRUSTED_PROXIES is warned about. if (isProduction()) { diff --git a/kits/tanstack-start/src/server/config.ts b/kits/tanstack-start/src/server/config.ts index c38e1ad..8c37985 100644 --- a/kits/tanstack-start/src/server/config.ts +++ b/kits/tanstack-start/src/server/config.ts @@ -24,8 +24,9 @@ let options: ProxyOptions | undefined; * is the proxy's address to Laravel, and they all share Keyring's rate * limits (trustedProxiesWarning()). * - * Production is any NODE_ENV but `development` and `test`, unset included: - * the defaults are for `vp dev` and the tests alone. + * Production is a built server (`vp build`), whatever NODE_ENV says, and + * any NODE_ENV but `development` and `test`, unset included: the defaults + * are for `vp dev` and the tests alone. */ export function proxyOptions( env: Record = process.env, @@ -37,8 +38,9 @@ export function proxyOptions( export function readOptions( env: Record, + built: boolean = import.meta.env.PROD, ): ProxyOptions { - const production = isProduction(env); + const production = isProduction(env, built); for (const name of ['LARAVEL_URL', 'FRONTEND_URL']) { if (production && !env[name]) { @@ -56,11 +58,17 @@ export function readOptions( }; } -/** Whether NODE_ENV is anything but `development` or `test`. */ +/** + * Whether this is a built server (`built`, Vite's import.meta.env.PROD, + * true in a production build), or NODE_ENV is anything but `development` + * or `test`. A built server started with NODE_ENV=development is still + * one in production. + */ export function isProduction( env: Record = process.env, + built: boolean = import.meta.env.PROD, ): boolean { - return env.NODE_ENV !== 'development' && env.NODE_ENV !== 'test'; + return built || (env.NODE_ENV !== 'development' && env.NODE_ENV !== 'test'); } /** diff --git a/kits/tanstack-start/src/server/proxy.test.ts b/kits/tanstack-start/src/server/proxy.test.ts index 2d04a55..4bd64bc 100644 --- a/kits/tanstack-start/src/server/proxy.test.ts +++ b/kits/tanstack-start/src/server/proxy.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from 'vite-plus/test'; -import { readOptions, trustedProxiesWarning } from './config'; +import { isProduction, readOptions, trustedProxiesWarning } from './config'; import { clientAddress, downstreamHeaders, @@ -637,6 +637,17 @@ describe('settings', () => { } }); + test('a built server needs them whatever NODE_ENV says', () => { + for (const NODE_ENV of ['development', 'test', undefined]) { + expect(isProduction({ NODE_ENV }, true), NODE_ENV).toBe(true); + expect(() => readOptions({ NODE_ENV }, true), NODE_ENV).toThrow( + /LARAVEL_URL/, + ); + } + + expect(isProduction({ NODE_ENV: 'development' }, false)).toBe(false); + }); + test('in development and tests they have defaults', () => { for (const NODE_ENV of ['development', 'test']) { const settings = readOptions({ NODE_ENV }); diff --git a/kits/tanstack-start/test/build.test.mjs b/kits/tanstack-start/test/build.test.mjs new file mode 100644 index 0000000..9531614 --- /dev/null +++ b/kits/tanstack-start/test/build.test.mjs @@ -0,0 +1,157 @@ +/** + * The production build, as it answers: `vp build`, then this starts + * server.mjs (what `npm start` runs) in front of a stand-in for Laravel, + * and checks how it starts and what it sends on. Run with Node's own test + * runner: `vp build && node --test test/build.test.mjs`. + */ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { existsSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { after, before, describe, test } from 'node:test'; +import { fileURLToPath } from 'node:url'; + +const server = fileURLToPath(new URL('../server.mjs', import.meta.url)); +const built = fileURLToPath( + new URL('../dist/server/server.js', import.meta.url), +); + +const guest = { name: 'App', auth: { user: null }, sidebarOpen: true }; + +/** What the stand-in for Laravel was asked for, with the headers it got. */ +const asked = []; + +const laravel = createServer((req, res) => { + asked.push({ url: req.url, headers: req.headers }); + res.setHeader('content-type', 'application/json'); + + if (req.url === '/api/me') { + res.end(JSON.stringify(guest)); + } else if (req.url === '/login') { + res.end( + JSON.stringify({ + page: 'login', + props: { canResetPassword: true, canRegister: true }, + }), + ); + } else { + res.statusCode = 404; + res.end('{"message":"Not Found"}'); + } +}); + +/** The built server, started as `node server.mjs`, on any free port. */ +function start(env) { + const child = spawn(process.execPath, [server], { + env: { PATH: process.env.PATH, HOST: '127.0.0.1', PORT: '0', ...env }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + let output = ''; + + child.stdout.on('data', (chunk) => (output += chunk)); + child.stderr.on('data', (chunk) => (output += chunk)); + + return { child, output: () => output }; +} + +let frontend; +let origin; + +before(async () => { + assert.ok(existsSync(built), 'Build the app first: vp build.'); + + laravel.listen(0, '127.0.0.1'); + await once(laravel, 'listening'); + + frontend = start({ + LARAVEL_URL: `http://127.0.0.1:${laravel.address().port}`, + FRONTEND_URL: 'http://localhost:3000', + }); + + for (let tries = 0; tries < 100 && !origin; tries++) { + origin = /Listening on:? (http:\/\/[^\s/]+)/.exec( + frontend.output(), + )?.[1]; + await new Promise((done) => setTimeout(done, 100)); + } + + assert.ok(origin, `The server didn't start:\n${frontend.output()}`); +}); + +after(() => { + frontend?.child.kill(); + laravel.close(); +}); + +/** A request as a browser sends it, by default. */ +async function get(path, headers = { accept: 'text/html' }) { + asked.length = 0; + + const response = await fetch(new URL(path, origin), { + headers, + redirect: 'manual', + }); + + return { response, body: await response.text() }; +} + +void describe('the built server', () => { + void test('warns as it starts that no proxy is trusted', () => { + assert.match(frontend.output(), /FRONTEND_TRUSTED_PROXIES is empty/); + }); + + void test('stops at once without LARAVEL_URL and FRONTEND_URL, whatever NODE_ENV says', async () => { + for (const NODE_ENV of ['development', 'test', 'production']) { + const { child, output } = start({ NODE_ENV }); + // One that starts anyway is stopped, and fails, rather than hangs. + const timer = setTimeout(() => child.kill(), 5000); + const [code] = await once(child, 'exit'); + + clearTimeout(timer); + + assert.notEqual(code, 0, NODE_ENV); + assert.match(output(), /Set LARAVEL_URL/, NODE_ENV); + } + }); + + void test('sends a page with the security headers, never cached', async () => { + const { response, body } = await get('/login'); + + assert.equal(response.status, 200); + assert.match(body, /
{ + const { response, body } = await get('/backend/api/me', { + accept: 'application/json', + 'x-forwarded-host': 'evil.example', + 'x-forwarded-proto': 'https', + }); + + assert.equal(response.status, 200); + assert.deepEqual(JSON.parse(body), guest); + assert.equal(asked.length, 1); + + const { url, headers } = asked[0]; + + assert.equal(url, '/api/me'); + assert.equal(headers.host, `127.0.0.1:${laravel.address().port}`); + assert.equal(headers['x-forwarded-host'], 'localhost:3000'); + assert.equal(headers['x-forwarded-proto'], 'http'); + assert.equal(headers['x-forwarded-prefix'], '/backend'); + }); +}); From 04723dff1df1781650ca601d1190dc2391bfa526 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 17:15:20 +0000 Subject: [PATCH 22/36] docs(headers): describe the security headers and that no-store keeps pages out of the back/forward cache --- README.md | 2 ++ kits/inertia-react/README.md | 4 ++++ tests/Feature/SecurityHeadersTest.php | 7 +++++-- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e0fcc1c..763ec6b 100644 --- a/README.md +++ b/README.md @@ -224,6 +224,8 @@ Emails (codes, email change links, security notices) go to `storage/logs/laravel On a server, set `APP_ENV=production` and `APP_DEBUG=false`: `.env.example` turns debug on for local work, and with it an error shows its message, file and stack trace to whoever caused it. Laravel only answers for `APP_URL`'s host (and, headless, `FRONTEND_URL`'s): a request with any other `Host` gets a `400`, so no link it builds can follow a made-up one. Both have to be full URLs, scheme included: one without a host, such as `example.com`, makes every request fail rather than trusting every host. The health check at `/up` answers at any host, so a load balancer can call it by the server's address. Laravel skips the host check when `APP_ENV` is `local`. +Every page Laravel sends, the app's own as well as Keyring's, has Keyring's security headers (`AddSecurityHeaders`, added to the `web` group in `bootstrap/app.php`): `X-Frame-Options: DENY`, so no other site can frame a page and line its own button up over one of yours, `X-Content-Type-Options: nosniff`, `Referrer-Policy: same-origin` (`no-referrer` on the pages emailed links open), `Cross-Origin-Opener-Policy: same-origin-allow-popups` and `Cache-Control: no-store, private`. That last one keeps signed-in pages out of shared and browser caches, and also out of the browser's back/forward cache, so going back reloads the page rather than showing it as it was. A response that sets its own `X-Frame-Options` (or a `Content-Security-Policy` with `frame-ancestors`) or `Cross-Origin-Opener-Policy` keeps it; to change the others, add your own middleware after it, or take it out of the `web` group. + To see how they look, open `http://localhost:8000/emails` while running locally: a gallery of every email the app sends, Keyring's and Laravel's verification and password reset emails, each with sample content (see [Emails](#emails)). diff --git a/kits/inertia-react/README.md b/kits/inertia-react/README.md index 0f62c4b..5522b83 100644 --- a/kits/inertia-react/README.md +++ b/kits/inertia-react/README.md @@ -40,3 +40,7 @@ Either way you get a `.env` with an app key and a migrated SQLite database. `php - In `.env`: `APP_ENV=production` and `APP_DEBUG=false`. `.env.example` turns debug on for local work, and with it any error page shows the exception's message, file, stack trace and the request to whoever caused it. - `APP_URL` as the site's `https://` address, such as `https://example.com`, and `SESSION_SECURE_COOKIE=true`. Passkeys need a secure origin, Keyring builds every emailed link from `APP_URL`, and Laravel only answers for `APP_URL`'s host: a request with any other `Host` gets a `400`, except the health check at `/up`, which a load balancer can call by the server's address. An `APP_URL` without its scheme, such as `example.com`, makes every request fail. - `TRUSTED_PROXIES`, when a load balancer or reverse proxy is in front, as its addresses, never `*`: only then is it believed about HTTPS and the visitor's address. + +## Security headers + +Every page Laravel sends, the app's own as well as Keyring's, has Keyring's security headers (`AddSecurityHeaders`, added to the `web` group in `bootstrap/app.php`): `X-Frame-Options: DENY`, so no other site can frame a page and line its own button up over one of yours, `X-Content-Type-Options: nosniff`, `Referrer-Policy: same-origin` (`no-referrer` on the pages emailed links open), `Cross-Origin-Opener-Policy: same-origin-allow-popups` and `Cache-Control: no-store, private`. That last one keeps signed-in pages out of shared and browser caches, and also out of the browser's back/forward cache, so going back reloads the page rather than showing it as it was. A response that sets its own `X-Frame-Options` (or a `Content-Security-Policy` with `frame-ancestors`) or `Cross-Origin-Opener-Policy` keeps it; to change the others, add your own middleware after it, or take it out of the `web` group. diff --git a/tests/Feature/SecurityHeadersTest.php b/tests/Feature/SecurityHeadersTest.php index b93cc6f..67ad154 100644 --- a/tests/Feature/SecurityHeadersTest.php +++ b/tests/Feature/SecurityHeadersTest.php @@ -20,13 +20,16 @@ public function test_the_apps_own_pages_may_not_be_framed() ->assertHeader('X-Frame-Options', 'DENY') ->assertHeader('X-Content-Type-Options', 'nosniff') ->assertHeader('Referrer-Policy', 'same-origin') - ->assertHeader('Cross-Origin-Opener-Policy', 'same-origin-allow-popups'); + ->assertHeader('Cross-Origin-Opener-Policy', 'same-origin-allow-popups') + // Never cached, which also keeps them out of the back/forward cache. + ->assertHeader('Cache-Control', 'no-store, private'); } public function test_keyrings_pages_still_get_them() { $this->get(route('login')) ->assertOk() - ->assertHeader('X-Frame-Options', 'DENY'); + ->assertHeader('X-Frame-Options', 'DENY') + ->assertHeader('Cache-Control', 'no-store, private'); } } From e8157f0520cc7368fdc70ac93481e642fe5ad63b Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 17:15:36 +0000 Subject: [PATCH 23/36] fix(ci): check for a re-run of a release before refusing an older tag --- .github/workflows/kits.yml | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/.github/workflows/kits.yml b/.github/workflows/kits.yml index 39e0458..bd0ee1d 100644 --- a/.github/workflows/kits.yml +++ b/.github/workflows/kits.yml @@ -304,20 +304,6 @@ jobs: git clone --depth 1 "git@github.com:$REPOSITORY.git" "$target" cd "$target" - # Never an older release over a newer one: the tag has to be - # the newest of the repository's release tags, or one of them - # already (a re-run, checked below). - latest=$(git ls-remote --tags --refs origin 'refs/tags/v*' \ - | sed 's#^.*refs/tags/##' \ - | { grep -E "$semver" || true; } \ - | sort -V | tail -n 1) - - if [ -n "$latest" ] && [ "$latest" != "$TAG" ] && - [ "$(printf '%s\n%s\n' "$latest" "$TAG" | sort -V | tail -n 1)" != "$TAG" ]; then - echo "::error::$REPOSITORY already has $latest, which is newer than $TAG." - exit 1 - fi - git checkout -B main find . -mindepth 1 -maxdepth 1 ! -name .git -exec rm -rf {} + # The export never has a .git, and one in the archive @@ -339,6 +325,20 @@ jobs: exit 1 fi + # Never an older release over a newer one: past a re-run, + # which is checked first, so an older release can be re-run, + # the tag has to be newer than every release tag there. + latest=$(git ls-remote --tags --refs origin 'refs/tags/v*' \ + | sed 's#^.*refs/tags/##' \ + | { grep -E "$semver" || true; } \ + | sort -V | tail -n 1) + + if [ -n "$latest" ] && + [ "$(printf '%s\n%s\n' "$latest" "$TAG" | sort -V | tail -n 1)" != "$TAG" ]; then + echo "::error::$REPOSITORY already has $latest, which is newer than $TAG." + exit 1 + fi + git config user.name 'github-actions[bot]' git config user.email '41898282+github-actions[bot]@users.noreply.github.com' From f9176fcbed15f739ffa41f67ddf86c596b00ebb4 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 17:16:09 +0000 Subject: [PATCH 24/36] test(ui): run the inertia app's and the shared sameOriginUrl() against the same cases --- resources/js/lib/url.test.ts | 69 ++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 resources/js/lib/url.test.ts diff --git a/resources/js/lib/url.test.ts b/resources/js/lib/url.test.ts new file mode 100644 index 0000000..df342ac --- /dev/null +++ b/resources/js/lib/url.test.ts @@ -0,0 +1,69 @@ +import { + afterAll, + beforeAll, + describe, + expect, + test, + vi, +} from 'vite-plus/test'; +import { sameOriginUrl } from '@/lib/url'; +import * as shared from '@keyringjs/ui-react/lib/url'; // @monorepo-only + +/** + * sameOriginUrl() keeps a full page load to a URL an answer gave on this + * site. Every copy of it runs the same cases, so they never drift apart. + */ +const copies: [string, typeof sameOriginUrl][] = [ + ['resources/js', sameOriginUrl], +]; +copies.push(['packages/ui-react', shared.sameOriginUrl]); // @monorepo-only + +const origin = 'https://app.example.test'; + +beforeAll(() => { + // The tests run in Node: a page on this site, as far as they look. + vi.stubGlobal('window', { location: new URL(`${origin}/settings`) }); +}); + +afterAll(() => { + vi.unstubAllGlobals(); +}); + +describe.each(copies)('sameOriginUrl() in %s', (_, sameOriginUrl) => { + test('keeps a URL on this site, as the browser reads it', () => { + expect(sameOriginUrl('/dashboard?x=1')).toBe(`${origin}/dashboard?x=1`); + expect(sameOriginUrl('billing')).toBe(`${origin}/billing`); + expect(sameOriginUrl(`${origin}/settings#a`)).toBe( + `${origin}/settings#a`, + ); + }); + + test('and nothing else', () => { + for (const value of [ + 'https://evil.example/dashboard', + 'http://app.example.test/dashboard', + 'https://app.example.test:8443/', + '//evil.example', + '/\\evil.example', + '/\t/evil.example', + 'javascript:alert(1)', + 'data:text/html,hi', + 'http://[', + '', + null, + undefined, + ]) { + expect(sameOriginUrl(value), String(value)).toBeUndefined(); + } + }); +}); + +describe('without a window, as on the server', () => { + test.each(copies)('%s gives nothing', (_, sameOriginUrl) => { + vi.stubGlobal('window', undefined); + + expect(sameOriginUrl('/dashboard')).toBeUndefined(); + + vi.stubGlobal('window', { location: new URL(`${origin}/settings`) }); + }); +}); From 7bf732ca70f9ce1f5b7017ac1bb8a2ea64a88d37 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 17:17:12 +0000 Subject: [PATCH 25/36] fix(export): resolve symlinks as the file system does and refuse dangling ones --- bin/export-kit.mjs | 43 +++++++++++++++++++++++++++----- bin/export-kit.test.mjs | 54 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 6 deletions(-) diff --git a/bin/export-kit.mjs b/bin/export-kit.mjs index 5bd2503..9af85db 100644 --- a/bin/export-kit.mjs +++ b/bin/export-kit.mjs @@ -419,12 +419,17 @@ function findLeftovers(out, files, names) { } /** - * The symlinks among `files`, each with whether it stays inside `out`: - * relative, and resolving to a path under it. An absolute target never - * does, since the export is unpacked somewhere else. + * The symlinks among `files`, each with whether it stays inside `out` and + * whether it points at anything at all. Inside means relative, and + * resolving, as the file system does, to a path under `out`: through any + * other symlinks on the way, which a lexical path.resolve() would skip, as + * in `leak -> up/../../etc/hostname` with `up -> ../..`. An absolute target + * never stays inside, since the export is unpacked somewhere else. A + * dangling one points at nothing in the export, such as an excluded file. */ function symlinksIn(out, files) { const links = []; + const realOut = fs.realpathSync.native(out); for (const file of files) { const target = path.join(out, file); @@ -434,13 +439,27 @@ function symlinksIn(out, files) { } const link = fs.readlinkSync(target); - const resolved = path.resolve(path.dirname(target), link); + /** @type {string | null} */ + let resolved = null; + + try { + resolved = fs.realpathSync.native(target); + } catch { + // Dangling, or a loop. + } + + const lexicallyInside = + !path.isAbsolute(link) && + path.resolve(path.dirname(target), link).startsWith(out + path.sep); links.push({ file, link, + dangling: lexicallyInside && resolved === null, inside: - !path.isAbsolute(link) && resolved.startsWith(out + path.sep), + lexicallyInside && + resolved !== null && + resolved.startsWith(realOut + path.sep), }); } @@ -978,7 +997,19 @@ export function exportKit({ // Symlinks are copied as they are: each has to point at a file in the // export, never at something outside it, wherever it's unpacked. const symlinks = symlinksIn(out, [...written]); - const outside = symlinks.filter((symlink) => !symlink.inside); + const dangling = symlinks.filter((symlink) => symlink.dangling); + const outside = symlinks.filter( + (symlink) => !symlink.dangling && !symlink.inside, + ); + + if (dangling.length > 0) { + fail( + 'these symlinks point at nothing in the export (excluded, or not there at all):\n ' + + dangling + .map((symlink) => `${symlink.file} -> ${symlink.link}`) + .join('\n '), + ); + } if (outside.length > 0) { fail( diff --git a/bin/export-kit.test.mjs b/bin/export-kit.test.mjs index 51fdf4c..9ac3e0f 100644 --- a/bin/export-kit.test.mjs +++ b/bin/export-kit.test.mjs @@ -875,6 +875,60 @@ void describe('exportKit', () => { assert.ok(logged.includes(' symlink: link.md -> README.md')); }); + void test('refuses a symlink that leaves the export through another symlink', () => { + // Lexically, leak's target stays inside: up/.. cancels out. On the + // disk, up is a/, and the rest climbs out of the export. + const dir = 'a/b/c/d/e/f/g/h'; + const leak = `up/${'../'.repeat(9)}etc/hostname`; + + fs.mkdirSync(path.join(root, dir), { recursive: true }); + fs.symlinkSync('../../../../../../..', path.join(root, dir, 'up')); + fs.symlinkSync(leak, path.join(root, dir, 'leak')); + track(); + + try { + assert.throws( + () => exportTo(path.join(tmp, 'symlink-chained')), + (error) => + error instanceof ExportError && + // Outside where /etc/hostname exists, dangling where not. + /point (outside the export|at nothing in the export)/.test( + error.message, + ) && + error.message.includes(`${dir}/leak -> ${leak}`) && + !error.message.includes(`${dir}/up ->`), + ); + } finally { + execFileSync('git', ['rm', '-q', '-r', '--cached', 'a'], { + cwd: root, + }); + fs.rmSync(path.join(root, 'a'), { recursive: true }); + track(); + } + }); + + void test('refuses a symlink to a file the export leaves out', () => { + fs.symlinkSync('resources/js/e2e.ts', path.join(root, 'e2e-link.ts')); + track(); + + try { + assert.throws( + () => exportTo(path.join(tmp, 'symlink-dangling')), + (error) => + error instanceof ExportError && + error.message.includes( + 'point at nothing in the export (excluded, or not there at all):\n e2e-link.ts -> resources/js/e2e.ts', + ), + ); + } finally { + execFileSync('git', ['rm', '-q', '--cached', 'e2e-link.ts'], { + cwd: root, + }); + fs.rmSync(path.join(root, 'e2e-link.ts')); + track(); + } + }); + void test('refuses kit.json paths outside the export or in .git', () => { const manifest = JSON.parse( fs.readFileSync(path.join(root, 'kits/demo/kit.json'), 'utf8'), From 04f00611f7202a5810fc08bb2a7d8cd146ecad45 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 17:17:53 +0000 Subject: [PATCH 26/36] fix(export): refuse git dependencies in a released lockfile, and document the symlink checks --- README.md | 4 ++-- bin/export-kit.mjs | 16 ++++++++++++---- bin/export-kit.test.mjs | 19 ++++++++++++++++++- 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 763ec6b..707f524 100644 --- a/README.md +++ b/README.md @@ -143,8 +143,8 @@ The output is what the kit's repository gets: a complete Laravel app with no wor 4. Leaves out text tagged monorepo-only: a line whose comment (`//`, `#`, `/*`, ` diff --git a/kits/inertia-react/README.md b/kits/inertia-react/README.md index 5522b83..0eecb4b 100644 --- a/kits/inertia-react/README.md +++ b/kits/inertia-react/README.md @@ -40,6 +40,7 @@ Either way you get a `.env` with an app key and a migrated SQLite database. `php - In `.env`: `APP_ENV=production` and `APP_DEBUG=false`. `.env.example` turns debug on for local work, and with it any error page shows the exception's message, file, stack trace and the request to whoever caused it. - `APP_URL` as the site's `https://` address, such as `https://example.com`, and `SESSION_SECURE_COOKIE=true`. Passkeys need a secure origin, Keyring builds every emailed link from `APP_URL`, and Laravel only answers for `APP_URL`'s host: a request with any other `Host` gets a `400`, except the health check at `/up`, which a load balancer can call by the server's address. An `APP_URL` without its scheme, such as `example.com`, makes every request fail. - `TRUSTED_PROXIES`, when a load balancer or reverse proxy is in front, as its addresses, never `*`: only then is it believed about HTTPS and the visitor's address. +- A reverse proxy in front of your PHP server, such as nginx, Caddy or a load balancer, whenever it listens on anything but loopback, with caps on request body size, header and idle timeouts, and connections, per client and in all, unless the PHP server sets them itself. `php artisan serve` is for local work only. ## Security headers diff --git a/kits/nuxt/README.md b/kits/nuxt/README.md index 267f5a5..fb91642 100644 --- a/kits/nuxt/README.md +++ b/kits/nuxt/README.md @@ -258,6 +258,7 @@ Build once with `npm run build`, then run Laravel behind your PHP server, its qu - `LARAVEL_URL`, where this app reaches Laravel, on loopback, such as `http://127.0.0.1:8000`. - Trusted proxies on both sides. Laravel believes the forwarded headers from loopback only (`TRUSTED_PROXIES` is `127.0.0.1,::1` in headless mode), which is this app's server: leave it, or set it to the addresses this server connects from, never `*`. Laravel's port must only be reachable by this app's server: have your PHP server listen on `127.0.0.1`, and never publish that port or put a tunnel in front of it, or pin `TRUSTED_PROXIES`. In front of this app, set `FRONTEND_TRUSTED_PROXIES` to your load balancer or reverse proxy's addresses (see [One origin](#one-origin)), so the browser's own address reaches Laravel's rate limits and security log, and leave it empty when browsers connect to `npm start` directly. - `HOST`, when a proxy on another machine connects to this app: the built server listens on `localhost` unless told otherwise, `npm start` or not. +- A reverse proxy in front, such as nginx, Caddy or a load balancer, whenever `HOST` isn't loopback, with its own caps on request body size, header and idle timeouts, and connections, per client and in all. The built server has some limits built in, `npm start` or not: the proxy holds a body it passes on of up to 256 KiB (a larger one gets a `413`) and gives it 15 seconds to arrive (a `408`), the server gives a client 30 seconds to send a whole request and 10 to send its headers (`server/plugins/settings.ts`, since Nitro has no setting for them), and Laravel gets 30 seconds to start answering a request passed on (a `504`) and 10 for a read while rendering a page. Nitro caps no other request body, and nothing in it limits how many connections a client opens. diff --git a/kits/tanstack-start/README.md b/kits/tanstack-start/README.md index 2c1eb17..daddf04 100644 --- a/kits/tanstack-start/README.md +++ b/kits/tanstack-start/README.md @@ -232,6 +232,7 @@ Build once with `npm run build`, then run Laravel behind your PHP server, its qu - `APP_URL` and `FRONTEND_URL`, in Laravel's `.env` and this app's environment, as the site's `https://` address, such as `https://example.com`. Passkeys need a secure origin, Keyring builds every emailed link from `APP_URL`, and Laravel only answers for those two hosts: a request with any other gets a `400`, except the health check at `/up`, which a load balancer can call by the server's address, and a URL without its scheme, such as `example.com`, makes every request fail. Set `SESSION_SECURE_COOKIE=true` too, so the session cookie is only sent over HTTPS. This app's own cookies (`__Host-keyring_notice`, `__Host-keyring_intended`) are Secure whenever `FRONTEND_URL` is `https://`. - `LARAVEL_URL`, where this app reaches Laravel, on loopback, such as `http://127.0.0.1:8000`. - Trusted proxies on both sides. Laravel believes the forwarded headers from loopback only (`TRUSTED_PROXIES` is `127.0.0.1,::1` in headless mode), which is this app's server: leave it, or set it to the addresses this server connects from, never `*`. Laravel's port must only be reachable by this app's server: have your PHP server listen on `127.0.0.1`, and never publish that port or put a tunnel in front of it, or pin `TRUSTED_PROXIES`. In front of this app, set `FRONTEND_TRUSTED_PROXIES` to your load balancer or reverse proxy's addresses (see [One origin](#one-origin)), so the browser's own address reaches Laravel's rate limits and security log, and leave it empty when browsers connect to `npm start` directly. +- A reverse proxy in front, such as nginx, Caddy or a load balancer, whenever `HOST` isn't loopback, with its own caps on request body size, header and idle timeouts, and connections, per client and in all. `npm start` has some limits built in: it holds a request body of up to 256 KiB (a larger one gets a `413`) and gives it 15 seconds to arrive (a `408`), gives a client 30 seconds to send a whole request and 10 to send its headers, and gives Laravel 30 seconds to start answering a request passed on (a `504`) and 10 for a read while rendering a page. Nothing in it limits how many connections a client opens. From 35978cdd9277a804ff1511169f0403df06142a5a Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 18:22:59 +0000 Subject: [PATCH 34/36] fix(registration): only take email addresses symfony mailer can send to --- app/Actions/Keyring/CreateNewUser.php | 7 ++++- app/Actions/Keyring/ValidateEmailChange.php | 6 ++++- app/Concerns/ProfileValidationRules.php | 2 +- tests/Feature/Auth/RegistrationTest.php | 27 ++++++++++++++++++++ tests/Feature/Settings/ProfileUpdateTest.php | 14 ++++++++++ 5 files changed, 53 insertions(+), 3 deletions(-) diff --git a/app/Actions/Keyring/CreateNewUser.php b/app/Actions/Keyring/CreateNewUser.php index f5bbdeb..987ceec 100644 --- a/app/Actions/Keyring/CreateNewUser.php +++ b/app/Actions/Keyring/CreateNewUser.php @@ -21,6 +21,11 @@ class CreateNewUser implements CreatesNewUsers * same way either way, so nobody can use the form to find out who has * an account. * + * `email:rfc,strict` only takes what Symfony Mailer can send to: the + * plain `email` rule lets through addresses such as + * `a(comment)@example.com`, which the mailer refuses, so the + * verification email would fail after the account was made. + * * @param array $input * @return array */ @@ -30,7 +35,7 @@ public function validate(array $input): array return Validator::make($input, [ 'name' => ['required', 'string', 'max:255'], - 'email' => ['required', 'string', 'email', 'max:255'], + 'email' => ['required', 'string', 'email:rfc,strict', 'max:255'], 'password' => $this->passwordRules(context: [$input['name'] ?? null, $input['email']]), ])->validate(); } diff --git a/app/Actions/Keyring/ValidateEmailChange.php b/app/Actions/Keyring/ValidateEmailChange.php index ca47cbd..959c643 100644 --- a/app/Actions/Keyring/ValidateEmailChange.php +++ b/app/Actions/Keyring/ValidateEmailChange.php @@ -20,6 +20,10 @@ class ValidateEmailChange implements ValidatesEmailChanges * Don't check here whether the address is taken: Keyring answers the same * way either way, so nobody can find out who has an account. * + * `email:rfc,strict` only takes what Symfony Mailer can send to: the + * plain `email` rule lets through addresses such as + * `a(comment)@example.com`, which the mailer refuses. + * * @param User $user * @param array $input */ @@ -28,7 +32,7 @@ public function validate(Authenticatable&Model $user, array $input): string $input['email'] = is_string($input['email'] ?? null) ? Keyring::normalizeUsername($input['email']) : null; $validated = Validator::make($input, [ - 'email' => ['required', 'string', 'email', 'max:255'], + 'email' => ['required', 'string', 'email:rfc,strict', 'max:255'], ])->validate(); return Arr::string($validated, 'email'); diff --git a/app/Concerns/ProfileValidationRules.php b/app/Concerns/ProfileValidationRules.php index 760e41e..81e3c27 100644 --- a/app/Concerns/ProfileValidationRules.php +++ b/app/Concerns/ProfileValidationRules.php @@ -42,7 +42,7 @@ protected function emailRules(?int $userId = null): array return [ 'required', 'string', - 'email', + 'email:rfc,strict', 'max:255', $userId === null ? Rule::unique(User::class) diff --git a/tests/Feature/Auth/RegistrationTest.php b/tests/Feature/Auth/RegistrationTest.php index 1604f75..126e6fb 100644 --- a/tests/Feature/Auth/RegistrationTest.php +++ b/tests/Feature/Auth/RegistrationTest.php @@ -12,6 +12,7 @@ use Illuminate\Support\Facades\Notification; use Illuminate\Testing\TestResponse; use Inertia\Testing\AssertableInertia as Assert; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\TestCase; /** @@ -50,6 +51,32 @@ public function test_new_users_are_told_to_check_their_email_and_are_not_signed_ Notification::assertSentTo($user, VerifyEmail::class); } + /** + * Laravel's plain `email` rule lets these through, but Symfony Mailer + * refuses them, so the verification email would fail after the account + * was made. + * + * @return array + */ + public static function addressesMailCantGoTo(): array + { + return [ + 'a comment' => ['a(comment)@example.com'], + 'a leading comment' => ['(comment)a@example.com'], + ]; + } + + #[DataProvider('addressesMailCantGoTo')] + public function test_an_address_mail_cant_be_sent_to_is_refused(string $email) + { + Notification::fake(); + + $this->register($email)->assertSessionHasErrors('email'); + + $this->assertSame(0, User::query()->count()); + Notification::assertNothingSent(); + } + public function test_the_login_page_shows_the_check_your_email_message() { Notification::fake(); diff --git a/tests/Feature/Settings/ProfileUpdateTest.php b/tests/Feature/Settings/ProfileUpdateTest.php index 3f242fe..3db8160 100644 --- a/tests/Feature/Settings/ProfileUpdateTest.php +++ b/tests/Feature/Settings/ProfileUpdateTest.php @@ -50,6 +50,20 @@ public function test_changing_the_email_sends_a_confirmation_to_the_new_address( $this->assertSame('test@example.com', $user->refresh()->email); } + public function test_a_new_address_mail_cant_be_sent_to_is_refused() + { + Notification::fake(); + $user = User::factory()->create(['email' => 'test@example.com']); + + // Laravel's plain `email` rule lets it through; Symfony Mailer doesn't. + $this->actingAs($user)->withAssurance(Assurance::AAL1) + ->post(route('keyring.email.store'), ['email' => 'a(comment)@example.com']) + ->assertSessionHasErrors('email'); + + Notification::assertNothingSent(); + $this->assertSame('test@example.com', $user->refresh()->email); + } + /** * A second factor the account has had for a while * (keyring.email_changes.established_after, a week by default) is proof From 8c6c087dc349222804f2f30760bd94e363ebf832 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 18:22:59 +0000 Subject: [PATCH 35/36] fix(proxies): believe x-forwarded-prefix only as one path of plain segments --- .../IgnoreInvalidForwardedPrefix.php | 22 ++++++++++-------- docs/headless-api.md | 2 +- .../Feature/Headless/ForwardedPrefixTest.php | 23 +++++++++++++++++++ 3 files changed, 37 insertions(+), 10 deletions(-) diff --git a/app/Http/Middleware/IgnoreInvalidForwardedPrefix.php b/app/Http/Middleware/IgnoreInvalidForwardedPrefix.php index e9c89f8..366f627 100644 --- a/app/Http/Middleware/IgnoreInvalidForwardedPrefix.php +++ b/app/Http/Middleware/IgnoreInvalidForwardedPrefix.php @@ -9,13 +9,17 @@ use Symfony\Component\HttpFoundation\Response; /** - * Drops an X-Forwarded-Prefix that isn't a plain path, run right after + * Drops an X-Forwarded-Prefix that isn't one plain path, run right after * TrustProxies (bootstrap/app.php). Symfony puts a trusted proxy's prefix * in front of every URL url() builds as it is, so `.evil.example` would * make them https://app.example.evil.example/..., and `//evil.example` or * `/\evil.example` a link a browser follows to another host. Laravel only * trusts the prefix in headless mode (AppServiceProvider), from the - * frontend's server, which sends `/backend`. + * frontend's server, which sends `/backend` once. + * + * Symfony reads only the first of several values (`/a/..,/b` is `/a/..`), + * so more than one, as a list or as several headers, is dropped, rather + * than checked as a whole. */ class IgnoreInvalidForwardedPrefix { @@ -26,7 +30,7 @@ public function handle(Request $request, Closure $next): Response { $prefixes = $request->headers->all('x-forwarded-prefix'); - if ($prefixes !== [] && ! collect($prefixes)->every(fn (?string $prefix) => self::isValid((string) $prefix))) { + if ($prefixes !== [] && (count($prefixes) > 1 || ! self::isValid((string) $prefixes[0]))) { $request->headers->remove('X-Forwarded-Prefix'); $request->server->remove('HTTP_X_FORWARDED_PREFIX'); } @@ -35,14 +39,14 @@ public function handle(Request $request, Closure $next): Response } /** - * A path that starts with a single `/`, with no `//`, backslash, `@`, - * control character or `..` segment. + * One path of plain segments (letters, digits, `.`, `_`, `~` and `-`), + * each after a single `/`, with no `.` or `..` segment, and at most a + * trailing `/`: nothing that could be read as a host, a query, a + * fragment, an escape, a second value or a step up. */ public static function isValid(string $prefix): bool { - return str_starts_with($prefix, '/') - && ! str_contains($prefix, '//') - && ! preg_match('/[\\\\@\x00-\x1F\x7F]/', $prefix) - && ! preg_match('#(^|/)\.\.(/|$)#', $prefix); + return preg_match('#^(/[A-Za-z0-9._~-]+)+/?$#D', $prefix) === 1 + && preg_match('#(^|/)\.{1,2}(/|$)#', $prefix) !== 1; } } diff --git a/docs/headless-api.md b/docs/headless-api.md index d1ad494..de82180 100644 --- a/docs/headless-api.md +++ b/docs/headless-api.md @@ -48,7 +48,7 @@ The headless kits use Keyring's "one origin" layout. The frontend's server is th | `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-Prefix` only when it's a plain path that starts with a single `/`, with no `//`, backslash, `@`, control character or `..` segment (anything else is ignored, and the Inertia app never believes it), and `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. h3's `proxyRequest()` passes on every header the browser sent, its own `X-Forwarded-For` included, so drop those before setting the four, as the kits' proxies do. 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`. +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-Prefix` only when it's one plain path: segments of letters, digits, `.`, `_`, `~` and `-`, each after a single `/`, with no `.` or `..` segment (anything else, or more than one value, is ignored, and the Inertia app never believes it), and `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. h3's `proxyRequest()` passes on every header the browser sent, its own `X-Forwarded-For` included, so drop those before setting the four, as the kits' proxies do. 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). diff --git a/tests/Feature/Headless/ForwardedPrefixTest.php b/tests/Feature/Headless/ForwardedPrefixTest.php index 3194701..0a26366 100644 --- a/tests/Feature/Headless/ForwardedPrefixTest.php +++ b/tests/Feature/Headless/ForwardedPrefixTest.php @@ -63,6 +63,19 @@ public static function invalidPrefixes(): array 'only a parent segment' => ['/..'], 'a trailing parent segment' => ['/backend/..'], 'an empty prefix' => [''], + 'only a slash' => ['/'], + 'a bad first value in a list' => ['/a/..,x'], + 'a list of good values' => ['/backend,/backend'], + 'a current segment' => ['/./backend'], + 'a trailing current segment' => ['/backend/.'], + 'a query' => ['/backend?x=1'], + 'a fragment' => ['/backend#x'], + 'an escape' => ['/back%2Fend'], + 'an escaped parent segment' => ['/backend/%2e%2e'], + 'a space' => ['/back end'], + 'a colon' => ['/backend:8000'], + 'a letter outside ascii' => ['/bäckend'], + 'a trailing newline' => ["/backend\n"], ]; } @@ -75,6 +88,16 @@ public function test_any_other_prefix_is_ignored(string $prefix) $this->assertSame('https://app.example.test/confirm', url('/confirm')); } + public function test_two_good_prefixes_in_separate_headers_are_dropped() + { + $request = Request::create('/api/me'); + $request->headers->set('X-Forwarded-Prefix', ['/backend', '/backend']); + + (new IgnoreInvalidForwardedPrefix)->handle($request, fn () => response('ok')); + + $this->assertFalse($request->headers->has('X-Forwarded-Prefix')); + } + public function test_one_bad_prefix_among_several_headers_drops_them_all() { $request = Request::create('/api/me'); From 0a7b46b231432b491bb3ef71c814de37e539cecd Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Sat, 28 Nov 2026 18:22:59 +0000 Subject: [PATCH 36/36] docs(hosts): say why a refused host gets a 400 --- app/Http/Middleware/TrustHosts.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/app/Http/Middleware/TrustHosts.php b/app/Http/Middleware/TrustHosts.php index 71d9112..3bc2bdd 100644 --- a/app/Http/Middleware/TrustHosts.php +++ b/app/Http/Middleware/TrustHosts.php @@ -40,8 +40,10 @@ public function handle(Request $request, $next) Request::setTrustedHosts(array_filter($this->hosts())); try { - // Checked now, while a made-up host still gets a 400 here, - // rather than wherever the host is first read. + // Checked now, rather than wherever the host is first read. + // Laravel's exception handler answers the exception with a 400, + // as it does any of Symfony's RequestExceptionInterface + // (prepareException()), which the tests assert. try { $request->getHost(); } catch (SuspiciousOperationException $e) {