From 9121f1721d0c03a0810b59a39e0272058b90b94b Mon Sep 17 00:00:00 2001 From: monarcode Date: Fri, 13 Nov 2026 20:59:23 +0100 Subject: [PATCH 01/26] feat(http)!: authFetch accepts a URL or a Request; createAuthFetch takes an options object An HTTP client with a fetch option (ky, axios's fetch adapter, openapi-fetch) can now send its requests through authFetch. BREAKING CHANGE: createAuthFetch(auth, baseUrl, options?) is now createAuthFetch(auth, { baseUrl, ...options }). AuthFetch's first parameter is string | URL | Request. --- CHANGELOG.md | 32 ++ examples/expo-router/src/auth.ts | 2 +- examples/next-app/app/ui.tsx | 5 +- examples/react-router-data/src/auth.ts | 2 +- examples/react-router-declarative/src/auth.ts | 2 +- .../react-router-framework-spa/app/auth.ts | 2 +- .../react-router-framework-ssr/app/ui.tsx | 5 +- examples/tanstack-router/src/auth.ts | 2 +- examples/tanstack-start-spa/src/auth.ts | 2 +- examples/tanstack-start-ssr/src/ui.tsx | 5 +- site/content/docs/(latest)/client/index.mdx | 2 +- .../(latest)/client/other-http-clients.mdx | 133 ++++--- .../content/docs/(latest)/client/requests.mdx | 17 +- .../content/docs/(latest)/client/sessions.mdx | 10 +- .../content/docs/(latest)/getting-started.mdx | 2 +- site/content/docs/(latest)/reference/http.mdx | 2 +- .../server-rendering/server-sessions.mdx | 6 +- site/content/docs/(latest)/setups/expo.mdx | 2 +- src/http/index.ts | 82 +++- src/server/auth.ts | 7 +- tests/consumer.ts | 29 +- tests/http.test.ts | 374 ++++++++++++++++-- tests/mirror.test.ts | 4 +- 23 files changed, 596 insertions(+), 133 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dd94901..dba379c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,40 @@ ## Unreleased +### Added + +- `authFetch` takes a `URL` or a `Request` as well as a path, as `fetch` + does. An HTTP client with a `fetch` option can now send its requests + through it, and they keep its safeguards: the token stays on one origin, a + 401 refreshes once, and only a GET or HEAD is sent again. The + [Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients) + page shows ky, axios with its `fetch` adapter, and openapi-fetch. It + replaces the ky recipe built on hooks, and keeps the axios interceptors for + an instance on axios's default adapter. + ### Changed +- **Breaking:** `createAuthFetch` takes the base URL as an option, as + `sessionBearer` does. A missing `baseUrl` throws `INVALID_OPTIONS`. + + ```ts + // Before + createAuthFetch(auth, "https://api.example.com/", { optional: true }); + // After + createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + optional: true, + }); + ``` + +- **Breaking:** `AuthFetch`'s first parameter is `string | URL | Request`, + not `string`. Only code that implements the type is affected, such as a + test fake that declares `(path: string) => …`: widen its parameter. +- `authFetch` rejects with `INVALID_OPTIONS` when called with no path. It + used to request `undefined` under the base URL. +- `authFetch` asks for the credentials before it builds the request. Signed + out or locked, a call with an `init` that `Request` refuses now rejects + with `UNAUTHENTICATED` or `LOCKED`, not with `Request`'s `TypeError`. - The guides moved to the documentation site, [session-kit.pages.dev](https://session-kit.pages.dev), with an API reference for every entry point and every error code. The README is now a diff --git a/examples/expo-router/src/auth.ts b/examples/expo-router/src/auth.ts index 64daf06..dca97ff 100644 --- a/examples/expo-router/src/auth.ts +++ b/examples/expo-router/src/auth.ts @@ -62,7 +62,7 @@ export const { AuthProvider, useAuth, useAuthClient } = * Sends requests to DummyJSON with the access token. After a 401 it * refreshes, then replays a GET or HEAD once. */ -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); /** Signs in with DummyJSON, then saves the tokens and the user it returned. */ export async function signInWithPassword(username: string, password: string) { diff --git a/examples/next-app/app/ui.tsx b/examples/next-app/app/ui.tsx index 6de59f1..cf65548 100644 --- a/examples/next-app/app/ui.tsx +++ b/examples/next-app/app/ui.tsx @@ -80,7 +80,10 @@ export function Profile({ fromServer }: { fromServer: string }) { const user = useAuth((state) => state.user); const auth = useAuthClient(); // The browser's requests get the access token from the server, in memory. - const authFetch = useMemo(() => createAuthFetch(auth, `${API}/`), [auth]); + const authFetch = useMemo( + () => createAuthFetch(auth, { baseUrl: `${API}/` }), + [auth], + ); const [fromBrowser, setFromBrowser] = useState(""); async function loadProfile() { diff --git a/examples/react-router-data/src/auth.ts b/examples/react-router-data/src/auth.ts index f509524..927e3e5 100644 --- a/examples/react-router-data/src/auth.ts +++ b/examples/react-router-data/src/auth.ts @@ -88,4 +88,4 @@ async function login(username: string, password: string): Promise { * Sends requests to DummyJSON with the access token. After a 401 it * refreshes, then replays a GET or HEAD once. */ -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); diff --git a/examples/react-router-declarative/src/auth.ts b/examples/react-router-declarative/src/auth.ts index 9ec9c05..b6f4cb6 100644 --- a/examples/react-router-declarative/src/auth.ts +++ b/examples/react-router-declarative/src/auth.ts @@ -84,4 +84,4 @@ async function login(username: string, password: string): Promise { * Sends requests to DummyJSON with the access token. After a 401 it * refreshes, then replays a GET or HEAD once. */ -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); diff --git a/examples/react-router-framework-spa/app/auth.ts b/examples/react-router-framework-spa/app/auth.ts index 9ec9c05..b6f4cb6 100644 --- a/examples/react-router-framework-spa/app/auth.ts +++ b/examples/react-router-framework-spa/app/auth.ts @@ -84,4 +84,4 @@ async function login(username: string, password: string): Promise { * Sends requests to DummyJSON with the access token. After a 401 it * refreshes, then replays a GET or HEAD once. */ -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); diff --git a/examples/react-router-framework-ssr/app/ui.tsx b/examples/react-router-framework-ssr/app/ui.tsx index 80ea9f4..eef2fff 100644 --- a/examples/react-router-framework-ssr/app/ui.tsx +++ b/examples/react-router-framework-ssr/app/ui.tsx @@ -60,7 +60,10 @@ export function Profile({ fromServer }: { fromServer: string }) { const user = useAuth((state) => state.user); const auth = useAuthClient(); // The browser's requests get the access token from the server, in memory. - const authFetch = useMemo(() => createAuthFetch(auth, `${API}/`), [auth]); + const authFetch = useMemo( + () => createAuthFetch(auth, { baseUrl: `${API}/` }), + [auth], + ); const [fromBrowser, setFromBrowser] = useState(""); async function loadProfile() { diff --git a/examples/tanstack-router/src/auth.ts b/examples/tanstack-router/src/auth.ts index 9ec9c05..b6f4cb6 100644 --- a/examples/tanstack-router/src/auth.ts +++ b/examples/tanstack-router/src/auth.ts @@ -84,4 +84,4 @@ async function login(username: string, password: string): Promise { * Sends requests to DummyJSON with the access token. After a 401 it * refreshes, then replays a GET or HEAD once. */ -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); diff --git a/examples/tanstack-start-spa/src/auth.ts b/examples/tanstack-start-spa/src/auth.ts index f509524..927e3e5 100644 --- a/examples/tanstack-start-spa/src/auth.ts +++ b/examples/tanstack-start-spa/src/auth.ts @@ -88,4 +88,4 @@ async function login(username: string, password: string): Promise { * Sends requests to DummyJSON with the access token. After a 401 it * refreshes, then replays a GET or HEAD once. */ -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); diff --git a/examples/tanstack-start-ssr/src/ui.tsx b/examples/tanstack-start-ssr/src/ui.tsx index 6a7f602..7529ac7 100644 --- a/examples/tanstack-start-ssr/src/ui.tsx +++ b/examples/tanstack-start-ssr/src/ui.tsx @@ -78,7 +78,10 @@ export function Profile({ fromServer }: { fromServer: string }) { const user = useAuth((state) => state.user); const auth = useAuthClient(); // The browser's requests get the access token from the server, in memory. - const authFetch = useMemo(() => createAuthFetch(auth, `${API}/`), [auth]); + const authFetch = useMemo( + () => createAuthFetch(auth, { baseUrl: `${API}/` }), + [auth], + ); const [fromBrowser, setFromBrowser] = useState(""); async function loadProfile() { diff --git a/site/content/docs/(latest)/client/index.mdx b/site/content/docs/(latest)/client/index.mdx index d7951e6..a64e35d 100644 --- a/site/content/docs/(latest)/client/index.mdx +++ b/site/content/docs/(latest)/client/index.mdx @@ -58,7 +58,7 @@ The examples in this section build on the app from { + return api.get(`auth/carts/user/${userId}`).json(); +} +``` + +With [axios](https://axios-http.com), choose its `fetch` adapter and pass +`authFetch` in `env`: + +```ts title="src/axios.ts" +import axios from "axios"; + +import { authFetch } from "./api.js"; +import { API } from "./backend.js"; + +export const http = axios.create({ + baseURL: API, + adapter: "fetch", + env: { fetch: authFetch }, +}); +``` + +[openapi-fetch](https://openapi-ts.dev/openapi-fetch/) takes it the same way +as ky: + +```ts +const client = createClient({ baseUrl: API, fetch: authFetch }); +``` + +What changes for the client's calls: + +- **Give the client the same API.** Its base URL must be on the origin that + `authFetch` was created for. A request for another origin rejects with + `INVALID_OPTIONS`, and the token isn't sent. +- **Signed out, every call rejects** with `UNAUTHENTICATED`. If the client + also calls public endpoints, such as your sign-in, create `authFetch` with + [`optional: true`](/docs/client/requests): those requests then go without a + token. +- **A 401 reaches the client after the refresh.** For a GET or HEAD, the + client sees the answer to the request that was sent again. For a write, it + sees the 401, as ky's `HTTPError` or axios's `AxiosError`. Retry it where + sending it twice is safe. +- **Session kit's errors keep their code.** ky rejects with the `AuthError` + itself. axios wraps it in an `AxiosError` that has the same `code`, with + the `AuthError` as its `cause`. Match on `error.code`, which works with + both, rather than on `instanceof AuthError`. +- **`authFetch` sets `Authorization`.** While signed in, it replaces a + header the client set itself. +- **Only what a `Request` holds is sent.** ky hands `fetch` the options it + doesn't know itself, such as Next.js's `next`. `authFetch` doesn't pass + those on. + +## Clients without a `fetch` option + +`createAuthFetch` and the [effetch plugin](/docs/effect#6-call-your-api-with-effetch) are built on three -calls, and any other HTTP client can use the same ones: +calls, and a client with its own transport can use the same ones: 1. **Before a request**, `auth.credentials.get()` resolves the credentials to send, waiting for a restore or a refresh that is under way. It resolves @@ -17,9 +91,10 @@ calls, and any other HTTP client can use the same ones: 3. **After a second 401**, `auth.credentials.reject(credentials)` ends the session, unless a newer one has replaced it. -With [axios](https://axios-http.com), that's two interceptors: +An axios instance that keeps its default adapter does it with two +interceptors: -```ts title="src/axios.ts" +```ts title="src/axios-interceptors.ts" import type { Credentials } from "@monarcode/session-kit"; import axios, { type InternalAxiosRequestConfig } from "axios"; @@ -64,54 +139,6 @@ http.interceptors.response.use(undefined, async (error: unknown) => { }); ``` -With [ky](https://github.com/sindresorhus/ky), two hooks do the same. The -request's `context` carries the credentials from one hook to the other: - -```ts title="src/ky.ts" -import type { Credentials } from "@monarcode/session-kit"; -import ky from "ky"; - -import { auth } from "./auth.js"; -import { API } from "./backend.js"; - -export const api = ky.create({ - baseUrl: `${API}/`, - hooks: { - beforeRequest: [ - async ({ request, options }) => { - const credentials = await auth.credentials.get(); - if (!credentials) return; - options.context.credentials = credentials; - request.headers.set( - "Authorization", - `Bearer ${credentials.accessToken}`, - ); - }, - ], - afterResponse: [ - async ({ request, options, response }) => { - const used = options.context.credentials as Credentials | undefined; - if (response.status !== 401 || !used) return; - - if (options.context.replayed) { - // The new token was refused too: end the session. - await auth.credentials.reject(used); - return; - } - const fresh = await auth.credentials.renew(used); - // As with authFetch, only a GET or HEAD is sent twice. - if (!fresh || !["GET", "HEAD"].includes(request.method)) return; - options.context.credentials = fresh; - options.context.replayed = true; - const headers = new Headers(request.headers); - headers.set("Authorization", `Bearer ${fresh.accessToken}`); - return ky.retry({ request: new Request(request, { headers }) }); - }, - ], - }, -}); -``` - Three things `createAuthFetch` does for you are yours to keep here: - **Keep the token on one origin.** Give the client one base URL, and don't diff --git a/site/content/docs/(latest)/client/requests.mdx b/site/content/docs/(latest)/client/requests.mdx index 5e0b77e..cb97981 100644 --- a/site/content/docs/(latest)/client/requests.mdx +++ b/site/content/docs/(latest)/client/requests.mdx @@ -3,12 +3,12 @@ title: Authenticated requests description: A fetch that sends the access token to one API, refreshes on a 401, and never leaks the token. --- -`createAuthFetch(auth, baseUrl)` returns a `fetch` for one API. It's built so -that a token can't leak and a user can't be signed out by accident: +`createAuthFetch(auth, { baseUrl })` returns a `fetch` for one API. It's +built so that a token can't leak and a user can't be signed out by accident: | When… | `authFetch`… | | --------------------------------------- | ---------------------------------------------------------------------------- | -| The path is on another origin | Rejects with `INVALID_OPTIONS`. The token goes only to `baseUrl`'s origin. | +| The request is for another origin | Rejects with `INVALID_OPTIONS`. The token goes only to `baseUrl`'s origin. | | The response is a redirect | Rejects rather than following it. | | The response is a 401 | Refreshes once, then sends a GET or HEAD again with the new token. | | A POST, PUT, PATCH or DELETE gets a 401 | Refreshes, and resolves the 401. It never sends a request twice on its own. | @@ -17,6 +17,12 @@ that a token can't leak and a user can't be signed out by accident: | Nobody is signed in | Rejects with `UNAUTHENTICATED`, unless `optional` is `true`. | | The network fails | Rejects as `fetch` does, unchanged. | +Call it with a path, which is resolved against `baseUrl` as a link is +against a page's address. End `baseUrl` with `/`, so that +`authFetch("orders")` lands under it. It also takes a `URL` or a `Request`, +as `fetch` does, so an HTTP client with a `fetch` option can send its +requests through it: see [Other HTTP clients](/docs/client/other-http-clients). + Because a write is never replayed for you, retry it yourself where sending it twice is safe. By then the token has been refreshed: @@ -41,7 +47,7 @@ export async function addToCart(userId: number, productId: number) { } ``` -Two options change the defaults: +Two more options change the defaults: ```ts title="src/public-api.ts" import { createAuthFetch } from "@monarcode/session-kit/http"; @@ -49,7 +55,8 @@ import { createAuthFetch } from "@monarcode/session-kit/http"; import { auth } from "./auth.js"; import { API } from "./backend.js"; -export const publicFetch = createAuthFetch(auth, `${API}/`, { +export const publicFetch = createAuthFetch(auth, { + baseUrl: `${API}/`, // One `fetch` for public and private endpoints: signed out, requests are // sent without a token instead of rejecting. optional: true, diff --git a/site/content/docs/(latest)/client/sessions.mdx b/site/content/docs/(latest)/client/sessions.mdx index 874b6ac..24d5595 100644 --- a/site/content/docs/(latest)/client/sessions.mdx +++ b/site/content/docs/(latest)/client/sessions.mdx @@ -24,11 +24,11 @@ export async function loadCart(): Promise { **Credentials** are the access token, `{ sessionId, accessToken, expiresAt }`, kept apart so that code which only needs the user never holds one. -[`createAuthFetch`](/docs/client/requests) reads them for you. Code that -sends requests another way uses `auth.credentials`: `get` before a request, -`renew` after a 401, and `reject` after a second one. -[Other HTTP clients](/docs/client/other-http-clients) explains the three, -with axios and ky. +[`createAuthFetch`](/docs/client/requests) reads them for you, and so does +an HTTP client that takes it as its `fetch`. Code that sends requests another +way uses `auth.credentials`: `get` before a request, `renew` after a 401, and +`reject` after a second one. +[Other HTTP clients](/docs/client/other-http-clients) explains both. `auth.isCurrent({ sessionId })` tells whether a session you're holding is still the signed-in one, for work that might finish after an account switch. diff --git a/site/content/docs/(latest)/getting-started.mdx b/site/content/docs/(latest)/getting-started.mdx index 1726d0d..224f3b9 100644 --- a/site/content/docs/(latest)/getting-started.mdx +++ b/site/content/docs/(latest)/getting-started.mdx @@ -275,7 +275,7 @@ import { createAuthFetch } from "@monarcode/session-kit/http"; import { auth } from "./auth.js"; import { API, userSchema } from "./backend.js"; -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); /** The signed-in user, fresh from the backend. */ export async function fetchProfile() { diff --git a/site/content/docs/(latest)/reference/http.mdx b/site/content/docs/(latest)/reference/http.mdx index bcf6066..8cf50e0 100644 --- a/site/content/docs/(latest)/reference/http.mdx +++ b/site/content/docs/(latest)/reference/http.mdx @@ -19,7 +19,7 @@ Creates a `fetch` for your API ([`AuthFetch`](#authfetch)) that sends the curren ### AuthFetch -The `fetch` that [`createAuthFetch`](#createauthfetch) returns. Call it with a path under your API's base URL, and `init` as you would pass to `fetch`. Use the name to type a prop, a context or a test fake that stands in for it. +The `fetch` that [`createAuthFetch`](#createauthfetch) returns. Call it with a path under your API's base URL, and `init` as you would pass to `fetch`. It takes a `URL` or a `Request` too, as `fetch` does. ### AuthFetchClient diff --git a/site/content/docs/(latest)/server-rendering/server-sessions.mdx b/site/content/docs/(latest)/server-rendering/server-sessions.mdx index 89c1dab..6a4269f 100644 --- a/site/content/docs/(latest)/server-rendering/server-sessions.mdx +++ b/site/content/docs/(latest)/server-rendering/server-sessions.mdx @@ -67,9 +67,9 @@ its cookies. `serverAuth.forRequest(jar)` is one request's session shaped like a client (`RequestAuth`). Code written for a client works on the server with it: -`createAuthFetch(serverAuth.forRequest(jar), baseUrl)` sends the cookie's -token and saves a renewed one after a 401, and Effect's `Auth.layer` takes -it ([Effect on the server](/docs/effect#on-the-server)). Make it per request, +`createAuthFetch(serverAuth.forRequest(jar), { baseUrl })` sends the +cookie's token and saves a renewed one after a 401, and Effect's +`Auth.layer` takes it ([Effect on the server](/docs/effect#on-the-server)). Make it per request, like the jar. ## Token refresh diff --git a/site/content/docs/(latest)/setups/expo.mdx b/site/content/docs/(latest)/setups/expo.mdx index 1c9e2dd..c66e21b 100644 --- a/site/content/docs/(latest)/setups/expo.mdx +++ b/site/content/docs/(latest)/setups/expo.mdx @@ -102,7 +102,7 @@ export const auth = createAuth({ export const { AuthProvider, useAuth, useAuthClient } = createAuthHooks(); -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); export async function signInWithPassword(username: string, password: string) { const response = await fetch(`${API}/auth/login`, { diff --git a/src/http/index.ts b/src/http/index.ts index b698f5a..8c5444f 100644 --- a/src/http/index.ts +++ b/src/http/index.ts @@ -35,7 +35,8 @@ export type AuthFetchClient = Pick< * declare const auth: AuthClient<{ id: number }, { id: number }>; * * // Some endpoints answer 401 for missing permissions, not a bad token. - * export const authFetch = createAuthFetch(auth, "https://api.example.com/", { + * export const authFetch = createAuthFetch(auth, { + * baseUrl: "https://api.example.com/", * signOutOnRepeated401: false, * }); * ``` @@ -43,6 +44,12 @@ export type AuthFetchClient = Pick< * @since 0.1.0 */ export type AuthFetchOptions = { + /** + * Your API's base URL. The access token goes only to requests on its + * origin. A path is resolved against it as a link is against a page's + * address. End it with `/`, so that `"orders"` lands under it. + */ + baseUrl: string; /** * Whether a request made while signed out is sent without an * `Authorization` header, rather than rejecting with `UNAUTHENTICATED`. @@ -63,8 +70,18 @@ export type AuthFetchOptions = { /** * The `fetch` that {@link createAuthFetch} returns. Call it with a path - * under your API's base URL, and `init` as you would pass to `fetch`. Use the - * name to type a prop, a context or a test fake that stands in for it. + * under your API's base URL, and `init` as you would pass to `fetch`. It + * takes a `URL` or a `Request` too, as `fetch` does. + * + * A `Request` with a body can be sent once, as with `fetch`. To retry a + * write after a 401, send a clone you kept. A call that rejects before + * sending anything leaves the `Request` unused. + * + * `init` takes what `Request` takes. An option that only a runtime's own + * `fetch` reads, such as Next.js's `next`, isn't passed on. + * + * Use the name to type a prop, a context or a test fake that stands in for + * it. * * @example * ```ts @@ -79,7 +96,10 @@ export type AuthFetchOptions = { * * @since 0.1.0 */ -export type AuthFetch = (path: string, init?: RequestInit) => Promise; +export type AuthFetch = ( + input: string | URL | Request, + init?: RequestInit, +) => Promise; /** Releases a response the caller will never see. */ async function discard(response: Response) { @@ -98,14 +118,19 @@ async function discard(response: Response) { * changes during a request, it rejects with `SESSION_CHANGED` rather than * resolve a response meant for another account. * - * The token never leaves your API. `path` is resolved against `baseUrl`, and - * a path on another origin, with a username or password in it, or invalid - * rejects with `INVALID_OPTIONS`. A redirect rejects rather than being - * followed. An invalid `baseUrl` throws `INVALID_OPTIONS`. + * The token never leaves your API. A request for another origin, with a + * username or password in its URL, or with an invalid URL rejects with + * `INVALID_OPTIONS`. A redirect rejects rather than being followed. A + * missing or invalid `baseUrl` throws `INVALID_OPTIONS`. While signed in, a + * request's own `Authorization` header is replaced. * * `fetch`'s own failures, such as a network error, and an `init` that * `Request` refuses, reject as `fetch` and `Request` do. * + * An HTTP client that takes a custom `fetch`, such as ky or openapi-fetch, + * can take this one. Its requests are then sent, and sent again after a 401, + * as above. + * * @example * ```ts * import type { AuthClient } from "@monarcode/session-kit"; @@ -114,7 +139,9 @@ async function discard(response: Response) { * type User = { id: number; name: string }; * declare const auth: AuthClient; * - * const authFetch = createAuthFetch(auth, "https://api.example.com/"); + * const authFetch = createAuthFetch(auth, { + * baseUrl: "https://api.example.com/", + * }); * * export async function loadOrders(): Promise { * const response = await authFetch("orders"); @@ -123,27 +150,47 @@ async function discard(response: Response) { * } * ``` * - * @see {@link AuthFetchOptions} for `optional` and `signOutOnRepeated401` + * @see {@link AuthFetchOptions} for `baseUrl`, `optional` and + * `signOutOnRepeated401` * * @since 0.1.0 */ export function createAuthFetch( auth: AuthFetchClient, - baseUrl: string, - options: AuthFetchOptions = {}, + options: AuthFetchOptions, ): AuthFetch { - const base = parseUrl(baseUrl); + if (typeof options?.baseUrl !== "string") + throw new AuthError( + "INVALID_OPTIONS", + "Pass your API's base URL as the baseUrl option", + ); + const base = parseUrl(options.baseUrl); const optional = options.optional ?? false; const signOutOnRepeated401 = options.signOutOnRepeated401 ?? true; - return async function authFetch(path: string, init: RequestInit = {}) { - const url = parseUrl(path, base); + return async function authFetch(input, init) { + if (input == null) + throw new AuthError( + "INVALID_OPTIONS", + "Pass authFetch a path, a URL or a Request", + ); + // Anything but this runtime's own `Request` becomes a string, as `fetch` + // makes it, so the URL checked here is the URL that is sent. + const given = input instanceof Request ? input : null; + const url = parseUrl(given ? given.url : String(input), base); if (url.origin !== base.origin || url.username || url.password) { throw new AuthError( "INVALID_OPTIONS", "Authenticated requests must stay on the configured API origin", ); } - const request = new Request(url, init); + + const captured = await auth.credentials.get(); + if (!captured && !optional) + throw new AuthError("UNAUTHENTICATED", "Sign in is required"); + + // Built once something will be sent: it uses up a `Request`'s body, and + // a call that rejects first must leave the caller's `Request` usable. + const request = new Request(given ?? url, init); const canReplay = request.method === "GET" || request.method === "HEAD"; const send = async (session: Credentials) => { @@ -160,10 +207,7 @@ export function createAuthFetch( return response; }; - const captured = await auth.credentials.get(); if (!captured) { - if (!optional) - throw new AuthError("UNAUTHENTICATED", "Sign in is required"); const response = await fetch( new Request(request, { redirect: "error" }), ); diff --git a/src/server/auth.ts b/src/server/auth.ts index 57893e3..388f298 100644 --- a/src/server/auth.ts +++ b/src/server/auth.ts @@ -198,10 +198,9 @@ declare const requestAuth: unique symbol; * * // Sends the cookie's token, and renews it after a 401. * export async function orders(jar: CookieJar) { - * const authFetch = createAuthFetch( - * serverAuth.forRequest(jar), - * "https://api.example.com", - * ); + * const authFetch = createAuthFetch(serverAuth.forRequest(jar), { + * baseUrl: "https://api.example.com", + * }); * return (await authFetch("/orders")).json(); * } * ``` diff --git a/tests/consumer.ts b/tests/consumer.ts index b709a41..775da3f 100644 --- a/tests/consumer.ts +++ b/tests/consumer.ts @@ -96,14 +96,27 @@ declare module "../dist/effect/index.js" { } connectAuth(router); -createAuthFetch(auth, "https://api.example.com"); -createAuthFetch(auth, "https://api.example.com", { optional: true }); -createAuthFetch(auth, "https://api.example.com", { optional: undefined }); -const authFetch: AuthFetch = createAuthFetch(auth, "https://api.example.com"); +const baseUrl = "https://api.example.com"; +createAuthFetch(auth, { baseUrl }); +createAuthFetch(auth, { baseUrl, optional: true }); +createAuthFetch(auth, { baseUrl, optional: undefined }); +// @ts-expect-error The base URL is an option, not an argument. +createAuthFetch(auth, baseUrl); +// @ts-expect-error baseUrl is required. +createAuthFetch(auth, { optional: true }); +const authFetch: AuthFetch = createAuthFetch(auth, { baseUrl }); void authFetch("orders", { method: "POST" }).then((response) => response.ok); +void authFetch(new URL("orders", baseUrl)); +void authFetch(new Request(`${baseUrl}/orders`), { method: "POST" }); const fakeFetch: AuthFetch = async () => new Response("[]"); const plainFetch: AuthFetch = fetch; -void [fakeFetch, plainFetch]; +// It fits wherever a `fetch` is taken: the global's type, and the narrower +// ones HTTP clients declare (ky's, then openapi-fetch's). +const asFetch: typeof fetch = authFetch; +const asKyFetch: (input: Request, init?: RequestInit) => Promise = + authFetch; +const asOpenApiFetch: (input: Request) => Promise = authFetch; +void [fakeFetch, plainFetch, asFetch, asKyFetch, asOpenApiFetch]; // @ts-expect-error: a path is required. void authFetch(); @@ -498,8 +511,8 @@ async function requestSide() { return [viewEmail, status, await requestAuth.credentials.get()]; } void requestSide; -createAuthFetch(requestAuth, "https://api.example.com"); -createAuthFetch(tokenServer.forRequest(jar), "https://api.example.com"); +createAuthFetch(requestAuth, { baseUrl }); +createAuthFetch(tokenServer.forRequest(jar), { baseUrl }); // @ts-expect-error Signing in stays on serverAuth. void requestAuth.signIn; // @ts-expect-error So does updateUser. @@ -538,7 +551,7 @@ void mirrorEmail; void mirror.signIn({ username: "emilys" }); // @ts-expect-error signIn takes what the signIn option takes. void mirror.signIn({ password: "x" }); -createAuthFetch(mirror, "https://api.example.com"); +createAuthFetch(mirror, { baseUrl }); createAuthHooks().AuthProvider({ client: mirror }); void requireSession(mirror, { location: { href: "/private" }, diff --git a/tests/http.test.ts b/tests/http.test.ts index b7866d9..82498f8 100644 --- a/tests/http.test.ts +++ b/tests/http.test.ts @@ -1,7 +1,10 @@ import assert from "node:assert/strict"; import { test } from "node:test"; +import { AuthError } from "@monarcode/session-kit"; import { createAuthFetch } from "@monarcode/session-kit/http"; +import axios from "axios"; +import ky from "ky"; import { cleanups, @@ -25,7 +28,9 @@ test("GET retries once; bearer tokens stay on the configured origin", async () = headers.push(request.headers.get("Authorization")); return new Response(null, { status: headers.length === 1 ? 401 : 200 }); }); - const request = createAuthFetch(auth, "https://api.example.com/"); + const request = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); assert.equal((await request("/me")).status, 200); assert.deepEqual(headers, ["Bearer access-1", "Bearer access-2"]); await assert.rejects(request("https://evil.example/me")); @@ -40,7 +45,9 @@ test("mutations are not replayed automatically", async () => { calls++; return new Response(null, { status: 401 }); }); - const request = createAuthFetch(auth, "https://api.example.com/"); + const request = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); assert.equal( (await request("/change", { method: "POST", body: "data" })).status, 401, @@ -52,7 +59,9 @@ test("second 401 ends only the matching session", async () => { const auth = client({ refresh: async () => ({ accessToken: "access-2" }) }); await auth.signIn(input()); setGlobal("fetch", async () => new Response(null, { status: 401 })); - const request = createAuthFetch(auth, "https://api.example.com/"); + const request = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); assert.equal((await request("/me")).status, 401); assert.equal(await auth.getSession(), null); }); @@ -73,7 +82,8 @@ test("a repeated 401 can keep the session when configured", async () => { const auth = client({ refresh: async () => ({ accessToken: "access-2" }) }); await auth.signIn(input()); setGlobal("fetch", async () => new Response(null, { status: 401 })); - const request = createAuthFetch(auth, "https://api.example.com/", { + const request = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", signOutOnRepeated401: false, }); assert.equal((await request("/me")).status, 401); @@ -89,7 +99,9 @@ test("a failed refresh after a 401 releases the 401 response body", async () => await auth.signIn(input()); const body = trackedBody(); setGlobal("fetch", async () => new Response(body.stream, { status: 401 })); - const request = createAuthFetch(auth, "https://api.example.com/"); + const request = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); await assert.rejects(request("/me"), code("REFRESH_FAILED")); assert.equal(body.cancelled, true); }); @@ -102,7 +114,9 @@ test("a session change during a request releases its response body", async () => await auth.signOut(); return new Response(body.stream); }); - const request = createAuthFetch(auth, "https://api.example.com/"); + const request = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); await assert.rejects(request("/me"), code("SESSION_CHANGED")); assert.equal(body.cancelled, true); }); @@ -122,7 +136,8 @@ test("optional sends signed-out requests without a token, but not locked ones", sent.push(request); return new Response(null, { status: sent.length === 1 ? 200 : 401 }); }); - const request = createAuthFetch(auth, "https://api.example.com/", { + const request = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", optional: true, }); assert.equal((await request("/feed")).status, 200); @@ -138,7 +153,9 @@ test("optional sends signed-out requests without a token, but not locked ones", code("INVALID_OPTIONS"), ); await assert.rejects( - createAuthFetch(auth, "https://api.example.com/")("/feed"), + createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + })("/feed"), code("UNAUTHENTICATED"), ); assert.equal(sent.length, 2); @@ -157,7 +174,8 @@ test("optional still sends the token, and renews after a 401, when signed in", a headers.push(request.headers.get("Authorization")); return new Response(null, { status: headers.length === 1 ? 401 : 200 }); }); - const request = createAuthFetch(auth, "https://api.example.com/", { + const request = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", optional: true, }); assert.equal((await request("/me")).status, 200); @@ -171,7 +189,8 @@ test("a sign-in during an optional signed-out request rejects with SESSION_CHANG await auth.signIn(input()); return new Response(body.stream, { status: 401 }); }); - const request = createAuthFetch(auth, "https://api.example.com/", { + const request = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", optional: true, }); await assert.rejects(request("/me"), code("SESSION_CHANGED")); @@ -187,10 +206,9 @@ test("createAuthFetch over a request's view sends the cookie's token and saves a headers.push(sent.headers.get("Authorization")); return new Response(null, { status: headers.length === 1 ? 401 : 200 }); }); - const authFetch = createAuthFetch( - serverAuth.forRequest(request()), - "https://api.example.com/", - ); + const authFetch = createAuthFetch(serverAuth.forRequest(request()), { + baseUrl: "https://api.example.com/", + }); assert.equal((await authFetch("/me")).status, 200); assert.deepEqual(headers, ["Bearer access-1", "Bearer access-2"]); // The next request reads the renewed token from the cookie. @@ -204,10 +222,9 @@ test("createAuthFetch over a request's view ends the session after a repeated 40 const { serverAuth, request, cookies, cookie } = serverSide("test"); await serverAuth.signIn(request(), tokens()); setGlobal("fetch", async () => new Response(null, { status: 401 })); - const authFetch = createAuthFetch( - serverAuth.forRequest(request()), - "https://api.example.com/", - ); + const authFetch = createAuthFetch(serverAuth.forRequest(request()), { + baseUrl: "https://api.example.com/", + }); assert.equal((await authFetch("/me")).status, 401); assert.equal(cookies.has(cookie), false); assert.equal(await serverAuth.getSession(request()), null); @@ -221,12 +238,325 @@ test("createAuthFetch over a read-only view can't renew after a 401, and keeps t calls++; return new Response(null, { status: 401 }); }); - const authFetch = createAuthFetch( - serverAuth.forRequest(request(false)), - "https://api.example.com/", - ); + const authFetch = createAuthFetch(serverAuth.forRequest(request(false)), { + baseUrl: "https://api.example.com/", + }); await assert.rejects(authFetch("/me"), code("REFRESH_FAILED")); assert.equal(calls, 1); assert.ok(cookies.has(cookie)); assert.ok(await serverAuth.getSession(request(false))); }); + +test("a URL or a Request is sent as fetch would send it", async () => { + const auth = client(); + await auth.signIn(input()); + const sent: Request[] = []; + setGlobal("fetch", async (request: Request) => { + sent.push(request); + return new Response(null, { status: 200 }); + }); + const authFetch = createAuthFetch(auth, { + baseUrl: "https://api.example.com/v1/", + }); + await authFetch(new URL("https://api.example.com/v1/me?full=1")); + await authFetch( + new Request("https://api.example.com/v1/orders", { + method: "POST", + headers: { "X-Trace": "from-request" }, + body: "data", + }), + ); + await authFetch(new Request("https://api.example.com/v1/orders"), { + method: "DELETE", + headers: { "X-Trace": "from-init" }, + }); + assert.deepEqual( + sent.map((request) => [request.method, request.url]), + [ + ["GET", "https://api.example.com/v1/me?full=1"], + ["POST", "https://api.example.com/v1/orders"], + ["DELETE", "https://api.example.com/v1/orders"], + ], + ); + assert.deepEqual( + sent.map((request) => request.headers.get("Authorization")), + ["Bearer access-1", "Bearer access-1", "Bearer access-1"], + ); + assert.equal(await sent[1]?.text(), "data"); + assert.equal(sent[1]?.headers.get("X-Trace"), "from-request"); + assert.equal(sent[2]?.headers.get("X-Trace"), "from-init"); +}); + +test("a URL or a Request for another origin is refused, and nothing is sent", async () => { + const auth = client(); + await auth.signIn(input()); + let calls = 0; + setGlobal("fetch", async () => { + calls++; + return new Response(null); + }); + const authFetch = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); + for (const target of [ + new URL("https://evil.example/me"), + new Request("https://evil.example/me"), + new URL("https://user:secret@api.example.com/me"), + // Same host, another origin. + new Request("http://api.example.com/me"), + ]) + await assert.rejects(authFetch(target), code("INVALID_OPTIONS")); + assert.equal(calls, 0); +}); + +test("a GET Request is sent again after a 401; a Request with a body is not", async () => { + let issued = 1; + const auth = client({ + refresh: async () => ({ accessToken: `access-${++issued}` }), + }); + await auth.signIn(input()); + const statuses = [401, 200, 401]; + const sent: string[] = []; + setGlobal("fetch", async (request: Request) => { + sent.push( + `${request.method} ${request.headers.get("Authorization")} ${request.headers.get("X-Trace")}`, + ); + return new Response(null, { status: statuses.shift() ?? 500 }); + }); + const authFetch = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); + const get = new Request("https://api.example.com/me", { + headers: { "X-Trace": "1" }, + }); + assert.equal((await authFetch(get)).status, 200); + const post = new Request("https://api.example.com/change", { + method: "POST", + body: "data", + }); + assert.equal((await authFetch(post)).status, 401); + assert.deepEqual(sent, [ + "GET Bearer access-1 1", + "GET Bearer access-2 1", + "POST Bearer access-2 null", + ]); +}); + +test("an HTTP client can take authFetch as its fetch", async () => { + const auth = client({ refresh: async () => ({ accessToken: "access-2" }) }); + await auth.signIn(input()); + const headers: (string | null)[] = []; + setGlobal("fetch", async (request: Request) => { + headers.push(request.headers.get("Authorization")); + return headers.length === 1 + ? new Response(null, { status: 401 }) + : new Response(JSON.stringify({ id: 1 }), { + headers: { "Content-Type": "application/json" }, + }); + }); + const api = ky.create({ + baseUrl: "https://api.example.com/", + fetch: createAuthFetch(auth, { baseUrl: "https://api.example.com/" }), + }); + assert.deepEqual(await api.get("me").json(), { id: 1 }); + assert.deepEqual(headers, ["Bearer access-1", "Bearer access-2"]); + // ky can't take the token elsewhere either, and passes the error on as + // it is. + await assert.rejects( + api.get("https://evil.example/me"), + (error: unknown) => + error instanceof AuthError && error.code === "INVALID_OPTIONS", + ); + assert.equal(headers.length, 2); +}); + +test("createAuthFetch throws INVALID_OPTIONS without a usable baseUrl", () => { + const auth = client(); + assert.throws( + // @ts-expect-error The base URL is an option, not an argument. + () => createAuthFetch(auth, "https://api.example.com/"), + code("INVALID_OPTIONS"), + ); + assert.throws( + // @ts-expect-error baseUrl is required. + () => createAuthFetch(auth, {}), + code("INVALID_OPTIONS"), + ); + // @ts-expect-error So is the options object. + assert.throws(() => createAuthFetch(auth), code("INVALID_OPTIONS")); + assert.throws( + () => createAuthFetch(auth, { baseUrl: "not a url" }), + code("INVALID_OPTIONS"), + ); +}); + +test("a HEAD Request is sent again after a 401", async () => { + const auth = client({ refresh: async () => ({ accessToken: "access-2" }) }); + await auth.signIn(input()); + const sent: string[] = []; + setGlobal("fetch", async (request: Request) => { + sent.push(`${request.method} ${request.headers.get("Authorization")}`); + return new Response(null, { status: sent.length === 1 ? 401 : 200 }); + }); + const authFetch = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); + const head = new Request("https://api.example.com/me", { method: "HEAD" }); + assert.equal((await authFetch(head)).status, 200); + assert.deepEqual(sent, ["HEAD Bearer access-1", "HEAD Bearer access-2"]); +}); + +test("a call that sends nothing leaves the caller's Request usable", async () => { + const auth = client(); + const sent: string[] = []; + setGlobal("fetch", async (request: Request) => { + sent.push(await request.text()); + return new Response(null, { status: 200 }); + }); + const authFetch = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); + const post = new Request("https://api.example.com/change", { + method: "POST", + body: "data", + }); + const elsewhere = new Request("https://evil.example/change", { + method: "POST", + body: "data", + }); + await assert.rejects(authFetch(post), code("UNAUTHENTICATED")); + await assert.rejects(authFetch(elsewhere), code("INVALID_OPTIONS")); + assert.equal(post.bodyUsed, false); + assert.equal(elsewhere.bodyUsed, false); + + await auth.signIn(input()); + assert.equal((await authFetch(post)).status, 200); + assert.deepEqual(sent, ["data"]); + // Sent once, it's used up, as with fetch. + assert.equal(post.bodyUsed, true); + await assert.rejects(authFetch(post), TypeError); +}); + +test("signed out with optional, a Request goes without a token and keeps its own", async () => { + const auth = client(); + const sent: Request[] = []; + setGlobal("fetch", async (request: Request) => { + sent.push(request); + return new Response(null, { status: 200 }); + }); + const authFetch = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + optional: true, + }); + await authFetch( + new Request("https://api.example.com/feed", { + headers: { "X-Trace": "1" }, + }), + ); + await authFetch( + new Request("https://api.example.com/login", { + method: "POST", + headers: { Authorization: "Basic abc" }, + body: "data", + }), + ); + assert.equal(sent[0]?.headers.get("Authorization"), null); + assert.equal(sent[0]?.headers.get("X-Trace"), "1"); + assert.equal(sent[1]?.headers.get("Authorization"), "Basic abc"); + assert.equal(await sent[1]?.text(), "data"); +}); + +test("a Request's signal still aborts the request that is sent", async () => { + const auth = client(); + await auth.signIn(input()); + const sent: Request[] = []; + setGlobal("fetch", async (request: Request) => { + sent.push(request); + return new Response(null, { status: 200 }); + }); + const authFetch = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); + const controller = new AbortController(); + await authFetch( + new Request("https://api.example.com/me", { signal: controller.signal }), + ); + assert.equal(sent[0]?.signal.aborted, false); + controller.abort(); + assert.equal(sent[0]?.signal.aborted, true); +}); + +test("the URL that is checked is the URL that is sent", async () => { + const auth = client(); + await auth.signIn(input()); + const sent: string[] = []; + setGlobal("fetch", async (request: Request) => { + sent.push(request.url); + return new Response(null, { status: 200 }); + }); + const authFetch = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); + // Not a Request, whatever it claims: it's read as fetch reads it, as a + // string, and never as the URL it names. + const lookalike = { url: "https://api.example.com/me" }; + await authFetch(lookalike as unknown as Request); + assert.deepEqual(sent, ["https://api.example.com/[object%20Object]"]); + for (const missing of [null, undefined]) + await assert.rejects( + authFetch(missing as unknown as string), + code("INVALID_OPTIONS"), + ); + assert.equal(sent.length, 1); +}); + +test("axios can take authFetch through its fetch adapter", async () => { + let issued = 1; + const auth = client({ + refresh: async () => ({ accessToken: `access-${++issued}` }), + }); + await auth.signIn(input()); + const statuses = [401, 200, 401]; + const sent: string[] = []; + setGlobal("fetch", async (request: Request) => { + sent.push(`${request.method} ${request.headers.get("Authorization")}`); + const status = statuses.shift() ?? 500; + return new Response(status === 200 ? JSON.stringify({ id: 1 }) : null, { + status, + headers: { "Content-Type": "application/json" }, + }); + }); + const http = axios.create({ + baseURL: "https://api.example.com/", + adapter: "fetch", + env: { + fetch: createAuthFetch(auth, { baseUrl: "https://api.example.com/" }), + }, + }); + assert.deepEqual((await http.get("me")).data, { id: 1 }); + // A write gets the 401 back, after the refresh, and isn't sent twice. + await assert.rejects( + http.post("change", { quantity: 1 }), + (error: unknown) => + axios.isAxiosError(error) && error.response?.status === 401, + ); + assert.deepEqual(sent, [ + "GET Bearer access-1", + "GET Bearer access-2", + "POST Bearer access-2", + ]); + + // axios wraps what its fetch rejects with: the code is kept, and the + // AuthError is the cause. + const wraps = (expected: string) => (error: unknown) => + axios.isAxiosError(error) && + error.code === expected && + error.cause instanceof AuthError; + await assert.rejects( + http.get("https://evil.example/me"), + wraps("INVALID_OPTIONS"), + ); + await auth.signOut(); + await assert.rejects(http.get("me"), wraps("UNAUTHENTICATED")); + assert.equal(sent.length, 3); +}); diff --git a/tests/mirror.test.ts b/tests/mirror.test.ts index a0b988b..70e2069 100644 --- a/tests/mirror.test.ts +++ b/tests/mirror.test.ts @@ -407,7 +407,9 @@ test("end to end: browser sign-in sealed on the server, then authFetch", async ( status: authorization === "Bearer access-1" ? 401 : 200, }); }; - const authFetch = createAuthFetch(auth, "https://api.example.com/"); + const authFetch = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); assert.equal((await authFetch("me")).status, 200); assert.deepEqual(sent, ["Bearer access-1", "Bearer access-2"]); From 327ab06a75f38311c6ccb7ac221ec5f65cbd99b3 Mon Sep 17 00:00:00 2001 From: monarcode Date: Fri, 13 Nov 2026 21:23:43 +0100 Subject: [PATCH 02/26] feat!: unwrap mirror sign-in errors, take options in useMirrorAuth, add connectSession BREAKING CHANGE: a createMirrorAuth client's signIn rejects with the app's own error instead of a USER_VALIDATION_FAILED AuthError. useMirrorAuth takes { create, session, onChange }. TanStack Start's connectSession(router) replaces sessionHydration(auth) and connectAuth(router); sessionHydration, SessionHydration and DehydratedSession are removed. --- AGENTS.md | 4 +- CHANGELOG.md | 55 +++++- examples/README.md | 2 +- examples/next-app/app/providers.tsx | 10 +- examples/next-app/app/ui.tsx | 5 +- .../react-router-framework-ssr/app/root.tsx | 6 +- .../tanstack-start-ssr/src/auth/client.ts | 2 +- examples/tanstack-start-ssr/src/router.tsx | 10 +- examples/tanstack-start-ssr/src/ui.tsx | 5 +- .../docs/(latest)/configuration/errors.mdx | 7 +- .../docs/(latest)/reference/error-codes.mdx | 2 +- .../content/docs/(latest)/reference/index.mdx | 2 +- .../content/docs/(latest)/reference/react.mdx | 10 ++ .../(latest)/reference/tanstack-start.mdx | 18 +- .../docs/(latest)/server-rendering/index.mdx | 2 +- site/content/docs/(latest)/setups/next.mdx | 13 +- .../docs/(latest)/setups/react-router-ssr.mdx | 6 +- .../docs/(latest)/setups/tanstack-start.mdx | 29 +-- src/core/errors.ts | 5 +- src/core/mirror.ts | 29 +-- src/effect/auth.ts | 20 ++- src/react/index.ts | 1 + src/react/mirror.ts | 77 ++++++-- src/tanstack-router/connect.ts | 2 +- src/tanstack-start/index.ts | 168 +++++++++--------- tests/consumer.ts | 69 ++++--- tests/effect.test.ts | 21 +++ tests/mirror.test.ts | 48 ++++- tests/package.test.ts | 4 +- tests/server-session-hooks.test.ts | 37 +++- tests/tanstack-start.test.ts | 153 +++++++++++++--- 31 files changed, 584 insertions(+), 238 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 14d0ad0..f3acdfa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,7 +82,9 @@ Consumers import from the root and from subpaths: (`INVALID_OPTIONS`). Wrap a failure at the operation's boundary with `toAuthError(code, message, cause)`, where the operation knows its code; a `cause` is whatever failed, and doesn't need to be an `AuthError`. - `fetch`'s and `Request`'s own failures pass through `authFetch`. + `fetch`'s and `Request`'s own failures pass through `authFetch`, and the + app's own sign-in errors pass through a `createMirrorAuth` client's + `signIn`. - Source imports use explicit `.js` extensions. Because `exactOptionalPropertyTypes` is on, write optional props as `foo?: T | undefined`. `readonly` is a separate, per-type choice: outputs diff --git a/CHANGELOG.md b/CHANGELOG.md index dba379c..756bc58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ page shows ky, axios with its `fetch` adapter, and openapi-fetch. It replaces the ky recipe built on hooks, and keeps the axios interceptors for an instance on axios's default adapter. +- `UseMirrorAuthOptions`, the type of `useMirrorAuth`'s options. ### Changed @@ -36,6 +37,53 @@ - `authFetch` asks for the credentials before it builds the request. Signed out or locked, a call with an `init` that `Request` refuses now rejects with `UNAUTHENTICATED` or `LOCKED`, not with `Request`'s `TypeError`. +- **Breaking:** the `signIn` of a `createMirrorAuth` client rejects with what + your `signIn` option threw, unchanged, as a sign-in in a single-page app + does. It used to wrap it in a `USER_VALIDATION_FAILED` `AuthError`, so a + sign-in form had to read the message from `cause`. A result that isn't a + session still rejects with `INVALID_SESSION`. + + ```ts + // Before + const reason = error instanceof Error ? error.cause : undefined; + setError(reason instanceof Error ? reason.message : "Could not sign in"); + // After + setError(error instanceof Error ? error.message : "Could not sign in"); + ``` + +- **Breaking:** `useMirrorAuth` takes one options object, and throws + `INVALID_OPTIONS` without `create` or `onChange`. + + ```ts + // Before + useMirrorAuth(createAppAuth, session, () => router.refresh()); + // After + useMirrorAuth({ + create: createAppAuth, + session, + onChange: () => router.refresh(), + }); + ``` + +- **Breaking:** TanStack Start's `connectSession(router)` replaces + `sessionHydration(auth)` and the `connectAuth(router)` beside it. It keeps + the router's own `dehydrate` and `hydrate`, which `...sessionHydration(auth)` + replaced, or was replaced by, depending on the order of the spread. + `sessionHydration`, `SessionHydration` and `DehydratedSession` are removed. + + ```ts + // Before + const router = createRouter({ + routeTree, + context: { auth }, + ...sessionHydration(auth), + }); + connectAuth(router); + // After + const router = createRouter({ routeTree, context: { auth } }); + connectSession(router); + ``` + - The guides moved to the documentation site, [session-kit.pages.dev](https://session-kit.pages.dev), with an API reference for every entry point and every error code. The README is now a @@ -54,10 +102,9 @@ `defaultError` to effetch-query's `endpoints`. `sessionBearer`'s example calls the client's methods too. - `AuthErrorCode`'s docs say which codes the browser client of a - server-rendered app rejects with: `USER_VALIDATION_FAILED` when signing in - on the server fails, `PERSISTENCE_FAILED` when signing out there fails, and - `REFRESH_FAILED` when reading the session or the access token from the - server fails. + server-rendered app rejects with: `PERSISTENCE_FAILED` when signing out on + the server fails, and `REFRESH_FAILED` when reading the session or the + access token from the server fails. - The setup guides are corrected against the code and the example apps. The TanStack Start guard renders `SessionOutlet`, the Next.js guard sends users back to the page they asked for after sign-in, and the React Router layout diff --git a/examples/README.md b/examples/README.md index 91083ed..5df2b9a 100644 --- a/examples/README.md +++ b/examples/README.md @@ -74,7 +74,7 @@ run ios` and `run android` build it natively. In CI it is only bundled, with `httpOnly` cookie with `createServerAuth` (`src/auth/server.ts`), signs in with DummyJSON from a server function, and refreshes in request middleware (`src/start.ts`). `createMirrorAuth` gives the routes and components a - client, filled by `loadSession` on the server and `sessionHydration` in the + client, filled by `loadSession` on the server and `connectSession` in the browser. `auth/me` is called both from a server function and, with `clientCredentials`, from the browser. Set `SESSION_SECRET` (32 or more random characters) to run `vite preview`; `vite dev` uses a development diff --git a/examples/next-app/app/providers.tsx b/examples/next-app/app/providers.tsx index 7203995..5354a0f 100644 --- a/examples/next-app/app/providers.tsx +++ b/examples/next-app/app/providers.tsx @@ -11,8 +11,8 @@ import { AuthProvider } from "./hooks"; /** * Gives Client Components the session the layout read. `useMirrorAuth` * follows the server's session when the page renders again, and renders it - * again with `router.refresh()` when the session changes in the browser, as after a sign-out here - * or in another tab, so the pages' redirects run. + * again with `router.refresh()` when the session changes in the browser, as + * after a sign-out here or in another tab, so the pages' redirects run. */ export function Providers({ session, @@ -22,6 +22,10 @@ export function Providers({ children: ReactNode; }) { const router = useRouter(); - const auth = useMirrorAuth(createAppAuth, session, () => router.refresh()); + const auth = useMirrorAuth({ + create: createAppAuth, + session, + onChange: () => router.refresh(), + }); return {children}; } diff --git a/examples/next-app/app/ui.tsx b/examples/next-app/app/ui.tsx index cf65548..38285d3 100644 --- a/examples/next-app/app/ui.tsx +++ b/examples/next-app/app/ui.tsx @@ -29,10 +29,7 @@ export function LoginForm() { }); } catch (cause) { // The Server Function's own message, such as a wrong password. - const reason = cause instanceof Error ? cause.cause : undefined; - setError( - reason instanceof Error ? reason.message : "Could not sign in", - ); + setError(cause instanceof Error ? cause.message : "Could not sign in"); setPending(false); } } diff --git a/examples/react-router-framework-ssr/app/root.tsx b/examples/react-router-framework-ssr/app/root.tsx index fd3d839..e41ffa0 100644 --- a/examples/react-router-framework-ssr/app/root.tsx +++ b/examples/react-router-framework-ssr/app/root.tsx @@ -57,7 +57,11 @@ export function Layout({ children }: { children: ReactNode }) { export default function App() { const { session } = useLoaderData(); const { revalidate } = useRevalidator(); - const auth = useMirrorAuth(createAppAuth, session, revalidate); + const auth = useMirrorAuth({ + create: createAppAuth, + session, + onChange: revalidate, + }); return ( diff --git a/examples/tanstack-start-ssr/src/auth/client.ts b/examples/tanstack-start-ssr/src/auth/client.ts index b3bb1a8..48d03eb 100644 --- a/examples/tanstack-start-ssr/src/auth/client.ts +++ b/examples/tanstack-start-ssr/src/auth/client.ts @@ -11,7 +11,7 @@ import { /** * The client the routes and components use. It mirrors the session the * server keeps in its cookie: `loadSession` fills it on the server, and - * `sessionHydration` carries that to the browser. Create one per router: on + * `connectSession` carries that to the browser. Create one per router: on * the server, that is one per request. */ export function createAppAuth() { diff --git a/examples/tanstack-start-ssr/src/router.tsx b/examples/tanstack-start-ssr/src/router.tsx index 777d5bb..66fcbf5 100644 --- a/examples/tanstack-start-ssr/src/router.tsx +++ b/examples/tanstack-start-ssr/src/router.tsx @@ -1,5 +1,4 @@ -import { connectAuth } from "@monarcode/session-kit/tanstack-router"; -import { sessionHydration } from "@monarcode/session-kit/tanstack-start"; +import { connectSession } from "@monarcode/session-kit/tanstack-start"; import { createRouter } from "@tanstack/react-router"; import { createAppAuth } from "./auth/client"; @@ -13,11 +12,10 @@ export function getRouter() { context: { auth }, defaultPendingComponent: Pending, scrollRestoration: true, - // Sends the session the server read to the browser, without tokens. - ...sessionHydration(auth), }); - // Re-runs guards when the session changes. Does nothing on the server. - connectAuth(router); + // Sends the session the server read to the browser, without tokens, and + // re-runs guards when it changes there. + connectSession(router); return router; } diff --git a/examples/tanstack-start-ssr/src/ui.tsx b/examples/tanstack-start-ssr/src/ui.tsx index 7529ac7..2620cc2 100644 --- a/examples/tanstack-start-ssr/src/ui.tsx +++ b/examples/tanstack-start-ssr/src/ui.tsx @@ -26,10 +26,7 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { await onSignedIn(); } catch (cause) { // The server function's own message, such as a wrong password. - const reason = cause instanceof Error ? cause.cause : undefined; - setError( - reason instanceof Error ? reason.message : "Could not sign in", - ); + setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { setPending(false); } diff --git a/site/content/docs/(latest)/configuration/errors.mdx b/site/content/docs/(latest)/configuration/errors.mdx index bc23a29..e537fc2 100644 --- a/site/content/docs/(latest)/configuration/errors.mdx +++ b/site/content/docs/(latest)/configuration/errors.mdx @@ -17,7 +17,7 @@ Match on an error's `code`, not its message, which may change in any release: | `UNAUTHENTICATED` | The operation needs a signed-in session, and there is none. | | `REFRESH_FAILED` | The refresh callback threw, or there was no callback or refresh token to use. With server rendering, reading the session or the access token from the server failed. | | `SESSION_CHANGED` | A newer sign-in, a sign-out, or another tab replaced the session while this ran. | -| `USER_VALIDATION_FAILED` | The user couldn't be accepted: the schema rejected it (`issues`), or, with server rendering, signing in on the server failed (`cause`). | +| `USER_VALIDATION_FAILED` | The user couldn't be accepted: the schema rejected it (`issues`), or an `updateUser` function failed (`cause`). | | `INVALID_SESSION` | Tokens or a saved session that can't be used, such as an expired token at sign-in. | | `PERSISTENCE_FAILED` | Storage couldn't be read, written, or cleared. With server rendering, signing out on the server failed. | | `REVOKE_FAILED` | The `revoke` callback failed. Published in `state.error`; `signOut()` still resolves. | @@ -49,8 +49,9 @@ export function errorMessage(error: unknown): string { ``` `authFetch` lets the failures of `fetch` and `Request`, such as a network -error, through unchanged. They aren't `AuthError`s, so `errorMessage` shows -their own message. +error, through unchanged. So does the `signIn` of a server-rendered app's +browser client, for what your sign-in function threw. They aren't +`AuthError`s, so `errorMessage` shows their own message. ## Handle storage failures diff --git a/site/content/docs/(latest)/reference/error-codes.mdx b/site/content/docs/(latest)/reference/error-codes.mdx index 2bc55da..c9a40d3 100644 --- a/site/content/docs/(latest)/reference/error-codes.mdx +++ b/site/content/docs/(latest)/reference/error-codes.mdx @@ -19,7 +19,7 @@ How errors reach your app, and how to show them: ## USER_VALIDATION_FAILED -The user couldn't be accepted. `issues` holds the schema's issues when it rejected the user, and `cause` holds the error when something else failed, such as an `updateUser` function or, in the browser of a server-rendered app, signing in on the server. Otherwise `message` says why, such as a user that isn't a plain JSON object. +The user couldn't be accepted. `issues` holds the schema's issues when it rejected the user, and `cause` holds the error when something else failed, such as an `updateUser` function. Otherwise `message` says why, such as a user that isn't a plain JSON object. ## INVALID_SESSION diff --git a/site/content/docs/(latest)/reference/index.mdx b/site/content/docs/(latest)/reference/index.mdx index 67f9b14..d8f1154 100644 --- a/site/content/docs/(latest)/reference/index.mdx +++ b/site/content/docs/(latest)/reference/index.mdx @@ -21,7 +21,7 @@ API. | [`@monarcode/session-kit/react-router/server`](/docs/reference/react-router-server) | `cookieJarMiddleware`, `routerJar`, types | | [`@monarcode/session-kit/http`](/docs/reference/http) | `createAuthFetch`, types | | [`@monarcode/session-kit/server`](/docs/reference/server) | `createServerAuth`, types | -| [`@monarcode/session-kit/tanstack-start`](/docs/reference/tanstack-start) | `sessionHydration`, `loadSession`, types | +| [`@monarcode/session-kit/tanstack-start`](/docs/reference/tanstack-start) | `connectSession`, `loadSession` | | [`@monarcode/session-kit/tanstack-start/server`](/docs/reference/tanstack-start-server) | `startJar` | | [`@monarcode/session-kit/next`](/docs/reference/next) | `nextJar`, `proxyJar`, types | | [`@monarcode/session-kit/expo`](/docs/reference/expo) | `secureStorage`, `SessionGate`, `rememberDeepLink`, types | diff --git a/site/content/docs/(latest)/reference/react.mdx b/site/content/docs/(latest)/reference/react.mdx index 208af44..8a3c358 100644 --- a/site/content/docs/(latest)/reference/react.mdx +++ b/site/content/docs/(latest)/reference/react.mdx @@ -52,3 +52,13 @@ What the React bindings need from an auth client: its `state`, and `mount` to st ### StateOf The state type of a client: what `useAuth()` returns (`AuthState`). + +### UseMirrorAuthOptions + +Options for [`useMirrorAuth`](#usemirrorauth). + + diff --git a/site/content/docs/(latest)/reference/tanstack-start.mdx b/site/content/docs/(latest)/reference/tanstack-start.mdx index befc923..42919ae 100644 --- a/site/content/docs/(latest)/reference/tanstack-start.mdx +++ b/site/content/docs/(latest)/reference/tanstack-start.mdx @@ -11,20 +11,10 @@ Guide: [TanStack Start](/docs/setups/tanstack-start). ## Functions -### loadSession - -Reads this request's session into the client. Call it in the root route's `beforeLoad`. - -### sessionHydration - -Router options that carry the session from the server render to the browser. Spread them into `createRouter`. +### connectSession -## Types +Connects a TanStack Start router to the browser client in its context, as `auth`. Call it once in `getRouter`, after `createRouter`. -### DehydratedSession - -The session the server render sends to the browser, from [`sessionHydration`](#sessionhydration)'s `dehydrate`. It holds no tokens. - -### SessionHydration +### loadSession -The router options [`sessionHydration`](#sessionhydration) returns, for `createRouter`. +Reads this request's session into the client. Call it in the root route's `beforeLoad`. diff --git a/site/content/docs/(latest)/server-rendering/index.mdx b/site/content/docs/(latest)/server-rendering/index.mdx index 18a3fa7..96094a8 100644 --- a/site/content/docs/(latest)/server-rendering/index.mdx +++ b/site/content/docs/(latest)/server-rendering/index.mdx @@ -42,7 +42,7 @@ how the session reaches the browser: | Framework | On the server | In the browser | Setup | | ------------------------------------- | ----------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------- | -| TanStack Start | `startJar()`, refreshing in request middleware | `sessionHydration`, `loadSession` | [TanStack Start](/docs/setups/tanstack-start) | +| TanStack Start | `startJar()`, refreshing in request middleware | `connectSession`, `loadSession` | [TanStack Start](/docs/setups/tanstack-start) | | Next.js 16, App Router | `nextJar(await cookies())`, `proxyJar` in Proxy | `useMirrorAuth` from `@monarcode/session-kit/react` | [Next.js](/docs/setups/next) | | React Router framework mode, with SSR | `cookieJarMiddleware`, `routerJar(context)` | `useMirrorAuth` from `@monarcode/session-kit/react` | [React Router with server rendering](/docs/setups/react-router-ssr) | diff --git a/site/content/docs/(latest)/setups/next.mdx b/site/content/docs/(latest)/setups/next.mdx index f30ab0e..976a78b 100644 --- a/site/content/docs/(latest)/setups/next.mdx +++ b/site/content/docs/(latest)/setups/next.mdx @@ -268,9 +268,11 @@ export function Providers(props: { children: ReactNode; }) { const router = useRouter(); - const auth = useMirrorAuth(createAppAuth, props.session, () => - router.refresh(), - ); + const auth = useMirrorAuth({ + create: createAppAuth, + session: props.session, + onChange: () => router.refresh(), + }); return {props.children}; } ``` @@ -354,9 +356,8 @@ export function SignInForm() { password: String(form.get("password")), }); } catch (failure) { - // An AuthError; its cause is what signInAction returned. - const cause = failure instanceof Error ? failure.cause : undefined; - setError(cause instanceof Error ? cause.message : "Sign-in failed"); + // What the client's signIn option threw, from signInAction's error. + setError(failure instanceof Error ? failure.message : "Sign-in failed"); } } diff --git a/site/content/docs/(latest)/setups/react-router-ssr.mdx b/site/content/docs/(latest)/setups/react-router-ssr.mdx index 6834e21..c20af47 100644 --- a/site/content/docs/(latest)/setups/react-router-ssr.mdx +++ b/site/content/docs/(latest)/setups/react-router-ssr.mdx @@ -337,7 +337,11 @@ export function Layout({ children }: { children: ReactNode }) { export default function App() { const { session } = useLoaderData(); const { revalidate } = useRevalidator(); - const auth = useMirrorAuth(createAppAuth, session, revalidate); + const auth = useMirrorAuth({ + create: createAppAuth, + session, + onChange: revalidate, + }); return ( diff --git a/site/content/docs/(latest)/setups/tanstack-start.mdx b/site/content/docs/(latest)/setups/tanstack-start.mdx index edb81f0..1ca0d0a 100644 --- a/site/content/docs/(latest)/setups/tanstack-start.mdx +++ b/site/content/docs/(latest)/setups/tanstack-start.mdx @@ -171,8 +171,9 @@ compare its `Sec-Fetch-Site` header to `same-origin`. `createMirrorAuth` makes the client that routes and components use. Create it in `getRouter`, which Start calls once per request on the server and once in -the browser, never at module level. `sessionHydration` sends the session the -server read to the browser with the page. +the browser, never at module level. `connectSession` sends the session the +server read to the browser with the page, and runs guards again when it +changes there. First, the client: @@ -198,8 +199,7 @@ export type AppAuth = ReturnType; Then the Router, which creates it and connects it: ```tsx title="src/router.tsx" -import { connectAuth } from "@monarcode/session-kit/tanstack-router"; -import { sessionHydration } from "@monarcode/session-kit/tanstack-start"; +import { connectSession } from "@monarcode/session-kit/tanstack-start"; import { createRouter } from "@tanstack/react-router"; import { createAppAuth } from "./auth/client"; @@ -207,12 +207,8 @@ import { routeTree } from "./routeTree.gen"; export function getRouter() { const auth = createAppAuth(); - const router = createRouter({ - routeTree, - context: { auth }, - ...sessionHydration(auth), - }); - connectAuth(router); + const router = createRouter({ routeTree, context: { auth } }); + connectSession(router); return router; } @@ -224,7 +220,9 @@ declare module "@tanstack/react-router" { ``` Let TypeScript infer the client's types from its options: with -`createMirrorAuth(…)`, `signIn` would be left out. +`createMirrorAuth(…)`, `signIn` would be left out. A `dehydrate` and a +`hydrate` of your own, such as for a query cache, go to `createRouter` as +usual: `connectSession` keeps them. ## 5. Load the session, then guard routes @@ -276,16 +274,19 @@ the session it returns, re-runs guards and tells other tabs: ```ts title="src/sign-in.ts" import type { AppAuth } from "./auth/client"; +/** Signs in, and resolves the message to show when it fails. */ export async function signIn( auth: AppAuth, username: string, password: string, -) { +): Promise { try { await auth.signIn({ username, password }); + return null; } catch (error) { - // An AuthError; its cause is what signInFn threw. - console.warn(error); + // What signInFn threw, such as your backend's message for a wrong + // password. + return error instanceof Error ? error.message : "Could not sign in"; } } ``` diff --git a/src/core/errors.ts b/src/core/errors.ts index 0fd79b2..1aa3795 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -20,9 +20,8 @@ export type AuthErrorCode = /** * The user couldn't be accepted. `issues` holds the schema's issues when * it rejected the user, and `cause` holds the error when something else - * failed, such as an `updateUser` function or, in the browser of a - * server-rendered app, signing in on the server. Otherwise `message` says - * why, such as a user that isn't a plain JSON object. + * failed, such as an `updateUser` function. Otherwise `message` says why, + * such as a user that isn't a plain JSON object. */ | "USER_VALIDATION_FAILED" /** diff --git a/src/core/mirror.ts b/src/core/mirror.ts index e445de5..c7a5706 100644 --- a/src/core/mirror.ts +++ b/src/core/mirror.ts @@ -250,10 +250,9 @@ export type MirrorAuth = MirrorAuthBase & * Signs in on your server with the `signIn` option, then takes the * session it resolves and tells other tabs. * - * If the option fails, it rejects with `USER_VALIDATION_FAILED`, - * whose `cause` is the original error. An `AuthError` passes - * through unchanged. If it resolves anything but a session, it - * rejects with `INVALID_SESSION`. + * If the option throws, it rejects with that error, unchanged, as a + * sign-in in a single-page app does. If it resolves anything but a + * session, it rejects with `INVALID_SESSION`. */ signIn: (input: In) => Promise>; }); @@ -656,13 +655,21 @@ export function createMirrorAuth( "INVALID_SESSION", "signIn must resolve the new session", ); - } catch (cause) { - const error = toAuthError( - "USER_VALIDATION_FAILED", - "Could not sign in", - cause, - ); - debug.log("sign-in", "rejected", undefined, error); + } catch (error) { + // Not wrapped: the app's own error, such as a wrong password, is + // what its sign-in form shows. A debug event carries only an + // `AuthError`. + if (error instanceof AuthError) + debug.log("sign-in", "rejected", undefined, error); + else + debug.log( + "sign-in", + "rejected by the signIn option", + debug.secret({ + reason: + error instanceof Error ? error.message : String(error), + }), + ); throw error; } change(next); diff --git a/src/effect/auth.ts b/src/effect/auth.ts index c3f019c..5ccb0cc 100644 --- a/src/effect/auth.ts +++ b/src/effect/auth.ts @@ -7,7 +7,7 @@ import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; -import { AuthError } from "../core/errors.js"; +import { AuthError, toAuthError } from "../core/errors.js"; import type { AuthClient, Credentials } from "../core/types.js"; import type { RequestAuth } from "../server/auth.js"; import { @@ -388,7 +388,9 @@ export class Auth extends Context.Service()( * example after a login request. * * Fails with `USER_VALIDATION_FAILED`, `INVALID_SESSION`, - * `PERSISTENCE_FAILED` or `SESSION_CHANGED`. + * `PERSISTENCE_FAILED` or `SESSION_CHANGED`. With a `createMirrorAuth` + * client, an error your `signIn` option throws, such as a wrong password, + * fails with `USER_VALIDATION_FAILED`, and is its `AuthError`'s `cause`. * * Dies when the client has no `signIn`. That's a `createMirrorAuth` client * made without one, or a request's view on the server, where you call @@ -402,7 +404,19 @@ export class Auth extends Context.Service()( client as { signIn?: (input: unknown) => Promise } ).signIn; return signIn - ? Effect.asVoid(fromPromise(() => signIn.call(client, input))) + ? fromPromise(async () => { + try { + await signIn.call(client, input); + } catch (cause) { + // A mirror client rejects with the app's own error. An Effect + // gets it as a typed failure rather than a defect. + throw toAuthError( + "USER_VALIDATION_FAILED", + "Could not sign in", + cause, + ); + } + }) : Effect.die( new AuthError( "INVALID_OPTIONS", diff --git a/src/react/index.ts b/src/react/index.ts index 6ccebca..92db4d8 100644 --- a/src/react/index.ts +++ b/src/react/index.ts @@ -7,3 +7,4 @@ export type { AuthHooksOptions, AuthProviderProps, } from "./hooks.js"; +export type { UseMirrorAuthOptions } from "./mirror.js"; diff --git a/src/react/mirror.ts b/src/react/mirror.ts index 52e99a7..64615f0 100644 --- a/src/react/mirror.ts +++ b/src/react/mirror.ts @@ -1,26 +1,68 @@ import { useEffect, useRef, useState } from "react"; +import { AuthError } from "../core/errors.js"; import type { MirrorAuth } from "../core/mirror.js"; import { watchVersion } from "../core/revalidate.js"; import type { Session } from "../core/types.js"; import { sameSession } from "../core/user.js"; +/** + * Options for {@link useMirrorAuth}. + * + * @example + * ```ts + * import type { MirrorAuth, Session } from "@monarcode/session-kit"; + * import type { UseMirrorAuthOptions } from "@monarcode/session-kit/react"; + * + * type User = { id: number; firstName: string }; + * declare function createAppAuth( + * session: Session | null, + * ): MirrorAuth; + * declare function refreshPage(): void; + * + * export function mirrorOptions( + * session: Session | null, + * ): UseMirrorAuthOptions> { + * return { create: createAppAuth, session, onChange: refreshPage }; + * } + * ``` + * + * @since 0.1.0 + */ +export interface UseMirrorAuthOptions> { + /** + * Creates the client from the session the page was rendered with. It's + * called once, on the first render. + */ + create: (session: Session | null) => C; + /** + * The session your server rendered this page with, or `null`. When a new + * server render brings another one, the client takes it. + */ + session: Session | null; + /** + * Called when the session changes in the browser, such as after + * `signOut()` or in another tab. Make it render on the server again, so + * its redirects run: `router.refresh()` in Next.js, or `revalidate` from + * `useRevalidator()` in React Router. It can be a new function on each + * render: the latest one is called. + */ + onChange: () => unknown; +} + /** * Creates a `createMirrorAuth` client once, from the session the page was * rendered with, and keeps it in step with your server. Call it in the * component that renders `AuthProvider`. * * When a new server render brings another session, such as after a server - * action signs in or out, the client takes it and tells other tabs. + * action signs in or out, the client takes it and tells other tabs. When the + * session changes in the browser, it calls `onChange`. * - * When the session changes in the browser, such as after `signOut()` or in - * another tab, it calls `onChange`. Make that render on the server again, so - * its redirects run: `router.refresh()` in Next.js, or `revalidate` from - * `useRevalidator()` in React Router. + * Throws `INVALID_OPTIONS` without a `create` or an `onChange` function. * * Creating the client here, rather than at module level, keeps one per - * request during server rendering. `onChange` can be a new function on each - * render, as the latest one is called. + * request during server rendering. * * @example * ```tsx @@ -48,18 +90,31 @@ import { sameSession } from "../core/user.js"; * export default function App() { * const { session } = useLoaderData(); * const { revalidate } = useRevalidator(); - * const auth = useMirrorAuth(createAppAuth, session, revalidate); + * const auth = useMirrorAuth({ + * create: createAppAuth, + * session, + * onChange: revalidate, + * }); * return ; * } * ``` * + * @see {@link UseMirrorAuthOptions} for `create`, `session` and `onChange` + * * @since 0.1.0 */ export function useMirrorAuth>( - create: (session: Session | null) => C, - session: Session | null, - onChange: () => unknown, + options: UseMirrorAuthOptions, ): C { + if ( + typeof options?.create !== "function" || + typeof options.onChange !== "function" + ) + throw new AuthError( + "INVALID_OPTIONS", + "Pass useMirrorAuth { create, session, onChange }", + ); + const { create, session, onChange } = options; const [auth] = useState(() => create(session)); const latestOnChange = useRef(onChange); // The session the server last rendered, which the client follows. diff --git a/src/tanstack-router/connect.ts b/src/tanstack-router/connect.ts index a561cfa..923cedf 100644 --- a/src/tanstack-router/connect.ts +++ b/src/tanstack-router/connect.ts @@ -1,7 +1,7 @@ import { watchVersion } from "../core/revalidate.js"; import type { AuthSource } from "../react/context.js"; -type AuthRouter = { +export type AuthRouter = { options: { context: { auth: AuthSource } }; invalidate: () => Promise; clearCache: () => void; diff --git a/src/tanstack-start/index.ts b/src/tanstack-start/index.ts index a950a37..96231d8 100644 --- a/src/tanstack-start/index.ts +++ b/src/tanstack-start/index.ts @@ -1,81 +1,56 @@ import { AuthError } from "../core/errors.js"; import { mirrorOf, type MirrorAuth } from "../core/mirror.js"; import type { Session } from "../core/types.js"; +import { connectAuth, type AuthRouter } from "../tanstack-router/connect.js"; -/** - * The session the server render sends to the browser, from - * {@link sessionHydration}'s `dehydrate`. It holds no tokens. - * - * @example - * ```ts - * import type { - * DehydratedSession, - * } from "@monarcode/session-kit/tanstack-start"; - * - * type User = { id: number; firstName: string }; - * - * export const signedOut: DehydratedSession = { - * loaded: true, - * session: null, - * }; - * ``` - * - * @since 0.1.0 - */ -export type DehydratedSession = { - /** - * Whether {@link loadSession} read the session on the server for this - * page. When it didn't, such as for a root route with `ssr: false` or a - * failed read, the browser reads the session itself. - */ +/** What the server render sends to the browser for the session. */ +type DehydratedSession = { + /** Whether `loadSession` read the session on the server for this page. */ loaded: boolean; - /** The session the server read, or `null` when signed out. */ - session: Session | null; + session: Session | null; }; /** - * The router options {@link sessionHydration} returns, for `createRouter`. - * - * @example - * ```ts - * import type { MirrorAuth } from "@monarcode/session-kit"; - * import { - * sessionHydration, - * type SessionHydration, - * } from "@monarcode/session-kit/tanstack-start"; - * - * type User = { id: number; firstName: string }; - * declare const auth: MirrorAuth; - * - * export const options: SessionHydration = sessionHydration(auth); - * ``` - * - * @since 0.1.0 + * The router's own `dehydrate` result is kept beside the session, so the + * app's `hydrate` gets exactly what its `dehydrate` returned. */ -export type SessionHydration = { - /** On the server: the session to send with the page. */ - dehydrate: () => DehydratedSession; - /** In the browser: starts the client from what `dehydrate` sent. */ - hydrate: (dehydrated: DehydratedSession) => void; +type Dehydrated = { sessionKit: DehydratedSession; app: unknown }; + +type SessionRouter = AuthRouter & { + options: { + context: { auth: MirrorAuth }; + dehydrate?: (() => unknown) | undefined; + hydrate?: ((dehydrated: never) => unknown) | undefined; + }; }; +const hydrated = new WeakSet(); + /** - * Router options that carry the session from the server render to the - * browser. Spread them into `createRouter`. + * Connects a TanStack Start router to the browser client in its context, as + * `auth`. Call it once in `getRouter`, after `createRouter`. + * + * It carries the session from the server render to the browser. On the + * server, the page is sent with the session {@link loadSession} read. In the + * browser, the client starts from it before the first render, without + * running guards again or telling other tabs. When the server didn't read + * the session, the browser reads it itself. * - * On the server, `dehydrate` sends the session {@link loadSession} read. In - * the browser, `hydrate` starts the client from it before the first render, - * without running guards again or telling other tabs. When the server didn't - * read the session, `hydrate` leaves the client as it is, and `loadSession` - * reads it in the browser. + * In the browser, it then does what `connectAuth` does for a TanStack Router + * app: guards run again when the session changes. It returns a function + * that stops. * - * `hydrate` throws `INVALID_OPTIONS` for a client that isn't from - * `createMirrorAuth`. + * Throws `INVALID_OPTIONS` when the router's context has no client from + * `createMirrorAuth` as `auth`. + * + * A `dehydrate` and a `hydrate` of your own keep working: yours gets back + * what yours sent. Pass them to `createRouter`. One set later, such as with + * `router.update`, replaces the session's. * * @example * ```ts * import type { MirrorAuth } from "@monarcode/session-kit"; - * import { sessionHydration } from "@monarcode/session-kit/tanstack-start"; + * import { connectSession } from "@monarcode/session-kit/tanstack-start"; * import { * createRootRouteWithContext, * createRouter, @@ -87,38 +62,61 @@ export type SessionHydration = { * export function getRouter() { * const auth = createAppAuth(); * const routeTree = createRootRouteWithContext<{ auth: typeof auth }>()(); - * return createRouter({ - * routeTree, - * context: { auth }, - * ...sessionHydration(auth), - * }); + * const router = createRouter({ routeTree, context: { auth } }); + * connectSession(router); + * return router; * } * ``` * + * @see {@link loadSession} to read the session before the guards run + * * @since 0.1.0 */ -export function sessionHydration(auth: MirrorAuth): SessionHydration { - return { - dehydrate() { +export function connectSession(router: SessionRouter): () => void { + // Read with care: JavaScript, or a router made without a context, can + // get here with no client at all. + const auth: MirrorAuth | undefined = router.options?.context?.auth; + const mirror = auth && mirrorOf(auth); + if (!mirror) + throw new AuthError( + "INVALID_OPTIONS", + "connectSession needs a createMirrorAuth client as context.auth", + ); + if (!hydrated.has(router)) { + hydrated.add(router); + const { options } = router; + const ownDehydrate = options.dehydrate; + const ownHydrate = options.hydrate; + // The router reads both options when it calls them, so they can change + // after `createRouter`. It calls them with the options as `this`. + options.dehydrate = async function dehydrate( + this: unknown, + ): Promise { + const app = await ownDehydrate?.call(this); const { sessionId, user } = auth.state.get(); return { - loaded: mirrorOf(auth)?.answered ?? false, - session: - sessionId !== null && user !== null ? { sessionId, user } : null, + sessionKit: { + loaded: mirror.answered, + session: + sessionId !== null && user !== null + ? { sessionId, user } + : null, + }, + app, }; - }, - hydrate(dehydrated) { - const mirror = mirrorOf(auth); - if (!mirror) - throw new AuthError( - "INVALID_OPTIONS", - "sessionHydration needs a client from createMirrorAuth", - ); - // The router passes `undefined` when the server sent no data, as from - // a router made without these options. - if (dehydrated?.loaded) mirror.hydrate(dehydrated.session); - }, - }; + }; + options.hydrate = function hydrate( + this: unknown, + dehydrated: Dehydrated | undefined, + ) { + // `undefined` when the server sent no data, as from a router that + // wasn't connected there. + const sent = dehydrated?.sessionKit; + if (sent?.loaded) mirror.hydrate(sent.session as Session | null); + return ownHydrate?.call(this, dehydrated?.app as never); + } as (dehydrated: never) => unknown; + } + return connectAuth(router); } /** @@ -127,7 +125,7 @@ export function sessionHydration(auth: MirrorAuth): SessionHydration { * * On the server, it calls the client's `revalidate`, so guards and the page * see the session from the cookie. In the browser, it does nothing when - * {@link sessionHydration} already brought the server's session. Otherwise, + * {@link connectSession} already brought the server's session. Otherwise, * such as for a root route that didn't render on the server, it asks the * server on each navigation until a read succeeds. * diff --git a/tests/consumer.ts b/tests/consumer.ts index 775da3f..6e97c5c 100644 --- a/tests/consumer.ts +++ b/tests/consumer.ts @@ -50,7 +50,11 @@ import { routerJar, type RouterContextLike, } from "../dist/react-router/server.js"; -import { createAuthHooks, useMirrorAuth } from "../dist/react/index.js"; +import { + createAuthHooks, + useMirrorAuth, + type UseMirrorAuthOptions, +} from "../dist/react/index.js"; import { createServerAuth, type CookieJar, @@ -62,12 +66,7 @@ import { SessionOutlet, useRouterAuth, } from "../dist/tanstack-router/index.js"; -import { - loadSession, - sessionHydration, - type DehydratedSession, - type SessionHydration, -} from "../dist/tanstack-start/index.js"; +import { connectSession, loadSession } from "../dist/tanstack-start/index.js"; import { startJar } from "../dist/tanstack-start/server.js"; const userSchema = z.object({ id: z.string(), email: z.string() }); @@ -569,11 +568,24 @@ void plainMirror.signIn; void plainMirror.lock; // TanStack Start: hydration and the request's jar. -const hydration: SessionHydration> = - sessionHydration(mirror); -const dehydrated: DehydratedSession> = - hydration.dehydrate(); -hydration.hydrate(dehydrated); +const startRoot = createRootRouteWithContext<{ auth: typeof mirror }>()({}); +const startRouter = createRouter({ + routeTree: startRoot, + context: { auth: mirror }, + // The app's own, beside the session. + dehydrate: () => ({ theme: "dark" }), + hydrate: (data: { theme: string }) => void data.theme, +}); +const disconnectSession: () => void = connectSession(startRouter); +void disconnectSession; +void connectSession( + createRouter({ + routeTree: createRootRouteWithContext<{ auth: typeof plainMirror }>()({}), + context: { auth: plainMirror }, + }), +); +// @ts-expect-error Only a mirror client holds the server's session. +connectSession(router); void loadSession(mirror); void loadSession(plainMirror); // @ts-expect-error Only a mirror client holds the server's session. @@ -593,26 +605,39 @@ void proxyJar(nextRequest, NextResponse.next()); // The mirror hook, for any server-rendering framework. declare const renderAgain: () => void; -const synced = useMirrorAuth( - (session) => +const synced = useMirrorAuth({ + create: (session) => createMirrorAuth({ name: "type-test", session, revalidate: async () => session, signOut: async () => {}, }), - initial, - renderAgain, -); + session: initial, + onChange: renderAgain, +}); const syncedUser: z.output | null = synced.state.get().user; void syncedUser; -// @ts-expect-error The client must hold the server session's user. -useMirrorAuth(() => plainMirror, initial, renderAgain); -void useMirrorAuth(() => mirror, initial, renderAgain).signIn({ - username: "emilys", +useMirrorAuth({ + // @ts-expect-error The client must hold the server session's user. + create: () => plainMirror, + session: initial, + onChange: renderAgain, }); +void useMirrorAuth({ + create: () => mirror, + session: initial, + onChange: renderAgain, +}).signIn({ username: "emilys" }); // @ts-expect-error The hook needs to know how to render on the server again. -useMirrorAuth(() => mirror, initial); +useMirrorAuth({ create: () => mirror, session: initial }); +// @ts-expect-error The options are one object. +useMirrorAuth(() => mirror, initial, renderAgain); +const mirrorOptions: UseMirrorAuthOptions< + z.output, + typeof mirror +> = { create: () => mirror, session: initial, onChange: renderAgain }; +void useMirrorAuth(mirrorOptions); // React Router: the request's jar and its middleware. declare const requestContext: RouterContextLike; diff --git a/tests/effect.test.ts b/tests/effect.test.ts index 2095151..c82dd77 100644 --- a/tests/effect.test.ts +++ b/tests/effect.test.ts @@ -284,6 +284,27 @@ test("a createMirrorAuth client is the Auth service, without updateUser", async assert.deepEqual(posted, [{ username: "alice" }]); assert.equal(session.sessionId, "s1"); + // The app's own sign-in error is a typed failure, not a defect. + const wrongPassword = new Error("Wrong password"); + const refusing = createMirrorAuth({ + name: "effect-mirror", + session: null, + revalidate: async () => null, + signIn: async (_data: { username: string }) => { + throw wrongPassword; + }, + signOut: async () => {}, + }); + const refused = await Effect.runPromise( + Effect.provide( + Effect.flip(Auth.signIn({ username: "alice" } as never)), + Auth.layer(refusing), + ), + ); + assert.ok(refused instanceof AuthFailure); + assert.equal(refused.code, "USER_VALIDATION_FAILED"); + assert.equal(refused.cause.cause, wrongPassword); + const plain = createMirrorAuth({ name: "effect-mirror", session: null, diff --git a/tests/mirror.test.ts b/tests/mirror.test.ts index 70e2069..4b8309a 100644 --- a/tests/mirror.test.ts +++ b/tests/mirror.test.ts @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { + type AuthDebugEvent, createMirrorAuth, type ClientCredentials, type MirrorAuthOptions, @@ -113,12 +114,35 @@ test("signIn forwards the input and adopts the session the server returns", asyn throw failure; }, }); + // The app's own error, unchanged, as a single-page app's sign-in form + // gets it. await assert.rejects(failing.signIn({ name: "x" }), (error: unknown) => { - assert.ok(code("USER_VALIDATION_FAILED")(error)); - assert.equal((error as Error).cause, failure); + assert.equal(error, failure); return true; }); assert.equal(failing.state.get().sessionId, "s1"); + const thrown = mirror({ + signIn: () => { + throw failure; + }, + }); + await assert.rejects(thrown.signIn({ name: "x" }), (error: unknown) => { + assert.equal(error, failure); + return true; + }); + const notASession = mirror({ + signIn: async () => ({ user }) as never, + }); + await assert.rejects( + notASession.signIn({ name: "x" }), + code("INVALID_SESSION"), + ); + const signedOut = mirror({ signIn: async () => null as never }); + await assert.rejects( + signedOut.signIn({ name: "x" }), + code("INVALID_SESSION"), + ); + assert.equal(signedOut.state.get().sessionId, "s1"); assert.equal( "signIn" in createMirrorAuth({ @@ -418,6 +442,26 @@ test("end to end: browser sign-in sealed on the server, then authFetch", async ( assert.equal(await serverAuth.getSession(jar()), null); }); +test("a sign-in the app's function refused is reported, with its message only when sensitive", async () => { + for (const sensitive of [false, true]) { + const events: AuthDebugEvent[] = []; + const auth = mirror({ + debug: { log: (event) => events.push(event), sensitive }, + signIn: async () => { + throw new Error("Wrong password"); + }, + }); + await assert.rejects(auth.signIn({ name: "x" })); + const rejected = events.find((event) => event.type === "sign-in"); + assert.equal(rejected?.message, "rejected by the signIn option"); + assert.equal(rejected?.error, undefined); + assert.deepEqual( + rejected?.data, + sensitive ? { reason: "Wrong password" } : undefined, + ); + } +}); + test("a failed sign-in leaves a revalidation in flight to apply", async () => { const answer = deferred | null>(); const auth = mirror({ diff --git a/tests/package.test.ts b/tests/package.test.ts index aa9798a..b3f3426 100644 --- a/tests/package.test.ts +++ b/tests/package.test.ts @@ -33,8 +33,8 @@ import { useRouterAuth, } from "@monarcode/session-kit/tanstack-router"; import { + connectSession, loadSession, - sessionHydration, } from "@monarcode/session-kit/tanstack-start"; import { startJar } from "@monarcode/session-kit/tanstack-start/server"; @@ -49,7 +49,7 @@ test("all public entry points import without browser globals", () => { webStorage, createServerAuth, loadSession, - sessionHydration, + connectSession, startJar, nextJar, proxyJar, diff --git a/tests/server-session-hooks.test.ts b/tests/server-session-hooks.test.ts index 626b4ce..cb6f734 100644 --- a/tests/server-session-hooks.test.ts +++ b/tests/server-session-hooks.test.ts @@ -10,7 +10,7 @@ import { } from "@monarcode/session-kit"; import { act, render, settle, useDom } from "./dom.ts"; -import { deferred, user } from "./helpers.ts"; +import { code, deferred, user } from "./helpers.ts"; type User = typeof user; @@ -73,12 +73,12 @@ const mountNext: Mount = async (name, initial, revalidate) => { function Providers() { const [session, setSession] = useState(initial); rendered = setSession; - client = react.useMirrorAuth( - createClient(name, () => counts.created++, revalidate), + client = react.useMirrorAuth({ + create: createClient(name, () => counts.created++, revalidate), session, // A new function each render, as apps write it. - () => counts.refreshes++, - ); + onChange: () => counts.refreshes++, + }); return null; } await render(h(Providers)); @@ -104,11 +104,11 @@ const mountReactRouter: Mount = async (name, initial, revalidate) => { session: Session | null; }; const { revalidate: load } = router.useRevalidator(); - client = react.useMirrorAuth( - createClient(name, () => counts.created++, revalidate), + client = react.useMirrorAuth({ + create: createClient(name, () => counts.created++, revalidate), session, - load, - ); + onChange: load, + }); return null; } const memory = router.createMemoryRouter([ @@ -230,3 +230,22 @@ for (const [framework, mount] of [ } }); } + +test("useMirrorAuth throws INVALID_OPTIONS without its options object", () => { + const create = (session: Session | null) => + createMirrorAuth({ + name: "hook-options", + session, + revalidate: async () => null, + signOut: async () => {}, + }); + // The form before 0.1.0-rc.0: three arguments. + assert.throws( + () => react.useMirrorAuth(create as never), + code("INVALID_OPTIONS"), + ); + assert.throws( + () => react.useMirrorAuth({ create, session: null } as never), + code("INVALID_OPTIONS"), + ); +}); diff --git a/tests/tanstack-start.test.ts b/tests/tanstack-start.test.ts index a661aa1..79c24cd 100644 --- a/tests/tanstack-start.test.ts +++ b/tests/tanstack-start.test.ts @@ -5,12 +5,13 @@ import { createAuth, createMirrorAuth, memoryStorage, + type MirrorAuth, type Session, } from "@monarcode/session-kit"; import { createServerAuth } from "@monarcode/session-kit/server"; import { + connectSession, loadSession, - sessionHydration, } from "@monarcode/session-kit/tanstack-start"; import { startJar } from "@monarcode/session-kit/tanstack-start/server"; import { @@ -121,7 +122,47 @@ test("startJar sets and deletes every chunk of a large session", async () => { ); }); -test("sessionHydration carries the session without running guards again", async (t) => { +/** The app's own data, beside the session, as TanStack Query's would be. */ +type Own = { theme: string }; + +/** + * A router as Start's `getRouter` makes it, connected, with the calls Start + * makes to send its data with the page and to read it in the browser. + */ +async function startRouter( + t: TestContext, + auth: MirrorAuth, + isServer: boolean, + own: Partial<{ + dehydrate: () => Own; + hydrate: (data: Own) => void; + }> = {}, +) { + const { createRouter, createRootRouteWithContext, createMemoryHistory } = + await import("@tanstack/react-router"); + const router = createRouter({ + routeTree: createRootRouteWithContext<{ auth: MirrorAuth }>()(), + context: { auth }, + history: createMemoryHistory(), + origin: "https://app.test", + isServer, + ...own, + }); + t.after(connectSession(router)); + const { options } = router; + return { + router, + dehydrate: async () => options.dehydrate?.call(options), + // A copy, as the page carries it. + hydrate: async (data: unknown) => + (options.hydrate as ((data: unknown) => unknown) | undefined)?.call( + options, + structuredClone(data), + ), + }; +} + +test("connectSession carries the session without running guards again", async (t) => { const reads: string[] = []; const otherTab = createMirrorAuth({ name: "hydration", @@ -135,32 +176,82 @@ test("sessionHydration carries the session without running guards again", async t.after(otherTab.mount()); const server = createMirrorAuth({ ...options(), session: null }); + const page = await startRouter(t, server, true); await loadSession(server); - const dehydrated = sessionHydration(server).dehydrate(); - assert.deepEqual(dehydrated, { loaded: true, session: alice }); + const sent = await page.dehydrate(); + // The page carries the session and nothing else: no tokens. + assert.deepEqual(sent, { + sessionKit: { loaded: true, session: alice }, + app: undefined, + }); const browser = createMirrorAuth({ ...options(), session: null }); const before = browser.state.get().version; - sessionHydration(browser).hydrate(structuredClone(dehydrated)); + await (await startRouter(t, browser, false)).hydrate(sent); assert.equal(browser.state.get().status, "authenticated"); assert.deepEqual(browser.state.get().user, user); assert.equal(browser.state.get().version, before); await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setImmediate(resolve)); assert.deepEqual(reads, []); +}); + +test("connectSession keeps the router's own dehydrate and hydrate", async (t) => { + const server = createMirrorAuth({ ...options(), session: null }); + const page = await startRouter(t, server, true, { + dehydrate: () => ({ theme: "dark" }), + }); + await loadSession(server); + const sent = await page.dehydrate(); + assert.deepEqual(sent, { + sessionKit: { loaded: true, session: alice }, + app: { theme: "dark" }, + }); + + const received: Own[] = []; + const browser = createMirrorAuth({ ...options(), session: null }); + const app = await startRouter(t, browser, false, { + hydrate: (data) => received.push(data), + }); + await app.hydrate(sent); + assert.deepEqual(received, [{ theme: "dark" }]); + assert.equal(browser.state.get().sessionId, "s1"); + // Connecting again neither wraps the options twice nor connects twice. + const disconnect = connectSession(app.router); + assert.equal(connectSession(app.router), disconnect); + await app.hydrate(sent); + assert.deepEqual(received, [{ theme: "dark" }, { theme: "dark" }]); +}); + +test("connectSession throws INVALID_OPTIONS without a browser client of a server-rendered app", async (t) => { + const { createRouter, createRootRouteWithContext } = + await import("@tanstack/react-router"); const client = createAuth({ name: "hydration", user: userSchema, storage: memoryStorage(), }); - for (const loaded of [true, false]) - assert.throws( - () => - // @ts-expect-error The types refuse it too, but JavaScript doesn't. - sessionHydration(client).hydrate({ loaded, session: null }), - code("INVALID_OPTIONS"), - ); + const router = createRouter({ + routeTree: createRootRouteWithContext<{ auth: typeof client }>()(), + context: { auth: client }, + isServer: true, + }); + // @ts-expect-error The types refuse it too, but JavaScript doesn't. + assert.throws(() => connectSession(router), code("INVALID_OPTIONS")); + // Nothing was changed. + assert.equal(router.options.dehydrate, undefined); + + const withoutContext = createRouter({ + routeTree: createRootRouteWithContext()(), + isServer: true, + }); + assert.throws( + // @ts-expect-error No context, so no client. + () => connectSession(withoutContext), + code("INVALID_OPTIONS"), + ); + void t; }); function options() { @@ -196,25 +287,37 @@ test("the browser reads a session the server didn't load", async (t) => { }, }); const failed = make(); + const failedPage = await startRouter(t, failed, true); await assert.rejects(loadSession(failed)); const skipped = make(); - for (const server of [failed, skipped]) - assert.deepEqual(sessionHydration(server).dehydrate(), { - loaded: false, - session: null, - }); + const skippedPage = await startRouter(t, skipped, true); + const sent = await failedPage.dehydrate(); + assert.deepEqual(sent, { + sessionKit: { loaded: false, session: null }, + app: undefined, + }); + for (const page of [failedPage, skippedPage]) + assert.deepEqual(await page.dehydrate(), sent); + // Made before `document` exists: the router reads more of the browser's + // globals when it does. + const browser = make(); + const browserPage = await startRouter(t, browser, false); + const nothing = make(); + const nothingPage = await startRouter(t, nothing, false); inBrowser(t); down = false; - const browser = make(); - sessionHydration(browser).hydrate( - structuredClone(sessionHydration(failed).dehydrate()), - ); + await browserPage.hydrate(sent); assert.equal(browser.state.get().sessionId, null); await loadSession(browser); await loadSession(browser); assert.equal(reads, 2); assert.equal(browser.state.get().sessionId, "s1"); + + // Nothing sent at all, as from a root route that didn't render on the + // server: the client is left as it is. + await nothingPage.hydrate(undefined); + assert.equal(nothing.state.get().sessionId, null); }); test("loadSession reads on the server every time, in the browser only without hydration", async (t) => { @@ -234,9 +337,13 @@ test("loadSession reads on the server every time, in the browser only without hy assert.equal(reads, 2); assert.equal(server.state.get().sessionId, "s1"); - inBrowser(t); + const page = await startRouter(t, server, true); + const sent = await page.dehydrate(); + const hydrated = make(); - sessionHydration(hydrated).hydrate({ loaded: true, session: alice }); + const hydratedPage = await startRouter(t, hydrated, false); + inBrowser(t); + await hydratedPage.hydrate(sent); await loadSession(hydrated); assert.equal(reads, 2); From 1dd9ba84c52336ce474ad5b2774e10d3c9ca9fbe Mon Sep 17 00:00:00 2001 From: monarcode Date: Fri, 13 Nov 2026 21:56:38 +0100 Subject: [PATCH 03/26] feat!: hooks without a hooks file, typed by one Register in the main entry point --- CHANGELOG.md | 50 ++++++ examples/expo-router/app/(app)/index.tsx | 3 +- examples/expo-router/app/_layout.tsx | 11 +- examples/expo-router/src/auth.ts | 4 - examples/next-app/app/hooks.ts | 6 - examples/next-app/app/providers.tsx | 17 +- examples/next-app/app/ui.tsx | 2 +- examples/react-router-data/src/hooks.ts | 6 - examples/react-router-data/src/main.tsx | 10 +- examples/react-router-data/src/ui.tsx | 3 +- .../react-router-declarative/src/hooks.ts | 6 - .../react-router-declarative/src/main.tsx | 10 +- examples/react-router-declarative/src/ui.tsx | 3 +- .../react-router-framework-spa/app/hooks.ts | 6 - .../react-router-framework-spa/app/root.tsx | 10 +- .../react-router-framework-spa/app/ui.tsx | 3 +- .../react-router-framework-ssr/app/hooks.ts | 6 - .../react-router-framework-ssr/app/root.tsx | 13 +- .../react-router-framework-ssr/app/ui.tsx | 2 +- examples/tanstack-router/src/hooks.ts | 7 - examples/tanstack-router/src/ui.tsx | 3 +- .../tanstack-start-spa-effetch/src/auth.ts | 2 +- .../tanstack-start-spa-effetch/src/hooks.ts | 7 - .../src/routes/__root.tsx | 2 +- .../tanstack-start-spa-effetch/src/ui.tsx | 2 +- examples/tanstack-start-spa/src/hooks.ts | 7 - examples/tanstack-start-spa/src/ui.tsx | 3 +- examples/tanstack-start-ssr/src/hooks.ts | 7 - examples/tanstack-start-ssr/src/ui.tsx | 2 +- package.json | 2 +- scripts/docs-pages.mjs | 8 +- site/content/docs/(latest)/effect.mdx | 13 +- .../content/docs/(latest)/getting-started.mdx | 29 ++-- site/content/docs/(latest)/reference/core.mdx | 8 + .../docs/(latest)/reference/effect.mdx | 10 +- .../content/docs/(latest)/reference/index.mdx | 4 +- .../content/docs/(latest)/reference/react.mdx | 20 ++- .../(latest)/reference/tanstack-router.mdx | 16 +- site/content/docs/(latest)/setups/expo.mdx | 29 ++-- site/content/docs/(latest)/setups/next.mdx | 32 ++-- .../docs/(latest)/setups/react-router-ssr.mdx | 29 ++-- .../docs/(latest)/setups/react-router.mdx | 43 +++-- .../docs/(latest)/setups/tanstack-router.mdx | 47 ++---- .../docs/(latest)/setups/tanstack-start.mdx | 8 +- site/src/lib/tour.ts | 4 +- src/core/register.ts | 68 ++++++++ src/effect/auth.ts | 86 +--------- src/effect/index.ts | 2 - src/index.ts | 1 + src/react/hooks.ts | 153 ++++++++++++++++-- src/react/index.ts | 8 +- src/tanstack-router/index.ts | 110 ++++++++++--- tests/consumer-mirror.ts | 10 +- tests/consumer-unregistered.ts | 56 +++++++ tests/consumer.ts | 41 ++++- tests/examples.test.ts | 15 +- tests/package.test.ts | 21 ++- tests/react.test.ts | 99 +++++++----- tests/tsconfig.unregistered.bundler.json | 4 + tests/tsconfig.unregistered.json | 4 + 60 files changed, 794 insertions(+), 399 deletions(-) delete mode 100644 examples/next-app/app/hooks.ts delete mode 100644 examples/react-router-data/src/hooks.ts delete mode 100644 examples/react-router-declarative/src/hooks.ts delete mode 100644 examples/react-router-framework-spa/app/hooks.ts delete mode 100644 examples/react-router-framework-ssr/app/hooks.ts delete mode 100644 examples/tanstack-router/src/hooks.ts delete mode 100644 examples/tanstack-start-spa-effetch/src/hooks.ts delete mode 100644 examples/tanstack-start-spa/src/hooks.ts delete mode 100644 examples/tanstack-start-ssr/src/hooks.ts create mode 100644 src/core/register.ts create mode 100644 tests/consumer-unregistered.ts create mode 100644 tests/tsconfig.unregistered.bundler.json create mode 100644 tests/tsconfig.unregistered.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 756bc58..e8fde21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,25 @@ replaces the ky recipe built on hooks, and keeps the axios interceptors for an instance on axios's default adapter. - `UseMirrorAuthOptions`, the type of `useMirrorAuth`'s options. +- Hooks without a hooks file. `@monarcode/session-kit/react` exports + `AuthProvider`, `useAuth` and `useAuthClient`, typed by the client you + register once in `Register`, from `@monarcode/session-kit`. Until you + register one, `AuthProvider` takes any client, and the user is `unknown`. + `ProvidedAuth` names the client they use. + `createAuthHooks` stays, for an app with several clients. + + ```ts + declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } + } + ``` + +- `@monarcode/session-kit/tanstack-router` exports `useAuth` and + `useAuthClient`, which read the client from Router context and are typed + by the Router you register. They need no `AuthProvider` and no + registration of their own. ### Changed @@ -84,6 +103,37 @@ connectSession(router); ``` +- **Breaking:** `Register` and `RegisteredAuth` moved from + `@monarcode/session-kit/effect` to `@monarcode/session-kit`, so one + registration types the hooks and the Effect service. Change the module you + augment. The other `Registered…` types stay in `./effect`. Register a + client from `createAuth` or `createMirrorAuth`: anything else now types the + hooks and the Effect service as `never`, where the Effect service used to + fall back to an `unknown` user. + + ```ts + // Before + declare module "@monarcode/session-kit/effect" { + interface Register { + auth: typeof auth; + } + } + // After + declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } + } + ``` + +- **Breaking:** in `@monarcode/session-kit/tanstack-router`, `useRouterAuth` + is now `useAuthClient`, and `RegisteredAuth` is now `RouterAuth`, so it + isn't confused with the main entry point's. When `auth` is optional in + Router context, `useAuthClient` returns the client without `undefined`, as + it throws when there's none. A hooks file made with + `createAuthHooks({ useClient: useRouterAuth })` can go: import `useAuth` + and `useAuthClient` from `@monarcode/session-kit/tanstack-router` instead. + - The guides moved to the documentation site, [session-kit.pages.dev](https://session-kit.pages.dev), with an API reference for every entry point and every error code. The README is now a diff --git a/examples/expo-router/app/(app)/index.tsx b/examples/expo-router/app/(app)/index.tsx index 8a51498..a3caeaa 100644 --- a/examples/expo-router/app/(app)/index.tsx +++ b/examples/expo-router/app/(app)/index.tsx @@ -1,9 +1,8 @@ import { Button, Text, View } from "react-native"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; import { Link } from "expo-router"; -import { useAuth, useAuthClient } from "../../src/auth"; - export default function Home() { const firstName = useAuth((state) => state.user?.firstName); const auth = useAuthClient(); diff --git a/examples/expo-router/app/_layout.tsx b/examples/expo-router/app/_layout.tsx index 4ac89dd..e3456e0 100644 --- a/examples/expo-router/app/_layout.tsx +++ b/examples/expo-router/app/_layout.tsx @@ -1,9 +1,18 @@ import { SessionGate } from "@monarcode/session-kit/expo"; +import { AuthProvider, useAuth } from "@monarcode/session-kit/react"; import { SplashScreen, Stack } from "expo-router"; -import { auth, AuthProvider, useAuth } from "../src/auth"; +import { auth } from "../src/auth"; import { Unavailable } from "../src/unavailable"; +// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` +// with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + // Keeps the splash screen up until SessionGate hides it. void SplashScreen.preventAutoHideAsync(); diff --git a/examples/expo-router/src/auth.ts b/examples/expo-router/src/auth.ts index dca97ff..da6a18d 100644 --- a/examples/expo-router/src/auth.ts +++ b/examples/expo-router/src/auth.ts @@ -1,7 +1,6 @@ import { createAuth } from "@monarcode/session-kit"; import { secureStorage } from "@monarcode/session-kit/expo"; import { createAuthFetch } from "@monarcode/session-kit/http"; -import { createAuthHooks } from "@monarcode/session-kit/react"; import { z } from "zod"; /** DummyJSON's auth API: https://dummyjson.com/docs/auth */ @@ -55,9 +54,6 @@ export const auth = createAuth({ }, }); -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); - /** * Sends requests to DummyJSON with the access token. After a 401 it * refreshes, then replays a GET or HEAD once. diff --git a/examples/next-app/app/hooks.ts b/examples/next-app/app/hooks.ts deleted file mode 100644 index ad697b9..0000000 --- a/examples/next-app/app/hooks.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { AppAuth } from "../lib/auth/client"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); diff --git a/examples/next-app/app/providers.tsx b/examples/next-app/app/providers.tsx index 5354a0f..2e7aaca 100644 --- a/examples/next-app/app/providers.tsx +++ b/examples/next-app/app/providers.tsx @@ -2,11 +2,22 @@ import type { ReactNode } from "react"; -import { useMirrorAuth } from "@monarcode/session-kit/react"; +import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react"; import { useRouter } from "next/navigation"; -import { createAppAuth, type AppSession } from "../lib/auth/client"; -import { AuthProvider } from "./hooks"; +import { + createAppAuth, + type AppAuth, + type AppSession, +} from "../lib/auth/client"; + +// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` +// with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: AppAuth; + } +} /** * Gives Client Components the session the layout read. `useMirrorAuth` diff --git a/examples/next-app/app/ui.tsx b/examples/next-app/app/ui.tsx index 38285d3..2293fb4 100644 --- a/examples/next-app/app/ui.tsx +++ b/examples/next-app/app/ui.tsx @@ -3,9 +3,9 @@ import { useMemo, useState, type FormEvent } from "react"; import { createAuthFetch } from "@monarcode/session-kit/http"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; import { API } from "../lib/auth/api"; -import { useAuth, useAuthClient } from "./hooks"; /** * The sign-in form, prefilled with DummyJSON's documented test user. Once diff --git a/examples/react-router-data/src/hooks.ts b/examples/react-router-data/src/hooks.ts deleted file mode 100644 index 615afc3..0000000 --- a/examples/react-router-data/src/hooks.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { auth } from "./auth"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); diff --git a/examples/react-router-data/src/main.tsx b/examples/react-router-data/src/main.tsx index 629d8e5..56f058f 100644 --- a/examples/react-router-data/src/main.tsx +++ b/examples/react-router-data/src/main.tsx @@ -9,6 +9,7 @@ import { } from "react-router"; import { safeReturnTo } from "@monarcode/session-kit"; +import { AuthProvider } from "@monarcode/session-kit/react"; import { redirectIfSignedIn, requireSession, @@ -18,9 +19,16 @@ import { import { createRoot } from "react-dom/client"; import { auth } from "./auth"; -import { AuthProvider } from "./hooks"; import { LoginForm, Pending, Profile, Unavailable } from "./ui"; +// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` +// with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + /** * Re-runs the guards in loaders after a sign-in, sign-out, account switch, * profile update, or a refresh that fails once access has expired. Token diff --git a/examples/react-router-data/src/ui.tsx b/examples/react-router-data/src/ui.tsx index c368f48..efbfc75 100644 --- a/examples/react-router-data/src/ui.tsx +++ b/examples/react-router-data/src/ui.tsx @@ -1,7 +1,8 @@ import { useState, type FormEvent } from "react"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; + import { authFetch, signInWithPassword } from "./auth"; -import { useAuth, useAuthClient } from "./hooks"; /** The sign-in form, prefilled with DummyJSON's documented test user. */ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { diff --git a/examples/react-router-declarative/src/hooks.ts b/examples/react-router-declarative/src/hooks.ts deleted file mode 100644 index 615afc3..0000000 --- a/examples/react-router-declarative/src/hooks.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { auth } from "./auth"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); diff --git a/examples/react-router-declarative/src/main.tsx b/examples/react-router-declarative/src/main.tsx index de5e719..218c58e 100644 --- a/examples/react-router-declarative/src/main.tsx +++ b/examples/react-router-declarative/src/main.tsx @@ -8,13 +8,21 @@ import { } from "react-router"; import { safeReturnTo } from "@monarcode/session-kit"; +import { AuthProvider, useAuth } from "@monarcode/session-kit/react"; import { SessionOutlet } from "@monarcode/session-kit/react-router"; import { createRoot } from "react-dom/client"; import { auth } from "./auth"; -import { AuthProvider, useAuth } from "./hooks"; import { LoginForm, Pending, Profile, Unavailable } from "./ui"; +// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` +// with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + /** * Doesn't navigate after `signIn`: the state change re-renders this page, * which then redirects. diff --git a/examples/react-router-declarative/src/ui.tsx b/examples/react-router-declarative/src/ui.tsx index c368f48..efbfc75 100644 --- a/examples/react-router-declarative/src/ui.tsx +++ b/examples/react-router-declarative/src/ui.tsx @@ -1,7 +1,8 @@ import { useState, type FormEvent } from "react"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; + import { authFetch, signInWithPassword } from "./auth"; -import { useAuth, useAuthClient } from "./hooks"; /** The sign-in form, prefilled with DummyJSON's documented test user. */ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { diff --git a/examples/react-router-framework-spa/app/hooks.ts b/examples/react-router-framework-spa/app/hooks.ts deleted file mode 100644 index 615afc3..0000000 --- a/examples/react-router-framework-spa/app/hooks.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { auth } from "./auth"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); diff --git a/examples/react-router-framework-spa/app/root.tsx b/examples/react-router-framework-spa/app/root.tsx index 5aaf93d..cd0b337 100644 --- a/examples/react-router-framework-spa/app/root.tsx +++ b/examples/react-router-framework-spa/app/root.tsx @@ -1,12 +1,20 @@ import type { ReactNode } from "react"; import { Links, Meta, Outlet, Scripts, ScrollRestoration } from "react-router"; +import { AuthProvider } from "@monarcode/session-kit/react"; import { useAuthRevalidation } from "@monarcode/session-kit/react-router"; import { auth } from "./auth"; -import { AuthProvider } from "./hooks"; import { Pending } from "./ui"; +// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` +// with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + export function Layout({ children }: { children: ReactNode }) { return ( diff --git a/examples/react-router-framework-spa/app/ui.tsx b/examples/react-router-framework-spa/app/ui.tsx index c368f48..efbfc75 100644 --- a/examples/react-router-framework-spa/app/ui.tsx +++ b/examples/react-router-framework-spa/app/ui.tsx @@ -1,7 +1,8 @@ import { useState, type FormEvent } from "react"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; + import { authFetch, signInWithPassword } from "./auth"; -import { useAuth, useAuthClient } from "./hooks"; /** The sign-in form, prefilled with DummyJSON's documented test user. */ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { diff --git a/examples/react-router-framework-ssr/app/hooks.ts b/examples/react-router-framework-ssr/app/hooks.ts deleted file mode 100644 index 7a7c0b9..0000000 --- a/examples/react-router-framework-ssr/app/hooks.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { AppAuth } from "./auth/client"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); diff --git a/examples/react-router-framework-ssr/app/root.tsx b/examples/react-router-framework-ssr/app/root.tsx index e41ffa0..577e6aa 100644 --- a/examples/react-router-framework-ssr/app/root.tsx +++ b/examples/react-router-framework-ssr/app/root.tsx @@ -11,13 +11,20 @@ import { type LoaderFunctionArgs, } from "react-router"; -import { useMirrorAuth } from "@monarcode/session-kit/react"; +import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react"; import { routerJar } from "@monarcode/session-kit/react-router/server"; -import { createAppAuth } from "./auth/client"; +import { createAppAuth, type AppAuth } from "./auth/client"; import { sessionMiddleware } from "./auth/middleware.server"; import { serverAuth } from "./auth/session.server"; -import { AuthProvider } from "./hooks"; + +// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` +// with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: AppAuth; + } +} export const middleware = sessionMiddleware; diff --git a/examples/react-router-framework-ssr/app/ui.tsx b/examples/react-router-framework-ssr/app/ui.tsx index eef2fff..bac0ceb 100644 --- a/examples/react-router-framework-ssr/app/ui.tsx +++ b/examples/react-router-framework-ssr/app/ui.tsx @@ -2,9 +2,9 @@ import { useMemo, useState } from "react"; import { Form } from "react-router"; import { createAuthFetch } from "@monarcode/session-kit/http"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; import { API } from "./auth/api"; -import { useAuth, useAuthClient } from "./hooks"; /** * The sign-in form, prefilled with DummyJSON's documented test user. It diff --git a/examples/tanstack-router/src/hooks.ts b/examples/tanstack-router/src/hooks.ts deleted file mode 100644 index a6294ae..0000000 --- a/examples/tanstack-router/src/hooks.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; -import { useRouterAuth } from "@monarcode/session-kit/tanstack-router"; - -// Reads the client from Router context, so no provider is needed. -export const { useAuth, useAuthClient } = createAuthHooks({ - useClient: useRouterAuth, -}); diff --git a/examples/tanstack-router/src/ui.tsx b/examples/tanstack-router/src/ui.tsx index c368f48..7d5cd77 100644 --- a/examples/tanstack-router/src/ui.tsx +++ b/examples/tanstack-router/src/ui.tsx @@ -1,7 +1,8 @@ import { useState, type FormEvent } from "react"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/tanstack-router"; + import { authFetch, signInWithPassword } from "./auth"; -import { useAuth, useAuthClient } from "./hooks"; /** The sign-in form, prefilled with DummyJSON's documented test user. */ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { diff --git a/examples/tanstack-start-spa-effetch/src/auth.ts b/examples/tanstack-start-spa-effetch/src/auth.ts index 1bc6a65..a902523 100644 --- a/examples/tanstack-start-spa-effetch/src/auth.ts +++ b/examples/tanstack-start-spa-effetch/src/auth.ts @@ -70,7 +70,7 @@ export const auth = createAuth({ }); // Registered once, so every `Auth` Effect is typed with this client's user. -declare module "@monarcode/session-kit/effect" { +declare module "@monarcode/session-kit" { interface Register { auth: typeof auth; } diff --git a/examples/tanstack-start-spa-effetch/src/hooks.ts b/examples/tanstack-start-spa-effetch/src/hooks.ts deleted file mode 100644 index a6294ae..0000000 --- a/examples/tanstack-start-spa-effetch/src/hooks.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; -import { useRouterAuth } from "@monarcode/session-kit/tanstack-router"; - -// Reads the client from Router context, so no provider is needed. -export const { useAuth, useAuthClient } = createAuthHooks({ - useClient: useRouterAuth, -}); diff --git a/examples/tanstack-start-spa-effetch/src/routes/__root.tsx b/examples/tanstack-start-spa-effetch/src/routes/__root.tsx index 41ed42d..6d63c44 100644 --- a/examples/tanstack-start-spa-effetch/src/routes/__root.tsx +++ b/examples/tanstack-start-spa-effetch/src/routes/__root.tsx @@ -2,6 +2,7 @@ import type { ReactNode } from "react"; import { QueryProvider } from "@monarcode/effetch-query/react"; +import { useAuth } from "@monarcode/session-kit/tanstack-router"; import { createRootRouteWithContext, HeadContent, @@ -10,7 +11,6 @@ import { } from "@tanstack/react-router"; import type { auth } from "../auth"; -import { useAuth } from "../hooks"; import { makeQueryClient } from "../query"; export const Route = createRootRouteWithContext<{ auth: typeof auth }>()({ diff --git a/examples/tanstack-start-spa-effetch/src/ui.tsx b/examples/tanstack-start-spa-effetch/src/ui.tsx index 07b81d5..a24a830 100644 --- a/examples/tanstack-start-spa-effetch/src/ui.tsx +++ b/examples/tanstack-start-spa-effetch/src/ui.tsx @@ -1,13 +1,13 @@ import { useState, type FormEvent } from "react"; import { useMutation, useQuery } from "@monarcode/effetch-query/react"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/tanstack-router"; import * as Exit from "effect/Exit"; import * as AsyncResult from "effect/reactivity/AsyncResult"; import { expiresInMins } from "./auth"; import { profileQuery, signInMutation } from "./endpoints"; import { apiErrorMessage } from "./error-message"; -import { useAuth, useAuthClient } from "./hooks"; /** The sign-in form, prefilled with DummyJSON's documented test user. */ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { diff --git a/examples/tanstack-start-spa/src/hooks.ts b/examples/tanstack-start-spa/src/hooks.ts deleted file mode 100644 index a6294ae..0000000 --- a/examples/tanstack-start-spa/src/hooks.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; -import { useRouterAuth } from "@monarcode/session-kit/tanstack-router"; - -// Reads the client from Router context, so no provider is needed. -export const { useAuth, useAuthClient } = createAuthHooks({ - useClient: useRouterAuth, -}); diff --git a/examples/tanstack-start-spa/src/ui.tsx b/examples/tanstack-start-spa/src/ui.tsx index c368f48..7d5cd77 100644 --- a/examples/tanstack-start-spa/src/ui.tsx +++ b/examples/tanstack-start-spa/src/ui.tsx @@ -1,7 +1,8 @@ import { useState, type FormEvent } from "react"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/tanstack-router"; + import { authFetch, signInWithPassword } from "./auth"; -import { useAuth, useAuthClient } from "./hooks"; /** The sign-in form, prefilled with DummyJSON's documented test user. */ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { diff --git a/examples/tanstack-start-ssr/src/hooks.ts b/examples/tanstack-start-ssr/src/hooks.ts deleted file mode 100644 index a6294ae..0000000 --- a/examples/tanstack-start-ssr/src/hooks.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; -import { useRouterAuth } from "@monarcode/session-kit/tanstack-router"; - -// Reads the client from Router context, so no provider is needed. -export const { useAuth, useAuthClient } = createAuthHooks({ - useClient: useRouterAuth, -}); diff --git a/examples/tanstack-start-ssr/src/ui.tsx b/examples/tanstack-start-ssr/src/ui.tsx index 2620cc2..6a4297f 100644 --- a/examples/tanstack-start-ssr/src/ui.tsx +++ b/examples/tanstack-start-ssr/src/ui.tsx @@ -1,10 +1,10 @@ import { useMemo, useState, type FormEvent } from "react"; import { createAuthFetch } from "@monarcode/session-kit/http"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/tanstack-router"; import { useRouter } from "@tanstack/react-router"; import { API } from "./auth/api"; -import { useAuth, useAuthClient } from "./hooks"; /** The sign-in form, prefilled with DummyJSON's documented test user. */ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { diff --git a/package.json b/package.json index 0aa96ea..0e677f6 100644 --- a/package.json +++ b/package.json @@ -111,7 +111,7 @@ "test": "pnpm run test:sync && pnpm run test:async", "test:sync": "node --conditions=development --test tests/*.test.ts", "test:async": "node --env-file=tests/async-storage.env --conditions=development --test tests/*.test.ts", - "test:types": "tsc -p tests/tsconfig.tests.json && tsc -p tests/tsconfig.json && tsc -p tests/tsconfig.bundler.json && tsc -p tests/tsconfig.json --exactOptionalPropertyTypes false && tsc -p tests/tsconfig.mirror.json && tsc -p tests/tsconfig.mirror.bundler.json && tsc -p tests/tsconfig.mirror.json --exactOptionalPropertyTypes false && pnpm run test:docs", + "test:types": "tsc -p tests/tsconfig.tests.json && tsc -p tests/tsconfig.json && tsc -p tests/tsconfig.bundler.json && tsc -p tests/tsconfig.json --exactOptionalPropertyTypes false && tsc -p tests/tsconfig.mirror.json && tsc -p tests/tsconfig.mirror.bundler.json && tsc -p tests/tsconfig.mirror.json --exactOptionalPropertyTypes false && tsc -p tests/tsconfig.unregistered.json && tsc -p tests/tsconfig.unregistered.bundler.json && tsc -p tests/tsconfig.unregistered.json --exactOptionalPropertyTypes false && pnpm run test:docs", "test:docs": "node scripts/check-docs.mjs", "docs:reference": "node scripts/reference-docs.mjs && oxfmt --write \"site/content/docs/(latest)/reference\"", "check": "pnpm run lint && pnpm run format:check && pnpm run build && pnpm test && pnpm run test:types", diff --git a/scripts/docs-pages.mjs b/scripts/docs-pages.mjs index 456faf2..63a9885 100644 --- a/scripts/docs-pages.mjs +++ b/scripts/docs-pages.mjs @@ -155,7 +155,6 @@ const GETTING_STARTED = { "src/backend.ts", "src/auth.ts", "src/sign-in.tsx", - "src/hooks.ts", "src/app.tsx", "src/api.ts", ], @@ -202,12 +201,7 @@ export const documents = [ fixtures: {}, shared: { from: page("getting-started"), - files: [ - "src/backend.ts", - "src/auth.ts", - "src/hooks.ts", - "src/sign-in.tsx", - ], + files: ["src/backend.ts", "src/auth.ts", "src/sign-in.tsx"], // Framework mode keeps its code in `app`. directories: ["src", "app"], }, diff --git a/site/content/docs/(latest)/effect.mdx b/site/content/docs/(latest)/effect.mdx index d69c353..415820a 100644 --- a/site/content/docs/(latest)/effect.mdx +++ b/site/content/docs/(latest)/effect.mdx @@ -136,11 +136,11 @@ export const refreshSession = (refreshToken: string, signal: AbortSignal) => ## 3. Register the client Create the client as usual, then register its type once, so every Effect -carries your user: +carries your user. The same registration types the hooks from +`@monarcode/session-kit/react`: ```ts title="src/auth.ts" import { createAuth, webStorage } from "@monarcode/session-kit"; -import { createAuthHooks } from "@monarcode/session-kit/react"; import { userSchema } from "./backend.js"; import { refreshSession } from "./refresh.js"; @@ -152,10 +152,7 @@ export const auth = createAuth({ refresh: ({ refreshToken, signal }) => refreshSession(refreshToken, signal), }); -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); - -declare module "@monarcode/session-kit/effect" { +declare module "@monarcode/session-kit" { interface Register { auth: typeof auth; } @@ -405,8 +402,8 @@ and its requests in flight, and renders the tree with a new one: import type { ReactNode } from "react"; import { QueryProvider } from "@monarcode/effetch-query/react"; +import { useAuth } from "@monarcode/session-kit/react"; -import { useAuth } from "./auth.js"; import { makeQueryClient } from "./query.js"; export function Queries({ children }: { children: ReactNode }) { @@ -432,10 +429,10 @@ queries and mutations made of them: ```tsx title="src/features/account.tsx" import * as Fetch from "@monarcode/effetch"; import { useMutation, useQuery } from "@monarcode/effetch-query/react"; +import { useAuthClient } from "@monarcode/session-kit/react"; import * as AsyncResult from "effect/reactivity/AsyncResult"; import * as Schema from "effect/Schema"; -import { useAuthClient } from "../auth.js"; import { SessionUser, SignInResponse } from "../backend.js"; import { api } from "../query.js"; diff --git a/site/content/docs/(latest)/getting-started.mdx b/site/content/docs/(latest)/getting-started.mdx index 224f3b9..6e7a79b 100644 --- a/site/content/docs/(latest)/getting-started.mdx +++ b/site/content/docs/(latest)/getting-started.mdx @@ -179,27 +179,30 @@ routers, which use it to send the user on to the page they asked for. ## 4. Read the session in React -Create the hooks once, typed by your client, and export them for every -component to share: - -```ts title="src/hooks.ts" -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { auth } from "./auth.js"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); -``` +The hooks come from `@monarcode/session-kit/react`. Register your client's +type once, where you render `AuthProvider`, and they carry your user. Then render by `status`. Each case is one of the states in [How it works](/docs#how-it-works). By the last case, TypeScript has narrowed `user` to a value that's set: ```tsx title="src/app.tsx" +import { + AuthProvider, + useAuth, + useAuthClient, +} from "@monarcode/session-kit/react"; + import { auth } from "./auth.js"; -import { AuthProvider, useAuth, useAuthClient } from "./hooks.js"; import { SignIn } from "./sign-in.js"; +// Types `AuthProvider` and the hooks with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + export function App() { return ( @@ -250,6 +253,8 @@ function AuthError() { - `useAuth()` returns the whole state. `useAuth(selector)` returns a part of it, and re-renders only when that part changes, as `AuthError` does. - `useAuthClient()` returns the client, for actions. +- With more than one client in an app, create hooks for each with + `createAuthHooks()` instead. - `retry` and `signOut` reject when they fail, and publish the same failure in `state.error`. `AuthError` shows it, so the handlers have nothing left to do. diff --git a/site/content/docs/(latest)/reference/core.mdx b/site/content/docs/(latest)/reference/core.mdx index e9e9d67..622dec9 100644 --- a/site/content/docs/(latest)/reference/core.mdx +++ b/site/content/docs/(latest)/reference/core.mdx @@ -178,6 +178,14 @@ What your refresh callback ([`RefreshFn`](#refreshfn)) returns: - [`Tokens`](#tokens): the new tokens. They must last at least five seconds. Leave out `refreshToken` or `user` to keep the current one. - `null`: your backend rejected the refresh token. The user is signed out. +### Register + +Register your client's type here, once, so the hooks from `@monarcode/session-kit/react` and the Effect service carry your user. Without it, the user is typed `unknown`. + +### RegisteredAuth + +The client registered in [`Register`](#register), or a client with an `unknown` user when none is. It's `never` when what's registered isn't a client. + ### RevokeFn Asks your backend to revoke the tokens of a session that just signed out. It's the `revoke` option of [`AuthOptions`](#authoptions). diff --git a/site/content/docs/(latest)/reference/effect.mdx b/site/content/docs/(latest)/reference/effect.mdx index 4ce32cd..cd7eb63 100644 --- a/site/content/docs/(latest)/reference/effect.mdx +++ b/site/content/docs/(latest)/reference/effect.mdx @@ -27,20 +27,12 @@ The codes an [`AuthFailure`](#authfailure) carries: every `AuthErrorCode` except ### AuthLayerClient -What `Auth.layer` takes. Once you register a client in [`Register`](#register), that's your client, or on the server a `serverAuth.forRequest(jar)` view with the same user. Until then, it's any [`AuthServiceClient`](#authserviceclient). +What `Auth.layer` takes. Once you register a client in `Register`, that's your client, or on the server a `serverAuth.forRequest(jar)` view with the same user. Until then, it's any [`AuthServiceClient`](#authserviceclient). ### AuthServiceClient What `Auth` needs from a client. Any `createAuth` or `createMirrorAuth` client fits, and so does a fake with these members in tests. `signIn` is optional, because a mirror made without it has none. -### Register - -Register your client's type here, once, so `Auth`'s Effects carry your user. Without it, the user is typed `unknown`. The same registration types `Auth` on the server, where `Auth.layer` takes a `serverAuth.forRequest(jar)` view. - -### RegisteredAuth - -The client registered in [`Register`](#register), or a client with an `unknown` user when none is. - ### RegisteredSession The session `Auth.session` gives you: your registered client's `Session`, never `null`. diff --git a/site/content/docs/(latest)/reference/index.mdx b/site/content/docs/(latest)/reference/index.mdx index d8f1154..52648d2 100644 --- a/site/content/docs/(latest)/reference/index.mdx +++ b/site/content/docs/(latest)/reference/index.mdx @@ -15,8 +15,8 @@ API. | Import | Exports | | --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | [`@monarcode/session-kit`](/docs/reference/core) | `createAuth`, `createMirrorAuth`, `fromAccessToken`, `webStorage`, `memoryStorage`, `safeReturnTo`, `AuthError`, types | -| [`@monarcode/session-kit/react`](/docs/reference/react) | `createAuthHooks`, `useMirrorAuth`, types | -| [`@monarcode/session-kit/tanstack-router`](/docs/reference/tanstack-router) | `connectAuth`, `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useRouterAuth`, types | +| [`@monarcode/session-kit/react`](/docs/reference/react) | `AuthProvider`, `useAuth`, `useAuthClient`, `createAuthHooks`, `useMirrorAuth`, types | +| [`@monarcode/session-kit/tanstack-router`](/docs/reference/tanstack-router) | `connectAuth`, `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuth`, `useAuthClient`, types | | [`@monarcode/session-kit/react-router`](/docs/reference/react-router) | `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuthRevalidation`, types | | [`@monarcode/session-kit/react-router/server`](/docs/reference/react-router-server) | `cookieJarMiddleware`, `routerJar`, types | | [`@monarcode/session-kit/http`](/docs/reference/http) | `createAuthFetch`, types | diff --git a/site/content/docs/(latest)/reference/react.mdx b/site/content/docs/(latest)/reference/react.mdx index 8a3c358..1a33a1b 100644 --- a/site/content/docs/(latest)/reference/react.mdx +++ b/site/content/docs/(latest)/reference/react.mdx @@ -13,12 +13,26 @@ Guide: [Read the session in React](/docs/getting-started#4-read-the-session-in-r ### createAuthHooks -Creates React hooks typed for one auth client. Each call has its own context, so an app with several clients calls it once per client. With TanStack Router, pass `useRouterAuth` as `useClient` instead of rendering `AuthProvider`. See [`AuthHooksOptions`](#authhooksoptions). +Creates React hooks typed for one auth client. Use it when an app has several clients: each call has its own context, so call it once per client. With one client, register it and use [`useAuth`](#useauth), [`useAuthClient`](#useauthclient) and [`AuthProvider`](#authprovider) instead. + +### useAuth + +Reads the current auth state, or the part `selector` picks, and re-renders when it changes. With a selector, it re-renders only when that part changes. + +### useAuthClient + +Returns the client of the nearest [`AuthProvider`](#authprovider), for actions such as `signIn` and `signOut`. It's typed by the client you register in `Register`, from `@monarcode/session-kit` ([`ProvidedAuth`](#providedauth)). ### useMirrorAuth Creates a `createMirrorAuth` client once, from the session the page was rendered with, and keeps it in step with your server. Call it in the component that renders `AuthProvider`. +## Components + +### AuthProvider + +Gives a client to the hooks below it, and mounts it while rendered, which starts expiry timers and following other tabs. Render it once, around your app. + ## Types ### AuthHooks @@ -49,6 +63,10 @@ Props for the `AuthProvider` that [`createAuthHooks`](#createauthhooks) returns. What the React bindings need from an auth client: its `state`, and `mount` to start background work while rendered. A `createAuth` or `createMirrorAuth` client fits. +### ProvidedAuth + +The client `AuthProvider` takes and `useAuthClient` returns: the one you register in `Register`, from `@monarcode/session-kit`. + ### StateOf The state type of a client: what `useAuth()` returns (`AuthState`). diff --git a/site/content/docs/(latest)/reference/tanstack-router.mdx b/site/content/docs/(latest)/reference/tanstack-router.mdx index 09fed65..58932b0 100644 --- a/site/content/docs/(latest)/reference/tanstack-router.mdx +++ b/site/content/docs/(latest)/reference/tanstack-router.mdx @@ -23,9 +23,13 @@ Guards your sign-in page in `beforeLoad`, so a signed-in user goes straight to ` Guards a route in `beforeLoad`, so only signed-in users get through. They get `{ session }` in route context, typed and never `null`, with no tokens in it. -### useRouterAuth +### useAuth -Reads the auth client from Router context, where it's `auth`. Pass it to `createAuthHooks` as `useClient`, so the hooks need no `AuthProvider`. Then mount the client with `connectAuth`. +Reads the current auth state of the client in Router context, or the part `selector` picks, and re-renders when it changes. With a selector, it re-renders only when that part changes. + +### useAuthClient + +Returns the auth client from Router context, where it's `auth`, for actions such as `signIn` and `signOut`. It needs no `AuthProvider`: `connectAuth` mounts the client. ## Components @@ -45,10 +49,6 @@ Options for [`redirectIfSignedIn`](#redirectifsignedin). name="RedirectIfSignedInOptions" /> -### RegisteredAuth - -The auth client type in your registered Router's context, which [`useRouterAuth`](#userouterauth) returns. It's `never` until the Router is registered. - ### RequireSessionOptions Options for [`requireSession`](#requiresession). @@ -59,6 +59,10 @@ Options for [`requireSession`](#requiresession). name="RequireSessionOptions" /> +### RouterAuth + +The auth client type in your registered Router's context, as `auth`, which [`useAuthClient`](#useauthclient) returns. It's `never` until the Router is registered. + ### SessionOutletProps Props for [`SessionOutlet`](#sessionoutlet). diff --git a/site/content/docs/(latest)/setups/expo.mdx b/site/content/docs/(latest)/setups/expo.mdx index c66e21b..d388b50 100644 --- a/site/content/docs/(latest)/setups/expo.mdx +++ b/site/content/docs/(latest)/setups/expo.mdx @@ -15,8 +15,8 @@ This page builds the [`expo-router` example app](https://github.com/monarcode/session-kit/tree/main/examples/expo-router) from scratch. It signs in against [DummyJSON's auth API](https://dummyjson.com/docs/auth), so it runs as -written. Its `src/auth.ts` takes the place of Getting started's `backend.ts`, -`auth.ts` and `hooks.ts`. [Using the client](/docs/client), +written. Its `src/auth.ts` takes the place of Getting started's `backend.ts` +and `auth.ts`. [Using the client](/docs/client), [Refresh](/docs/configuration/refresh) and [Errors](/docs/configuration/errors) explain how the client works. This page covers what differs on Expo. @@ -63,7 +63,6 @@ as on the web: import { createAuth } from "@monarcode/session-kit"; import { secureStorage } from "@monarcode/session-kit/expo"; import { createAuthFetch } from "@monarcode/session-kit/http"; -import { createAuthHooks } from "@monarcode/session-kit/react"; import { z } from "zod"; const API = "https://dummyjson.com"; @@ -99,9 +98,6 @@ export const auth = createAuth({ }, }); -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); - export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); export async function signInWithPassword(username: string, password: string) { @@ -122,15 +118,24 @@ export async function signInWithPassword(username: string, password: string) { `SessionGate` goes inside `AuthProvider`, around the root navigator. Guard the screens with `Stack.Protected`. Signed-in users see the `(app)` group, and -everyone else sees `login`: +everyone else sees `login`. Register the client's type here too, so the hooks +from `@monarcode/session-kit/react` carry your user: ```tsx title="app/_layout.tsx" import { SessionGate } from "@monarcode/session-kit/expo"; +import { AuthProvider, useAuth } from "@monarcode/session-kit/react"; import { SplashScreen, Stack } from "expo-router"; -import { auth, AuthProvider, useAuth } from "../src/auth"; +import { auth } from "../src/auth"; import { Unavailable } from "../src/unavailable"; +// Types `AuthProvider` and the hooks with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + // Keeps the splash screen up until SessionGate hides it. void SplashScreen.preventAutoHideAsync(); @@ -278,7 +283,9 @@ Its first screen shows the user's name, fetches their email, and signs out: import { useEffect, useState } from "react"; import { Button, Text, View } from "react-native"; -import { authFetch, useAuth, useAuthClient } from "../../src/auth"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; + +import { authFetch } from "../../src/auth"; export default function Home() { const firstName = useAuth((state) => state.user?.firstName); @@ -644,7 +651,9 @@ import { Button, Text, View } from "react-native"; import { Link } from "expo-router"; -import { auth, useAuth } from "../src/auth"; +import { useAuth } from "@monarcode/session-kit/react"; + +import { auth } from "../src/auth"; import { loadKey } from "../src/session-key"; export default function WelcomeBack() { diff --git a/site/content/docs/(latest)/setups/next.mdx b/site/content/docs/(latest)/setups/next.mdx index 976a78b..c9eb879 100644 --- a/site/content/docs/(latest)/setups/next.mdx +++ b/site/content/docs/(latest)/setups/next.mdx @@ -235,33 +235,33 @@ export function createAppAuth(session: AppSession | null) { export type AppAuth = ReturnType; ``` -Create the hooks, typed by that client: - -```ts title="app/hooks.ts" -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { AppAuth } from "../lib/auth/client"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); -``` - `useMirrorAuth` from `@monarcode/session-kit/react` creates the client in a Client Component, once per request on the server, never at module level. It keeps the client and the server in step both ways, rendering Server Components again with `router.refresh()` when the session changes in the -browser: +browser. Register the client's type where you render `AuthProvider`, so the +hooks carry your user: ```tsx title="app/providers.tsx" "use client"; import type { ReactNode } from "react"; -import { useMirrorAuth } from "@monarcode/session-kit/react"; +import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react"; import { useRouter } from "next/navigation"; -import { createAppAuth, type AppSession } from "../lib/auth/client"; -import { AuthProvider } from "./hooks"; +import { + createAppAuth, + type AppAuth, + type AppSession, +} from "../lib/auth/client"; + +// Types `AuthProvider` and the hooks with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: AppAuth; + } +} export function Providers(props: { session: AppSession | null; @@ -341,7 +341,7 @@ The form is a Client Component that calls the client's `signIn`: import { useState, type FormEvent } from "react"; -import { useAuthClient } from "../hooks"; +import { useAuthClient } from "@monarcode/session-kit/react"; export function SignInForm() { const auth = useAuthClient(); diff --git a/site/content/docs/(latest)/setups/react-router-ssr.mdx b/site/content/docs/(latest)/setups/react-router-ssr.mdx index c20af47..a82bdb9 100644 --- a/site/content/docs/(latest)/setups/react-router-ssr.mdx +++ b/site/content/docs/(latest)/setups/react-router-ssr.mdx @@ -276,22 +276,13 @@ export function createAppAuth(initial: AppSession | null) { export type AppAuth = ReturnType; ``` -Create the hooks, typed by that client: - -```ts title="app/hooks.ts" -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { AppAuth } from "./auth/client"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); -``` - The root route runs the middleware and reads the session, and its component creates the client with `useMirrorAuth` from `@monarcode/session-kit/react`: once per request on the server, never at module level. It keeps the client and the server in step both ways, running loaders again with `revalidate` -from `useRevalidator()` when the session changes in the browser: +from `useRevalidator()` when the session changes in the browser. Register the +client's type here, where you render `AuthProvider`, so the hooks carry your +user: ```tsx title="app/root.tsx" import type { ReactNode } from "react"; @@ -305,13 +296,19 @@ import { type LoaderFunctionArgs, } from "react-router"; -import { useMirrorAuth } from "@monarcode/session-kit/react"; +import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react"; import { routerJar } from "@monarcode/session-kit/react-router/server"; -import { createAppAuth } from "./auth/client"; +import { createAppAuth, type AppAuth } from "./auth/client"; import { sessionMiddleware } from "./auth/middleware.server"; import { serverAuth } from "./auth/session.server"; -import { AuthProvider } from "./hooks"; + +// Types `AuthProvider` and the hooks with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: AppAuth; + } +} export const middleware = sessionMiddleware; @@ -379,7 +376,7 @@ export default function Protected() { A page nested in it reads the user as usual: ```tsx title="app/routes/home.tsx" -import { useAuth } from "../hooks"; +import { useAuth } from "@monarcode/session-kit/react"; export default function Home() { const user = useAuth((state) => state.user); diff --git a/site/content/docs/(latest)/setups/react-router.mdx b/site/content/docs/(latest)/setups/react-router.mdx index 0dc1583..88e40b4 100644 --- a/site/content/docs/(latest)/setups/react-router.mdx +++ b/site/content/docs/(latest)/setups/react-router.mdx @@ -20,8 +20,7 @@ rendering, follow ## Before you begin Follow [Getting started](/docs/getting-started) through step 4. This guide -uses its client in `src/auth.ts`, its hooks in `src/hooks.ts`, and its form in -`src/sign-in.tsx`. +uses its client in `src/auth.ts` and its form in `src/sign-in.tsx`. ## Installation @@ -37,12 +36,14 @@ React Router 7 and 8 both work. In every mode, `AuthProvider` goes around the router. It mounts the client in a layout effect, so with `localStorage` and a synchronous schema, the session -is restored before the first paint. Nothing starts on a server. +is restored before the first paint. Nothing starts on a server. Register the +client where you render it, as in Getting started, and the hooks from +`@monarcode/session-kit/react` carry your user. Every mode on this page protects the same page: ```tsx title="src/home.tsx" -import { useAuth, useAuthClient } from "./hooks.js"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; export function Home() { const user = useAuth((state) => state.user); @@ -75,14 +76,21 @@ import { } from "react-router"; import { safeReturnTo } from "@monarcode/session-kit"; +import { AuthProvider, useAuth } from "@monarcode/session-kit/react"; import { SessionOutlet } from "@monarcode/session-kit/react-router"; import { createRoot } from "react-dom/client"; import { auth } from "./auth.js"; import { Home } from "./home.js"; -import { AuthProvider, useAuth } from "./hooks.js"; import { SignIn } from "./sign-in.js"; +// Types `AuthProvider` and the hooks with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + /** The guard: its child routes render only while someone is signed in. */ function Private() { return ( @@ -153,6 +161,7 @@ import { } from "react-router"; import { safeReturnTo } from "@monarcode/session-kit"; +import { useAuthClient } from "@monarcode/session-kit/react"; import { redirectIfSignedIn, requireSession, @@ -162,7 +171,6 @@ import { import { auth } from "./auth.js"; import { Home } from "./home.js"; -import { useAuthClient } from "./hooks.js"; import { SignIn } from "./sign-in.js"; /** Runs the loaders again when auth changes, and with them the guards. */ @@ -234,12 +242,19 @@ Then render the router inside the provider, in `src/main.tsx`: import { StrictMode } from "react"; import { RouterProvider } from "react-router"; +import { AuthProvider } from "@monarcode/session-kit/react"; import { createRoot } from "react-dom/client"; import { auth } from "./auth.js"; -import { AuthProvider } from "./hooks.js"; import { router } from "./router.js"; +// Types `AuthProvider` and the hooks with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + createRoot(document.getElementById("root")!).render( @@ -286,10 +301,17 @@ Provide the client, and watch for auth changes, in the root route: import type { ReactNode } from "react"; import { Links, Meta, Outlet, Scripts, ScrollRestoration } from "react-router"; +import { AuthProvider } from "@monarcode/session-kit/react"; import { useAuthRevalidation } from "@monarcode/session-kit/react-router"; import { auth } from "./auth.js"; -import { AuthProvider } from "./hooks.js"; + +// Types `AuthProvider` and the hooks with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} export function Layout({ children }: { children: ReactNode }) { return ( @@ -333,13 +355,13 @@ Guard a layout route, and nest the private routes under it: ```tsx title="app/routes/protected.tsx" import { useRouteError } from "react-router"; +import { useAuthClient } from "@monarcode/session-kit/react"; import { requireSession, SessionOutlet, } from "@monarcode/session-kit/react-router"; import { auth } from "../auth.js"; -import { useAuthClient } from "../hooks.js"; export function clientLoader({ request }: { request: Request }) { return requireSession(auth, { request, loginPath: "/login" }); @@ -426,10 +448,9 @@ and a top bar. Render it in the guarded route's element, with `SessionOutlet` where the pages go: ```tsx title="src/dashboard.tsx" +import { useAuth } from "@monarcode/session-kit/react"; import { SessionOutlet } from "@monarcode/session-kit/react-router"; -import { useAuth } from "./hooks.js"; - /** The guarded route's element: `element: `. */ export function Dashboard() { // From state, not loader data: this stays mounted through a sign-out. diff --git a/site/content/docs/(latest)/setups/tanstack-router.mdx b/site/content/docs/(latest)/setups/tanstack-router.mdx index 15b2cde..590a0dd 100644 --- a/site/content/docs/(latest)/setups/tanstack-router.mdx +++ b/site/content/docs/(latest)/setups/tanstack-router.mdx @@ -6,7 +6,9 @@ description: Keep the client in Router context, guard private routes before they In this guide, you add TanStack Router to the app from Getting started: a sign-in route, private routes that redirect signed-out users, and hooks that read the client from the Router. Guards run in `beforeLoad`, before a private -route loads or renders, and the hooks need no `AuthProvider`. +route loads or renders. The hooks come from +`@monarcode/session-kit/tanstack-router`, typed by the Router you register, +and need no `AuthProvider`. A complete app is in [`examples/tanstack-router`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-router). @@ -46,34 +48,16 @@ export default defineConfig({ The plugin generates `src/routeTree.gen.ts` from the files under `src/routes`. -## 1. Create the hooks - -Create hooks that read the client from Router context. They replace Getting -started's `src/hooks.ts`: - -```ts title="src/hooks.ts" -import { createAuthHooks } from "@monarcode/session-kit/react"; -import { useRouterAuth } from "@monarcode/session-kit/tanstack-router"; - -// Reads the client from Router context, so no provider is needed. -export const { useAuth, useAuthClient } = createAuthHooks({ - useClient: useRouterAuth, -}); -``` - -Routes take the place of Getting started's `src/app.tsx`. Registering the -Router in step 5 gives the hooks your user type. - -## 2. Type the root route +## 1. Type the root route The root route declares that Router context holds the client, so every guard gets a typed `context.auth`: ```tsx title="src/routes/__root.tsx" +import { useAuth } from "@monarcode/session-kit/tanstack-router"; import { createRootRouteWithContext, Outlet } from "@tanstack/react-router"; import type { AppAuth } from "../auth.js"; -import { useAuth } from "../hooks.js"; export const Route = createRootRouteWithContext<{ auth: AppAuth }>()({ component: Root, @@ -92,7 +76,7 @@ function Root() { } ``` -## 3. Add the sign-in route +## 2. Add the sign-in route The sign-in route renders the form from Getting started, and sends the user on to the page they asked for: @@ -130,7 +114,7 @@ Pass `{ loginPath }` if sign-in lives somewhere other than `/login`. `redirectIfSignedIn` sends signed-in users on to `redirectTo`, checked the same way. -## 4. Guard private routes +## 3. Guard private routes Guard private routes with a pathless layout. Its child routes are guarded without `authenticated` appearing in their URLs: @@ -139,14 +123,13 @@ without `authenticated` appearing in their URLs: import { requireSession, SessionOutlet, + useAuthClient, } from "@monarcode/session-kit/tanstack-router"; import { createFileRoute, type ErrorComponentProps, } from "@tanstack/react-router"; -import { useAuthClient } from "../hooks.js"; - export const Route = createFileRoute("/_authenticated")({ beforeLoad: ({ context, location }) => requireSession(context.auth, { location, loginPath: "/login" }), @@ -181,10 +164,9 @@ Child routes read the session from route context, where `user` is typed and never `null`: ```tsx title="src/routes/_authenticated/index.tsx" +import { useAuthClient } from "@monarcode/session-kit/tanstack-router"; import { createFileRoute } from "@tanstack/react-router"; -import { useAuthClient } from "../../hooks.js"; - export const Route = createFileRoute("/_authenticated/")({ component: Home, }); @@ -203,7 +185,7 @@ function Home() { } ``` -## 5. Create and connect the Router +## 4. Create and connect the Router Create the Router with the client in its context, then connect the two: @@ -235,7 +217,10 @@ declare module "@tanstack/react-router" { app, and one thing more: when the session changes, it runs the guards again, so a sign-out in another tab redirects this one. -## 6. Render the app +Registering the Router also types `useAuth` and `useAuthClient` with your +client. Until it's registered, they're typed `never`. + +## 5. Render the app Render the Router: @@ -269,9 +254,7 @@ the pages go: ```tsx title="src/dashboard.tsx" import { useState } from "react"; -import { SessionOutlet } from "@monarcode/session-kit/tanstack-router"; - -import { useAuth } from "./hooks.js"; +import { SessionOutlet, useAuth } from "@monarcode/session-kit/tanstack-router"; /** The guarded route's component: `component: Dashboard`. */ export function Dashboard() { diff --git a/site/content/docs/(latest)/setups/tanstack-start.mdx b/site/content/docs/(latest)/setups/tanstack-start.mdx index 1ca0d0a..cd89d11 100644 --- a/site/content/docs/(latest)/setups/tanstack-start.mdx +++ b/site/content/docs/(latest)/setups/tanstack-start.mdx @@ -8,8 +8,7 @@ Start. The server signs in, refreshes the tokens before rendering, and sends the signed-in page first, so the browser never shows a "Checking session…" state or a flash of signed-out content. The browser holds a small client that mirrors the session, and the -[hooks](/docs/getting-started#4-read-the-session-in-react) -and the [TanStack Router guards](/docs/setups/tanstack-router) work with it. +[TanStack Router hooks and guards](/docs/setups/tanstack-router) work with it. [Server rendering](/docs/server-rendering) explains how the pieces fit. For TanStack Start in SPA mode, where the browser keeps the session, follow @@ -259,7 +258,7 @@ export const Route = createFileRoute("/_authenticated")({ }); ``` -[Guard private routes](/docs/setups/tanstack-router#4-guard-private-routes) +[Guard private routes](/docs/setups/tanstack-router#3-guard-private-routes) explains `SessionOutlet`, and an error component for a failed refresh. Guards decide what a page shows. Server functions that return private data @@ -291,6 +290,9 @@ export async function signIn( } ``` +In a component, `useAuthClient` from `@monarcode/session-kit/tanstack-router` +gives you `auth`, from Router context. + In this guide, the server signs in with your backend, so the user in the cookie comes from the backend. If the browser signs in with the backend itself, for example through a provider's SDK, have `signInFn` take the tokens and the user diff --git a/site/src/lib/tour.ts b/site/src/lib/tour.ts index 13930be..f2eee53 100644 --- a/site/src/lib/tour.ts +++ b/site/src/lib/tour.ts @@ -28,14 +28,14 @@ const TOUR = [ label: "Guard private routes", page: "setups/tanstack-router", file: "src/routes/_authenticated.tsx", - href: "/docs/setups/tanstack-router#4-guard-private-routes", + href: "/docs/setups/tanstack-router#3-guard-private-routes", guide: "the TanStack Router guide", }, { label: "Read the session in a guarded page", page: "setups/tanstack-router", file: "src/routes/_authenticated/index.tsx", - href: "/docs/setups/tanstack-router#4-guard-private-routes", + href: "/docs/setups/tanstack-router#3-guard-private-routes", guide: "the TanStack Router guide", }, ] as const; diff --git a/src/core/register.ts b/src/core/register.ts new file mode 100644 index 0000000..137d045 --- /dev/null +++ b/src/core/register.ts @@ -0,0 +1,68 @@ +import type { AuthClient } from "./types.js"; + +/** + * Register your client's type here, once, so the hooks from + * `@monarcode/session-kit/react` and the Effect service carry your user. + * Without it, the user is typed `unknown`. + * + * Register the client you give `AuthProvider`: one from `createAuth`, or with + * server rendering from `createMirrorAuth`. Register a mirror client by the + * type its function returns, such as `ReturnType`. + * Anything else types the hooks and the Effect service as `never`. + * + * A TanStack Router app doesn't need it for its hooks: those from + * `@monarcode/session-kit/tanstack-router` are typed by the Router. + * + * @example + * ```ts + * import { createAuth, webStorage } from "@monarcode/session-kit"; + * import { z } from "zod"; + * + * export const auth = createAuth({ + * name: "app", + * user: z.object({ id: z.string(), name: z.string() }), + * storage: webStorage(), + * }); + * + * declare module "@monarcode/session-kit" { + * interface Register { + * auth: typeof auth; + * } + * } + * ``` + * + * @see {@link RegisteredAuth} for the type it gives + * + * @since 0.1.0 + */ +export interface Register {} + +/** + * What a registered client has: every client from `createAuth` or + * `createMirrorAuth` does. + */ +type RegisterableAuth = Pick< + AuthClient, + "state" | "mount" | "getSession" | "signOut" | "isCurrent" | "credentials" +>; + +/** + * The client registered in {@link Register}, or a client with an `unknown` + * user when none is. It's `never` when what's registered isn't a client. + * + * @example + * ```ts + * import type { RegisteredAuth } from "@monarcode/session-kit"; + * + * export function status(client: RegisteredAuth) { + * return client.state.get().status; + * } + * ``` + * + * @since 0.1.0 + */ +export type RegisteredAuth = Register extends { readonly auth: infer Client } + ? Client extends RegisterableAuth + ? Client + : never + : AuthClient; diff --git a/src/effect/auth.ts b/src/effect/auth.ts index 5ccb0cc..b7077cc 100644 --- a/src/effect/auth.ts +++ b/src/effect/auth.ts @@ -8,7 +8,8 @@ import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import { AuthError, toAuthError } from "../core/errors.js"; -import type { AuthClient, Credentials } from "../core/types.js"; +import type { Register, RegisteredAuth } from "../core/register.js"; +import type { Credentials } from "../core/types.js"; import type { RequestAuth } from "../server/auth.js"; import { type AuthFailure, @@ -17,63 +18,6 @@ import { unauthenticated, } from "./failure.js"; -/** - * Register your client's type here, once, so `Auth`'s Effects carry your - * user. Without it, the user is typed `unknown`. The same registration - * types `Auth` on the server, where {@link Auth.layer} takes a - * `serverAuth.forRequest(jar)` view. - * - * @example - * ```ts - * import { createAuth, memoryStorage } from "@monarcode/session-kit"; - * import { Auth } from "@monarcode/session-kit/effect"; - * import { z } from "zod"; - * - * export const auth = createAuth({ - * name: "app", - * user: z.object({ id: z.string(), name: z.string() }), - * storage: memoryStorage(), - * }); - * - * declare module "@monarcode/session-kit/effect" { - * interface Register { - * auth: typeof auth; - * } - * } - * - * export const AuthLive = Auth.layer(auth); - * ``` - * - * @example - * A `createMirrorAuth` client, made per request with server rendering, - * registers its type the same way: - * ```ts - * import { createMirrorAuth, type Session } from "@monarcode/session-kit"; - * import { Auth } from "@monarcode/session-kit/effect"; - * - * declare function getSessionFn(): Promise | null>; - * - * export const createAppAuth = () => - * createMirrorAuth({ - * name: "app", - * session: null, - * revalidate: getSessionFn, - * signOut: async () => {}, - * }); - * - * declare module "@monarcode/session-kit/effect" { - * interface Register { - * auth: ReturnType; - * } - * } - * - * export const layer = () => Auth.layer(createAppAuth()); - * ``` - * - * @since 0.1.0 - */ -export interface Register {} - /** * What `Auth` needs from a client. Any `createAuth` or `createMirrorAuth` * client fits, and so does a fake with these members in tests. `signIn` is @@ -114,26 +58,6 @@ export type AuthServiceClient = { }; }; -/** - * The client registered in {@link Register}, or a client with an `unknown` - * user when none is. - * - * @example - * ```ts - * import type { RegisteredAuth } from "@monarcode/session-kit/effect"; - * - * declare const client: RegisteredAuth; - * export const status = client.state.get().status; - * ``` - * - * @since 0.1.0 - */ -export type RegisteredAuth = Register extends { - readonly auth: infer Client extends AuthServiceClient; -} - ? Client - : AuthClient; - /** * What {@link Auth.layer} takes. Once you register a client in * {@link Register}, that's your client, or on the server a @@ -151,7 +75,7 @@ export type RegisteredAuth = Register extends { * @since 0.1.0 */ export type AuthLayerClient = Register extends { - readonly auth: AuthServiceClient; + readonly auth: object; } ? | RegisteredAuth @@ -241,8 +165,8 @@ export type RegisteredUserInput = RegisteredAuth extends { * an access token for API calls, sign in and out, update the user, and * stream state changes. * - * Provide it with {@link Auth.layer}. Register your client's type in - * {@link Register} so the Effects carry your user. + * Provide it with {@link Auth.layer}. Register your client's type in the + * main entry point's {@link Register}, so the Effects carry your user. * * Each Effect fails with an {@link AuthFailure} whose `code` is the client's * `AuthErrorCode`. An Effect dies on misuse (`INVALID_OPTIONS`). diff --git a/src/effect/index.ts b/src/effect/index.ts index 6020a23..26d4532 100644 --- a/src/effect/index.ts +++ b/src/effect/index.ts @@ -4,8 +4,6 @@ export { AuthFailure } from "./failure.js"; export type { AuthLayerClient, AuthServiceClient, - Register, - RegisteredAuth, RegisteredSession, RegisteredSignIn, RegisteredState, diff --git a/src/index.ts b/src/index.ts index e8699b1..ccd207a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,6 +18,7 @@ export type { MirrorAuthOptions, MirrorCredentials, } from "./core/mirror.js"; +export type { Register, RegisteredAuth } from "./core/register.js"; export type { SafeReturnToOptions } from "./core/return-to.js"; export type { AccessTokenUser, diff --git a/src/react/hooks.ts b/src/react/hooks.ts index 6b5a182..f8f6f1f 100644 --- a/src/react/hooks.ts +++ b/src/react/hooks.ts @@ -6,6 +6,8 @@ import { type ReactNode, } from "react"; +import type { Register, RegisteredAuth } from "../core/register.js"; +import type { AuthClient } from "../core/types.js"; import { assertAuthSource, ClientContext, @@ -34,11 +36,10 @@ import { */ export type AuthHooksOptions = { /** - * Finds the client some other way than `AuthProvider`, such as from router - * context with `useRouterAuth`. It's called as a hook, inside every hook, - * on every render. The hooks then need no `AuthProvider`, so mount the - * client another way, such as with `connectAuth`. Default: reads the - * nearest `AuthProvider`. + * Finds the client some other way than `AuthProvider`, such as from a + * context of your own. It's called as a hook, inside every hook, on every + * render. The hooks then need no `AuthProvider`, so mount the client + * another way. Default: reads the nearest `AuthProvider`. */ useClient?: (() => Client) | undefined; }; @@ -120,10 +121,10 @@ export type AuthHooks = { }; /** - * Creates React hooks typed for one auth client. Each call has its own - * context, so an app with several clients calls it once per client. With - * TanStack Router, pass `useRouterAuth` as `useClient` instead of - * rendering `AuthProvider`. See {@link AuthHooksOptions}. + * Creates React hooks typed for one auth client. Use it when an app has + * several clients: each call has its own context, so call it once per + * client. With one client, register it and use {@link useAuth}, + * {@link useAuthClient} and {@link AuthProvider} instead. * * @example * ```tsx @@ -145,6 +146,8 @@ export type AuthHooks = { * } * ``` * + * @see {@link AuthHooksOptions} to find the client without `AuthProvider` + * * @since 0.1.0 */ export function createAuthHooks( @@ -178,7 +181,10 @@ export function createAuthHooks( client, options.useClient ? "useClient did not return an auth client" - : "Render AuthProvider with an auth client before using auth hooks", + : "Render AuthProvider with an auth client before using auth hooks. " + + "The hooks read only the AuthProvider they came with. " + + "With TanStack Router, use the hooks from " + + "@monarcode/session-kit/tanstack-router, which read Router context", ); return client; } @@ -196,3 +202,130 @@ export function createAuthHooks( useAuth: useAuth as AuthHooks["useAuth"], }; } + +/** + * The client `AuthProvider` takes and `useAuthClient` returns: the one you + * register in `Register`, from `@monarcode/session-kit`. + * + * Until you register one, it's any client, with what every client has: its + * state, `getSession`, `signOut`, `isCurrent` and `credentials`. Its user is + * then `unknown`. + * + * @example + * ```ts + * import type { ProvidedAuth } from "@monarcode/session-kit/react"; + * + * export function signOutQuietly(client: ProvidedAuth) { + * return client.signOut().catch(() => {}); + * } + * ``` + * + * @since 0.1.0 + */ +export type ProvidedAuth = Register extends { readonly auth: unknown } + ? RegisteredAuth + : Pick< + AuthClient, + | "state" + | "mount" + | "getSession" + | "signOut" + | "isCurrent" + | "credentials" + >; + +// The hooks most apps use. One context, as for any `createAuthHooks` call. +const provided = createAuthHooks(); + +/** + * Gives a client to the hooks below it, and mounts it while rendered, which + * starts expiry timers and following other tabs. Render it once, around your + * app. + * + * Mounting restores the saved session, before the first paint with + * synchronous storage and schemas. On a server, nothing starts, as effects + * don't run there. + * + * Its `client` is typed by the client you register in `Register`, from + * `@monarcode/session-kit`. Until you register one, it takes any client + * ({@link ProvidedAuth}). + * + * @example + * ```tsx + * import type { ReactNode } from "react"; + * import type { AuthClient } from "@monarcode/session-kit"; + * import { AuthProvider } from "@monarcode/session-kit/react"; + * + * declare const auth: AuthClient<{ name: string }, { name: string }>; + * + * export function Providers({ children }: { children: ReactNode }) { + * return {children}; + * } + * ``` + * + * @see {@link useAuth} to read the session below it + * + * @since 0.1.0 + */ +export function AuthProvider( + props: AuthProviderProps, +): ReactElement { + return provided.AuthProvider(props); +} + +/** + * Reads the current auth state, or the part `selector` picks, and re-renders + * when it changes. With a selector, it re-renders only when that part + * changes. + * + * It reads the client of the nearest {@link AuthProvider}, typed by the + * client you register in `Register`, from `@monarcode/session-kit`. + * + * Throws `INVALID_OPTIONS` without an `AuthProvider` above. With TanStack + * Router, use the hooks from `@monarcode/session-kit/tanstack-router` + * instead: they read Router context, and need no `AuthProvider`. + * + * @example + * ```tsx + * import { useAuth } from "@monarcode/session-kit/react"; + * + * export function Greeting() { + * const status = useAuth((state) => state.status); + * return

{status === "unauthenticated" ? "Signed out" : "Welcome"}

; + * } + * ``` + * + * @since 0.1.0 + */ +export const useAuth: { + (): StateOf; + (selector: (state: StateOf) => T): T; +} = provided.useAuth; + +/** + * Returns the client of the nearest {@link AuthProvider}, for actions such + * as `signIn` and `signOut`. It's typed by the client you register in + * `Register`, from `@monarcode/session-kit` ({@link ProvidedAuth}). + * + * Throws `INVALID_OPTIONS` without an `AuthProvider` above, as + * {@link useAuth} does. + * + * @example + * ```tsx + * import { useAuthClient } from "@monarcode/session-kit/react"; + * + * export function SignOutButton() { + * const auth = useAuthClient(); + * return ( + * + * ); + * } + * ``` + * + * @since 0.1.0 + */ +export function useAuthClient(): ProvidedAuth { + return provided.useAuthClient(); +} diff --git a/src/react/index.ts b/src/react/index.ts index 92db4d8..c822f1c 100644 --- a/src/react/index.ts +++ b/src/react/index.ts @@ -1,4 +1,9 @@ -export { createAuthHooks } from "./hooks.js"; +export { + AuthProvider, + createAuthHooks, + useAuth, + useAuthClient, +} from "./hooks.js"; export { useMirrorAuth } from "./mirror.js"; export type { AuthSource, StateOf } from "./context.js"; @@ -6,5 +11,6 @@ export type { AuthHooks, AuthHooksOptions, AuthProviderProps, + ProvidedAuth, } from "./hooks.js"; export type { UseMirrorAuthOptions } from "./mirror.js"; diff --git a/src/tanstack-router/index.ts b/src/tanstack-router/index.ts index 75208ba..56c8a7e 100644 --- a/src/tanstack-router/index.ts +++ b/src/tanstack-router/index.ts @@ -1,6 +1,11 @@ import { useRouter, type Register } from "@tanstack/react-router"; -import { assertAuthSource } from "../react/context.js"; +import { + assertAuthSource, + type AuthSource, + type StateOf, +} from "../react/context.js"; +import { createAuthHooks } from "../react/hooks.js"; export { connectAuth } from "./connect.js"; export { redirectIfSignedIn, requireSession } from "./guards.js"; @@ -13,8 +18,8 @@ export type { export type { SessionOutletProps } from "./outlet.js"; /** - * The auth client type in your registered Router's context, which - * {@link useRouterAuth} returns. It's `never` until the Router is registered. + * The auth client type in your registered Router's context, as `auth`, which + * {@link useAuthClient} returns. It's `never` until the Router is registered. * * @example * ```ts @@ -23,7 +28,7 @@ export type { SessionOutletProps } from "./outlet.js"; * createRouter, * } from "@tanstack/react-router"; * import type { AuthClient } from "@monarcode/session-kit"; - * import type { RegisteredAuth } from "@monarcode/session-kit/tanstack-router"; + * import type { RouterAuth } from "@monarcode/session-kit/tanstack-router"; * * type User = { name: string }; * declare const auth: AuthClient; @@ -37,47 +42,106 @@ export type { SessionOutletProps } from "./outlet.js"; * } * } * - * export function userName(client: RegisteredAuth) { + * export function userName(client: RouterAuth) { * return client.state.get().user?.name; * } * ``` * * @since 0.1.0 */ -export type RegisteredAuth = Register extends { - router: { options: { context: { auth: infer Client } } }; +export type RouterAuth = Register extends { + router: { options: { context: { auth?: infer Client } } }; } - ? Client + ? NonNullable extends AuthSource + ? NonNullable + : never : never; /** - * Reads the auth client from Router context, where it's `auth`. Pass it to - * `createAuthHooks` as `useClient`, so the hooks need no `AuthProvider`. - * Then mount the client with `connectAuth`. + * Returns the auth client from Router context, where it's `auth`, for + * actions such as `signIn` and `signOut`. It needs no `AuthProvider`: + * `connectAuth` mounts the client. * + * The client's type comes from your registered Router ({@link RouterAuth}). * Router context is per request in TanStack Start, so this is safe during - * server rendering. Throws `INVALID_OPTIONS` when Router context has no - * `auth`. The client's type comes from your registered Router - * ({@link RegisteredAuth}). + * server rendering. + * + * Throws `INVALID_OPTIONS` when Router context has no `auth`. * * @example - * ```ts - * import { createAuthHooks } from "@monarcode/session-kit/react"; - * import { useRouterAuth } from "@monarcode/session-kit/tanstack-router"; + * ```tsx + * import { + * createRootRouteWithContext, + * createRouter, + * } from "@tanstack/react-router"; + * import type { AuthClient } from "@monarcode/session-kit"; + * import { useAuthClient } from "@monarcode/session-kit/tanstack-router"; + * + * declare const auth: AuthClient<{ name: string }, { name: string }>; + * const routeTree = createRootRouteWithContext<{ auth: typeof auth }>()(); + * const router = createRouter({ routeTree, context: { auth } }); + * declare module "@tanstack/react-router" { + * interface Register { + * router: typeof router; + * } + * } * - * // With the Router registered, as `RegisteredAuth` shows. - * export const { useAuth, useAuthClient } = createAuthHooks({ - * useClient: useRouterAuth, - * }); + * export function SignOutButton() { + * const auth = useAuthClient(); + * return ( + * + * ); + * } * ``` * * @since 0.1.0 */ -export function useRouterAuth(): RegisteredAuth { +export function useAuthClient(): RouterAuth { const auth: unknown = useRouter().options.context?.auth; assertAuthSource( auth, "Provide an auth client as `auth` in Router context before using auth hooks", ); - return auth as RegisteredAuth; + return auth as RouterAuth; } + +/** + * Reads the current auth state of the client in Router context, or the part + * `selector` picks, and re-renders when it changes. With a selector, it + * re-renders only when that part changes. + * + * Typed by your registered Router, as {@link useAuthClient} is. Throws + * `INVALID_OPTIONS` when Router context has no `auth`. + * + * @example + * ```tsx + * import { + * createRootRouteWithContext, + * createRouter, + * } from "@tanstack/react-router"; + * import type { AuthClient } from "@monarcode/session-kit"; + * import { useAuth } from "@monarcode/session-kit/tanstack-router"; + * + * declare const auth: AuthClient<{ name: string }, { name: string }>; + * const routeTree = createRootRouteWithContext<{ auth: typeof auth }>()(); + * const router = createRouter({ routeTree, context: { auth } }); + * declare module "@tanstack/react-router" { + * interface Register { + * router: typeof router; + * } + * } + * + * export function Greeting() { + * const status = useAuth((state) => state.status); + * return

{status === "unauthenticated" ? "Signed out" : "Welcome"}

; + * } + * ``` + * + * @since 0.1.0 + */ +export const useAuth: { + (): StateOf; + (selector: (state: StateOf) => T): T; +} = createAuthHooks({ useClient: useAuthClient }).useAuth; diff --git a/tests/consumer-mirror.ts b/tests/consumer-mirror.ts index 59fe080..9f1cd2e 100644 --- a/tests/consumer-mirror.ts +++ b/tests/consumer-mirror.ts @@ -6,6 +6,7 @@ import { Auth } from "../dist/effect/index.js"; // A program of its own: one `Register` per program, here the mirror client a // server-rendered app registers. import { createMirrorAuth, type Session } from "../dist/index.js"; +import { AuthProvider, useAuth } from "../dist/react/index.js"; import { createServerAuth, type CookieJar } from "../dist/server/index.js"; const userSchema = z.object({ id: z.number(), firstName: z.string() }); @@ -30,12 +31,19 @@ const createAppAuth = () => signOut: async () => {}, }); -declare module "../dist/effect/index.js" { +declare module "../dist/index.js" { interface Register { auth: ReturnType; } } +// The hooks from `./react` take the mirror client, and carry its user. +AuthProvider({ client: createAppAuth() }); +const mirrorName: string | undefined = useAuth( + (state) => state.user?.firstName, +); +void mirrorName; + declare const jar: CookieJar; const requestLayer: Layer.Layer = Auth.layer(serverAuth.forRequest(jar)); const browserLayer: Layer.Layer = Auth.layer(createAppAuth()); diff --git a/tests/consumer-unregistered.ts b/tests/consumer-unregistered.ts new file mode 100644 index 0000000..487d526 --- /dev/null +++ b/tests/consumer-unregistered.ts @@ -0,0 +1,56 @@ +// A program of its own, that registers nothing: the hooks still work, with an +// `unknown` user, and TanStack Router's need the Router registered. +import { z } from "zod"; + +import { Auth } from "../dist/effect/index.js"; +import { + createAuth, + createMirrorAuth, + webStorage, + type AuthClient, + type AuthState, + type RegisteredAuth, +} from "../dist/index.js"; +import { + AuthProvider, + useAuth, + useAuthClient, + type ProvidedAuth, +} from "../dist/react/index.js"; +import * as router from "../dist/tanstack-router/index.js"; + +const auth = createAuth({ + name: "unregistered-type-test", + user: z.object({ id: z.string() }), + storage: webStorage(), +}); + +AuthProvider({ client: auth }); +// A mirror made without `signIn` fits too. +AuthProvider({ + client: createMirrorAuth({ + name: "unregistered-mirror", + session: null, + revalidate: async () => null, + signOut: async () => {}, + }), +}); +const state: AuthState = useAuth(); +const user: unknown = useAuth((current) => current.user); +// @ts-expect-error Without a registration, the user's fields are unknown. +void useAuth((current) => current.user?.id); +// @ts-expect-error Without a selector, it returns the state, whatever is asked. +const notState: string = useAuth(); +const client: ProvidedAuth = useAuthClient(); +void client.signOut(); +// @ts-expect-error Only what every client has: a mirror has no `retry`. +void client.retry(); +// Effect's fallback is a full client, with an `unknown` user. +declare const effectClient: RegisteredAuth; +const fallback: AuthClient = effectClient; +void [state, user, notState, fallback]; +void Auth.layer(auth); + +// Until the Router is registered, its client is `never`. +const routerClient: never = router.useAuthClient(); +void routerClient; diff --git a/tests/consumer.ts b/tests/consumer.ts index 6e97c5c..22daf2e 100644 --- a/tests/consumer.ts +++ b/tests/consumer.ts @@ -50,6 +50,7 @@ import { routerJar, type RouterContextLike, } from "../dist/react-router/server.js"; +import * as react from "../dist/react/index.js"; import { createAuthHooks, useMirrorAuth, @@ -64,7 +65,9 @@ import { connectAuth, requireSession, SessionOutlet, - useRouterAuth, + useAuth, + useAuthClient, + type RouterAuth, } from "../dist/tanstack-router/index.js"; import { connectSession, loadSession } from "../dist/tanstack-start/index.js"; import { startJar } from "../dist/tanstack-start/server.js"; @@ -88,7 +91,8 @@ declare module "@tanstack/react-router" { } } -declare module "../dist/effect/index.js" { +// One registration types the hooks from `./react` and the Effect service. +declare module "../dist/index.js" { interface Register { auth: typeof auth; } @@ -119,10 +123,33 @@ void [fakeFetch, plainFetch, asFetch, asKyFetch, asOpenApiFetch]; // @ts-expect-error: a path is required. void authFetch(); -// Provider-free hooks typed by the registered Router. -const { useAuth, useAuthClient } = createAuthHooks({ - useClient: useRouterAuth, -}); +// TanStack Router's hooks, typed by the registered Router. +const routerClient: typeof auth = useAuthClient(); +const routerAuth: RouterAuth = routerClient; +void routerAuth; +// The hooks from `./react`, typed by the registered client. +const registeredClient: typeof auth = react.useAuthClient(); +const registeredEmail: string | undefined = react.useAuth( + (state) => state.user?.email, +); +const registeredState: AuthState> = react.useAuth(); +void [registeredClient, registeredEmail, registeredState]; +react.AuthProvider({ client: auth }); +// @ts-expect-error User fields come from the registered client's schema. +react.useAuth((state) => state.user?.missing); +// @ts-expect-error Without a selector, it returns the state, whatever is asked. +const notState: string = react.useAuth(); +// @ts-expect-error Without a selector, it takes no type argument. +react.useAuth(); +// @ts-expect-error The router's hook returns the state too. +const notRouterState: string = useAuth(); +void [notState, notRouterState]; +// The rest of `createAuthHooks`, for an app with several clients. +const fromRouter = createAuthHooks({ useClient: useAuthClient }); +const routerEmail: string | undefined = fromRouter.useAuth( + (state) => state.user?.email, +); +void routerEmail; // Hooks for an explicit client type, with a provider. const provided = createAuthHooks(); provided.AuthProvider({ client: auth }); @@ -133,6 +160,8 @@ const otherAuth = createAuth({ }); // @ts-expect-error The provider takes the client these hooks were made for. provided.AuthProvider({ client: otherAuth }); +// @ts-expect-error So does the registered one. +react.AuthProvider({ client: otherAuth }); SessionOutlet({ pending: "Checking session…" }); async function guard() { diff --git a/tests/examples.test.ts b/tests/examples.test.ts index 6e6ed9e..b599c73 100644 --- a/tests/examples.test.ts +++ b/tests/examples.test.ts @@ -8,9 +8,11 @@ const examples = join(import.meta.dirname, "..", "examples"); // Each example app stands alone, so these files are copies rather than // imports. Edit one, then copy it to the rest. const copies = { - "the UI": [ + "the TanStack Router UI": [ "tanstack-router/src/ui.tsx", "tanstack-start-spa/src/ui.tsx", + ], + "the React Router UI": [ "react-router-declarative/src/ui.tsx", "react-router-data/src/ui.tsx", "react-router-framework-spa/app/ui.tsx", @@ -20,12 +22,6 @@ const copies = { "react-router-declarative/src/auth.ts", "react-router-framework-spa/app/auth.ts", ], - "the TanStack Router hooks": [ - "tanstack-router/src/hooks.ts", - "tanstack-start-spa/src/hooks.ts", - "tanstack-start-spa-effetch/src/hooks.ts", - "tanstack-start-ssr/src/hooks.ts", - ], "the TanStack Router guarded layout": [ "tanstack-router/src/routes/_authenticated.tsx", "tanstack-start-spa/src/routes/_authenticated.tsx", @@ -51,11 +47,6 @@ const copies = { "tanstack-start-spa/src/start.ts", "tanstack-start-spa-effetch/src/start.ts", ], - "the React Router hooks": [ - "react-router-declarative/src/hooks.ts", - "react-router-data/src/hooks.ts", - "react-router-framework-spa/app/hooks.ts", - ], "the DummyJSON address": [ "tanstack-start-ssr/src/auth/api.ts", "next-app/lib/auth/api.ts", diff --git a/tests/package.test.ts b/tests/package.test.ts index b3f3426..ad0691b 100644 --- a/tests/package.test.ts +++ b/tests/package.test.ts @@ -14,7 +14,13 @@ import { Auth, AuthFailure } from "@monarcode/session-kit/effect"; import { sessionBearer } from "@monarcode/session-kit/effetch"; import { createAuthFetch } from "@monarcode/session-kit/http"; import { nextJar, proxyJar } from "@monarcode/session-kit/next"; -import { createAuthHooks, useMirrorAuth } from "@monarcode/session-kit/react"; +import { + AuthProvider, + createAuthHooks, + useAuth, + useAuthClient, + useMirrorAuth, +} from "@monarcode/session-kit/react"; import { requireSession as requireLoaderSession, SessionOutlet as RouterSessionOutlet, @@ -30,7 +36,8 @@ import { redirectIfSignedIn, requireSession, SessionOutlet, - useRouterAuth, + useAuth as useRouterState, + useAuthClient as useRouterClient, } from "@monarcode/session-kit/tanstack-router"; import { connectSession, @@ -55,11 +62,15 @@ test("all public entry points import without browser globals", () => { proxyJar, useMirrorAuth, createAuthHooks, + AuthProvider, + useAuth, + useAuthClient, connectAuth, requireSession, redirectIfSignedIn, SessionOutlet, - useRouterAuth, + useRouterState, + useRouterClient, requireLoaderSession, RouterSessionOutlet, useAuthRevalidation, @@ -161,6 +172,6 @@ test("TanStack Router declarations retain consumer Router registration", async ( "utf8", ); assert.match(declarations, /Register extends/); - assert.match(declarations, /useRouterAuth\(\): RegisteredAuth/); - assert.doesNotMatch(declarations, /useRouterAuth\(\): any/); + assert.match(declarations, /useAuthClient\(\): RouterAuth/); + assert.doesNotMatch(declarations, /useAuthClient\(\): any/); }); diff --git a/tests/react.test.ts b/tests/react.test.ts index 10e3a03..da356ed 100644 --- a/tests/react.test.ts +++ b/tests/react.test.ts @@ -42,8 +42,9 @@ beforeEach(async () => { }); /** - * Hooks for `auth` and a way to render under them, either through - * `AuthProvider` or provider-free from Router context. + * Hooks for `auth` and a way to render under them: through an `AuthProvider` + * from `createAuthHooks`, through `./react`'s registered one, or from Router + * context with `./tanstack-router`'s hooks. */ type Setup = { hooks: Pick, "useAuth" | "useAuthClient">; @@ -58,17 +59,28 @@ const setups: Record Setup> = { wrap: (child) => h(hooks.AuthProvider, { client: auth }, child), }; }, + registered(auth) { + return { + // The tests register no client, so the types are the unregistered ones. + hooks: { + useAuth: binding.useAuth, + useAuthClient: binding.useAuthClient, + } as unknown as Setup["hooks"], + wrap: (child) => h(binding.AuthProvider, { client: auth }, child), + }; + }, router(auth) { const router = routerModule.createRouter({ routeTree: routerModule.createRootRoute({}), context: { auth }, history: routerModule.createMemoryHistory({ initialEntries: ["/"] }), }); - const hooks = binding.createAuthHooks({ - useClient: routerBinding.useRouterAuth as () => Client, - }); return { - hooks, + // The tests register no Router, so the types are `never`. + hooks: { + useAuth: routerBinding.useAuth, + useAuthClient: routerBinding.useAuthClient, + } as unknown as Setup["hooks"], wrap: (child) => h(routerModule.RouterContextProvider, { router: router as AnyRouter, @@ -348,42 +360,55 @@ test("AuthProvider mounts its client while rendered", async () => { assert.equal(mounted, 0); }); -test("hooks without a provider explain what is missing", async () => { - const { useAuth } = binding.createAuthHooks(); - function Status() { - return h( - "output", - null, - useAuth((state) => state.status), +for (const [kind, useAuth, message] of [ + [ + "createAuthHooks", + () => binding.createAuthHooks().useAuth, + /Render AuthProvider/, + ], + ["registered", () => binding.useAuth, /Render AuthProvider/], + [ + "useClient", + () => + binding.createAuthHooks({ + useClient: () => null as unknown as Client, + }).useAuth, + /useClient did not return an auth client/, + ], +] as const) + test(`hooks without a client explain what is missing (${kind})`, async () => { + const useStatus = useAuth() as AuthHooks["useAuth"]; + function Status() { + return h( + "output", + null, + useStatus((state) => state.status), + ); + } + const errors: unknown[] = []; + const onError = (event: ErrorEvent) => { + errors.push(event.error); + event.preventDefault(); + }; + dom.window.addEventListener("error", onError); + const consoleError = console.error; + console.error = () => {}; + try { + await render(h(Status)).catch((error) => errors.push(error)); + } finally { + console.error = consoleError; + dom.window.removeEventListener("error", onError); + } + assert.ok( + errors.some((error) => message.test((error as Error)?.message ?? "")), ); - } - const errors: unknown[] = []; - const onError = (event: ErrorEvent) => { - errors.push(event.error); - event.preventDefault(); - }; - dom.window.addEventListener("error", onError); - const consoleError = console.error; - console.error = () => {}; - try { - await render(h(Status)).catch((error) => errors.push(error)); - } finally { - console.error = consoleError; - dom.window.removeEventListener("error", onError); - } - assert.ok( - errors.some((error) => - /Render AuthProvider/.test((error as Error)?.message ?? ""), - ), - ); -}); + }); test("SessionOutlet keeps child routes through profile updates and swaps them on account changes", async () => { const auth = newClient(); await signIn(auth); - const { useAuth } = binding.createAuthHooks({ - useClient: routerBinding.useRouterAuth as () => Client, - }); + const useAuth = + routerBinding.useAuth as unknown as AuthHooks["useAuth"]; let homeMounts = 0; function Home() { const email = useAuth((state) => state.user?.email); diff --git a/tests/tsconfig.unregistered.bundler.json b/tests/tsconfig.unregistered.bundler.json new file mode 100644 index 0000000..9c474ed --- /dev/null +++ b/tests/tsconfig.unregistered.bundler.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.bundler.json", + "include": ["consumer-unregistered.ts"] +} diff --git a/tests/tsconfig.unregistered.json b/tests/tsconfig.unregistered.json new file mode 100644 index 0000000..dfc8376 --- /dev/null +++ b/tests/tsconfig.unregistered.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "include": ["consumer-unregistered.ts"] +} From 6bc042a27491b535499b1fe5a432df6d7a99c805 Mon Sep 17 00:00:00 2001 From: monarcode Date: Fri, 13 Nov 2026 22:33:34 +0100 Subject: [PATCH 04/26] feat(server)!: one request-scoped session object, with startAuth, routerAuth, SessionOf and UserOf --- CHANGELOG.md | 33 ++ examples/next-app/lib/auth/client.ts | 7 +- .../app/auth/client.ts | 7 +- .../app/auth/middleware.server.ts | 13 +- .../app/auth/session.server.ts | 7 + .../react-router-framework-ssr/app/root.tsx | 5 +- .../app/routes/auth.credentials.ts | 9 +- .../app/routes/auth.session.ts | 8 +- .../app/routes/home.tsx | 9 +- .../app/routes/login.tsx | 8 +- .../tanstack-start-ssr/src/auth/functions.ts | 20 +- .../tanstack-start-ssr/src/auth/server.ts | 9 +- examples/tanstack-start-ssr/src/start.ts | 5 +- site/content/docs/(latest)/effect.mdx | 91 ++-- site/content/docs/(latest)/reference/core.mdx | 8 + .../docs/(latest)/reference/effect.mdx | 2 +- site/content/docs/(latest)/reference/http.mdx | 2 +- .../content/docs/(latest)/reference/index.mdx | 4 +- .../reference/react-router-server.mdx | 8 +- .../docs/(latest)/reference/server.mdx | 4 +- .../reference/tanstack-start-server.mdx | 6 +- .../docs/(latest)/server-rendering/index.mdx | 24 +- .../server-rendering/server-sessions.mdx | 74 ++-- site/content/docs/(latest)/setups/next.mdx | 8 +- .../docs/(latest)/setups/react-router-ssr.mdx | 97 ++--- .../docs/(latest)/setups/tanstack-start.mdx | 52 +-- src/core/infer.ts | 49 +++ src/core/request-session.ts | 18 + src/effect/auth.ts | 88 ++-- src/effetch/index.ts | 4 +- src/http/index.ts | 2 +- src/index.ts | 1 + src/react-router/server.ts | 81 +++- src/server/auth.ts | 399 +++++++++++------- src/server/cookies.ts | 4 +- src/tanstack-start/server.ts | 58 ++- tests/consumer.ts | 67 ++- tests/effect.test.ts | 6 +- tests/package.test.ts | 8 +- tests/react-router-server.test.ts | 28 ++ tests/server.test.ts | 54 +++ tests/tanstack-start.test.ts | 133 +++++- 42 files changed, 1072 insertions(+), 448 deletions(-) create mode 100644 src/core/infer.ts create mode 100644 src/core/request-session.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index e8fde21..26ad47d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,31 @@ `useAuthClient`, which read the client from Router context and are typed by the Router you register. They need no `AuthProvider` and no registration of their own. +- One request's session on the server, without passing its cookie jar. + `startAuth(serverAuth)` in `@monarcode/session-kit/tanstack-start/server` + finds the request on each call, so it's made once, at module level, and + one `createAuthFetch` over it serves every request. + `routerAuth(serverAuth)` in `@monarcode/session-kit/react-router/server` + takes the route's `context`. The guides use these. The jar-first methods + stay, for servers without an adapter. + + ```ts + // Before + await serverAuth.signIn(startJar(), tokens); + // After + export const session = startAuth(serverAuth); + await session.signIn(tokens); + ``` + +- `serverAuth.forRequest(jar)` has every method now: `signIn`, + `updateUser`, `refreshIfDue` and `clientCredentials` join the rest. +- `SessionOf` and `UserOf` in `@monarcode/session-kit` give the + session and user types of any client: one from `createAuth`, + `createMirrorAuth` or `createServerAuth`, or a request's session. + + ```ts + type AppSession = SessionOf; // { sessionId, user } + ``` ### Changed @@ -133,6 +158,14 @@ it throws when there's none. A hooks file made with `createAuthHooks({ useClient: useRouterAuth })` can go: import `useAuth` and `useAuthClient` from `@monarcode/session-kit/tanstack-router` instead. +- **Breaking:** `RequestAuth` takes the user `signIn` accepts as a second + type parameter, as `ServerAuth` does: `RequestAuth`, or + `RequestAuth` when the user comes from the access token. Most + apps write `SessionOf` or `UserOf` instead. +- Effect's `Auth.layer` binds a session from `startAuth` to the request + that's current when it's called, and throws `INVALID_OPTIONS` outside + one. `Auth.signIn` and `Auth.updateUser` still die on a request's session, + and now point at its own `signIn` and `updateUser`. - The guides moved to the documentation site, [session-kit.pages.dev](https://session-kit.pages.dev), with an API diff --git a/examples/next-app/lib/auth/client.ts b/examples/next-app/lib/auth/client.ts index 68f1ae7..a89e8a7 100644 --- a/examples/next-app/lib/auth/client.ts +++ b/examples/next-app/lib/auth/client.ts @@ -1,6 +1,7 @@ import { createMirrorAuth, type ClientCredentials, + type SessionOf, } from "@monarcode/session-kit"; import { @@ -8,10 +9,10 @@ import { signInAction, signOutAction, } from "../../app/actions"; +// Types only: erased from the browser's bundle. +import type { serverAuth } from "./server"; -export type AppSession = NonNullable< - Awaited> ->; +export type AppSession = SessionOf; /** Asks the route handler for the access token, or renews `rejected`. */ async function credentials(rejected?: object) { diff --git a/examples/react-router-framework-ssr/app/auth/client.ts b/examples/react-router-framework-ssr/app/auth/client.ts index eac0160..f2ab864 100644 --- a/examples/react-router-framework-ssr/app/auth/client.ts +++ b/examples/react-router-framework-ssr/app/auth/client.ts @@ -1,12 +1,13 @@ import { createMirrorAuth, type ClientCredentials, - type Session, + type SessionOf, } from "@monarcode/session-kit"; -import type { User } from "./backend"; +// Types only: erased from the browser's bundle. +import type { serverAuth } from "./session.server"; -export type AppSession = Session; +export type AppSession = SessionOf; /** Calls one of the resource routes in `routes/auth.*.ts`. */ async function call(method: "GET" | "POST", path: string, body?: object) { diff --git a/examples/react-router-framework-ssr/app/auth/middleware.server.ts b/examples/react-router-framework-ssr/app/auth/middleware.server.ts index d07b597..d2a7081 100644 --- a/examples/react-router-framework-ssr/app/auth/middleware.server.ts +++ b/examples/react-router-framework-ssr/app/auth/middleware.server.ts @@ -1,11 +1,8 @@ import { redirect, type MiddlewareFunction } from "react-router"; -import { - cookieJarMiddleware, - routerJar, -} from "@monarcode/session-kit/react-router/server"; +import { cookieJarMiddleware } from "@monarcode/session-kit/react-router/server"; -import { serverAuth } from "./session.server"; +import { auth } from "./session.server"; /** * Refreshes access that is about to expire before loaders and actions read @@ -17,8 +14,8 @@ const refreshSession: MiddlewareFunction = async ( next, ) => { // The example's tokens live a minute: refresh in their last 15 seconds. - await serverAuth - .refreshIfDue(routerJar(context), { within: 15 }) + await auth(context) + .refreshIfDue({ within: 15 }) .catch(() => {}); const response = await next(); // Every page and resource route here depends on who is signed in. A @@ -43,7 +40,7 @@ export const requireSession: MiddlewareFunction = async ({ context, url, }) => { - if (!(await serverAuth.getSession(routerJar(context)))) + if (!(await auth(context).getSession())) throw redirect( `/login?redirectTo=${encodeURIComponent(url.pathname + url.search)}`, ); diff --git a/examples/react-router-framework-ssr/app/auth/session.server.ts b/examples/react-router-framework-ssr/app/auth/session.server.ts index dd4c1e6..546e2ab 100644 --- a/examples/react-router-framework-ssr/app/auth/session.server.ts +++ b/examples/react-router-framework-ssr/app/auth/session.server.ts @@ -1,5 +1,6 @@ // Holds the secret and the tokens: the `.server` name keeps it out of the // browser's bundle, and the build fails if browser code imports it. +import { routerAuth } from "@monarcode/session-kit/react-router/server"; import { createServerAuth } from "@monarcode/session-kit/server"; import { refresh, userSchema } from "./backend"; @@ -31,3 +32,9 @@ export const serverAuth = createServerAuth({ // `react-router dev` serves plain http; Safari drops Secure cookies there. cookie: { secure: !import.meta.env.DEV }, }); + +/** + * The session of the request React Router is handling, by its `context`: + * `auth(context).getSession()` in a loader, action or middleware. + */ +export const auth = routerAuth(serverAuth); diff --git a/examples/react-router-framework-ssr/app/root.tsx b/examples/react-router-framework-ssr/app/root.tsx index 577e6aa..d748742 100644 --- a/examples/react-router-framework-ssr/app/root.tsx +++ b/examples/react-router-framework-ssr/app/root.tsx @@ -12,11 +12,10 @@ import { } from "react-router"; import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react"; -import { routerJar } from "@monarcode/session-kit/react-router/server"; import { createAppAuth, type AppAuth } from "./auth/client"; import { sessionMiddleware } from "./auth/middleware.server"; -import { serverAuth } from "./auth/session.server"; +import { auth } from "./auth/session.server"; // Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` // with this client. @@ -30,7 +29,7 @@ export const middleware = sessionMiddleware; /** Who is signed in, from the cookie. Holds no tokens. */ export async function loader({ context }: LoaderFunctionArgs) { - return { session: await serverAuth.getSession(routerJar(context)) }; + return { session: await auth(context).getSession() }; } export function Layout({ children }: { children: ReactNode }) { diff --git a/examples/react-router-framework-ssr/app/routes/auth.credentials.ts b/examples/react-router-framework-ssr/app/routes/auth.credentials.ts index 444d489..f7f5ff1 100644 --- a/examples/react-router-framework-ssr/app/routes/auth.credentials.ts +++ b/examples/react-router-framework-ssr/app/routes/auth.credentials.ts @@ -1,9 +1,8 @@ import type { ActionFunctionArgs } from "react-router"; -import { routerJar } from "@monarcode/session-kit/react-router/server"; import { z } from "zod"; -import { serverAuth } from "../auth/session.server"; +import { auth } from "../auth/session.server"; const rejected = z.object({ sessionId: z.string(), accessToken: z.string() }); @@ -16,11 +15,11 @@ const rejected = z.object({ sessionId: z.string(), accessToken: z.string() }); export async function action({ request, context }: ActionFunctionArgs) { if (request.headers.get("sec-fetch-site") !== "same-origin") return new Response(null, { status: 403 }); - const jar = routerJar(context); + const session = auth(context); const body = rejected.safeParse(await request.json().catch(() => null)); return Response.json( body.success - ? await serverAuth.clientCredentials.renew(jar, body.data) - : await serverAuth.clientCredentials.get(jar), + ? await session.clientCredentials.renew(body.data) + : await session.clientCredentials.get(), ); } diff --git a/examples/react-router-framework-ssr/app/routes/auth.session.ts b/examples/react-router-framework-ssr/app/routes/auth.session.ts index 2dedf40..9f8be42 100644 --- a/examples/react-router-framework-ssr/app/routes/auth.session.ts +++ b/examples/react-router-framework-ssr/app/routes/auth.session.ts @@ -1,12 +1,10 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router"; -import { routerJar } from "@monarcode/session-kit/react-router/server"; - -import { serverAuth } from "../auth/session.server"; +import { auth } from "../auth/session.server"; /** Who is signed in, from the cookie, for the client's `revalidate`. */ export async function loader({ context }: LoaderFunctionArgs) { - return Response.json(await serverAuth.getSession(routerJar(context))); + return Response.json(await auth(context).getSession()); } /** @@ -16,6 +14,6 @@ export async function loader({ context }: LoaderFunctionArgs) { export async function action({ request, context }: ActionFunctionArgs) { if (request.headers.get("sec-fetch-site") !== "same-origin") return new Response(null, { status: 403 }); - await serverAuth.signOut(routerJar(context)); + await auth(context).signOut(); return Response.json(null); } diff --git a/examples/react-router-framework-ssr/app/routes/home.tsx b/examples/react-router-framework-ssr/app/routes/home.tsx index a4ced29..bbe8c81 100644 --- a/examples/react-router-framework-ssr/app/routes/home.tsx +++ b/examples/react-router-framework-ssr/app/routes/home.tsx @@ -1,21 +1,20 @@ import { useLoaderData, type LoaderFunctionArgs } from "react-router"; -import { routerJar } from "@monarcode/session-kit/react-router/server"; import { z } from "zod"; import { API } from "../auth/api"; -import { serverAuth } from "../auth/session.server"; +import { auth } from "../auth/session.server"; import { Profile } from "../ui"; /** Calls DummyJSON's `auth/me` from the server, with the cookie's token. */ export async function loader({ context }: LoaderFunctionArgs) { - const jar = routerJar(context); - const credentials = await serverAuth.credentials.get(jar); + const session = auth(context); + const credentials = await session.credentials.get(); if (!credentials) return { email: "Signed out" }; let response = await me(credentials.accessToken); if (response.status === 401) { // Refreshes once, then tries again. - const renewed = await serverAuth.credentials.renew(jar, credentials); + const renewed = await session.credentials.renew(credentials); if (!renewed) return { email: "Signed out" }; response = await me(renewed.accessToken); } diff --git a/examples/react-router-framework-ssr/app/routes/login.tsx b/examples/react-router-framework-ssr/app/routes/login.tsx index e1352a2..9c74e39 100644 --- a/examples/react-router-framework-ssr/app/routes/login.tsx +++ b/examples/react-router-framework-ssr/app/routes/login.tsx @@ -7,15 +7,14 @@ import { } from "react-router"; import { safeReturnTo } from "@monarcode/session-kit"; -import { routerJar } from "@monarcode/session-kit/react-router/server"; import { login } from "../auth/backend"; -import { serverAuth } from "../auth/session.server"; +import { auth } from "../auth/session.server"; import { LoginForm } from "../ui"; /** Signed in, before or after the form: the server sends the user on. */ export async function loader({ context, url }: LoaderFunctionArgs) { - if (await serverAuth.getSession(routerJar(context))) + if (await auth(context).getSession()) throw redirect(safeReturnTo(url.searchParams.get("redirectTo"))); return null; } @@ -28,8 +27,7 @@ export async function loader({ context, url }: LoaderFunctionArgs) { export async function action({ request, context, url }: ActionFunctionArgs) { const form = await request.formData(); try { - await serverAuth.signIn( - routerJar(context), + await auth(context).signIn( await login( String(form.get("username")), String(form.get("password")), diff --git a/examples/tanstack-start-ssr/src/auth/functions.ts b/examples/tanstack-start-ssr/src/auth/functions.ts index 8171c47..32125ab 100644 --- a/examples/tanstack-start-ssr/src/auth/functions.ts +++ b/examples/tanstack-start-ssr/src/auth/functions.ts @@ -1,50 +1,48 @@ -import { startJar } from "@monarcode/session-kit/tanstack-start/server"; import { createServerFn } from "@tanstack/react-start"; import { z } from "zod"; import { API } from "./api"; import { login } from "./backend"; -import { serverAuth } from "./server"; +import { session } from "./server"; // Each handler runs on the server; Start's compiler replaces it with a fetch -// in the browser, and leaves `startJar` and `serverAuth` out of that bundle. +// in the browser, and leaves `session` out of that bundle. /** Who is signed in, from the cookie. Holds no tokens. */ export const getSessionFn = createServerFn().handler(() => - serverAuth.getSession(startJar()), + session.getSession(), ); /** Signs in with DummyJSON on the server and sets the cookie. */ export const signInFn = createServerFn({ method: "POST" }) .validator(z.object({ username: z.string(), password: z.string() })) .handler(async ({ data }) => - serverAuth.signIn(startJar(), await login(data.username, data.password)), + session.signIn(await login(data.username, data.password)), ); /** Clears the cookie. */ export const signOutFn = createServerFn({ method: "POST" }).handler(() => - serverAuth.signOut(startJar()), + session.signOut(), ); /** The access token for the browser's own requests, never the refresh token. */ export const getCredentialsFn = createServerFn({ method: "POST" }).handler(() => - serverAuth.clientCredentials.get(startJar()), + session.clientCredentials.get(), ); /** New access after DummyJSON rejected the browser's token. */ export const renewCredentialsFn = createServerFn({ method: "POST" }) .validator(z.object({ sessionId: z.string(), accessToken: z.string() })) - .handler(({ data }) => serverAuth.clientCredentials.renew(startJar(), data)); + .handler(({ data }) => session.clientCredentials.renew(data)); /** Calls DummyJSON's `auth/me` from the server, with the cookie's token. */ export const getProfileFn = createServerFn().handler(async () => { - const jar = startJar(); - const credentials = await serverAuth.credentials.get(jar); + const credentials = await session.credentials.get(); if (!credentials) return { email: "Signed out" }; let response = await me(credentials.accessToken); if (response.status === 401) { // Refreshes once, then tries again. - const renewed = await serverAuth.credentials.renew(jar, credentials); + const renewed = await session.credentials.renew(credentials); if (!renewed) return { email: "Signed out" }; response = await me(renewed.accessToken); } diff --git a/examples/tanstack-start-ssr/src/auth/server.ts b/examples/tanstack-start-ssr/src/auth/server.ts index e6a21a0..5ae3b09 100644 --- a/examples/tanstack-start-ssr/src/auth/server.ts +++ b/examples/tanstack-start-ssr/src/auth/server.ts @@ -1,6 +1,7 @@ // Holds the secret and the tokens: Start refuses to bundle it for the browser. import "@tanstack/react-start/server-only"; import { createServerAuth } from "@monarcode/session-kit/server"; +import { startAuth } from "@monarcode/session-kit/tanstack-start/server"; import { refresh, userSchema } from "./backend"; @@ -21,7 +22,7 @@ function sessionSecret(): string { * `clientCredentials`, the browser can ask for the access token too, through * the server functions in `functions.ts`; the refresh token stays here. */ -export const serverAuth = createServerAuth({ +const serverAuth = createServerAuth({ name: "session-kit-example", user: userSchema, secret: sessionSecret(), @@ -30,3 +31,9 @@ export const serverAuth = createServerAuth({ // `vite dev` serves plain http; Safari drops Secure cookies there. cookie: { secure: !import.meta.env.DEV }, }); + +/** + * The session of the request Start is handling: each call finds it, so one + * object serves every request. + */ +export const session = startAuth(serverAuth); diff --git a/examples/tanstack-start-ssr/src/start.ts b/examples/tanstack-start-ssr/src/start.ts index 05942ed..f07e3a3 100644 --- a/examples/tanstack-start-ssr/src/start.ts +++ b/examples/tanstack-start-ssr/src/start.ts @@ -1,4 +1,3 @@ -import { startJar } from "@monarcode/session-kit/tanstack-start/server"; import { createCsrfMiddleware, createMiddleware, @@ -6,7 +5,7 @@ import { } from "@tanstack/react-start"; import { setResponseHeader } from "@tanstack/react-start/server"; -import { serverAuth } from "./auth/server"; +import { session } from "./auth/server"; /** * Refreshes access that is about to expire before routes and server @@ -19,7 +18,7 @@ const sessionMiddleware = createMiddleware({ type: "request" }).server( // Every page and server function here depends on who is signed in. setResponseHeader("Cache-Control", "private, no-store"); // The example's tokens live a minute: refresh in their last 15 seconds. - await serverAuth.refreshIfDue(startJar(), { within: 15 }).catch(() => {}); + await session.refreshIfDue({ within: 15 }).catch(() => {}); return next(); }, ); diff --git a/site/content/docs/(latest)/effect.mdx b/site/content/docs/(latest)/effect.mdx index 415820a..d3419e9 100644 --- a/site/content/docs/(latest)/effect.mdx +++ b/site/content/docs/(latest)/effect.mdx @@ -490,9 +490,10 @@ README describes. Make it on the server over that request's session, as With server rendering, server functions, actions and route handlers run Effects too, and the session they read is the cookie the server keeps ([Server sessions](/docs/server-rendering/server-sessions)). -`serverAuth.forRequest(jar)` is one request's session, and `Auth.layer` takes -it, so `Auth.session`, `Auth.credentials` and `sessionBearer` work there: -`sessionBearer` sends the cookie's token, and saves a renewed one after a 401. +Each framework's adapter gives one request's session (`RequestAuth`), and +`Auth.layer` takes it, so `Auth.session`, `Auth.credentials` and +`sessionBearer` work there: `sessionBearer` sends the cookie's token, and +saves a renewed one after a 401. On the server, the session comes from `createServerAuth`, with the user schema the app registers and the same refresh. The server's files build on @@ -521,6 +522,9 @@ export const serverAuth = createServerAuth({ secret, refresh: ({ refreshToken, signal }) => refreshSession(refreshToken, signal), }); + +/** One request's session, as your framework's adapter gives it. */ +export type ServerSession = ReturnType; ``` A request's session belongs to that request, and so does everything that @@ -529,30 +533,29 @@ user: ```ts title="src/server/run.ts" import { Auth } from "@monarcode/session-kit/effect"; -import type { CookieJar } from "@monarcode/session-kit/server"; import * as Effect from "effect/Effect"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as Layer from "effect/Layer"; import * as ManagedRuntime from "effect/ManagedRuntime"; import { type ApiClient, ApiClientLive } from "../api.js"; -import { serverAuth } from "./auth.js"; +import type { ServerSession } from "./auth.js"; /** Built once: what belongs to no user. */ const serverRuntime = ManagedRuntime.make(FetchHttpClient.layer); /** Built per request: its session, and the API client that uses it. */ -export const requestLayer = (jar: CookieJar) => - ApiClientLive.pipe( - Layer.provideMerge(Auth.layer(serverAuth.forRequest(jar))), - ); +export const requestLayer = (session: ServerSession) => + ApiClientLive.pipe(Layer.provideMerge(Auth.layer(session))); -/** Runs `effect` with the session of the request `jar` belongs to. */ +/** Runs `effect` with the request's `session`. */ export function runRequest( - jar: CookieJar, + session: ServerSession, effect: Effect.Effect, ): Promise { - return serverRuntime.runPromise(Effect.provide(effect, requestLayer(jar))); + return serverRuntime.runPromise( + Effect.provide(effect, requestLayer(session)), + ); } ``` @@ -561,43 +564,44 @@ doesn't compile until it goes through `runRequest`, and nothing a service keeps outlives its request. Building them is cheap next to the request your API answers. -Each framework's adapter gives the jar, in the server function, action or -handler: +Each framework's adapter gives the request's session, in the server +function, action or handler: ```ts title="src/server/profile.ts" -import type { CookieJar } from "@monarcode/session-kit/server"; - import { currentUser } from "../user.js"; +import type { ServerSession } from "./auth.js"; import { runRequest } from "./run.js"; -// TanStack Start: startJar(). React Router: routerJar(context). -// Next.js: nextJar(await cookies(), { writable: true }). -export const profileFor = (jar: CookieJar) => runRequest(jar, currentUser); +// TanStack Start: startAuth(serverAuth). React Router: +// routerAuth(serverAuth)(context). Next.js: +// serverAuth.forRequest(nextJar(await cookies(), { writable: true })). +export const profileFor = (session: ServerSession) => + runRequest(session, currentUser); ``` ### Sign in on the server -`Auth.signIn` and `Auth.updateUser` aren't available on a request's session: -the user comes in through `serverAuth`. Ask your backend with an Effect, then +On a request's session, sign in with its own `signIn`, which takes the +tokens and the user, and update the user with its own `updateUser`. +`Auth.signIn` and `Auth.updateUser` take what the browser client's methods +do, so they aren't available there. Ask your backend with an Effect, then seal what it returns: ```ts title="src/server/sign-in.ts" -import type { CookieJar } from "@monarcode/session-kit/server"; - import { login } from "../user.js"; -import { serverAuth } from "./auth.js"; +import type { ServerSession } from "./auth.js"; import { runRequest } from "./run.js"; export async function signIn( - jar: CookieJar, + session: ServerSession, username: string, password: string, ) { const { accessToken, refreshToken, ...user } = await runRequest( - jar, + session, login(username, password), ); - return serverAuth.signIn(jar, { accessToken, refreshToken, user }); + return session.signIn({ accessToken, refreshToken, user }); } ``` @@ -608,15 +612,15 @@ server, over that request's layer, and dispose of it once the page is sent: ```ts title="src/server/query-client.ts" import { QueryClient } from "@monarcode/effetch-query"; -import type { CookieJar } from "@monarcode/session-kit/server"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as Layer from "effect/Layer"; +import type { ServerSession } from "./auth.js"; import { requestLayer } from "./run.js"; -export const queryClientFor = (jar: CookieJar) => +export const queryClientFor = (session: ServerSession) => QueryClient.make({ - layer: requestLayer(jar).pipe(Layer.provide(FetchHttpClient.layer)), + layer: requestLayer(session).pipe(Layer.provide(FetchHttpClient.layer)), }); ``` @@ -647,29 +651,30 @@ the mirror client. calls, which call `runRequest`, and TypeScript reports a circular type. For the same reason, the server functions the mirror is made from (its `revalidate`, `signIn` - and `signOut`) read the session with `serverAuth`, not `Auth.session`. + and `signOut`) read the request's session directly, not `Auth.session`. - **Keep a request's layer off a shared `memoMap`,** such as the runtime's or one passed to `QueryClient.make`. Layers are shared by identity there, so overlapping requests can get one build: a service that keeps `Auth` when it's built would then serve one request's session to another. -- **Read-only jars,** such as a Next.js Server Component's: `Auth.session` - returns the cookie's session as it is, while `Auth.credentials` and - `sessionBearer` fail with `REFRESH_FAILED` once access has expired, and - after a 401, which can't be renewed there unless the same request's - writable jar already renewed it. Refresh in middleware or a proxy first, - with `serverAuth.refreshIfDue`, as the framework guides do. Sign out in an - action or route handler. -- **Only `Auth`'s Effects.** A request's session has only what `Auth`'s - Effects use, so don't reach for other client methods through `Auth.use` - there. +- **Requests that can't set cookies,** such as a Next.js Server + Component's: `Auth.session` returns the cookie's session as it is, while + `Auth.credentials` and `sessionBearer` fail with `REFRESH_FAILED` once + access has expired, and after a 401, which can't be renewed there unless + the same request already renewed it where it could. Refresh in middleware + or a proxy first, with `refreshIfDue`, as the framework guides do. Sign + out in an action or route handler. +- **Only `Auth`'s Effects.** A request's session isn't your browser client, + so don't reach for client methods through `Auth.use` there. +- **`Auth.layer` binds a session from `startAuth`** to the request that's + current when it's called, so call it per request, as `requestLayer` does. ## What stays on the client `Auth` covers what Effect code does with a session: reading it, signing in and out, and updating the user. Everything else stays on the client, which React and the routers already drive: `lock` and `unlock`, `refresh` and -`retry`, `mount`, and the client's options. On the server, signing in and -updating the user are `serverAuth`'s. +`retry`, `mount`, and the client's options. On the server, a request's +session signs in and updates the user. ## Next steps diff --git a/site/content/docs/(latest)/reference/core.mdx b/site/content/docs/(latest)/reference/core.mdx index 622dec9..f8b2366 100644 --- a/site/content/docs/(latest)/reference/core.mdx +++ b/site/content/docs/(latest)/reference/core.mdx @@ -204,6 +204,10 @@ Options for [`safeReturnTo`](#safereturnto). Who is signed in: the session ID and the user, from `getSession()`. It holds no tokens, so it's safe to keep in route context or pass around. +### SessionOf + +The session type of a client: what its `getSession` resolves, without `null`. It takes any client: one from `createAuth` or `createMirrorAuth`, the server's from `createServerAuth`, or a request's session from it. + ### SignInInput What `signIn` takes: the [`Tokens`](#tokens), plus the `user` when a schema validates it. With `fromAccessToken` (`I` is `never`), it takes tokens only. @@ -226,6 +230,10 @@ The signed-in user's type, inferred from the `user` option: what `state.user` an The user that `signIn` and `updateUser` accept, inferred from the `user` option. It differs from [`User`](#user) when the schema has defaults or transforms. +### UserOf + +The user type of a client, as [`SessionOf`](#sessionof) finds it: the `user` of its session. + ### UserSource What `createAuth`'s `user` option takes: a schema, such as Zod's, that checks the `user` passed to `signIn`, or [`fromAccessToken`](#fromaccesstoken), which reads the user from the access token. diff --git a/site/content/docs/(latest)/reference/effect.mdx b/site/content/docs/(latest)/reference/effect.mdx index cd7eb63..b53ceca 100644 --- a/site/content/docs/(latest)/reference/effect.mdx +++ b/site/content/docs/(latest)/reference/effect.mdx @@ -27,7 +27,7 @@ The codes an [`AuthFailure`](#authfailure) carries: every `AuthErrorCode` except ### AuthLayerClient -What `Auth.layer` takes. Once you register a client in `Register`, that's your client, or on the server a `serverAuth.forRequest(jar)` view with the same user. Until then, it's any [`AuthServiceClient`](#authserviceclient). +What `Auth.layer` takes. Once you register a client in `Register`, that's your client, or on the server a request's session with the same user (`RequestAuth`). Until then, it's any [`AuthServiceClient`](#authserviceclient). ### AuthServiceClient diff --git a/site/content/docs/(latest)/reference/http.mdx b/site/content/docs/(latest)/reference/http.mdx index 8cf50e0..6a96fa3 100644 --- a/site/content/docs/(latest)/reference/http.mdx +++ b/site/content/docs/(latest)/reference/http.mdx @@ -23,7 +23,7 @@ The `fetch` that [`createAuthFetch`](#createauthfetch) returns. Call it with a p ### AuthFetchClient -The part of an auth client that [`createAuthFetch`](#createauthfetch) uses. A `createAuth` or `createMirrorAuth` client fits, and so does a request's session from `serverAuth.forRequest(jar)`. +The part of an auth client that [`createAuthFetch`](#createauthfetch) uses. A `createAuth` or `createMirrorAuth` client fits, and so does a request's session on the server (`RequestAuth`). ### AuthFetchOptions diff --git a/site/content/docs/(latest)/reference/index.mdx b/site/content/docs/(latest)/reference/index.mdx index 52648d2..2c1333b 100644 --- a/site/content/docs/(latest)/reference/index.mdx +++ b/site/content/docs/(latest)/reference/index.mdx @@ -18,11 +18,11 @@ API. | [`@monarcode/session-kit/react`](/docs/reference/react) | `AuthProvider`, `useAuth`, `useAuthClient`, `createAuthHooks`, `useMirrorAuth`, types | | [`@monarcode/session-kit/tanstack-router`](/docs/reference/tanstack-router) | `connectAuth`, `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuth`, `useAuthClient`, types | | [`@monarcode/session-kit/react-router`](/docs/reference/react-router) | `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuthRevalidation`, types | -| [`@monarcode/session-kit/react-router/server`](/docs/reference/react-router-server) | `cookieJarMiddleware`, `routerJar`, types | +| [`@monarcode/session-kit/react-router/server`](/docs/reference/react-router-server) | `routerAuth`, `cookieJarMiddleware`, `routerJar`, types | | [`@monarcode/session-kit/http`](/docs/reference/http) | `createAuthFetch`, types | | [`@monarcode/session-kit/server`](/docs/reference/server) | `createServerAuth`, types | | [`@monarcode/session-kit/tanstack-start`](/docs/reference/tanstack-start) | `connectSession`, `loadSession` | -| [`@monarcode/session-kit/tanstack-start/server`](/docs/reference/tanstack-start-server) | `startJar` | +| [`@monarcode/session-kit/tanstack-start/server`](/docs/reference/tanstack-start-server) | `startAuth`, `startJar` | | [`@monarcode/session-kit/next`](/docs/reference/next) | `nextJar`, `proxyJar`, types | | [`@monarcode/session-kit/expo`](/docs/reference/expo) | `secureStorage`, `SessionGate`, `rememberDeepLink`, types | | [`@monarcode/session-kit/effect`](/docs/reference/effect) | `Auth`, `AuthFailure`, types | diff --git a/site/content/docs/(latest)/reference/react-router-server.mdx b/site/content/docs/(latest)/reference/react-router-server.mdx index 9dd42e2..13ede8c 100644 --- a/site/content/docs/(latest)/reference/react-router-server.mdx +++ b/site/content/docs/(latest)/reference/react-router-server.mdx @@ -15,12 +15,16 @@ Guide: [React Router with server rendering](/docs/setups/react-router-ssr). Server middleware that gives each request a `CookieJar`, found with [`routerJar`](#routerjar). It sets the cookies written to the jar on the response, redirects and error responses included. +### routerAuth + +Returns a function that gives the session of the request React Router is handling (`RequestAuth`), with every `serverAuth` method and no cookie jar. Call it with `context` in server middleware, loaders and actions, after [`cookieJarMiddleware`](#cookiejarmiddleware). Make it once, at module level. + ### routerJar -The `CookieJar` for the request React Router is handling, to pass to `serverAuth` from `@monarcode/session-kit/server`. Call it with `context` in server middleware, loaders and actions, after [`cookieJarMiddleware`](#cookiejarmiddleware). Every call during one request returns the same jar. +The `CookieJar` for the request React Router is handling, to pass to `serverAuth` from `@monarcode/session-kit/server`. [`routerAuth`](#routerauth) passes it for you. Call it with `context` in server middleware, loaders and actions, after [`cookieJarMiddleware`](#cookiejarmiddleware). Every call during one request returns the same jar. ## Types ### RouterContextLike -The `context` React Router passes to server middleware, loaders and actions in framework mode: a `RouterContextProvider`, one per request. [`routerJar`](#routerjar) and [`cookieJarMiddleware`](#cookiejarmiddleware) find the request's jar by it. It's typed by its shape, so this entry point doesn't depend on React Router's types. +The `context` React Router passes to server middleware, loaders and actions in framework mode: a `RouterContextProvider`, one per request. [`routerAuth`](#routerauth) and [`cookieJarMiddleware`](#cookiejarmiddleware) find the request by it. It's typed by its shape, so this entry point doesn't depend on React Router's types. diff --git a/site/content/docs/(latest)/reference/server.mdx b/site/content/docs/(latest)/reference/server.mdx index 81d161d..65e9a52 100644 --- a/site/content/docs/(latest)/reference/server.mdx +++ b/site/content/docs/(latest)/reference/server.mdx @@ -53,11 +53,11 @@ Options for [`ServerAuth`](#serverauth)'s `refreshIfDue`. ### RequestAuth -One request's session, shaped like a client. Get it from `serverAuth.forRequest(jar)`, and pass it to code that expects a client, such as `createAuthFetch` from `@monarcode/session-kit/http`. Make one per request, never at module level. +One request's session: what [`ServerAuth`](#serverauth) does for a request, without its [`CookieJar`](#cookiejar). `startAuth` from `@monarcode/session-kit/tanstack-start/server` and `routerAuth` from `@monarcode/session-kit/react-router/server` give you one. Elsewhere, `serverAuth.forRequest(jar)` does. ### ServerAuth -The server side of Session kit, from [`createServerAuth`](#createserverauth). It keeps the session in an encrypted cookie. Each method takes the request's [`CookieJar`](#cookiejar), and `forRequest(jar)` gives one request's session shaped like a client ([`RequestAuth`](#requestauth)). +The server side of Session kit, from [`createServerAuth`](#createserverauth). It keeps the session in an encrypted cookie. ### ServerAuthOptions diff --git a/site/content/docs/(latest)/reference/tanstack-start-server.mdx b/site/content/docs/(latest)/reference/tanstack-start-server.mdx index d46da0c..fdf521f 100644 --- a/site/content/docs/(latest)/reference/tanstack-start-server.mdx +++ b/site/content/docs/(latest)/reference/tanstack-start-server.mdx @@ -11,6 +11,10 @@ Guide: [TanStack Start](/docs/setups/tanstack-start). ## Functions +### startAuth + +The session of the request TanStack Start is handling (`RequestAuth`), with every `serverAuth` method and no cookie jar. Each call finds the current request, so make it once, at module level, beside `serverAuth`. + ### startJar -The `CookieJar` for the request TanStack Start is handling, to pass to `serverAuth` from `@monarcode/session-kit/server`. Use it in a server function, request middleware, a server route, or `beforeLoad` and loaders while they run on the server. Every call during one request returns the same jar. +The `CookieJar` for the request TanStack Start is handling, to pass to `serverAuth` from `@monarcode/session-kit/server`. [`startAuth`](#startauth) passes it for you. Use it in a server function, request middleware, a server route, or `beforeLoad` and loaders while they run on the server. Every call during one request returns the same jar. diff --git a/site/content/docs/(latest)/server-rendering/index.mdx b/site/content/docs/(latest)/server-rendering/index.mdx index 96094a8..fed5c68 100644 --- a/site/content/docs/(latest)/server-rendering/index.mdx +++ b/site/content/docs/(latest)/server-rendering/index.mdx @@ -22,9 +22,9 @@ before rendering, so pages never show a "Checking session…" state. session the server rendered. `AuthProvider`, the hooks, and the TanStack Router guards work with it, and sign-ins and sign-outs reach every tab. - **Your server code** signs in and out with your backend and calls your API - with the access token. `serverAuth.forRequest(jar)` gives code written for - a client, such as `createAuthFetch` or Effect's `Auth`, one request's - session. To call your API from the browser too, opt in with + with the access token, through one request's session. It's shaped like a + client, so code written for one, such as `createAuthFetch` or Effect's + `Auth`, takes it. To call your API from the browser too, opt in with `clientCredentials`: page scripts then get the access token in memory, never the refresh token. @@ -37,18 +37,18 @@ server code, as in ## Frameworks -What differs between frameworks is how the cookie jar reaches the engine, and -how the session reaches the browser: +What differs between frameworks is how server code gets a request's +session, and how the session reaches the browser: -| Framework | On the server | In the browser | Setup | -| ------------------------------------- | ----------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------- | -| TanStack Start | `startJar()`, refreshing in request middleware | `connectSession`, `loadSession` | [TanStack Start](/docs/setups/tanstack-start) | -| Next.js 16, App Router | `nextJar(await cookies())`, `proxyJar` in Proxy | `useMirrorAuth` from `@monarcode/session-kit/react` | [Next.js](/docs/setups/next) | -| React Router framework mode, with SSR | `cookieJarMiddleware`, `routerJar(context)` | `useMirrorAuth` from `@monarcode/session-kit/react` | [React Router with server rendering](/docs/setups/react-router-ssr) | +| Framework | On the server | In the browser | Setup | +| ------------------------------------- | --------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------- | +| TanStack Start | `startAuth(serverAuth)`, refreshing in request middleware | `connectSession`, `loadSession` | [TanStack Start](/docs/setups/tanstack-start) | +| Next.js 16, App Router | `nextJar(await cookies())`, `proxyJar` in Proxy | `useMirrorAuth` from `@monarcode/session-kit/react` | [Next.js](/docs/setups/next) | +| React Router framework mode, with SSR | `cookieJarMiddleware`, `routerAuth(serverAuth)` | `useMirrorAuth` from `@monarcode/session-kit/react` | [React Router with server rendering](/docs/setups/react-router-ssr) | Locking isn't available with server rendering. For another server, such as -the Next.js Pages Router, build a `CookieJar` over its cookies and use -`createServerAuth` directly. +the Next.js Pages Router, build a `CookieJar` over its cookies and pass it +to `serverAuth.forRequest(jar)`. ## Next steps diff --git a/site/content/docs/(latest)/server-rendering/server-sessions.mdx b/site/content/docs/(latest)/server-rendering/server-sessions.mdx index 6a4269f..819fb49 100644 --- a/site/content/docs/(latest)/server-rendering/server-sessions.mdx +++ b/site/content/docs/(latest)/server-rendering/server-sessions.mdx @@ -4,7 +4,7 @@ description: How the server keeps the session in every framework, from the cooki --- This page covers what every server-rendered setup shares: the cookie and its -secret, cookie jars, refreshes, sign-out, and limits. Read it once your app +secret, a request's session, refreshes, sign-out, and limits. Read it once your app works, to deploy it. The setup guides show the code: [TanStack Start](/docs/setups/tanstack-start), [Next.js](/docs/setups/next), and [React Router with server rendering](/docs/setups/react-router-ssr). @@ -49,28 +49,44 @@ export const serverAuth = createServerAuth({ Remove `OLD_SESSION_SECRET` once the sessions it sealed have expired. A cookie that no listed secret opens reads as signed out. -## Cookie jars - -Every `serverAuth` method takes the request's `CookieJar`, which each -framework's adapter gives you. Use one jar per request: calls with the same -jar share what it read and wrote and one refresh, so a jar kept at module -level would show one request's session to the next. - -A jar is read-only where the framework can't set cookies, as while a Server -Component renders or a page streams. There, nothing is refreshed or saved: -see `CookieJar.writable` for which calls reject and with what. Refresh before -rendering, in middleware or a proxy, with `serverAuth.refreshIfDue`. For -another server, build a [`CookieJar`](/docs/reference/server#cookiejar) over -its cookies. - -## Code that takes a client - -`serverAuth.forRequest(jar)` is one request's session shaped like a client -(`RequestAuth`). Code written for a client works on the server with it: -`createAuthFetch(serverAuth.forRequest(jar), { baseUrl })` sends the -cookie's token and saves a renewed one after a 401, and Effect's -`Auth.layer` takes it ([Effect on the server](/docs/effect#on-the-server)). Make it per request, -like the jar. +## A request's session + +Your server code reads and changes the session through one request's +session (`RequestAuth`). It has every `serverAuth` method, without the +request's cookie jar to pass: + +- **TanStack Start:** `startAuth(serverAuth)`, made once at module level. + Each call finds the request Start is handling. +- **React Router:** `routerAuth(serverAuth)` makes a function you call with + a loader's, action's or middleware's `context`. +- **Next.js, and servers without an adapter:** + `serverAuth.forRequest(jar)`, over the request's cookie jar. + +It's shaped like a client, so code written for one works on the server with +it. `createAuthFetch(session, { baseUrl })` sends the cookie's token and saves +a renewed one after a 401, and Effect's `Auth.layer` takes it +([Effect on the server](/docs/effect#on-the-server)). + +Some requests can't set cookies: a Next.js Server Component rendering, or a +React Router loader once its response has left the middleware. There, +nothing is saved, so `signIn`, `signOut` and `refreshIfDue` reject with +`INVALID_OPTIONS`, and an expired access token rejects with +`REFRESH_FAILED`. TanStack Start can't tell once a page has started +streaming, so a cookie set then is lost. Refresh before rendering, in +middleware or a proxy, with `refreshIfDue`. + +## Servers without an adapter + +Every `serverAuth` method also takes the request's `CookieJar` first: +`serverAuth.getSession(jar)` does what a request's `getSession()` does, and +`serverAuth.forRequest(jar)` gives that request's session. For a server +without an adapter, build a [`CookieJar`](/docs/reference/server#cookiejar) +over its cookies. + +Use one jar per request. Calls with the same jar share what it read and +wrote and one refresh, so a jar kept at module level would show one +request's session to the next. A jar that can't set cookies says so with +`writable: false`. ## Token refresh @@ -86,7 +102,7 @@ instances that refresh the same session then don't sign it out. ## Sign-out -`serverAuth.signOut` clears the cookie in this browser, then calls your +A request's `signOut` clears the cookie in this browser, then calls your `revoke`. The cookie holds the whole session and the server keeps no list of sessions, so a copy of the cookie made before sign-out still reads as signed in. For ten seconds, the instance that signed out treats such a copy as @@ -100,11 +116,11 @@ revocation. ## The access token in the browser -Server code calls your API with `serverAuth.credentials`. To call it from the -browser too, with `createAuthFetch` or effetch's `sessionBearer`, opt in with -`clientCredentials: true` and expose `serverAuth.clientCredentials.get` and -`.renew` through your own same-origin endpoint, passed to `createMirrorAuth` -as `credentials`. Page scripts then hold the access token in memory, never the +Server code calls your API with a request's `credentials`. To call it from +the browser too, with `createAuthFetch` or effetch's `sessionBearer`, opt in +with `clientCredentials: true` and expose a request's `clientCredentials.get` +and `.renew` through your own same-origin endpoint, passed to +`createMirrorAuth` as `credentials`. Page scripts then hold the access token in memory, never the refresh token, so a script injected into the page can use the API while the page is open, as it could with any token the browser holds. diff --git a/site/content/docs/(latest)/setups/next.mdx b/site/content/docs/(latest)/setups/next.mdx index c9eb879..bf8d3f3 100644 --- a/site/content/docs/(latest)/setups/next.mdx +++ b/site/content/docs/(latest)/setups/next.mdx @@ -206,17 +206,17 @@ the browser. session the layout read and your Server Functions: ```ts title="lib/auth/client.ts" -import { createMirrorAuth } from "@monarcode/session-kit"; +import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit"; import { getSessionAction, signInAction, signOutAction, } from "../../app/actions"; +// Types only: left out of the browser's bundle. +import type { serverAuth } from "./server"; -export type AppSession = NonNullable< - Awaited> ->; +export type AppSession = SessionOf; export function createAppAuth(session: AppSession | null) { return createMirrorAuth({ diff --git a/site/content/docs/(latest)/setups/react-router-ssr.mdx b/site/content/docs/(latest)/setups/react-router-ssr.mdx index a82bdb9..c6bfb41 100644 --- a/site/content/docs/(latest)/setups/react-router-ssr.mdx +++ b/site/content/docs/(latest)/setups/react-router-ssr.mdx @@ -43,16 +43,15 @@ Put the user schema in a module that the server and the browser both import: import { z } from "zod"; export const userSchema = z.object({ id: z.number(), firstName: z.string() }); - -export type User = z.infer; ``` `createServerAuth` from `@monarcode/session-kit/server` keeps the session in -a cookie sealed with your `secret`, and refreshes it with your backend. Create -it in a `.server` module, so React Router refuses to bundle it for the -browser: +a cookie sealed with your `secret`, and refreshes it with your backend. +`routerAuth` gives a request's session by its `context`. Create both in a +`.server` module, so React Router refuses to bundle it for the browser: ```ts title="app/auth/session.server.ts" +import { routerAuth } from "@monarcode/session-kit/react-router/server"; import { createServerAuth } from "@monarcode/session-kit/server"; import { z } from "zod"; @@ -80,6 +79,9 @@ export const serverAuth = createServerAuth({ }, }); +/** The request's session: `auth(context)` in middleware, loaders and actions. */ +export const auth = routerAuth(serverAuth); + /** Signs in with your backend, from the server. */ export async function login(username: string, password: string) { const response = await fetch(`${API}/auth/login`, { @@ -107,10 +109,10 @@ setup shares. ## 2. Add middleware -Every `serverAuth` method takes a cookie jar. `cookieJarMiddleware` from -`@monarcode/session-kit/react-router/server` gives each request one and sets -the cookies written to it on the response, redirects included. -`routerJar(context)` finds the jar in middleware, loaders and actions. +`cookieJarMiddleware` from `@monarcode/session-kit/react-router/server` +reads each request's cookies and sets the ones written on the response, +redirects included. After it, `auth(context)` gives the request's session in +middleware, loaders and actions. After it, refresh access that is about to expire, before any loader reads it, and keep pages that depend on the session out of shared caches: @@ -118,19 +120,18 @@ it, and keep pages that depend on the session out of shared caches: ```ts title="app/auth/middleware.server.ts" import { redirect, type MiddlewareFunction } from "react-router"; -import { - cookieJarMiddleware, - routerJar, -} from "@monarcode/session-kit/react-router/server"; +import { cookieJarMiddleware } from "@monarcode/session-kit/react-router/server"; -import { serverAuth } from "./session.server"; +import { auth } from "./session.server"; const refreshSession: MiddlewareFunction = async ( { context }, next, ) => { // A failed refresh shows up when a loader reads the session. - await serverAuth.refreshIfDue(routerJar(context)).catch(() => {}); + await auth(context) + .refreshIfDue() + .catch(() => {}); const response = await next(); // A copy: some responses, such as `fetch`'s, can't change their headers. const page = new Response(response.body, response); @@ -138,7 +139,7 @@ const refreshSession: MiddlewareFunction = async ( return page; }; -/** For the root route: the jar first, so it wraps the rest. */ +/** For the root route: the cookies first, so they wrap the rest. */ export const sessionMiddleware = [cookieJarMiddleware, refreshSession]; /** Sends signed-out users to the sign-in page, which brings them back. */ @@ -146,7 +147,7 @@ export const requireSession: MiddlewareFunction = async ({ context, url, }) => { - if (!(await serverAuth.getSession(routerJar(context)))) + if (!(await auth(context).getSession())) throw redirect( `/login?redirectTo=${encodeURIComponent(url.pathname + url.search)}`, ); @@ -173,12 +174,11 @@ import { } from "react-router"; import { safeReturnTo } from "@monarcode/session-kit"; -import { routerJar } from "@monarcode/session-kit/react-router/server"; -import { login, serverAuth } from "../auth/session.server"; +import { auth, login } from "../auth/session.server"; export async function loader({ context, url }: LoaderFunctionArgs) { - if (await serverAuth.getSession(routerJar(context))) + if (await auth(context).getSession()) throw redirect(safeReturnTo(url.searchParams.get("redirectTo"))); return null; } @@ -186,8 +186,7 @@ export async function loader({ context, url }: LoaderFunctionArgs) { export async function action({ request, context, url }: ActionFunctionArgs) { const form = await request.formData(); try { - await serverAuth.signIn( - routerJar(context), + await auth(context).signIn( await login(String(form.get("username")), String(form.get("password"))), ); } catch (error) { @@ -228,18 +227,16 @@ accepts your own site only: ```ts title="app/routes/auth.session.ts" import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router"; -import { routerJar } from "@monarcode/session-kit/react-router/server"; - -import { serverAuth } from "../auth/session.server"; +import { auth } from "../auth/session.server"; export async function loader({ context }: LoaderFunctionArgs) { - return Response.json(await serverAuth.getSession(routerJar(context))); + return Response.json(await auth(context).getSession()); } export async function action({ request, context }: ActionFunctionArgs) { if (request.headers.get("sec-fetch-site") !== "same-origin") return new Response(null, { status: 403 }); - await serverAuth.signOut(routerJar(context)); + await auth(context).signOut(); return Response.json(null); } ``` @@ -252,11 +249,12 @@ Add it to `app/routes.ts` as `route("auth/session", "routes/auth.session.ts")`. the root loader read and the resource route: ```ts title="app/auth/client.ts" -import { createMirrorAuth, type Session } from "@monarcode/session-kit"; +import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit"; -import type { User } from "./user"; +// Types only: left out of the browser's bundle. +import type { serverAuth } from "./session.server"; -export type AppSession = Session; +export type AppSession = SessionOf; async function session(method: "GET" | "POST") { const response = await fetch("/auth/session", { method }); @@ -297,11 +295,10 @@ import { } from "react-router"; import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react"; -import { routerJar } from "@monarcode/session-kit/react-router/server"; import { createAppAuth, type AppAuth } from "./auth/client"; import { sessionMiddleware } from "./auth/middleware.server"; -import { serverAuth } from "./auth/session.server"; +import { auth } from "./auth/session.server"; // Types `AuthProvider` and the hooks with this client. declare module "@monarcode/session-kit" { @@ -313,7 +310,7 @@ declare module "@monarcode/session-kit" { export const middleware = sessionMiddleware; export async function loader({ context }: LoaderFunctionArgs) { - return { session: await serverAuth.getSession(routerJar(context)) }; + return { session: await auth(context).getSession() }; } export function Layout({ children }: { children: ReactNode }) { @@ -398,19 +395,18 @@ with the access token. ## Call your API -Loaders and actions get the access token with the request's jar, refreshing -it first when it has expired, and can `renew` it after a 401: +Loaders and actions get the access token from the request's session, +refreshed first when it has expired, and can `renew` it after a 401: ```tsx title="app/routes/orders.tsx" import { redirect, useLoaderData, type LoaderFunctionArgs } from "react-router"; -import { routerJar } from "@monarcode/session-kit/react-router/server"; import { z } from "zod"; -import { serverAuth } from "../auth/session.server"; +import { auth } from "../auth/session.server"; export async function loader({ context }: LoaderFunctionArgs) { - const credentials = await serverAuth.credentials.get(routerJar(context)); + const credentials = await auth(context).credentials.get(); if (!credentials) throw redirect("/login?redirectTo=/orders"); const response = await fetch("https://api.example.com/orders", { headers: { Authorization: `Bearer ${credentials.accessToken}` }, @@ -427,28 +423,27 @@ export default function Orders() { To call the API from the browser too, with `createAuthFetch` or effetch's `sessionBearer`, opt in with `clientCredentials: true` in `createServerAuth`. -Expose `serverAuth.clientCredentials.get` and `.renew` through a resource +Expose the request's `clientCredentials.get` and `.renew` through a resource route, added as `route("auth/credentials", "routes/auth.credentials.ts")`: ```ts title="app/routes/auth.credentials.ts" import type { ActionFunctionArgs } from "react-router"; -import { routerJar } from "@monarcode/session-kit/react-router/server"; import { z } from "zod"; -import { serverAuth } from "../auth/session.server"; +import { auth } from "../auth/session.server"; const rejected = z.object({ sessionId: z.string(), accessToken: z.string() }); export async function action({ request, context }: ActionFunctionArgs) { if (request.headers.get("sec-fetch-site") !== "same-origin") return new Response(null, { status: 403 }); - const jar = routerJar(context); + const session = auth(context); const body = rejected.safeParse(await request.json().catch(() => null)); return Response.json( body.success - ? await serverAuth.clientCredentials.renew(jar, body.data) - : await serverAuth.clientCredentials.get(jar), + ? await session.clientCredentials.renew(body.data) + : await session.clientCredentials.get(), ); } ``` @@ -464,14 +459,14 @@ The example app does this. - **Signing out ends the session only with `revoke`.** A copy of the cookie works again ten seconds after sign-out: see [Sign-out](/docs/server-rendering/server-sessions#sign-out). -- **Refresh in middleware.** The jar sets cookies until the response leaves - `cookieJarMiddleware`, which first waits for a refresh under way. A - loader's deferred data that reads the session later, while the page - streams, gets a read-only jar: an expired token then rejects with - `REFRESH_FAILED`, since the jar can't save a new one. `refreshIfDue` in +- **Refresh in middleware.** The request's session sets cookies until the + response leaves `cookieJarMiddleware`, which first waits for a refresh + under way. A loader's deferred data that reads the session later, while + the page streams, can't set cookies: an expired token then rejects with + `REFRESH_FAILED`, since nothing new can be saved. `refreshIfDue` in middleware refreshes before that. -- **One jar per request.** `routerJar` returns the same jar for every call - with the same `context`, which React Router makes per request. +- **One session per request.** `auth(context)` returns the same session for + every call with the same `context`, which React Router makes per request. - **Tabs.** Signing in or out in one tab reaches the others, which ask the server again and run their loaders again. So does returning to a tab after a while. diff --git a/site/content/docs/(latest)/setups/tanstack-start.mdx b/site/content/docs/(latest)/setups/tanstack-start.mdx index cd89d11..a4ad070 100644 --- a/site/content/docs/(latest)/setups/tanstack-start.mdx +++ b/site/content/docs/(latest)/setups/tanstack-start.mdx @@ -34,12 +34,14 @@ npm install @monarcode/session-kit @tanstack/react-start zod ## 1. Create the server engine `createServerAuth` from `@monarcode/session-kit/server` keeps the session in -a cookie sealed with your `secret`, and refreshes it with your backend. Create -it in a server-only module, so Start refuses to bundle it for the browser: +a cookie sealed with your `secret`, and refreshes it with your backend. +`startAuth` gives the session of the request Start is handling. Create both +in a server-only module, so Start refuses to bundle it for the browser: ```ts title="src/auth/server.ts" import "@tanstack/react-start/server-only"; import { createServerAuth } from "@monarcode/session-kit/server"; +import { startAuth } from "@monarcode/session-kit/tanstack-start/server"; import { z } from "zod"; const API = "https://api.example.com"; @@ -47,7 +49,7 @@ const API = "https://api.example.com"; const userSchema = z.object({ id: z.number(), firstName: z.string() }); const tokens = z.object({ accessToken: z.string(), refreshToken: z.string() }); -export const serverAuth = createServerAuth({ +const serverAuth = createServerAuth({ name: "app", user: userSchema, secret: process.env.SESSION_SECRET!, @@ -65,6 +67,9 @@ export const serverAuth = createServerAuth({ }, }); +/** The session of the request Start is handling, found on each call. */ +export const session = startAuth(serverAuth); + /** Signs in with your backend, from the server. */ export async function login(username: string, password: string) { const response = await fetch(`${API}/auth/login`, { @@ -92,36 +97,33 @@ setup shares. ## 2. Add server functions -Every `serverAuth` method takes the request's cookie jar, and `startJar()` -from `@monarcode/session-kit/tanstack-start/server` gives it. Your server -functions decide what the browser may ask for: +`session` finds the request each time it's called, so one object serves +every request. Your server functions decide what the browser may ask for: ```ts title="src/auth/functions.ts" -import { startJar } from "@monarcode/session-kit/tanstack-start/server"; import { createServerFn } from "@tanstack/react-start"; import { z } from "zod"; -import { login, serverAuth } from "./server"; +import { login, session } from "./server"; export const getSessionFn = createServerFn().handler(() => - serverAuth.getSession(startJar()), + session.getSession(), ); export const signInFn = createServerFn({ method: "POST" }) .validator(z.object({ username: z.string(), password: z.string() })) .handler(async ({ data }) => - serverAuth.signIn(startJar(), await login(data.username, data.password)), + session.signIn(await login(data.username, data.password)), ); export const signOutFn = createServerFn({ method: "POST" }).handler(() => - serverAuth.signOut(startJar()), + session.signOut(), ); ``` `getSession` and `signIn` resolve `{ sessionId, user }`, never tokens, so their results are safe to send to the browser. Start's compiler replaces each -handler with a request in the browser bundle, and leaves `startJar` and -`serverAuth` out of it. +handler with a request in the browser bundle, and leaves `session` out of it. ## 3. Refresh before rendering @@ -132,19 +134,18 @@ then, such as in a deferred loader's promise, would spend the refresh token and drop the new one: ```ts title="src/start.ts" -import { startJar } from "@monarcode/session-kit/tanstack-start/server"; import { createCsrfMiddleware, createMiddleware, createStart, } from "@tanstack/react-start"; -import { serverAuth } from "./auth/server"; +import { session } from "./auth/server"; const sessionMiddleware = createMiddleware({ type: "request" }).server( async ({ next }) => { // A failed refresh shows up when a route reads the session. - await serverAuth.refreshIfDue(startJar()).catch(() => {}); + await session.refreshIfDue().catch(() => {}); return next(); }, ); @@ -262,8 +263,8 @@ export const Route = createFileRoute("/_authenticated")({ explains `SessionOutlet`, and an error component for a failed refresh. Guards decide what a page shows. Server functions that return private data -must check the session themselves, with `serverAuth.getSession(startJar())` -or `serverAuth.credentials.get(startJar())`. +must check the session themselves, with `session.getSession()` or +`session.credentials.get()`. ## Sign in @@ -296,7 +297,7 @@ gives you `auth`, from Router context. In this guide, the server signs in with your backend, so the user in the cookie comes from the backend. If the browser signs in with the backend itself, for example through a provider's SDK, have `signInFn` take the tokens and the user -instead and pass them to `serverAuth.signIn`. It seals what it's given: until a +instead and pass them to `session.signIn`. It seals what it's given: until a refresh or `updateUser` replaces it, the user in the cookie is what the browser sent. Use it to show who is signed in, and let your backend authorize requests with the access token, or check the tokens in `signInFn` first. @@ -307,14 +308,13 @@ On the server, get the access token in a server function. `credentials.get` refreshes it first when it has expired: ```ts title="src/orders.ts" -import { startJar } from "@monarcode/session-kit/tanstack-start/server"; import { createServerFn } from "@tanstack/react-start"; import { z } from "zod"; -import { serverAuth } from "./auth/server"; +import { session } from "./auth/server"; export const getOrdersFn = createServerFn().handler(async () => { - const credentials = await serverAuth.credentials.get(startJar()); + const credentials = await session.credentials.get(); if (!credentials) throw new Error("Sign in first"); const response = await fetch("https://api.example.com/orders", { headers: { Authorization: `Bearer ${credentials.accessToken}` }, @@ -326,7 +326,7 @@ export const getOrdersFn = createServerFn().handler(async () => { To call the API from the browser too, with `createAuthFetch` or effetch's `sessionBearer`, opt in with `clientCredentials: true` in `createServerAuth`. -Expose `serverAuth.clientCredentials.get` and `.renew` through two POST server +Expose `session.clientCredentials.get` and `.renew` through two POST server functions, and pass them as the client's `credentials`. The browser then keeps the access token in memory, never the refresh token. The example app does this. @@ -336,8 +336,10 @@ does this. - **Signing out ends the session only with `revoke`.** A copy of the cookie works again ten seconds after sign-out: see [Sign-out](/docs/server-rendering/server-sessions#sign-out). -- **One jar per request.** `startJar()` returns the same jar for every call - while Start handles a request. +- **One session per request.** Each call to `session` reads the request + Start is handling, and calls during one request share what it read and + one refresh. Outside a request, such as in the browser, they reject with + `INVALID_OPTIONS`. - **Caching.** Pages and server functions that read the session differ per user, and Start sends no `Cache-Control` for them. Behind a CDN or proxy that caches responses, mark them private, for example with diff --git a/src/core/infer.ts b/src/core/infer.ts new file mode 100644 index 0000000..d0d2a9a --- /dev/null +++ b/src/core/infer.ts @@ -0,0 +1,49 @@ +/** + * The session type of a client: what its `getSession` resolves, without + * `null`. It takes any client: one from `createAuth` or `createMirrorAuth`, + * the server's from `createServerAuth`, or a request's session from it. + * + * The browser can take its types from the server's. An `import type` of the + * server's module is left out of the browser bundle. + * + * @example + * ```ts + * import { createAuth, webStorage, type SessionOf } from "@monarcode/session-kit"; + * import { z } from "zod"; + * + * export const auth = createAuth({ + * name: "app", + * user: z.object({ id: z.string(), name: z.string() }), + * storage: webStorage(), + * }); + * + * export type AppSession = SessionOf; // { sessionId, user } + * ``` + * + * @see {@link UserOf} for the user alone + * + * @since 0.1.0 + */ +export type SessionOf< + Client extends { getSession: (...args: never[]) => Promise }, +> = NonNullable>>; + +/** + * The user type of a client, as {@link SessionOf} finds it: the `user` of + * its session. + * + * @example + * ```ts + * import type { UserOf } from "@monarcode/session-kit"; + * import type { ServerAuth } from "@monarcode/session-kit/server"; + * + * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; + * + * export type AppUser = UserOf; // { id: number } + * ``` + * + * @since 0.1.0 + */ +export type UserOf< + Client extends { getSession: (...args: never[]) => Promise }, +> = SessionOf extends { readonly user: infer U } ? U : never; diff --git a/src/core/request-session.ts b/src/core/request-session.ts new file mode 100644 index 0000000..4c5714f --- /dev/null +++ b/src/core/request-session.ts @@ -0,0 +1,18 @@ +/** + * Marks a server request's session at runtime, so code that takes a client, + * such as Effect's `Auth`, can tell one apart. Its value returns the session + * bound to the current request: the session itself for `forRequest`'s, the + * current request's for one that finds its request on each call. A global + * symbol, so two copies of the package agree. + */ +export const REQUEST_SESSION: unique symbol = Symbol.for( + "@monarcode/session-kit/request-session", +); + +/** The session bound to the current request, when `client` is a request's. */ +export function boundSession(client: object): object | undefined { + const bind = (client as { [REQUEST_SESSION]?: () => object })[ + REQUEST_SESSION + ]; + return typeof bind === "function" ? bind() : undefined; +} diff --git a/src/effect/auth.ts b/src/effect/auth.ts index b7077cc..0e51705 100644 --- a/src/effect/auth.ts +++ b/src/effect/auth.ts @@ -8,7 +8,9 @@ import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import { AuthError, toAuthError } from "../core/errors.js"; +import type { SessionOf, UserOf } from "../core/infer.js"; import type { Register, RegisteredAuth } from "../core/register.js"; +import { boundSession, REQUEST_SESSION } from "../core/request-session.js"; import type { Credentials } from "../core/types.js"; import type { RequestAuth } from "../server/auth.js"; import { @@ -60,15 +62,15 @@ export type AuthServiceClient = { /** * What {@link Auth.layer} takes. Once you register a client in - * {@link Register}, that's your client, or on the server a - * `serverAuth.forRequest(jar)` view with the same user. Until then, it's any + * {@link Register}, that's your client, or on the server a request's session + * with the same user (`RequestAuth`). Until then, it's any * {@link AuthServiceClient}. * * @example * ```ts * import { Auth, type AuthLayerClient } from "@monarcode/session-kit/effect"; * - * // Takes the browser client or one request's view on the server. + * // Takes the browser client, or one request's session on the server. * export const provideAuth = (client: AuthLayerClient) => Auth.layer(client); * ``` * @@ -79,11 +81,11 @@ export type AuthLayerClient = Register extends { } ? | RegisteredAuth - | RequestAuth< - RegisteredSession extends { readonly user: infer U } - ? U - : unknown - > + // A request's session with the registered user, whatever its + // `signIn` takes: `any` accepts every input, `never` the servers + // that read the user from the access token. + | RequestAuth, any> + | RequestAuth, never> : AuthServiceClient; /** @@ -99,9 +101,7 @@ export type AuthLayerClient = Register extends { * * @since 0.1.0 */ -export type RegisteredSession = NonNullable< - Awaited> ->; +export type RegisteredSession = SessionOf; /** * Your registered client's `AuthState`, as {@link Auth.changes} emits it. @@ -196,21 +196,19 @@ export type RegisteredUserInput = RegisteredAuth extends { * ``` * * @example - * On the server, each request provides its own session, from - * `serverAuth.forRequest(jar)`. Build what uses it per request too: + * On the server, each request provides its own session (`RequestAuth`), + * such as one from `startAuth`. Build what uses it per request too: * ```ts * import * as Effect from "effect/Effect"; * import { Auth } from "@monarcode/session-kit/effect"; - * import type { CookieJar, ServerAuth } from "@monarcode/session-kit/server"; + * import type { RequestAuth } from "@monarcode/session-kit/server"; * - * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; + * declare const session: RequestAuth<{ id: number }, { id: number }>; * - * const program = Effect.map(Auth.session, (session) => session.sessionId); + * const program = Effect.map(Auth.session, (current) => current.sessionId); * - * export const sessionId = (jar: CookieJar) => - * Effect.runPromise( - * Effect.provide(program, Auth.layer(serverAuth.forRequest(jar))), - * ); + * export const sessionId = () => + * Effect.runPromise(Effect.provide(program, Auth.layer(session))); * ``` * * @since 0.1.0 @@ -221,13 +219,19 @@ export class Auth extends Context.Service()( /** * Provides `client` as the {@link Auth} service. * - * On the server, pass `serverAuth.forRequest(jar)`, and provide it per - * request with the services that use it. Never put it in a runtime that - * every request shares. A request's view has only what `Auth`'s Effects - * use, so don't reach for other client methods through `Auth.use` there. + * On the server, pass the request's session, and provide it per request + * with the services that use it. Never put it in a runtime that every + * request shares. A session from `startAuth` is bound to the request that + * is current when you call this. Outside a request, it throws + * `INVALID_OPTIONS`. + * + * A request's session isn't your browser client, so use only `Auth`'s + * Effects there, not other client methods through `Auth.use`. */ static readonly layer = (client: AuthLayerClient): Layer.Layer => - Layer.succeed(Auth, client as RegisteredAuth); + // Bound now, in the caller's request: inside a fiber, the current + // request may not be the one the Effect runs for. + Layer.succeed(Auth, (boundSession(client) ?? client) as RegisteredAuth); /** * The current session, refreshed first if the access token expired, as @@ -316,17 +320,21 @@ export class Auth extends Context.Service()( * client, an error your `signIn` option throws, such as a wrong password, * fails with `USER_VALIDATION_FAILED`, and is its `AuthError`'s `cause`. * - * Dies when the client has no `signIn`. That's a `createMirrorAuth` client - * made without one, or a request's view on the server, where you call - * `serverAuth.signIn(jar, …)` instead. + * Dies when the client has no `signIn`: a `createMirrorAuth` client made + * without one. It dies with a request's session on the server too. Call + * that session's own `signIn`, which takes the tokens and the user. */ static readonly signIn = ( input: RegisteredSignIn, ): Effect.Effect => Auth.use((client) => { - const signIn = ( - client as { signIn?: (input: unknown) => Promise } - ).signIn; + // A request's session has a `signIn`, but it takes the tokens and the + // user, not what the registered client's takes. + const signIn = + REQUEST_SESSION in client + ? undefined + : (client as { signIn?: (input: unknown) => Promise }) + .signIn; return signIn ? fromPromise(async () => { try { @@ -344,7 +352,7 @@ export class Auth extends Context.Service()( : Effect.die( new AuthError( "INVALID_OPTIONS", - "This client has no signIn: pass signIn to createMirrorAuth, or on the server call serverAuth.signIn(jar, input)", + "Auth.signIn needs a client with signIn: pass signIn to createMirrorAuth. On the server, call signIn on the request's session instead, with the tokens and the user", ), ); }); @@ -372,8 +380,9 @@ export class Auth extends Context.Service()( * failure passes through as is. * * Dies when the client can't update the user: its user comes from the - * access token, it's a `createMirrorAuth` client, or it's a request's view - * on the server. There, call `serverAuth.updateUser(jar, …)` instead. + * access token, or it's a `createMirrorAuth` client. It dies with a + * request's session on the server too. Call that session's own + * `updateUser`. */ static readonly updateUser = ( input: RegisteredUserInput | Effect.Effect, @@ -384,6 +393,15 @@ export class Auth extends Context.Service()( Auth | R > { const client = yield* Auth; + // A request's session has an `updateUser`, but its input is the + // server's user, and it resolves the session. + if (REQUEST_SESSION in client) + return yield* Effect.die( + new AuthError( + "INVALID_OPTIONS", + "Auth.updateUser needs a browser client: on the server, call updateUser on the request's session instead", + ), + ); const update = ( client as { updateUser?: (input: unknown) => Promise } ).updateUser; @@ -391,7 +409,7 @@ export class Auth extends Context.Service()( return yield* Effect.die( new AuthError( "INVALID_OPTIONS", - "This client has no updateUser: its user comes from the access token or from the server. On the server, unless the user comes from the access token, call serverAuth.updateUser(jar, input)", + "This client has no updateUser: its user comes from the access token or from the server. Unless it comes from the access token, update it on the server, with updateUser on the request's session", ), ); if (!Effect.isEffect(input)) diff --git a/src/effetch/index.ts b/src/effetch/index.ts index b85a4ef..03bc962 100644 --- a/src/effetch/index.ts +++ b/src/effetch/index.ts @@ -122,8 +122,8 @@ const refuseRedirects = ( * token. `Fetch.make` then needs the `Auth` service, but calls don't. * * On the server, make the effetch client per request, and provide it the - * `Auth` layer for that request's `serverAuth.forRequest(jar)`. That view - * reads the token from the request's cookie and saves a renewed one. + * `Auth` layer for that request's session (`RequestAuth`). It reads the + * token from the request's cookie and saves a renewed one. * * @example * ```ts diff --git a/src/http/index.ts b/src/http/index.ts index 8c5444f..a3712b4 100644 --- a/src/http/index.ts +++ b/src/http/index.ts @@ -5,7 +5,7 @@ import { parseUrl } from "../core/url.js"; /** * The part of an auth client that {@link createAuthFetch} uses. A * `createAuth` or `createMirrorAuth` client fits, and so does a request's - * session from `serverAuth.forRequest(jar)`. + * session on the server (`RequestAuth`). * * @example * ```ts diff --git a/src/index.ts b/src/index.ts index ccd207a..f076707 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,6 +12,7 @@ export type { AuthDebugType, } from "./core/debug.js"; export type { AuthErrorCode, AuthErrorOptions } from "./core/errors.js"; +export type { SessionOf, UserOf } from "./core/infer.js"; export type { ClientCredentials, MirrorAuth, diff --git a/src/react-router/server.ts b/src/react-router/server.ts index ab6a2e4..d303b64 100644 --- a/src/react-router/server.ts +++ b/src/react-router/server.ts @@ -1,26 +1,26 @@ import { AuthError } from "../core/errors.js"; +import type { RequestAuth, ServerAuth } from "../server/auth.js"; import type { CookieJar } from "../server/cookies.js"; import { requestJar, type RequestJar } from "../server/request-jar.js"; /** * The `context` React Router passes to server middleware, loaders and actions * in framework mode: a `RouterContextProvider`, one per request. - * {@link routerJar} and {@link cookieJarMiddleware} find the request's jar by - * it. It's typed by its shape, so this entry point doesn't depend on React + * {@link routerAuth} and {@link cookieJarMiddleware} find the request by it. + * It's typed by its shape, so this entry point doesn't depend on React * Router's types. * * @example * ```ts - * import { - * routerJar, - * type RouterContextLike, - * } from "@monarcode/session-kit/react-router/server"; - * import type { ServerAuth } from "@monarcode/session-kit/server"; + * import type { RouterContextLike } from "@monarcode/session-kit/react-router/server"; + * import type { RequestAuth } from "@monarcode/session-kit/server"; * - * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; + * declare const auth: ( + * context: RouterContextLike, + * ) => RequestAuth<{ id: number }, { id: number }>; * * export async function loader({ context }: { context: RouterContextLike }) { - * return { session: await serverAuth.getSession(routerJar(context)) }; + * return { session: await auth(context).getSession() }; * } * ``` * @@ -50,25 +50,26 @@ const requests = new WeakMap< * first waits for a refresh under way, so its new tokens are saved. After * that, such as while a loader's deferred data streams, it's read-only. * Nothing is saved, and a call that needs a refresh rejects with - * `REFRESH_FAILED`. Refresh before rendering, with `serverAuth.refreshIfDue` - * in middleware. + * `REFRESH_FAILED`. Refresh before rendering, with `refreshIfDue` in + * middleware. * * @example * ```ts * import { * cookieJarMiddleware, - * routerJar, * type RouterContextLike, * } from "@monarcode/session-kit/react-router/server"; - * import type { ServerAuth } from "@monarcode/session-kit/server"; + * import type { RequestAuth } from "@monarcode/session-kit/server"; * - * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; + * declare const auth: ( + * context: RouterContextLike, + * ) => RequestAuth<{ id: number }, { id: number }>; * * // app/root.tsx: refresh access that expires within a minute. * export const middleware = [ * cookieJarMiddleware, * async ({ context }: { context: RouterContextLike }) => { - * await serverAuth.refreshIfDue(routerJar(context)).catch(() => {}); + * await auth(context).refreshIfDue().catch(() => {}); * }, * ]; * ``` @@ -91,10 +92,10 @@ export async function cookieJarMiddleware( /** * The {@link CookieJar} for the request React Router is handling, to pass to - * `serverAuth` from `@monarcode/session-kit/server`. Call it with `context` - * in server middleware, loaders and actions, after - * {@link cookieJarMiddleware}. Every call during one request returns the - * same jar. + * `serverAuth` from `@monarcode/session-kit/server`. {@link routerAuth} + * passes it for you. Call it with `context` in server middleware, loaders + * and actions, after {@link cookieJarMiddleware}. Every call during one + * request returns the same jar. * * Throws `INVALID_OPTIONS` when the middleware hasn't run for `context`, * such as in a client loader. @@ -123,7 +124,47 @@ export function routerJar(context: RouterContextLike): CookieJar { if (!current) throw new AuthError( "INVALID_OPTIONS", - "Add cookieJarMiddleware to the root route's middleware, and call routerJar(context) on the server, in middleware, loaders and actions", + "Add cookieJarMiddleware to the root route's middleware, and read the session on the server, in middleware, loaders and actions", ); return current.cookies.jar; } + +/** + * Returns a function that gives the session of the request React Router is + * handling ({@link RequestAuth}), with every `serverAuth` method and no + * cookie jar. Call it with `context` in server middleware, loaders and + * actions, after {@link cookieJarMiddleware}. Make it once, at module level. + * + * Calling it throws `INVALID_OPTIONS` when the middleware hasn't run for + * `context`, as {@link routerJar} does. + * + * @example + * ```ts + * import { createServerAuth } from "@monarcode/session-kit/server"; + * import { + * routerAuth, + * type RouterContextLike, + * } from "@monarcode/session-kit/react-router/server"; + * import { z } from "zod"; + * + * declare const secret: string; + * + * const serverAuth = createServerAuth({ + * name: "app", + * user: z.object({ id: z.number(), firstName: z.string() }), + * secret, + * }); + * export const auth = routerAuth(serverAuth); + * + * export async function loader({ context }: { context: RouterContextLike }) { + * return { session: await auth(context).getSession() }; + * } + * ``` + * + * @since 0.1.0 + */ +export function routerAuth( + serverAuth: ServerAuth, +): (context: RouterContextLike) => RequestAuth { + return (context) => serverAuth.forRequest(routerJar(context)); +} diff --git a/src/server/auth.ts b/src/server/auth.ts index 388f298..c18637b 100644 --- a/src/server/auth.ts +++ b/src/server/auth.ts @@ -3,6 +3,7 @@ import type { AuthDebug } from "../core/debug.js"; import { AuthError, sessionChanged, toAuthError } from "../core/errors.js"; import type { ClientCredentials } from "../core/mirror.js"; import { checkOptions } from "../core/persistence.js"; +import { REQUEST_SESSION } from "../core/request-session.js"; import { resolveUserSource, type UserSource } from "../core/sources.js"; import type { AuthStorage } from "../core/storage.js"; import type { @@ -151,13 +152,12 @@ export type ServerAuthOptions = { * * @example * ```ts - * import type { CookieJar, ServerAuth } from "@monarcode/session-kit/server"; + * import type { RequestAuth } from "@monarcode/session-kit/server"; * - * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; - * declare const jar: CookieJar; + * declare const session: RequestAuth<{ id: number }, { id: number }>; * * // Refresh when less than two minutes are left. - * await serverAuth.refreshIfDue(jar, { within: 120 }); + * await session.refreshIfDue({ within: 120 }); * ``` * * @since 0.1.0 @@ -174,154 +174,201 @@ export type RefreshIfDueOptions = { declare const requestAuth: unique symbol; -/** - * One request's session, shaped like a client. Get it from - * `serverAuth.forRequest(jar)`, and pass it to code that expects a client, - * such as `createAuthFetch` from `@monarcode/session-kit/http`. Make one per - * request, never at module level. - * - * It reads, refreshes and saves the session as the `serverAuth` methods do. - * It has no `signIn` or `updateUser`. Call those on `serverAuth`. - * - * A read-only jar can't save a new token, so `credentials.renew` rejects - * with `REFRESH_FAILED`, and `createAuthFetch` rejects rather than return the - * 401. The exception is a token the same request's writable jar already - * renewed, which it resolves. Refresh first, in middleware or a proxy, with - * `refreshIfDue`. - * - * @example - * ```ts - * import { createAuthFetch } from "@monarcode/session-kit/http"; - * import type { CookieJar, ServerAuth } from "@monarcode/session-kit/server"; - * - * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; - * - * // Sends the cookie's token, and renews it after a 401. - * export async function orders(jar: CookieJar) { - * const authFetch = createAuthFetch(serverAuth.forRequest(jar), { - * baseUrl: "https://api.example.com", - * }); - * return (await authFetch("/orders")).json(); - * } - * ``` - * - * @since 0.1.0 - */ -export type RequestAuth = Readonly<{ +type RequestAuthBase = { /** * Marks a request's session, so a client isn't taken for one. Types only. */ [requestAuth]: true; - /** Like `serverAuth.getSession(jar)`. */ + /** + * Resolves who is signed in, from the cookie, or `null`. An expired access + * token is refreshed first, and a refresh token your backend rejects signs + * out. Where the request can't set cookies, the session is returned as the + * cookie holds it. + */ getSession: () => Promise | null>; - /** Like `serverAuth.signOut(jar)`. */ + /** + * Refreshes the access token when it has less than `within` seconds left + * ({@link RefreshIfDueOptions}), then resolves the session. Use it in + * middleware or a proxy that runs before rendering, so pages get a fresh + * token to read. + * + * It refreshes at most once per request. A failed refresh is ignored while + * the access token still works. Rejects with `INVALID_OPTIONS` where the + * request can't set cookies. + */ + refreshIfDue: (options?: RefreshIfDueOptions) => Promise | null>; + /** + * Signs in with `input`, checked as the client's `signIn` does, and seals + * it into the cookie. Resolves the new session, which holds no tokens, so + * you can return it to the browser. Rejects with `INVALID_OPTIONS` where + * the request can't set cookies. + */ + signIn: (input: SignInInput) => Promise>; + /** + * Signs out by clearing the cookie, then calls `revoke` and waits for it. + * A failed `revoke` doesn't reject. Rejects with `INVALID_OPTIONS` where + * the request can't set cookies. + */ signOut: () => Promise; - /** Like `serverAuth.credentials`, for this request's jar. */ + /** + * The access token ({@link Credentials}), for server code that calls your + * API. `get`, `renew` and `reject` work like the client's. + */ credentials: Readonly<{ + /** + * Resolves the current access token, or `null`, refreshing an expired + * one first. Where the request can't set cookies, an expired one rejects + * with `REFRESH_FAILED`. + */ get: () => Promise; + /** + * Gets a new access token after your API rejected `credentials`, such as + * with a 401. Where the request can't set cookies, it rejects with + * `REFRESH_FAILED`, unless the same request already renewed the token + * where it could, which it then resolves. + */ renew: (credentials: Credentials) => Promise; /** * Signs out because your API rejected `credentials` for good, unless - * they're no longer current. With a read-only jar, it resolves without - * signing out, as that jar can't clear the cookie. + * they're no longer current. Where the request can't set cookies, it + * resolves without signing out. */ reject: (credentials: Credentials) => Promise; }>; + /** + * The access token for your own page scripts ({@link ClientCredentials}), + * with the `clientCredentials` option. Expose these only through a + * same-origin server function, action or route handler protected against + * CSRF. Both reject with `INVALID_OPTIONS` without the option. + */ + clientCredentials: Readonly<{ + /** Like `credentials.get`, refreshing when access has expired. */ + get: () => Promise; + /** + * Like `credentials.renew`, after your API rejected the token. It takes + * what the browser sent, so anything but a session ID and an access + * token rejects with `INVALID_OPTIONS`. + */ + renew: (credentials: unknown) => Promise; + }>; /** Whether `session` is the one this request has read. */ isCurrent: (session: { sessionId: string }) => boolean; /** * The state of this request's session, an `AuthState`. * - * It's `initializing` until a call reads the cookie. With a writable jar - * holding an expired access token, it stays so until a call refreshes it. - * It's `unavailable` when a read-only jar holds an expired access token, - * or the secret is missing. + * It's `initializing` until a call reads the cookie. Where the request + * can set cookies and the access token has expired, it stays so until a + * call refreshes it. It's `unavailable` when the request can't set cookies + * and the access token has expired, or the secret is missing. * - * A read-only jar paired with a writable one, as Next's are, follows the - * writable jar's session once that has read or written one. Listeners - * must not throw. Their errors are rethrown asynchronously, which is an - * uncaught exception on a server. + * A Next.js page, which can't set cookies, follows the session that the + * same request's Server Function signed in or refreshed. Listeners must not + * throw. Their errors are rethrown asynchronously, which is an uncaught + * exception on a server. */ state: Readonly["state"]>; -}>; +}; + +/** What a request's session object holds, checked where one is built. */ +type Members = Omit, typeof requestAuth> & { + [REQUEST_SESSION]: () => unknown; + updateUser?: (input: I | (() => Promise)) => Promise>; +}; + +/** + * One request's session: what {@link ServerAuth} does for a request, without + * its {@link CookieJar}. `startAuth` from + * `@monarcode/session-kit/tanstack-start/server` and `routerAuth` from + * `@monarcode/session-kit/react-router/server` give you one. Elsewhere, + * `serverAuth.forRequest(jar)` does. + * + * It's shaped like a client, so code written for one works on the server + * with it, such as `createAuthFetch` from `@monarcode/session-kit/http`. + * `U` is the user, and `I` is the user `signIn` accepts, as for + * {@link ServerAuth}. Write `SessionOf` or `UserOf` from + * `@monarcode/session-kit` for its types. + * + * Some requests can't set cookies: a Next.js page, or a React Router loader + * once its response has left the middleware. There, nothing can be saved, so + * `signIn`, `signOut` and `refreshIfDue` reject with `INVALID_OPTIONS`, and + * an expired access token rejects with `REFRESH_FAILED`. Refresh first, in + * middleware or a proxy, with `refreshIfDue`. + * + * @example + * ```ts + * import type { RequestAuth } from "@monarcode/session-kit/server"; + * + * type User = { id: number; firstName: string }; + * declare const session: RequestAuth; + * + * export async function greeting() { + * const current = await session.getSession(); + * return current ? `Hi, ${current.user.firstName}` : "Please sign in"; + * } + * ``` + * + * @since 0.1.0 + */ +export type RequestAuth = Readonly> & + ([I] extends [never] + ? unknown + : Readonly<{ + /** + * Replaces the signed-in user and keeps the session, as the + * client's `updateUser` does, then resolves the session. Rejects + * with `INVALID_OPTIONS` where the request can't set cookies. + */ + updateUser: (input: I | (() => Promise)) => Promise>; + }>); type ServerAuthBase = { - /** - * Resolves who is signed in, from the cookie, or `null`. With a writable - * jar, an expired access token is refreshed first, and a refresh token - * your backend rejects signs out. With a read-only jar, the session is - * returned as the cookie holds it. - */ + /** {@link RequestAuth}'s `getSession`, for `jar`. */ getSession: (jar: CookieJar) => Promise | null>; /** - * Refreshes the access token when it has less than `within` seconds left - * ({@link RefreshIfDueOptions}), then resolves the session. Use it in - * middleware or a proxy that runs before rendering, so pages get a fresh - * token to read. - * - * It refreshes at most once per jar. A failed refresh is ignored while the - * access token still works. Rejects with `INVALID_OPTIONS` given a - * read-only jar. + * {@link RequestAuth}'s `refreshIfDue`, for `jar`. It refreshes at most + * once per jar. */ refreshIfDue: ( jar: CookieJar, options?: RefreshIfDueOptions, ) => Promise | null>; - /** - * Signs in with `input`, checked as the client's `signIn` does, and seals - * it into the cookie. Resolves the new session, which holds no tokens, so - * you can return it to the browser. Rejects with `INVALID_OPTIONS` given a - * read-only jar. - */ + /** {@link RequestAuth}'s `signIn`, for `jar`. */ signIn: (jar: CookieJar, input: SignInInput) => Promise>; - /** - * Signs out by clearing the cookie, then calls `revoke` and waits for it. - * A failed `revoke` doesn't reject. Rejects with `INVALID_OPTIONS` given a - * read-only jar. - */ + /** {@link RequestAuth}'s `signOut`, for `jar`. */ signOut: (jar: CookieJar) => Promise; - /** - * The access token ({@link Credentials}), for server code that calls your - * API. `get`, `renew` and `reject` work like the client's. - */ + /** {@link RequestAuth}'s `credentials`, for `jar`. */ credentials: { /** - * Resolves the current access token, or `null`, refreshing an expired - * one first. A read-only jar can't save a refreshed token, so an expired - * one rejects with `REFRESH_FAILED`. Refresh first, in middleware or a - * proxy, with `refreshIfDue`. + * Resolves the access token for `jar`, or `null`, as + * {@link RequestAuth}'s `credentials.get` does. With a read-only jar, + * an expired one rejects with `REFRESH_FAILED`. */ get: (jar: CookieJar) => Promise; /** - * Gets a new access token after your API rejected `credentials`, such as - * with a 401. A read-only jar can't save one, so it rejects with - * `REFRESH_FAILED`, unless the same request's writable jar already - * renewed the token, which it then resolves. + * Gets a new access token for `jar` after your API rejected + * `credentials`, as {@link RequestAuth}'s `credentials.renew` does. */ renew: ( jar: CookieJar, credentials: Credentials, ) => Promise; /** - * Signs out because your API rejected `credentials` for good, unless - * they're no longer current. Rejects with `INVALID_OPTIONS` given a - * read-only jar. + * Signs `jar`'s session out because your API rejected `credentials` for + * good, unless they're no longer current. Rejects with + * `INVALID_OPTIONS` given a read-only jar. */ reject: (jar: CookieJar, credentials: Credentials) => Promise; }; - /** - * The access token for your own page scripts ({@link ClientCredentials}), - * with the `clientCredentials` option. Expose these only through a - * same-origin server function, action or route handler protected against - * CSRF. Both reject with `INVALID_OPTIONS` without the option. - */ + /** {@link RequestAuth}'s `clientCredentials`, for `jar`. */ clientCredentials: { - /** Like `credentials.get`, refreshing when access has expired. */ + /** + * The access token for your page scripts, for `jar`, as + * {@link RequestAuth}'s `clientCredentials.get` gives it. + */ get: (jar: CookieJar) => Promise; /** - * Like `credentials.renew`, after your API rejected the token. It takes - * what the browser sent, so anything but a session ID and an access - * token rejects with `INVALID_OPTIONS`. + * Renews the page scripts' access token for `jar`, as + * {@link RequestAuth}'s `clientCredentials.renew` does. */ renew: ( jar: CookieJar, @@ -329,17 +376,20 @@ type ServerAuthBase = { ) => Promise; }; /** - * This request's session, shaped like a client ({@link RequestAuth}). The - * same jar always gives the same object. + * This request's session ({@link RequestAuth}), for code that has the + * request's jar. The same jar always gives the same object. */ - forRequest: (jar: CookieJar) => RequestAuth; + forRequest: (jar: CookieJar) => RequestAuth; }; /** * The server side of Session kit, from {@link createServerAuth}. It keeps the - * session in an encrypted cookie. Each method takes the request's - * {@link CookieJar}, and `forRequest(jar)` gives one request's session shaped - * like a client ({@link RequestAuth}). + * session in an encrypted cookie. + * + * Your framework's adapter gives you one request's session + * ({@link RequestAuth}), with every method and no cookie jar. Its methods + * are here too, each taking the request's {@link CookieJar}, for a server + * without an adapter. `forRequest(jar)` gives that request's session. * * `U` is the user, and `I` is the user `signIn` accepts, or `never` with * `fromAccessToken`. Write `typeof serverAuth` rather than spelling them out. @@ -362,10 +412,10 @@ type ServerAuthBase = { * * type User = { id: number; firstName: string }; * declare const serverAuth: ServerAuth; - * declare const jar: CookieJar; * - * export async function greeting() { - * const session = await serverAuth.getSession(jar); + * // On a server without an adapter, with a jar over its request. + * export async function greeting(jar: CookieJar) { + * const session = await serverAuth.forRequest(jar).getSession(); * return session ? `Hi, ${session.user.firstName}` : "Please sign in"; * } * ``` @@ -376,11 +426,7 @@ export type ServerAuth = ServerAuthBase & ([I] extends [never] ? unknown : { - /** - * Replaces the signed-in user and keeps the session, as the - * client's `updateUser` does, then resolves the session. Rejects - * with `INVALID_OPTIONS` given a read-only jar. - */ + /** {@link RequestAuth}'s `updateUser`, for `jar`. */ updateUser: ( jar: CookieJar, input: I | (() => Promise), @@ -395,10 +441,10 @@ const DEFAULT_WITHIN = 60; * tokens and the user in an encrypted, `httpOnly` cookie, so page scripts * never see the refresh token. * - * Create one per app, at module level, and pass each request's - * {@link CookieJar} to its methods. Throws `INVALID_OPTIONS` for options it - * can't use, such as a bad `name`. A missing or short `secret` is reported - * later, when a method first runs. + * Create one per app, at module level, and give it to your framework's + * adapter for each request's session. Throws `INVALID_OPTIONS` for options + * it can't use, such as a bad `name`. A missing or short `secret` is + * reported later, when a method first runs. * * @example * ```ts @@ -484,7 +530,7 @@ export function createServerAuth( if (!jar.writable) throw new AuthError( "INVALID_OPTIONS", - `${method} needs a cookie jar that can set cookies, such as one in a server function, action or route handler`, + `${method} needs a request that can set cookies, such as a server function, action or route handler`, ); } @@ -540,7 +586,7 @@ export function createServerAuth( if (stored.expiresAt !== undefined && stored.expiresAt <= Date.now()) throw new AuthError( "REFRESH_FAILED", - "The access token expired, and this cookie jar can't save a refreshed one; refresh first in middleware or a proxy, with refreshIfDue", + "The access token expired, and this request can't save a refreshed one; refresh first in middleware or a proxy, with refreshIfDue", ); return Object.freeze({ sessionId: stored.id, @@ -568,7 +614,7 @@ export function createServerAuth( }); throw new AuthError( "REFRESH_FAILED", - "This cookie jar can't save a refreshed token; renew in a server function, action or route handler", + "This request can't save a refreshed token; renew in a server function, action or route handler", ); } const client = clientOf(jar); @@ -591,7 +637,7 @@ export function createServerAuth( return session; } - const views = new WeakMap>(); + const views = new WeakMap>(); /** * Runs `read` on `jar`'s client, or `fallback` when there's no client @@ -611,7 +657,18 @@ export function createServerAuth( return read(client); } - function forRequest(jar: CookieJar): RequestAuth { + async function updateUser(jar: CookieJar, input: I | (() => Promise)) { + requireWritable(jar, "updateUser"); + const client = clientOf(jar); + await ( + client as unknown as { + updateUser: (input: unknown) => Promise; + } + ).updateUser(input); + return current(client); + } + + function forRequest(jar: CookieJar): RequestAuth { let view = views.get(jar); if (view) return view; let unusable: AuthState | undefined; @@ -697,9 +754,14 @@ export function createServerAuth( }, }; }; - // The brand exists in types only. - view = Object.freeze({ + // The brand exists in types only. The marker is for code that takes a + // client and must tell a request's session apart. + const members = { + [REQUEST_SESSION]: () => view!, getSession: () => serverAuth.getSession(jar), + refreshIfDue: (refreshOptions?: RefreshIfDueOptions) => + serverAuth.refreshIfDue(jar, refreshOptions), + signIn: (input: SignInInput) => serverAuth.signIn(jar, input), signOut: () => serverAuth.signOut(jar), credentials: Object.freeze({ get: () => getCredentials(jar), @@ -709,6 +771,16 @@ export function createServerAuth( await serverAuth.credentials.reject(jar, credentials); }, }), + clientCredentials: Object.freeze({ + get: () => serverAuth.clientCredentials.get(jar), + renew: (credentials: unknown) => + serverAuth.clientCredentials.renew(jar, credentials), + }), + // A user read from the access token can't be updated on its own. + ...(users.saved && { + updateUser: (input: I | (() => Promise)) => + updateUser(jar, input), + }), isCurrent: (session: { sessionId: string }) => sync( jar, @@ -716,7 +788,8 @@ export function createServerAuth( () => false, ), state: Object.freeze({ get: stateOf, subscribe }), - }) as unknown as RequestAuth; + } satisfies Members; + view = Object.freeze(members) as unknown as RequestAuth; views.set(jar, view); return view; } @@ -799,19 +872,61 @@ export function createServerAuth( }, forRequest, }; - // A user read from the access token can't be updated on its own. if (!users.saved) return serverAuth as ServerAuth; - return { - ...serverAuth, - async updateUser(jar: CookieJar, input: I | (() => Promise)) { - requireWritable(jar, "updateUser"); - const client = clientOf(jar); - await ( - client as unknown as { - updateUser: (input: unknown) => Promise; - } - ).updateUser(input); - return current(client); - }, - } as ServerAuth; + return { ...serverAuth, updateUser } as ServerAuth; +} + +/** + * A request's session that finds its jar on each call, so one object, made at + * module level, serves every request. Methods that return a promise reject, + * rather than throw, when `jarOf` throws outside a request. + */ +export function lazyRequestAuth( + serverAuth: ServerAuth, + jarOf: () => CookieJar, +): RequestAuth { + type View = RequestAuthBase & { + updateUser?: (input: unknown) => Promise>; + }; + const view = () => serverAuth.forRequest(jarOf()) as unknown as View; + const later = + ( + call: (view: View, ...args: A) => Promise, + ): ((...args: A) => Promise) => + async (...args) => + call(view(), ...args); + const lazy = { + [REQUEST_SESSION]: () => view(), + getSession: later((view) => view.getSession()), + refreshIfDue: later((view, options?: RefreshIfDueOptions) => + view.refreshIfDue(options), + ), + signIn: later((view, input: SignInInput) => view.signIn(input)), + signOut: later((view) => view.signOut()), + credentials: Object.freeze({ + get: later((view) => view.credentials.get()), + renew: later((view, credentials: Credentials) => + view.credentials.renew(credentials), + ), + reject: later((view, credentials: Credentials) => + view.credentials.reject(credentials), + ), + }), + clientCredentials: Object.freeze({ + get: later((view) => view.clientCredentials.get()), + renew: later((view, credentials: unknown) => + view.clientCredentials.renew(credentials), + ), + }), + ...("updateUser" in serverAuth && { + updateUser: later((view, input: unknown) => view.updateUser!(input)), + }), + isCurrent: (session: { sessionId: string }) => view().isCurrent(session), + state: Object.freeze({ + get: () => view().state.get(), + subscribe: (listener: (state: AuthState) => void) => + view().state.subscribe(listener), + }), + } satisfies Members; + return Object.freeze(lazy) as unknown as RequestAuth; } diff --git a/src/server/cookies.ts b/src/server/cookies.ts index cdbeb62..d7e3ffe 100644 --- a/src/server/cookies.ts +++ b/src/server/cookies.ts @@ -339,7 +339,7 @@ export function jarStorage(input: { if (!jar.writable) throw new AuthError( "INVALID_OPTIONS", - "This cookie jar can't set cookies, so the session can't be saved here", + "This request can't set cookies, so the session can't be saved here", ); const parts: string[] = []; if (sealed.length > CHUNK_SIZE) { @@ -424,7 +424,7 @@ export function jarStorage(input: { if (!jar.writable) throw new AuthError( "REFRESH_FAILED", - "This cookie jar can't set cookies any more, so the session isn't refreshed here", + "This request can't set cookies any more, so the session isn't refreshed here", ); const tried = session; const failure = tried && shared.failure(tried); diff --git a/src/tanstack-start/server.ts b/src/tanstack-start/server.ts index 08adffd..42e39b3 100644 --- a/src/tanstack-start/server.ts +++ b/src/tanstack-start/server.ts @@ -6,6 +6,11 @@ import { } from "@tanstack/react-start/server"; import { AuthError } from "../core/errors.js"; +import { + lazyRequestAuth, + type RequestAuth, + type ServerAuth, +} from "../server/auth.js"; import type { CookieJar, CookieOptions } from "../server/cookies.js"; /** `options` without unset attributes, which Start's types don't accept. */ @@ -22,10 +27,10 @@ const jars = new WeakMap(); /** * The {@link CookieJar} for the request TanStack Start is handling, to pass - * to `serverAuth` from `@monarcode/session-kit/server`. Use it in a server - * function, request middleware, a server route, or `beforeLoad` and loaders - * while they run on the server. Every call during one request returns the - * same jar. + * to `serverAuth` from `@monarcode/session-kit/server`. {@link startAuth} + * passes it for you. Use it in a server function, request middleware, a + * server route, or `beforeLoad` and loaders while they run on the server. + * Every call during one request returns the same jar. * * Start adds its cookies to the response, a redirect's included, but not * once it has started streaming a page. A cookie set after that is lost, so @@ -59,7 +64,7 @@ export function startJar(): CookieJar { } catch (cause) { throw new AuthError( "INVALID_OPTIONS", - "Call startJar() on the server while TanStack Start handles a request, such as in a server function or request middleware", + "There's no request here: use the session on the server, while TanStack Start handles a request, such as in a server function or request middleware", { cause }, ); } @@ -77,3 +82,46 @@ export function startJar(): CookieJar { } return jar; } + +/** + * The session of the request TanStack Start is handling ({@link RequestAuth}), + * with every `serverAuth` method and no cookie jar. Each call finds the + * current request, so make it once, at module level, beside `serverAuth`. + * + * Use it in server functions, request middleware, server routes, and + * `beforeLoad` and loaders while they run on the server. As + * {@link startJar} explains, Start can't set a cookie once a page streams, + * so refresh before rendering, in request middleware with `refreshIfDue`. + * + * Outside a request, such as in the browser, its methods reject with + * `INVALID_OPTIONS`, and `isCurrent` and `state` throw it. Import it only + * from server code, as you do `serverAuth`. + * + * @example + * ```ts + * import { createServerAuth } from "@monarcode/session-kit/server"; + * import { startAuth } from "@monarcode/session-kit/tanstack-start/server"; + * import { createServerFn } from "@tanstack/react-start"; + * import { z } from "zod"; + * + * declare const secret: string; + * + * const serverAuth = createServerAuth({ + * name: "app", + * user: z.object({ id: z.number(), firstName: z.string() }), + * secret, + * }); + * export const session = startAuth(serverAuth); + * + * export const getSessionFn = createServerFn().handler(() => + * session.getSession(), + * ); + * ``` + * + * @since 0.1.0 + */ +export function startAuth( + serverAuth: ServerAuth, +): RequestAuth { + return lazyRequestAuth(serverAuth, startJar); +} diff --git a/tests/consumer.ts b/tests/consumer.ts index 22daf2e..1c8e1a2 100644 --- a/tests/consumer.ts +++ b/tests/consumer.ts @@ -41,12 +41,15 @@ import { type MirrorAuth, type RefreshFn, type Session, + type SessionOf, type UserInput, + type UserOf, } from "../dist/index.js"; import { nextJar, proxyJar, type NextCookies } from "../dist/next/index.js"; import * as reactRouter from "../dist/react-router/index.js"; import { cookieJarMiddleware, + routerAuth, routerJar, type RouterContextLike, } from "../dist/react-router/server.js"; @@ -70,7 +73,7 @@ import { type RouterAuth, } from "../dist/tanstack-router/index.js"; import { connectSession, loadSession } from "../dist/tanstack-start/index.js"; -import { startJar } from "../dist/tanstack-start/server.js"; +import { startAuth, startJar } from "../dist/tanstack-start/server.js"; const userSchema = z.object({ id: z.string(), email: z.string() }); @@ -125,8 +128,8 @@ void authFetch(); // TanStack Router's hooks, typed by the registered Router. const routerClient: typeof auth = useAuthClient(); -const routerAuth: RouterAuth = routerClient; -void routerAuth; +const routerClientType: RouterAuth = routerClient; +void routerClientType; // The hooks from `./react`, typed by the registered client. const registeredClient: typeof auth = react.useAuthClient(); const registeredEmail: string | undefined = react.useAuth( @@ -529,30 +532,72 @@ const tokenServer = createServerAuth({ // @ts-expect-error A user read from the token has no updateUser. void tokenServer.updateUser; -// One request's session, shaped like a client's read side. -const requestAuth: RequestAuth> = - serverAuth.forRequest(jar); +// One request's session: every server method, without the jar. +type AppUser = z.output; +const requestAuth: RequestAuth = serverAuth.forRequest(jar); async function requestSide() { const session = await requestAuth.getSession(); const viewEmail: string | undefined = session?.user.email; const status: AuthState["status"] = requestAuth.state.get().status; - return [viewEmail, status, await requestAuth.credentials.get()]; + const signedIn: Session = await requestAuth.signIn({ + accessToken: "a", + user: { id: "1", email: "a@example.com" }, + }); + // @ts-expect-error signIn needs the user the schema validates. + await requestAuth.signIn({ accessToken: "a" }); + await requestAuth.updateUser({ id: "1", email: signedIn.user.email }); + await requestAuth.updateUser(async () => ({ + id: "1", + email: "b@example.com", + })); + const refreshed: Session | null = await requestAuth.refreshIfDue({ + within: 30, + }); + const forBrowser = await requestAuth.clientCredentials.get(); + await requestAuth.clientCredentials.renew({ + sessionId: "s", + accessToken: "a", + }); + return [viewEmail, status, refreshed, forBrowser?.expiresIn]; } void requestSide; createAuthFetch(requestAuth, { baseUrl }); createAuthFetch(tokenServer.forRequest(jar), { baseUrl }); -// @ts-expect-error Signing in stays on serverAuth. -void requestAuth.signIn; -// @ts-expect-error So does updateUser. -void requestAuth.updateUser; +// @ts-expect-error A user read from the token has no updateUser. +void tokenServer.forRequest(jar).updateUser; // @ts-expect-error The view is read-only. requestAuth.getSession = async () => null; // @ts-expect-error So is its state. requestAuth.state.get = () => requestAuth.state.get(); +// The adapters' request sessions: the same type, without a jar. +const startSession: RequestAuth = startAuth(serverAuth); +createAuthFetch(startSession, { baseUrl }); +// @ts-expect-error A user read from the token has no updateUser. +void startAuth(tokenServer).updateUser; +const sessionOf = routerAuth(serverAuth); +declare const routerContext: RouterContextLike; +const routerSession: RequestAuth = sessionOf(routerContext); +void routerSession; + +// The session and user types of any client. +const appSession: SessionOf = { + sessionId: "s", + user: { id: "1", email: "a@example.com" }, +}; +const fromRequest: SessionOf = appSession; +const fromClient: SessionOf = fromRequest; +const appUser: UserOf = fromClient.user; +const clientUser: UserOf = appUser; +const tokenUser: UserOf = { sub: "1" }; +// @ts-expect-error The user's fields come from the schema. +const wrongUser: UserOf = { id: 1 }; +void [clientUser, tokenUser, wrongUser]; + // On the server, `Auth.layer` takes a request's session with the registered user. const requestLayer: Layer.Layer = Auth.layer(serverAuth.forRequest(jar)); void Effect.runPromise(Effect.provide(Auth.session, requestLayer)); +Auth.layer(startSession); // @ts-expect-error A request's session with another user doesn't fit. Auth.layer(tokenServer.forRequest(jar)); // @ts-expect-error An Effect that needs the session doesn't run without it. diff --git a/tests/effect.test.ts b/tests/effect.test.ts index c82dd77..12164c1 100644 --- a/tests/effect.test.ts +++ b/tests/effect.test.ts @@ -481,6 +481,7 @@ test("on a request's server session, signIn and updateUser die, and a read-only t.mock.timers.enable({ apis: ["Date"] }); const { serverAuth, request } = serverSide("effect-server"); const signedIn = await serverAuth.signIn(request(), tokens()); + // Its own signIn and updateUser take the server's input, not the browser's. for (const effect of [ Auth.signIn(tokens() as never), Auth.updateUser(user as never), @@ -491,14 +492,15 @@ test("on a request's server session, signIn and updateUser die, and a read-only ); assert.ok(died instanceof AuthError); assert.equal(died.code, "INVALID_OPTIONS"); - assert.match(died.message, /serverAuth\./); + assert.match(died.message, /request's session/); } + const updated = signedIn; t.mock.timers.tick(901_000); const render = Auth.layer(serverAuth.forRequest(request(false))); assert.deepEqual( await Effect.runPromise(Effect.provide(Auth.session, render)), - signedIn, + updated, ); const failed = await Effect.runPromise( Effect.provide(Effect.flip(Auth.credentials), render), diff --git a/tests/package.test.ts b/tests/package.test.ts index ad0691b..875cf58 100644 --- a/tests/package.test.ts +++ b/tests/package.test.ts @@ -28,6 +28,7 @@ import { } from "@monarcode/session-kit/react-router"; import { cookieJarMiddleware, + routerAuth, routerJar, } from "@monarcode/session-kit/react-router/server"; import { createServerAuth } from "@monarcode/session-kit/server"; @@ -43,7 +44,10 @@ import { connectSession, loadSession, } from "@monarcode/session-kit/tanstack-start"; -import { startJar } from "@monarcode/session-kit/tanstack-start/server"; +import { + startAuth, + startJar, +} from "@monarcode/session-kit/tanstack-start/server"; const packageRoot = new URL("../", import.meta.url); @@ -58,6 +62,7 @@ test("all public entry points import without browser globals", () => { loadSession, connectSession, startJar, + startAuth, nextJar, proxyJar, useMirrorAuth, @@ -76,6 +81,7 @@ test("all public entry points import without browser globals", () => { useAuthRevalidation, cookieJarMiddleware, routerJar, + routerAuth, createAuthFetch, Auth, AuthFailure, diff --git a/tests/react-router-server.test.ts b/tests/react-router-server.test.ts index 29daf90..6775d3c 100644 --- a/tests/react-router-server.test.ts +++ b/tests/react-router-server.test.ts @@ -6,6 +6,7 @@ import * as reactRouter from "react-router"; import type { Credentials, Session } from "@monarcode/session-kit"; import { cookieJarMiddleware, + routerAuth, routerJar, type RouterContextLike, } from "@monarcode/session-kit/react-router/server"; @@ -79,6 +80,33 @@ test("routerJar needs cookieJarMiddleware", () => { assert.throws(() => routerJar(newContext()), code("INVALID_OPTIONS")); }); +test("routerAuth gives the request's session by its context", async () => { + const auth = routerAuth(serverAuth); + assert.throws(() => auth(newContext()), code("INVALID_OPTIONS")); + + let signedIn: Session | undefined; + const context = newContext(); + const response = await cookieJarMiddleware( + { request: request(), context }, + async () => { + const session = auth(context); + assert.equal(auth(context), session); + assert.equal(session, serverAuth.forRequest(routerJar(context))); + signedIn = await session.signIn(tokens()); + return new Response("ok"); + }, + ); + const cookie = cookieHeader(response); + const read = newContext(); + await cookieJarMiddleware( + { request: request(cookie), context: read }, + async () => { + assert.deepEqual(await auth(read).getSession(), signedIn); + return new Response("ok"); + }, + ); +}); + test("cookieJarMiddleware sets the cookies a request wrote on its response", async () => { const context = newContext(); let session: Session | undefined; diff --git a/tests/server.test.ts b/tests/server.test.ts index 2708f49..0410a33 100644 --- a/tests/server.test.ts +++ b/tests/server.test.ts @@ -714,6 +714,60 @@ test("forRequest gives one request's session, shaped like a client", async (t) = assert.equal(await app.getSession(tab.request()), null); }); +test("forRequest signs in, updates the user, refreshes when due and serves the browser's token", async (t) => { + t.mock.timers.enable({ apis: ["Date"] }); + let refreshes = 0; + const app = server({ + clientCredentials: true, + refresh: async () => { + refreshes++; + return { accessToken: `access-${refreshes + 1}`, expiresIn: 900 }; + }, + }); + const tab = browser(); + const view = app.forRequest(tab.request()); + assert.ok(Object.isFrozen(view.clientCredentials)); + + const signedIn = await view.signIn(tokens()); + assert.deepEqual(await app.getSession(tab.request(false)), signedIn); + const updated = await view.updateUser({ ...user, role: "admin" }); + assert.equal(updated.sessionId, signedIn.sessionId); + assert.equal((await app.getSession(tab.request(false)))?.user.role, "admin"); + + const forBrowser = await view.clientCredentials.get(); + assert.equal(forBrowser?.accessToken, "access-1"); + // Not due yet: nothing is refreshed. + assert.deepEqual(await view.refreshIfDue(), updated); + assert.equal(refreshes, 0); + const renewed = await view.clientCredentials.renew({ + sessionId: forBrowser!.sessionId, + accessToken: "access-1", + }); + assert.equal(renewed?.accessToken, "access-2"); + + // Within the window, a later request's view refreshes once. + t.mock.timers.tick(850_000); + const later = app.forRequest(tab.request()); + await later.refreshIfDue({ within: 60 }); + await later.refreshIfDue({ within: 60 }); + assert.equal(refreshes, 2); + + // A request that can't set cookies can't sign in or refresh. + const render = app.forRequest(tab.request(false)); + await assert.rejects(render.signIn(tokens()), code("INVALID_OPTIONS")); + await assert.rejects(render.refreshIfDue(), code("INVALID_OPTIONS")); + await assert.rejects(render.updateUser(user), code("INVALID_OPTIONS")); +}); + +test("with fromAccessToken, a request's session has no updateUser", () => { + const app = createServerAuth({ + name: "test", + user: fromAccessToken(z.object({ sub: z.string() })), + secret: SECRET, + }); + assert.equal("updateUser" in app.forRequest(browser().request()), false); +}); + test("forRequest renews and rejects as serverAuth's credentials do", async () => { let refreshes = 0; const app = server({ diff --git a/tests/tanstack-start.test.ts b/tests/tanstack-start.test.ts index 79c24cd..7ab5f5c 100644 --- a/tests/tanstack-start.test.ts +++ b/tests/tanstack-start.test.ts @@ -8,18 +8,24 @@ import { type MirrorAuth, type Session, } from "@monarcode/session-kit"; +import { Auth } from "@monarcode/session-kit/effect"; +import { createAuthFetch } from "@monarcode/session-kit/http"; import { createServerAuth } from "@monarcode/session-kit/server"; import { connectSession, loadSession, } from "@monarcode/session-kit/tanstack-start"; -import { startJar } from "@monarcode/session-kit/tanstack-start/server"; +import { + startAuth, + startJar, +} from "@monarcode/session-kit/tanstack-start/server"; import { createServerEntry, getResponseHeaders, } from "@tanstack/react-start/server"; +import * as Effect from "effect/Effect"; -import { code, SECRET, user, userSchema } from "./helpers.ts"; +import { code, deferred, SECRET, tokens, user, userSchema } from "./helpers.ts"; type User = typeof user; @@ -122,6 +128,129 @@ test("startJar sets and deletes every chunk of a large session", async () => { ); }); +// Made once, at module level, as an app does. +const session = startAuth(serverAuth); + +test("startAuth finds each request's session, and rejects outside a request", async () => { + await assert.rejects(session.getSession(), code("INVALID_OPTIONS")); + await assert.rejects(session.credentials.get(), code("INVALID_OPTIONS")); + assert.throws(() => session.state.get(), code("INVALID_OPTIONS")); + assert.ok(Object.isFrozen(session)); + + const signedIn = await handle("", () => session.signIn(tokens())); + assert.match(signedIn.setCookies[0]!, /^app\.session=1\./); + const cookie = cookieHeader(signedIn.setCookies); + + const read = await handle(cookie, async () => { + const current = await session.getSession(); + assert.equal(session.isCurrent(current!), true); + assert.equal(session.state.get().sessionId, current!.sessionId); + return current; + }); + assert.deepEqual(read.result, signedIn.result); + assert.equal((await handle("", () => session.getSession())).result, null); + + const updated = await handle(cookie, () => + session.updateUser({ ...user, role: "admin" }), + ); + assert.equal(updated.result.user.role, "admin"); + + const signedOut = await handle(cookieHeader(updated.setCookies), () => + session.signOut(), + ); + assert.match(signedOut.setCookies[0]!, /^app\.session=; Max-Age=0/); +}); + +test("startAuth has every member a request's session has, passed through", async () => { + const app = createServerAuth({ + name: "app", + user: userSchema, + secret: SECRET, + clientCredentials: true, + refresh: async () => ({ + accessToken: `access-${++refreshes}`, + expiresIn: 900, + }), + }); + let refreshes = 1; + const lazy = startAuth(app); + const signedIn = await handle("", () => lazy.signIn(tokens())); + const { result } = await handle( + cookieHeader(signedIn.setCookies), + async () => { + const view = app.forRequest(startJar()); + const keys = (value: object) => Object.keys(value).sort(); + assert.deepEqual(keys(lazy), keys(view)); + for (const member of [ + "credentials", + "clientCredentials", + "state", + ] as const) + assert.deepEqual(keys(lazy[member]), keys(view[member])); + + assert.deepEqual(await lazy.refreshIfDue(), signedIn.result); + const credentials = await lazy.credentials.get(); + const renewed = await lazy.credentials.renew(credentials!); + assert.equal(renewed?.accessToken, "access-2"); + const forBrowser = await lazy.clientCredentials.get(); + assert.equal(forBrowser?.accessToken, "access-2"); + assert.equal( + (await lazy.clientCredentials.renew(forBrowser!))?.accessToken, + "access-3", + ); + const seen: string[] = []; + const { unsubscribe } = lazy.state.subscribe((state) => + seen.push(state.status), + ); + await lazy.credentials.reject((await lazy.credentials.get())!); + unsubscribe(); + assert.ok(seen.includes("unauthenticated")); + return view.state.get().sessionId; + }, + ); + assert.equal(result, null); +}); + +test("Auth.layer binds a startAuth session to the request that's current", async () => { + assert.throws(() => Auth.layer(session), code("INVALID_OPTIONS")); + const signedIn = await handle("", () => session.signIn(tokens())); + const read = await handle(cookieHeader(signedIn.setCookies), () => + Effect.runPromise(Effect.provide(Auth.session, Auth.layer(session))), + ); + assert.deepEqual(read.result, signedIn.result); +}); + +test("one module-level createAuthFetch over startAuth sends each request's own token", async (t) => { + const alice = await handle("", () => + session.signIn(tokens({ accessToken: "alice-token" })), + ); + const bob = await handle("", () => + session.signIn( + tokens({ accessToken: "bob-token", user: { ...user, id: "bob" } }), + ), + ); + const authFetch = createAuthFetch(session, { baseUrl: "https://api.test" }); + + // Both requests are in flight before either answers. + const bothSent = deferred(); + let sent = 0; + t.mock.method(globalThis, "fetch", async (request: Request) => { + if (++sent === 2) bothSent.resolve(); + await bothSent.promise; + return new Response(request.headers.get("authorization")); + }); + const [fromAlice, fromBob] = await Promise.all([ + handle(cookieHeader(alice.setCookies), async () => + (await authFetch("/me")).text(), + ), + handle(cookieHeader(bob.setCookies), async () => + (await authFetch("/me")).text(), + ), + ]); + assert.equal(fromAlice.result, "Bearer alice-token"); + assert.equal(fromBob.result, "Bearer bob-token"); +}); + /** The app's own data, beside the session, as TanStack Query's would be. */ type Own = { theme: string }; From 4f9ec53e1fc9e876b5caded3df524fa689e787dc Mon Sep 17 00:00:00 2001 From: monarcode Date: Sat, 14 Nov 2026 02:21:00 +0100 Subject: [PATCH 05/26] feat(server): middleware and server guards for Start, React Router and Next; export loginHref --- CHANGELOG.md | 33 ++ examples/README.md | 8 +- examples/next-app/app/actions.ts | 19 +- .../app/api/auth/credentials/route.ts | 10 +- examples/next-app/app/layout.tsx | 6 +- examples/next-app/app/login/page.tsx | 8 +- examples/next-app/app/page.tsx | 11 +- examples/next-app/lib/auth/session.ts | 29 +- examples/next-app/proxy.ts | 12 +- .../app/auth/middleware.server.ts | 47 --- .../app/auth/session.server.ts | 13 +- .../react-router-framework-ssr/app/root.tsx | 15 +- .../app/routes/login.tsx | 12 +- .../app/routes/protected.tsx | 8 +- .../tanstack-start-ssr/src/auth/server.ts | 2 +- examples/tanstack-start-ssr/src/start.ts | 19 +- site/content/docs/(latest)/effect.mdx | 6 +- site/content/docs/(latest)/reference/core.mdx | 4 + .../content/docs/(latest)/reference/index.mdx | 30 +- site/content/docs/(latest)/reference/next.mdx | 18 + .../reference/react-router-server.mdx | 38 ++ .../docs/(latest)/reference/server.mdx | 10 + .../reference/tanstack-start-server.mdx | 4 + .../docs/(latest)/server-rendering/index.mdx | 16 +- .../server-rendering/server-sessions.mdx | 13 +- site/content/docs/(latest)/setups/next.mdx | 156 +++----- .../docs/(latest)/setups/react-router-ssr.mdx | 297 +++++++------- .../docs/(latest)/setups/tanstack-start.mdx | 30 +- src/core/return-to.ts | 24 +- src/index.ts | 2 +- src/next/index.ts | 183 +++++++++ src/react-router/basename.ts | 25 ++ src/react-router/guards.ts | 21 +- src/react-router/server.ts | 360 ++++++++++++++++- src/server/auth.ts | 78 +++- src/server/index.ts | 1 + src/server/request-jar.ts | 22 +- src/tanstack-start/server.ts | 63 +++ tests/consumer.ts | 82 +++- tests/next.test.ts | 121 ++++++ tests/react-router-server.test.ts | 374 +++++++++++++++++- tests/tanstack-start.test.ts | 127 ++++++ 42 files changed, 1857 insertions(+), 500 deletions(-) delete mode 100644 examples/react-router-framework-ssr/app/auth/middleware.server.ts create mode 100644 src/react-router/basename.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 26ad47d..2f899f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,39 @@ type AppSession = SessionOf; // { sessionId, user } ``` +- Middleware and server guards for the server-rendered setups, in place of + the code the guides had you copy. Each refreshes before rendering, while a + cookie can still be set, and ignores a failed refresh. The TanStack Start + and React Router middleware also mark each response that doesn't set its + own `Cache-Control` as `private, no-store` (`cacheControl` changes or + skips it). Next.js marks pages that read cookies `no-store` itself. + - TanStack Start: `refreshSession(serverAuth, options?)` in + `@monarcode/session-kit/tanstack-start/server`, a handler for Start's + `createMiddleware({ type: "request" }).server()`. Start strips what's in + `.server()` from the browser bundle, `serverAuth` included. + - React Router: `sessionMiddleware(serverAuth, options?)` for the root + route, `requireSession(serverAuth, { loginPath, basename })` for guarded + routes, whose `session(context)` gives their loaders a session that's + never `null`, and `redirectIfSignedIn(serverAuth, options?)` as the + sign-in page's loader, in `@monarcode/session-kit/react-router/server`. + - Next.js: `nextSession(serverAuth, { cookies, redirect })` in + `@monarcode/session-kit/next`, with `get()`, `require(path)` and + `redirectIfSignedIn(redirectTo)` for Server Components, `readOnly()` and + `writable()` for the request's session, and `refresh(request, response)` + for `proxy.ts`. You pass Next's own `cookies` and `redirect`. + + ```ts + // app/root.tsx + export const middleware = sessionMiddleware(serverAuth); + // app/routes/protected.tsx + export const middleware = [signedIn]; // signedIn = requireSession(serverAuth) + ``` + +- `loginHref(loginPath, returnTo)` in `@monarcode/session-kit` builds the + sign-in page's URL with `?redirectTo=`, for a guard of your own. +- `SessionMiddlewareOptions` in `@monarcode/session-kit/server`: `within` + and `cacheControl`, for `refreshSession` and `sessionMiddleware`. + ### Changed - **Breaking:** `createAuthFetch` takes the base URL as an option, as diff --git a/examples/README.md b/examples/README.md index 5df2b9a..4c2dbff 100644 --- a/examples/README.md +++ b/examples/README.md @@ -90,12 +90,12 @@ run ios` and `run android` build it natively. In CI it is only bundled, with `SESSION_SECRET` and Safari work as for TanStack Start, with `next start` and `next dev`. See [the guide](https://session-kit.pages.dev/docs/setups/next). - **React Router with server rendering** keeps the session the same way. - Root middleware (`app/auth/middleware.server.ts`) gives each request a - cookie jar and refreshes, the root loader reads the session, and the sign-in - route's action signs in with a plain form that works before scripts load. + The root route's `sessionMiddleware` gives each request a cookie jar and + refreshes, the root loader reads the session, and the sign-in route's + action signs in with a plain form that works before scripts load. `useMirrorAuth` in `app/root.tsx` gives the components the client and runs the loaders again when the session changes in the browser, so the - protected route's middleware redirects. The browser signs out, revalidates + protected route's `requireSession` guard redirects. The browser signs out, revalidates and gets the access token through the resource routes in `app/routes/auth.*.ts`. `SESSION_SECRET` and Safari work as for TanStack Start, with `pnpm start` (after `pnpm build`) and `react-router dev`. See diff --git a/examples/next-app/app/actions.ts b/examples/next-app/app/actions.ts index bafbdeb..c68216d 100644 --- a/examples/next-app/app/actions.ts +++ b/examples/next-app/app/actions.ts @@ -2,20 +2,14 @@ // Server Functions the browser calls. Each is a public endpoint: Next checks // that calls come from this site, and each one checks its own input. -import { nextJar } from "@monarcode/session-kit/next"; -import { cookies } from "next/headers"; import { z } from "zod"; import { login } from "../lib/auth/backend"; -import { serverAuth } from "../lib/auth/server"; - -async function jar() { - return nextJar(await cookies(), { writable: true }); -} +import { session } from "../lib/auth/session"; /** Who is signed in, from the cookie. Holds no tokens. */ export async function getSessionAction() { - return serverAuth.getSession(await jar()); + return (await session.writable()).getSession(); } const credentials = z.object({ username: z.string(), password: z.string() }); @@ -29,10 +23,9 @@ export async function signInAction(input: unknown) { const { username, password } = credentials.parse(input); try { return { - session: await serverAuth.signIn( - await jar(), - await login(username, password), - ), + session: await ( + await session.writable() + ).signIn(await login(username, password)), }; } catch (error) { return { @@ -43,5 +36,5 @@ export async function signInAction(input: unknown) { /** Clears the cookie. */ export async function signOutAction() { - await serverAuth.signOut(await jar()); + await (await session.writable()).signOut(); } diff --git a/examples/next-app/app/api/auth/credentials/route.ts b/examples/next-app/app/api/auth/credentials/route.ts index 6a9d4d1..5305c80 100644 --- a/examples/next-app/app/api/auth/credentials/route.ts +++ b/examples/next-app/app/api/auth/credentials/route.ts @@ -1,8 +1,6 @@ -import { nextJar } from "@monarcode/session-kit/next"; -import { cookies } from "next/headers"; import { z } from "zod"; -import { serverAuth } from "../../../../lib/auth/server"; +import { session } from "../../../../lib/auth/session"; const rejected = z.object({ sessionId: z.string(), accessToken: z.string() }); @@ -16,11 +14,11 @@ export async function POST(request: Request) { // Route handlers get no CSRF check from Next: accept this site only. if (request.headers.get("sec-fetch-site") !== "same-origin") return new Response(null, { status: 403 }); - const jar = nextJar(await cookies(), { writable: true }); + const auth = await session.writable(); const body = rejected.safeParse(await request.json().catch(() => null)); const credentials = body.success - ? await serverAuth.clientCredentials.renew(jar, body.data) - : await serverAuth.clientCredentials.get(jar); + ? await auth.clientCredentials.renew(body.data) + : await auth.clientCredentials.get(); return Response.json(credentials, { headers: { "Cache-Control": "no-store" }, }); diff --git a/examples/next-app/app/layout.tsx b/examples/next-app/app/layout.tsx index 93950ac..54ff386 100644 --- a/examples/next-app/app/layout.tsx +++ b/examples/next-app/app/layout.tsx @@ -1,6 +1,6 @@ import type { ReactNode } from "react"; -import { getSession } from "../lib/auth/session"; +import { session } from "../lib/auth/session"; import { Providers } from "./providers"; export const metadata = { title: "session-kit with Next.js" }; @@ -10,11 +10,11 @@ export default async function RootLayout({ }: { children: ReactNode; }) { - const session = await getSession(); + const current = await session.get(); return ( - {children} + {children} ); diff --git a/examples/next-app/app/login/page.tsx b/examples/next-app/app/login/page.tsx index 8751832..c620fc2 100644 --- a/examples/next-app/app/login/page.tsx +++ b/examples/next-app/app/login/page.tsx @@ -1,7 +1,4 @@ -import { safeReturnTo } from "@monarcode/session-kit"; -import { redirect } from "next/navigation"; - -import { getSession } from "../../lib/auth/session"; +import { session } from "../../lib/auth/session"; import { LoginForm } from "../ui"; export default async function Login({ @@ -10,7 +7,6 @@ export default async function Login({ searchParams: Promise>; }) { // Signed in, before or after the form: the server sends the user on. - if (await getSession()) - redirect(safeReturnTo((await searchParams).redirectTo)); + await session.redirectIfSignedIn((await searchParams).redirectTo); return ; } diff --git a/examples/next-app/app/page.tsx b/examples/next-app/app/page.tsx index 1696a39..1ab85c3 100644 --- a/examples/next-app/app/page.tsx +++ b/examples/next-app/app/page.tsx @@ -1,18 +1,13 @@ -import { nextJar } from "@monarcode/session-kit/next"; -import { cookies } from "next/headers"; import { z } from "zod"; import { API } from "../lib/auth/api"; -import { serverAuth } from "../lib/auth/server"; -import { requireSession } from "../lib/auth/session"; +import { session } from "../lib/auth/session"; import { Profile } from "./ui"; /** Calls DummyJSON's `auth/me` while rendering, with the cookie's token. */ async function profileEmail() { // Read-only: Proxy refreshed the token before this render. - const credentials = await serverAuth.credentials.get( - nextJar(await cookies()), - ); + const credentials = await (await session.readOnly()).credentials.get(); if (!credentials) return "Signed out"; const response = await fetch(`${API}/auth/me`, { headers: { Authorization: `Bearer ${credentials.accessToken}` }, @@ -23,7 +18,7 @@ async function profileEmail() { } export default async function Home() { - await requireSession("/"); + await session.require("/"); const fromServer = await profileEmail().catch( (error: unknown) => (error as Error).message, ); diff --git a/examples/next-app/lib/auth/session.ts b/examples/next-app/lib/auth/session.ts index 9d5fa3c..9fb40fd 100644 --- a/examples/next-app/lib/auth/session.ts +++ b/examples/next-app/lib/auth/session.ts @@ -1,26 +1,19 @@ -// The data access layer: how Server Components read the session. +// How server code reads and changes the session. import "server-only"; -import { cache } from "react"; - -import { safeReturnTo } from "@monarcode/session-kit"; -import { nextJar } from "@monarcode/session-kit/next"; +import { nextSession } from "@monarcode/session-kit/next"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; import { serverAuth } from "./server"; /** - * The session from the cookie, once per render. The jar is read-only, as - * Server Components can't set cookies: Proxy refreshed it first. + * The session for Server Components, Server Functions, Route Handlers and + * Proxy. Server Components read it with `get` and `require`, which can't set + * cookies: Proxy refreshed it first, with `refresh`. */ -export const getSession = cache(async () => - serverAuth.getSession(nextJar(await cookies())), -); - -/** The session, or a redirect to the sign-in page that comes back to `path`. */ -export async function requireSession(path: string) { - const session = await getSession(); - if (!session) - redirect(`/login?redirectTo=${encodeURIComponent(safeReturnTo(path))}`); - return session; -} +export const session = nextSession(serverAuth, { + cookies, + redirect, + // The example's tokens live a minute: refresh in their last 15 seconds. + within: 15, +}); diff --git a/examples/next-app/proxy.ts b/examples/next-app/proxy.ts index ee0a211..4378229 100644 --- a/examples/next-app/proxy.ts +++ b/examples/next-app/proxy.ts @@ -1,7 +1,6 @@ -import { proxyJar } from "@monarcode/session-kit/next"; import { NextResponse, type NextRequest } from "next/server"; -import { serverAuth } from "./lib/auth/server"; +import { session } from "./lib/auth/session"; /** * Refreshes access that is about to expire before Server Components and @@ -9,13 +8,8 @@ import { serverAuth } from "./lib/auth/server"; * Proxy can, and Next passes the new cookie on to them. A failed refresh is * left for the page, which then reads the session as it was. */ -export async function proxy(request: NextRequest) { - const response = NextResponse.next(); - // The example's tokens live a minute: refresh in their last 15 seconds. - await serverAuth - .refreshIfDue(proxyJar(request, response), { within: 15 }) - .catch(() => {}); - return response; +export function proxy(request: NextRequest) { + return session.refresh(request, NextResponse.next()); } export const config = { diff --git a/examples/react-router-framework-ssr/app/auth/middleware.server.ts b/examples/react-router-framework-ssr/app/auth/middleware.server.ts deleted file mode 100644 index d2a7081..0000000 --- a/examples/react-router-framework-ssr/app/auth/middleware.server.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { redirect, type MiddlewareFunction } from "react-router"; - -import { cookieJarMiddleware } from "@monarcode/session-kit/react-router/server"; - -import { auth } from "./session.server"; - -/** - * Refreshes access that is about to expire before loaders and actions read - * it, while the response can still set the cookie. A failed refresh is left - * for the loaders, which then read the session as it was. - */ -const refreshSession: MiddlewareFunction = async ( - { context }, - next, -) => { - // The example's tokens live a minute: refresh in their last 15 seconds. - await auth(context) - .refreshIfDue({ within: 15 }) - .catch(() => {}); - const response = await next(); - // Every page and resource route here depends on who is signed in. A - // copy: some responses, such as `fetch`'s, can't change their headers. - const page = new Response(response.body, response); - page.headers.set("Cache-Control", "private, no-store"); - return page; -}; - -/** - * The root route's middleware. The jar comes first: it sets the cookies the - * rest write on the response. - */ -export const sessionMiddleware = [cookieJarMiddleware, refreshSession]; - -/** - * Sends signed-out users to the sign-in page, which brings them back. As - * middleware, it runs on the server before any loader or action below the - * route, for documents and for data requests alike. - */ -export const requireSession: MiddlewareFunction = async ({ - context, - url, -}) => { - if (!(await auth(context).getSession())) - throw redirect( - `/login?redirectTo=${encodeURIComponent(url.pathname + url.search)}`, - ); -}; diff --git a/examples/react-router-framework-ssr/app/auth/session.server.ts b/examples/react-router-framework-ssr/app/auth/session.server.ts index 546e2ab..e2e42e0 100644 --- a/examples/react-router-framework-ssr/app/auth/session.server.ts +++ b/examples/react-router-framework-ssr/app/auth/session.server.ts @@ -1,6 +1,9 @@ // Holds the secret and the tokens: the `.server` name keeps it out of the // browser's bundle, and the build fails if browser code imports it. -import { routerAuth } from "@monarcode/session-kit/react-router/server"; +import { + requireSession, + routerAuth, +} from "@monarcode/session-kit/react-router/server"; import { createServerAuth } from "@monarcode/session-kit/server"; import { refresh, userSchema } from "./backend"; @@ -38,3 +41,11 @@ export const serverAuth = createServerAuth({ * `auth(context).getSession()` in a loader, action or middleware. */ export const auth = routerAuth(serverAuth); + +/** + * Lets only signed-in users through to the routes it guards, as middleware: + * it runs on the server before their loaders and actions, for page loads and + * navigation alike. Signed-out users go to the sign-in page, which brings + * them back. `signedIn.session(context)` gives those loaders the session. + */ +export const signedIn = requireSession(serverAuth); diff --git a/examples/react-router-framework-ssr/app/root.tsx b/examples/react-router-framework-ssr/app/root.tsx index d748742..7a9caee 100644 --- a/examples/react-router-framework-ssr/app/root.tsx +++ b/examples/react-router-framework-ssr/app/root.tsx @@ -12,10 +12,10 @@ import { } from "react-router"; import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react"; +import { sessionMiddleware } from "@monarcode/session-kit/react-router/server"; import { createAppAuth, type AppAuth } from "./auth/client"; -import { sessionMiddleware } from "./auth/middleware.server"; -import { auth } from "./auth/session.server"; +import { auth, serverAuth } from "./auth/session.server"; // Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` // with this client. @@ -25,7 +25,16 @@ declare module "@monarcode/session-kit" { } } -export const middleware = sessionMiddleware; +/** + * Gives each request its cookies, then refreshes access that is about to + * expire before loaders and actions read it, while the response can still + * set the cookie. Every response is marked private, as each one depends on + * who is signed in. + */ +export const middleware = sessionMiddleware(serverAuth, { + // The example's tokens live a minute: refresh in their last 15 seconds. + within: 15, +}); /** Who is signed in, from the cookie. Holds no tokens. */ export async function loader({ context }: LoaderFunctionArgs) { diff --git a/examples/react-router-framework-ssr/app/routes/login.tsx b/examples/react-router-framework-ssr/app/routes/login.tsx index 9c74e39..bd7d11f 100644 --- a/examples/react-router-framework-ssr/app/routes/login.tsx +++ b/examples/react-router-framework-ssr/app/routes/login.tsx @@ -3,21 +3,17 @@ import { useActionData, useNavigation, type ActionFunctionArgs, - type LoaderFunctionArgs, } from "react-router"; import { safeReturnTo } from "@monarcode/session-kit"; +import { redirectIfSignedIn } from "@monarcode/session-kit/react-router/server"; import { login } from "../auth/backend"; -import { auth } from "../auth/session.server"; +import { auth, serverAuth } from "../auth/session.server"; import { LoginForm } from "../ui"; -/** Signed in, before or after the form: the server sends the user on. */ -export async function loader({ context, url }: LoaderFunctionArgs) { - if (await auth(context).getSession()) - throw redirect(safeReturnTo(url.searchParams.get("redirectTo"))); - return null; -} +/** Signed in already: the server sends the user on to `redirectTo`. */ +export const loader = redirectIfSignedIn(serverAuth); /** * Signs in with DummyJSON on the server and sets the cookie. React Router diff --git a/examples/react-router-framework-ssr/app/routes/protected.tsx b/examples/react-router-framework-ssr/app/routes/protected.tsx index 9d2050f..351fd3d 100644 --- a/examples/react-router-framework-ssr/app/routes/protected.tsx +++ b/examples/react-router-framework-ssr/app/routes/protected.tsx @@ -1,8 +1,12 @@ import { Outlet } from "react-router"; -import { requireSession } from "../auth/middleware.server"; +import { signedIn } from "../auth/session.server"; -export const middleware = [requireSession]; +export const middleware = [signedIn]; + +// So navigation in the browser runs the middleware, whatever the routes +// nested here load. +export const loader = () => null; export default function Protected() { return ; diff --git a/examples/tanstack-start-ssr/src/auth/server.ts b/examples/tanstack-start-ssr/src/auth/server.ts index 5ae3b09..aa942f8 100644 --- a/examples/tanstack-start-ssr/src/auth/server.ts +++ b/examples/tanstack-start-ssr/src/auth/server.ts @@ -22,7 +22,7 @@ function sessionSecret(): string { * `clientCredentials`, the browser can ask for the access token too, through * the server functions in `functions.ts`; the refresh token stays here. */ -const serverAuth = createServerAuth({ +export const serverAuth = createServerAuth({ name: "session-kit-example", user: userSchema, secret: sessionSecret(), diff --git a/examples/tanstack-start-ssr/src/start.ts b/examples/tanstack-start-ssr/src/start.ts index f07e3a3..50a67f1 100644 --- a/examples/tanstack-start-ssr/src/start.ts +++ b/examples/tanstack-start-ssr/src/start.ts @@ -1,26 +1,21 @@ +import { refreshSession } from "@monarcode/session-kit/tanstack-start/server"; import { createCsrfMiddleware, createMiddleware, createStart, } from "@tanstack/react-start"; -import { setResponseHeader } from "@tanstack/react-start/server"; -import { session } from "./auth/server"; +import { serverAuth } from "./auth/server"; /** * Refreshes access that is about to expire before routes and server - * functions read it, while the response can still set the cookie. A failed - * refresh is left for the route: `loadSession` then rejects, and the root - * route's error component offers a retry. + * functions read it, while the response can still set the cookie. Start + * keeps what's inside `.server()` out of the browser bundle, `serverAuth` + * included. */ const sessionMiddleware = createMiddleware({ type: "request" }).server( - async ({ next }) => { - // Every page and server function here depends on who is signed in. - setResponseHeader("Cache-Control", "private, no-store"); - // The example's tokens live a minute: refresh in their last 15 seconds. - await session.refreshIfDue({ within: 15 }).catch(() => {}); - return next(); - }, + // The example's tokens live a minute: refresh in their last 15 seconds. + refreshSession(serverAuth, { within: 15 }), ); export const startInstance = createStart(() => ({ diff --git a/site/content/docs/(latest)/effect.mdx b/site/content/docs/(latest)/effect.mdx index d3419e9..624b026 100644 --- a/site/content/docs/(latest)/effect.mdx +++ b/site/content/docs/(latest)/effect.mdx @@ -573,8 +573,8 @@ import type { ServerSession } from "./auth.js"; import { runRequest } from "./run.js"; // TanStack Start: startAuth(serverAuth). React Router: -// routerAuth(serverAuth)(context). Next.js: -// serverAuth.forRequest(nextJar(await cookies(), { writable: true })). +// routerAuth(serverAuth)(context). Next.js: await session.writable(), +// from nextSession(serverAuth, { cookies, redirect }). export const profileFor = (session: ServerSession) => runRequest(session, currentUser); ``` @@ -661,7 +661,7 @@ the mirror client. `Auth.credentials` and `sessionBearer` fail with `REFRESH_FAILED` once access has expired, and after a 401, which can't be renewed there unless the same request already renewed it where it could. Refresh in middleware - or a proxy first, with `refreshIfDue`, as the framework guides do. Sign + or Proxy first, as the framework guides do. Sign out in an action or route handler. - **Only `Auth`'s Effects.** A request's session isn't your browser client, so don't reach for client methods through `Auth.use` there. diff --git a/site/content/docs/(latest)/reference/core.mdx b/site/content/docs/(latest)/reference/core.mdx index f8b2366..e3364f8 100644 --- a/site/content/docs/(latest)/reference/core.mdx +++ b/site/content/docs/(latest)/reference/core.mdx @@ -23,6 +23,10 @@ Creates a browser client ([`MirrorAuth`](#mirrorauth)) for a session your server Reads the user from the access token, rather than from what `signIn` is given. Pass the result as `createAuth`'s `user` option. +### loginHref + +Builds the sign-in page's URL, with `?redirectTo=` set to `returnTo`, so the user comes back after signing in. The guards use it. Use it in a guard of your own, such as in a route handler. + ### memoryStorage Keeps the session in memory only. It ends when the page unloads, and other tabs never see it. Use it in tests, or where tokens must never be written to disk. Each call has its own entries. diff --git a/site/content/docs/(latest)/reference/index.mdx b/site/content/docs/(latest)/reference/index.mdx index 2c1333b..f98614c 100644 --- a/site/content/docs/(latest)/reference/index.mdx +++ b/site/content/docs/(latest)/reference/index.mdx @@ -12,21 +12,21 @@ exports, with their options and types. Import from these paths only. Internal `dist` paths aren't part of the public API. -| Import | Exports | -| --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -| [`@monarcode/session-kit`](/docs/reference/core) | `createAuth`, `createMirrorAuth`, `fromAccessToken`, `webStorage`, `memoryStorage`, `safeReturnTo`, `AuthError`, types | -| [`@monarcode/session-kit/react`](/docs/reference/react) | `AuthProvider`, `useAuth`, `useAuthClient`, `createAuthHooks`, `useMirrorAuth`, types | -| [`@monarcode/session-kit/tanstack-router`](/docs/reference/tanstack-router) | `connectAuth`, `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuth`, `useAuthClient`, types | -| [`@monarcode/session-kit/react-router`](/docs/reference/react-router) | `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuthRevalidation`, types | -| [`@monarcode/session-kit/react-router/server`](/docs/reference/react-router-server) | `routerAuth`, `cookieJarMiddleware`, `routerJar`, types | -| [`@monarcode/session-kit/http`](/docs/reference/http) | `createAuthFetch`, types | -| [`@monarcode/session-kit/server`](/docs/reference/server) | `createServerAuth`, types | -| [`@monarcode/session-kit/tanstack-start`](/docs/reference/tanstack-start) | `connectSession`, `loadSession` | -| [`@monarcode/session-kit/tanstack-start/server`](/docs/reference/tanstack-start-server) | `startAuth`, `startJar` | -| [`@monarcode/session-kit/next`](/docs/reference/next) | `nextJar`, `proxyJar`, types | -| [`@monarcode/session-kit/expo`](/docs/reference/expo) | `secureStorage`, `SessionGate`, `rememberDeepLink`, types | -| [`@monarcode/session-kit/effect`](/docs/reference/effect) | `Auth`, `AuthFailure`, types | -| [`@monarcode/session-kit/effetch`](/docs/reference/effetch) | `sessionBearer`, types | +| Import | Exports | +| --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| [`@monarcode/session-kit`](/docs/reference/core) | `createAuth`, `createMirrorAuth`, `fromAccessToken`, `webStorage`, `memoryStorage`, `safeReturnTo`, `loginHref`, `AuthError`, types | +| [`@monarcode/session-kit/react`](/docs/reference/react) | `AuthProvider`, `useAuth`, `useAuthClient`, `createAuthHooks`, `useMirrorAuth`, types | +| [`@monarcode/session-kit/tanstack-router`](/docs/reference/tanstack-router) | `connectAuth`, `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuth`, `useAuthClient`, types | +| [`@monarcode/session-kit/react-router`](/docs/reference/react-router) | `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuthRevalidation`, types | +| [`@monarcode/session-kit/react-router/server`](/docs/reference/react-router-server) | `sessionMiddleware`, `requireSession`, `redirectIfSignedIn`, `routerAuth`, `cookieJarMiddleware`, `routerJar`, types | +| [`@monarcode/session-kit/http`](/docs/reference/http) | `createAuthFetch`, types | +| [`@monarcode/session-kit/server`](/docs/reference/server) | `createServerAuth`, types | +| [`@monarcode/session-kit/tanstack-start`](/docs/reference/tanstack-start) | `connectSession`, `loadSession` | +| [`@monarcode/session-kit/tanstack-start/server`](/docs/reference/tanstack-start-server) | `startAuth`, `refreshSession`, `startJar` | +| [`@monarcode/session-kit/next`](/docs/reference/next) | `nextSession`, `nextJar`, `proxyJar`, types | +| [`@monarcode/session-kit/expo`](/docs/reference/expo) | `secureStorage`, `SessionGate`, `rememberDeepLink`, types | +| [`@monarcode/session-kit/effect`](/docs/reference/effect) | `Auth`, `AuthFailure`, types | +| [`@monarcode/session-kit/effetch`](/docs/reference/effetch) | `sessionBearer`, types | ## Bundle size diff --git a/site/content/docs/(latest)/reference/next.mdx b/site/content/docs/(latest)/reference/next.mdx index 9f6f9b1..a278b94 100644 --- a/site/content/docs/(latest)/reference/next.mdx +++ b/site/content/docs/(latest)/reference/next.mdx @@ -15,6 +15,10 @@ Guide: [Next.js](/docs/setups/next). The `CookieJar` for `cookies()` from `next/headers`, to pass to `serverAuth` from `@monarcode/session-kit/server`. +### nextSession + +Gives a Next.js app its session ([`NextSession`](#nextsession)), over [`nextJar`](#nextjar) and [`proxyJar`](#proxyjar). Make it once, beside `serverAuth`, in a module only server code imports. + ### proxyJar The `CookieJar` for a request in Next's Proxy (`proxy.ts`). It reads `request`'s cookies and sets new ones on `response`. Use it with `serverAuth.refreshIfDue`, so the pages that render the request see a fresh token through [`nextJar`](#nextjar). @@ -35,6 +39,20 @@ Options for [`nextJar`](#nextjar). name="NextJarOptions" /> +### NextSession + +The session in a Next.js app, made by [`nextSession`](#nextsession): reads and guards for Server Components, the request's session for Server Functions and Route Handlers, and the refresh for Proxy. + +### NextSessionOptions + +Options for [`nextSession`](#nextsession). Pass Next's own `cookies` and `redirect`, as this entry point doesn't import `next`. + + + ### ProxyRequest The request [`proxyJar`](#proxyjar) reads cookies from. A `NextRequest` fits. diff --git a/site/content/docs/(latest)/reference/react-router-server.mdx b/site/content/docs/(latest)/reference/react-router-server.mdx index 13ede8c..85e0d08 100644 --- a/site/content/docs/(latest)/reference/react-router-server.mdx +++ b/site/content/docs/(latest)/reference/react-router-server.mdx @@ -15,6 +15,14 @@ Guide: [React Router with server rendering](/docs/setups/react-router-ssr). Server middleware that gives each request a `CookieJar`, found with [`routerJar`](#routerjar). It sets the cookies written to the jar on the response, redirects and error responses included. +### redirectIfSignedIn + +Makes the loader for your sign-in page, which sends a signed-in user on to the page's `redirectTo` search param, made safe with `safeReturnTo`. Signed-out users see the page. React Router adds the app's `basename` to the redirect. + +### requireSession + +Makes server middleware that lets only signed-in users through to a route and the routes nested in it ([`SessionGuard`](#sessionguard)). Their loaders and actions get the session from its `session(context)`, never `null`. + ### routerAuth Returns a function that gives the session of the request React Router is handling (`RequestAuth`), with every `serverAuth` method and no cookie jar. Call it with `context` in server middleware, loaders and actions, after [`cookieJarMiddleware`](#cookiejarmiddleware). Make it once, at module level. @@ -23,8 +31,38 @@ Returns a function that gives the session of the request React Router is handlin The `CookieJar` for the request React Router is handling, to pass to `serverAuth` from `@monarcode/session-kit/server`. [`routerAuth`](#routerauth) passes it for you. Call it with `context` in server middleware, loaders and actions, after [`cookieJarMiddleware`](#cookiejarmiddleware). Every call during one request returns the same jar. +### sessionMiddleware + +The root route's server middleware, which gives each request a cookie jar and refreshes the session while the response can still set the cookie. Export it as the root route's `middleware`, or spread it first into a list of your own. + ## Types +### RouterArgs + +The arguments React Router passes to server middleware and loaders, as far as the middleware and guards here read them. It's typed by its shape, like [`RouterContextLike`](#routercontextlike). + ### RouterContextLike The `context` React Router passes to server middleware, loaders and actions in framework mode: a `RouterContextProvider`, one per request. [`routerAuth`](#routerauth) and [`cookieJarMiddleware`](#cookiejarmiddleware) find the request by it. It's typed by its shape, so this entry point doesn't depend on React Router's types. + +### RouterLoader + +A loader typed by its shape, such as [`redirectIfSignedIn`](#redirectifsignedin)'s. + +### RouterMiddleware + +Server middleware for a route's `middleware`, typed by its shape. + +### SessionGuard + +Server middleware that lets only signed-in users through, made by [`requireSession`](#requiresession). Call `session(context)` in the loaders and actions it guards for the session, which is never `null` there. + +### SessionGuardOptions + +Options for [`requireSession`](#requiresession). + + diff --git a/site/content/docs/(latest)/reference/server.mdx b/site/content/docs/(latest)/reference/server.mdx index 65e9a52..558abc2 100644 --- a/site/content/docs/(latest)/reference/server.mdx +++ b/site/content/docs/(latest)/reference/server.mdx @@ -78,3 +78,13 @@ The session cookie's attributes: the `cookie` option of [`ServerAuthOptions`](#s path="node_modules/@monarcode/session-kit/dist/server/index.d.ts" name="SessionCookieOptions" /> + +### SessionMiddlewareOptions + +Options for the middleware that refreshes before each request: `refreshSession` from `@monarcode/session-kit/tanstack-start/server` and `sessionMiddleware` from `@monarcode/session-kit/react-router/server`. + + diff --git a/site/content/docs/(latest)/reference/tanstack-start-server.mdx b/site/content/docs/(latest)/reference/tanstack-start-server.mdx index fdf521f..9786ce3 100644 --- a/site/content/docs/(latest)/reference/tanstack-start-server.mdx +++ b/site/content/docs/(latest)/reference/tanstack-start-server.mdx @@ -11,6 +11,10 @@ Guide: [TanStack Start](/docs/setups/tanstack-start). ## Functions +### refreshSession + +Refreshes the session before each request, while the response can still set the cookie. Pass it to Start's `createMiddleware().server()`, and list that middleware in `requestMiddleware` in `src/start.ts`. + ### startAuth The session of the request TanStack Start is handling (`RequestAuth`), with every `serverAuth` method and no cookie jar. Each call finds the current request, so make it once, at module level, beside `serverAuth`. diff --git a/site/content/docs/(latest)/server-rendering/index.mdx b/site/content/docs/(latest)/server-rendering/index.mdx index fed5c68..09b0934 100644 --- a/site/content/docs/(latest)/server-rendering/index.mdx +++ b/site/content/docs/(latest)/server-rendering/index.mdx @@ -15,9 +15,9 @@ before rendering, so pages never show a "Checking session…" state. ## The pieces - **On the server**, `createServerAuth` from `@monarcode/session-kit/server` - seals the cookie with your secret and refreshes before rendering. Each of - its methods takes the request's cookie jar, which each framework's adapter - gives you. + seals the cookie with your secret. Each framework's adapter gives one + request's session over it, and middleware that refreshes before + rendering. - **In the browser**, `createMirrorAuth` makes a client that starts from the session the server rendered. `AuthProvider`, the hooks, and the TanStack Router guards work with it, and sign-ins and sign-outs reach every tab. @@ -40,11 +40,11 @@ server code, as in What differs between frameworks is how server code gets a request's session, and how the session reaches the browser: -| Framework | On the server | In the browser | Setup | -| ------------------------------------- | --------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------- | -| TanStack Start | `startAuth(serverAuth)`, refreshing in request middleware | `connectSession`, `loadSession` | [TanStack Start](/docs/setups/tanstack-start) | -| Next.js 16, App Router | `nextJar(await cookies())`, `proxyJar` in Proxy | `useMirrorAuth` from `@monarcode/session-kit/react` | [Next.js](/docs/setups/next) | -| React Router framework mode, with SSR | `cookieJarMiddleware`, `routerAuth(serverAuth)` | `useMirrorAuth` from `@monarcode/session-kit/react` | [React Router with server rendering](/docs/setups/react-router-ssr) | +| Framework | On the server | In the browser | Setup | +| ------------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------- | +| TanStack Start | `startAuth(serverAuth)`, with `refreshSession` in request middleware | `connectSession`, `loadSession` | [TanStack Start](/docs/setups/tanstack-start) | +| Next.js 16, App Router | `nextSession(serverAuth, { cookies, redirect })` | `useMirrorAuth` from `@monarcode/session-kit/react` | [Next.js](/docs/setups/next) | +| React Router framework mode, with SSR | `routerAuth(serverAuth)`, with `sessionMiddleware` in the root route | `useMirrorAuth` from `@monarcode/session-kit/react` | [React Router with server rendering](/docs/setups/react-router-ssr) | Locking isn't available with server rendering. For another server, such as the Next.js Pages Router, build a `CookieJar` over its cookies and pass it diff --git a/site/content/docs/(latest)/server-rendering/server-sessions.mdx b/site/content/docs/(latest)/server-rendering/server-sessions.mdx index 819fb49..8fc3310 100644 --- a/site/content/docs/(latest)/server-rendering/server-sessions.mdx +++ b/site/content/docs/(latest)/server-rendering/server-sessions.mdx @@ -59,8 +59,11 @@ request's cookie jar to pass: Each call finds the request Start is handling. - **React Router:** `routerAuth(serverAuth)` makes a function you call with a loader's, action's or middleware's `context`. -- **Next.js, and servers without an adapter:** - `serverAuth.forRequest(jar)`, over the request's cookie jar. +- **Next.js:** `nextSession(serverAuth, { cookies, redirect })`, whose + `writable()` gives it in Server Functions and Route Handlers, and + `readOnly()` in Server Components. +- **Servers without an adapter:** `serverAuth.forRequest(jar)`, over the + request's cookie jar. It's shaped like a client, so code written for one works on the server with it. `createAuthFetch(session, { baseUrl })` sends the cookie's token and saves @@ -72,8 +75,10 @@ React Router loader once its response has left the middleware. There, nothing is saved, so `signIn`, `signOut` and `refreshIfDue` reject with `INVALID_OPTIONS`, and an expired access token rejects with `REFRESH_FAILED`. TanStack Start can't tell once a page has started -streaming, so a cookie set then is lost. Refresh before rendering, in -middleware or a proxy, with `refreshIfDue`. +streaming, so a cookie set then is lost. Refresh before rendering, with the +middleware each setup guide adds: `refreshSession` in TanStack Start, +`sessionMiddleware` in React Router, and `nextSession`'s `refresh` in +Next.js's Proxy. ## Servers without an adapter diff --git a/site/content/docs/(latest)/setups/next.mdx b/site/content/docs/(latest)/setups/next.mdx index bf8d3f3..5d30060 100644 --- a/site/content/docs/(latest)/setups/next.mdx +++ b/site/content/docs/(latest)/setups/next.mdx @@ -91,56 +91,39 @@ setup shares. ## 2. Read the session in Server Components -Every `serverAuth` method takes a cookie jar. `nextJar(await cookies())` -from `@monarcode/session-kit/next` gives one over Next's cookies, read-only -by default, as Server Components can't set cookies. A data access layer -reads the session once per render: +`nextSession` from `@monarcode/session-kit/next` gives your app its session +over Next's cookies. Pass it Next's own `cookies` and `redirect`, and create +it in a server-only module too: ```ts title="lib/auth/session.ts" import "server-only"; -import { cache } from "react"; - -import { safeReturnTo } from "@monarcode/session-kit"; -import { nextJar } from "@monarcode/session-kit/next"; +import { nextSession } from "@monarcode/session-kit/next"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; import { serverAuth } from "./server"; -export const getSession = cache(async () => - serverAuth.getSession(nextJar(await cookies())), -); - -/** The session, or the sign-in page, which sends the user back to `path`. */ -export async function requireSession(path: string) { - const session = await getSession(); - if (!session) - redirect(`/login?redirectTo=${encodeURIComponent(safeReturnTo(path))}`); - return session; -} +export const session = nextSession(serverAuth, { cookies, redirect }); ``` -`getSession` resolves `{ sessionId, user }`, never tokens, so it's safe to -pass to Client Components. +In a Server Component, `await session.get()` resolves `{ sessionId, user }`, +never tokens, so it's safe to pass to Client Components, or `null`. It +doesn't set cookies, as Server Components can't. Proxy refreshes first. ## 3. Refresh in Proxy -A read-only jar can't save refreshed tokens, so Proxy refreshes access that -is about to expire before any page or Server Function reads it. -`proxyJar(request, response)` sets the new cookie on the response, and Next -passes it on to the Server Components rendering the same request: +Proxy refreshes access that is about to expire before any page or Server +Function reads it. `session.refresh(request, response)` sets the new cookie +on the response, and Next passes it on to the Server Components rendering +the same request: ```ts title="proxy.ts" -import { proxyJar } from "@monarcode/session-kit/next"; import { NextResponse, type NextRequest } from "next/server"; -import { serverAuth } from "./lib/auth/server"; +import { session } from "./lib/auth/session"; -export async function proxy(request: NextRequest) { - const response = NextResponse.next(); - // If the refresh fails, the page still renders with the cookie as it is. - await serverAuth.refreshIfDue(proxyJar(request, response)).catch(() => {}); - return response; +export function proxy(request: NextRequest) { + return session.refresh(request, NextResponse.next()); } export const config = { @@ -148,29 +131,26 @@ export const config = { }; ``` +If the refresh fails, the page still renders with the cookie as it is. Server Functions are POST requests to the page that calls them, so keep the matcher wide enough to include those pages. ## 4. Add Server Functions -Server Functions set cookies, so they pass `{ writable: true }`. They decide -what the browser may ask for: +Server Functions set cookies, so they use `session.writable()`, the +request's session with every `serverAuth` method. They decide what the +browser may ask for: ```ts title="app/actions.ts" "use server"; -import { nextJar } from "@monarcode/session-kit/next"; -import { cookies } from "next/headers"; import { z } from "zod"; -import { login, serverAuth } from "../lib/auth/server"; - -async function jar() { - return nextJar(await cookies(), { writable: true }); -} +import { login } from "../lib/auth/server"; +import { session } from "../lib/auth/session"; export async function getSessionAction() { - return serverAuth.getSession(await jar()); + return (await session.writable()).getSession(); } const credentials = z.object({ username: z.string(), password: z.string() }); @@ -179,10 +159,9 @@ export async function signInAction(input: unknown) { const { username, password } = credentials.parse(input); try { return { - session: await serverAuth.signIn( - await jar(), - await login(username, password), - ), + session: await ( + await session.writable() + ).signIn(await login(username, password)), }; } catch (error) { return { @@ -192,7 +171,7 @@ export async function signInAction(input: unknown) { } export async function signOutAction() { - await serverAuth.signOut(await jar()); + await (await session.writable()).signOut(); } ``` @@ -282,15 +261,15 @@ Render the providers in the root layout, with the session it reads: ```tsx title="app/layout.tsx" import type { ReactNode } from "react"; -import { getSession } from "../lib/auth/session"; +import { session } from "../lib/auth/session"; import { Providers } from "./providers"; export default async function RootLayout(props: { children: ReactNode }) { - const session = await getSession(); + const current = await session.get(); return ( - {props.children} + {props.children} ); @@ -299,28 +278,28 @@ export default async function RootLayout(props: { children: ReactNode }) { ## 6. Protect pages -Check the session in each page, or in the data access layer, rather than in -a layout. Layouts don't render again on navigation: +Check the session in each page with `session.require`, rather than in a +layout. Layouts don't render again on navigation. It takes the page's own +path, where the sign-in page sends the user back, as Server Components don't +know their URL: ```tsx title="app/page.tsx" -import { requireSession } from "../lib/auth/session"; +import { session } from "../lib/auth/session"; export default async function Home() { - const session = await requireSession("/"); - return

Welcome, {session.user.firstName}

; + const { user } = await session.require("/"); + return

Welcome, {user.firstName}

; } ``` -The sign-in page sends a signed-in user back to `redirectTo`, and its form -calls the client's `signIn`. When the session changes in the browser, after a -sign-in or sign-out here or in another tab, `useMirrorAuth` renders the page -again on the server, so these redirects run without code in the form: +The sign-in page sends a signed-in user on to `redirectTo` with +`session.redirectIfSignedIn`, and its form calls the client's `signIn`. When +the session changes in the browser, after a sign-in or sign-out here or in +another tab, `useMirrorAuth` renders the page again on the server, so these +redirects run without code in the form: ```tsx title="app/login/page.tsx" -import { safeReturnTo } from "@monarcode/session-kit"; -import { redirect } from "next/navigation"; - -import { getSession } from "../../lib/auth/session"; +import { session } from "../../lib/auth/session"; import { SignInForm } from "./sign-in-form"; export default async function Login({ @@ -328,8 +307,7 @@ export default async function Login({ }: { searchParams: Promise>; }) { - if (await getSession()) - redirect(safeReturnTo((await searchParams).redirectTo)); + await session.redirectIfSignedIn((await searchParams).redirectTo); return ; } ``` @@ -391,24 +369,20 @@ with the access token. ## Call your API -In Server Components, get the access token with a read-only jar. Proxy -refreshed it before the render. A token that expired anyway rejects with -`REFRESH_FAILED`, since the jar can't save a new one: +In Server Components, get the access token from `session.readOnly()`, the +request's session that doesn't set cookies. Proxy refreshed it before the +render. A token that expired anyway rejects with `REFRESH_FAILED`, since +nothing new can be saved: ```tsx title="app/orders/page.tsx" -import { nextJar } from "@monarcode/session-kit/next"; -import { cookies } from "next/headers"; import { z } from "zod"; -import { serverAuth } from "../../lib/auth/server"; -import { requireSession } from "../../lib/auth/session"; +import { session } from "../../lib/auth/session"; export default async function Orders() { - await requireSession("/orders"); - const credentials = await serverAuth.credentials.get( - nextJar(await cookies()), - ); - // requireSession has checked that someone is signed in. + await session.require("/orders"); + const credentials = await (await session.readOnly()).credentials.get(); + // require has checked that someone is signed in. const response = await fetch("https://api.example.com/orders", { headers: { Authorization: `Bearer ${credentials!.accessToken}` }, }); @@ -420,35 +394,33 @@ export default async function Orders() { } ``` -In Server Functions and Route Handlers, a writable jar can also `renew` -after a 401. +In Server Functions and Route Handlers, `session.writable()` can also +`renew` after a 401. To call the API from the browser too, with `createAuthFetch` or effetch's `sessionBearer`, opt in with `clientCredentials: true` in `createServerAuth`. -Expose `serverAuth.clientCredentials.get` and `.renew` through a Route +Expose the request's `clientCredentials.get` and `.renew` through a Route Handler, and pass them as the client's `credentials`. A Route Handler rather than a Server Function, because Next dispatches Server Functions one at a time and renders the page again after one sets a cookie. Next doesn't check where a Route Handler's requests come from, so accept your own site only: ```ts title="app/api/auth/credentials/route.ts" -import { nextJar } from "@monarcode/session-kit/next"; -import { cookies } from "next/headers"; import { z } from "zod"; -import { serverAuth } from "../../../../lib/auth/server"; +import { session } from "../../../../lib/auth/session"; const rejected = z.object({ sessionId: z.string(), accessToken: z.string() }); export async function POST(request: Request) { if (request.headers.get("sec-fetch-site") !== "same-origin") return new Response(null, { status: 403 }); - const jar = nextJar(await cookies(), { writable: true }); + const auth = await session.writable(); const body = rejected.safeParse(await request.json().catch(() => null)); return Response.json( body.success - ? await serverAuth.clientCredentials.renew(jar, body.data) - : await serverAuth.clientCredentials.get(jar), + ? await auth.clientCredentials.renew(body.data) + : await auth.clientCredentials.get(), ); } ``` @@ -462,13 +434,11 @@ The example app does this. - **Signing out ends the session only with `revoke`.** A copy of the cookie works again ten seconds after sign-out: see [Sign-out](/docs/server-rendering/server-sessions#sign-out). -- **Writable jars only where Next allows writes.** Pass `{ writable: true }` - in Server Functions and Route Handlers only. In a Server Component, a - writable jar would refresh and then fail to save the new tokens, which - spends a rotating refresh token. -- **One jar per request.** `nextJar` returns the same jar for the same store - and `writable`, and the read-only jar follows the writable one. `proxyJar` - returns the same jar for the same response. +- **`writable()` only where Next allows writes.** Use it in Server Functions + and Route Handlers only. In a Server Component, it would refresh and then + fail to save the new tokens, which spends a rotating refresh token. +- **One read per request.** Calls to `session` during one request read the + cookie once, and a sign-in through `writable()` shows in `get()`. - **Separate instances.** Next builds Proxy, Route Handlers, and pages with their Server Functions separately, so each has its own `serverAuth`, even on one server: they share no refresh. A matcher that covers every route diff --git a/site/content/docs/(latest)/setups/react-router-ssr.mdx b/site/content/docs/(latest)/setups/react-router-ssr.mdx index c6bfb41..e9b8a86 100644 --- a/site/content/docs/(latest)/setups/react-router-ssr.mdx +++ b/site/content/docs/(latest)/setups/react-router-ssr.mdx @@ -47,11 +47,15 @@ export const userSchema = z.object({ id: z.number(), firstName: z.string() }); `createServerAuth` from `@monarcode/session-kit/server` keeps the session in a cookie sealed with your `secret`, and refreshes it with your backend. -`routerAuth` gives a request's session by its `context`. Create both in a -`.server` module, so React Router refuses to bundle it for the browser: +`routerAuth` gives a request's session by its `context`, and +`requireSession` makes the guard that protects routes in step 4. Create them +in a `.server` module, so React Router refuses to bundle it for the browser: ```ts title="app/auth/session.server.ts" -import { routerAuth } from "@monarcode/session-kit/react-router/server"; +import { + requireSession, + routerAuth, +} from "@monarcode/session-kit/react-router/server"; import { createServerAuth } from "@monarcode/session-kit/server"; import { z } from "zod"; @@ -82,6 +86,9 @@ export const serverAuth = createServerAuth({ /** The request's session: `auth(context)` in middleware, loaders and actions. */ export const auth = routerAuth(serverAuth); +/** Lets only signed-in users through to the routes it guards. */ +export const signedIn = requireSession(serverAuth); + /** Signs in with your backend, from the server. */ export async function login(username: string, password: string) { const response = await fetch(`${API}/auth/login`, { @@ -107,146 +114,20 @@ export async function login(username: string, password: string) { its other options, rotating the secret, signing out, and the limits every setup shares. -## 2. Add middleware - -`cookieJarMiddleware` from `@monarcode/session-kit/react-router/server` -reads each request's cookies and sets the ones written on the response, -redirects included. After it, `auth(context)` gives the request's session in -middleware, loaders and actions. - -After it, refresh access that is about to expire, before any loader reads -it, and keep pages that depend on the session out of shared caches: - -```ts title="app/auth/middleware.server.ts" -import { redirect, type MiddlewareFunction } from "react-router"; - -import { cookieJarMiddleware } from "@monarcode/session-kit/react-router/server"; - -import { auth } from "./session.server"; - -const refreshSession: MiddlewareFunction = async ( - { context }, - next, -) => { - // A failed refresh shows up when a loader reads the session. - await auth(context) - .refreshIfDue() - .catch(() => {}); - const response = await next(); - // A copy: some responses, such as `fetch`'s, can't change their headers. - const page = new Response(response.body, response); - page.headers.set("Cache-Control", "private, no-store"); - return page; -}; - -/** For the root route: the cookies first, so they wrap the rest. */ -export const sessionMiddleware = [cookieJarMiddleware, refreshSession]; - -/** Sends signed-out users to the sign-in page, which brings them back. */ -export const requireSession: MiddlewareFunction = async ({ - context, - url, -}) => { - if (!(await auth(context).getSession())) - throw redirect( - `/login?redirectTo=${encodeURIComponent(url.pathname + url.search)}`, - ); -}; -``` - -`url` leaves out React Router's `.data` suffix, which `request.url` keeps. - -## 3. Sign in and out - -The sign-in route's action signs in with your backend and seals the result -into the cookie. React Router 7.12 and later refuse route actions posted from -other sites. On 7.9 to 7.11, start the action with the `Sec-Fetch-Site` check -that the sign-out action in `app/routes/auth.session.ts` uses. The form works -before the page's scripts load: - -```tsx title="app/routes/login.tsx" -import { - Form, - redirect, - useActionData, - type ActionFunctionArgs, - type LoaderFunctionArgs, -} from "react-router"; - -import { safeReturnTo } from "@monarcode/session-kit"; - -import { auth, login } from "../auth/session.server"; - -export async function loader({ context, url }: LoaderFunctionArgs) { - if (await auth(context).getSession()) - throw redirect(safeReturnTo(url.searchParams.get("redirectTo"))); - return null; -} - -export async function action({ request, context, url }: ActionFunctionArgs) { - const form = await request.formData(); - try { - await auth(context).signIn( - await login(String(form.get("username")), String(form.get("password"))), - ); - } catch (error) { - return { - error: error instanceof Error ? error.message : "Sign-in failed", - }; - } - throw redirect(safeReturnTo(url.searchParams.get("redirectTo"))); -} - -export default function Login() { - const result = useActionData(); - return ( -
- - - {result?.error &&

{result.error}

} - -
- ); -} -``` - -A resource route gives the browser's client the session and signs out. React -Router doesn't check where resource routes' requests come from, so its action -accepts your own site only: - -```ts title="app/routes/auth.session.ts" -import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router"; - -import { auth } from "../auth/session.server"; - -export async function loader({ context }: LoaderFunctionArgs) { - return Response.json(await auth(context).getSession()); -} - -export async function action({ request, context }: ActionFunctionArgs) { - if (request.headers.get("sec-fetch-site") !== "same-origin") - return new Response(null, { status: 403 }); - await auth(context).signOut(); - return Response.json(null); -} -``` - -Add it to `app/routes.ts` as `route("auth/session", "routes/auth.session.ts")`. +## 2. Add the root route -## 4. Create the browser client +The root route's middleware is `sessionMiddleware(serverAuth)` from +`@monarcode/session-kit/react-router/server`. It reads each request's +cookies and sets the ones written on the response, redirects included, so +`auth(context)` gives the request's session in middleware, loaders and +actions. Then it refreshes access that is about to expire, before any loader +reads it, and marks each response that doesn't set its own +`Cache-Control` as `private, no-store`, so shared caches keep none. A failed +refresh doesn't fail the request. Loaders read the session as usual, and an +error there reaches the route's error boundary. `createMirrorAuth` makes the client that components use, from the session -the root loader read and the resource route: +the root loader read and the resource route that step 3 adds: ```ts title="app/auth/client.ts" import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit"; @@ -295,10 +176,10 @@ import { } from "react-router"; import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react"; +import { sessionMiddleware } from "@monarcode/session-kit/react-router/server"; import { createAppAuth, type AppAuth } from "./auth/client"; -import { sessionMiddleware } from "./auth/middleware.server"; -import { auth } from "./auth/session.server"; +import { auth, serverAuth } from "./auth/session.server"; // Types `AuthProvider` and the hooks with this client. declare module "@monarcode/session-kit" { @@ -307,7 +188,7 @@ declare module "@monarcode/session-kit" { } } -export const middleware = sessionMiddleware; +export const middleware = sessionMiddleware(serverAuth); export async function loader({ context }: LoaderFunctionArgs) { return { session: await auth(context).getSession() }; @@ -350,17 +231,103 @@ an action signs in or out, the loader reads the new session and the client adopts it; after a sign-out in the browser, here or in another tab, loaders run again, so the server's redirects run. -## 5. Protect routes +## 3. Sign in and out + +The sign-in route's action signs in with your backend and seals the result +into the cookie. React Router 7.12 and later refuse route actions posted from +other sites. On 7.9 to 7.11, start the action with the `Sec-Fetch-Site` check +that the sign-out action in `app/routes/auth.session.ts` uses. The form works +before the page's scripts load: + +```tsx title="app/routes/login.tsx" +import { + Form, + redirect, + useActionData, + type ActionFunctionArgs, +} from "react-router"; + +import { safeReturnTo } from "@monarcode/session-kit"; +import { redirectIfSignedIn } from "@monarcode/session-kit/react-router/server"; + +import { auth, login, serverAuth } from "../auth/session.server"; -Guard a layout route with middleware. It runs on the server before any -loader or action nested in it, which loaders on their own can't promise: +// A signed-in user goes on to `redirectTo`. +export const loader = redirectIfSignedIn(serverAuth); + +export async function action({ request, context, url }: ActionFunctionArgs) { + const form = await request.formData(); + try { + await auth(context).signIn( + await login(String(form.get("username")), String(form.get("password"))), + ); + } catch (error) { + return { + error: error instanceof Error ? error.message : "Sign-in failed", + }; + } + throw redirect(safeReturnTo(url.searchParams.get("redirectTo"))); +} + +export default function Login() { + const result = useActionData(); + return ( +
+ + + {result?.error &&

{result.error}

} + +
+ ); +} +``` + +A resource route gives the browser's client the session and signs out. React +Router doesn't check where resource routes' requests come from, so its action +accepts your own site only: + +```ts title="app/routes/auth.session.ts" +import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router"; + +import { auth } from "../auth/session.server"; + +export async function loader({ context }: LoaderFunctionArgs) { + return Response.json(await auth(context).getSession()); +} + +export async function action({ request, context }: ActionFunctionArgs) { + if (request.headers.get("sec-fetch-site") !== "same-origin") + return new Response(null, { status: 403 }); + await auth(context).signOut(); + return Response.json(null); +} +``` + +Add it to `app/routes.ts` as `route("auth/session", "routes/auth.session.ts")`. + +## 4. Protect routes + +Guard a layout route with `signedIn`, the middleware `requireSession` made. +It runs on the server before any loader or action nested in it, which +loaders on their own can't promise. Signed-out users go to `/login`, with +`?redirectTo=` set to the page they asked for: ```tsx title="app/routes/protected.tsx" import { Outlet } from "react-router"; -import { requireSession } from "../auth/middleware.server"; +import { signedIn } from "../auth/session.server"; -export const middleware = [requireSession]; +export const middleware = [signedIn]; // So navigation in the browser runs the middleware. export const loader = () => null; @@ -370,14 +337,22 @@ export default function Protected() { } ``` -A page nested in it reads the user as usual: +A loader nested in it gets the session from `signedIn.session(context)`, +which is never `null` there. Components read the user with the hooks as +usual: ```tsx title="app/routes/home.tsx" -import { useAuth } from "@monarcode/session-kit/react"; +import { useLoaderData, type LoaderFunctionArgs } from "react-router"; + +import { signedIn } from "../auth/session.server"; + +export function loader({ context }: LoaderFunctionArgs) { + return { name: signedIn.session(context).user.firstName }; +} export default function Home() { - const user = useAuth((state) => state.user); - return

Welcome, {user?.firstName}

; + const { name } = useLoaderData(); + return

Welcome, {name}

; } ``` @@ -401,13 +376,15 @@ refreshed first when it has expired, and can `renew` it after a 401: ```tsx title="app/routes/orders.tsx" import { redirect, useLoaderData, type LoaderFunctionArgs } from "react-router"; +import { loginHref } from "@monarcode/session-kit"; import { z } from "zod"; import { auth } from "../auth/session.server"; export async function loader({ context }: LoaderFunctionArgs) { const credentials = await auth(context).credentials.get(); - if (!credentials) throw redirect("/login?redirectTo=/orders"); + // Outside the guarded layout: send the user to sign in, then back here. + if (!credentials) throw redirect(loginHref("/login", "/orders")); const response = await fetch("https://api.example.com/orders", { headers: { Authorization: `Bearer ${credentials.accessToken}` }, }); @@ -460,13 +437,17 @@ The example app does this. works again ten seconds after sign-out: see [Sign-out](/docs/server-rendering/server-sessions#sign-out). - **Refresh in middleware.** The request's session sets cookies until the - response leaves `cookieJarMiddleware`, which first waits for a refresh - under way. A loader's deferred data that reads the session later, while - the page streams, can't set cookies: an expired token then rejects with - `REFRESH_FAILED`, since nothing new can be saved. `refreshIfDue` in - middleware refreshes before that. + response leaves `sessionMiddleware`, which first waits for a refresh under + way. A loader's deferred data that reads the session later, while the + page streams, can't set cookies: an expired token then rejects with + `REFRESH_FAILED`, since nothing new can be saved. `sessionMiddleware` + refreshes before that. - **One session per request.** `auth(context)` returns the same session for every call with the same `context`, which React Router makes per request. +- **A `basename`.** Pass it to the guard too, as + `requireSession(serverAuth, { basename: "/app" })`. React Router adds it to + loaders' and actions' redirects, but not to middleware's, so the guard adds + it to its own. - **Tabs.** Signing in or out in one tab reaches the others, which ask the server again and run their loaders again. So does returning to a tab after a while. diff --git a/site/content/docs/(latest)/setups/tanstack-start.mdx b/site/content/docs/(latest)/setups/tanstack-start.mdx index a4ad070..c67e648 100644 --- a/site/content/docs/(latest)/setups/tanstack-start.mdx +++ b/site/content/docs/(latest)/setups/tanstack-start.mdx @@ -49,7 +49,7 @@ const API = "https://api.example.com"; const userSchema = z.object({ id: z.number(), firstName: z.string() }); const tokens = z.object({ accessToken: z.string(), refreshToken: z.string() }); -const serverAuth = createServerAuth({ +export const serverAuth = createServerAuth({ name: "app", user: userSchema, secret: process.env.SESSION_SECRET!, @@ -131,23 +131,26 @@ Request middleware refreshes access that is about to expire before any route or server function reads it, while the response can still set the cookie. Once Start starts streaming a page, a cookie set later is lost, so a refresh then, such as in a deferred loader's promise, would spend the refresh token -and drop the new one: +and drop the new one. + +`refreshSession` from `@monarcode/session-kit/tanstack-start/server` does +the refresh, and marks each response private unless it sets its own +`Cache-Control`. Pass it to Start's own `createMiddleware().server()`. Start +bundles `src/start.ts` for the browser too, and leaves out only what's +inside `.server()`, `serverAuth` included: ```ts title="src/start.ts" +import { refreshSession } from "@monarcode/session-kit/tanstack-start/server"; import { createCsrfMiddleware, createMiddleware, createStart, } from "@tanstack/react-start"; -import { session } from "./auth/server"; +import { serverAuth } from "./auth/server"; const sessionMiddleware = createMiddleware({ type: "request" }).server( - async ({ next }) => { - // A failed refresh shows up when a route reads the session. - await session.refreshIfDue().catch(() => {}); - return next(); - }, + refreshSession(serverAuth), ); export const startInstance = createStart(() => ({ @@ -160,6 +163,9 @@ export const startInstance = createStart(() => ({ })); ``` +A failed refresh doesn't fail the request. Routes read the session as +usual, and an error there reaches the route's error component. + An app that defines `createStart` has no CSRF protection for its server functions until it adds `createCsrfMiddleware`. Its `filter` keeps the check to server-function calls: unfiltered, it also refuses page loads from links @@ -341,11 +347,9 @@ does this. one refresh. Outside a request, such as in the browser, they reject with `INVALID_OPTIONS`. - **Caching.** Pages and server functions that read the session differ per - user, and Start sends no `Cache-Control` for them. Behind a CDN or proxy - that caches responses, mark them private, for example with - `setResponseHeader("Cache-Control", "private, no-store")` from - `@tanstack/react-start/server` in request middleware, as the example app - does. + user. `refreshSession` sends `Cache-Control: private, no-store` with each + response that doesn't set its own, so a CDN or proxy doesn't cache them. + To leave every response as it is, pass `{ cacheControl: false }`. - **Prerendering.** A prerendered page renders at build time, without a cookie, so it shows the signed-out state. Don't prerender pages that read the session. diff --git a/src/core/return-to.ts b/src/core/return-to.ts index ae81d31..d7c1d4b 100644 --- a/src/core/return-to.ts +++ b/src/core/return-to.ts @@ -110,8 +110,28 @@ export function safeReturnTo( } /** - * The sign-in URL for `loginPath`, with `?redirectTo=` set to `returnTo` so - * the user comes back after signing in. + * Builds the sign-in page's URL, with `?redirectTo=` set to `returnTo`, so + * the user comes back after signing in. The guards use it. Use it in a guard + * of your own, such as in a route handler. + * + * `returnTo` is encoded as is. Pass a path you read from the request through + * {@link safeReturnTo} first. Throws `INVALID_OPTIONS` when `loginPath` + * doesn't start with `/`. + * + * @example + * ```ts + * import { loginHref, safeReturnTo } from "@monarcode/session-kit"; + * + * loginHref("/login", "/orders?page=2"); // "/login?redirectTo=%2Forders%3Fpage%3D2" + * + * export function signInFirst(request: Request) { + * const url = new URL(request.url); + * const location = loginHref("/login", safeReturnTo(url.pathname + url.search)); + * return new Response(null, { status: 302, headers: { location } }); + * } + * ``` + * + * @since 0.1.0 */ export function loginHref(loginPath: string, returnTo: string): string { if (!loginPath.startsWith("/")) diff --git a/src/index.ts b/src/index.ts index f076707..51c6349 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,7 +1,7 @@ export { createAuth } from "./core/client.js"; export { AuthError } from "./core/errors.js"; export { createMirrorAuth } from "./core/mirror.js"; -export { safeReturnTo } from "./core/return-to.js"; +export { loginHref, safeReturnTo } from "./core/return-to.js"; export { fromAccessToken } from "./core/sources.js"; export { memoryStorage, webStorage } from "./core/storage.js"; diff --git a/src/next/index.ts b/src/next/index.ts index 0c5cd01..e7720f3 100644 --- a/src/next/index.ts +++ b/src/next/index.ts @@ -1,3 +1,12 @@ +import { AuthError } from "../core/errors.js"; +import { loginHref, safeReturnTo } from "../core/return-to.js"; +import type { Session } from "../core/types.js"; +import { + refreshBeforeRendering, + refreshWithin, + type RequestAuth, + type ServerAuth, +} from "../server/auth.js"; import { pairJars, type CookieJar, @@ -216,3 +225,177 @@ export function proxyJar( } return jar; } + +/** + * Options for {@link nextSession}. Pass Next's own `cookies` and `redirect`, + * as this entry point doesn't import `next`. + * + * @example + * ```ts + * import type { NextSessionOptions } from "@monarcode/session-kit/next"; + * import { cookies } from "next/headers"; + * import { redirect } from "next/navigation"; + * + * export const options: NextSessionOptions = { + * cookies, + * redirect, + * loginPath: "/sign-in", + * }; + * ``` + * + * @since 0.1.0 + */ +export type NextSessionOptions = { + /** `cookies` from `next/headers`. */ + cookies: () => Promise; + /** `redirect` from `next/navigation`. */ + redirect: (url: string) => never; + /** + * Your sign-in page's path, starting with `/`. + * @default "/login" + */ + loginPath?: string | undefined; + /** + * How soon before the access token expires `refresh` refreshes it, in + * seconds, as `serverAuth.refreshIfDue` explains. + * @default 60 + */ + within?: number | undefined; +}; + +/** + * The session in a Next.js app, made by {@link nextSession}: reads and + * guards for Server Components, the request's session for Server Functions + * and Route Handlers, and the refresh for Proxy. + * + * @example + * ```ts + * import type { NextSession } from "@monarcode/session-kit/next"; + * + * type User = { id: number; firstName: string }; + * declare const session: NextSession; + * + * // app/orders/page.tsx: the user, or the sign-in page. + * export default async function Orders() { + * const { user } = await session.require("/orders"); + * return user.firstName; + * } + * ``` + * + * @since 0.1.0 + */ +export type NextSession = { + /** + * Resolves who is signed in, from the cookie, or `null`. It doesn't set + * cookies, so it works in Server Components. Proxy refreshes first. + */ + get: () => Promise | null>; + /** + * Resolves the session, or redirects to the sign-in page with + * `?redirectTo=` set to `path`, the page's own path, as Server Components + * don't know their URL. + */ + require: (path: string) => Promise>; + /** + * For your sign-in page: redirects a signed-in user to `redirectTo`, + * usually the `redirectTo` search param, made safe with `safeReturnTo`. + * It resolves for a signed-out user, or when the session can't be read. + */ + redirectIfSignedIn: (redirectTo: unknown) => Promise; + /** + * The request's session for Server Components, which doesn't set + * cookies. Read its `credentials` to call your API while rendering. + */ + readOnly: () => Promise>; + /** + * The request's session for Server Functions and Route Handlers, which + * sets cookies. Sign in and out with it, and renew the access token. + */ + writable: () => Promise>; + /** + * For Proxy: refreshes access that expires within `within` seconds, + * setting the new cookie on `response`, and resolves `response`. A + * failed refresh is left for the page, which reads the session as it is. + */ + refresh: ( + request: ProxyRequest, + response: R, + ) => Promise; +}; + +/** + * Gives a Next.js app its session ({@link NextSession}), over {@link nextJar} + * and {@link proxyJar}. Make it once, beside `serverAuth`, in a module only + * server code imports. + * + * Server Components read it with `get` and guard pages with `require`. + * Server Functions and Route Handlers sign in and out through `writable()`. + * `proxy.ts` refreshes with `refresh`, as rendering can't set cookies. + * + * Throws `INVALID_OPTIONS` without `cookies` and `redirect`, when + * `loginPath` doesn't start with `/`, or when `within` is negative. + * + * @example + * ```ts + * import { nextSession } from "@monarcode/session-kit/next"; + * import type { ServerAuth } from "@monarcode/session-kit/server"; + * import { cookies } from "next/headers"; + * import { redirect } from "next/navigation"; + * import { NextResponse, type NextRequest } from "next/server"; + * + * type User = { id: number; firstName: string }; + * declare const serverAuth: ServerAuth; + * + * export const session = nextSession(serverAuth, { cookies, redirect }); + * + * // proxy.ts + * export function proxy(request: NextRequest) { + * return session.refresh(request, NextResponse.next()); + * } + * ``` + * + * @since 0.1.0 + */ +export function nextSession( + serverAuth: ServerAuth, + options: NextSessionOptions, +): NextSession { + const { cookies, redirect } = options; + if (typeof cookies !== "function" || typeof redirect !== "function") + throw new AuthError( + "INVALID_OPTIONS", + "Pass cookies from next/headers and redirect from next/navigation", + ); + const loginPath = options.loginPath ?? "/login"; + // Fails fast on bad options, before any request. + loginHref(loginPath, "/"); + const within = refreshWithin({ within: options.within }); + const jar = async (writable: boolean) => + nextJar(await cookies(), { writable }); + const get = async () => serverAuth.getSession(await jar(false)); + return { + get, + async require(path) { + const session = await get(); + if (session) return session; + return redirect( + loginHref(loginPath, safeReturnTo(path, { loginPath })), + ); + }, + async redirectIfSignedIn(redirectTo) { + // Outside the catch: Next's `redirect` throws to redirect. + if (await get().catch(() => null)) + redirect(safeReturnTo(redirectTo, { loginPath })); + }, + readOnly: async () => serverAuth.forRequest(await jar(false)), + writable: async () => serverAuth.forRequest(await jar(true)), + async refresh(request, response) { + await refreshBeforeRendering( + serverAuth, + proxyJar(request, response), + within, + ); + return response; + }, + }; +} diff --git a/src/react-router/basename.ts b/src/react-router/basename.ts new file mode 100644 index 0000000..c6581d5 --- /dev/null +++ b/src/react-router/basename.ts @@ -0,0 +1,25 @@ +import { AuthError } from "../core/errors.js"; + +/** + * `pathname` without `basename`, matched ignoring case as React Router does. + */ +export function stripBasename(pathname: string, basename = "/"): string { + if (!basename.startsWith("/")) + throw new AuthError( + "INVALID_OPTIONS", + `basename must start with "/": ${basename}`, + ); + const base = basename.replace(/\/+$/, ""); + if (!base) return pathname; + const lower = pathname.toLowerCase(); + const prefix = base.toLowerCase(); + if (lower === prefix) return "/"; + return lower.startsWith(`${prefix}/`) + ? pathname.slice(base.length) + : pathname; +} + +/** `href`, an in-app path, under `basename`. */ +export function withBasename(href: string, basename = "/"): string { + return basename.replace(/\/+$/, "") + href; +} diff --git a/src/react-router/guards.ts b/src/react-router/guards.ts index 9119333..513ca78 100644 --- a/src/react-router/guards.ts +++ b/src/react-router/guards.ts @@ -1,6 +1,5 @@ import { redirect } from "react-router"; -import { AuthError } from "../core/errors.js"; import { guardSession, sessionOrNull, @@ -8,6 +7,7 @@ import { } from "../core/guard.js"; import { loginHref, safeReturnTo } from "../core/return-to.js"; import type { Session } from "../core/types.js"; +import { stripBasename } from "./basename.js"; /** * Options for {@link requireSession}. @@ -45,25 +45,6 @@ export type RequireSessionOptions = { basename?: string | undefined; }; -/** - * `pathname` without `basename`, matched ignoring case as React Router does. - */ -function stripBasename(pathname: string, basename = "/"): string { - if (!basename.startsWith("/")) - throw new AuthError( - "INVALID_OPTIONS", - `basename must start with "/": ${basename}`, - ); - const base = basename.replace(/\/+$/, ""); - if (!base) return pathname; - const lower = pathname.toLowerCase(); - const prefix = base.toLowerCase(); - if (lower === prefix) return "/"; - return lower.startsWith(`${prefix}/`) - ? pathname.slice(base.length) - : pathname; -} - /** * Guards a route in its loader, in data or framework mode, so only * signed-in users get through. They get `{ session }`, which holds no tokens. diff --git a/src/react-router/server.ts b/src/react-router/server.ts index d303b64..42427b5 100644 --- a/src/react-router/server.ts +++ b/src/react-router/server.ts @@ -1,7 +1,24 @@ import { AuthError } from "../core/errors.js"; -import type { RequestAuth, ServerAuth } from "../server/auth.js"; +import { + loginHref, + safeReturnTo, + type SafeReturnToOptions, +} from "../core/return-to.js"; +import type { Session } from "../core/types.js"; +import { + middlewareOptions, + refreshBeforeRendering, + type RequestAuth, + type ServerAuth, + type SessionMiddlewareOptions, +} from "../server/auth.js"; import type { CookieJar } from "../server/cookies.js"; -import { requestJar, type RequestJar } from "../server/request-jar.js"; +import { + requestJar, + withHeaders, + type RequestJar, +} from "../server/request-jar.js"; +import { stripBasename, withBasename } from "./basename.js"; /** * The `context` React Router passes to server middleware, loaders and actions @@ -43,8 +60,10 @@ const requests = new WeakMap< * {@link routerJar}. It sets the cookies written to the jar on the response, * redirects and error responses included. * - * List it first in the root route's `middleware`, so it wraps the rest. It - * needs React Router 8, or 7.9 and later with `future.v8_middleware`. + * {@link sessionMiddleware} starts with it, so most apps don't list it + * themselves. To refresh your own way, list it first in the root route's + * `middleware`, so it wraps the rest. It needs React Router 8, or 7.9 and + * later with `future.v8_middleware`. * * The jar can set cookies until the response leaves the middleware, which * first waits for a refresh under way, so its new tokens are saved. After @@ -65,11 +84,13 @@ const requests = new WeakMap< * context: RouterContextLike, * ) => RequestAuth<{ id: number }, { id: number }>; * - * // app/root.tsx: refresh access that expires within a minute. + * // app/root.tsx: refresh for GET requests only. * export const middleware = [ * cookieJarMiddleware, - * async ({ context }: { context: RouterContextLike }) => { - * await auth(context).refreshIfDue().catch(() => {}); + * async (args: { context: RouterContextLike; request: Request }) => { + * const { context, request } = args; + * if (request.method === "GET") + * await auth(context).refreshIfDue().catch(() => {}); * }, * ]; * ``` @@ -168,3 +189,328 @@ export function routerAuth( ): (context: RouterContextLike) => RequestAuth { return (context) => serverAuth.forRequest(routerJar(context)); } + +/** + * The arguments React Router passes to server middleware and loaders, as far + * as the middleware and guards here read them. It's typed by its shape, like + * {@link RouterContextLike}. + * + * @example + * ```ts + * import type { RouterArgs } from "@monarcode/session-kit/react-router/server"; + * + * export function pathOf({ request, url }: RouterArgs) { + * const { pathname, search } = url ?? new URL(request.url); + * return pathname + search; + * } + * ``` + * + * @since 0.1.0 + */ +export type RouterArgs = { + request: Request; + context: RouterContextLike; + /** + * The URL without React Router's `.data` suffix, from React Router 8. + * React Router 7 removes the suffix from `request.url` instead. + */ + url?: URL | undefined; +}; + +/** + * Server middleware for a route's `middleware`, typed by its shape. + * + * @example + * ```ts + * import type { + * RouterMiddleware, + * } from "@monarcode/session-kit/react-router/server"; + * + * export const noStore: RouterMiddleware = async (_args, next) => { + * const response = await next(); + * const page = new Response(response.body, response); + * page.headers.set("Cache-Control", "no-store"); + * return page; + * }; + * ``` + * + * @since 0.1.0 + */ +export type RouterMiddleware = ( + args: RouterArgs, + next: () => Promise, +) => Promise; + +/** The URL the request asked for, without React Router's `.data` suffix. */ +function urlOf({ request, url }: RouterArgs): URL { + if (url) return url; + // React Router 7 passes no `url`. `_routes` is only ever its own param. + const fromRequest = new URL(request.url); + fromRequest.searchParams.delete("_routes"); + return fromRequest; +} + +/** A redirect, as React Router's `redirect` makes, without importing it. */ +function redirectTo(location: string): Response { + return new Response(null, { status: 302, headers: { Location: location } }); +} + +/** + * The root route's server middleware, which gives each request a cookie + * jar and refreshes the session while the response can still set the + * cookie. Export it as the root route's `middleware`, or spread it first + * into a list of your own. + * + * It refreshes access that expires within `within` seconds, before any + * loader reads it. A failed refresh doesn't fail the request. Loaders read + * the session as usual, and an error there reaches the route's error + * boundary. + * + * It sets `Cache-Control` to `private, no-store` on each response that + * doesn't set its own, unless you pass `cacheControl`. + * + * It's {@link cookieJarMiddleware} followed by the refresh, and needs React + * Router 8, or 7.9 and later with `future.v8_middleware`. + * + * Throws `INVALID_OPTIONS` when `within` is negative. + * + * @example + * ```ts + * import type { ServerAuth } from "@monarcode/session-kit/server"; + * import { sessionMiddleware } from "@monarcode/session-kit/react-router/server"; + * + * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; + * + * // app/root.tsx + * export const middleware = sessionMiddleware(serverAuth); + * ``` + * + * @see {@link requireSession} to let only signed-in users through. + * @since 0.1.0 + */ +export function sessionMiddleware( + serverAuth: ServerAuth, + options?: SessionMiddlewareOptions, +): RouterMiddleware[] { + const { within, cacheControl } = middlewareOptions(options); + const refresh: RouterMiddleware = async ({ context }, next) => { + await refreshBeforeRendering(serverAuth, routerJar(context), within); + const response = await next(); + if (cacheControl === false || response.headers.has("Cache-Control")) + return response; + return withHeaders(response, (headers) => + headers.set("Cache-Control", cacheControl), + ); + }; + return [cookieJarMiddleware, refresh]; +} + +/** + * Options for {@link requireSession}. + * + * @example + * ```ts + * import type { + * SessionGuardOptions, + * } from "@monarcode/session-kit/react-router/server"; + * + * // For an app built with `basename: "/app"`. + * export const options: SessionGuardOptions = { + * loginPath: "/sign-in", + * basename: "/app", + * }; + * ``` + * + * @since 0.1.0 + */ +export type SessionGuardOptions = { + /** + * Your sign-in page's path in the app, starting with `/`, without the + * `basename`. + * @default "/login" + */ + loginPath?: string | undefined; + /** + * The app's `basename`, if it has one. React Router adds it to a + * loader's redirects but not to middleware's, so the guard adds it to + * its own. It leaves it out of `redirectTo`, which a loader then uses. + */ + basename?: string | undefined; +}; + +/** + * Server middleware that lets only signed-in users through, made by + * {@link requireSession}. Call `session(context)` in the loaders and actions + * it guards for the session, which is never `null` there. + * + * @example + * ```ts + * import type { + * RouterContextLike, + * SessionGuard, + * } from "@monarcode/session-kit/react-router/server"; + * + * declare const signedIn: SessionGuard<{ id: number; firstName: string }>; + * + * export function loader({ context }: { context: RouterContextLike }) { + * return { name: signedIn.session(context).user.firstName }; + * } + * ``` + * + * @since 0.1.0 + */ +export type SessionGuard = RouterMiddleware & { + /** + * The request's session, once the guard has let it through. It's read + * when called, so a change by an action shows. + * + * Throws `INVALID_OPTIONS` when the guard hasn't run for this request, + * such as in a route outside the ones it guards. Throws `UNAUTHENTICATED` + * once an action signed out, and `REFRESH_FAILED` when the access token + * can no longer be refreshed. + */ + readonly session: (context: RouterContextLike) => Session; +}; + +/** + * Makes server middleware that lets only signed-in users through to a route + * and the routes nested in it ({@link SessionGuard}). Their loaders and + * actions get the session from its `session(context)`, never `null`. + * + * Signed-out users go to `loginPath`, with `?redirectTo=` set to the URL + * they asked for, for page loads and navigation in the browser alike. Other + * errors, such as `REFRESH_FAILED` after a failed refresh, reach the route's + * error boundary. + * + * List it in the guarded route's `middleware`, with + * {@link sessionMiddleware} in the root route. Server middleware runs during + * navigation in the browser only when a route has a loader to fetch, so give + * the guarded route a `loader`, even `() => null`. + * + * Throws `INVALID_OPTIONS` when `loginPath` or `basename` doesn't start with + * `/`. + * + * @example + * ```ts + * import type { ServerAuth } from "@monarcode/session-kit/server"; + * import { requireSession } from "@monarcode/session-kit/react-router/server"; + * + * type User = { id: number; firstName: string }; + * declare const serverAuth: ServerAuth; + * + * // app/auth/session.server.ts + * export const signedIn = requireSession(serverAuth); + * + * // app/routes/protected.tsx + * export const middleware = [signedIn]; + * export const loader = () => null; + * ``` + * + * @see {@link redirectIfSignedIn} for the sign-in page. + * @since 0.1.0 + */ +export function requireSession( + serverAuth: ServerAuth, + options: SessionGuardOptions = {}, +): SessionGuard { + const { loginPath = "/login", basename } = options; + // Fails fast on bad paths, before any request. + loginHref(loginPath, "/"); + stripBasename("/", basename); + // The requests it let through, by their jar. + const passed = new WeakSet(); + const guard: RouterMiddleware = async (args, next) => { + const jar = routerJar(args.context); + if (!(await serverAuth.getSession(jar))) { + const { pathname, search } = urlOf(args); + const returnTo = safeReturnTo( + stripBasename(pathname, basename) + search, + { loginPath }, + ); + throw redirectTo( + withBasename(loginHref(loginPath, returnTo), basename), + ); + } + passed.add(jar); + return next(); + }; + return Object.assign(guard, { + session(context: RouterContextLike): Session { + const jar = routerJar(context); + if (!passed.has(jar)) + throw new AuthError( + "INVALID_OPTIONS", + "Read the session where requireSession guards the route: list it in the middleware of this route or a route above it", + ); + const state = serverAuth.forRequest(jar).state.get(); + if (state.status === "authenticated" || state.status === "refreshing") + return Object.freeze({ + sessionId: state.sessionId, + user: state.user, + }); + throw state.status === "unavailable" + ? new AuthError( + "REFRESH_FAILED", + "The session can't be used: its access token couldn't be refreshed", + ) + : new AuthError( + "UNAUTHENTICATED", + "Signed out since requireSession let the request through", + ); + }, + }); +} + +/** + * A loader typed by its shape, such as {@link redirectIfSignedIn}'s. + * + * @example + * ```ts + * import type { RouterLoader } from "@monarcode/session-kit/react-router/server"; + * + * export const loader: RouterLoader = async () => null; + * ``` + * + * @since 0.1.0 + */ +export type RouterLoader = (args: RouterArgs) => Promise; + +/** + * Makes the loader for your sign-in page, which sends a signed-in user on to + * the page's `redirectTo` search param, made safe with `safeReturnTo`. + * Signed-out users see the page. React Router adds the app's `basename` to + * the redirect. + * + * If the session can't be read, such as after a failed refresh, the sign-in + * page shows, so the user can sign in again. + * + * Throws `INVALID_OPTIONS` when a `loginPath` doesn't start with `/`. + * + * @example + * ```ts + * import type { ServerAuth } from "@monarcode/session-kit/server"; + * import { redirectIfSignedIn } from "@monarcode/session-kit/react-router/server"; + * + * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; + * + * // app/routes/login.tsx + * export const loader = redirectIfSignedIn(serverAuth); + * ``` + * + * @since 0.1.0 + */ +export function redirectIfSignedIn( + serverAuth: ServerAuth, + options: SafeReturnToOptions = {}, +): RouterLoader { + // Fails fast on a bad path, before any request. + safeReturnTo("/", options); + return async (args) => { + const jar = routerJar(args.context); + if (await serverAuth.getSession(jar).catch(() => null)) { + const redirect = urlOf(args).searchParams.get("redirectTo"); + throw redirectTo(safeReturnTo(redirect, options)); + } + return null; + }; +} diff --git a/src/server/auth.ts b/src/server/auth.ts index c18637b..bfec1b8 100644 --- a/src/server/auth.ts +++ b/src/server/auth.ts @@ -172,6 +172,66 @@ export type RefreshIfDueOptions = { within?: number | undefined; }; +/** + * Options for the middleware that refreshes before each request: + * `refreshSession` from `@monarcode/session-kit/tanstack-start/server` and + * `sessionMiddleware` from `@monarcode/session-kit/react-router/server`. + * + * @example + * ```ts + * import type { SessionMiddlewareOptions } from "@monarcode/session-kit/server"; + * + * // Tokens that live five minutes: refresh in their last two. + * export const options: SessionMiddlewareOptions = { + * within: 120, + * cacheControl: "private, no-store", + * }; + * ``` + * + * @since 0.1.0 + */ +export type SessionMiddlewareOptions = { + /** + * Refreshes when the access token expires within this many seconds, as + * {@link RefreshIfDueOptions} explains. + * @default 60 + */ + within?: number | undefined; + /** + * The `Cache-Control` header for every response that doesn't set its own, + * as each one depends on who is signed in. `false` leaves every response + * as it is. + * @default "private, no-store" + */ + cacheControl?: string | false | undefined; +}; + +/** + * Refreshes before rendering, for the adapters' middleware. A failure is + * left for the routes, which read the session as usual. + */ +export async function refreshBeforeRendering( + serverAuth: ServerAuth, + jar: CookieJar, + within: number, +): Promise { + await serverAuth.refreshIfDue(jar, { within }).catch(() => {}); +} + +/** + * The middleware's options, checked when it's made: a bad `within` would + * otherwise reject on every request, where the middleware swallows it. + */ +export function middlewareOptions({ + within, + cacheControl = "private, no-store", +}: SessionMiddlewareOptions = {}): { + within: number; + cacheControl: string | false; +} { + return { within: refreshWithin({ within }), cacheControl }; +} + declare const requestAuth: unique symbol; type RequestAuthBase = { @@ -433,8 +493,15 @@ export type ServerAuth = ServerAuthBase & ) => Promise>; }); -/** `refreshIfDue`'s default `within`, in seconds. */ -const DEFAULT_WITHIN = 60; +/** `refreshIfDue`'s `within`, in seconds. */ +export function refreshWithin({ within = 60 }: RefreshIfDueOptions): number { + if (!Number.isFinite(within) || within < 0) + throw new AuthError( + "INVALID_OPTIONS", + "within must be zero or more seconds", + ); + return within; +} /** * Creates the server side of Session kit ({@link ServerAuth}). It keeps both @@ -804,12 +871,7 @@ export function createServerAuth( }, async refreshIfDue(jar, refreshOptions = {}) { requireWritable(jar, "refreshIfDue"); - const within = refreshOptions.within ?? DEFAULT_WITHIN; - if (!Number.isFinite(within) || within < 0) - throw new AuthError( - "INVALID_OPTIONS", - "within must be zero or more seconds", - ); + const within = refreshWithin(refreshOptions); const client = clientOf(jar); const credentials = await client.credentials.get(); if (!credentials) return null; diff --git a/src/server/index.ts b/src/server/index.ts index 28a3641..900e199 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -7,5 +7,6 @@ export type { ServerAuth, ServerAuthOptions, SessionCookieOptions, + SessionMiddlewareOptions, } from "./auth.js"; export type { CookieJar, CookieOptions } from "./cookies.js"; diff --git a/src/server/request-jar.ts b/src/server/request-jar.ts index 9f2d521..66f8ab4 100644 --- a/src/server/request-jar.ts +++ b/src/server/request-jar.ts @@ -54,19 +54,31 @@ function parseCookies(header: string | null): Map { return cookies; } -/** `response` with `lines` as `Set-Cookie` headers. */ -function withCookies(response: Response, lines: string[]): Response { +/** + * `response` after `change` to its headers, or a copy when they can't + * change, as on `Response.redirect()` or a `fetch` response. + */ +export function withHeaders( + response: Response, + change: (headers: Headers) => void, +): Response { try { - for (const line of lines) response.headers.append("Set-Cookie", line); + change(response.headers); return response; } catch { - // Immutable headers, as on `Response.redirect()` or a `fetch` response. const copy = new Response(response.body, response); - for (const line of lines) copy.headers.append("Set-Cookie", line); + change(copy.headers); return copy; } } +/** `response` with `lines` as `Set-Cookie` headers. */ +function withCookies(response: Response, lines: string[]): Response { + return withHeaders(response, (headers) => { + for (const line of lines) headers.append("Set-Cookie", line); + }); +} + /** * The cookie jar of `request`, whose cookies `respond` sets on its response. */ diff --git a/src/tanstack-start/server.ts b/src/tanstack-start/server.ts index 42e39b3..254de77 100644 --- a/src/tanstack-start/server.ts +++ b/src/tanstack-start/server.ts @@ -1,15 +1,21 @@ +import type { RequestServerFn } from "@tanstack/react-start"; import { deleteCookie, getCookie, getRequest, + getResponseHeader, setCookie, + setResponseHeader, } from "@tanstack/react-start/server"; import { AuthError } from "../core/errors.js"; import { lazyRequestAuth, + middlewareOptions, + refreshBeforeRendering, type RequestAuth, type ServerAuth, + type SessionMiddlewareOptions, } from "../server/auth.js"; import type { CookieJar, CookieOptions } from "../server/cookies.js"; @@ -125,3 +131,60 @@ export function startAuth( ): RequestAuth { return lazyRequestAuth(serverAuth, startJar); } + +/** + * Refreshes the session before each request, while the response can still + * set the cookie. Pass it to Start's `createMiddleware().server()`, and list + * that middleware in `requestMiddleware` in `src/start.ts`. + * + * It refreshes access that expires within `within` seconds, so pages and + * server functions don't refresh while rendering, once a cookie can't be + * set. A failed refresh doesn't fail the request. Routes read the session + * as usual, and an error there reaches the route's error component. + * + * It sets `Cache-Control` to `private, no-store` on each response that + * doesn't set its own, unless you pass `cacheControl`. + * + * Start bundles `src/start.ts` for the browser too, and strips only what's + * inside `.server()` from it. Calling `refreshSession` there keeps + * `serverAuth` out of the browser bundle. + * + * Throws `INVALID_OPTIONS` when `within` is negative. + * + * @example + * ```ts + * import type { ServerAuth } from "@monarcode/session-kit/server"; + * import { refreshSession } from "@monarcode/session-kit/tanstack-start/server"; + * import { createMiddleware, createStart } from "@tanstack/react-start"; + * + * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; + * + * const sessionMiddleware = createMiddleware({ type: "request" }).server( + * refreshSession(serverAuth), + * ); + * + * export const startInstance = createStart(() => ({ + * requestMiddleware: [sessionMiddleware], + * })); + * ``` + * + * @since 0.1.0 + */ +export function refreshSession( + serverAuth: ServerAuth, + options?: SessionMiddlewareOptions, +): RequestServerFn { + const { within, cacheControl } = middlewareOptions(options); + return async ({ next }) => { + await refreshBeforeRendering(serverAuth, startJar(), within); + const result = await next(); + // Start applies helper headers over a response's own: check both. + if ( + cacheControl !== false && + !result.response.headers.has("Cache-Control") && + getResponseHeader("Cache-Control") === undefined + ) + setResponseHeader("Cache-Control", cacheControl); + return result; + }; +} diff --git a/tests/consumer.ts b/tests/consumer.ts index 1c8e1a2..f390aba 100644 --- a/tests/consumer.ts +++ b/tests/consumer.ts @@ -1,14 +1,23 @@ +import type { + LoaderFunction, + LoaderFunctionArgs, + MiddlewareFunction, +} from "react-router"; + import * as Fetch from "@monarcode/effetch"; import { createRootRouteWithContext, createRouter, } from "@tanstack/react-router"; +import { createMiddleware, createStart } from "@tanstack/react-start"; import * as Effect from "effect/Effect"; import type * as HttpClient from "effect/http/HttpClient"; import type * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; import * as SecureStore from "expo-secure-store"; +import { cookies } from "next/headers.js"; +import { redirect } from "next/navigation.js"; import { NextResponse, type NextRequest } from "next/server.js"; import { z } from "zod"; @@ -45,12 +54,21 @@ import { type UserInput, type UserOf, } from "../dist/index.js"; -import { nextJar, proxyJar, type NextCookies } from "../dist/next/index.js"; +import { + nextJar, + nextSession, + proxyJar, + type NextCookies, + type NextSession, +} from "../dist/next/index.js"; import * as reactRouter from "../dist/react-router/index.js"; import { cookieJarMiddleware, + redirectIfSignedIn, + requireSession as requireServerSession, routerAuth, routerJar, + sessionMiddleware, type RouterContextLike, } from "../dist/react-router/server.js"; import * as react from "../dist/react/index.js"; @@ -73,7 +91,11 @@ import { type RouterAuth, } from "../dist/tanstack-router/index.js"; import { connectSession, loadSession } from "../dist/tanstack-start/index.js"; -import { startAuth, startJar } from "../dist/tanstack-start/server.js"; +import { + refreshSession, + startAuth, + startJar, +} from "../dist/tanstack-start/server.js"; const userSchema = z.object({ id: z.string(), email: z.string() }); @@ -580,6 +602,62 @@ declare const routerContext: RouterContextLike; const routerSession: RequestAuth = sessionOf(routerContext); void routerSession; +// The adapters' middleware and guards fit the frameworks' own types. +const rootMiddleware: MiddlewareFunction[] = + sessionMiddleware(serverAuth); +const signedIn = requireServerSession(serverAuth, { + loginPath: "/login", + basename: "/app", +}); +const guardMiddleware: MiddlewareFunction[] = [signedIn]; +const loginLoader: LoaderFunction = redirectIfSignedIn(serverAuth, { + loginPath: ["/login", "/sign-up"], +}); +void [rootMiddleware, guardMiddleware, loginLoader]; +export function guardedLoader({ context }: LoaderFunctionArgs) { + const email: string = signedIn.session(context).user.email; + return email; +} +// @ts-expect-error The middleware takes no list of paths. +sessionMiddleware(serverAuth, { paths: ["/"] }); +void sessionMiddleware(serverAuth, { within: 15, cacheControl: false }); +// @ts-expect-error The guard's session is never null. +const guardedNull: null = signedIn.session(routerContext); +void guardedNull; + +const startSessionMiddleware = createMiddleware({ type: "request" }).server( + refreshSession(serverAuth, { within: 15, cacheControl: "private" }), +); +void createStart(() => ({ requestMiddleware: [startSessionMiddleware] })); +// After middleware that adds context. +const withRequestId = createMiddleware({ type: "request" }).server(({ next }) => + next({ context: { requestId: "r1" } }), +); +void createMiddleware({ type: "request" }) + .middleware([withRequestId]) + .server(refreshSession(serverAuth)); + +const appSessionNext: NextSession = nextSession(serverAuth, { + cookies, + redirect, +}); +export async function guardedPage() { + const { user } = await appSessionNext.require("/orders"); + const current: AppUser | undefined = (await appSessionNext.get())?.user; + await appSessionNext.redirectIfSignedIn(null); + const writable: RequestAuth = + await appSessionNext.writable(); + return [user.email, current, writable]; +} +declare const proxyRequest: NextRequest; +const proxied: Promise = appSessionNext.refresh( + proxyRequest, + NextResponse.next(), +); +void proxied; +// @ts-expect-error nextSession needs Next's cookies and redirect. +nextSession(serverAuth, { cookies }); + // The session and user types of any client. const appSession: SessionOf = { sessionId: "s", diff --git a/tests/next.test.ts b/tests/next.test.ts index f2dbca3..40b361d 100644 --- a/tests/next.test.ts +++ b/tests/next.test.ts @@ -3,6 +3,7 @@ import { test } from "node:test"; import { nextJar, + nextSession, proxyJar, type NextCookies, } from "@monarcode/session-kit/next"; @@ -250,3 +251,123 @@ test("a read-only view's renew returns a token the writable jar already renewed" code("REFRESH_FAILED"), ); }); + +/** What Next's `redirect` throws, standing in for it. */ +class Redirect extends Error { + readonly location: string; + constructor(location: string) { + super(`Redirect to ${location}`); + this.location = location; + } +} +const redirect = (url: string): never => { + throw new Redirect(url); +}; +const redirected = (location: string) => (error: unknown) => + error instanceof Redirect && error.location === location; + +test("nextSession reads and guards for Server Components, and writes for Server Functions", async () => { + const response = NextResponse.next(); + const store = actionStore(nextRequest(), response); + const session = nextSession(serverAuth, { + cookies: async () => store, + redirect, + }); + + assert.equal(await session.get(), null); + await assert.rejects( + session.require("/orders?page=2"), + redirected("/login?redirectTo=%2Forders%3Fpage%3D2"), + ); + await session.redirectIfSignedIn("/orders"); + await assert.rejects( + (await session.readOnly()).signIn(tokens()), + code("INVALID_OPTIONS"), + ); + + const signedIn = await (await session.writable()).signIn(tokens()); + assert.match(response.headers.getSetCookie()[0]!, /^app\.session=1\./); + assert.deepEqual(await session.get(), signedIn); + assert.deepEqual(await session.require("/orders"), signedIn); + assert.equal( + (await (await session.readOnly()).credentials.get())?.accessToken, + "access-1", + ); + await assert.rejects( + session.redirectIfSignedIn("/orders"), + redirected("/orders"), + ); + await assert.rejects( + session.redirectIfSignedIn("https://evil.test/"), + redirected("/"), + ); + await assert.rejects(session.redirectIfSignedIn("/login"), redirected("/")); +}); + +test("nextSession's guards use loginPath, and bad options throw", async () => { + const store = actionStore(nextRequest(), NextResponse.next()); + const cookies = async () => store; + const session = nextSession(serverAuth, { + cookies, + redirect, + loginPath: "/sign-in", + }); + await assert.rejects( + session.require("/sign-in"), + redirected("/sign-in?redirectTo=%2F"), + ); + assert.throws( + () => nextSession(serverAuth, {} as never), + code("INVALID_OPTIONS"), + ); + assert.throws( + () => nextSession(serverAuth, { cookies, redirect, loginPath: "login" }), + code("INVALID_OPTIONS"), + ); + assert.throws( + () => nextSession(serverAuth, { cookies, redirect, within: -1 }), + code("INVALID_OPTIONS"), + ); +}); + +test("nextSession's refresh refreshes in Proxy and resolves the response", async () => { + const signedIn = NextResponse.next(); + await serverAuth.signIn( + nextJar(actionStore(nextRequest(), signedIn), { writable: true }), + tokens({ expiresIn: 30 }), + ); + const cookies = async () => actionStore(nextRequest(), NextResponse.next()); + + refreshes = 0; + const early = NextResponse.next(); + const later = nextSession(serverAuth, { cookies, redirect, within: 10 }); + assert.equal(await later.refresh(nextRequest(signedIn), early), early); + assert.equal(refreshes, 0); + assert.deepEqual(early.headers.getSetCookie(), []); + + const response = NextResponse.next(); + const session = nextSession(serverAuth, { cookies, redirect }); + assert.equal( + await session.refresh(nextRequest(signedIn), response), + response, + ); + assert.equal(refreshes, 1); + assert.match(response.headers.getSetCookie()[0]!, /^app\.session=1\./); + + const failing = createServerAuth({ + name: "app", + user: userSchema, + secret: SECRET, + refresh: async () => { + throw new Error("backend down"); + }, + }); + const kept = NextResponse.next(); + assert.equal( + await nextSession(failing, { cookies, redirect }).refresh( + nextRequest(signedIn), + kept, + ), + kept, + ); +}); diff --git a/tests/react-router-server.test.ts b/tests/react-router-server.test.ts index 6775d3c..6bb3eb9 100644 --- a/tests/react-router-server.test.ts +++ b/tests/react-router-server.test.ts @@ -6,9 +6,14 @@ import * as reactRouter from "react-router"; import type { Credentials, Session } from "@monarcode/session-kit"; import { cookieJarMiddleware, + redirectIfSignedIn, + requireSession, routerAuth, routerJar, + sessionMiddleware, + type RouterArgs, type RouterContextLike, + type RouterMiddleware, } from "@monarcode/session-kit/react-router/server"; import { createServerAuth } from "@monarcode/session-kit/server"; @@ -293,7 +298,8 @@ const middlewareSupported = "RouterContextProvider" in reactRouter; * documents answer with the loaders' data. `/` is guarded, `/login` signs in * and `/session` is a resource route. */ -function requestHandler() { +function requestHandler({ basename }: { basename?: string } = {}) { + const guard = basename ? requireSession(serverAuth, { basename }) : signedIn; const component = () => null; const routes = { root: { @@ -301,14 +307,7 @@ function requestHandler() { path: "", module: { default: component, - middleware: [ - cookieJarMiddleware, - async ({ context }: { context: RouterContextLike }) => { - await serverAuth - .refreshIfDue(routerJar(context)) - .catch(() => {}); - }, - ], + middleware: sessionMiddleware(serverAuth), loader: async ({ context }: { context: RouterContextLike }) => ({ session: await serverAuth.getSession(routerJar(context)), }), @@ -320,6 +319,7 @@ function requestHandler() { path: "login", module: { default: component, + loader: redirectIfSignedIn(serverAuth), action: async ({ context }: { context: RouterContextLike }) => { await serverAuth.signIn(routerJar(context), tokens()); throw reactRouter.redirect("/"); @@ -331,12 +331,8 @@ function requestHandler() { parentId: "root", module: { default: component, - middleware: [ - async ({ context }: { context: RouterContextLike }) => { - if (!(await serverAuth.getSession(routerJar(context)))) - throw reactRouter.redirect("/login"); - }, - ], + middleware: [guard], + loader: () => null, }, }, "routes/home": { @@ -345,9 +341,12 @@ function requestHandler() { index: true, module: { default: component, - loader: async ({ context }: { context: RouterContextLike }) => - (await serverAuth.credentials.get(routerJar(context))) - ?.accessToken, + loader: async ({ context }: { context: RouterContextLike }) => ({ + accessToken: ( + await serverAuth.credentials.get(routerJar(context)) + )?.accessToken, + user: guard.session(context).user, + }), }, }, "routes/session": { @@ -385,6 +384,7 @@ function requestHandler() { publicPath: "/", assetsBuildDirectory: "build/client", future: { v8_middleware: true }, + ...(basename && { basename }), ssr: true, isSpaMode: false, prerender: [], @@ -406,6 +406,289 @@ const expiring = async () => ), ); +/** Runs `middleware` in order around `respond`, as React Router does. */ +function run( + middleware: readonly RouterMiddleware[], + args: RouterArgs, + respond: () => Promise = async () => new Response("ok"), +): Promise { + const [first, ...rest] = middleware; + return first ? first(args, () => run(rest, args, respond)) : respond(); +} + +/** Calls the redirect a guard throws, or fails. */ +async function thrown(promise: Promise): Promise { + try { + await promise; + } catch (error) { + if (error instanceof Response) return error; + throw error; + } + assert.fail("Expected a redirect"); +} + +const signedIn = requireSession(serverAuth); + +test("sessionMiddleware gives the request a jar, refreshes, and marks the response private", async () => { + const cookie = await expiring(); + refreshes = 0; + const context = newContext(); + const response = await run( + sessionMiddleware(serverAuth), + { request: request(cookie), context }, + async () => { + assert.equal( + (await serverAuth.credentials.get(routerJar(context)))?.accessToken, + "access-2", + ); + return Response.json({ ok: true }); + }, + ); + assert.equal(refreshes, 1); + assert.equal(response.headers.get("Cache-Control"), "private, no-store"); + assert.match(response.headers.getSetCookie()[0]!, /^app\.session=1\./); + assert.deepEqual(await response.json(), { ok: true }); +}); + +test("sessionMiddleware takes the header's value, or leaves it alone", async () => { + const custom = await run( + sessionMiddleware(serverAuth, { cacheControl: "private, max-age=0" }), + { request: request(), context: newContext() }, + ); + assert.equal(custom.headers.get("Cache-Control"), "private, max-age=0"); + + const own = await run( + sessionMiddleware(serverAuth, { cacheControl: false }), + { request: request(), context: newContext() }, + async () => + new Response("ok", { headers: { "Cache-Control": "max-age=60" } }), + ); + assert.equal(own.headers.get("Cache-Control"), "max-age=60"); +}); + +test("sessionMiddleware refreshes within `within`, and a failed refresh doesn't fail the request", async (t) => { + t.mock.timers.enable({ apis: ["Date"], now: Date.now() }); + const cookie = await expiring(); + refreshes = 0; + await run(sessionMiddleware(serverAuth, { within: 10 }), { + request: request(cookie), + context: newContext(), + }); + assert.equal(refreshes, 0); + + // Expired, and the backend can't refresh it. + t.mock.timers.tick(31_000); + const down = Promise.reject(new Error("backend down")); + down.catch(() => {}); + refreshAnswer = down; + const context = newContext(); + const response = await run( + sessionMiddleware(serverAuth), + { request: request(cookie), context }, + async () => { + await assert.rejects( + serverAuth.credentials.get(routerJar(context)), + code("REFRESH_FAILED"), + ); + return new Response("ok"); + }, + ); + assert.equal(refreshes, 1); + assert.equal(response.status, 200); +}); + +test("sessionMiddleware, requireSession and redirectIfSignedIn check their options when made", () => { + assert.throws( + () => sessionMiddleware(serverAuth, { within: -1 }), + code("INVALID_OPTIONS"), + ); + assert.throws( + () => requireSession(serverAuth, { loginPath: "login" }), + code("INVALID_OPTIONS"), + ); + assert.throws( + () => + redirectIfSignedIn(serverAuth, { loginPath: ["/login", "sign-in"] }), + code("INVALID_OPTIONS"), + ); +}); + +test("requireSession sends a signed-out request to sign in, and back", async () => { + const context = newContext(); + const response = await thrown( + run([cookieJarMiddleware, signedIn], { + request: request("", "https://app.test/orders.data?page=2"), + url: new URL("https://app.test/orders?page=2"), + context, + }), + ); + assert.equal(response.status, 302); + assert.equal( + response.headers.get("Location"), + "/login?redirectTo=%2Forders%3Fpage%3D2", + ); + assert.throws(() => signedIn.session(context), code("INVALID_OPTIONS")); + + // React Router 7 passes no `url`, and a path that leaves the site comes back home. + const home = await thrown( + run( + [ + cookieJarMiddleware, + requireSession(serverAuth, { loginPath: "/sign-in" }), + ], + { + request: request("", "https://app.test//evil.test/"), + context: newContext(), + }, + ), + ); + assert.equal(home.headers.get("Location"), "/sign-in?redirectTo=%2F"); +}); + +test("requireSession adds the basename to its redirect, and leaves it out of redirectTo", async () => { + const response = await thrown( + run( + [ + cookieJarMiddleware, + requireSession(serverAuth, { basename: "/app/" }), + ], + { + request: request("", "https://app.test/app/orders?page=2"), + url: new URL("https://app.test/app/orders?page=2"), + context: newContext(), + }, + ), + ); + assert.equal( + response.headers.get("Location"), + "/app/login?redirectTo=%2Forders%3Fpage%3D2", + ); + assert.throws( + () => requireSession(serverAuth, { basename: "app" }), + code("INVALID_OPTIONS"), + ); +}); + +test("requireSession leaves React Router 7's _routes param out of redirectTo", async () => { + const response = await thrown( + run([cookieJarMiddleware, signedIn], { + request: request( + "", + "https://app.test/orders?page=2&_routes=routes%2Forders", + ), + context: newContext(), + }), + ); + assert.equal( + response.headers.get("Location"), + "/login?redirectTo=%2Forders%3Fpage%3D2", + ); +}); + +test("requireSession's session follows an action's changes in the same request", async () => { + const cookie = cookieHeader( + await handle("", (jar) => serverAuth.signIn(jar, tokens())), + ); + const context = newContext(); + await run( + [cookieJarMiddleware, signedIn], + { request: request(cookie), context }, + async () => { + const session = routerAuth(serverAuth)(context); + await session.updateUser({ ...user, role: "admin" }); + assert.equal(signedIn.session(context).user.role, "admin"); + assert.ok(Object.isFrozen(signedIn.session(context))); + await session.signOut(); + assert.throws( + () => signedIn.session(context), + code("UNAUTHENTICATED"), + ); + return new Response("ok"); + }, + ); +}); + +test("sessionMiddleware sets Cache-Control on a response that can't change, and leaves a response's own alone", async () => { + const response = await run( + sessionMiddleware(serverAuth), + { request: request(), context: newContext() }, + async () => Response.redirect("https://app.test/public", 302), + ); + assert.equal(response.headers.get("Cache-Control"), "private, no-store"); + const own = await run( + sessionMiddleware(serverAuth), + { request: request(), context: newContext() }, + async () => + new Response("ok", { + headers: { "Cache-Control": "public, max-age=60" }, + }), + ); + assert.equal(own.headers.get("Cache-Control"), "public, max-age=60"); +}); + +test("requireSession lets a signed-in request through, with its session for the loaders", async () => { + const cookie = cookieHeader( + await handle("", (jar) => serverAuth.signIn(jar, tokens())), + ); + const context = newContext(); + const response = await run( + [cookieJarMiddleware, signedIn], + { request: request(cookie), context }, + async () => Response.json(signedIn.session(context).user), + ); + assert.deepEqual(await response.json(), user); + assert.throws( + () => requireSession(serverAuth).session(context), + code("INVALID_OPTIONS"), + ); + + // A context reused for another request doesn't keep the session. + await run([cookieJarMiddleware], { request: request(), context }); + assert.throws(() => signedIn.session(context), code("INVALID_OPTIONS")); +}); + +test("redirectIfSignedIn sends a signed-in user on to a safe redirectTo", async () => { + const cookie = cookieHeader( + await handle("", (jar) => serverAuth.signIn(jar, tokens())), + ); + const loader = redirectIfSignedIn(serverAuth); + + const at = async (cookie: string, url: string) => { + const context = newContext(); + let result: unknown; + await run( + [cookieJarMiddleware], + { request: request(cookie, url), context }, + async () => { + result = await loader({ + request: request(cookie, url), + context, + }).catch((error: unknown) => error); + return new Response("ok"); + }, + ); + return result; + }; + + assert.equal( + await at("", "https://app.test/login?redirectTo=%2Forders"), + null, + ); + const orders = await at( + cookie, + "https://app.test/login?redirectTo=%2Forders", + ); + assert.ok(orders instanceof Response); + assert.equal(orders.headers.get("Location"), "/orders"); + const unsafe = await at( + cookie, + "https://app.test/login?redirectTo=https%3A%2F%2Fevil.test", + ); + assert.equal((unsafe as Response).headers.get("Location"), "/"); + const back = await at(cookie, "https://app.test/login?redirectTo=%2Flogin"); + assert.equal((back as Response).headers.get("Location"), "/"); +}); + test( "React Router: a page refreshes in middleware, and its loaders and response get the new tokens", { skip: !middlewareSupported }, @@ -414,7 +697,8 @@ test( assert.equal(response.status, 200); assert.equal(refreshes, 1); const data = (await response.json()) as Record; - assert.equal(data["routes/home"], "access-2"); + assert.deepEqual(data["routes/home"], { accessToken: "access-2", user }); + assert.equal(response.headers.get("Cache-Control"), "private, no-store"); assert.deepEqual( (data.root as { session: { user: unknown } }).session.user, user, @@ -458,7 +742,7 @@ test( refreshAnswer = null; const response = await requestHandler()(request(cookie)); assert.equal(response.status, 302); - assert.equal(response.headers.get("Location"), "/login"); + assert.equal(response.headers.get("Location"), "/login?redirectTo=%2F"); assert.deepEqual(deleted(response), ["app.session"]); }, ); @@ -478,3 +762,53 @@ test( assert.match(response.headers.getSetCookie()[0]!, /^app\.session=1\./); }, ); + +test( + "React Router: the guards redirect page loads and navigation in the browser", + { skip: !middlewareSupported }, + async () => { + const handler = requestHandler(); + // Single fetch: the redirect travels in the body, without `.data`. + const data = await handler(request("", "https://app.test/_.data")); + assert.equal(data.status, 202); + const body = await data.text(); + assert.match(body, /\/login\?redirectTo=%2F/); + assert.doesNotMatch(body, /redirectTo=[^"]*\.data/); + + const cookie = cookieHeader( + await handle("", (jar) => serverAuth.signIn(jar, tokens())), + ); + const login = await handler( + request(cookie, "https://app.test/login?redirectTo=%2Fsession"), + ); + assert.equal(login.status, 302); + assert.equal(login.headers.get("Location"), "/session"); + assert.equal( + (await handler(request("", "https://app.test/login"))).status, + 200, + ); + }, +); + +test( + "React Router: with a basename, the guards' redirects stay under it", + { skip: !middlewareSupported }, + async () => { + const handler = requestHandler({ basename: "/app" }); + const guarded = await handler(request("", "https://app.test/app/")); + assert.equal(guarded.status, 302); + assert.equal( + guarded.headers.get("Location"), + "/app/login?redirectTo=%2F", + ); + + const cookie = cookieHeader( + await handle("", (jar) => serverAuth.signIn(jar, tokens())), + ); + const login = await handler( + request(cookie, "https://app.test/app/login?redirectTo=%2Fsession"), + ); + assert.equal(login.status, 302); + assert.equal(login.headers.get("Location"), "/app/session"); + }, +); diff --git a/tests/tanstack-start.test.ts b/tests/tanstack-start.test.ts index 7ab5f5c..83a4d3f 100644 --- a/tests/tanstack-start.test.ts +++ b/tests/tanstack-start.test.ts @@ -16,12 +16,14 @@ import { loadSession, } from "@monarcode/session-kit/tanstack-start"; import { + refreshSession, startAuth, startJar, } from "@monarcode/session-kit/tanstack-start/server"; import { createServerEntry, getResponseHeaders, + setResponseHeader, } from "@tanstack/react-start/server"; import * as Effect from "effect/Effect"; @@ -161,6 +163,131 @@ test("startAuth finds each request's session, and rejects outside a request", as assert.match(signedOut.setCookies[0]!, /^app\.session=; Max-Age=0/); }); +/** A server engine whose backend answers refreshes with `answer()`. */ +function refreshingAuth(answer: () => Promise) { + let refreshes = 0; + const app = createServerAuth({ + name: "app", + user: userSchema, + secret: SECRET, + refresh: async () => { + refreshes++; + return (await answer()) as never; + }, + }); + return { app, refreshes: () => refreshes }; +} + +/** + * Runs a request middleware's server function, as Start does for a page, + * with `respond` standing in for the routes after it. + */ +async function runMiddleware( + middleware: ReturnType, + respond: () => Promise, + response = new Response("ok"), +) { + let value!: T; + const next = async () => { + value = await respond(); + return { response }; + }; + const result = (await middleware({ next } as never)) as unknown as { + response: Response; + }; + assert.equal(result.response, response); + return value; +} + +test("refreshSession refreshes before the request and marks the response private", async () => { + const { app, refreshes } = refreshingAuth(async () => ({ + accessToken: "access-2", + refreshToken: "refresh-2", + expiresIn: 900, + })); + const signedIn = await handle("", () => + startAuth(app).signIn(tokens({ expiresIn: 30 })), + ); + const middleware = refreshSession(app); + const { result, setCookies } = await handle( + cookieHeader(signedIn.setCookies), + async () => { + const next = await runMiddleware(middleware, async () => { + const credentials = await startAuth(app).credentials.get(); + return credentials!.accessToken; + }); + return { + next, + cacheControl: getResponseHeaders().get("cache-control"), + }; + }, + ); + assert.deepEqual(result, { + next: "access-2", + cacheControl: "private, no-store", + }); + assert.equal(refreshes(), 1); + assert.match(setCookies[0]!, /^app\.session=1\./); +}); + +test("refreshSession takes the header's value or leaves it alone, and a failed refresh doesn't fail the request", async () => { + const { app, refreshes } = refreshingAuth(() => + Promise.reject(new Error("backend down")), + ); + const signedIn = await handle("", () => + startAuth(app).signIn(tokens({ expiresIn: 30 })), + ); + const cookie = cookieHeader(signedIn.setCookies); + const header = ( + middleware: ReturnType, + respond: () => Promise = async () => {}, + response?: Response, + ) => + handle(cookie, async () => { + await runMiddleware(middleware, respond, response); + return getResponseHeaders().get("cache-control"); + }); + assert.equal( + ( + await header( + refreshSession(app, { cacheControl: "private, max-age=0" }), + ) + ).result, + "private, max-age=0", + ); + assert.equal(refreshes(), 1); + assert.equal( + (await header(refreshSession(app, { cacheControl: false }))).result, + null, + ); + assert.equal( + (await header(refreshSession(app, { within: 10 }))).result, + "private, no-store", + ); + + // A route's own header stays, from its response or Start's helpers. + const own = new Response("ok", { + headers: { "Cache-Control": "public, max-age=60" }, + }); + assert.equal( + (await header(refreshSession(app), async () => {}, own)).result, + null, + ); + assert.equal( + ( + await header(refreshSession(app), async () => { + setResponseHeader("Cache-Control", "public, max-age=60"); + }) + ).result, + "public, max-age=60", + ); + + assert.throws( + () => refreshSession(app, { within: -1 }), + code("INVALID_OPTIONS"), + ); +}); + test("startAuth has every member a request's session has, passed through", async () => { const app = createServerAuth({ name: "app", From b5b7c7ccb524e803bca569d89bbc77c3911a93ba Mon Sep 17 00:00:00 2001 From: monarcode Date: Sat, 14 Nov 2026 03:36:21 +0100 Subject: [PATCH 06/26] feat(server): add a session route that the mirror client calls - Add sessionHandler and per-framework sessionRoute (Start, React Router, Next) - Make createMirrorAuth's revalidate, signOut and credentials optional with endpoint - Move the SSR examples and guides to the session route --- CHANGELOG.md | 25 ++ examples/README.md | 25 +- examples/next-app/app/actions.ts | 15 +- .../app/api/auth/credentials/route.ts | 25 -- examples/next-app/app/api/session/route.ts | 10 + examples/next-app/lib/auth/client.ts | 34 +-- examples/next-app/lib/auth/server.ts | 2 +- .../app/auth/client.ts | 36 +-- .../app/auth/session.server.ts | 2 +- .../react-router-framework-ssr/app/routes.ts | 3 +- .../app/routes/auth.credentials.ts | 25 -- .../app/routes/auth.session.ts | 24 +- .../tanstack-start-ssr/src/auth/client.ts | 19 +- .../tanstack-start-ssr/src/auth/functions.ts | 21 +- .../tanstack-start-ssr/src/auth/server.ts | 2 +- .../src/routes/api/session.ts | 13 + scripts/docs-pages.mjs | 18 +- site/content/docs/(latest)/effect.mdx | 6 +- site/content/docs/(latest)/reference/core.mdx | 2 +- .../content/docs/(latest)/reference/index.mdx | 30 +-- site/content/docs/(latest)/reference/next.mdx | 8 + .../reference/react-router-server.mdx | 8 + .../docs/(latest)/reference/server.mdx | 8 + .../reference/tanstack-start-server.mdx | 10 + site/content/docs/(latest)/security.mdx | 17 ++ .../docs/(latest)/server-rendering/index.mdx | 6 +- .../server-rendering/server-sessions.mdx | 17 +- site/content/docs/(latest)/setups/next.mdx | 76 +++--- .../docs/(latest)/setups/react-router-ssr.mdx | 75 ++---- .../docs/(latest)/setups/tanstack-start.mdx | 50 ++-- src/core/endpoint.ts | 123 ++++++++++ src/core/mirror.ts | 116 ++++++--- src/next/index.ts | 60 +++++ src/react-router/server.ts | 63 +++++ src/server/handler.ts | 187 +++++++++++++++ src/server/index.ts | 2 + src/tanstack-start/server.ts | 61 +++++ tests/consumer.ts | 44 ++++ tests/mirror.test.ts | 223 +++++++++++++++++- tests/next.test.ts | 28 +++ tests/react-router-server.test.ts | 54 +++++ tests/server.test.ts | 144 ++++++++++- tests/tanstack-start.test.ts | 29 +++ 43 files changed, 1384 insertions(+), 362 deletions(-) delete mode 100644 examples/next-app/app/api/auth/credentials/route.ts create mode 100644 examples/next-app/app/api/session/route.ts delete mode 100644 examples/react-router-framework-ssr/app/routes/auth.credentials.ts create mode 100644 examples/tanstack-start-ssr/src/routes/api/session.ts create mode 100644 src/core/endpoint.ts create mode 100644 src/server/handler.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f899f7..a5e6aa7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -90,6 +90,31 @@ sign-in page's URL with `?redirectTo=`, for a guard of your own. - `SessionMiddlewareOptions` in `@monarcode/session-kit/server`: `within` and `cacheControl`, for `refreshSession` and `sessionMiddleware`. +- A session route, in place of the server functions, Server Functions and + resource routes the guides had you write for the browser's client. It + reads the session, signs out, and gets or renews the access token when + `createServerAuth` has `clientCredentials`. It answers your own site's + pages only (by `Sec-Fetch-Site`, or a `POST`'s `Origin` on plain http), + with `Cache-Control: no-store`. Signing in stays your own code. + - `createMirrorAuth({ endpoint })` calls it. `revalidate`, `signOut` and + `credentials` are optional now, and win over `endpoint` when given. The + options' type needs `endpoint`, or `revalidate` and `signOut`. A failure + the server reports rejects with its `AuthErrorCode`. + - `sessionHandler(serverAuth)` in `@monarcode/session-kit/server` answers + it, for a request and its cookie jar (`SessionHandler`). + - `sessionRoute(serverAuth)` wraps it for each framework: a server route's + `handlers` in `@monarcode/session-kit/tanstack-start/server` + (`StartSessionRoute`), a resource route's `loader` and `action` in + `@monarcode/session-kit/react-router/server` (`RouterSessionRoute`), and + a Route Handler's `GET` and `POST` in `@monarcode/session-kit/next`, with + Next's `cookies` (`NextSessionRoute`). + + ```ts + // app/api/session/route.ts + export const { GET, POST } = sessionRoute(serverAuth, cookies); + // lib/auth/client.ts + createMirrorAuth({ name: "app", session, endpoint: "/api/session", signIn }); + ``` ### Changed diff --git a/examples/README.md b/examples/README.md index 4c2dbff..44e6f10 100644 --- a/examples/README.md +++ b/examples/README.md @@ -75,18 +75,21 @@ run ios` and `run android` build it natively. In CI it is only bundled, with with DummyJSON from a server function, and refreshes in request middleware (`src/start.ts`). `createMirrorAuth` gives the routes and components a client, filled by `loadSession` on the server and `connectSession` in the - browser. `auth/me` is called both from a server function and, with - `clientCredentials`, from the browser. Set `SESSION_SECRET` (32 or more - random characters) to run `vite preview`; `vite dev` uses a development - secret. The cookie is `Secure` outside `vite dev`, which Safari refuses - over `http://localhost`: try `vite preview` in another browser. See + browser. The browser signs out and gets the access token through the + session route (`src/routes/api/session.ts`). `auth/me` is called both from + a server function and, with `clientCredentials`, from the browser. Set + `SESSION_SECRET` (32 or more random characters) to run `vite preview`; + `vite dev` uses a development secret. The cookie is `Secure` outside + `vite dev`, which Safari refuses over `http://localhost`: try + `vite preview` in another browser. See [the guide](https://session-kit.pages.dev/docs/setups/tanstack-start). - **Next.js** keeps the session the same way: Proxy refreshes it (`proxy.ts`), Server Components read it through `lib/auth/session.ts`, and - Server Functions in `app/actions.ts` sign in and out. `useMirrorAuth` in + a Server Function in `app/actions.ts` signs in. `useMirrorAuth` in `app/providers.tsx` gives Client Components the client and renders the page again when the session changes in the browser, so the pages' - redirects run. The browser gets the access token from a Route Handler. + redirects run. The browser reads the session, signs out and gets the + access token through the session route (`app/api/session/route.ts`). `SESSION_SECRET` and Safari work as for TanStack Start, with `next start` and `next dev`. See [the guide](https://session-kit.pages.dev/docs/setups/next). - **React Router with server rendering** keeps the session the same way. @@ -95,10 +98,10 @@ run ios` and `run android` build it natively. In CI it is only bundled, with action signs in with a plain form that works before scripts load. `useMirrorAuth` in `app/root.tsx` gives the components the client and runs the loaders again when the session changes in the browser, so the - protected route's `requireSession` guard redirects. The browser signs out, revalidates - and gets the access token through the resource routes in - `app/routes/auth.*.ts`. `SESSION_SECRET` and Safari work as for TanStack - Start, with `pnpm start` (after `pnpm build`) and `react-router dev`. See + protected route's `requireSession` guard redirects. The browser reads the + session, signs out and gets the access token through the session route in + `app/routes/auth.session.ts`. `SESSION_SECRET` and Safari work as for + TanStack Start, with `pnpm start` (after `pnpm build`) and `react-router dev`. See [the guide](https://session-kit.pages.dev/docs/setups/react-router-ssr). - **Expo Router** saves the session with `secureStorage()`. `SessionGate` in `app/_layout.tsx` holds the splash screen, shows `src/unavailable.tsx` diff --git a/examples/next-app/app/actions.ts b/examples/next-app/app/actions.ts index c68216d..560fef2 100644 --- a/examples/next-app/app/actions.ts +++ b/examples/next-app/app/actions.ts @@ -1,17 +1,13 @@ "use server"; -// Server Functions the browser calls. Each is a public endpoint: Next checks -// that calls come from this site, and each one checks its own input. +// The sign-in the browser calls: a public endpoint. Next checks that calls +// come from this site, and it checks its own input. The session route in +// `api/session/route.ts` does the rest. import { z } from "zod"; import { login } from "../lib/auth/backend"; import { session } from "../lib/auth/session"; -/** Who is signed in, from the cookie. Holds no tokens. */ -export async function getSessionAction() { - return (await session.writable()).getSession(); -} - const credentials = z.object({ username: z.string(), password: z.string() }); /** @@ -33,8 +29,3 @@ export async function signInAction(input: unknown) { }; } } - -/** Clears the cookie. */ -export async function signOutAction() { - await (await session.writable()).signOut(); -} diff --git a/examples/next-app/app/api/auth/credentials/route.ts b/examples/next-app/app/api/auth/credentials/route.ts deleted file mode 100644 index 5305c80..0000000 --- a/examples/next-app/app/api/auth/credentials/route.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { z } from "zod"; - -import { session } from "../../../../lib/auth/session"; - -const rejected = z.object({ sessionId: z.string(), accessToken: z.string() }); - -/** - * The access token for the browser's own requests, never the refresh token: - * a POST with no body gets it, and one with the token DummyJSON rejected - * renews it. A route handler rather than a Server Function, so these calls - * don't wait behind other Server Functions or render the page again. - */ -export async function POST(request: Request) { - // Route handlers get no CSRF check from Next: accept this site only. - if (request.headers.get("sec-fetch-site") !== "same-origin") - return new Response(null, { status: 403 }); - const auth = await session.writable(); - const body = rejected.safeParse(await request.json().catch(() => null)); - const credentials = body.success - ? await auth.clientCredentials.renew(body.data) - : await auth.clientCredentials.get(); - return Response.json(credentials, { - headers: { "Cache-Control": "no-store" }, - }); -} diff --git a/examples/next-app/app/api/session/route.ts b/examples/next-app/app/api/session/route.ts new file mode 100644 index 0000000..d0c5126 --- /dev/null +++ b/examples/next-app/app/api/session/route.ts @@ -0,0 +1,10 @@ +import { sessionRoute } from "@monarcode/session-kit/next"; +import { cookies } from "next/headers"; + +import { serverAuth } from "../../../lib/auth/server"; + +/** + * The session route the browser's client calls: it reads the session, signs + * out, and gets the access token. It answers this site's own pages only. + */ +export const { GET, POST } = sessionRoute(serverAuth, cookies); diff --git a/examples/next-app/lib/auth/client.ts b/examples/next-app/lib/auth/client.ts index a89e8a7..e41f603 100644 --- a/examples/next-app/lib/auth/client.ts +++ b/examples/next-app/lib/auth/client.ts @@ -1,49 +1,27 @@ -import { - createMirrorAuth, - type ClientCredentials, - type SessionOf, -} from "@monarcode/session-kit"; +import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit"; -import { - getSessionAction, - signInAction, - signOutAction, -} from "../../app/actions"; +import { signInAction } from "../../app/actions"; // Types only: erased from the browser's bundle. import type { serverAuth } from "./server"; export type AppSession = SessionOf; -/** Asks the route handler for the access token, or renews `rejected`. */ -async function credentials(rejected?: object) { - const response = await fetch("/api/auth/credentials", { - method: "POST", - body: JSON.stringify(rejected ?? null), - }); - if (!response.ok) throw new Error(`Credentials failed (${response.status})`); - return (await response.json()) as ClientCredentials | null; -} - /** * The client the components use. It mirrors the session the server keeps in - * its cookie, starting from the one the layout rendered. `useMirrorAuth` - * creates it, once per request on the server and once in the browser. + * its cookie, starting from the one the layout rendered, and calls the + * session route in `app/api/session/route.ts`. `useMirrorAuth` creates it, + * once per request on the server and once in the browser. */ export function createAppAuth(session: AppSession | null) { return createMirrorAuth({ name: "session-kit-example", session, - revalidate: getSessionAction, + endpoint: "/api/session", signIn: async (input: { username: string; password: string }) => { const result = await signInAction(input); if ("error" in result) throw new Error(result.error); return result.session; }, - signOut: signOutAction, - credentials: { - get: () => credentials(), - renew: (rejected) => credentials(rejected), - }, }); } diff --git a/examples/next-app/lib/auth/server.ts b/examples/next-app/lib/auth/server.ts index 3d82a8a..00abba8 100644 --- a/examples/next-app/lib/auth/server.ts +++ b/examples/next-app/lib/auth/server.ts @@ -21,7 +21,7 @@ function sessionSecret(): string { /** * Keeps both tokens and the user in an encrypted, httpOnly cookie. With * `clientCredentials`, the browser can ask for the access token too, through - * the route handler in `app/api/auth/credentials`; the refresh token stays + * the session route in `app/api/session`; the refresh token stays * here. */ export const serverAuth = createServerAuth({ diff --git a/examples/react-router-framework-ssr/app/auth/client.ts b/examples/react-router-framework-ssr/app/auth/client.ts index f2ab864..5410bc0 100644 --- a/examples/react-router-framework-ssr/app/auth/client.ts +++ b/examples/react-router-framework-ssr/app/auth/client.ts @@ -1,47 +1,21 @@ -import { - createMirrorAuth, - type ClientCredentials, - type SessionOf, -} from "@monarcode/session-kit"; +import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit"; // Types only: erased from the browser's bundle. import type { serverAuth } from "./session.server"; export type AppSession = SessionOf; -/** Calls one of the resource routes in `routes/auth.*.ts`. */ -async function call(method: "GET" | "POST", path: string, body?: object) { - const response = await fetch(path, { - method, - ...(body && { - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }), - }); - if (!response.ok) throw new Error(`${path} failed (${response.status})`); - return (await response.json()) as T; -} - /** * The client the components use. It mirrors the session the server keeps in - * its cookie, starting from the one the root loader read. `useMirrorAuth` - * creates it, once per request on the server and once in the browser. + * its cookie, starting from the one the root loader read, and calls the + * session route in `routes/auth.session.ts`. `useMirrorAuth` creates it, + * once per request on the server and once in the browser. */ export function createAppAuth(session: AppSession | null) { return createMirrorAuth({ name: "session-kit-example", session, - revalidate: () => call("GET", "/auth/session"), - signOut: () => call("POST", "/auth/session"), - credentials: { - get: () => call("POST", "/auth/credentials"), - renew: (rejected) => - call( - "POST", - "/auth/credentials", - rejected, - ), - }, + endpoint: "/auth/session", }); } diff --git a/examples/react-router-framework-ssr/app/auth/session.server.ts b/examples/react-router-framework-ssr/app/auth/session.server.ts index e2e42e0..27ced94 100644 --- a/examples/react-router-framework-ssr/app/auth/session.server.ts +++ b/examples/react-router-framework-ssr/app/auth/session.server.ts @@ -23,7 +23,7 @@ function sessionSecret(): string { /** * Keeps both tokens and the user in an encrypted, httpOnly cookie. With * `clientCredentials`, the browser can ask for the access token too, through - * the resource route in `routes/auth.credentials.ts`; the refresh token stays + * the session route in `routes/auth.session.ts`; the refresh token stays * here. */ export const serverAuth = createServerAuth({ diff --git a/examples/react-router-framework-ssr/app/routes.ts b/examples/react-router-framework-ssr/app/routes.ts index 4a6f0db..9bf6255 100644 --- a/examples/react-router-framework-ssr/app/routes.ts +++ b/examples/react-router-framework-ssr/app/routes.ts @@ -8,7 +8,6 @@ import { export default [ route("login", "routes/login.tsx"), layout("routes/protected.tsx", [index("routes/home.tsx")]), - // Resource routes the browser's client calls. + // The session route the browser's client calls. route("auth/session", "routes/auth.session.ts"), - route("auth/credentials", "routes/auth.credentials.ts"), ] satisfies RouteConfig; diff --git a/examples/react-router-framework-ssr/app/routes/auth.credentials.ts b/examples/react-router-framework-ssr/app/routes/auth.credentials.ts deleted file mode 100644 index f7f5ff1..0000000 --- a/examples/react-router-framework-ssr/app/routes/auth.credentials.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { ActionFunctionArgs } from "react-router"; - -import { z } from "zod"; - -import { auth } from "../auth/session.server"; - -const rejected = z.object({ sessionId: z.string(), accessToken: z.string() }); - -/** - * The access token for the browser's own requests, never the refresh token: - * a POST with no body gets it, and one with the token DummyJSON rejected - * renews it. React Router checks no origin for resource routes: accept this - * site only. - */ -export async function action({ request, context }: ActionFunctionArgs) { - if (request.headers.get("sec-fetch-site") !== "same-origin") - return new Response(null, { status: 403 }); - const session = auth(context); - const body = rejected.safeParse(await request.json().catch(() => null)); - return Response.json( - body.success - ? await session.clientCredentials.renew(body.data) - : await session.clientCredentials.get(), - ); -} diff --git a/examples/react-router-framework-ssr/app/routes/auth.session.ts b/examples/react-router-framework-ssr/app/routes/auth.session.ts index 9f8be42..aa4efa8 100644 --- a/examples/react-router-framework-ssr/app/routes/auth.session.ts +++ b/examples/react-router-framework-ssr/app/routes/auth.session.ts @@ -1,19 +1,13 @@ -import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router"; +import { sessionRoute } from "@monarcode/session-kit/react-router/server"; -import { auth } from "../auth/session.server"; - -/** Who is signed in, from the cookie, for the client's `revalidate`. */ -export async function loader({ context }: LoaderFunctionArgs) { - return Response.json(await auth(context).getSession()); -} +import { serverAuth } from "../auth/session.server"; /** - * Signs out, for the client's `signOut`. React Router checks the origin of - * route actions, but not of resource routes': accept this site only. + * The session route the browser's client calls: it reads the session, signs + * out, and gets the access token. It answers this site's own pages only. */ -export async function action({ request, context }: ActionFunctionArgs) { - if (request.headers.get("sec-fetch-site") !== "same-origin") - return new Response(null, { status: 403 }); - await auth(context).signOut(); - return Response.json(null); -} +const route = sessionRoute(serverAuth); + +// One by one: React Router's build can't remove a destructured export. +export const loader = route.loader; +export const action = route.action; diff --git a/examples/tanstack-start-ssr/src/auth/client.ts b/examples/tanstack-start-ssr/src/auth/client.ts index 48d03eb..0417a9a 100644 --- a/examples/tanstack-start-ssr/src/auth/client.ts +++ b/examples/tanstack-start-ssr/src/auth/client.ts @@ -1,31 +1,22 @@ import { createMirrorAuth } from "@monarcode/session-kit"; -import { - getCredentialsFn, - getSessionFn, - renewCredentialsFn, - signInFn, - signOutFn, -} from "./functions"; +import { getSessionFn, signInFn } from "./functions"; /** * The client the routes and components use. It mirrors the session the * server keeps in its cookie: `loadSession` fills it on the server, and - * `connectSession` carries that to the browser. Create one per router: on - * the server, that is one per request. + * `connectSession` carries that to the browser. It signs out and gets the + * access token through the session route in `routes/api/session.ts`. Create + * one per router: on the server, that is one per request. */ export function createAppAuth() { return createMirrorAuth({ name: "session-kit-example", session: null, + endpoint: "/api/session", revalidate: () => getSessionFn(), signIn: (data: { username: string; password: string }) => signInFn({ data }), - signOut: () => signOutFn(), - credentials: { - get: () => getCredentialsFn(), - renew: (rejected) => renewCredentialsFn({ data: rejected }), - }, }); } diff --git a/examples/tanstack-start-ssr/src/auth/functions.ts b/examples/tanstack-start-ssr/src/auth/functions.ts index 32125ab..a47af66 100644 --- a/examples/tanstack-start-ssr/src/auth/functions.ts +++ b/examples/tanstack-start-ssr/src/auth/functions.ts @@ -8,7 +8,11 @@ import { session } from "./server"; // Each handler runs on the server; Start's compiler replaces it with a fetch // in the browser, and leaves `session` out of that bundle. -/** Who is signed in, from the cookie. Holds no tokens. */ +/** + * Who is signed in, from the cookie. Holds no tokens. The client's + * `revalidate`: `loadSession` calls it while Start renders on the server, + * where the client can't call the session route. + */ export const getSessionFn = createServerFn().handler(() => session.getSession(), ); @@ -20,21 +24,6 @@ export const signInFn = createServerFn({ method: "POST" }) session.signIn(await login(data.username, data.password)), ); -/** Clears the cookie. */ -export const signOutFn = createServerFn({ method: "POST" }).handler(() => - session.signOut(), -); - -/** The access token for the browser's own requests, never the refresh token. */ -export const getCredentialsFn = createServerFn({ method: "POST" }).handler(() => - session.clientCredentials.get(), -); - -/** New access after DummyJSON rejected the browser's token. */ -export const renewCredentialsFn = createServerFn({ method: "POST" }) - .validator(z.object({ sessionId: z.string(), accessToken: z.string() })) - .handler(({ data }) => session.clientCredentials.renew(data)); - /** Calls DummyJSON's `auth/me` from the server, with the cookie's token. */ export const getProfileFn = createServerFn().handler(async () => { const credentials = await session.credentials.get(); diff --git a/examples/tanstack-start-ssr/src/auth/server.ts b/examples/tanstack-start-ssr/src/auth/server.ts index aa942f8..ed0bc79 100644 --- a/examples/tanstack-start-ssr/src/auth/server.ts +++ b/examples/tanstack-start-ssr/src/auth/server.ts @@ -20,7 +20,7 @@ function sessionSecret(): string { /** * Keeps both tokens and the user in an encrypted, httpOnly cookie. With * `clientCredentials`, the browser can ask for the access token too, through - * the server functions in `functions.ts`; the refresh token stays here. + * the session route in `routes/api/session.ts`; the refresh token stays here. */ export const serverAuth = createServerAuth({ name: "session-kit-example", diff --git a/examples/tanstack-start-ssr/src/routes/api/session.ts b/examples/tanstack-start-ssr/src/routes/api/session.ts new file mode 100644 index 0000000..7dd014e --- /dev/null +++ b/examples/tanstack-start-ssr/src/routes/api/session.ts @@ -0,0 +1,13 @@ +import { sessionRoute } from "@monarcode/session-kit/tanstack-start/server"; +import { createFileRoute } from "@tanstack/react-router"; + +import { serverAuth } from "../../auth/server"; + +/** + * The session route the browser's client calls to sign out and get the + * access token. It answers this site's own pages only. Start keeps + * `server.handlers` out of the browser bundle, `serverAuth` included. + */ +export const Route = createFileRoute("/api/session")({ + server: { handlers: sessionRoute(serverAuth) }, +}); diff --git a/scripts/docs-pages.mjs b/scripts/docs-pages.mjs index 63a9885..f1dbcee 100644 --- a/scripts/docs-pages.mjs +++ b/scripts/docs-pages.mjs @@ -92,13 +92,22 @@ declare module "expo-crypto" { const START_ROUTE_TREE = ` import { Route as rootRoute } from "./routes/__root"; import { Route as authenticatedRouteImport } from "./routes/_authenticated"; +import { Route as apiSessionRouteImport } from "./routes/api/session"; const authenticatedRoute = authenticatedRouteImport.update({ id: "/_authenticated", getParentRoute: () => rootRoute, } as any); +const apiSessionRoute = apiSessionRouteImport.update({ + id: "/api/session", + path: "/api/session", + getParentRoute: () => rootRoute, +} as any); -export const routeTree = rootRoute.addChildren([authenticatedRoute]); +export const routeTree = rootRoute.addChildren([ + authenticatedRoute, + apiSessionRoute, +]); declare module "@tanstack/react-router" { interface FileRoutesByPath { @@ -109,6 +118,13 @@ declare module "@tanstack/react-router" { preLoaderRoute: typeof authenticatedRouteImport; parentRoute: typeof rootRoute; }; + "/api/session": { + id: "/api/session"; + path: "/api/session"; + fullPath: "/api/session"; + preLoaderRoute: typeof apiSessionRouteImport; + parentRoute: typeof rootRoute; + }; } } `; diff --git a/site/content/docs/(latest)/effect.mdx b/site/content/docs/(latest)/effect.mdx index 624b026..632ab5c 100644 --- a/site/content/docs/(latest)/effect.mdx +++ b/site/content/docs/(latest)/effect.mdx @@ -649,9 +649,9 @@ the mirror client. does, rather than inferring them from `requestLayer`. With a mirror registered, the registration depends on the server functions the mirror calls, which call `runRequest`, and TypeScript reports a circular type. For - the same reason, - the server functions the mirror is made from (its `revalidate`, `signIn` - and `signOut`) read the request's session directly, not `Auth.session`. + the same reason, the server functions the mirror is made from, such as its + `revalidate` and `signIn`, read the request's session directly, not + `Auth.session`. - **Keep a request's layer off a shared `memoMap`,** such as the runtime's or one passed to `QueryClient.make`. Layers are shared by identity there, so overlapping requests can get one build: a service that keeps `Auth` diff --git a/site/content/docs/(latest)/reference/core.mdx b/site/content/docs/(latest)/reference/core.mdx index e3364f8..ab60a40 100644 --- a/site/content/docs/(latest)/reference/core.mdx +++ b/site/content/docs/(latest)/reference/core.mdx @@ -159,7 +159,7 @@ The browser client that [`createMirrorAuth`](#createmirrorauth) returns. It mirr ### MirrorAuthOptions -Options for [`createMirrorAuth`](#createmirrorauth). Each function is your own server function, action, or `fetch` to a route handler, which calls `serverAuth` from `@monarcode/session-kit/server`. +Options for [`createMirrorAuth`](#createmirrorauth). The client talks to your server through `endpoint`, your session route, or through functions of your own, such as server functions, which call `serverAuth` from `@monarcode/session-kit/server`. Pass `endpoint`, or `revalidate` and `signOut`. +### NextSessionRoute + +The Route Handlers [`sessionRoute`](#sessionroute) makes, for `GET` and `POST`. + ### ProxyRequest The request [`proxyJar`](#proxyjar) reads cookies from. A `NextRequest` fits. diff --git a/site/content/docs/(latest)/reference/react-router-server.mdx b/site/content/docs/(latest)/reference/react-router-server.mdx index 85e0d08..ece8586 100644 --- a/site/content/docs/(latest)/reference/react-router-server.mdx +++ b/site/content/docs/(latest)/reference/react-router-server.mdx @@ -35,6 +35,10 @@ The `CookieJar` for the request React Router is handling, to pass to `serverAuth The root route's server middleware, which gives each request a cookie jar and refreshes the session while the response can still set the cookie. Export it as the root route's `middleware`, or spread it first into a list of your own. +### sessionRoute + +Makes the loader and action of your session route, a resource route that answers `createMirrorAuth`'s `endpoint`: the browser client reads the session, signs out and gets the access token through it. It needs [`sessionMiddleware`](#sessionmiddleware) in the root route. + ## Types ### RouterArgs @@ -53,6 +57,10 @@ A loader typed by its shape, such as [`redirectIfSignedIn`](#redirectifsignedin) Server middleware for a route's `middleware`, typed by its shape. +### RouterSessionRoute + +The loader and action [`sessionRoute`](#sessionroute) makes, for a resource route. + ### SessionGuard Server middleware that lets only signed-in users through, made by [`requireSession`](#requiresession). Call `session(context)` in the loaders and actions it guards for the session, which is never `null` there. diff --git a/site/content/docs/(latest)/reference/server.mdx b/site/content/docs/(latest)/reference/server.mdx index 558abc2..1704fbf 100644 --- a/site/content/docs/(latest)/reference/server.mdx +++ b/site/content/docs/(latest)/reference/server.mdx @@ -15,6 +15,10 @@ Guide: [Server sessions](/docs/server-rendering/server-sessions). Creates the server side of Session kit ([`ServerAuth`](#serverauth)). It keeps both tokens and the user in an encrypted, `httpOnly` cookie, so page scripts never see the refresh token. +### sessionHandler + +Makes the handler for your session route ([`SessionHandler`](#sessionhandler)), which answers `createMirrorAuth`'s `endpoint`. A `GET` reads the session. A `POST` signs out, or gets or renews the access token for page scripts. + ## Types ### ClientCredentials @@ -79,6 +83,10 @@ The session cookie's attributes: the `cookie` option of [`ServerAuthOptions`](#s name="SessionCookieOptions" /> +### SessionHandler + +Answers the browser client's requests to your session route, for one request and its cookie jar. [`sessionHandler`](#sessionhandler) makes one. + ### SessionMiddlewareOptions Options for the middleware that refreshes before each request: `refreshSession` from `@monarcode/session-kit/tanstack-start/server` and `sessionMiddleware` from `@monarcode/session-kit/react-router/server`. diff --git a/site/content/docs/(latest)/reference/tanstack-start-server.mdx b/site/content/docs/(latest)/reference/tanstack-start-server.mdx index 9786ce3..a3d7bb4 100644 --- a/site/content/docs/(latest)/reference/tanstack-start-server.mdx +++ b/site/content/docs/(latest)/reference/tanstack-start-server.mdx @@ -15,6 +15,10 @@ Guide: [TanStack Start](/docs/setups/tanstack-start). Refreshes the session before each request, while the response can still set the cookie. Pass it to Start's `createMiddleware().server()`, and list that middleware in `requestMiddleware` in `src/start.ts`. +### sessionRoute + +Makes the handlers of your session route, a server route that answers `createMirrorAuth`'s `endpoint`: the browser client signs out and gets the access token through it. Pass them as the route's `server.handlers`. + ### startAuth The session of the request TanStack Start is handling (`RequestAuth`), with every `serverAuth` method and no cookie jar. Each call finds the current request, so make it once, at module level, beside `serverAuth`. @@ -22,3 +26,9 @@ The session of the request TanStack Start is handling (`RequestAuth`), with ever ### startJar The `CookieJar` for the request TanStack Start is handling, to pass to `serverAuth` from `@monarcode/session-kit/server`. [`startAuth`](#startauth) passes it for you. Use it in a server function, request middleware, a server route, or `beforeLoad` and loaders while they run on the server. Every call during one request returns the same jar. + +## Types + +### StartSessionRoute + +The handlers [`sessionRoute`](#sessionroute) makes, for a server route's `GET` and `POST`. diff --git a/site/content/docs/(latest)/security.mdx b/site/content/docs/(latest)/security.mdx index 145ea1a..c85529d 100644 --- a/site/content/docs/(latest)/security.mdx +++ b/site/content/docs/(latest)/security.mdx @@ -32,6 +32,23 @@ Each setup saves the tokens in a different place: backups with the `expo-secure-store` config plugin. It also removes a session that an earlier install left in the iOS keychain. +## The session route + +With server rendering, the browser's client reads the session, signs out and +gets the access token through your session route. `sessionHandler` from +`@monarcode/session-kit/server` answers it, through each framework's +`sessionRoute`. + +It answers your own site's pages only, so another site can't sign the user +out or ask for the access token. It checks the `Sec-Fetch-Site` header, +which browsers send to https and localhost pages since 2023 (Safari 16.4). +On plain http, such as a phone testing your dev server, a `POST` needs an +`Origin` header that matches the request's URL. Anything else is refused +with 403. Every answer has `Cache-Control: no-store`. + +Signing in stays your own server code. A route of your own that changes the +session must refuse other sites too, where the framework doesn't check. + ## Where tokens go [`authFetch`](/docs/client/requests) and the effetch plugin diff --git a/site/content/docs/(latest)/server-rendering/index.mdx b/site/content/docs/(latest)/server-rendering/index.mdx index 09b0934..3c447ff 100644 --- a/site/content/docs/(latest)/server-rendering/index.mdx +++ b/site/content/docs/(latest)/server-rendering/index.mdx @@ -31,7 +31,8 @@ before rendering, so pages never show a "Checking session…" state. The engine is the same `createServerAuth` call in every framework: [Create the server engine](/docs/setups/tanstack-start#1-create-the-server-engine) on the TanStack Start page shows one. The browser's client mirrors what the -server rendered, and asks the server to sign in and out through your own +server rendered. It reads the session and signs out through a session route, +which each adapter's `sessionRoute` makes, and signs in through your own server code, as in [Create the browser client](/docs/setups/tanstack-start#4-create-the-browser-client). @@ -48,7 +49,8 @@ session, and how the session reaches the browser: Locking isn't available with server rendering. For another server, such as the Next.js Pages Router, build a `CookieJar` over its cookies and pass it -to `serverAuth.forRequest(jar)`. +to `serverAuth.forRequest(jar)`. Its session route is `sessionHandler`, from +`@monarcode/session-kit/server`, called with the request and that jar. ## Next steps diff --git a/site/content/docs/(latest)/server-rendering/server-sessions.mdx b/site/content/docs/(latest)/server-rendering/server-sessions.mdx index 8fc3310..6a53ce8 100644 --- a/site/content/docs/(latest)/server-rendering/server-sessions.mdx +++ b/site/content/docs/(latest)/server-rendering/server-sessions.mdx @@ -123,15 +123,14 @@ revocation. Server code calls your API with a request's `credentials`. To call it from the browser too, with `createAuthFetch` or effetch's `sessionBearer`, opt in -with `clientCredentials: true` and expose a request's `clientCredentials.get` -and `.renew` through your own same-origin endpoint, passed to -`createMirrorAuth` as `credentials`. Page scripts then hold the access token in memory, never the -refresh token, so a script injected into the page can use the API while the -page is open, as it could with any token the browser holds. - -Accept requests to that endpoint from your own site only. Where the framework -doesn't check, compare `Sec-Fetch-Site` to `same-origin`: browsers send it -since 2023 (Safari 16.4), and older ones are refused. +with `clientCredentials: true`. The session route then serves the access +token, and the browser's client gets it there. Page scripts hold the access +token in memory, never the refresh token, so a script injected into the page +can use the API while the page is open, as it could with any token the +browser holds. + +The session route answers your own site's pages only: see +[The session route](/docs/security#the-session-route). ## Limits diff --git a/site/content/docs/(latest)/setups/next.mdx b/site/content/docs/(latest)/setups/next.mdx index 5d30060..15bf0b3 100644 --- a/site/content/docs/(latest)/setups/next.mdx +++ b/site/content/docs/(latest)/setups/next.mdx @@ -4,8 +4,8 @@ description: Keep the session in an encrypted cookie with the Next.js App Router --- In this guide, you keep the session in an encrypted cookie with the Next.js -App Router. Server Functions sign in and out, Proxy refreshes the tokens, and -Server Components read the session. The first response already shows the +App Router. A Server Function signs in, a session route answers the browser, +Proxy refreshes the tokens, and Server Components read the session. The first response already shows the signed-in page, so the browser never shows a "Checking session…" state or a flash of signed-out content. Client Components get a small client that mirrors the session, and the @@ -135,11 +135,27 @@ If the refresh fails, the page still renders with the cookie as it is. Server Functions are POST requests to the page that calls them, so keep the matcher wide enough to include those pages. -## 4. Add Server Functions +## 4. Add the session route and sign-in -Server Functions set cookies, so they use `session.writable()`, the -request's session with every `serverAuth` method. They decide what the -browser may ask for: +The browser's client reads the session and signs out through a session +route. `sessionRoute` from `@monarcode/session-kit/next` makes its `GET` and +`POST` handlers. Pass it Next's `cookies`: + +```ts title="app/api/session/route.ts" +import { sessionRoute } from "@monarcode/session-kit/next"; +import { cookies } from "next/headers"; + +import { serverAuth } from "../../../lib/auth/server"; + +export const { GET, POST } = sessionRoute(serverAuth, cookies); +``` + +It answers your own site's pages only, so another site can't sign the user +out: see [Security](/docs/security). + +Signing in is yours, as it takes your form's input. A Server Function sets +the cookie with `session.writable()`, the request's session with every +`serverAuth` method: ```ts title="app/actions.ts" "use server"; @@ -149,10 +165,6 @@ import { z } from "zod"; import { login } from "../lib/auth/server"; import { session } from "../lib/auth/session"; -export async function getSessionAction() { - return (await session.writable()).getSession(); -} - const credentials = z.object({ username: z.string(), password: z.string() }); export async function signInAction(input: unknown) { @@ -169,10 +181,6 @@ export async function signInAction(input: unknown) { }; } } - -export async function signOutAction() { - await (await session.writable()).signOut(); -} ``` `signInAction` returns its failure rather than throwing it, as Next advises @@ -182,16 +190,12 @@ the browser. ## 5. Create the browser client `createMirrorAuth` makes the client that Client Components use, from the -session the layout read and your Server Functions: +session the layout read, the session route and your sign-in: ```ts title="lib/auth/client.ts" import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit"; -import { - getSessionAction, - signInAction, - signOutAction, -} from "../../app/actions"; +import { signInAction } from "../../app/actions"; // Types only: left out of the browser's bundle. import type { serverAuth } from "./server"; @@ -201,13 +205,12 @@ export function createAppAuth(session: AppSession | null) { return createMirrorAuth({ name: "app", session, - revalidate: getSessionAction, + endpoint: "/api/session", signIn: async (input: { username: string; password: string }) => { const result = await signInAction(input); if ("error" in result) throw new Error(result.error); return result.session; }, - signOut: signOutAction, }); } @@ -399,31 +402,8 @@ In Server Functions and Route Handlers, `session.writable()` can also To call the API from the browser too, with `createAuthFetch` or effetch's `sessionBearer`, opt in with `clientCredentials: true` in `createServerAuth`. -Expose the request's `clientCredentials.get` and `.renew` through a Route -Handler, and pass them as the client's `credentials`. A Route Handler rather -than a Server Function, because Next dispatches Server Functions one at a -time and renders the page again after one sets a cookie. Next doesn't check -where a Route Handler's requests come from, so accept your own site only: - -```ts title="app/api/auth/credentials/route.ts" -import { z } from "zod"; - -import { session } from "../../../../lib/auth/session"; - -const rejected = z.object({ sessionId: z.string(), accessToken: z.string() }); - -export async function POST(request: Request) { - if (request.headers.get("sec-fetch-site") !== "same-origin") - return new Response(null, { status: 403 }); - const auth = await session.writable(); - const body = rejected.safeParse(await request.json().catch(() => null)); - return Response.json( - body.success - ? await auth.clientCredentials.renew(body.data) - : await auth.clientCredentials.get(), - ); -} -``` +The session route then serves the access token, and the client's +`credentials` get it there. The browser keeps the access token in memory, never the refresh token; see [Server sessions](/docs/server-rendering/server-sessions#the-access-token-in-the-browser). @@ -444,6 +424,8 @@ The example app does this. on one server: they share no refresh. A matcher that covers every route that reads the session lets Proxy refresh first, so Route Handlers and Server Functions rarely need to. +- **A `basePath`.** Next doesn't add it to `fetch`, so the client's + `endpoint` includes it: `"/app/api/session"`. - **Rendering.** Reading cookies makes a page dynamic. Next sends such pages with `Cache-Control: no-store`, and plain `use cache` can't read cookies. Keep pages that read the session on the Node.js runtime, the default: diff --git a/site/content/docs/(latest)/setups/react-router-ssr.mdx b/site/content/docs/(latest)/setups/react-router-ssr.mdx index e9b8a86..04c99f1 100644 --- a/site/content/docs/(latest)/setups/react-router-ssr.mdx +++ b/site/content/docs/(latest)/setups/react-router-ssr.mdx @@ -127,7 +127,7 @@ refresh doesn't fail the request. Loaders read the session as usual, and an error there reaches the route's error boundary. `createMirrorAuth` makes the client that components use, from the session -the root loader read and the resource route that step 3 adds: +the root loader read and the session route that step 3 adds: ```ts title="app/auth/client.ts" import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit"; @@ -137,18 +137,11 @@ import type { serverAuth } from "./session.server"; export type AppSession = SessionOf; -async function session(method: "GET" | "POST") { - const response = await fetch("/auth/session", { method }); - if (!response.ok) throw new Error(`Session failed (${response.status})`); - return (await response.json()) as AppSession | null; -} - -export function createAppAuth(initial: AppSession | null) { +export function createAppAuth(session: AppSession | null) { return createMirrorAuth({ name: "app", - session: initial, - revalidate: () => session("GET"), - signOut: () => session("POST"), + session, + endpoint: "/auth/session", }); } @@ -292,28 +285,26 @@ export default function Login() { } ``` -A resource route gives the browser's client the session and signs out. React -Router doesn't check where resource routes' requests come from, so its action -accepts your own site only: +The browser's client reads the session and signs out through a session +route, a resource route. `sessionRoute` from +`@monarcode/session-kit/react-router/server` makes its loader and action: ```ts title="app/routes/auth.session.ts" -import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router"; +import { sessionRoute } from "@monarcode/session-kit/react-router/server"; -import { auth } from "../auth/session.server"; +import { serverAuth } from "../auth/session.server"; -export async function loader({ context }: LoaderFunctionArgs) { - return Response.json(await auth(context).getSession()); -} +const route = sessionRoute(serverAuth); -export async function action({ request, context }: ActionFunctionArgs) { - if (request.headers.get("sec-fetch-site") !== "same-origin") - return new Response(null, { status: 403 }); - await auth(context).signOut(); - return Response.json(null); -} +export const loader = route.loader; +export const action = route.action; ``` Add it to `app/routes.ts` as `route("auth/session", "routes/auth.session.ts")`. +Export the loader and action one by one, as above. React Router's build fails +on a destructured `export const { loader, action }`. The route answers your +own site's pages only, so another site can't sign the user out: see +[Security](/docs/security). ## 4. Protect routes @@ -400,34 +391,9 @@ export default function Orders() { To call the API from the browser too, with `createAuthFetch` or effetch's `sessionBearer`, opt in with `clientCredentials: true` in `createServerAuth`. -Expose the request's `clientCredentials.get` and `.renew` through a resource -route, added as `route("auth/credentials", "routes/auth.credentials.ts")`: - -```ts title="app/routes/auth.credentials.ts" -import type { ActionFunctionArgs } from "react-router"; - -import { z } from "zod"; - -import { auth } from "../auth/session.server"; - -const rejected = z.object({ sessionId: z.string(), accessToken: z.string() }); - -export async function action({ request, context }: ActionFunctionArgs) { - if (request.headers.get("sec-fetch-site") !== "same-origin") - return new Response(null, { status: 403 }); - const session = auth(context); - const body = rejected.safeParse(await request.json().catch(() => null)); - return Response.json( - body.success - ? await session.clientCredentials.renew(body.data) - : await session.clientCredentials.get(), - ); -} -``` - -Then pass the client a `credentials` option: `get` posts to the route with -no body, and `renew` posts the rejected token. The browser keeps the access -token in memory, never the refresh token; see +The session route then serves the access token, and the client's +`credentials` get it there. The browser keeps the access token in memory, +never the refresh token; see [Server sessions](/docs/server-rendering/server-sessions#the-access-token-in-the-browser). The example app does this. @@ -447,7 +413,8 @@ The example app does this. - **A `basename`.** Pass it to the guard too, as `requireSession(serverAuth, { basename: "/app" })`. React Router adds it to loaders' and actions' redirects, but not to middleware's, so the guard adds - it to its own. + it to its own. The client's `endpoint` includes it as well: + `"/app/auth/session"`. - **Tabs.** Signing in or out in one tab reaches the others, which ask the server again and run their loaders again. So does returning to a tab after a while. diff --git a/site/content/docs/(latest)/setups/tanstack-start.mdx b/site/content/docs/(latest)/setups/tanstack-start.mdx index c67e648..26a6b6a 100644 --- a/site/content/docs/(latest)/setups/tanstack-start.mdx +++ b/site/content/docs/(latest)/setups/tanstack-start.mdx @@ -95,10 +95,32 @@ export async function login(username: string, password: string) { its other options, rotating the secret, signing out, and the limits every setup shares. -## 2. Add server functions +## 2. Add the session route and server functions -`session` finds the request each time it's called, so one object serves -every request. Your server functions decide what the browser may ask for: +The browser's client signs out and gets the access token through a session +route. `sessionRoute` from `@monarcode/session-kit/tanstack-start/server` +makes its `GET` and `POST` handlers, for a server route. Start leaves +`server.handlers` out of the browser bundle, `serverAuth` included: + +```ts title="src/routes/api/session.ts" +import { sessionRoute } from "@monarcode/session-kit/tanstack-start/server"; +import { createFileRoute } from "@tanstack/react-router"; + +import { serverAuth } from "../../auth/server"; + +export const Route = createFileRoute("/api/session")({ + server: { handlers: sessionRoute(serverAuth) }, +}); +``` + +It answers your own site's pages only, so another site can't sign the user +out: see [Security](/docs/security). + +Two server functions do the rest. Signing in takes your form's input. Reading +the session is a server function too, because `loadSession` reads it while +Start renders on the server, where the client can't call a route on its own +site. `session` finds the request each time it's called, so one object +serves every request: ```ts title="src/auth/functions.ts" import { createServerFn } from "@tanstack/react-start"; @@ -115,10 +137,6 @@ export const signInFn = createServerFn({ method: "POST" }) .handler(async ({ data }) => session.signIn(await login(data.username, data.password)), ); - -export const signOutFn = createServerFn({ method: "POST" }).handler(() => - session.signOut(), -); ``` `getSession` and `signIn` resolve `{ sessionId, user }`, never tokens, so @@ -169,9 +187,10 @@ usual, and an error there reaches the route's error component. An app that defines `createStart` has no CSRF protection for its server functions until it adds `createCsrfMiddleware`. Its `filter` keeps the check to server-function calls: unfiltered, it also refuses page loads from links -on other sites and from the address bar. Server routes are left out too, so -a server route that changes the session must refuse other sites itself: -compare its `Sec-Fetch-Site` header to `same-origin`. +on other sites and from the address bar. Server routes are left out too. +`sessionRoute` refuses other sites itself. A server route of your own that +changes the session must do the same: compare its `Sec-Fetch-Site` header to +`same-origin`. ## 4. Create the browser client @@ -186,16 +205,16 @@ First, the client: ```ts title="src/auth/client.ts" import { createMirrorAuth } from "@monarcode/session-kit"; -import { getSessionFn, signInFn, signOutFn } from "./functions"; +import { getSessionFn, signInFn } from "./functions"; export function createAppAuth() { return createMirrorAuth({ name: "app", session: null, // filled by loadSession, then by hydration + endpoint: "/api/session", revalidate: () => getSessionFn(), signIn: (data: { username: string; password: string }) => signInFn({ data }), - signOut: () => signOutFn(), }); } @@ -332,10 +351,9 @@ export const getOrdersFn = createServerFn().handler(async () => { To call the API from the browser too, with `createAuthFetch` or effetch's `sessionBearer`, opt in with `clientCredentials: true` in `createServerAuth`. -Expose `session.clientCredentials.get` and `.renew` through two POST server -functions, and pass them as the client's `credentials`. The browser then -keeps the access token in memory, never the refresh token. The example app -does this. +The session route then serves the access token, and the client's +`credentials` get it there. The browser keeps the access token in memory, +never the refresh token. The example app does this. ## Things to know diff --git a/src/core/endpoint.ts b/src/core/endpoint.ts new file mode 100644 index 0000000..bbadaad --- /dev/null +++ b/src/core/endpoint.ts @@ -0,0 +1,123 @@ +import { AuthError, type AuthErrorCode } from "./errors.js"; +import { isRecord } from "./json.js"; +import type { ClientCredentials, MirrorCredentials } from "./mirror.js"; + +// What passes between `sessionHandler` on the server and `createMirrorAuth`'s +// `endpoint` in the browser. Both ship in this package, so only a page loaded +// before a deploy can send an older version, and the server refuses it. + +/** The format's version, in every request body and every response. */ +export const ENDPOINT_VERSION = 1; + +/** What a `POST` asks for. A `GET` reads the session. */ +export type EndpointAction = "signOut" | "credentials" | "renew"; + +const CODES = { + USER_VALIDATION_FAILED: true, + INVALID_SESSION: true, + PERSISTENCE_FAILED: true, + REFRESH_FAILED: true, + REVOKE_FAILED: true, + SESSION_CHANGED: true, + UNAUTHENTICATED: true, + LOCKED: true, + UNLOCK_FAILED: true, + INVALID_OPTIONS: true, +} satisfies Record; + +const isCode = (value: unknown): value is AuthErrorCode => + typeof value === "string" && + Object.prototype.hasOwnProperty.call(CODES, value); + +/** Checks `createMirrorAuth`'s `endpoint`: a path on this site. */ +export function isEndpoint(value: unknown): value is string { + return ( + typeof value === "string" && + value.startsWith("/") && + !value.startsWith("//") && + // URL parsing drops tabs and newlines and reads `\` as `/`, so + // `/\t/evil.test` would lead to another site. + // oxlint-disable-next-line no-control-regex + !/[\\\u0000- \u007f]/.test(value) + ); +} + +/** The endpoint's URL on the page's own site. */ +function urlOf(endpoint: string): URL { + // A relative fetch has nothing to resolve against on the server. + if (typeof location === "undefined") + throw new AuthError( + "INVALID_OPTIONS", + "endpoint is called from the browser only: pass revalidate, signOut or credentials for calls on the server", + ); + const url = new URL(endpoint, location.href); + if (url.origin !== location.origin) + throw new AuthError( + "INVALID_OPTIONS", + `endpoint must be a path on this site: ${endpoint}`, + ); + return url; +} + +/** + * Calls the endpoint and returns its answer. A failure the server reports + * rejects with the server's code, and anything else with a plain error, which + * the mirror wraps as it wraps the app's own functions' failures. + */ +async function call( + endpoint: string, + action?: EndpointAction, + extra?: object, +): Promise> { + const response = await fetch(urlOf(endpoint), { + method: action ? "POST" : "GET", + credentials: "same-origin", + cache: "no-store", + ...(action && { + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ v: ENDPOINT_VERSION, action, ...extra }), + }), + }); + const body: unknown = await response.json().catch(() => undefined); + if (!isRecord(body) || body.v !== ENDPOINT_VERSION) + throw new Error( + `${endpoint} answered ${response.status} without a session-kit response: is it the session route?`, + ); + if (!response.ok) { + const error = isRecord(body.error) ? body.error : {}; + const message = + typeof error.message === "string" + ? error.message + : `${endpoint} answered ${response.status}`; + throw isCode(error.code) + ? new AuthError(error.code, message) + : new Error(message); + } + return body; +} + +/** The mirror's `revalidate`, `signOut` and `credentials`, over `endpoint`. */ +export function endpointTransport(endpoint: string): { + revalidate: () => Promise; + signOut: () => Promise; + credentials: MirrorCredentials; +} { + return { + revalidate: async () => (await call(endpoint)).session, + signOut: () => call(endpoint, "signOut"), + credentials: { + get: async () => + (await call(endpoint, "credentials")) + .credentials as ClientCredentials | null, + renew: async (rejected) => + ( + await call(endpoint, "renew", { + rejected: { + sessionId: rejected.sessionId, + accessToken: rejected.accessToken, + }, + }) + ).credentials as ClientCredentials | null, + }, + }; +} diff --git a/src/core/mirror.ts b/src/core/mirror.ts index c7a5706..ba906bc 100644 --- a/src/core/mirror.ts +++ b/src/core/mirror.ts @@ -1,6 +1,7 @@ import { atom } from "nanostores"; import { createDebugger, registerDebugger, type AuthDebug } from "./debug.js"; +import { endpointTransport, isEndpoint } from "./endpoint.js"; import { AuthError, sessionChanged, toAuthError } from "./errors.js"; import { isAuthName } from "./persistence.js"; import { countMounts, inBackground, stateView } from "./store.js"; @@ -78,9 +79,11 @@ export type MirrorCredentials = { }; /** - * Options for {@link createMirrorAuth}. Each function is your own server - * function, action, or `fetch` to a route handler, which calls `serverAuth` - * from `@monarcode/session-kit/server`. + * Options for {@link createMirrorAuth}. The client talks to your server + * through `endpoint`, your session route, or through functions of your own, + * such as server functions, which call `serverAuth` from + * `@monarcode/session-kit/server`. Pass `endpoint`, or `revalidate` and + * `signOut`. * * @example * ```ts @@ -88,14 +91,11 @@ export type MirrorCredentials = { * * type User = { id: number; firstName: string }; * declare const session: Session | null; - * declare function getSessionFn(): Promise | null>; - * declare function signOutFn(): Promise; * * export const options: MirrorAuthOptions = { * name: "app", * session, - * revalidate: () => getSessionFn(), - * signOut: () => signOutFn(), + * endpoint: "/api/session", * }; * ``` * @@ -113,10 +113,28 @@ export type MirrorAuthOptions = { * `null`. The client starts from it, so there's no loading state. */ session: Session | null; - /** Reads the session on the server again, with `serverAuth.getSession`. */ - revalidate: () => Promise | null>; - /** Signs out on the server, with `serverAuth.signOut`. */ - signOut: () => Promise; + /** + * The path of your session route on this site, such as `"/api/session"`, + * which answers with `sessionRoute` or `sessionHandler` from the server + * entry points. The client reads the session, signs out and gets the + * access token through it. `revalidate`, `signOut` and `credentials` win + * when you pass them too. + * + * It's the full path, with your app's base path, such as React Router's + * `basename` or Next's `basePath`. It's called from the browser only: on + * the server, a call through it rejects with `INVALID_OPTIONS`. + */ + endpoint?: string | undefined; + /** + * Reads the session on the server again, with `serverAuth.getSession`. + * Default: a `GET` to `endpoint`. + */ + revalidate?: (() => Promise | null>) | undefined; + /** + * Signs out on the server, with `serverAuth.signOut`. Default: through + * `endpoint`. + */ + signOut?: (() => Promise) | undefined; /** * Signs in on the server with `input`, and resolves the new session. Use * `serverAuth.signIn`, or your own sign-in that ends with it. Without this @@ -127,13 +145,25 @@ export type MirrorAuthOptions = { /** * Gets the access token from your server ({@link MirrorCredentials}), so * page scripts can call your API with `createAuthFetch` or `sessionBearer`. - * Leave it out if they never do. `credentials.get()` and - * `credentials.renew()` then reject with `INVALID_OPTIONS`. + * Default: through `endpoint`, which serves it when `createServerAuth` + * has `clientCredentials`. Without either, `credentials.get()` and + * `credentials.renew()` reject with `INVALID_OPTIONS`. */ credentials?: MirrorCredentials | undefined; /** Logs what the client does, like `createAuth`'s `debug`. */ debug?: AuthDebug | undefined; -}; +} & ( + | { + /** Required unless you pass `revalidate` and `signOut`. */ + endpoint: string; + } + | { + /** Required without `endpoint`. */ + revalidate: () => Promise | null>; + /** Required without `endpoint`. */ + signOut: () => Promise; + } +); type MirrorAuthBase = { /** @@ -156,9 +186,10 @@ type MirrorAuthBase = { */ getSession: () => Promise | null>; /** - * Asks your server for the session again, with `revalidate`, and resolves - * it. If that fails, it rejects with `REFRESH_FAILED` and keeps the - * current session. + * Asks your server for the session again, with `revalidate` or + * `endpoint`, and resolves it. If that fails, it rejects and keeps the + * current session. The code is `REFRESH_FAILED`, or the session route's + * own code, such as `INVALID_OPTIONS` for a request it refused. */ retry: () => Promise | null>; /** @@ -174,8 +205,8 @@ type MirrorAuthBase = { isCurrent: (session: { sessionId: string }) => boolean; /** * Signs out on your server, then in this tab and the others. If the - * server's sign-out fails, it rejects with `PERSISTENCE_FAILED` and keeps - * the session. + * server's sign-out fails, it rejects and keeps the session. The code is + * `PERSISTENCE_FAILED`, or the session route's own code. */ signOut: () => Promise; /** @@ -195,20 +226,23 @@ type MirrorAuthBase = { mount: () => () => void; /** * The access token ({@link Credentials}), for `createAuthFetch` and - * `sessionBearer`. Needs the `credentials` option. The token is kept in + * `sessionBearer`. Needs `endpoint` or the `credentials` option, or + * `get` and `renew` reject with `INVALID_OPTIONS`. The token is kept in * memory only, and fetched again shortly before it expires. */ credentials: { /** * Resolves the current access token, or `null` when signed out. Calls * that overlap share one request. Rejects with `REFRESH_FAILED` when - * your server's function fails. + * your server fails, or with the session route's own code, such as + * `INVALID_OPTIONS` without `clientCredentials`. */ get: () => Promise; /** * Asks your server for a new access token after your API rejected * `credentials`. Calls that overlap share one request. Resolves `null` - * when the server has signed out. + * when the server has signed out. Rejects with `SESSION_CHANGED` when + * the server holds another account, and follows it. */ renew: (credentials: Credentials) => Promise; /** @@ -360,15 +394,28 @@ function stateOf( export function createMirrorAuth( options: MirrorAuthOptions, ): MirrorAuth { + if (options.endpoint !== undefined && !isEndpoint(options.endpoint)) + throw new AuthError( + "INVALID_OPTIONS", + `endpoint must be a path on this site, starting with "/": ${String(options.endpoint)}`, + ); + const endpoint = + options.endpoint === undefined + ? undefined + : endpointTransport(options.endpoint); + const readServer = options.revalidate ?? endpoint?.revalidate; + const endServer = options.signOut ?? endpoint?.signOut; + const credentialsSource = options.credentials ?? endpoint?.credentials; if ( !isAuthName(options.name) || - typeof options.revalidate !== "function" || - typeof options.signOut !== "function" + typeof readServer !== "function" || + typeof endServer !== "function" ) throw new AuthError( "INVALID_OPTIONS", - "Pass a simple name, and revalidate and signOut functions", + "Pass a simple name, and an endpoint or revalidate and signOut functions", ); + const server = { revalidate: readServer, signOut: endServer }; const debug = createDebugger(options.name, options.debug); let session = readSession(options.session); const store = atom>(stateOf(session, null, 0)); @@ -466,7 +513,7 @@ export function createMirrorAuth( debug.log("sync", `revalidating (${reason})`); const promise = (async () => { try { - const next = readSession(await options.revalidate()); + const next = readSession(await server.revalidate()); checkedAt = Date.now(); answered = true; if (generation === started) follow(next); @@ -495,7 +542,7 @@ export function createMirrorAuth( async function signOut() { const ending = session?.sessionId ?? null; try { - await options.signOut(); + await server.signOut(); } catch (cause) { const error = toAuthError( "PERSISTENCE_FAILED", @@ -511,12 +558,12 @@ export function createMirrorAuth( } function requireCredentials(): MirrorCredentials { - if (!options.credentials) + if (!credentialsSource) throw new AuthError( "INVALID_OPTIONS", - "Pass credentials to createMirrorAuth to read the access token in the browser", + "Pass endpoint or credentials to createMirrorAuth to read the access token in the browser", ); - return options.credentials; + return credentialsSource; } /** Asks the server for credentials for session `sessionId`. */ @@ -530,6 +577,15 @@ export function createMirrorAuth( try { value = await ask(); } catch (cause) { + if ( + cause instanceof AuthError && + cause.code === "SESSION_CHANGED" && + session?.sessionId === sessionId + ) { + // The server holds another session: follow it. + cached = undefined; + inBackground(revalidate("another session on the server")); + } throw toAuthError( "REFRESH_FAILED", "Could not get the access token from the server", diff --git a/src/next/index.ts b/src/next/index.ts index e7720f3..bb0d95c 100644 --- a/src/next/index.ts +++ b/src/next/index.ts @@ -12,6 +12,7 @@ import { type CookieJar, type CookieOptions, } from "../server/cookies.js"; +import { handleSession } from "../server/handler.js"; /** * A request's cookie store, as `cookies()` from `next/headers` resolves it. @@ -399,3 +400,62 @@ export function nextSession( }, }; } + +/** + * The Route Handlers {@link sessionRoute} makes, for `GET` and `POST`. + * + * @example + * ```ts + * import type { NextSessionRoute } from "@monarcode/session-kit/next"; + * + * declare const route: NextSessionRoute; + * + * export const { GET, POST } = route; + * ``` + * + * @since 0.1.0 + */ +export type NextSessionRoute = { + GET: (request: Request) => Promise; + POST: (request: Request) => Promise; +}; + +/** + * Makes the Route Handlers for your session route, which answers + * `createMirrorAuth`'s `endpoint`: the browser client reads the session, + * signs out and gets the access token through it. Pass `cookies` from + * `next/headers`. + * + * It answers this site's own pages only, as `sessionHandler` from + * `@monarcode/session-kit/server` explains, and serves the access token only + * when `createServerAuth` has `clientCredentials`. Sign-in stays your own + * Server Function. + * + * @example + * ```ts + * import { sessionRoute } from "@monarcode/session-kit/next"; + * import type { ServerAuth } from "@monarcode/session-kit/server"; + * import { cookies } from "next/headers"; + * + * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; + * + * // app/api/session/route.ts + * export const { GET, POST } = sessionRoute(serverAuth, cookies); + * ``` + * + * @since 0.1.0 + */ +export function sessionRoute( + serverAuth: ServerAuth, + cookies: () => Promise, +): NextSessionRoute { + if (typeof cookies !== "function") + throw new AuthError( + "INVALID_OPTIONS", + "Pass cookies from next/headers to sessionRoute", + ); + const handle = handleSession(serverAuth); + const route = (request: Request) => + handle(request, async () => nextJar(await cookies(), { writable: true })); + return { GET: route, POST: route }; +} diff --git a/src/react-router/server.ts b/src/react-router/server.ts index 42427b5..5ee2a84 100644 --- a/src/react-router/server.ts +++ b/src/react-router/server.ts @@ -13,6 +13,7 @@ import { type SessionMiddlewareOptions, } from "../server/auth.js"; import type { CookieJar } from "../server/cookies.js"; +import { handleSession } from "../server/handler.js"; import { requestJar, withHeaders, @@ -514,3 +515,65 @@ export function redirectIfSignedIn( return null; }; } + +/** + * The loader and action {@link sessionRoute} makes, for a resource route. + * + * @example + * ```ts + * import type { + * RouterSessionRoute, + * } from "@monarcode/session-kit/react-router/server"; + * + * declare const route: RouterSessionRoute; + * + * export const loader = route.loader; + * export const action = route.action; + * ``` + * + * @since 0.1.0 + */ +export type RouterSessionRoute = { + loader: (args: RouterArgs) => Promise; + action: (args: RouterArgs) => Promise; +}; + +/** + * Makes the loader and action of your session route, a resource route that + * answers `createMirrorAuth`'s `endpoint`: the browser client reads the + * session, signs out and gets the access token through it. It needs + * {@link sessionMiddleware} in the root route. + * + * It answers this site's own pages only, as `sessionHandler` from + * `@monarcode/session-kit/server` explains, and serves the access token only + * when `createServerAuth` has `clientCredentials`. Sign-in stays your own + * action. + * + * Export the loader and action one by one, as below. React Router's build + * can't remove a destructured `export const { loader }` from the browser's + * bundle, and fails. + * + * @example + * ```ts + * import type { ServerAuth } from "@monarcode/session-kit/server"; + * import { sessionRoute } from "@monarcode/session-kit/react-router/server"; + * + * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; + * + * // app/routes/auth.session.ts + * const route = sessionRoute(serverAuth); + * + * export const loader = route.loader; + * export const action = route.action; + * ``` + * + * @since 0.1.0 + */ +export function sessionRoute( + serverAuth: ServerAuth, +): RouterSessionRoute { + const handle = handleSession(serverAuth); + const route = ({ request, context }: RouterArgs) => + handle(request, () => routerJar(context)); + return { loader: route, action: route }; +} diff --git a/src/server/handler.ts b/src/server/handler.ts new file mode 100644 index 0000000..c582fcf --- /dev/null +++ b/src/server/handler.ts @@ -0,0 +1,187 @@ +import { ENDPOINT_VERSION } from "../core/endpoint.js"; +import { AuthError, type AuthErrorCode } from "../core/errors.js"; +import { isRecord } from "../core/json.js"; +import type { ServerAuth } from "./auth.js"; +import type { CookieJar } from "./cookies.js"; + +/** + * Answers the browser client's requests to your session route, for one + * request and its cookie jar. {@link sessionHandler} makes one. + * + * @example + * ```ts + * import type { CookieJar, SessionHandler } from "@monarcode/session-kit/server"; + * + * declare const handle: SessionHandler; + * declare function jarOf(request: Request): CookieJar; + * + * export const route = (request: Request) => handle(request, jarOf(request)); + * ``` + * + * @since 0.1.0 + */ +export type SessionHandler = ( + request: Request, + jar: CookieJar, +) => Promise; + +const STATUS: Partial> = { + INVALID_OPTIONS: 400, + UNAUTHENTICATED: 401, + SESSION_CHANGED: 409, +}; + +function answer(status: number, body: object, headers: HeadersInit = {}) { + const response = Response.json( + { v: ENDPOINT_VERSION, ...body }, + { status, headers }, + ); + // What it says belongs to one user, for this moment. + response.headers.set("Cache-Control", "no-store"); + return response; +} + +function refuse( + error: AuthError, + status = STATUS[error.code] ?? 500, + headers?: HeadersInit, +) { + return answer( + status, + { error: { code: error.code, message: error.message } }, + headers, + ); +} + +/** + * Whether the request comes from this site's own pages. Browsers send + * `Sec-Fetch-Site` to https and localhost pages only, so on plain http a + * `POST` is checked by its `Origin` instead. A `GET` without either is let + * through: it changes nothing, and another site can't read the answer. + */ +function fromThisSite(request: Request): boolean { + const site = request.headers.get("sec-fetch-site"); + if (site !== null) return site === "same-origin"; + if (request.method === "GET") return true; + return request.headers.get("origin") === new URL(request.url).origin; +} + +/** What a `POST` asks for, or an `AuthError` saying why it can't be read. */ +async function readAction(request: Request) { + const body: unknown = await request.json().catch(() => undefined); + if (!isRecord(body)) + return new AuthError("INVALID_OPTIONS", "Send a JSON body"); + if (body.v !== ENDPOINT_VERSION) + return new AuthError( + "INVALID_OPTIONS", + "This page came from another version of the app: reload it", + ); + return body; +} + +/** + * Makes the handler for your session route ({@link SessionHandler}), which + * answers `createMirrorAuth`'s `endpoint`. A `GET` reads the session. A + * `POST` signs out, or gets or renews the access token for page scripts. + * + * It answers only this site's own pages, by the `Sec-Fetch-Site` header, so + * another site can't sign the user out or ask for a token. Browsers send it + * to https and localhost pages, since 2023 (Safari 16.4). On plain http, a + * `POST` needs an `Origin` header that matches the request's URL. Anything + * else is refused with 403. Every answer has `Cache-Control: no-store`. + * + * The access token is served only when `createServerAuth` has + * `clientCredentials`. A failure answers with its `AuthErrorCode`, which the + * browser client rejects with. Anything that isn't an `AuthError` is thrown, + * for your framework to log. + * + * Each framework's `sessionRoute` wraps it in a route. Use it directly on a + * server without an adapter, with the request's cookie jar. + * + * @example + * ```ts + * import { + * sessionHandler, + * type CookieJar, + * type ServerAuth, + * } from "@monarcode/session-kit/server"; + * + * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; + * declare function jarOf(request: Request): CookieJar; + * + * const handle = sessionHandler(serverAuth); + * + * // A route at /api/session, for GET and POST. + * export const route = (request: Request) => handle(request, jarOf(request)); + * ``` + * + * @since 0.1.0 + */ +export function sessionHandler( + serverAuth: ServerAuth, +): SessionHandler { + const handle = handleSession(serverAuth); + return (request, jar) => handle(request, () => jar); +} + +/** + * {@link sessionHandler} for the adapters, which find the request's cookie + * jar inside, so a setup error, such as a missing middleware, still answers + * in the format the browser client reads. + */ +export function handleSession(serverAuth: ServerAuth) { + return async ( + request: Request, + jarOf: () => CookieJar | Promise, + ): Promise => { + if (!fromThisSite(request)) + return refuse( + new AuthError( + "INVALID_OPTIONS", + "The session route answers this site's own pages only", + ), + 403, + ); + if (request.method !== "GET" && request.method !== "POST") + return refuse( + new AuthError( + "INVALID_OPTIONS", + "The session route answers GET and POST", + ), + 405, + { Allow: "GET, POST" }, + ); + try { + const session = serverAuth.forRequest(await jarOf()); + if (request.method === "GET") + return answer(200, { session: await session.getSession() }); + const body = await readAction(request); + if (body instanceof AuthError) return refuse(body); + switch (body.action) { + case "signOut": + await session.signOut(); + return answer(200, { session: null }); + case "credentials": + return answer(200, { + credentials: await session.clientCredentials.get(), + }); + case "renew": + return answer(200, { + credentials: await session.clientCredentials.renew( + body.rejected as never, + ), + }); + default: + return refuse( + new AuthError( + "INVALID_OPTIONS", + "Ask for signOut, credentials or renew", + ), + ); + } + } catch (error) { + if (error instanceof AuthError) return refuse(error); + throw error; + } + }; +} diff --git a/src/server/index.ts b/src/server/index.ts index 900e199..7246dfc 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -1,4 +1,5 @@ export { createServerAuth } from "./auth.js"; +export { sessionHandler } from "./handler.js"; export type { ClientCredentials } from "../core/mirror.js"; export type { @@ -10,3 +11,4 @@ export type { SessionMiddlewareOptions, } from "./auth.js"; export type { CookieJar, CookieOptions } from "./cookies.js"; +export type { SessionHandler } from "./handler.js"; diff --git a/src/tanstack-start/server.ts b/src/tanstack-start/server.ts index 254de77..5eddecd 100644 --- a/src/tanstack-start/server.ts +++ b/src/tanstack-start/server.ts @@ -18,6 +18,7 @@ import { type SessionMiddlewareOptions, } from "../server/auth.js"; import type { CookieJar, CookieOptions } from "../server/cookies.js"; +import { handleSession } from "../server/handler.js"; /** `options` without unset attributes, which Start's types don't accept. */ function attributes({ domain, maxAge, ...rest }: CookieOptions) { @@ -188,3 +189,63 @@ export function refreshSession( return result; }; } + +/** + * The handlers {@link sessionRoute} makes, for a server route's `GET` and + * `POST`. + * + * @example + * ```ts + * import type { + * StartSessionRoute, + * } from "@monarcode/session-kit/tanstack-start/server"; + * + * declare const route: StartSessionRoute; + * + * export const methods = Object.keys(route); // ["GET", "POST"] + * ``` + * + * @since 0.1.0 + */ +export type StartSessionRoute = { + GET: (context: { request: Request }) => Promise; + POST: (context: { request: Request }) => Promise; +}; + +/** + * Makes the handlers of your session route, a server route that answers + * `createMirrorAuth`'s `endpoint`: the browser client signs out and gets the + * access token through it. Pass them as the route's `server.handlers`. + * + * It answers this site's own pages only, as `sessionHandler` from + * `@monarcode/session-kit/server` explains, and serves the access token only + * when `createServerAuth` has `clientCredentials`. Start's + * `createCsrfMiddleware` filtered to server functions doesn't cover server + * routes, so this check does. + * + * `loadSession` reads the session while Start renders on the server, where + * the client can't call the route. Pass `createMirrorAuth` a `revalidate` + * server function too. Sign-in stays your own server function. + * + * @example + * ```ts + * import type { ServerAuth } from "@monarcode/session-kit/server"; + * import { sessionRoute } from "@monarcode/session-kit/tanstack-start/server"; + * + * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; + * + * // In src/routes/api/session.ts: + * // createFileRoute("/api/session")({ server: { handlers: route } }) + * export const route = sessionRoute(serverAuth); + * ``` + * + * @since 0.1.0 + */ +export function sessionRoute( + serverAuth: ServerAuth, +): StartSessionRoute { + const handle = handleSession(serverAuth); + const route = ({ request }: { request: Request }) => + handle(request, startJar); + return { GET: route, POST: route }; +} diff --git a/tests/consumer.ts b/tests/consumer.ts index f390aba..06cb03a 100644 --- a/tests/consumer.ts +++ b/tests/consumer.ts @@ -1,4 +1,5 @@ import type { + ActionFunction, LoaderFunction, LoaderFunctionArgs, MiddlewareFunction, @@ -58,6 +59,7 @@ import { nextJar, nextSession, proxyJar, + sessionRoute as nextSessionRoute, type NextCookies, type NextSession, } from "../dist/next/index.js"; @@ -69,6 +71,7 @@ import { routerAuth, routerJar, sessionMiddleware, + sessionRoute as routerSessionRoute, type RouterContextLike, } from "../dist/react-router/server.js"; import * as react from "../dist/react/index.js"; @@ -79,6 +82,7 @@ import { } from "../dist/react/index.js"; import { createServerAuth, + sessionHandler, type CookieJar, type RequestAuth, } from "../dist/server/index.js"; @@ -655,6 +659,17 @@ const proxied: Promise = appSessionNext.refresh( NextResponse.next(), ); void proxied; +// The session route, in each framework's own route types. +export const { GET, POST } = nextSessionRoute(serverAuth, cookies); +const resourceRoute = routerSessionRoute(serverAuth); +const sessionLoader: LoaderFunction = resourceRoute.loader; +const sessionAction: ActionFunction = resourceRoute.action; +void [sessionLoader, sessionAction]; +const answered: Promise = sessionHandler(serverAuth)( + new Request("https://app.test/api/session"), + jar, +); +void answered; // @ts-expect-error nextSession needs Next's cookies and redirect. nextSession(serverAuth, { cookies }); @@ -708,12 +723,41 @@ void requireSession(mirror, { location: { href: "/private" }, loginPath: "/login", }); +// With the session route, a session that starts null, and a typed signIn. +declare function signInFn(input: { + data: { username: string }; +}): Promise>>; +const routed = createMirrorAuth({ + name: "type-test", + session: null, + endpoint: "/api/session", + signIn: (data: { username: string }) => signInFn({ data }), +}); +const routedEmail: string | undefined = routed.state.get().user?.email; +void routedEmail; +void routed.signIn({ username: "emilys" }); +// @ts-expect-error signIn's input is inferred from the option. +void routed.signIn({ password: "x" }); +createAuthFetch(routed, { baseUrl }); const plainMirror: MirrorAuth<{ id: string }> = createMirrorAuth({ name: "type-test", session: null as Session<{ id: string }> | null, revalidate: async () => null, signOut: async () => {}, }); +// With endpoint, revalidate alone is fine, as Start passes it. +createMirrorAuth({ + name: "type-test", + session: null as Session<{ id: string }> | null, + endpoint: "/api/session", + revalidate: async () => null, +}); +// @ts-expect-error Without endpoint, revalidate needs signOut. +createMirrorAuth({ + name: "type-test", + session: null, + revalidate: async () => null, +}); // @ts-expect-error Without the signIn option, there is no signIn. void plainMirror.signIn; // @ts-expect-error The mirror can't lock. diff --git a/tests/mirror.test.ts b/tests/mirror.test.ts index 4b8309a..da067e5 100644 --- a/tests/mirror.test.ts +++ b/tests/mirror.test.ts @@ -11,6 +11,7 @@ import { import { createAuthFetch } from "@monarcode/session-kit/http"; import { createServerAuth, + sessionHandler, type CookieJar, } from "@monarcode/session-kit/server"; @@ -39,7 +40,7 @@ function mirror( revalidate: async () => alice, signOut: async () => {}, ...options, - }); + } as MirrorAuthOptions); } test("starts from the server's session, with no initializing state", async () => { @@ -421,8 +422,14 @@ test("end to end: browser sign-in sealed on the server, then authFetch", async ( const sent: Array = []; const originalFetch = globalThis.fetch; + // The page the client runs in. + Object.defineProperty(globalThis, "location", { + value: new URL("https://app.test/dashboard"), + configurable: true, + }); t.after(() => { globalThis.fetch = originalFetch; + delete (globalThis as { location?: unknown }).location; }); globalThis.fetch = async (request) => { const authorization = (request as Request).headers.get("Authorization"); @@ -476,3 +483,217 @@ test("a failed sign-in leaves a revalidation in flight to apply", async () => { assert.equal(await revalidating, null); assert.equal(auth.state.get().status, "unauthenticated"); }); + +/** + * A server with a session route at `/api/session`, and `fetch` routed to it + * as a browser on the same site would send it. + */ +function withSessionRoute( + t: { after: (fn: () => void) => void }, + options: { clientCredentials?: boolean } = {}, +) { + const cookies = new Map(); + const jar = (): CookieJar => { + const snapshot = new Map(cookies); + return { + writable: true, + get: (name) => snapshot.get(name), + set: (name, value) => cookies.set(name, value), + delete: (name) => cookies.delete(name), + }; + }; + let refreshes = 0; + const serverAuth = createServerAuth({ + name: "app", + user: userSchema, + secret: SECRET, + ...options, + refresh: async () => ({ + accessToken: `access-${++refreshes + 1}`, + expiresIn: 900, + }), + }); + const handle = sessionHandler(serverAuth); + const sent: string[] = []; + const originalFetch = globalThis.fetch; + // The page the client runs in. + Object.defineProperty(globalThis, "location", { + value: new URL("https://app.test/dashboard"), + configurable: true, + }); + t.after(() => { + globalThis.fetch = originalFetch; + delete (globalThis as { location?: unknown }).location; + }); + const network = { down: false, site: "same-origin" }; + globalThis.fetch = async (input, init) => { + if (network.down) throw new TypeError("fetch failed"); + const headers = new Headers(init?.headers); + headers.set("Sec-Fetch-Site", network.site); + const request = new Request(new URL(String(input), "https://app.test"), { + ...init, + headers, + }); + sent.push(`${request.method} ${request.url}`); + if (!request.url.endsWith("/api/session")) + return new Response("

Not found

", { status: 404 }); + return handle(request, jar()); + }; + return { serverAuth, jar, cookies, sent, network }; +} + +test("endpoint: the client reads, gets the token and signs out through the session route", async (t) => { + const { serverAuth, jar, cookies, sent } = withSessionRoute(t, { + clientCredentials: true, + }); + const signedIn = await serverAuth.signIn(jar(), { + accessToken: "access-1", + refreshToken: "refresh-1", + expiresIn: 900, + user, + }); + const auth = createMirrorAuth({ + name: "app", + session: null as Session | null, + endpoint: "/api/session", + }); + assert.deepEqual(await auth.retry(), signedIn); + assert.equal(auth.state.get().status, "authenticated"); + + const credentials = await auth.credentials.get(); + assert.equal(credentials?.accessToken, "access-1"); + const renewed = await auth.credentials.renew(credentials!); + assert.equal(renewed?.accessToken, "access-2"); + + await auth.signOut(); + assert.equal(auth.state.get().status, "unauthenticated"); + assert.equal(cookies.has("app.session"), false); + assert.deepEqual(sent, [ + "GET https://app.test/api/session", + "POST https://app.test/api/session", + "POST https://app.test/api/session", + "POST https://app.test/api/session", + ]); +}); + +test("endpoint: failures reject with the server's code, or as the app's functions' do", async (t) => { + const { serverAuth, jar, network } = withSessionRoute(t); + const session = await serverAuth.signIn(jar(), { + accessToken: "access-1", + expiresIn: 900, + user, + }); + const auth = createMirrorAuth({ + name: "app", + session, + endpoint: "/api/session", + }); + // Without clientCredentials, the server keeps the token. + await assert.rejects(auth.credentials.get(), code("INVALID_OPTIONS")); + network.site = "cross-site"; + await assert.rejects(auth.retry(), code("INVALID_OPTIONS")); + network.site = "same-origin"; + network.down = true; + await assert.rejects(auth.retry(), code("REFRESH_FAILED")); + await assert.rejects(auth.signOut(), code("PERSISTENCE_FAILED")); + assert.equal(auth.state.get().status, "authenticated"); + network.down = false; + + const elsewhere = createMirrorAuth({ + name: "app", + session, + endpoint: "/api/sessions", + }); + await assert.rejects(elsewhere.retry(), code("REFRESH_FAILED")); +}); + +test("endpoint: revalidate, signOut and credentials win, and the path is checked", async (t) => { + const { sent } = withSessionRoute(t); + const auth = createMirrorAuth({ + name: "app", + session: alice, + endpoint: "/api/session", + revalidate: async () => bob, + credentials: { + get: async () => ({ sessionId: "s2", accessToken: "own" }), + renew: async () => null, + }, + }); + assert.deepEqual(await auth.retry(), bob); + assert.equal((await auth.credentials.get())?.accessToken, "own"); + assert.deepEqual(sent, []); + + for (const endpoint of [ + "api/session", + "//evil.test/session", + "/\\evil", + "/\t/evil.test/session", + "/\n\\evil.test", + "/api session", + 1, + ]) + assert.throws( + () => + createMirrorAuth({ + name: "app", + session: null, + endpoint: endpoint as string, + }), + code("INVALID_OPTIONS"), + ); + assert.throws( + // @ts-expect-error: neither endpoint nor revalidate and signOut + () => createMirrorAuth({ name: "app", session: null }), + code("INVALID_OPTIONS"), + ); + assert.throws( + () => + // @ts-expect-error: revalidate without signOut + createMirrorAuth({ + name: "app", + session: null, + revalidate: async () => null, + }), + code("INVALID_OPTIONS"), + ); +}); + +test("endpoint: on the server, a call through it rejects with INVALID_OPTIONS", async (t) => { + withSessionRoute(t); + delete (globalThis as { location?: unknown }).location; + const auth = createMirrorAuth({ + name: "app", + session: alice, + endpoint: "/api/session", + }); + await assert.rejects(auth.retry(), code("INVALID_OPTIONS")); + await assert.rejects(auth.signOut(), code("INVALID_OPTIONS")); +}); + +test("endpoint: when the server holds another account, renew follows it", async (t) => { + const { serverAuth, jar } = withSessionRoute(t, { clientCredentials: true }); + const first = await serverAuth.signIn(jar(), { + accessToken: "access-1", + expiresIn: 900, + user, + }); + const auth = createMirrorAuth({ + name: "app", + session: first, + endpoint: "/api/session", + }); + const credentials = await auth.credentials.get(); + // Another account signs in with a form post: no tab hears of it. + const second = await serverAuth.signIn(jar(), { + accessToken: "access-9", + expiresIn: 900, + user: { ...user, id: "u2" }, + }); + await assert.rejects( + auth.credentials.renew(credentials!), + code("SESSION_CHANGED"), + ); + await settle(); + assert.equal(auth.state.get().sessionId, second.sessionId); + assert.equal((await auth.credentials.get())?.accessToken, "access-9"); +}); diff --git a/tests/next.test.ts b/tests/next.test.ts index 40b361d..6d7ddda 100644 --- a/tests/next.test.ts +++ b/tests/next.test.ts @@ -5,6 +5,7 @@ import { nextJar, nextSession, proxyJar, + sessionRoute, type NextCookies, } from "@monarcode/session-kit/next"; import { createServerAuth } from "@monarcode/session-kit/server"; @@ -371,3 +372,30 @@ test("nextSession's refresh refreshes in Proxy and resolves the response", async kept, ); }); + +test("sessionRoute answers the browser client in a Route Handler, setting cookies", async () => { + const signedIn = NextResponse.next(); + const session = await serverAuth.signIn( + nextJar(actionStore(nextRequest(), signedIn), { writable: true }), + tokens(), + ); + const response = NextResponse.next(); + const store = actionStore(nextRequest(signedIn), response); + const { GET, POST } = sessionRoute(serverAuth, async () => store); + const toRoute = (method: string, body?: object) => + new Request("https://app.test/api/session", { + method, + headers: { "Sec-Fetch-Site": "same-origin" }, + ...(body && { body: JSON.stringify(body) }), + }); + + const read = await GET(toRoute("GET")); + assert.deepEqual((await read.json()).session, session); + const signedOut = await POST(toRoute("POST", { v: 1, action: "signOut" })); + assert.equal(signedOut.status, 200); + assert.deepEqual(deleted(response), ["app.session"]); + assert.throws( + () => sessionRoute(serverAuth, undefined as never), + code("INVALID_OPTIONS"), + ); +}); diff --git a/tests/react-router-server.test.ts b/tests/react-router-server.test.ts index 6bb3eb9..dc129ed 100644 --- a/tests/react-router-server.test.ts +++ b/tests/react-router-server.test.ts @@ -11,6 +11,7 @@ import { routerAuth, routerJar, sessionMiddleware, + sessionRoute, type RouterArgs, type RouterContextLike, type RouterMiddleware, @@ -85,6 +86,19 @@ test("routerJar needs cookieJarMiddleware", () => { assert.throws(() => routerJar(newContext()), code("INVALID_OPTIONS")); }); +test("sessionRoute without the middleware answers with the code the client reads", async () => { + const response = await sessionRoute(serverAuth).loader({ + request: new Request("https://app.test/auth/session", { + headers: { "Sec-Fetch-Site": "same-origin" }, + }), + context: newContext(), + } as never); + assert.equal(response.status, 400); + const body = (await response.json()) as any; + assert.equal(body.error.code, "INVALID_OPTIONS"); + assert.match(body.error.message, /cookieJarMiddleware/); +}); + test("routerAuth gives the request's session by its context", async () => { const auth = routerAuth(serverAuth); assert.throws(() => auth(newContext()), code("INVALID_OPTIONS")); @@ -349,6 +363,12 @@ function requestHandler({ basename }: { basename?: string } = {}) { }), }, }, + "routes/auth.session": { + id: "routes/auth.session", + parentId: "root", + path: "auth/session", + module: sessionRoute(serverAuth), + }, "routes/session": { id: "routes/session", parentId: "root", @@ -812,3 +832,37 @@ test( assert.equal(login.headers.get("Location"), "/app/session"); }, ); + +test( + "React Router: sessionRoute is a resource route for the browser client", + { skip: !middlewareSupported }, + async () => { + const handler = requestHandler(); + const toRoute = (cookie: string, method: string, body?: object) => + new Request("https://app.test/auth/session", { + method, + headers: { cookie, "Sec-Fetch-Site": "same-origin" }, + ...(body && { body: JSON.stringify(body) }), + }); + const cookie = cookieHeader( + await handle("", (jar) => serverAuth.signIn(jar, tokens())), + ); + const read = await handler(toRoute(cookie, "GET")); + assert.equal(read.status, 200); + assert.equal(read.headers.get("Cache-Control"), "no-store"); + assert.deepEqual(((await read.json()) as any).session.user, user); + + const signedOut = await handler( + toRoute(cookie, "POST", { v: 1, action: "signOut" }), + ); + assert.equal(signedOut.status, 200); + assert.deepEqual(deleted(signedOut), ["app.session"]); + + const elsewhere = await handler( + new Request("https://app.test/auth/session", { + headers: { cookie, "Sec-Fetch-Site": "cross-site" }, + }), + ); + assert.equal(elsewhere.status, 403); + }, +); diff --git a/tests/server.test.ts b/tests/server.test.ts index 0410a33..840dde2 100644 --- a/tests/server.test.ts +++ b/tests/server.test.ts @@ -1,9 +1,10 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { fromAccessToken } from "@monarcode/session-kit"; +import { AuthError, fromAccessToken } from "@monarcode/session-kit"; import { createServerAuth, + sessionHandler, type CookieJar, type CookieOptions, type ServerAuthOptions, @@ -892,3 +893,144 @@ test("a writable view with expired access goes straight to refreshing, never una ["authenticated", version], ]); }); + +/** A request to the session route, from this site unless `site` says. */ +function toRoute( + method = "GET", + body?: unknown, + site: string | null = "same-origin", + origin?: string, +) { + const headers = new Headers(); + if (site) headers.set("Sec-Fetch-Site", site); + if (origin) headers.set("Origin", origin); + if (body !== undefined) headers.set("Content-Type", "application/json"); + return new Request("https://app.test/api/session", { + method, + headers, + ...(body !== undefined && { body: JSON.stringify(body) }), + }); +} + +const answerOf = async (response: Response) => + (await response.json()) as Record; + +test("sessionHandler reads the session, gives and renews the token, and signs out", async () => { + const app = server({ + clientCredentials: true, + refresh: async () => ({ accessToken: "access-2", expiresIn: 900 }), + }); + const handle = sessionHandler(app); + const cookies = browser(); + await app.signIn(cookies.request(), tokens()); + + const read = await handle(toRoute(), cookies.request()); + assert.equal(read.status, 200); + assert.equal(read.headers.get("Cache-Control"), "no-store"); + const session = await answerOf(read); + assert.equal(session.v, 1); + assert.deepEqual(session.session.user, user); + + const given = await answerOf( + await handle( + toRoute("POST", { v: 1, action: "credentials" }), + cookies.request(), + ), + ); + assert.equal(given.credentials.accessToken, "access-1"); + const renewed = await answerOf( + await handle( + toRoute("POST", { + v: 1, + action: "renew", + rejected: { + sessionId: session.session.sessionId, + accessToken: "access-1", + }, + }), + cookies.request(), + ), + ); + assert.equal(renewed.credentials.accessToken, "access-2"); + + const signedOut = await handle( + toRoute("POST", { v: 1, action: "signOut" }), + cookies.request(), + ); + assert.deepEqual(await answerOf(signedOut), { v: 1, session: null }); + assert.equal(await app.getSession(cookies.request()), null); +}); + +test("sessionHandler refuses other sites, other versions and requests it can't read", async () => { + const handle = sessionHandler(server()); + const cookies = browser(); + const refused = async (request: Request, status: number) => { + const response = await handle(request, cookies.request()); + assert.equal(response.status, status); + assert.equal(response.headers.get("Cache-Control"), "no-store"); + const { error } = await answerOf(response); + assert.equal(error.code, "INVALID_OPTIONS"); + return { response, error }; + }; + for (const site of ["cross-site", "same-site", "none", null]) + await refused(toRoute("POST", { v: 1, action: "signOut" }, site), 403); + await refused(toRoute("GET", undefined, "cross-site"), 403); + // On plain http, browsers send no Sec-Fetch-Site: a POST needs its Origin. + await refused( + toRoute("POST", { v: 1, action: "signOut" }, null, "https://evil.test"), + 403, + ); + const reload = await refused( + toRoute("POST", { v: 2, action: "signOut" }), + 400, + ); + assert.match(reload.error.message, /reload/); + await refused(toRoute("POST", { v: 1, action: "lock" }), 400); + await refused(toRoute("POST", "not json"), 400); + await refused( + toRoute("POST", { v: 1, action: "renew", rejected: { sessionId: 1 } }), + 400, + ); + const put = await refused(toRoute("PUT", { v: 1 }), 405); + assert.equal(put.response.headers.get("Allow"), "GET, POST"); + // Without clientCredentials, the token stays on the server. + await refused(toRoute("POST", { v: 1, action: "credentials" }), 400); +}); + +test("sessionHandler answers this site's pages on plain http by their Origin", async () => { + const handle = sessionHandler(server()); + const cookies = browser(); + const read = await handle( + toRoute("GET", undefined, null), + cookies.request(), + ); + assert.deepEqual(await answerOf(read), { v: 1, session: null }); + const signedOut = await handle( + toRoute("POST", { v: 1, action: "signOut" }, null, "https://app.test"), + cookies.request(), + ); + assert.equal(signedOut.status, 200); +}); + +test("sessionHandler answers an AuthError with its code, and throws anything else", async () => { + const failing = (error: unknown) => + sessionHandler({ + forRequest: () => ({ + getSession: async () => { + throw error; + }, + }), + } as never); + const response = await failing( + new AuthError("REFRESH_FAILED", "Refresh failed"), + )(toRoute(), browser().request()); + assert.equal(response.status, 500); + assert.deepEqual(await answerOf(response), { + v: 1, + error: { code: "REFRESH_FAILED", message: "Refresh failed" }, + }); + await assert.rejects( + failing(new TypeError("a bug"))(toRoute(), browser().request()), + TypeError, + ); +}); diff --git a/tests/tanstack-start.test.ts b/tests/tanstack-start.test.ts index 83a4d3f..71929b0 100644 --- a/tests/tanstack-start.test.ts +++ b/tests/tanstack-start.test.ts @@ -17,6 +17,7 @@ import { } from "@monarcode/session-kit/tanstack-start"; import { refreshSession, + sessionRoute, startAuth, startJar, } from "@monarcode/session-kit/tanstack-start/server"; @@ -288,6 +289,34 @@ test("refreshSession takes the header's value or leaves it alone, and a failed r ); }); +test("sessionRoute's handlers answer the browser client through Start's cookies", async () => { + const route = sessionRoute(serverAuth); + const toRoute = (method: string, body?: object) => + new Request("https://app.test/api/session", { + method, + headers: { "Sec-Fetch-Site": "same-origin" }, + ...(body && { body: JSON.stringify(body) }), + }); + const signedIn = await handle("", () => session.signIn(tokens())); + const cookie = cookieHeader(signedIn.setCookies); + + const read = await handle(cookie, async () => + (await route.GET({ request: toRoute("GET") })).json(), + ); + assert.deepEqual(read.result, { v: 1, session: signedIn.result }); + const signedOut = await handle( + cookie, + async () => + ( + await route.POST({ + request: toRoute("POST", { v: 1, action: "signOut" }), + }) + ).status, + ); + assert.equal(signedOut.result, 200); + assert.match(signedOut.setCookies[0]!, /^app\.session=; Max-Age=0/); +}); + test("startAuth has every member a request's session has, passed through", async () => { const app = createServerAuth({ name: "app", From eab4c81e1cf901865a0414e47c9a8a3746697f32 Mon Sep 17 00:00:00 2001 From: monarcode Date: Sat, 14 Nov 2026 03:39:32 +0100 Subject: [PATCH 07/26] feat(server): session route for the browser client, with sessionHandler, sessionRoute and createMirrorAuth's endpoint --- CHANGELOG.md | 4 +-- examples/next-app/app/api/session/route.ts | 2 +- site/content/docs/(latest)/reference/next.mdx | 12 ++++++++- site/content/docs/(latest)/setups/next.mdx | 2 +- src/next/index.ts | 26 ++++++++++++++++--- tests/consumer.ts | 2 +- tests/next.test.ts | 13 ++++++---- 7 files changed, 47 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a5e6aa7..72a6f9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -107,11 +107,11 @@ (`StartSessionRoute`), a resource route's `loader` and `action` in `@monarcode/session-kit/react-router/server` (`RouterSessionRoute`), and a Route Handler's `GET` and `POST` in `@monarcode/session-kit/next`, with - Next's `cookies` (`NextSessionRoute`). + Next's `cookies` in `NextSessionRouteOptions` (`NextSessionRoute`). ```ts // app/api/session/route.ts - export const { GET, POST } = sessionRoute(serverAuth, cookies); + export const { GET, POST } = sessionRoute(serverAuth, { cookies }); // lib/auth/client.ts createMirrorAuth({ name: "app", session, endpoint: "/api/session", signIn }); ``` diff --git a/examples/next-app/app/api/session/route.ts b/examples/next-app/app/api/session/route.ts index d0c5126..7c82f2b 100644 --- a/examples/next-app/app/api/session/route.ts +++ b/examples/next-app/app/api/session/route.ts @@ -7,4 +7,4 @@ import { serverAuth } from "../../../lib/auth/server"; * The session route the browser's client calls: it reads the session, signs * out, and gets the access token. It answers this site's own pages only. */ -export const { GET, POST } = sessionRoute(serverAuth, cookies); +export const { GET, POST } = sessionRoute(serverAuth, { cookies }); diff --git a/site/content/docs/(latest)/reference/next.mdx b/site/content/docs/(latest)/reference/next.mdx index b9568a0..c5daae8 100644 --- a/site/content/docs/(latest)/reference/next.mdx +++ b/site/content/docs/(latest)/reference/next.mdx @@ -25,7 +25,7 @@ The `CookieJar` for a request in Next's Proxy (`proxy.ts`). It reads `request`'s ### sessionRoute -Makes the Route Handlers for your session route, which answers `createMirrorAuth`'s `endpoint`: the browser client reads the session, signs out and gets the access token through it. Pass `cookies` from `next/headers`. +Makes the Route Handlers for your session route, which answers `createMirrorAuth`'s `endpoint`: the browser client reads the session, signs out and gets the access token through it. Pass `cookies` from `next/headers` ([`NextSessionRouteOptions`](#nextsessionrouteoptions)). ## Types @@ -61,6 +61,16 @@ Options for [`nextSession`](#nextsession). Pass Next's own `cookies` and `redire The Route Handlers [`sessionRoute`](#sessionroute) makes, for `GET` and `POST`. +### NextSessionRouteOptions + +Options for [`sessionRoute`](#sessionroute). Pass Next's own `cookies`, as this entry point doesn't import `next`. + + + ### ProxyRequest The request [`proxyJar`](#proxyjar) reads cookies from. A `NextRequest` fits. diff --git a/site/content/docs/(latest)/setups/next.mdx b/site/content/docs/(latest)/setups/next.mdx index 15bf0b3..57342e9 100644 --- a/site/content/docs/(latest)/setups/next.mdx +++ b/site/content/docs/(latest)/setups/next.mdx @@ -147,7 +147,7 @@ import { cookies } from "next/headers"; import { serverAuth } from "../../../lib/auth/server"; -export const { GET, POST } = sessionRoute(serverAuth, cookies); +export const { GET, POST } = sessionRoute(serverAuth, { cookies }); ``` It answers your own site's pages only, so another site can't sign the user diff --git a/src/next/index.ts b/src/next/index.ts index bb0d95c..1bf368e 100644 --- a/src/next/index.ts +++ b/src/next/index.ts @@ -420,11 +420,30 @@ export type NextSessionRoute = { POST: (request: Request) => Promise; }; +/** + * Options for {@link sessionRoute}. Pass Next's own `cookies`, as this entry + * point doesn't import `next`. + * + * @example + * ```ts + * import type { NextSessionRouteOptions } from "@monarcode/session-kit/next"; + * import { cookies } from "next/headers"; + * + * export const options: NextSessionRouteOptions = { cookies }; + * ``` + * + * @since 0.1.0 + */ +export type NextSessionRouteOptions = { + /** `cookies` from `next/headers`. */ + cookies: () => Promise; +}; + /** * Makes the Route Handlers for your session route, which answers * `createMirrorAuth`'s `endpoint`: the browser client reads the session, * signs out and gets the access token through it. Pass `cookies` from - * `next/headers`. + * `next/headers` ({@link NextSessionRouteOptions}). * * It answers this site's own pages only, as `sessionHandler` from * `@monarcode/session-kit/server` explains, and serves the access token only @@ -440,15 +459,16 @@ export type NextSessionRoute = { * declare const serverAuth: ServerAuth<{ id: number }, { id: number }>; * * // app/api/session/route.ts - * export const { GET, POST } = sessionRoute(serverAuth, cookies); + * export const { GET, POST } = sessionRoute(serverAuth, { cookies }); * ``` * * @since 0.1.0 */ export function sessionRoute( serverAuth: ServerAuth, - cookies: () => Promise, + options: NextSessionRouteOptions, ): NextSessionRoute { + const cookies = options?.cookies; if (typeof cookies !== "function") throw new AuthError( "INVALID_OPTIONS", diff --git a/tests/consumer.ts b/tests/consumer.ts index 06cb03a..19109b7 100644 --- a/tests/consumer.ts +++ b/tests/consumer.ts @@ -660,7 +660,7 @@ const proxied: Promise = appSessionNext.refresh( ); void proxied; // The session route, in each framework's own route types. -export const { GET, POST } = nextSessionRoute(serverAuth, cookies); +export const { GET, POST } = nextSessionRoute(serverAuth, { cookies }); const resourceRoute = routerSessionRoute(serverAuth); const sessionLoader: LoaderFunction = resourceRoute.loader; const sessionAction: ActionFunction = resourceRoute.action; diff --git a/tests/next.test.ts b/tests/next.test.ts index 6d7ddda..ea7479a 100644 --- a/tests/next.test.ts +++ b/tests/next.test.ts @@ -381,7 +381,9 @@ test("sessionRoute answers the browser client in a Route Handler, setting cookie ); const response = NextResponse.next(); const store = actionStore(nextRequest(signedIn), response); - const { GET, POST } = sessionRoute(serverAuth, async () => store); + const { GET, POST } = sessionRoute(serverAuth, { + cookies: async () => store, + }); const toRoute = (method: string, body?: object) => new Request("https://app.test/api/session", { method, @@ -394,8 +396,9 @@ test("sessionRoute answers the browser client in a Route Handler, setting cookie const signedOut = await POST(toRoute("POST", { v: 1, action: "signOut" })); assert.equal(signedOut.status, 200); assert.deepEqual(deleted(response), ["app.session"]); - assert.throws( - () => sessionRoute(serverAuth, undefined as never), - code("INVALID_OPTIONS"), - ); + for (const options of [undefined, {}, { cookies: "x" }]) + assert.throws( + () => sessionRoute(serverAuth, options as never), + code("INVALID_OPTIONS"), + ); }); From 80efcc1918d0cebf86f4478570da5f790dfe0a10 Mon Sep 17 00:00:00 2001 From: monarcode Date: Sat, 14 Nov 2026 07:06:46 +0100 Subject: [PATCH 08/26] feat: add isSignedIn, loader guards and a deep link handler - Add isSignedIn(state), a selector that narrows user - Let React Router's guards be loaders, and default loginPath to "/login" - Add deepLinkHandler to Expo for app/+native-intent.tsx --- CHANGELOG.md | 20 ++ examples/expo-router/app/+native-intent.tsx | 14 +- examples/expo-router/app/_layout.tsx | 8 +- examples/react-router-data/src/main.tsx | 13 +- .../react-router-declarative/src/main.tsx | 8 +- .../app/routes/login.tsx | 6 +- .../app/routes/protected.tsx | 6 +- .../src/routes/_authenticated.tsx | 2 +- .../src/routes/_authenticated.tsx | 2 +- .../src/routes/_authenticated.tsx | 2 +- .../src/routes/_authenticated.tsx | 2 +- site/content/docs/(latest)/client/state.mdx | 4 +- site/content/docs/(latest)/reference/core.mdx | 4 + site/content/docs/(latest)/reference/expo.mdx | 8 + .../content/docs/(latest)/reference/index.mdx | 30 +-- .../docs/(latest)/reference/react-router.mdx | 32 ++- site/content/docs/(latest)/setups/expo.mdx | 49 ++-- .../docs/(latest)/setups/react-router.mdx | 55 ++-- .../docs/(latest)/setups/tanstack-router.mdx | 7 +- .../docs/(latest)/setups/tanstack-start.mdx | 2 +- src/core/return-to.ts | 5 +- src/core/signed-in.ts | 27 ++ src/effect/auth.ts | 5 +- src/expo/deep-link.ts | 61 +++++ src/expo/gate.ts | 7 +- src/expo/index.ts | 4 +- src/index.ts | 1 + src/next/index.ts | 4 +- src/react-router/guards.ts | 239 +++++++++++++++--- src/react-router/index.ts | 4 + src/react-router/outlet.ts | 16 +- src/react-router/server.ts | 6 +- src/react/context.ts | 8 +- src/tanstack-router/guards.ts | 22 +- src/tanstack-router/outlet.ts | 17 +- tests/consumer.ts | 43 +++- tests/expo-modules.ts | 2 +- tests/gate.test.ts | 39 ++- tests/react-router.test.ts | 76 +++++- tests/router.test.ts | 3 +- tests/session.test.ts | 34 ++- 41 files changed, 675 insertions(+), 222 deletions(-) create mode 100644 src/core/signed-in.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 72a6f9a..27c36e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,6 +116,26 @@ createMirrorAuth({ name: "app", session, endpoint: "/api/session", signIn }); ``` +- `isSignedIn(state)` in `@monarcode/session-kit`: `true` while + `authenticated` or `refreshing`, and `false` while `locked`. It narrows + `user`, and works as a selector: `useAuth(isSignedIn)`. +- React Router's guards are loaders of their own: `requireSession(auth)` and + `redirectIfSignedIn(auth)` read the request, and the second reads + `redirectTo` from its URL. They take `RequireSessionLoaderOptions` and + `RedirectIfSignedInLoaderOptions`, and return `RequireSessionLoader` and + `RedirectIfSignedInLoader`. The forms that take `request` or `redirectTo` + stay, for a loader of your own: awaiting a loader form checks nothing. + + ```ts + export const clientLoader = requireSession(auth); + ``` + +- `loginPath` defaults to `"/login"` in `requireSession` for TanStack Router + and React Router, and in React Router's `SessionOutlet`. +- `deepLinkHandler(auth, options?)` in `@monarcode/session-kit/expo` makes + `redirectSystemPath` for `app/+native-intent.tsx` (`DeepLinkHandler`). + `rememberDeepLink` stays, for a `redirectSystemPath` that does more. + ### Changed - **Breaking:** `createAuthFetch` takes the base URL as an option, as diff --git a/examples/expo-router/app/+native-intent.tsx b/examples/expo-router/app/+native-intent.tsx index fc97214..6681e7a 100644 --- a/examples/expo-router/app/+native-intent.tsx +++ b/examples/expo-router/app/+native-intent.tsx @@ -1,18 +1,10 @@ -import { rememberDeepLink } from "@monarcode/session-kit/expo"; +import { deepLinkHandler } from "@monarcode/session-kit/expo"; import { auth } from "../src/auth"; /** * Expo Router calls this with every URL that opens the app, before routing. - * Remembers the link, so SessionGate can open it after a sign-in if + * It remembers the link, so SessionGate can open it after a sign-in if * Stack.Protected turns it away now, and routes it unchanged. */ -export function redirectSystemPath({ - path, -}: { - path: string; - initial: boolean; -}) { - rememberDeepLink(auth, path); - return path; -} +export const redirectSystemPath = deepLinkHandler(auth); diff --git a/examples/expo-router/app/_layout.tsx b/examples/expo-router/app/_layout.tsx index e3456e0..4180f4d 100644 --- a/examples/expo-router/app/_layout.tsx +++ b/examples/expo-router/app/_layout.tsx @@ -1,3 +1,4 @@ +import { isSignedIn } from "@monarcode/session-kit"; import { SessionGate } from "@monarcode/session-kit/expo"; import { AuthProvider, useAuth } from "@monarcode/session-kit/react"; import { SplashScreen, Stack } from "expo-router"; @@ -27,12 +28,9 @@ export default function RootLayout() { } function RootStack() { - // Check `status`, not `user`: a locked session keeps its user. SessionGate + // A locked session isn't signed in, though it keeps its user. SessionGate // handles `initializing` and `unavailable` before this renders. - const signedIn = useAuth( - (state) => - state.status === "authenticated" || state.status === "refreshing", - ); + const signedIn = useAuth(isSignedIn); return ( diff --git a/examples/react-router-data/src/main.tsx b/examples/react-router-data/src/main.tsx index 56f058f..59bd07b 100644 --- a/examples/react-router-data/src/main.tsx +++ b/examples/react-router-data/src/main.tsx @@ -62,20 +62,13 @@ const router = createBrowserRouter([ children: [ { path: "/login", - loader: async ({ request }) => { - const redirectTo = new URL(request.url).searchParams.get( - "redirectTo", - ); - await redirectIfSignedIn(auth, { redirectTo }); - return null; - }, + loader: redirectIfSignedIn(auth), element: , }, { - loader: ({ request }) => - requireSession(auth, { request, loginPath: "/login" }), + loader: requireSession(auth), errorElement: , - element: } />, + element: } />, children: [{ index: true, element: }], }, ], diff --git a/examples/react-router-declarative/src/main.tsx b/examples/react-router-declarative/src/main.tsx index 218c58e..98da83a 100644 --- a/examples/react-router-declarative/src/main.tsx +++ b/examples/react-router-declarative/src/main.tsx @@ -7,7 +7,7 @@ import { useSearchParams, } from "react-router"; -import { safeReturnTo } from "@monarcode/session-kit"; +import { isSignedIn, safeReturnTo } from "@monarcode/session-kit"; import { AuthProvider, useAuth } from "@monarcode/session-kit/react"; import { SessionOutlet } from "@monarcode/session-kit/react-router"; import { createRoot } from "react-dom/client"; @@ -28,10 +28,7 @@ declare module "@monarcode/session-kit" { * which then redirects. */ function Login() { - const signedIn = useAuth( - (state) => - state.status === "authenticated" || state.status === "refreshing", - ); + const signedIn = useAuth(isSignedIn); const [search] = useSearchParams(); if (signedIn) return ; @@ -47,7 +44,6 @@ createRoot(document.getElementById("root")!).render( } unavailable={({ error }) => ( diff --git a/examples/react-router-framework-spa/app/routes/login.tsx b/examples/react-router-framework-spa/app/routes/login.tsx index 9494bd1..dc80c62 100644 --- a/examples/react-router-framework-spa/app/routes/login.tsx +++ b/examples/react-router-framework-spa/app/routes/login.tsx @@ -6,11 +6,7 @@ import { redirectIfSignedIn } from "@monarcode/session-kit/react-router"; import { auth } from "../auth"; import { LoginForm } from "../ui"; -export async function clientLoader({ request }: { request: Request }) { - const redirectTo = new URL(request.url).searchParams.get("redirectTo"); - await redirectIfSignedIn(auth, { redirectTo }); - return null; -} +export const clientLoader = redirectIfSignedIn(auth); export default function Login() { const navigate = useNavigate(); diff --git a/examples/react-router-framework-spa/app/routes/protected.tsx b/examples/react-router-framework-spa/app/routes/protected.tsx index f40eea3..0fa1a6e 100644 --- a/examples/react-router-framework-spa/app/routes/protected.tsx +++ b/examples/react-router-framework-spa/app/routes/protected.tsx @@ -8,12 +8,10 @@ import { import { auth } from "../auth"; import { Pending, Unavailable } from "../ui"; -export function clientLoader({ request }: { request: Request }) { - return requireSession(auth, { request, loginPath: "/login" }); -} +export const clientLoader = requireSession(auth); export default function Protected() { - return } />; + return } />; } export function ErrorBoundary() { diff --git a/examples/tanstack-router/src/routes/_authenticated.tsx b/examples/tanstack-router/src/routes/_authenticated.tsx index eef8802..11e5f0c 100644 --- a/examples/tanstack-router/src/routes/_authenticated.tsx +++ b/examples/tanstack-router/src/routes/_authenticated.tsx @@ -8,7 +8,7 @@ import { Pending, Unavailable } from "../ui"; export const Route = createFileRoute("/_authenticated")({ beforeLoad: ({ context, location }) => - requireSession(context.auth, { location, loginPath: "/login" }), + requireSession(context.auth, { location }), errorComponent: ({ error }) => , component: () => } />, }); diff --git a/examples/tanstack-start-spa-effetch/src/routes/_authenticated.tsx b/examples/tanstack-start-spa-effetch/src/routes/_authenticated.tsx index eef8802..11e5f0c 100644 --- a/examples/tanstack-start-spa-effetch/src/routes/_authenticated.tsx +++ b/examples/tanstack-start-spa-effetch/src/routes/_authenticated.tsx @@ -8,7 +8,7 @@ import { Pending, Unavailable } from "../ui"; export const Route = createFileRoute("/_authenticated")({ beforeLoad: ({ context, location }) => - requireSession(context.auth, { location, loginPath: "/login" }), + requireSession(context.auth, { location }), errorComponent: ({ error }) => , component: () => } />, }); diff --git a/examples/tanstack-start-spa/src/routes/_authenticated.tsx b/examples/tanstack-start-spa/src/routes/_authenticated.tsx index eef8802..11e5f0c 100644 --- a/examples/tanstack-start-spa/src/routes/_authenticated.tsx +++ b/examples/tanstack-start-spa/src/routes/_authenticated.tsx @@ -8,7 +8,7 @@ import { Pending, Unavailable } from "../ui"; export const Route = createFileRoute("/_authenticated")({ beforeLoad: ({ context, location }) => - requireSession(context.auth, { location, loginPath: "/login" }), + requireSession(context.auth, { location }), errorComponent: ({ error }) => , component: () => } />, }); diff --git a/examples/tanstack-start-ssr/src/routes/_authenticated.tsx b/examples/tanstack-start-ssr/src/routes/_authenticated.tsx index eef8802..11e5f0c 100644 --- a/examples/tanstack-start-ssr/src/routes/_authenticated.tsx +++ b/examples/tanstack-start-ssr/src/routes/_authenticated.tsx @@ -8,7 +8,7 @@ import { Pending, Unavailable } from "../ui"; export const Route = createFileRoute("/_authenticated")({ beforeLoad: ({ context, location }) => - requireSession(context.auth, { location, loginPath: "/login" }), + requireSession(context.auth, { location }), errorComponent: ({ error }) => , component: () => } />, }); diff --git a/site/content/docs/(latest)/client/state.mdx b/site/content/docs/(latest)/client/state.mdx index 4d18585..896a7d9 100644 --- a/site/content/docs/(latest)/client/state.mdx +++ b/site/content/docs/(latest)/client/state.mdx @@ -38,4 +38,6 @@ Two habits follow from these fields: - **Scope private cached data to `sessionId`**, such as TanStack Query results, so one account never sees another's. - **Check `status`, not `user`, to know whether access is usable.** A - [locked](/docs/client/locking) session keeps its user. + [locked](/docs/client/locking) session keeps its user. `isSignedIn(state)` + is the check: `true` while `authenticated` or `refreshing`, and it narrows + `user`. `useAuth(isSignedIn)` reads it in a component. diff --git a/site/content/docs/(latest)/reference/core.mdx b/site/content/docs/(latest)/reference/core.mdx index ab60a40..510114a 100644 --- a/site/content/docs/(latest)/reference/core.mdx +++ b/site/content/docs/(latest)/reference/core.mdx @@ -23,6 +23,10 @@ Creates a browser client ([`MirrorAuth`](#mirrorauth)) for a session your server Reads the user from the access token, rather than from what `signIn` is given. Pass the result as `createAuth`'s `user` option. +### isSignedIn + +Whether someone is signed in: `true` while `authenticated` or `refreshing`. It narrows `state`, so `state.user` is set when it's `true`. + ### loginHref Builds the sign-in page's URL, with `?redirectTo=` set to `returnTo`, so the user comes back after signing in. The guards use it. Use it in a guard of your own, such as in a route handler. diff --git a/site/content/docs/(latest)/reference/expo.mdx b/site/content/docs/(latest)/reference/expo.mdx index 081d478..6c14fde 100644 --- a/site/content/docs/(latest)/reference/expo.mdx +++ b/site/content/docs/(latest)/reference/expo.mdx @@ -11,6 +11,10 @@ Guide: [Expo Router](/docs/setups/expo). ## Functions +### deepLinkHandler + +Makes `redirectSystemPath` for `app/+native-intent.tsx`. It keeps each incoming link with [`rememberDeepLink`](#rememberdeeplink), so `SessionGate` opens it after sign-in, and returns the path unchanged. + ### rememberDeepLink Keeps an incoming deep link, so `SessionGate` can open it after the user signs in. Without it, `Stack.Protected` sends a signed-out user from a guarded screen to one they may see, and the link is lost. @@ -27,6 +31,10 @@ Wraps the root navigator in `app/_layout.tsx`. It adds what Expo Router's `Stack ## Types +### DeepLinkHandler + +The `redirectSystemPath` that [`deepLinkHandler`](#deeplinkhandler) makes, for `app/+native-intent.tsx`. + ### RememberDeepLinkOptions Options for [`rememberDeepLink`](#rememberdeeplink), the same as `safeReturnTo`'s. Set `loginPath` when your sign-in screen isn't `/login`, so links to it are dropped rather than kept. diff --git a/site/content/docs/(latest)/reference/index.mdx b/site/content/docs/(latest)/reference/index.mdx index db4df29..347008c 100644 --- a/site/content/docs/(latest)/reference/index.mdx +++ b/site/content/docs/(latest)/reference/index.mdx @@ -12,21 +12,21 @@ exports, with their options and types. Import from these paths only. Internal `dist` paths aren't part of the public API. -| Import | Exports | -| --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -| [`@monarcode/session-kit`](/docs/reference/core) | `createAuth`, `createMirrorAuth`, `fromAccessToken`, `webStorage`, `memoryStorage`, `safeReturnTo`, `loginHref`, `AuthError`, types | -| [`@monarcode/session-kit/react`](/docs/reference/react) | `AuthProvider`, `useAuth`, `useAuthClient`, `createAuthHooks`, `useMirrorAuth`, types | -| [`@monarcode/session-kit/tanstack-router`](/docs/reference/tanstack-router) | `connectAuth`, `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuth`, `useAuthClient`, types | -| [`@monarcode/session-kit/react-router`](/docs/reference/react-router) | `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuthRevalidation`, types | -| [`@monarcode/session-kit/react-router/server`](/docs/reference/react-router-server) | `sessionMiddleware`, `requireSession`, `redirectIfSignedIn`, `sessionRoute`, `routerAuth`, `cookieJarMiddleware`, `routerJar`, types | -| [`@monarcode/session-kit/http`](/docs/reference/http) | `createAuthFetch`, types | -| [`@monarcode/session-kit/server`](/docs/reference/server) | `createServerAuth`, `sessionHandler`, types | -| [`@monarcode/session-kit/tanstack-start`](/docs/reference/tanstack-start) | `connectSession`, `loadSession` | -| [`@monarcode/session-kit/tanstack-start/server`](/docs/reference/tanstack-start-server) | `startAuth`, `refreshSession`, `sessionRoute`, `startJar`, types | -| [`@monarcode/session-kit/next`](/docs/reference/next) | `nextSession`, `sessionRoute`, `nextJar`, `proxyJar`, types | -| [`@monarcode/session-kit/expo`](/docs/reference/expo) | `secureStorage`, `SessionGate`, `rememberDeepLink`, types | -| [`@monarcode/session-kit/effect`](/docs/reference/effect) | `Auth`, `AuthFailure`, types | -| [`@monarcode/session-kit/effetch`](/docs/reference/effetch) | `sessionBearer`, types | +| Import | Exports | +| --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| [`@monarcode/session-kit`](/docs/reference/core) | `createAuth`, `createMirrorAuth`, `fromAccessToken`, `webStorage`, `memoryStorage`, `isSignedIn`, `safeReturnTo`, `loginHref`, `AuthError`, types | +| [`@monarcode/session-kit/react`](/docs/reference/react) | `AuthProvider`, `useAuth`, `useAuthClient`, `createAuthHooks`, `useMirrorAuth`, types | +| [`@monarcode/session-kit/tanstack-router`](/docs/reference/tanstack-router) | `connectAuth`, `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuth`, `useAuthClient`, types | +| [`@monarcode/session-kit/react-router`](/docs/reference/react-router) | `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuthRevalidation`, types | +| [`@monarcode/session-kit/react-router/server`](/docs/reference/react-router-server) | `sessionMiddleware`, `requireSession`, `redirectIfSignedIn`, `sessionRoute`, `routerAuth`, `cookieJarMiddleware`, `routerJar`, types | +| [`@monarcode/session-kit/http`](/docs/reference/http) | `createAuthFetch`, types | +| [`@monarcode/session-kit/server`](/docs/reference/server) | `createServerAuth`, `sessionHandler`, types | +| [`@monarcode/session-kit/tanstack-start`](/docs/reference/tanstack-start) | `connectSession`, `loadSession` | +| [`@monarcode/session-kit/tanstack-start/server`](/docs/reference/tanstack-start-server) | `startAuth`, `refreshSession`, `sessionRoute`, `startJar`, types | +| [`@monarcode/session-kit/next`](/docs/reference/next) | `nextSession`, `sessionRoute`, `nextJar`, `proxyJar`, types | +| [`@monarcode/session-kit/expo`](/docs/reference/expo) | `secureStorage`, `SessionGate`, `deepLinkHandler`, `rememberDeepLink`, types | +| [`@monarcode/session-kit/effect`](/docs/reference/effect) | `Auth`, `AuthFailure`, types | +| [`@monarcode/session-kit/effetch`](/docs/reference/effetch) | `sessionBearer`, types | ## Bundle size diff --git a/site/content/docs/(latest)/reference/react-router.mdx b/site/content/docs/(latest)/reference/react-router.mdx index 0da0f1b..b43fb56 100644 --- a/site/content/docs/(latest)/reference/react-router.mdx +++ b/site/content/docs/(latest)/reference/react-router.mdx @@ -13,11 +13,11 @@ Guide: [React Router](/docs/setups/react-router). ### redirectIfSignedIn -Guards your sign-in page in its loader, so a signed-in user goes straight to `redirectTo`, made safe with `safeReturnTo`. +Guards your sign-in page in its loader, so a signed-in user goes straight to `redirectTo`, made safe with `safeReturnTo`. `redirectIfSignedIn(auth)` is the loader itself, and reads `redirectTo` from the URL's search. ### requireSession -Guards a route in its loader, in data or framework mode, so only signed-in users get through. They get `{ session }`, which holds no tokens. +Guards a route in its loader, in data or framework mode, so only signed-in users get through. They get `{ session }`, which holds no tokens. `requireSession(auth)` is the loader itself. ### useAuthRevalidation @@ -31,6 +31,20 @@ Renders child routes only while someone is signed in, in any mode. It needs an ` ## Types +### RedirectIfSignedInLoader + +The loader that `redirectIfSignedIn(auth)` makes. It reads `redirectTo` from the request's URL, and resolves `null` for a signed-out user. + +### RedirectIfSignedInLoaderOptions + +Options for the loader that `redirectIfSignedIn(auth, options)` makes. + + + ### RedirectIfSignedInOptions Options for [`redirectIfSignedIn`](#redirectifsignedin). @@ -41,6 +55,20 @@ Options for [`redirectIfSignedIn`](#redirectifsignedin). name="RedirectIfSignedInOptions" /> +### RequireSessionLoader + +The loader that `requireSession(auth)` makes. It resolves `{ session }`, typed with the client's user. + +### RequireSessionLoaderOptions + +Options for the loader that `requireSession(auth, options)` makes. + + + ### RequireSessionOptions Options for [`requireSession`](#requiresession). diff --git a/site/content/docs/(latest)/setups/expo.mdx b/site/content/docs/(latest)/setups/expo.mdx index d388b50..c517bb3 100644 --- a/site/content/docs/(latest)/setups/expo.mdx +++ b/site/content/docs/(latest)/setups/expo.mdx @@ -122,6 +122,7 @@ everyone else sees `login`. Register the client's type here too, so the hooks from `@monarcode/session-kit/react` carry your user: ```tsx title="app/_layout.tsx" +import { isSignedIn } from "@monarcode/session-kit"; import { SessionGate } from "@monarcode/session-kit/expo"; import { AuthProvider, useAuth } from "@monarcode/session-kit/react"; import { SplashScreen, Stack } from "expo-router"; @@ -150,9 +151,8 @@ export default function RootLayout() { } function RootStack() { - // `status`, not `user`: a locked session keeps its user. See Locking. - const status = useAuth((state) => state.status); - const signedIn = status === "authenticated" || status === "refreshing"; + // Not signed in while locked, though a locked session keeps its user. + const signedIn = useAuth(isSignedIn); return ( @@ -188,28 +188,22 @@ const [fontsLoaded] = useFonts(fonts); `Stack.Protected` sends a link to a guarded screen to the first screen the user may see, so a signed-out user who opens `myapp://profile` lands on the -sign-in screen and the link is lost. `rememberDeepLink` keeps it, and +sign-in screen and the link is lost. `deepLinkHandler` keeps it, and `SessionGate` opens it after the sign-in. Expo Router calls `redirectSystemPath` with every URL that opens the app, before routing: ```tsx title="app/+native-intent.tsx" -import { rememberDeepLink } from "@monarcode/session-kit/expo"; +import { deepLinkHandler } from "@monarcode/session-kit/expo"; import { auth } from "../src/auth"; -export function redirectSystemPath({ - path, -}: { - path: string; - initial: boolean; -}) { - rememberDeepLink(auth, path); - return path; -} +export const redirectSystemPath = deepLinkHandler(auth); ``` -Return `path` unchanged: the link still goes to Expo Router, which shows it -right away when the user is signed in. +It returns the path unchanged: the link still goes to Expo Router, which +shows it right away when the user is signed in. If your `redirectSystemPath` +does more, such as rewriting old links, call `rememberDeepLink(auth, path)` +in it instead. ## 4. Add the sign-in screen @@ -435,8 +429,12 @@ decides what to do with it: Links are checked with `safeReturnTo`, so the root, the sign-in path, and anything that could leave the app are ignored. Pass -`rememberDeepLink(auth, path, { loginPath: "/sign-in" })` if your sign-in -screen isn't `/login`. A newer link replaces an older one. +`deepLinkHandler(auth, { loginPath: "/sign-in" })` if your sign-in screen +isn't `/login`. A newer link replaces an older one. + +`Stack.Protected`'s `redirectTo` only chooses the screen a turned-away link +goes to, such as `/login`. It doesn't keep the link, so `deepLinkHandler` is +still what opens it after the sign-in. There is no `?redirectTo=` parameter on Expo: the link waits in memory, not in the URL, and an app restart forgets it. @@ -618,20 +616,23 @@ export async function signInWithPassword(username: string, password: string) { } ``` -Guard the screens by `status`, since a locked session keeps its user. The -unlock screen comes before the sign-in screen, so a locked app opens on it, -and the sign-in screen stays open to a locked user for the password path: +Guard the screens with `isSignedIn` and `status`, since a locked session +keeps its user. The unlock screen comes before the sign-in screen, so a +locked app opens on it, and the sign-in screen stays open to a locked user +for the password path: ```tsx +import { isSignedIn } from "@monarcode/session-kit"; + function RootStack() { - const status = useAuth((state) => state.status); - const signedIn = status === "authenticated" || status === "refreshing"; + const signedIn = useAuth(isSignedIn); + const locked = useAuth((state) => state.status === "locked"); return ( - + diff --git a/site/content/docs/(latest)/setups/react-router.mdx b/site/content/docs/(latest)/setups/react-router.mdx index 88e40b4..b408253 100644 --- a/site/content/docs/(latest)/setups/react-router.mdx +++ b/site/content/docs/(latest)/setups/react-router.mdx @@ -75,7 +75,7 @@ import { useSearchParams, } from "react-router"; -import { safeReturnTo } from "@monarcode/session-kit"; +import { isSignedIn, safeReturnTo } from "@monarcode/session-kit"; import { AuthProvider, useAuth } from "@monarcode/session-kit/react"; import { SessionOutlet } from "@monarcode/session-kit/react-router"; import { createRoot } from "react-dom/client"; @@ -95,7 +95,6 @@ declare module "@monarcode/session-kit" { function Private() { return ( Checking session…

} unavailable={({ error, retry }) => (
@@ -109,10 +108,7 @@ function Private() { /** Signing in changes the state, which renders this again and redirects. */ function Login() { - const signedIn = useAuth( - (state) => - state.status === "authenticated" || state.status === "refreshing", - ); + const signedIn = useAuth(isSignedIn); const [search] = useSearchParams(); if (signedIn) return ; @@ -136,9 +132,11 @@ createRoot(document.getElementById("root")!).render( ``` `SessionOutlet` shows `pending` while the saved session is restored, sends -signed-out users to `loginPath` with `redirectTo` set to where they were -going, and renders `unavailable` after a failed refresh. Without -`unavailable`, the error is thrown to the nearest error boundary. +signed-out users to `loginPath` (`/login` unless you pass another) with +`redirectTo` set to where they were going, and renders `unavailable` after a +failed refresh. Without `unavailable`, the error is thrown to the nearest +error boundary. With another sign-in page, pass the same `loginPath` to +`SessionOutlet` and `requireSession`. `safeReturnTo` accepts only same-origin paths and returns `/` for anything else, including the sign-in page itself, so a stale `redirectTo` can't loop. @@ -210,25 +208,13 @@ export const router = createBrowserRouter([ children: [ { path: "/login", - loader: async ({ request }) => { - const redirectTo = new URL(request.url).searchParams.get( - "redirectTo", - ); - await redirectIfSignedIn(auth, { redirectTo }); - return null; - }, + loader: redirectIfSignedIn(auth), element: , }, { - loader: ({ request }) => - requireSession(auth, { request, loginPath: "/login" }), + loader: requireSession(auth), errorElement: , - element: ( - Checking session…

} - /> - ), + element: Checking session…

} />, children: [{ index: true, element: }], }, ], @@ -266,8 +252,9 @@ createRoot(document.getElementById("root")!).render( Three pieces work together: -- **`requireSession`** redirects signed-out users to `loginPath` with - `redirectTo`, and returns `{ session }` as the route's loader data. A failed +- **`requireSession(auth)`** is the route's loader. It redirects signed-out + users to `/login` with `redirectTo`, and returns `{ session }` as the + route's loader data. Pass `{ loginPath }` for another sign-in page. A failed refresh is rethrown for the route's error element instead: the user is still signed in. - **`useAuthRevalidation`** runs the loaders again after a sign-in, a @@ -363,14 +350,10 @@ import { import { auth } from "../auth.js"; -export function clientLoader({ request }: { request: Request }) { - return requireSession(auth, { request, loginPath: "/login" }); -} +export const clientLoader = requireSession(auth); export default function Protected() { - return ( - Checking session…

} /> - ); + return Checking session…

} />; } /** Shown after a failed refresh; a repeated failure shows here again. */ @@ -397,11 +380,7 @@ import { redirectIfSignedIn } from "@monarcode/session-kit/react-router"; import { auth } from "../auth.js"; import { SignIn } from "../sign-in.js"; -export async function clientLoader({ request }: { request: Request }) { - const redirectTo = new URL(request.url).searchParams.get("redirectTo"); - await redirectIfSignedIn(auth, { redirectTo }); - return null; -} +export const clientLoader = redirectIfSignedIn(auth); export default function Login() { const navigate = useNavigate(); @@ -462,7 +441,7 @@ export function Dashboard() { {/* Keyed by session, so one account's choices never show for the next. */}
- Checking session…

} /> + Checking session…

} />
); diff --git a/site/content/docs/(latest)/setups/tanstack-router.mdx b/site/content/docs/(latest)/setups/tanstack-router.mdx index 590a0dd..f6fbb89 100644 --- a/site/content/docs/(latest)/setups/tanstack-router.mdx +++ b/site/content/docs/(latest)/setups/tanstack-router.mdx @@ -132,7 +132,7 @@ import { export const Route = createFileRoute("/_authenticated")({ beforeLoad: ({ context, location }) => - requireSession(context.auth, { location, loginPath: "/login" }), + requireSession(context.auth, { location }), errorComponent: SessionError, component: () => Checking session…

} />, }); @@ -149,8 +149,9 @@ function SessionError({ error }: ErrorComponentProps) { } ``` -`requireSession` redirects signed-out users to `loginPath` with `redirectTo` -set to where they were going, and puts `{ session }` in route context. A +`requireSession` redirects signed-out users to `/login`, or the `loginPath` +you pass, with `redirectTo` set to where they were going, and puts +`{ session }` in route context. A failed refresh reaches the error component instead of a redirect, because the user is still signed in. diff --git a/site/content/docs/(latest)/setups/tanstack-start.mdx b/site/content/docs/(latest)/setups/tanstack-start.mdx index 26a6b6a..4995caa 100644 --- a/site/content/docs/(latest)/setups/tanstack-start.mdx +++ b/site/content/docs/(latest)/setups/tanstack-start.mdx @@ -279,7 +279,7 @@ import { createFileRoute } from "@tanstack/react-router"; export const Route = createFileRoute("/_authenticated")({ beforeLoad: ({ context, location }) => - requireSession(context.auth, { location, loginPath: "/login" }), + requireSession(context.auth, { location }), component: () => Loading…

} />, }); ``` diff --git a/src/core/return-to.ts b/src/core/return-to.ts index d7c1d4b..e0ea9d9 100644 --- a/src/core/return-to.ts +++ b/src/core/return-to.ts @@ -1,5 +1,8 @@ import { AuthError } from "./errors.js"; +/** The sign-in page's path when a guard or `safeReturnTo` isn't told. */ +export const LOGIN_PATH = "/login"; + /** * Options for {@link safeReturnTo}. * @@ -72,7 +75,7 @@ export function safeReturnTo( value: unknown, options: SafeReturnToOptions = {}, ): string { - const loginPaths = [options.loginPath ?? "/login"].flat(); + const loginPaths = [options.loginPath ?? LOGIN_PATH].flat(); for (const path of loginPaths) { if (!path.startsWith("/")) throw new AuthError( diff --git a/src/core/signed-in.ts b/src/core/signed-in.ts new file mode 100644 index 0000000..4c17e84 --- /dev/null +++ b/src/core/signed-in.ts @@ -0,0 +1,27 @@ +import type { AuthState } from "./types.js"; + +/** + * Whether someone is signed in: `true` while `authenticated` or `refreshing`. + * It narrows `state`, so `state.user` is set when it's `true`. + * + * Check this rather than `status === "authenticated"`, which is `false` for a + * moment while an expired access token refreshes. A `locked` session is + * `false`. It has a user, but no access until it's unlocked. + * + * @example + * ```ts + * import { isSignedIn, type AuthClient } from "@monarcode/session-kit"; + * + * declare const auth: AuthClient<{ name: string }, { name: string }>; + * + * const state = auth.state.get(); + * if (isSignedIn(state)) console.log(state.user.name); + * ``` + * + * @since 0.1.0 + */ +export function isSignedIn( + state: AuthState, +): state is Extract, { status: "authenticated" | "refreshing" }> { + return state.status === "authenticated" || state.status === "refreshing"; +} diff --git a/src/effect/auth.ts b/src/effect/auth.ts index 0e51705..ed5f04e 100644 --- a/src/effect/auth.ts +++ b/src/effect/auth.ts @@ -108,10 +108,11 @@ export type RegisteredSession = SessionOf; * * @example * ```ts + * import { isSignedIn } from "@monarcode/session-kit"; * import type { RegisteredState } from "@monarcode/session-kit/effect"; * - * export const signedIn = (state: RegisteredState) => - * state.status === "authenticated" || state.status === "refreshing"; + * export const signedInUser = (state: RegisteredState) => + * isSignedIn(state) ? state.user : null; * ``` * * @since 0.1.0 diff --git a/src/expo/deep-link.ts b/src/expo/deep-link.ts index d44e3be..6ad98e1 100644 --- a/src/expo/deep-link.ts +++ b/src/expo/deep-link.ts @@ -147,6 +147,67 @@ export function rememberDeepLink( linkOf(auth).set({ path, waiting: false }); } +/** + * The `redirectSystemPath` that {@link deepLinkHandler} makes, for + * `app/+native-intent.tsx`. + * + * @example + * ```ts + * import type { AuthClient } from "@monarcode/session-kit"; + * import { + * deepLinkHandler, + * type DeepLinkHandler, + * } from "@monarcode/session-kit/expo"; + * + * declare const auth: AuthClient<{ name: string }, { name: string }>; + * + * export const redirectSystemPath: DeepLinkHandler = deepLinkHandler(auth); + * ``` + * + * @since 0.1.0 + */ +export type DeepLinkHandler = (event: { + path: string; + initial: boolean; +}) => string; + +/** + * Makes `redirectSystemPath` for `app/+native-intent.tsx`. It keeps each + * incoming link with {@link rememberDeepLink}, so `SessionGate` opens it + * after sign-in, and returns the path unchanged. + * + * Use `rememberDeepLink` itself when your `redirectSystemPath` does more, + * such as rewriting old links. + * + * Throws `INVALID_OPTIONS` for a `loginPath` that doesn't start with `/`. + * It throws when it's made, so a link never meets the error. + * + * @example + * ```ts + * // app/+native-intent.tsx + * import type { AuthClient } from "@monarcode/session-kit"; + * import { deepLinkHandler } from "@monarcode/session-kit/expo"; + * + * declare const auth: AuthClient<{ name: string }, { name: string }>; + * + * export const redirectSystemPath = deepLinkHandler(auth); + * ``` + * + * @since 0.1.0 + */ +export function deepLinkHandler( + auth: AuthSource, + options: RememberDeepLinkOptions = {}, +): DeepLinkHandler { + // Checked now: Expo Router warns that a throw on a link can crash the app, + // and with good options, remembering a link doesn't throw. + safeReturnTo("/", options); + return ({ path }) => { + rememberDeepLink(auth, path, options); + return path; + }; +} + /** * What a change of status or screen does to a remembered link. A sign-in opens * a waiting link, and while signed out or locked the link waits. Restoring and diff --git a/src/expo/gate.ts b/src/expo/gate.ts index e47d6f7..477953e 100644 --- a/src/expo/gate.ts +++ b/src/expo/gate.ts @@ -167,7 +167,7 @@ function useAccountKey(sessionId: string | null): number { * @example * ```tsx * // Rendered inside `AuthProvider` in app/_layout.tsx. - * import type { AuthClient } from "@monarcode/session-kit"; + * import { isSignedIn, type AuthClient } from "@monarcode/session-kit"; * import { SessionGate } from "@monarcode/session-kit/expo"; * import { createAuthHooks } from "@monarcode/session-kit/react"; * import { SplashScreen, Stack } from "expo-router"; @@ -178,10 +178,7 @@ function useAccountKey(sessionId: string | null): number { * void SplashScreen.preventAutoHideAsync(); * * export function RootNavigator() { - * // `status`, not `user`: a locked session keeps its user. - * const signedIn = useAuth( - * ({ status }) => status === "authenticated" || status === "refreshing", - * ); + * const signedIn = useAuth(isSignedIn); * return ( * * diff --git a/src/expo/index.ts b/src/expo/index.ts index 7f76e3f..be441b0 100644 --- a/src/expo/index.ts +++ b/src/expo/index.ts @@ -1,7 +1,7 @@ -export { rememberDeepLink } from "./deep-link.js"; +export { deepLinkHandler, rememberDeepLink } from "./deep-link.js"; export { SessionGate } from "./gate.js"; export { secureStorage } from "./secure-storage.js"; -export type { RememberDeepLinkOptions } from "./deep-link.js"; +export type { DeepLinkHandler, RememberDeepLinkOptions } from "./deep-link.js"; export type { SessionGateProps, UnavailableProps } from "./gate.js"; export type { SecureStorageOptions } from "./secure-storage.js"; diff --git a/src/index.ts b/src/index.ts index 51c6349..c33cd25 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,6 +2,7 @@ export { createAuth } from "./core/client.js"; export { AuthError } from "./core/errors.js"; export { createMirrorAuth } from "./core/mirror.js"; export { loginHref, safeReturnTo } from "./core/return-to.js"; +export { isSignedIn } from "./core/signed-in.js"; export { fromAccessToken } from "./core/sources.js"; export { memoryStorage, webStorage } from "./core/storage.js"; diff --git a/src/next/index.ts b/src/next/index.ts index 1bf368e..1be417c 100644 --- a/src/next/index.ts +++ b/src/next/index.ts @@ -1,5 +1,5 @@ import { AuthError } from "../core/errors.js"; -import { loginHref, safeReturnTo } from "../core/return-to.js"; +import { LOGIN_PATH, loginHref, safeReturnTo } from "../core/return-to.js"; import type { Session } from "../core/types.js"; import { refreshBeforeRendering, @@ -367,7 +367,7 @@ export function nextSession( "INVALID_OPTIONS", "Pass cookies from next/headers and redirect from next/navigation", ); - const loginPath = options.loginPath ?? "/login"; + const loginPath = options.loginPath ?? LOGIN_PATH; // Fails fast on bad options, before any request. loginHref(loginPath, "/"); const within = refreshWithin({ within: options.within }); diff --git a/src/react-router/guards.ts b/src/react-router/guards.ts index 513ca78..a786cdb 100644 --- a/src/react-router/guards.ts +++ b/src/react-router/guards.ts @@ -5,7 +5,7 @@ import { sessionOrNull, type GuardClient, } from "../core/guard.js"; -import { loginHref, safeReturnTo } from "../core/return-to.js"; +import { LOGIN_PATH, loginHref, safeReturnTo } from "../core/return-to.js"; import type { Session } from "../core/types.js"; import { stripBasename } from "./basename.js"; @@ -23,21 +23,46 @@ import { stripBasename } from "./basename.js"; * // For a router created with `{ basename: "/app" }`. * export const options: RequireSessionOptions = { * request, - * loginPath: "/login", + * loginPath: "/sign-in", * basename: "/app", * }; * ``` * * @since 0.1.0 */ -export type RequireSessionOptions = { +export type RequireSessionOptions = RequireSessionLoaderOptions & { /** * The loader's `request`. Signed-out users come back to its URL after * signing in. */ request: Request; - /** Your sign-in page's path, starting with `/`, such as `"/login"`. */ - loginPath: string; +}; + +/** + * Options for the loader that `requireSession(auth, options)` makes. + * + * @example + * ```ts + * import type { + * RequireSessionLoaderOptions, + * } from "@monarcode/session-kit/react-router"; + * + * // For a router created with `{ basename: "/app" }`. + * export const options: RequireSessionLoaderOptions = { + * loginPath: "/sign-in", + * basename: "/app", + * }; + * ``` + * + * @since 0.1.0 + */ +export type RequireSessionLoaderOptions = { + /** + * Your sign-in page's path, starting with `/`. Use the same one as + * `SessionOutlet`'s. + * @default "/login" + */ + loginPath?: string | undefined; /** * The router's `basename`, if it has one. Loaders see URLs that include * it, but redirects add it again, so `redirectTo` must leave it out. @@ -45,9 +70,34 @@ export type RequireSessionOptions = { basename?: string | undefined; }; +/** + * The loader that `requireSession(auth)` makes. It resolves `{ session }`, + * typed with the client's user. + * + * @example + * ```ts + * import type { AuthClient } from "@monarcode/session-kit"; + * import { + * requireSession, + * type RequireSessionLoader, + * } from "@monarcode/session-kit/react-router"; + * + * type User = { name: string }; + * declare const auth: AuthClient; + * + * export const loader: RequireSessionLoader = requireSession(auth); + * ``` + * + * @since 0.1.0 + */ +export type RequireSessionLoader = (args: { + request: Request; +}) => Promise<{ session: Session }>; + /** * Guards a route in its loader, in data or framework mode, so only * signed-in users get through. They get `{ session }`, which holds no tokens. + * `requireSession(auth)` is the loader itself. * * Signed-out users go to `loginPath`, with `?redirectTo=` set to the URL they * asked for. A locked session counts as signed out, as locking is for native @@ -72,9 +122,8 @@ export type RequireSessionOptions = { * * export const router = createBrowserRouter([ * { - * loader: ({ request }) => - * requireSession(auth, { request, loginPath: "/login" }), - * element: , + * loader: requireSession(auth), + * element: , * children: [{ index: true, element:

Signed in

}], * }, * ]); @@ -82,19 +131,70 @@ export type RequireSessionOptions = { * * @since 0.1.0 */ -export async function requireSession( +export function requireSession( auth: GuardClient, options: RequireSessionOptions, -): Promise<{ session: Session }> { - // Fails fast on a bad path, before any session is read. - loginHref(options.loginPath, "/"); +): Promise<{ session: Session }>; +/** + * The guard as a loader of its own, for `loader` or `clientLoader`. Pass + * `loginPath` or `basename` when they aren't the defaults. + * + * It returns the loader, so pass it as one. Inside a loader of your own, + * call the form that takes `request`: awaiting this one checks nothing. + * + * Throws `INVALID_OPTIONS` when it's made, for a `loginPath` that doesn't + * start with `/` or a bad `basename`. + * + * @example + * ```ts + * import type { AuthClient } from "@monarcode/session-kit"; + * import { requireSession } from "@monarcode/session-kit/react-router"; + * + * declare const auth: AuthClient<{ name: string }, { name: string }>; + * + * export const clientLoader = requireSession(auth, { loginPath: "/sign-in" }); + * ``` + * + * @since 0.1.0 + */ +export function requireSession( + auth: GuardClient, + options?: RequireSessionLoaderOptions, +): RequireSessionLoader; +export function requireSession( + auth: GuardClient, + options: Partial = {}, +): RequireSessionLoader | Promise<{ session: Session }> { + const { request, ...rest } = options; + if (request) + return (async () => { + checkPaths(rest); + return guard(auth, request, rest); + })(); + checkPaths(rest); + return (args) => guard(auth, args.request, rest); +} + +/** Fails fast on a bad path, before any session is read. */ +function checkPaths(options: RequireSessionLoaderOptions) { + loginHref(options.loginPath ?? LOGIN_PATH, "/"); stripBasename("/", options.basename); +} + +async function guard( + auth: GuardClient, + request: Request, + options: RequireSessionLoaderOptions, +): Promise<{ session: Session }> { const session = await guardSession(auth); if (!session) { - const url = new URL(options.request.url); + const url = new URL(request.url); const path = stripBasename(url.pathname, options.basename); throw redirect( - loginHref(options.loginPath, path + url.search + url.hash), + loginHref( + options.loginPath ?? LOGIN_PATH, + path + url.search + url.hash, + ), ); } return { session }; @@ -120,12 +220,32 @@ export async function requireSession( * * @since 0.1.0 */ -export type RedirectIfSignedInOptions = { +export type RedirectIfSignedInOptions = RedirectIfSignedInLoaderOptions & { /** * Where to send a signed-in user, usually the `redirectTo` search param. * It's checked with `safeReturnTo`. */ redirectTo: unknown; +}; + +/** + * Options for the loader that `redirectIfSignedIn(auth, options)` makes. + * + * @example + * ```ts + * import type { + * RedirectIfSignedInLoaderOptions, + * } from "@monarcode/session-kit/react-router"; + * + * // A sign-up page never returns to either sign-in page. + * export const options: RedirectIfSignedInLoaderOptions = { + * loginPath: ["/login", "/sign-up"], + * }; + * ``` + * + * @since 0.1.0 + */ +export type RedirectIfSignedInLoaderOptions = { /** * Your sign-in page's path, or several. `redirectTo` never sends the user * back to one. @@ -134,38 +254,97 @@ export type RedirectIfSignedInOptions = { loginPath?: string | readonly string[] | undefined; }; +/** + * The loader that `redirectIfSignedIn(auth)` makes. It reads `redirectTo` + * from the request's URL, and resolves `null` for a signed-out user. + * + * @example + * ```ts + * import type { AuthClient } from "@monarcode/session-kit"; + * import { + * redirectIfSignedIn, + * type RedirectIfSignedInLoader, + * } from "@monarcode/session-kit/react-router"; + * + * declare const auth: AuthClient<{ name: string }, { name: string }>; + * + * export const loader: RedirectIfSignedInLoader = redirectIfSignedIn(auth); + * ``` + * + * @since 0.1.0 + */ +export type RedirectIfSignedInLoader = (args: { + request: Request; +}) => Promise; + /** * Guards your sign-in page in its loader, so a signed-in user goes straight - * to `redirectTo`, made safe with `safeReturnTo`. + * to `redirectTo`, made safe with `safeReturnTo`. `redirectIfSignedIn(auth)` + * is the loader itself, and reads `redirectTo` from the URL's search. * * If the session can't be read, such as after a failed refresh or while * locked, the sign-in page shows, so the user can sign in again. * * @example * ```ts - * import type { LoaderFunctionArgs } from "react-router"; * import type { AuthClient } from "@monarcode/session-kit"; * import { redirectIfSignedIn } from "@monarcode/session-kit/react-router"; * - * type User = { name: string }; - * declare const auth: AuthClient; + * declare const auth: AuthClient<{ name: string }, { name: string }>; * - * export async function loginLoader({ request }: LoaderFunctionArgs) { - * const redirectTo = new URL(request.url).searchParams.get("redirectTo"); - * await redirectIfSignedIn(auth, { redirectTo }); - * return null; - * } + * // The sign-in route. + * export const clientLoader = redirectIfSignedIn(auth); * ``` * * @since 0.1.0 */ -export async function redirectIfSignedIn( +export function redirectIfSignedIn( auth: GuardClient, options: RedirectIfSignedInOptions, +): Promise; +/** + * The guard as a loader of its own, for `loader` or `clientLoader`, with + * `redirectTo` read from the URL's search. + * + * It returns the loader, so pass it as one. Inside a loader of your own, + * call the form that takes `redirectTo`: awaiting this one checks nothing. + * + * @example + * ```ts + * import type { AuthClient } from "@monarcode/session-kit"; + * import { redirectIfSignedIn } from "@monarcode/session-kit/react-router"; + * + * declare const auth: AuthClient<{ name: string }, { name: string }>; + * + * export const loader = redirectIfSignedIn(auth, { + * loginPath: ["/login", "/sign-up"], + * }); + * ``` + * + * @since 0.1.0 + */ +export function redirectIfSignedIn( + auth: GuardClient, + options?: RedirectIfSignedInLoaderOptions, +): RedirectIfSignedInLoader; +export function redirectIfSignedIn( + auth: GuardClient, + options: Partial = {}, +): RedirectIfSignedInLoader | Promise { + if ("redirectTo" in options) + return sendOn(auth, options.redirectTo, options.loginPath); + return async ({ request }) => { + const redirectTo = new URL(request.url).searchParams.get("redirectTo"); + await sendOn(auth, redirectTo, options.loginPath); + return null; + }; +} + +async function sendOn( + auth: GuardClient, + redirectTo: unknown, + loginPath: string | readonly string[] | undefined, ): Promise { - if (await sessionOrNull(auth)) { - throw redirect( - safeReturnTo(options.redirectTo, { loginPath: options.loginPath }), - ); - } + if (await sessionOrNull(auth)) + throw redirect(safeReturnTo(redirectTo, { loginPath })); } diff --git a/src/react-router/index.ts b/src/react-router/index.ts index eb12f47..6acf248 100644 --- a/src/react-router/index.ts +++ b/src/react-router/index.ts @@ -3,7 +3,11 @@ export { SessionOutlet } from "./outlet.js"; export { useAuthRevalidation } from "./revalidation.js"; export type { + RedirectIfSignedInLoader, + RedirectIfSignedInLoaderOptions, RedirectIfSignedInOptions, + RequireSessionLoader, + RequireSessionLoaderOptions, RequireSessionOptions, } from "./guards.js"; export type { SessionOutletProps } from "./outlet.js"; diff --git a/src/react-router/outlet.ts b/src/react-router/outlet.ts index 292741a..0081cdd 100644 --- a/src/react-router/outlet.ts +++ b/src/react-router/outlet.ts @@ -13,7 +13,7 @@ import { useLocation, } from "react-router"; -import { loginHref } from "../core/return-to.js"; +import { LOGIN_PATH, loginHref } from "../core/return-to.js"; import { renderUnavailable, useAdapterClient, @@ -31,7 +31,7 @@ import { * * export const layout = ( * Restoring session…

} * unavailable={({ error, retry }) => ( *
@@ -46,8 +46,12 @@ import { * @since 0.1.0 */ export type SessionOutletProps = { - /** Your sign-in page's path, starting with `/`, such as `"/login"`. */ - loginPath: string; + /** + * Your sign-in page's path, starting with `/`. Use the same one as + * `requireSession`'s. + * @default "/login" + */ + loginPath?: string | undefined; /** * Shown while the saved session is read and, in data mode, until the * loader has accepted a new session. @@ -109,7 +113,7 @@ function useGuardedSessionId(): string | undefined { * // Declarative mode, inside `AuthProvider` and `BrowserRouter`. * export const routes = ( * - * }> + * }> * Signed in

} /> *
* Sign in

} /> @@ -120,7 +124,7 @@ function useGuardedSessionId(): string | undefined { * @since 0.1.0 */ export function SessionOutlet({ - loginPath, + loginPath = LOGIN_PATH, pending = null, unavailable, client, diff --git a/src/react-router/server.ts b/src/react-router/server.ts index 5ee2a84..ad23d60 100644 --- a/src/react-router/server.ts +++ b/src/react-router/server.ts @@ -1,9 +1,11 @@ import { AuthError } from "../core/errors.js"; import { + LOGIN_PATH, loginHref, safeReturnTo, type SafeReturnToOptions, } from "../core/return-to.js"; +import { isSignedIn } from "../core/signed-in.js"; import type { Session } from "../core/types.js"; import { middlewareOptions, @@ -414,7 +416,7 @@ export function requireSession( serverAuth: ServerAuth, options: SessionGuardOptions = {}, ): SessionGuard { - const { loginPath = "/login", basename } = options; + const { loginPath = LOGIN_PATH, basename } = options; // Fails fast on bad paths, before any request. loginHref(loginPath, "/"); stripBasename("/", basename); @@ -444,7 +446,7 @@ export function requireSession( "Read the session where requireSession guards the route: list it in the middleware of this route or a route above it", ); const state = serverAuth.forRequest(jar).state.get(); - if (state.status === "authenticated" || state.status === "refreshing") + if (isSignedIn(state)) return Object.freeze({ sessionId: state.sessionId, user: state.user, diff --git a/src/react/context.ts b/src/react/context.ts index 9f21a7d..ab7798b 100644 --- a/src/react/context.ts +++ b/src/react/context.ts @@ -36,11 +36,11 @@ export function useMountEffect( * * @example * ```ts + * import { isSignedIn } from "@monarcode/session-kit"; * import type { AuthSource } from "@monarcode/session-kit/react"; * - * export function isSignedIn(auth: AuthSource): boolean { - * const { status } = auth.state.get(); - * return status === "authenticated" || status === "refreshing"; + * export function signedInNow(auth: AuthSource): boolean { + * return isSignedIn(auth.state.get()); * } * ``` * @@ -148,7 +148,7 @@ export type RetryableSource = AuthSource & * } * * export const layout = ( - * + * * ); * ``` * diff --git a/src/tanstack-router/guards.ts b/src/tanstack-router/guards.ts index b95f325..2db9699 100644 --- a/src/tanstack-router/guards.ts +++ b/src/tanstack-router/guards.ts @@ -5,7 +5,7 @@ import { sessionOrNull, type GuardClient, } from "../core/guard.js"; -import { loginHref, safeReturnTo } from "../core/return-to.js"; +import { LOGIN_PATH, loginHref, safeReturnTo } from "../core/return-to.js"; import type { Session } from "../core/types.js"; /** @@ -21,7 +21,7 @@ import type { Session } from "../core/types.js"; * * export const options: RequireSessionOptions = { * location, - * loginPath: "/login", + * loginPath: "/sign-in", * }; * ``` * @@ -33,8 +33,11 @@ export type RequireSessionOptions = { * come back to it after signing in. */ location: { href: string }; - /** Your sign-in page's path, starting with `/`, such as `"/login"`. */ - loginPath: string; + /** + * Your sign-in page's path, starting with `/`. + * @default "/login" + */ + loginPath?: string | undefined; }; /** @@ -74,8 +77,8 @@ export type RequireSessionOptions = { * getParentRoute: () => rootRoute, * id: "authenticated", * beforeLoad: ({ context, location }) => - * requireSession(context.auth, { location, loginPath: "/login" }), - * component: () => Checking session…

} />, + * requireSession(context.auth, { location }), + * component: SessionOutlet, * }); * ``` * @@ -85,13 +88,12 @@ export async function requireSession( auth: GuardClient, options: RequireSessionOptions, ): Promise<{ session: Session }> { + const loginPath = options.loginPath ?? LOGIN_PATH; // Fails fast on a bad path, before any session is read. - loginHref(options.loginPath, "/"); + loginHref(loginPath, "/"); const session = await guardSession(auth); if (!session) - throw redirect({ - href: loginHref(options.loginPath, options.location.href), - }); + throw redirect({ href: loginHref(loginPath, options.location.href) }); return { session }; } diff --git a/src/tanstack-router/outlet.ts b/src/tanstack-router/outlet.ts index f4a7dcb..5f0f9cb 100644 --- a/src/tanstack-router/outlet.ts +++ b/src/tanstack-router/outlet.ts @@ -7,7 +7,8 @@ import { import { Outlet, useMatch, useRouter } from "@tanstack/react-router"; -import type { AuthStatus } from "../core/types.js"; +import { isSignedIn } from "../core/signed-in.js"; +import type { AuthState } from "../core/types.js"; import { assertAuthSource, useAuthState, @@ -80,7 +81,7 @@ export type SessionOutletProps = { * getParentRoute: () => rootRoute, * id: "authenticated", * beforeLoad: ({ context, location }) => - * requireSession(context.auth, { location, loginPath: "/login" }), + * requireSession(context.auth, { location }), * component: () => Checking session…

} />, * }); * ``` @@ -97,15 +98,9 @@ export function SessionOutlet({ auth, "Provide an auth client in Router context or AuthProvider before rendering SessionOutlet", ); - const signedIn = useAuthState(auth, (state) => { - const { status, sessionId } = state as { - status: AuthStatus; - sessionId: string | null; - }; - // `status`, not `user`, as a locked session still has a user. - return status === "authenticated" || status === "refreshing" - ? sessionId - : null; + const signedIn = useAuthState(auth, (value) => { + const state = value as AuthState; + return isSignedIn(state) ? state.sessionId : null; }); // The nearest match is this route's, whose context holds what its guard // returned. diff --git a/tests/consumer.ts b/tests/consumer.ts index 19109b7..12fc052 100644 --- a/tests/consumer.ts +++ b/tests/consumer.ts @@ -8,6 +8,7 @@ import type { import * as Fetch from "@monarcode/effetch"; import { createRootRouteWithContext, + createRoute, createRouter, } from "@tanstack/react-router"; import { createMiddleware, createStart } from "@tanstack/react-start"; @@ -38,6 +39,7 @@ import { createAuth, createMirrorAuth, fromAccessToken, + isSignedIn, memoryStorage, webStorage, type AuthClient, @@ -203,6 +205,24 @@ async function guard() { } void guard; +// A route's guard: loginPath defaults to "/login". +createRoute({ + getParentRoute: () => root, + id: "guarded", + beforeLoad: ({ context, location }) => + requireSession(context.auth, { location }), + component: SessionOutlet, +}); + +// isSignedIn narrows the state, and is a selector as it is. +const signedInNow: boolean = useAuth(isSignedIn); +void signedInNow; +const someState = auth.state.get(); +if (isSignedIn(someState)) { + const email: string = someState.user.email; + void email; +} + function Component() { const email: string | undefined = useAuth((state) => state.user?.email); const client = useAuthClient(); @@ -357,11 +377,28 @@ async function loader({ request }: { request: Request }) { return email; } void loader; +// loginPath defaults to "/login" in the immediate form too. +export async function defaultLoader({ request }: { request: Request }) { + const { session } = await reactRouter.requireSession(auth, { request }); + const email: string = session.user.email; + return email; +} +// The loader forms, typed by the client. +const guardLoader: LoaderFunction = reactRouter.requireSession(auth); +void guardLoader; +const shortLoader = reactRouter.requireSession(auth, { basename: "/app" }); +export async function useShortLoader(request: Request) { + const email: string = (await shortLoader({ request })).session.user.email; + return email; +} +const signInLoader: LoaderFunction = reactRouter.redirectIfSignedIn(auth); +void signInLoader; +// @ts-expect-error The immediate form needs redirectTo. +void reactRouter.redirectIfSignedIn(auth, { loginPath: "/x" }).then(() => {}); reactRouter.SessionOutlet({ loginPath: "/login", unavailable: ({ error, retry }) => `${error?.code}${String(retry)}`, }); -// @ts-expect-error The outlet needs the sign-in path. reactRouter.SessionOutlet({}); // `AuthClient` needs both the user and its input, so `updateUser` is never @@ -409,6 +446,10 @@ expo.SessionGate({ client: { state: expoAuth.state, mount: expoAuth.mount } }); expo.rememberDeepLink(expoAuth, "myapp://orders/42", { loginPath: "/sign-in" }); // @ts-expect-error The deep link is kept for one client. expo.rememberDeepLink("myapp://orders/42"); +export const redirectSystemPath: (event: { + path: string; + initial: boolean; +}) => Promise | string | null = expo.deepLinkHandler(expoAuth); // Locking: `true`, or the app's `seal` and `open`, which may be async. createAuth({ ...debugBase, locking: true }); diff --git a/tests/expo-modules.ts b/tests/expo-modules.ts index a1a26ab..0b523f4 100644 --- a/tests/expo-modules.ts +++ b/tests/expo-modules.ts @@ -26,5 +26,5 @@ registerHooks({ }, }); -export const { rememberDeepLink, SessionGate, secureStorage } = +export const { deepLinkHandler, rememberDeepLink, SessionGate, secureStorage } = await import("@monarcode/session-kit/expo"); diff --git a/tests/gate.test.ts b/tests/gate.test.ts index 60cc371..511e5c7 100644 --- a/tests/gate.test.ts +++ b/tests/gate.test.ts @@ -23,7 +23,11 @@ import { createAuthHooks } from "@monarcode/session-kit/react"; import { deferredStorage } from "./deferred-storage.ts"; import { act, render, settle, user, userSchema, useDom } from "./dom.ts"; -import { rememberDeepLink, SessionGate } from "./expo-modules.ts"; +import { + deepLinkHandler, + rememberDeepLink, + SessionGate, +} from "./expo-modules.ts"; import { lockable } from "./helpers.ts"; import { navigation } from "./mocks/expo-router.ts"; import { appState } from "./mocks/react-native.ts"; @@ -220,6 +224,39 @@ test("opens a link kept while signed out, once, after the sign-in", async () => assert.equal(navigation.replaced.length, 1); }); +test("deepLinkHandler remembers each link and returns its path", async () => { + const auth = newClient(); + const redirectSystemPath = deepLinkHandler(auth, { loginPath: "/sign-in" }); + navigation.go("/sign-in"); + await renderGate(auth); + let returned = ""; + await act(async () => { + returned = redirectSystemPath({ + path: "myapp://orders/7", + initial: false, + }); + }); + assert.equal(returned, "myapp://orders/7"); + await act(() => auth.signIn({ accessToken: "access-1", user })); + assert.deepEqual(navigation.replaced, ["/orders/7"]); + assert.throws( + () => deepLinkHandler(auth, { loginPath: "sign-in" }), + (error: AuthError) => error.code === "INVALID_OPTIONS", + ); +}); + +test("deepLinkHandler without options drops links to /login", async () => { + const auth = newClient(); + const redirectSystemPath = deepLinkHandler(auth); + navigation.go("/login"); + await renderGate(auth); + await act(async () => { + redirectSystemPath({ path: "myapp://login", initial: true }); + }); + await act(() => auth.signIn({ accessToken: "access-1", user })); + assert.deepEqual(navigation.replaced, []); +}); + test("keeps a link that arrived before the session was restored", async () => { const auth = newClient(deferredStorage(memoryStorage())); rememberDeepLink(auth, "https://example.com/orders/42"); diff --git a/tests/react-router.test.ts b/tests/react-router.test.ts index 1972530..0017795 100644 --- a/tests/react-router.test.ts +++ b/tests/react-router.test.ts @@ -47,13 +47,7 @@ function Root() { } /** A sign-in route loader that sends a signed-in user on to `redirectTo`. */ -const loginLoader = - (auth: Client) => - async ({ request }: { request: Request }) => { - const redirectTo = new URL(request.url).searchParams.get("redirectTo"); - await binding.redirectIfSignedIn(auth, { redirectTo }); - return null; - }; +const loginLoader = (auth: Client) => binding.redirectIfSignedIn(auth); /** A home page that counts its mounts and shows the user's email. */ const homePage = ( @@ -254,7 +248,7 @@ test("data mode: StrictMode lets a loader's refresh finish and sends the token o request, loginPath: "/login", }), - element: h(binding.SessionOutlet, { loginPath: "/login" }), + element: h(binding.SessionOutlet, {}), children: [{ index: true, element: "home" }], }, ], @@ -290,7 +284,7 @@ test("declarative mode: SessionOutlet sends signed-out users to sign in", async h( Route, { - element: h(binding.SessionOutlet, { loginPath: "/login" }), + element: h(binding.SessionOutlet, {}), }, h(Route, { path: "/private", element: "private" }), ), @@ -416,16 +410,72 @@ test("data mode: loaders guard routes and re-run when auth changes", async () => assert.equal(view.container.textContent, "home:alice@example.com"); }); -test("loader guards redirect with the requested URL and never leave the site", async () => { +test("requireSession(auth) and redirectIfSignedIn(auth) are loaders themselves", async () => { const auth = newClient(); await auth.getSession(); - const request = new Request("https://auth.test/private?tab=2#top"); - const redirected = await binding - .requireSession(auth, { request, loginPath: "/login" }) + const request = new Request("https://auth.test/app/private?tab=2"); + const guard = binding.requireSession(auth, { basename: "/app" }); + const redirected = await guard({ request }).then( + () => assert.fail("Expected a redirect"), + (response: Response) => response, + ); + assert.equal( + redirected.headers.get("Location"), + "/login?redirectTo=%2Fprivate%3Ftab%3D2", + ); + await signIn(auth); + assert.deepEqual( + (await guard({ request })).session, + await auth.getSession(), + ); + const signInPage = binding.redirectIfSignedIn(auth, { + loginPath: ["/login", "/sign-up"], + }); + for (const [redirectTo, to] of [ + ["/orders", "/orders"], + ["/sign-up", "/"], + ] as const) { + const away = await signInPage({ + request: new Request( + `https://auth.test/login?redirectTo=${encodeURIComponent(redirectTo)}`, + ), + }).then( + () => assert.fail("Expected a redirect"), + (response: Response) => response, + ); + assert.equal(away.headers.get("Location"), to); + } + await auth.signOut(); + assert.equal( + await signInPage({ request: new Request("https://auth.test/login") }), + null, + ); + assert.throws(() => binding.requireSession(auth, { loginPath: "login" }), { + code: "INVALID_OPTIONS", + }); + assert.throws(() => binding.requireSession(auth, { basename: "app" }), { + code: "INVALID_OPTIONS", + }); + const elsewhere = await binding + .requireSession(auth, { loginPath: "/sign-in" })({ request }) .then( () => assert.fail("Expected a redirect"), (response: Response) => response, ); + assert.equal( + elsewhere.headers.get("Location"), + "/sign-in?redirectTo=%2Fapp%2Fprivate%3Ftab%3D2", + ); +}); + +test("loader guards redirect with the requested URL and never leave the site", async () => { + const auth = newClient(); + await auth.getSession(); + const request = new Request("https://auth.test/private?tab=2#top"); + const redirected = await binding.requireSession(auth, { request }).then( + () => assert.fail("Expected a redirect"), + (response: Response) => response, + ); assert.equal(redirected.status, 302); assert.equal( redirected.headers.get("Location"), diff --git a/tests/router.test.ts b/tests/router.test.ts index 222e34d..1ea83e0 100644 --- a/tests/router.test.ts +++ b/tests/router.test.ts @@ -289,8 +289,9 @@ const guardedRouter = async ( const privateRoute = createRoute({ getParentRoute: () => root, path: "/private", + // No loginPath: it defaults to "/login". beforeLoad: ({ context, location }) => - requireSession(context.auth, { location, loginPath: "/login" }), + requireSession(context.auth, { location }), }); const router = createRouter({ routeTree: root.addChildren([login, privateRoute]), diff --git a/tests/session.test.ts b/tests/session.test.ts index 33f3568..bab63f1 100644 --- a/tests/session.test.ts +++ b/tests/session.test.ts @@ -1,7 +1,14 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { createAuth, webStorage, type AuthError } from "@monarcode/session-kit"; +import { + createAuth, + isSignedIn, + webStorage, + type AuthError, + type AuthState, + type AuthStatus, +} from "@monarcode/session-kit"; import { z } from "zod"; import { @@ -643,3 +650,28 @@ test("mounting signs out of an invalid saved session at once, then discards it", assert.equal(auth.state.get().status, "unauthenticated"); assert.equal(values.size, 0); }); + +test("isSignedIn is true while authenticated or refreshing, not locked", async () => { + const expected: Record = { + initializing: false, + authenticated: true, + refreshing: true, + locked: false, + unauthenticated: false, + unavailable: false, + }; + for (const [status, signedIn] of Object.entries(expected)) + assert.equal( + isSignedIn({ status } as AuthState), + signedIn, + status, + ); + const auth = client(); + await auth.signIn(input()); + const state = auth.state.get(); + assert.ok(isSignedIn(state)); + // Narrowed: the user is set. + assert.equal(state.user.email, user.email); + await auth.signOut(); + assert.equal(isSignedIn(auth.state.get()), false); +}); From 1ba6763c16d0cb1fd73fd355e9e44ceff211fd97 Mon Sep 17 00:00:00 2001 From: monarcode Date: Sat, 14 Nov 2026 07:19:12 +0100 Subject: [PATCH 09/26] refactor(react-router): split the loader guards into their own functions - Add requireSessionLoader and redirectIfSignedInLoader in place of the loader overloads of requireSession and redirectIfSignedIn - Update the examples, the React Router guide and the reference --- CHANGELOG.md | 16 +- examples/react-router-data/src/main.tsx | 8 +- .../app/routes/login.tsx | 4 +- .../app/routes/protected.tsx | 4 +- .../content/docs/(latest)/reference/index.mdx | 2 +- .../docs/(latest)/reference/react-router.mdx | 20 ++- .../docs/(latest)/setups/react-router.mdx | 41 ++--- src/react-router/guards.ts | 148 +++++++++--------- src/react-router/index.ts | 7 +- tests/consumer.ts | 16 +- tests/react-router.test.ts | 28 ++-- 11 files changed, 160 insertions(+), 134 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 27c36e7..3018a0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -119,15 +119,17 @@ - `isSignedIn(state)` in `@monarcode/session-kit`: `true` while `authenticated` or `refreshing`, and `false` while `locked`. It narrows `user`, and works as a selector: `useAuth(isSignedIn)`. -- React Router's guards are loaders of their own: `requireSession(auth)` and - `redirectIfSignedIn(auth)` read the request, and the second reads - `redirectTo` from its URL. They take `RequireSessionLoaderOptions` and - `RedirectIfSignedInLoaderOptions`, and return `RequireSessionLoader` and - `RedirectIfSignedInLoader`. The forms that take `request` or `redirectTo` - stay, for a loader of your own: awaiting a loader form checks nothing. +- `requireSessionLoader(auth, options?)` and + `redirectIfSignedInLoader(auth, options?)` in + `@monarcode/session-kit/react-router` make the guards' loaders, for + `loader` or `clientLoader`. The second reads `?redirectTo=` from the URL. + Their options are `RequireSessionLoaderOptions` and + `RedirectIfSignedInLoaderOptions`, and they return `RequireSessionLoader` + and `RedirectIfSignedInLoader`. `requireSession` and `redirectIfSignedIn` + stay, for a loader that does more. ```ts - export const clientLoader = requireSession(auth); + export const clientLoader = requireSessionLoader(auth); ``` - `loginPath` defaults to `"/login"` in `requireSession` for TanStack Router diff --git a/examples/react-router-data/src/main.tsx b/examples/react-router-data/src/main.tsx index 59bd07b..5b8867a 100644 --- a/examples/react-router-data/src/main.tsx +++ b/examples/react-router-data/src/main.tsx @@ -11,8 +11,8 @@ import { import { safeReturnTo } from "@monarcode/session-kit"; import { AuthProvider } from "@monarcode/session-kit/react"; import { - redirectIfSignedIn, - requireSession, + redirectIfSignedInLoader, + requireSessionLoader, SessionOutlet, useAuthRevalidation, } from "@monarcode/session-kit/react-router"; @@ -62,11 +62,11 @@ const router = createBrowserRouter([ children: [ { path: "/login", - loader: redirectIfSignedIn(auth), + loader: redirectIfSignedInLoader(auth), element: , }, { - loader: requireSession(auth), + loader: requireSessionLoader(auth), errorElement: , element: } />, children: [{ index: true, element: }], diff --git a/examples/react-router-framework-spa/app/routes/login.tsx b/examples/react-router-framework-spa/app/routes/login.tsx index dc80c62..b0876bd 100644 --- a/examples/react-router-framework-spa/app/routes/login.tsx +++ b/examples/react-router-framework-spa/app/routes/login.tsx @@ -1,12 +1,12 @@ import { useNavigate, useSearchParams } from "react-router"; import { safeReturnTo } from "@monarcode/session-kit"; -import { redirectIfSignedIn } from "@monarcode/session-kit/react-router"; +import { redirectIfSignedInLoader } from "@monarcode/session-kit/react-router"; import { auth } from "../auth"; import { LoginForm } from "../ui"; -export const clientLoader = redirectIfSignedIn(auth); +export const clientLoader = redirectIfSignedInLoader(auth); export default function Login() { const navigate = useNavigate(); diff --git a/examples/react-router-framework-spa/app/routes/protected.tsx b/examples/react-router-framework-spa/app/routes/protected.tsx index 0fa1a6e..3cda2ed 100644 --- a/examples/react-router-framework-spa/app/routes/protected.tsx +++ b/examples/react-router-framework-spa/app/routes/protected.tsx @@ -1,14 +1,14 @@ import { useRouteError } from "react-router"; import { - requireSession, + requireSessionLoader, SessionOutlet, } from "@monarcode/session-kit/react-router"; import { auth } from "../auth"; import { Pending, Unavailable } from "../ui"; -export const clientLoader = requireSession(auth); +export const clientLoader = requireSessionLoader(auth); export default function Protected() { return } />; diff --git a/site/content/docs/(latest)/reference/index.mdx b/site/content/docs/(latest)/reference/index.mdx index 347008c..0897d2f 100644 --- a/site/content/docs/(latest)/reference/index.mdx +++ b/site/content/docs/(latest)/reference/index.mdx @@ -17,7 +17,7 @@ API. | [`@monarcode/session-kit`](/docs/reference/core) | `createAuth`, `createMirrorAuth`, `fromAccessToken`, `webStorage`, `memoryStorage`, `isSignedIn`, `safeReturnTo`, `loginHref`, `AuthError`, types | | [`@monarcode/session-kit/react`](/docs/reference/react) | `AuthProvider`, `useAuth`, `useAuthClient`, `createAuthHooks`, `useMirrorAuth`, types | | [`@monarcode/session-kit/tanstack-router`](/docs/reference/tanstack-router) | `connectAuth`, `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuth`, `useAuthClient`, types | -| [`@monarcode/session-kit/react-router`](/docs/reference/react-router) | `requireSession`, `redirectIfSignedIn`, `SessionOutlet`, `useAuthRevalidation`, types | +| [`@monarcode/session-kit/react-router`](/docs/reference/react-router) | `requireSession`, `requireSessionLoader`, `redirectIfSignedIn`, `redirectIfSignedInLoader`, `SessionOutlet`, `useAuthRevalidation`, types | | [`@monarcode/session-kit/react-router/server`](/docs/reference/react-router-server) | `sessionMiddleware`, `requireSession`, `redirectIfSignedIn`, `sessionRoute`, `routerAuth`, `cookieJarMiddleware`, `routerJar`, types | | [`@monarcode/session-kit/http`](/docs/reference/http) | `createAuthFetch`, types | | [`@monarcode/session-kit/server`](/docs/reference/server) | `createServerAuth`, `sessionHandler`, types | diff --git a/site/content/docs/(latest)/reference/react-router.mdx b/site/content/docs/(latest)/reference/react-router.mdx index b43fb56..655c6e3 100644 --- a/site/content/docs/(latest)/reference/react-router.mdx +++ b/site/content/docs/(latest)/reference/react-router.mdx @@ -13,11 +13,19 @@ Guide: [React Router](/docs/setups/react-router). ### redirectIfSignedIn -Guards your sign-in page in its loader, so a signed-in user goes straight to `redirectTo`, made safe with `safeReturnTo`. `redirectIfSignedIn(auth)` is the loader itself, and reads `redirectTo` from the URL's search. +Sends a signed-in user from your sign-in page straight to `redirectTo`, made safe with `safeReturnTo`, inside a loader of your own. When the loader does nothing else, use [`redirectIfSignedInLoader`](#redirectifsignedinloader) instead. + +### redirectIfSignedInLoader + +Makes the loader for your sign-in page, for `loader` or `clientLoader`. It reads `?redirectTo=` from the URL and works as [`redirectIfSignedIn`](#redirectifsignedin) does. ### requireSession -Guards a route in its loader, in data or framework mode, so only signed-in users get through. They get `{ session }`, which holds no tokens. `requireSession(auth)` is the loader itself. +Checks for a signed-in user inside a loader of your own, in data or framework mode, and resolves `{ session }`, which holds no tokens. When the loader does nothing else, use [`requireSessionLoader`](#requiresessionloader) as the loader instead. + +### requireSessionLoader + +Makes the loader that guards a route, for `loader` or `clientLoader`, so only signed-in users get through. It resolves `{ session }`, typed with the client's user, and works as [`requireSession`](#requiresession) does. ### useAuthRevalidation @@ -33,11 +41,11 @@ Renders child routes only while someone is signed in, in any mode. It needs an ` ### RedirectIfSignedInLoader -The loader that `redirectIfSignedIn(auth)` makes. It reads `redirectTo` from the request's URL, and resolves `null` for a signed-out user. +The loader that [`redirectIfSignedInLoader`](#redirectifsignedinloader) makes. It reads `redirectTo` from the request's URL, and resolves `null` for a signed-out user. ### RedirectIfSignedInLoaderOptions -Options for the loader that `redirectIfSignedIn(auth, options)` makes. +Options for [`redirectIfSignedInLoader`](#redirectifsignedinloader). , }, { - loader: requireSession(auth), + loader: requireSessionLoader(auth), errorElement: , element: Checking session…

} />, children: [{ index: true, element: }], @@ -252,11 +252,12 @@ createRoot(document.getElementById("root")!).render( Three pieces work together: -- **`requireSession(auth)`** is the route's loader. It redirects signed-out - users to `/login` with `redirectTo`, and returns `{ session }` as the - route's loader data. Pass `{ loginPath }` for another sign-in page. A failed - refresh is rethrown for the route's error element instead: the user is still - signed in. +- **`requireSessionLoader(auth)`** is the route's loader. It redirects + signed-out users to `/login` with `redirectTo`, and returns `{ session }` + as the route's loader data. Pass `{ loginPath }` for another sign-in page. + A failed refresh is rethrown for the route's error element instead: the + user is still signed in. In a loader that does more, call + `requireSession(auth, { request })` and carry on. - **`useAuthRevalidation`** runs the loaders again after a sign-in, a sign-out, an account switch, or a profile update, so the guards run again. Call it once, in the root route. @@ -344,13 +345,13 @@ import { useRouteError } from "react-router"; import { useAuthClient } from "@monarcode/session-kit/react"; import { - requireSession, + requireSessionLoader, SessionOutlet, } from "@monarcode/session-kit/react-router"; import { auth } from "../auth.js"; -export const clientLoader = requireSession(auth); +export const clientLoader = requireSessionLoader(auth); export default function Protected() { return Checking session…

} />; @@ -375,12 +376,12 @@ Add the sign-in route, which sends signed-in users on to `redirectTo`: import { useNavigate, useSearchParams } from "react-router"; import { safeReturnTo } from "@monarcode/session-kit"; -import { redirectIfSignedIn } from "@monarcode/session-kit/react-router"; +import { redirectIfSignedInLoader } from "@monarcode/session-kit/react-router"; import { auth } from "../auth.js"; import { SignIn } from "../sign-in.js"; -export const clientLoader = redirectIfSignedIn(auth); +export const clientLoader = redirectIfSignedInLoader(auth); export default function Login() { const navigate = useNavigate(); @@ -463,10 +464,10 @@ Three things follow from where `SessionOutlet` sits: ## Things to know -- **A router `basename`.** Pass the same `basename` to `requireSession`, so +- **A router `basename`.** Pass the same `basename` to the guard, so `redirectTo` leaves it out. Redirects add it again. - **A failed refresh is not a redirect.** In declarative mode it renders - `unavailable`. In data and framework mode, `requireSession` rethrows it for + `unavailable`. In data and framework mode, the guard rethrows it for the route's error element, which can offer `auth.retry()`. - **Locked sessions.** [Locking](/docs/client/locking) is for native apps, so the guards treat a locked session as signed out. diff --git a/src/react-router/guards.ts b/src/react-router/guards.ts index a786cdb..18a711c 100644 --- a/src/react-router/guards.ts +++ b/src/react-router/guards.ts @@ -39,7 +39,7 @@ export type RequireSessionOptions = RequireSessionLoaderOptions & { }; /** - * Options for the loader that `requireSession(auth, options)` makes. + * Options for {@link requireSessionLoader}. * * @example * ```ts @@ -71,21 +71,21 @@ export type RequireSessionLoaderOptions = { }; /** - * The loader that `requireSession(auth)` makes. It resolves `{ session }`, + * The loader that {@link requireSessionLoader} makes. It resolves `{ session }`, * typed with the client's user. * * @example * ```ts * import type { AuthClient } from "@monarcode/session-kit"; * import { - * requireSession, + * requireSessionLoader, * type RequireSessionLoader, * } from "@monarcode/session-kit/react-router"; * * type User = { name: string }; * declare const auth: AuthClient; * - * export const loader: RequireSessionLoader = requireSession(auth); + * export const loader: RequireSessionLoader = requireSessionLoader(auth); * ``` * * @since 0.1.0 @@ -95,9 +95,10 @@ export type RequireSessionLoader = (args: { }) => Promise<{ session: Session }>; /** - * Guards a route in its loader, in data or framework mode, so only - * signed-in users get through. They get `{ session }`, which holds no tokens. - * `requireSession(auth)` is the loader itself. + * Checks for a signed-in user inside a loader of your own, in data or + * framework mode, and resolves `{ session }`, which holds no tokens. When + * the loader does nothing else, use {@link requireSessionLoader} as the + * loader instead. * * Signed-out users go to `loginPath`, with `?redirectTo=` set to the URL they * asked for. A locked session counts as signed out, as locking is for native @@ -105,74 +106,73 @@ export type RequireSessionLoader = (args: { * * Other errors, such as `REFRESH_FAILED` after a failed refresh, are * rethrown to the route's error element, which can offer `auth.retry()`. + * A `loginPath` that doesn't start with `/`, or a bad `basename`, rejects + * with `INVALID_OPTIONS`. * * Use `SessionOutlet` as the route's element, and call * `useAuthRevalidation`, so the loader runs again when the session changes. * * @example - * ```tsx - * import { createBrowserRouter } from "react-router"; + * ```ts * import type { AuthClient } from "@monarcode/session-kit"; - * import { - * requireSession, - * SessionOutlet, - * } from "@monarcode/session-kit/react-router"; + * import { requireSession } from "@monarcode/session-kit/react-router"; * * declare const auth: AuthClient<{ name: string }, { name: string }>; + * declare function fetchOrders(): Promise; * - * export const router = createBrowserRouter([ - * { - * loader: requireSession(auth), - * element: , - * children: [{ index: true, element:

Signed in

}], - * }, - * ]); + * export async function clientLoader({ request }: { request: Request }) { + * const { session } = await requireSession(auth, { request }); + * return { name: session.user.name, orders: await fetchOrders() }; + * } * ``` * * @since 0.1.0 */ -export function requireSession( +export async function requireSession( auth: GuardClient, options: RequireSessionOptions, -): Promise<{ session: Session }>; +): Promise<{ session: Session }> { + checkPaths(options); + return guard(auth, options.request, options); +} + /** - * The guard as a loader of its own, for `loader` or `clientLoader`. Pass - * `loginPath` or `basename` when they aren't the defaults. - * - * It returns the loader, so pass it as one. Inside a loader of your own, - * call the form that takes `request`: awaiting this one checks nothing. + * Makes the loader that guards a route, for `loader` or `clientLoader`, so + * only signed-in users get through. It resolves `{ session }`, typed with the + * client's user, and works as {@link requireSession} does. * - * Throws `INVALID_OPTIONS` when it's made, for a `loginPath` that doesn't - * start with `/` or a bad `basename`. + * Pass `loginPath` or `basename` when they aren't the defaults. A + * `loginPath` that doesn't start with `/`, or a bad `basename`, throws + * `INVALID_OPTIONS` when the loader is made. * * @example - * ```ts + * ```tsx + * import { createBrowserRouter } from "react-router"; * import type { AuthClient } from "@monarcode/session-kit"; - * import { requireSession } from "@monarcode/session-kit/react-router"; + * import { + * requireSessionLoader, + * SessionOutlet, + * } from "@monarcode/session-kit/react-router"; * * declare const auth: AuthClient<{ name: string }, { name: string }>; * - * export const clientLoader = requireSession(auth, { loginPath: "/sign-in" }); + * export const router = createBrowserRouter([ + * { + * loader: requireSessionLoader(auth), + * element: , + * children: [{ index: true, element:

Signed in

}], + * }, + * ]); * ``` * * @since 0.1.0 */ -export function requireSession( - auth: GuardClient, - options?: RequireSessionLoaderOptions, -): RequireSessionLoader; -export function requireSession( +export function requireSessionLoader( auth: GuardClient, - options: Partial = {}, -): RequireSessionLoader | Promise<{ session: Session }> { - const { request, ...rest } = options; - if (request) - return (async () => { - checkPaths(rest); - return guard(auth, request, rest); - })(); - checkPaths(rest); - return (args) => guard(auth, args.request, rest); + options: RequireSessionLoaderOptions = {}, +): RequireSessionLoader { + checkPaths(options); + return ({ request }) => guard(auth, request, options); } /** Fails fast on a bad path, before any session is read. */ @@ -229,7 +229,7 @@ export type RedirectIfSignedInOptions = RedirectIfSignedInLoaderOptions & { }; /** - * Options for the loader that `redirectIfSignedIn(auth, options)` makes. + * Options for {@link redirectIfSignedInLoader}. * * @example * ```ts @@ -255,20 +255,20 @@ export type RedirectIfSignedInLoaderOptions = { }; /** - * The loader that `redirectIfSignedIn(auth)` makes. It reads `redirectTo` + * The loader that {@link redirectIfSignedInLoader} makes. It reads `redirectTo` * from the request's URL, and resolves `null` for a signed-out user. * * @example * ```ts * import type { AuthClient } from "@monarcode/session-kit"; * import { - * redirectIfSignedIn, + * redirectIfSignedInLoader, * type RedirectIfSignedInLoader, * } from "@monarcode/session-kit/react-router"; * * declare const auth: AuthClient<{ name: string }, { name: string }>; * - * export const loader: RedirectIfSignedInLoader = redirectIfSignedIn(auth); + * export const loader: RedirectIfSignedInLoader = redirectIfSignedInLoader(auth); * ``` * * @since 0.1.0 @@ -278,61 +278,61 @@ export type RedirectIfSignedInLoader = (args: { }) => Promise; /** - * Guards your sign-in page in its loader, so a signed-in user goes straight - * to `redirectTo`, made safe with `safeReturnTo`. `redirectIfSignedIn(auth)` - * is the loader itself, and reads `redirectTo` from the URL's search. + * Sends a signed-in user from your sign-in page straight to `redirectTo`, + * made safe with `safeReturnTo`, inside a loader of your own. When the loader + * does nothing else, use {@link redirectIfSignedInLoader} instead. * * If the session can't be read, such as after a failed refresh or while * locked, the sign-in page shows, so the user can sign in again. * * @example * ```ts + * import type { LoaderFunctionArgs } from "react-router"; * import type { AuthClient } from "@monarcode/session-kit"; * import { redirectIfSignedIn } from "@monarcode/session-kit/react-router"; * * declare const auth: AuthClient<{ name: string }, { name: string }>; * - * // The sign-in route. - * export const clientLoader = redirectIfSignedIn(auth); + * export async function loader({ request }: LoaderFunctionArgs) { + * const search = new URL(request.url).searchParams; + * await redirectIfSignedIn(auth, { redirectTo: search.get("next") }); + * return { invited: search.has("invite") }; + * } * ``` * * @since 0.1.0 */ -export function redirectIfSignedIn( +export async function redirectIfSignedIn( auth: GuardClient, options: RedirectIfSignedInOptions, -): Promise; +): Promise { + await sendOn(auth, options.redirectTo, options.loginPath); +} + /** - * The guard as a loader of its own, for `loader` or `clientLoader`, with - * `redirectTo` read from the URL's search. - * - * It returns the loader, so pass it as one. Inside a loader of your own, - * call the form that takes `redirectTo`: awaiting this one checks nothing. + * Makes the loader for your sign-in page, for `loader` or `clientLoader`. + * It reads `?redirectTo=` from the URL and works as + * {@link redirectIfSignedIn} does. * * @example * ```ts * import type { AuthClient } from "@monarcode/session-kit"; - * import { redirectIfSignedIn } from "@monarcode/session-kit/react-router"; + * import { redirectIfSignedInLoader } from "@monarcode/session-kit/react-router"; * * declare const auth: AuthClient<{ name: string }, { name: string }>; * - * export const loader = redirectIfSignedIn(auth, { + * // The sign-in route. A sign-up page never returns to either one. + * export const clientLoader = redirectIfSignedInLoader(auth, { * loginPath: ["/login", "/sign-up"], * }); * ``` * * @since 0.1.0 */ -export function redirectIfSignedIn( - auth: GuardClient, - options?: RedirectIfSignedInLoaderOptions, -): RedirectIfSignedInLoader; -export function redirectIfSignedIn( +export function redirectIfSignedInLoader( auth: GuardClient, - options: Partial = {}, -): RedirectIfSignedInLoader | Promise { - if ("redirectTo" in options) - return sendOn(auth, options.redirectTo, options.loginPath); + options: RedirectIfSignedInLoaderOptions = {}, +): RedirectIfSignedInLoader { return async ({ request }) => { const redirectTo = new URL(request.url).searchParams.get("redirectTo"); await sendOn(auth, redirectTo, options.loginPath); diff --git a/src/react-router/index.ts b/src/react-router/index.ts index 6acf248..12de990 100644 --- a/src/react-router/index.ts +++ b/src/react-router/index.ts @@ -1,4 +1,9 @@ -export { redirectIfSignedIn, requireSession } from "./guards.js"; +export { + redirectIfSignedIn, + redirectIfSignedInLoader, + requireSession, + requireSessionLoader, +} from "./guards.js"; export { SessionOutlet } from "./outlet.js"; export { useAuthRevalidation } from "./revalidation.js"; diff --git a/tests/consumer.ts b/tests/consumer.ts index 12fc052..b620d23 100644 --- a/tests/consumer.ts +++ b/tests/consumer.ts @@ -383,18 +383,22 @@ export async function defaultLoader({ request }: { request: Request }) { const email: string = session.user.email; return email; } -// The loader forms, typed by the client. -const guardLoader: LoaderFunction = reactRouter.requireSession(auth); +// @ts-expect-error The check needs the loader's request. +void reactRouter.requireSession(auth); +// The loaders, typed by the client. +const guardLoader: LoaderFunction = reactRouter.requireSessionLoader(auth); void guardLoader; -const shortLoader = reactRouter.requireSession(auth, { basename: "/app" }); +const shortLoader = reactRouter.requireSessionLoader(auth, { + basename: "/app", +}); export async function useShortLoader(request: Request) { const email: string = (await shortLoader({ request })).session.user.email; return email; } -const signInLoader: LoaderFunction = reactRouter.redirectIfSignedIn(auth); +const signInLoader: LoaderFunction = reactRouter.redirectIfSignedInLoader(auth); void signInLoader; -// @ts-expect-error The immediate form needs redirectTo. -void reactRouter.redirectIfSignedIn(auth, { loginPath: "/x" }).then(() => {}); +// @ts-expect-error The check needs redirectTo. +void reactRouter.redirectIfSignedIn(auth, { loginPath: "/x" }); reactRouter.SessionOutlet({ loginPath: "/login", unavailable: ({ error, retry }) => `${error?.code}${String(retry)}`, diff --git a/tests/react-router.test.ts b/tests/react-router.test.ts index 0017795..4568a7b 100644 --- a/tests/react-router.test.ts +++ b/tests/react-router.test.ts @@ -47,7 +47,7 @@ function Root() { } /** A sign-in route loader that sends a signed-in user on to `redirectTo`. */ -const loginLoader = (auth: Client) => binding.redirectIfSignedIn(auth); +const loginLoader = (auth: Client) => binding.redirectIfSignedInLoader(auth); /** A home page that counts its mounts and shows the user's email. */ const homePage = ( @@ -410,11 +410,11 @@ test("data mode: loaders guard routes and re-run when auth changes", async () => assert.equal(view.container.textContent, "home:alice@example.com"); }); -test("requireSession(auth) and redirectIfSignedIn(auth) are loaders themselves", async () => { +test("requireSessionLoader and redirectIfSignedInLoader make the loaders", async () => { const auth = newClient(); await auth.getSession(); const request = new Request("https://auth.test/app/private?tab=2"); - const guard = binding.requireSession(auth, { basename: "/app" }); + const guard = binding.requireSessionLoader(auth, { basename: "/app" }); const redirected = await guard({ request }).then( () => assert.fail("Expected a redirect"), (response: Response) => response, @@ -428,7 +428,7 @@ test("requireSession(auth) and redirectIfSignedIn(auth) are loaders themselves", (await guard({ request })).session, await auth.getSession(), ); - const signInPage = binding.redirectIfSignedIn(auth, { + const signInPage = binding.redirectIfSignedInLoader(auth, { loginPath: ["/login", "/sign-up"], }); for (const [redirectTo, to] of [ @@ -450,14 +450,20 @@ test("requireSession(auth) and redirectIfSignedIn(auth) are loaders themselves", await signInPage({ request: new Request("https://auth.test/login") }), null, ); - assert.throws(() => binding.requireSession(auth, { loginPath: "login" }), { - code: "INVALID_OPTIONS", - }); - assert.throws(() => binding.requireSession(auth, { basename: "app" }), { - code: "INVALID_OPTIONS", - }); + assert.throws( + () => binding.requireSessionLoader(auth, { loginPath: "login" }), + { + code: "INVALID_OPTIONS", + }, + ); + assert.throws( + () => binding.requireSessionLoader(auth, { basename: "app" }), + { + code: "INVALID_OPTIONS", + }, + ); const elsewhere = await binding - .requireSession(auth, { loginPath: "/sign-in" })({ request }) + .requireSessionLoader(auth, { loginPath: "/sign-in" })({ request }) .then( () => assert.fail("Expected a redirect"), (response: Response) => response, From ac10d38f70b450828380c12dbf522b9ec1219f1e Mon Sep 17 00:00:00 2001 From: monarcode Date: Sat, 14 Nov 2026 08:04:49 +0100 Subject: [PATCH 10/26] docs: revise the guides and examples to match the current API - Stop navigating from sign-in pages, since the sign-in page's guard redirects - Call the API with createAuthFetch over the request's session in the server-rendering guides - Add the profile screen to the Expo guide and tidy wording across the site's pages --- CHANGELOG.md | 5 + README.md | 4 +- examples/README.md | 10 +- examples/next-app/app/page.tsx | 8 +- examples/next-app/app/ui.tsx | 4 +- examples/react-router-data/src/main.tsx | 17 +- examples/react-router-data/src/ui.tsx | 13 +- .../react-router-declarative/src/main.tsx | 2 +- examples/react-router-declarative/src/ui.tsx | 13 +- .../app/routes/login.tsx | 16 +- .../react-router-framework-spa/app/ui.tsx | 13 +- .../app/routes/home.tsx | 20 +- .../react-router-framework-ssr/app/ui.tsx | 4 +- examples/tanstack-router/src/routes/login.tsx | 15 +- examples/tanstack-router/src/ui.tsx | 13 +- .../src/routes/login.tsx | 15 +- .../tanstack-start-spa-effetch/src/ui.tsx | 13 +- .../tanstack-start-spa/src/routes/login.tsx | 15 +- examples/tanstack-start-spa/src/ui.tsx | 13 +- .../tanstack-start-ssr/src/auth/functions.ts | 19 +- .../tanstack-start-ssr/src/auth/server.ts | 8 + .../tanstack-start-ssr/src/routes/login.tsx | 15 +- examples/tanstack-start-ssr/src/ui.tsx | 13 +- scripts/reference-docs.mjs | 4 +- site/content/docs/(latest)/client/index.mdx | 33 +-- site/content/docs/(latest)/client/locking.mdx | 9 +- .../(latest)/client/other-http-clients.mdx | 6 +- .../content/docs/(latest)/client/requests.mdx | 25 +- .../content/docs/(latest)/client/sessions.mdx | 8 +- .../(latest)/client/signing-in-and-out.mdx | 20 +- site/content/docs/(latest)/client/state.mdx | 6 +- .../docs/(latest)/configuration/errors.mdx | 33 +-- .../docs/(latest)/configuration/expiry.mdx | 2 +- .../docs/(latest)/configuration/index.mdx | 22 +- .../docs/(latest)/configuration/refresh.mdx | 10 +- .../docs/(latest)/configuration/storage.mdx | 7 +- .../docs/(latest)/configuration/tabs.mdx | 10 +- .../(latest)/configuration/user-schemas.mdx | 16 +- site/content/docs/(latest)/effect.mdx | 23 +- site/content/docs/(latest)/faq.mdx | 4 +- .../content/docs/(latest)/getting-started.mdx | 35 +-- site/content/docs/(latest)/index.mdx | 2 +- site/content/docs/(latest)/installation.mdx | 4 +- .../docs/(latest)/reference/compatibility.mdx | 2 + .../docs/(latest)/reference/error-codes.mdx | 4 +- .../docs/(latest)/reference/server.mdx | 2 +- site/content/docs/(latest)/security.mdx | 26 ++- .../docs/(latest)/server-rendering/index.mdx | 30 +-- .../server-rendering/server-sessions.mdx | 22 +- site/content/docs/(latest)/setups/expo.mdx | 214 +++++++++--------- site/content/docs/(latest)/setups/next.mdx | 61 ++--- .../docs/(latest)/setups/react-router-ssr.mdx | 53 +++-- .../docs/(latest)/setups/react-router.mdx | 71 ++---- .../docs/(latest)/setups/tanstack-router.mdx | 51 +++-- .../docs/(latest)/setups/tanstack-start.mdx | 68 ++++-- src/expo/gate.ts | 31 +-- src/server/auth.ts | 24 +- src/tanstack-start/server.ts | 5 +- 58 files changed, 600 insertions(+), 611 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3018a0c..ddede4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -279,6 +279,11 @@ - The compatibility page lists `effect` as a peer of `./effetch` as well as `./effect`, and the entry points page orders the entry points as the reference does. +- The router guides' sign-in pages no longer navigate after a sign-in. The + sign-in page's guard runs again and sends the user on, so a form only signs + in. The server-rendering guides call the API with `createAuthFetch` over the + request's session, and the Expo guide adds the profile screen its deep-link + steps open. - The reference lists the members of `AuthStorage`, `Tokens` and `CookieJar`, the types an app builds itself. The server-rendering guides' sign-in shows the backend's own message for a failed sign-in, as the diff --git a/README.md b/README.md index 5d8d678..5f540e3 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,9 @@ export const auth = createAuth({ }); ``` -And render by the session's status: +Register the client's type once, and the hooks from +`@monarcode/session-kit/react` carry your user. Then render by the session's +status: diff --git a/examples/README.md b/examples/README.md index 44e6f10..2460a14 100644 --- a/examples/README.md +++ b/examples/README.md @@ -53,9 +53,10 @@ run ios` and `run android` build it natively. In CI it is only bundled, with Tokens last one minute, so the early refresh runs after about 30 seconds. Requests omit `credentials: "include"`, which DummyJSON's own snippets use, because session-kit keeps tokens out of cookies. -- **Guards**: `requireSession` and `SessionOutlet` for TanStack Router and - Start, `SessionOutlet` alone in React Router's declarative mode, and loader - guards with `useAuthRevalidation` in data and framework mode. +- **Guards**: `requireSession`, `redirectIfSignedIn` and `SessionOutlet` for + TanStack Router and Start. `SessionOutlet` alone in React Router's + declarative mode. `requireSessionLoader`, `redirectIfSignedInLoader`, + `SessionOutlet` and `useAuthRevalidation` in data and framework mode. - **TanStack Start** sets `defaultSsr: false` in `src/start.ts`. Start's own server still renders requests in SPA mode, and the guards need the browser's saved session. @@ -111,7 +112,8 @@ run ios` and `run android` build it natively. In CI it is only bundled, with `expo-secure-store` config plugin keeps the session out of Android backups. Each app is self-contained, so it can be copied out on its own. That is why -the client-side web apps have the same `ui.tsx` rather than sharing one. The +the client-side web apps have the same `ui.tsx`, apart from where the hooks +come from, rather than sharing one. The server-rendered apps have their own, since they sign in on the server, and so does the Effect app, whose handlers run Effects. The apps differ in where the user comes from on purpose, so both user sources appear: the login response, diff --git a/examples/next-app/app/page.tsx b/examples/next-app/app/page.tsx index 1ab85c3..d79fff5 100644 --- a/examples/next-app/app/page.tsx +++ b/examples/next-app/app/page.tsx @@ -1,3 +1,4 @@ +import { createAuthFetch } from "@monarcode/session-kit/http"; import { z } from "zod"; import { API } from "../lib/auth/api"; @@ -7,11 +8,10 @@ import { Profile } from "./ui"; /** Calls DummyJSON's `auth/me` while rendering, with the cookie's token. */ async function profileEmail() { // Read-only: Proxy refreshed the token before this render. - const credentials = await (await session.readOnly()).credentials.get(); - if (!credentials) return "Signed out"; - const response = await fetch(`${API}/auth/me`, { - headers: { Authorization: `Bearer ${credentials.accessToken}` }, + const apiFetch = createAuthFetch(await session.readOnly(), { + baseUrl: `${API}/`, }); + const response = await apiFetch("auth/me"); if (!response.ok) return `HTTP ${response.status}`; const profile = z.object({ email: z.string() }).parse(await response.json()); return profile.email; diff --git a/examples/next-app/app/ui.tsx b/examples/next-app/app/ui.tsx index 2293fb4..1cbfa69 100644 --- a/examples/next-app/app/ui.tsx +++ b/examples/next-app/app/ui.tsx @@ -107,7 +107,9 @@ export function Profile({ fromServer }: { fromServer: string }) { Load profile in the browser {fromBrowser &&

auth/me in the browser: {fromBrowser}

} - + ); } diff --git a/examples/react-router-data/src/main.tsx b/examples/react-router-data/src/main.tsx index 5b8867a..2f8e48b 100644 --- a/examples/react-router-data/src/main.tsx +++ b/examples/react-router-data/src/main.tsx @@ -3,12 +3,9 @@ import { createBrowserRouter, Outlet, RouterProvider, - useNavigate, useRouteError, - useSearchParams, } from "react-router"; -import { safeReturnTo } from "@monarcode/session-kit"; import { AuthProvider } from "@monarcode/session-kit/react"; import { redirectIfSignedInLoader, @@ -39,18 +36,6 @@ function Root() { return ; } -function Login() { - const navigate = useNavigate(); - const [search] = useSearchParams(); - return ( - - navigate(safeReturnTo(search.get("redirectTo")), { replace: true }) - } - /> - ); -} - function RouteError() { return ; } @@ -63,7 +48,7 @@ const router = createBrowserRouter([ { path: "/login", loader: redirectIfSignedInLoader(auth), - element: , + element: , }, { loader: requireSessionLoader(auth), diff --git a/examples/react-router-data/src/ui.tsx b/examples/react-router-data/src/ui.tsx index efbfc75..38d17ff 100644 --- a/examples/react-router-data/src/ui.tsx +++ b/examples/react-router-data/src/ui.tsx @@ -4,8 +4,12 @@ import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; import { authFetch, signInWithPassword } from "./auth"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -19,7 +23,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { String(form.get("username")), String(form.get("password")), ); - await onSignedIn(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { @@ -91,7 +94,9 @@ export function Profile() { Load profile {fromApi &&

auth/me: {fromApi}

} - + ); } diff --git a/examples/react-router-declarative/src/main.tsx b/examples/react-router-declarative/src/main.tsx index 98da83a..1fb8cb5 100644 --- a/examples/react-router-declarative/src/main.tsx +++ b/examples/react-router-declarative/src/main.tsx @@ -32,7 +32,7 @@ function Login() { const [search] = useSearchParams(); if (signedIn) return ; - return {}} />; + return ; } createRoot(document.getElementById("root")!).render( diff --git a/examples/react-router-declarative/src/ui.tsx b/examples/react-router-declarative/src/ui.tsx index efbfc75..38d17ff 100644 --- a/examples/react-router-declarative/src/ui.tsx +++ b/examples/react-router-declarative/src/ui.tsx @@ -4,8 +4,12 @@ import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; import { authFetch, signInWithPassword } from "./auth"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -19,7 +23,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { String(form.get("username")), String(form.get("password")), ); - await onSignedIn(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { @@ -91,7 +94,9 @@ export function Profile() { Load profile {fromApi &&

auth/me: {fromApi}

} - + ); } diff --git a/examples/react-router-framework-spa/app/routes/login.tsx b/examples/react-router-framework-spa/app/routes/login.tsx index b0876bd..e2be783 100644 --- a/examples/react-router-framework-spa/app/routes/login.tsx +++ b/examples/react-router-framework-spa/app/routes/login.tsx @@ -1,21 +1,9 @@ -import { useNavigate, useSearchParams } from "react-router"; - -import { safeReturnTo } from "@monarcode/session-kit"; import { redirectIfSignedInLoader } from "@monarcode/session-kit/react-router"; import { auth } from "../auth"; import { LoginForm } from "../ui"; +// Runs again after a sign-in, as useAuthRevalidation runs the loaders again. export const clientLoader = redirectIfSignedInLoader(auth); -export default function Login() { - const navigate = useNavigate(); - const [search] = useSearchParams(); - return ( - - navigate(safeReturnTo(search.get("redirectTo")), { replace: true }) - } - /> - ); -} +export default LoginForm; diff --git a/examples/react-router-framework-spa/app/ui.tsx b/examples/react-router-framework-spa/app/ui.tsx index efbfc75..38d17ff 100644 --- a/examples/react-router-framework-spa/app/ui.tsx +++ b/examples/react-router-framework-spa/app/ui.tsx @@ -4,8 +4,12 @@ import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; import { authFetch, signInWithPassword } from "./auth"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -19,7 +23,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { String(form.get("username")), String(form.get("password")), ); - await onSignedIn(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { @@ -91,7 +94,9 @@ export function Profile() { Load profile {fromApi &&

auth/me: {fromApi}

} - + ); } diff --git a/examples/react-router-framework-ssr/app/routes/home.tsx b/examples/react-router-framework-ssr/app/routes/home.tsx index bbe8c81..069df04 100644 --- a/examples/react-router-framework-ssr/app/routes/home.tsx +++ b/examples/react-router-framework-ssr/app/routes/home.tsx @@ -1,5 +1,6 @@ import { useLoaderData, type LoaderFunctionArgs } from "react-router"; +import { createAuthFetch } from "@monarcode/session-kit/http"; import { z } from "zod"; import { API } from "../auth/api"; @@ -8,27 +9,14 @@ import { Profile } from "../ui"; /** Calls DummyJSON's `auth/me` from the server, with the cookie's token. */ export async function loader({ context }: LoaderFunctionArgs) { - const session = auth(context); - const credentials = await session.credentials.get(); - if (!credentials) return { email: "Signed out" }; - let response = await me(credentials.accessToken); - if (response.status === 401) { - // Refreshes once, then tries again. - const renewed = await session.credentials.renew(credentials); - if (!renewed) return { email: "Signed out" }; - response = await me(renewed.accessToken); - } + // After a 401, it renews the token, saves it in the cookie, and tries again. + const apiFetch = createAuthFetch(auth(context), { baseUrl: `${API}/` }); + const response = await apiFetch("auth/me"); if (!response.ok) return { email: `HTTP ${response.status}` }; const profile = z.object({ email: z.string() }).parse(await response.json()); return { email: profile.email }; } -function me(accessToken: string) { - return fetch(`${API}/auth/me`, { - headers: { Authorization: `Bearer ${accessToken}` }, - }); -} - export default function Home() { const { email } = useLoaderData(); return ; diff --git a/examples/react-router-framework-ssr/app/ui.tsx b/examples/react-router-framework-ssr/app/ui.tsx index bac0ceb..bbc3ebd 100644 --- a/examples/react-router-framework-ssr/app/ui.tsx +++ b/examples/react-router-framework-ssr/app/ui.tsx @@ -90,7 +90,9 @@ export function Profile({ fromServer }: { fromServer: string }) { Load profile in the browser {fromBrowser &&

auth/me in the browser: {fromBrowser}

} - + ); } diff --git a/examples/tanstack-router/src/routes/login.tsx b/examples/tanstack-router/src/routes/login.tsx index 06976a2..3553fd4 100644 --- a/examples/tanstack-router/src/routes/login.tsx +++ b/examples/tanstack-router/src/routes/login.tsx @@ -1,6 +1,6 @@ import { safeReturnTo } from "@monarcode/session-kit"; import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router"; -import { createFileRoute, useRouter } from "@tanstack/react-router"; +import { createFileRoute } from "@tanstack/react-router"; import { LoginForm } from "../ui"; @@ -8,17 +8,8 @@ export const Route = createFileRoute("/login")({ validateSearch: (search: Record) => ({ redirectTo: safeReturnTo(search.redirectTo), }), + // Runs again after a sign-in, as connectAuth runs the guards again. beforeLoad: ({ context, search }) => redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }), - component: Login, + component: LoginForm, }); - -function Login() { - const router = useRouter(); - const { redirectTo } = Route.useSearch(); - return ( - router.navigate({ href: redirectTo, replace: true })} - /> - ); -} diff --git a/examples/tanstack-router/src/ui.tsx b/examples/tanstack-router/src/ui.tsx index 7d5cd77..fccf796 100644 --- a/examples/tanstack-router/src/ui.tsx +++ b/examples/tanstack-router/src/ui.tsx @@ -4,8 +4,12 @@ import { useAuth, useAuthClient } from "@monarcode/session-kit/tanstack-router"; import { authFetch, signInWithPassword } from "./auth"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -19,7 +23,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { String(form.get("username")), String(form.get("password")), ); - await onSignedIn(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { @@ -91,7 +94,9 @@ export function Profile() { Load profile {fromApi &&

auth/me: {fromApi}

} - + ); } diff --git a/examples/tanstack-start-spa-effetch/src/routes/login.tsx b/examples/tanstack-start-spa-effetch/src/routes/login.tsx index 06976a2..3553fd4 100644 --- a/examples/tanstack-start-spa-effetch/src/routes/login.tsx +++ b/examples/tanstack-start-spa-effetch/src/routes/login.tsx @@ -1,6 +1,6 @@ import { safeReturnTo } from "@monarcode/session-kit"; import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router"; -import { createFileRoute, useRouter } from "@tanstack/react-router"; +import { createFileRoute } from "@tanstack/react-router"; import { LoginForm } from "../ui"; @@ -8,17 +8,8 @@ export const Route = createFileRoute("/login")({ validateSearch: (search: Record) => ({ redirectTo: safeReturnTo(search.redirectTo), }), + // Runs again after a sign-in, as connectAuth runs the guards again. beforeLoad: ({ context, search }) => redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }), - component: Login, + component: LoginForm, }); - -function Login() { - const router = useRouter(); - const { redirectTo } = Route.useSearch(); - return ( - router.navigate({ href: redirectTo, replace: true })} - /> - ); -} diff --git a/examples/tanstack-start-spa-effetch/src/ui.tsx b/examples/tanstack-start-spa-effetch/src/ui.tsx index a24a830..9306ff2 100644 --- a/examples/tanstack-start-spa-effetch/src/ui.tsx +++ b/examples/tanstack-start-spa-effetch/src/ui.tsx @@ -9,8 +9,12 @@ import { expiresInMins } from "./auth"; import { profileQuery, signInMutation } from "./endpoints"; import { apiErrorMessage } from "./error-message"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const auth = useAuthClient(); const signIn = useMutation(signInMutation); const [error, setError] = useState(""); @@ -33,7 +37,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { try { // The tokens carry the user, so they are all the client needs. await auth.signIn(exit.value); - await onSignedIn(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } @@ -93,7 +96,9 @@ export function Profile() {

Signed in as {user?.username}

{showEmail && } - + ); } diff --git a/examples/tanstack-start-spa/src/routes/login.tsx b/examples/tanstack-start-spa/src/routes/login.tsx index 06976a2..3553fd4 100644 --- a/examples/tanstack-start-spa/src/routes/login.tsx +++ b/examples/tanstack-start-spa/src/routes/login.tsx @@ -1,6 +1,6 @@ import { safeReturnTo } from "@monarcode/session-kit"; import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router"; -import { createFileRoute, useRouter } from "@tanstack/react-router"; +import { createFileRoute } from "@tanstack/react-router"; import { LoginForm } from "../ui"; @@ -8,17 +8,8 @@ export const Route = createFileRoute("/login")({ validateSearch: (search: Record) => ({ redirectTo: safeReturnTo(search.redirectTo), }), + // Runs again after a sign-in, as connectAuth runs the guards again. beforeLoad: ({ context, search }) => redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }), - component: Login, + component: LoginForm, }); - -function Login() { - const router = useRouter(); - const { redirectTo } = Route.useSearch(); - return ( - router.navigate({ href: redirectTo, replace: true })} - /> - ); -} diff --git a/examples/tanstack-start-spa/src/ui.tsx b/examples/tanstack-start-spa/src/ui.tsx index 7d5cd77..fccf796 100644 --- a/examples/tanstack-start-spa/src/ui.tsx +++ b/examples/tanstack-start-spa/src/ui.tsx @@ -4,8 +4,12 @@ import { useAuth, useAuthClient } from "@monarcode/session-kit/tanstack-router"; import { authFetch, signInWithPassword } from "./auth"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -19,7 +23,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { String(form.get("username")), String(form.get("password")), ); - await onSignedIn(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { @@ -91,7 +94,9 @@ export function Profile() { Load profile {fromApi &&

auth/me: {fromApi}

} - + ); } diff --git a/examples/tanstack-start-ssr/src/auth/functions.ts b/examples/tanstack-start-ssr/src/auth/functions.ts index a47af66..ec810d2 100644 --- a/examples/tanstack-start-ssr/src/auth/functions.ts +++ b/examples/tanstack-start-ssr/src/auth/functions.ts @@ -1,9 +1,8 @@ import { createServerFn } from "@tanstack/react-start"; import { z } from "zod"; -import { API } from "./api"; import { login } from "./backend"; -import { session } from "./server"; +import { apiFetch, session } from "./server"; // Each handler runs on the server; Start's compiler replaces it with a fetch // in the browser, and leaves `session` out of that bundle. @@ -26,22 +25,8 @@ export const signInFn = createServerFn({ method: "POST" }) /** Calls DummyJSON's `auth/me` from the server, with the cookie's token. */ export const getProfileFn = createServerFn().handler(async () => { - const credentials = await session.credentials.get(); - if (!credentials) return { email: "Signed out" }; - let response = await me(credentials.accessToken); - if (response.status === 401) { - // Refreshes once, then tries again. - const renewed = await session.credentials.renew(credentials); - if (!renewed) return { email: "Signed out" }; - response = await me(renewed.accessToken); - } + const response = await apiFetch("auth/me"); if (!response.ok) return { email: `HTTP ${response.status}` }; const profile = z.object({ email: z.string() }).parse(await response.json()); return { email: profile.email }; }); - -function me(accessToken: string) { - return fetch(`${API}/auth/me`, { - headers: { Authorization: `Bearer ${accessToken}` }, - }); -} diff --git a/examples/tanstack-start-ssr/src/auth/server.ts b/examples/tanstack-start-ssr/src/auth/server.ts index ed0bc79..c113df4 100644 --- a/examples/tanstack-start-ssr/src/auth/server.ts +++ b/examples/tanstack-start-ssr/src/auth/server.ts @@ -1,8 +1,10 @@ // Holds the secret and the tokens: Start refuses to bundle it for the browser. import "@tanstack/react-start/server-only"; +import { createAuthFetch } from "@monarcode/session-kit/http"; import { createServerAuth } from "@monarcode/session-kit/server"; import { startAuth } from "@monarcode/session-kit/tanstack-start/server"; +import { API } from "./api"; import { refresh, userSchema } from "./backend"; /** @@ -37,3 +39,9 @@ export const serverAuth = createServerAuth({ * object serves every request. */ export const session = startAuth(serverAuth); + +/** + * Calls DummyJSON with the cookie's access token. After a 401, it renews the + * token, saves it in the cookie, and sends a `GET` again. + */ +export const apiFetch = createAuthFetch(session, { baseUrl: `${API}/` }); diff --git a/examples/tanstack-start-ssr/src/routes/login.tsx b/examples/tanstack-start-ssr/src/routes/login.tsx index 06976a2..3553fd4 100644 --- a/examples/tanstack-start-ssr/src/routes/login.tsx +++ b/examples/tanstack-start-ssr/src/routes/login.tsx @@ -1,6 +1,6 @@ import { safeReturnTo } from "@monarcode/session-kit"; import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router"; -import { createFileRoute, useRouter } from "@tanstack/react-router"; +import { createFileRoute } from "@tanstack/react-router"; import { LoginForm } from "../ui"; @@ -8,17 +8,8 @@ export const Route = createFileRoute("/login")({ validateSearch: (search: Record) => ({ redirectTo: safeReturnTo(search.redirectTo), }), + // Runs again after a sign-in, as connectAuth runs the guards again. beforeLoad: ({ context, search }) => redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }), - component: Login, + component: LoginForm, }); - -function Login() { - const router = useRouter(); - const { redirectTo } = Route.useSearch(); - return ( - router.navigate({ href: redirectTo, replace: true })} - /> - ); -} diff --git a/examples/tanstack-start-ssr/src/ui.tsx b/examples/tanstack-start-ssr/src/ui.tsx index 6a4297f..36f3de3 100644 --- a/examples/tanstack-start-ssr/src/ui.tsx +++ b/examples/tanstack-start-ssr/src/ui.tsx @@ -6,8 +6,12 @@ import { useRouter } from "@tanstack/react-router"; import { API } from "./auth/api"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const auth = useAuthClient(); const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -23,7 +27,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { username: String(form.get("username")), password: String(form.get("password")), }); - await onSignedIn(); } catch (cause) { // The server function's own message, such as a wrong password. setError(cause instanceof Error ? cause.message : "Could not sign in"); @@ -105,7 +108,9 @@ export function Profile({ fromServer }: { fromServer: string }) { Load profile in the browser {fromBrowser &&

auth/me in the browser: {fromBrowser}

} - + ); } diff --git a/scripts/reference-docs.mjs b/scripts/reference-docs.mjs index 62ab7d2..aa80785 100644 --- a/scripts/reference-docs.mjs +++ b/scripts/reference-docs.mjs @@ -184,8 +184,8 @@ title: Error codes description: Every AuthErrorCode, what it means and when you'll see it. --- -Every error Session kit throws or reports is an \`AuthError\`. Match on its -\`code\`; the \`message\` is for people, and may change. +Every error from Session kit's own logic is an \`AuthError\`. Match on its +\`code\`. The \`message\` is for people, and may change. \`\`\`ts title="src/error-codes.ts" import { AuthError } from "@monarcode/session-kit"; diff --git a/site/content/docs/(latest)/client/index.mdx b/site/content/docs/(latest)/client/index.mdx index a64e35d..3c7a24d 100644 --- a/site/content/docs/(latest)/client/index.mdx +++ b/site/content/docs/(latest)/client/index.mdx @@ -8,25 +8,30 @@ session with hooks. Everything else, such as loaders, event handlers, and request code, calls the client that `createAuth` returned. These are its methods: -| Call | What it does | -| ---------------------------------- | -------------------------------------------------------------------------- | -| `auth.state.get()`, `.subscribe()` | Reads the [state](/docs/client/state), or follows its changes. | -| `auth.getSession()` | Resolves who is signed in, restoring or refreshing first, or `null`. | -| `auth.signIn(tokens)` | Saves a new session, replacing any current one. | -| `auth.signOut()` | Ends the session, clears storage, and tells other tabs. | -| `auth.updateUser(user)` | Replaces the user and keeps the session. | -| `auth.refresh()` | Refreshes now, even while the access token is usable. | -| `auth.retry()` | Tries again after a failed refresh. | -| `auth.isCurrent(session)` | Tells whether a session is still the signed-in one. | -| `auth.credentials.get()` | Resolves the access token, for code that sends requests. | -| `auth.lock()`, `auth.unlock()` | Locks and unlocks a saved session, with [`locking`](/docs/client/locking). | -| `auth.mount()` | Starts timers and tab sync. `AuthProvider` and the routers call it. | +| Call | What it does | +| ------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| `auth.state.get()`, `.subscribe()` | Reads the [state](/docs/client/state), or follows its changes. | +| `auth.getSession()` | Resolves who is signed in, restoring or refreshing first, or `null`. | +| `auth.signIn({ ...tokens, user })` | Saves a new session, replacing any current one. | +| `auth.signOut()` | Ends the session, clears storage, and tells other tabs. | +| `auth.updateUser(user)` | Replaces the user and keeps the session. | +| `auth.refresh()` | Refreshes now, even while the access token is usable. | +| `auth.retry()` | Tries again after a failed refresh. | +| `auth.isCurrent(session)` | Tells whether a session is still the signed-in one. | +| `auth.credentials.get()`, `.renew()`, `.reject()` | Resolves the access token, and replaces or ends it after a 401, for code that sends requests. | +| `auth.lock()`, `auth.unlock()` | Locks and unlocks a saved session, with [`locking`](/docs/client/locking). | +| `auth.mount()` | Starts timers and tab sync. `AuthProvider` and the routers call it. | Each method's JSDoc says what it resolves and which `AuthError` it rejects with, so your editor shows the details where you use them. +With server rendering, the browser's client comes from `createMirrorAuth`. It +has the same state, `getSession`, `signOut`, `isCurrent` and `credentials`, +but no `lock`, `unlock` or `updateUser`. See +[Server rendering](/docs/server-rendering). + The examples in this section build on the app from -[Getting started](/docs/getting-started): `auth` is its client, and +[Getting started](/docs/getting-started). `auth` is its client, and `authFetch` its `fetch`. diff --git a/site/content/docs/(latest)/client/locking.mdx b/site/content/docs/(latest)/client/locking.mdx index bbfda80..2c2a86b 100644 --- a/site/content/docs/(latest)/client/locking.mdx +++ b/site/content/docs/(latest)/client/locking.mdx @@ -5,7 +5,7 @@ description: Restore a saved session as locked until the user unlocks it, for ex Locking is for native apps that ask a returning user to unlock, for example with biometrics, before the app opens. With the `locking` option, a saved -session restores as `locked`: `user` and `sessionId` are set, so a +session restores as `locked`. `user` and `sessionId` are set, so a "Welcome back" screen can greet the user, but the tokens wait for `auth.unlock()`. @@ -47,9 +47,10 @@ export const lockApp = () => lockedAuth.lock(); - **While locked, nothing waits.** `getSession`, `retry`, `refresh`, `updateUser`, `credentials.get`, and `credentials.renew` reject with `LOCKED` instead of waiting for an unlock that may never come. Nothing - refreshes, and timers are off. `signIn` replaces the session, which is the - password path. After `lock()` resolves, `signOut` clears it without - calling `revoke`, since no tokens are left in memory. + refreshes, and timers are off. `signIn` still works and replaces the + locked session, so a user who can't unlock can sign in again. After + `lock()` resolves, `signOut` clears it without calling `revoke`, since no + tokens are left in memory. - **A failed unlock isn't always still locked.** When `open` throws, `unlock()` rejects with `UNLOCK_FAILED` and the session stays locked. But a refresh that fails after the tokens were opened rejects with diff --git a/site/content/docs/(latest)/client/other-http-clients.mdx b/site/content/docs/(latest)/client/other-http-clients.mdx index 94b0980..e2f3128 100644 --- a/site/content/docs/(latest)/client/other-http-clients.mdx +++ b/site/content/docs/(latest)/client/other-http-clients.mdx @@ -59,8 +59,8 @@ What changes for the client's calls: `INVALID_OPTIONS`, and the token isn't sent. - **Signed out, every call rejects** with `UNAUTHENTICATED`. If the client also calls public endpoints, such as your sign-in, create `authFetch` with - [`optional: true`](/docs/client/requests): those requests then go without a - token. + [`optional: true`](/docs/client/requests). Those requests then go without + a token. - **A 401 reaches the client after the refresh.** For a GET or HEAD, the client sees the answer to the request that was sent again. For a write, it sees the 401, as ky's `HTTPError` or axios's `AxiosError`. Retry it where @@ -144,7 +144,7 @@ Three things `createAuthFetch` does for you are yours to keep here: - **Keep the token on one origin.** Give the client one base URL, and don't pass it absolute URLs to other hosts. - **Don't read the token early.** Ask for credentials in the request hook, - never once at startup: a token saved in a variable goes stale at the next + never once at startup. A token saved in a variable goes stale at the next refresh. - **Check the account after slow work.** `auth.isCurrent(credentials)` tells whether the session that sent a request is still the signed-in one, before diff --git a/site/content/docs/(latest)/client/requests.mdx b/site/content/docs/(latest)/client/requests.mdx index cb97981..a0066c8 100644 --- a/site/content/docs/(latest)/client/requests.mdx +++ b/site/content/docs/(latest)/client/requests.mdx @@ -6,22 +6,25 @@ description: A fetch that sends the access token to one API, refreshes on a 401, `createAuthFetch(auth, { baseUrl })` returns a `fetch` for one API. It's built so that a token can't leak and a user can't be signed out by accident: -| When… | `authFetch`… | -| --------------------------------------- | ---------------------------------------------------------------------------- | -| The request is for another origin | Rejects with `INVALID_OPTIONS`. The token goes only to `baseUrl`'s origin. | -| The response is a redirect | Rejects rather than following it. | -| The response is a 401 | Refreshes once, then sends a GET or HEAD again with the new token. | -| A POST, PUT, PATCH or DELETE gets a 401 | Refreshes, and resolves the 401. It never sends a request twice on its own. | -| The replayed request gets a 401 too | Signs out, unless `signOutOnRepeated401` is `false`. | -| The session changes during the request | Rejects with `SESSION_CHANGED` rather than resolve another account's answer. | -| Nobody is signed in | Rejects with `UNAUTHENTICATED`, unless `optional` is `true`. | -| The network fails | Rejects as `fetch` does, unchanged. | +| When… | `authFetch`… | +| --------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| The request is for another origin, or has a username or password in its URL | Rejects with `INVALID_OPTIONS`. The token goes only to `baseUrl`'s origin. | +| The response is a redirect | Rejects rather than following it. | +| The response is a 401 | Refreshes once, then sends a GET or HEAD again with the new token. | +| Any other method gets a 401 | Refreshes, and resolves the 401. It never sends a request twice on its own. | +| The replayed request gets a 401 too | Signs out, unless `signOutOnRepeated401` is `false`. | +| The session changes during the request | Rejects with `SESSION_CHANGED` rather than resolve another account's answer. | +| Nobody is signed in | Rejects with `UNAUTHENTICATED`, unless `optional` is `true`. | +| The session is locked | Rejects with `LOCKED`, even when `optional` is `true`. | +| The network fails | Rejects as `fetch` does, unchanged. | Call it with a path, which is resolved against `baseUrl` as a link is against a page's address. End `baseUrl` with `/`, so that `authFetch("orders")` lands under it. It also takes a `URL` or a `Request`, as `fetch` does, so an HTTP client with a `fetch` option can send its -requests through it: see [Other HTTP clients](/docs/client/other-http-clients). +requests through it. See [Other HTTP clients](/docs/client/other-http-clients). +A `Request` with a body is used up once sent, so read +[`AuthFetch`](/docs/reference/http#authfetch) before you retry one. Because a write is never replayed for you, retry it yourself where sending it twice is safe. By then the token has been refreshed: diff --git a/site/content/docs/(latest)/client/sessions.mdx b/site/content/docs/(latest)/client/sessions.mdx index 24d5595..c45e4d6 100644 --- a/site/content/docs/(latest)/client/sessions.mdx +++ b/site/content/docs/(latest)/client/sessions.mdx @@ -25,10 +25,10 @@ export async function loadCart(): Promise { **Credentials** are the access token, `{ sessionId, accessToken, expiresAt }`, kept apart so that code which only needs the user never holds one. [`createAuthFetch`](/docs/client/requests) reads them for you, and so does -an HTTP client that takes it as its `fetch`. Code that sends requests another -way uses `auth.credentials`: `get` before a request, `renew` after a 401, and -`reject` after a second one. -[Other HTTP clients](/docs/client/other-http-clients) explains both. +an HTTP client that takes `authFetch` as its `fetch`. Code that sends +requests another way uses `auth.credentials`, as +[Other HTTP clients](/docs/client/other-http-clients#clients-without-a-fetch-option) +shows. `auth.isCurrent({ sessionId })` tells whether a session you're holding is still the signed-in one, for work that might finish after an account switch. diff --git a/site/content/docs/(latest)/client/signing-in-and-out.mdx b/site/content/docs/(latest)/client/signing-in-and-out.mdx index 8dc5bea..947633b 100644 --- a/site/content/docs/(latest)/client/signing-in-and-out.mdx +++ b/site/content/docs/(latest)/client/signing-in-and-out.mdx @@ -3,17 +3,19 @@ title: Signing in and out description: Save a new session, end it in every tab, and revoke the ended tokens on your backend. --- -`auth.signIn({ accessToken, refreshToken?, expiresIn?, user })` validates and -saves a new session, replacing any current one. The latest call wins, and -invalid input keeps the previous session. [Expiry](/docs/configuration/expiry) -covers how the token's lifetime is found. +`auth.signIn({ ...tokens, user })` validates and saves a new session, +replacing any current one, even a locked one. With +[`fromAccessToken`](/docs/client/users-from-tokens), leave out `user`. The +latest call wins, and invalid input keeps the previous session. +[Expiry](/docs/configuration/expiry) covers how the token's lifetime is +found. `auth.signOut()` ends the session and clears storage. Other tabs sign out too when the storage reports changes, as `webStorage()` does, and `locking` is off. -If your backend can revoke tokens, give the client a `revoke` callback: it -receives the ended tokens once the user is already signed out. +If your backend can revoke tokens, give the client a `revoke` callback. It +receives the ended tokens after the user is signed out. ```ts title="src/revoke.ts" import type { RevokeFn } from "@monarcode/session-kit"; @@ -31,6 +33,6 @@ export const revoke: RevokeFn = async ({ refreshToken, signal }) => { }; ``` -A failed revocation is reported in `state.error` as `REVOKE_FAILED` without -undoing the sign-out: the user asked to leave, and has. The client doesn't -revoke a session the backend already rejected. +A failed revocation shows in `state.error` as `REVOKE_FAILED`, and the +sign-out stands. The user asked to leave, and has. The client doesn't revoke +a session the backend already rejected. diff --git a/site/content/docs/(latest)/client/state.mdx b/site/content/docs/(latest)/client/state.mdx index 896a7d9..03fc9a7 100644 --- a/site/content/docs/(latest)/client/state.mdx +++ b/site/content/docs/(latest)/client/state.mdx @@ -22,7 +22,7 @@ export function logStatus() { ``` `subscribe` reports later changes, not the current value. A listener that -throws doesn't interrupt auth: its error is rethrown asynchronously, where +throws doesn't interrupt auth. Its error is rethrown asynchronously, where error reporting can catch it. | Field | Holds | @@ -39,5 +39,5 @@ Two habits follow from these fields: results, so one account never sees another's. - **Check `status`, not `user`, to know whether access is usable.** A [locked](/docs/client/locking) session keeps its user. `isSignedIn(state)` - is the check: `true` while `authenticated` or `refreshing`, and it narrows - `user`. `useAuth(isSignedIn)` reads it in a component. + is the check. It's `true` while `authenticated` or `refreshing`, and it + narrows `user`. `useAuth(isSignedIn)` reads it in a component. diff --git a/site/content/docs/(latest)/configuration/errors.mdx b/site/content/docs/(latest)/configuration/errors.mdx index e537fc2..e3fb211 100644 --- a/site/content/docs/(latest)/configuration/errors.mdx +++ b/site/content/docs/(latest)/configuration/errors.mdx @@ -1,31 +1,18 @@ --- title: Errors -description: The AuthError codes Session kit fails with, how to show them to users, and the storage failures that need your decision. +description: How Session kit's errors reach your app, how to show them to users, and the storage failures that need your decision. --- Every error from Session kit's own logic is an `AuthError`, whether a method -throws it, rejects with it, or publishes it in `state.error`. This page lists -the codes, shows how to turn them into messages for your users, and covers the +throws it, rejects with it, or publishes it in `state.error`. This page shows +how to match on them, how to turn them into messages for your users, and the two storage failures you need to handle. ## Error codes -Match on an error's `code`, not its message, which may change in any release: - -| Code | Meaning | -| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `UNAUTHENTICATED` | The operation needs a signed-in session, and there is none. | -| `REFRESH_FAILED` | The refresh callback threw, or there was no callback or refresh token to use. With server rendering, reading the session or the access token from the server failed. | -| `SESSION_CHANGED` | A newer sign-in, a sign-out, or another tab replaced the session while this ran. | -| `USER_VALIDATION_FAILED` | The user couldn't be accepted: the schema rejected it (`issues`), or an `updateUser` function failed (`cause`). | -| `INVALID_SESSION` | Tokens or a saved session that can't be used, such as an expired token at sign-in. | -| `PERSISTENCE_FAILED` | Storage couldn't be read, written, or cleared. With server rendering, signing out on the server failed. | -| `REVOKE_FAILED` | The `revoke` callback failed. Published in `state.error`; `signOut()` still resolves. | -| `LOCKED` | The session is locked: `unlock()` it first. | -| `UNLOCK_FAILED` | `locking.open` failed, so the session stays locked. | -| `INVALID_OPTIONS` | Misuse: an option or argument Session kit can't use. | - -See [Error codes](/docs/reference/error-codes) for each code in full. +Match on an error's `code`, not its message, which may change in any +release. [Error codes](/docs/reference/error-codes) lists every code and what +it means. ## Show errors to users @@ -48,10 +35,10 @@ export function errorMessage(error: unknown): string { } ``` -`authFetch` lets the failures of `fetch` and `Request`, such as a network -error, through unchanged. So does the `signIn` of a server-rendered app's -browser client, for what your sign-in function threw. They aren't -`AuthError`s, so `errorMessage` shows their own message. +`authFetch` passes on the failures of `fetch` and `Request`, such as a +network error, unchanged. With server rendering, the browser client's +`signIn` passes on what your sign-in function threw, unchanged too. These +usually aren't `AuthError`s, so `errorMessage` shows their own message. ## Handle storage failures diff --git a/site/content/docs/(latest)/configuration/expiry.mdx b/site/content/docs/(latest)/configuration/expiry.mdx index 4ba8bb1..1174fae 100644 --- a/site/content/docs/(latest)/configuration/expiry.mdx +++ b/site/content/docs/(latest)/configuration/expiry.mdx @@ -21,7 +21,7 @@ counts it from when it receives the tokens, so a wrong device clock doesn't matter. A JWT with `iat` works the same way. Send `expiresAt` only when your backend gives no lifetime. -Pass `expiresIn` or `expiresAt`, not both: tokens with both are an +Pass `expiresIn` or `expiresAt`, not both. Tokens with both are an `INVALID_SESSION` error. See [`Tokens`](/docs/reference/core#tokens) for each field. diff --git a/site/content/docs/(latest)/configuration/index.mdx b/site/content/docs/(latest)/configuration/index.mdx index 7d4229f..4ada43d 100644 --- a/site/content/docs/(latest)/configuration/index.mdx +++ b/site/content/docs/(latest)/configuration/index.mdx @@ -11,16 +11,16 @@ longer fit your app. `createAuth` takes three required options and five optional ones: -| Option | Required | What it sets | -| --------- | -------- | ---------------------------------------------------------------------------------------------------------- | -| `name` | Yes | The storage namespace: letters, digits, `_` or `-`. Keeps two apps on one origin apart. | -| `user` | Yes | A [user schema](/docs/configuration/user-schemas), or [`fromAccessToken`](/docs/client/users-from-tokens). | -| `storage` | Yes | [Where the session is saved](/docs/configuration/storage). | -| `refresh` | No | [How to get new tokens](/docs/configuration/refresh). Without it, an expired token signs the user out. | -| `revoke` | No | [Revokes the ended tokens](/docs/client/signing-in-and-out) on your backend after a sign-out. | -| `maxAge` | No | How long a saved session can be restored, in seconds. Default: 30 days, counted again from each save. | -| `debug` | No | [Reports what the client does](/docs/configuration/debugging). Default: off. | -| `locking` | No | [Restores a saved session as `locked`](/docs/client/locking), for native apps. Default: off. | +| Option | Required | What it sets | +| --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| `name` | Yes | Names the saved session and the refresh lock: letters, digits, `_` or `-`, up to 64 characters. Keeps two apps on one origin apart. | +| `user` | Yes | A [user schema](/docs/configuration/user-schemas), or [`fromAccessToken`](/docs/client/users-from-tokens). | +| `storage` | Yes | [Where the session is saved](/docs/configuration/storage). | +| `refresh` | No | [How to get new tokens](/docs/configuration/refresh). Without it, an expired token signs the user out. | +| `revoke` | No | [Revokes the ended tokens](/docs/client/signing-in-and-out) on your backend after a sign-out. | +| `maxAge` | No | How long a saved session can be restored, in seconds. Default: 30 days, counted again from each save. | +| `debug` | No | [Reports what the client does](/docs/configuration/debugging). Default: off. | +| `locking` | No | [Restores a saved session as `locked`](/docs/client/locking), for native apps. Default: off. | ## Pages in this section @@ -56,7 +56,7 @@ tokens, saves the session, follows other tabs, and reports what happens. :auth:session` entry. Each save is then a single write, which other tabs see whole. A [user read from the access token](/docs/client/users-from-tokens) isn't -saved: the client reads it from the token again on restore. - -Sessions saved by 0.1.0-alpha.3 or earlier aren't restored. Users of those -versions sign in once after upgrading. +saved. The client reads it from the token again on restore. diff --git a/site/content/docs/(latest)/configuration/tabs.mdx b/site/content/docs/(latest)/configuration/tabs.mdx index 1ae58cb..3dd5c54 100644 --- a/site/content/docs/(latest)/configuration/tabs.mdx +++ b/site/content/docs/(latest)/configuration/tabs.mdx @@ -15,6 +15,10 @@ through `storage` events: - A sign-in or an account switch switches every tab. - A profile update or a refresh shows in every tab. +With server rendering, `createMirrorAuth` clients follow each other over a +`BroadcastChannel` instead, as [Server rendering](/docs/server-rendering) +explains. + ## One refresh at a time The client refreshes under the `:auth:refresh` @@ -25,8 +29,8 @@ Rotating refresh tokens therefore work with several tabs open. Without Web Locks, two tabs that refresh at the same instant can both spend the token. A short reuse window on your backend covers that case. -## Expo apps and locking +## Expo apps An Expo app has one JavaScript context, so it has no tabs to follow and needs -no lock. With [`locking`](/docs/client/locking) on, tabs don't follow each -other. +no lock. In a browser, [`locking`](/docs/client/locking) stops tabs from +following each other. diff --git a/site/content/docs/(latest)/configuration/user-schemas.mdx b/site/content/docs/(latest)/configuration/user-schemas.mdx index ca12a67..5e5c02a 100644 --- a/site/content/docs/(latest)/configuration/user-schemas.mdx +++ b/site/content/docs/(latest)/configuration/user-schemas.mdx @@ -9,13 +9,14 @@ and the two rules it must follow so that a saved session can be restored. Any [Standard Schema](https://standardschema.dev) library works, such as Zod, Valibot or ArkType. If your backend puts the user in the access token -instead, see [Users from tokens](/docs/client/users-from-tokens). +instead, see [Users from the access token](/docs/client/users-from-tokens). ## When the schema runs The client runs the schema on every user it accepts: - At sign-in. +- When `updateUser` replaces the user. - After a refresh that returns a user. - When it restores a saved session. - When another tab saves a session. @@ -42,6 +43,11 @@ const { user } = auth.state.get(); // ^? ``` +To name the types elsewhere, use `UserOf` and +`SessionOf`. To type the hooks from +`@monarcode/session-kit/react`, register the client once, as +[Getting started](/docs/getting-started#4-read-the-session-in-react) shows. + ## Rules for restoring The client saves the user beside the tokens, and runs the schema on it again @@ -52,13 +58,13 @@ when it restores the session. That sets two rules for the schema: - **It accepts its own output and returns it unchanged.** A one-way transform, such as one that renames a field, breaks this rule. -`signIn` rejects a schema that breaks either rule with -`USER_VALIDATION_FAILED`. That way the problem shows up when you sign in, -not as users being signed out on their next reload. +A schema that breaks either rule is rejected with `USER_VALIDATION_FAILED` +the first time it accepts a user, usually at sign-in. That way the problem +shows up at once, not as users being signed out on their next reload. ## Users the schema rejects A deploy can change the schema so that it rejects users saved before it. The -client doesn't restore such a user: the user signs in again. A user saved by +client doesn't restore such a user, so the user signs in again. A user saved by another tab that the schema rejects signs every tab out, with `USER_VALIDATION_FAILED` in `state.error`. diff --git a/site/content/docs/(latest)/effect.mdx b/site/content/docs/(latest)/effect.mdx index 632ab5c..ebdeb61 100644 --- a/site/content/docs/(latest)/effect.mdx +++ b/site/content/docs/(latest)/effect.mdx @@ -573,8 +573,9 @@ import type { ServerSession } from "./auth.js"; import { runRequest } from "./run.js"; // TanStack Start: startAuth(serverAuth). React Router: -// routerAuth(serverAuth)(context). Next.js: await session.writable(), -// from nextSession(serverAuth, { cookies, redirect }). +// routerAuth(serverAuth)(context). Next.js, from +// nextSession(serverAuth, { cookies, redirect }): await session.writable() +// in a Server Function, or await session.readOnly() in a Server Component. export const profileFor = (session: ServerSession) => runRequest(session, currentUser); ``` @@ -633,12 +634,13 @@ the mirror client. ### Things to know - **One registration.** An app with server rendering registers its mirror - client, and that registration types `Auth` on the server too: `Auth.layer` + client, and that registration types `Auth` on the server too. `Auth.layer` takes a request's session whose user is the registered one. In the browser, `Auth.layer(mirror)` is built where the mirror is created. - `Auth.signIn` needs the mirror's `signIn` option there, `sessionBearer` - its `credentials` option, and `Auth.updateUser` isn't available, since the - user comes from the server. + `Auth.signIn` needs the mirror's `signIn` option there. `sessionBearer` + needs `clientCredentials: true` in `createServerAuth`, or the mirror's + `credentials` option. `Auth.updateUser` isn't available, since the user + comes from the server. - **Keep server modules free of the browser client.** In this guide, the server's files import only `src/backend.ts`, `src/refresh.ts`, `src/api.ts` and `src/user.ts`, which create no Session kit client. Keep it that way in @@ -657,11 +659,10 @@ the mirror client. so overlapping requests can get one build: a service that keeps `Auth` when it's built would then serve one request's session to another. - **Requests that can't set cookies,** such as a Next.js Server - Component's: `Auth.session` returns the cookie's session as it is, while - `Auth.credentials` and `sessionBearer` fail with `REFRESH_FAILED` once - access has expired, and after a 401, which can't be renewed there unless - the same request already renewed it where it could. Refresh in middleware - or Proxy first, as the framework guides do. Sign + Component's. `Auth.session` returns the cookie's session as it is. + `Auth.credentials` and `sessionBearer` fail with `REFRESH_FAILED` once the + access token has expired, or after a 401, since nothing new can be saved. + Refresh first, in middleware or Proxy, as the framework guides do. Sign out in an action or route handler. - **Only `Auth`'s Effects.** A request's session isn't your browser client, so don't reach for client methods through `Auth.use` there. diff --git a/site/content/docs/(latest)/faq.mdx b/site/content/docs/(latest)/faq.mdx index 0785502..6bee967 100644 --- a/site/content/docs/(latest)/faq.mdx +++ b/site/content/docs/(latest)/faq.mdx @@ -39,8 +39,8 @@ does. ## What if some endpoints answer 401 for other reasons? -Pass `{ signOutOnRepeated401: false }` to `createAuthFetch`, so that those -endpoints can't sign users out. See +Set `signOutOnRepeated401: false` in `createAuthFetch`'s options, beside +`baseUrl`, so that those endpoints can't sign users out. See [Authenticated requests](/docs/client/requests). ## How much does it add to my bundle? diff --git a/site/content/docs/(latest)/getting-started.mdx b/site/content/docs/(latest)/getting-started.mdx index 6e7a79b..289b9f2 100644 --- a/site/content/docs/(latest)/getting-started.mdx +++ b/site/content/docs/(latest)/getting-started.mdx @@ -4,10 +4,9 @@ description: Build a small app that signs in, stays signed in across reloads and --- In this guide, you build a small React app that signs in, stays signed in -across reloads and tabs, calls an API, and signs out. The six steps are the -same for every setup that keeps the session in the browser or on the device. -Server-rendered apps create their client differently, so start from -[Server rendering](/docs/server-rendering) instead. +across reloads and tabs, calls an API, and signs out. The web router guides +build on this app. Server-rendered apps create their client differently, so +start from [Server rendering](/docs/server-rendering) instead. The code signs in against [DummyJSON's auth API](https://dummyjson.com/docs/auth), a public test @@ -15,7 +14,7 @@ backend, so it runs as written. ## Before you begin -Install Session kit, Zod, and React, as +In a React app, install Session kit and Zod, as [Installation](/docs/installation) shows. ## 1. Talk to your backend @@ -71,7 +70,7 @@ export async function refresh(refreshToken: string, signal: AbortSignal) { } ``` -The schemas do two jobs: they check what the backend sent, and they give the +The schemas do two jobs. They check what the backend sent, and they give the rest of the app its types. Requests omit `credentials: "include"`, because Session kit keeps tokens out of cookies and attaches them itself. @@ -111,7 +110,8 @@ doesn't sign anyone out. [Refresh](/docs/configuration/refresh) has the details, and [Storage](/docs/configuration/storage) lists the other places a session can be saved. -Create one client per `name` in each tab, once, as this module does. +Create the client once, at module level, as this file does. Give each client +in an app its own `name`. DummyJSON's tokens are JWTs, so their expiry comes from the `exp` and `iat` claims. [Expiry](/docs/configuration/expiry) covers backends that say it @@ -127,7 +127,7 @@ import { useState, type FormEvent } from "react"; import { signInWithPassword } from "./auth.js"; -export function SignIn({ onSignedIn }: { onSignedIn?: () => unknown }) { +export function SignIn() { const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -141,7 +141,6 @@ export function SignIn({ onSignedIn }: { onSignedIn?: () => unknown }) { String(form.get("username")), String(form.get("password")), ); - await onSignedIn?.(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { @@ -173,9 +172,9 @@ export function SignIn({ onSignedIn }: { onSignedIn?: () => unknown }) { } ``` -The form doesn't have to do anything when it succeeds: signing in changes the -client's state, and the next step renders from that state. `onSignedIn` is for -routers, which use it to send the user on to the page they asked for. +The form doesn't have to do anything when it succeeds. Signing in changes the +client's state, and the next step renders from that state. With a router, the +sign-in page's guard runs again and sends the user on. ## 4. Read the session in React @@ -248,18 +247,21 @@ function AuthError() { } ``` -- `AuthProvider` mounts the client: it restores the saved session, starts the +- `AuthProvider` mounts the client. It restores the saved session, starts the refresh timer, and follows other tabs. - `useAuth()` returns the whole state. `useAuth(selector)` returns a part of it, and re-renders only when that part changes, as `AuthError` does. - `useAuthClient()` returns the client, for actions. - With more than one client in an app, create hooks for each with `createAuthHooks()` instead. +- `isSignedIn(state)` is `true` while `authenticated` or `refreshing`. Pass it + to `useAuth` to read just that: `useAuth(isSignedIn)`. It comes from + `@monarcode/session-kit`. - `retry` and `signOut` reject when they fail, and publish the same failure in `state.error`. `AuthError` shows it, so the handlers have nothing left to do. -With [`locking`](/docs/client/locking), give `locked` a case of its own: it +With [`locking`](/docs/client/locking), give `locked` a case of its own. It has a user too, but no usable access. That's a working app. To check it: @@ -305,8 +307,9 @@ your router: [TanStack Start in SPA mode](/docs/setups/tanstack-router#tanstack-start-in-spa-mode). - [React Router](/docs/setups/react-router), in declarative, data, or framework mode with `ssr: false`. -- [Expo Router](/docs/setups/expo), for iOS and Android. -- Without a router, you are done: render by `status`, as `Screen` does. +- [Expo Router](/docs/setups/expo), for iOS and Android. Its guide starts from + scratch. +- Without a router, you are done. Render by `status`, as `Screen` does. With Effect, the same client becomes a service: see [Effect and effetch](/docs/effect). diff --git a/site/content/docs/(latest)/index.mdx b/site/content/docs/(latest)/index.mdx index 0e738ab..d296be8 100644 --- a/site/content/docs/(latest)/index.mdx +++ b/site/content/docs/(latest)/index.mdx @@ -45,7 +45,7 @@ Session kit handles each of these moments for you: ### What it doesn't do Session kit doesn't sign users in. It has no sign-in form, no OAuth flow, and -no user database: it starts where your backend's sign-in response ends. If you +no user database. It starts where your backend's sign-in response ends. If you need those too, use an auth service or framework such as Auth.js, Better Auth, or Clerk, which manage their own sessions. diff --git a/site/content/docs/(latest)/installation.mdx b/site/content/docs/(latest)/installation.mdx index 7d983e1..0f0ea07 100644 --- a/site/content/docs/(latest)/installation.mdx +++ b/site/content/docs/(latest)/installation.mdx @@ -58,7 +58,7 @@ Two guides apply to more than one setup: ## Next steps - For a setup that keeps the session in the browser or on the device, start - with [Getting started](/docs/getting-started). The router guides build on - its app. + with [Getting started](/docs/getting-started). The web router guides build + on its app. The Expo guide starts from scratch. - For a server-rendered setup, start with [Server rendering](/docs/server-rendering). diff --git a/site/content/docs/(latest)/reference/compatibility.mdx b/site/content/docs/(latest)/reference/compatibility.mdx index a9da827..e7b73ff 100644 --- a/site/content/docs/(latest)/reference/compatibility.mdx +++ b/site/content/docs/(latest)/reference/compatibility.mdx @@ -50,6 +50,8 @@ Hermes and Metro), and in Node.js 20 and newer: - **Web Locks** keep tabs to one refresh at a time when present. Without them, two tabs can refresh at the same instant, as [Tabs](/docs/configuration/tabs) explains. +- **`BroadcastChannel`** lets a `createMirrorAuth` client follow sign-ins and + sign-outs in other tabs, when present. - **Web Crypto** is required on the server by `@monarcode/session-kit/server`, as in Node.js 20 and newer. diff --git a/site/content/docs/(latest)/reference/error-codes.mdx b/site/content/docs/(latest)/reference/error-codes.mdx index c9a40d3..92b403c 100644 --- a/site/content/docs/(latest)/reference/error-codes.mdx +++ b/site/content/docs/(latest)/reference/error-codes.mdx @@ -3,8 +3,8 @@ title: Error codes description: Every AuthErrorCode, what it means and when you'll see it. --- -Every error Session kit throws or reports is an `AuthError`. Match on its -`code`; the `message` is for people, and may change. +Every error from Session kit's own logic is an `AuthError`. Match on its +`code`. The `message` is for people, and may change. ```ts title="src/error-codes.ts" import { AuthError } from "@monarcode/session-kit"; diff --git a/site/content/docs/(latest)/reference/server.mdx b/site/content/docs/(latest)/reference/server.mdx index 1704fbf..75e74f9 100644 --- a/site/content/docs/(latest)/reference/server.mdx +++ b/site/content/docs/(latest)/reference/server.mdx @@ -57,7 +57,7 @@ Options for [`ServerAuth`](#serverauth)'s `refreshIfDue`. ### RequestAuth -One request's session: what [`ServerAuth`](#serverauth) does for a request, without its [`CookieJar`](#cookiejar). `startAuth` from `@monarcode/session-kit/tanstack-start/server` and `routerAuth` from `@monarcode/session-kit/react-router/server` give you one. Elsewhere, `serverAuth.forRequest(jar)` does. +One request's session: what [`ServerAuth`](#serverauth) does for a request, without its [`CookieJar`](#cookiejar). `startAuth` from `@monarcode/session-kit/tanstack-start/server` and `routerAuth` from `@monarcode/session-kit/react-router/server` give you one, and so do `readOnly()` and `writable()` from `nextSession` in `@monarcode/session-kit/next`. Elsewhere, `serverAuth.forRequest(jar)` does. ### ServerAuth diff --git a/site/content/docs/(latest)/security.mdx b/site/content/docs/(latest)/security.mdx index c85529d..831454d 100644 --- a/site/content/docs/(latest)/security.mdx +++ b/site/content/docs/(latest)/security.mdx @@ -13,6 +13,12 @@ Your backend must authenticate every request and authorize private operations. Route guards, screen guards and the user's fields in the client decide what to show, not what's allowed. +With server rendering, `signIn` seals what it's given. If the browser signs +in with your backend and sends the tokens and the user, the cookie's user is +what the browser sent, until a refresh or `updateUser` replaces it. Use it to +show who is signed in. Let your backend authorize requests with the access +token, or check the tokens before `signIn`. + ## Where tokens live Each setup saves the tokens in a different place: @@ -34,24 +40,24 @@ Each setup saves the tokens in a different place: ## The session route -With server rendering, the browser's client reads the session, signs out and -gets the access token through your session route. `sessionHandler` from -`@monarcode/session-kit/server` answers it, through each framework's -`sessionRoute`. +With server rendering, the browser's client signs out and gets the access +token through your session route, and reads the session there in most +setups. `sessionHandler` from `@monarcode/session-kit/server` answers it, +through each framework's `sessionRoute`. It answers your own site's pages only, so another site can't sign the user -out or ask for the access token. It checks the `Sec-Fetch-Site` header, -which browsers send to https and localhost pages since 2023 (Safari 16.4). -On plain http, such as a phone testing your dev server, a `POST` needs an -`Origin` header that matches the request's URL. Anything else is refused -with 403. Every answer has `Cache-Control: no-store`. +out or ask for the access token. +[`sessionHandler`](/docs/reference/server#sessionhandler) says how it tells. Signing in stays your own server code. A route of your own that changes the session must refuse other sites too, where the framework doesn't check. +Refuse a request that has a `Sec-Fetch-Site` header other than `same-origin`. +On plain http, where browsers don't send that header, refuse a `POST` whose +`Origin` isn't your site's. ## Where tokens go -[`authFetch`](/docs/client/requests) and the effetch plugin +[`createAuthFetch`](/docs/client/requests) and the effetch plugin [`sessionBearer`](/docs/effect#6-call-your-api-with-effetch) send the access token only to your API's origin: diff --git a/site/content/docs/(latest)/server-rendering/index.mdx b/site/content/docs/(latest)/server-rendering/index.mdx index 3c447ff..4af9695 100644 --- a/site/content/docs/(latest)/server-rendering/index.mdx +++ b/site/content/docs/(latest)/server-rendering/index.mdx @@ -21,19 +21,20 @@ before rendering, so pages never show a "Checking session…" state. - **In the browser**, `createMirrorAuth` makes a client that starts from the session the server rendered. `AuthProvider`, the hooks, and the TanStack Router guards work with it, and sign-ins and sign-outs reach every tab. -- **Your server code** signs in and out with your backend and calls your API - with the access token, through one request's session. It's shaped like a +- **Your server code** signs in with your backend and calls your API with + the access token, through one request's session. It's shaped like a client, so code written for one, such as `createAuthFetch` or Effect's `Auth`, takes it. To call your API from the browser too, opt in with - `clientCredentials`: page scripts then get the access token in memory, + `clientCredentials`. Page scripts then get the access token in memory, never the refresh token. -The engine is the same `createServerAuth` call in every framework: +The engine is the same `createServerAuth` call in every framework. [Create the server engine](/docs/setups/tanstack-start#1-create-the-server-engine) on the TanStack Start page shows one. The browser's client mirrors what the -server rendered. It reads the session and signs out through a session route, -which each adapter's `sessionRoute` makes, and signs in through your own -server code, as in +server rendered. It signs out and gets the access token through a session +route, which each adapter's `sessionRoute` makes. It reads the session there +too, except in TanStack Start, where a server function reads it, as the +server render needs. It signs in through your own server code, as in [Create the browser client](/docs/setups/tanstack-start#4-create-the-browser-client). ## Frameworks @@ -41,16 +42,15 @@ server code, as in What differs between frameworks is how server code gets a request's session, and how the session reaches the browser: -| Framework | On the server | In the browser | Setup | -| ------------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------- | -| TanStack Start | `startAuth(serverAuth)`, with `refreshSession` in request middleware | `connectSession`, `loadSession` | [TanStack Start](/docs/setups/tanstack-start) | -| Next.js 16, App Router | `nextSession(serverAuth, { cookies, redirect })` | `useMirrorAuth` from `@monarcode/session-kit/react` | [Next.js](/docs/setups/next) | -| React Router framework mode, with SSR | `routerAuth(serverAuth)`, with `sessionMiddleware` in the root route | `useMirrorAuth` from `@monarcode/session-kit/react` | [React Router with server rendering](/docs/setups/react-router-ssr) | +| Framework | On the server | In the browser | Setup | +| ------------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------- | +| TanStack Start | `startAuth(serverAuth)`, with `refreshSession` in request middleware | `connectSession`, `loadSession` | [TanStack Start](/docs/setups/tanstack-start) | +| Next.js 16, App Router | `nextSession(serverAuth, { cookies, redirect })`, with its `refresh` in Proxy | `useMirrorAuth` from `@monarcode/session-kit/react` | [Next.js](/docs/setups/next) | +| React Router framework mode, with SSR | `routerAuth(serverAuth)`, with `sessionMiddleware` in the root route | `useMirrorAuth` from `@monarcode/session-kit/react` | [React Router with server rendering](/docs/setups/react-router-ssr) | Locking isn't available with server rendering. For another server, such as -the Next.js Pages Router, build a `CookieJar` over its cookies and pass it -to `serverAuth.forRequest(jar)`. Its session route is `sessionHandler`, from -`@monarcode/session-kit/server`, called with the request and that jar. +the Next.js Pages Router, see +[Servers without an adapter](/docs/server-rendering/server-sessions#servers-without-an-adapter). ## Next steps diff --git a/site/content/docs/(latest)/server-rendering/server-sessions.mdx b/site/content/docs/(latest)/server-rendering/server-sessions.mdx index 6a53ce8..6c966d2 100644 --- a/site/content/docs/(latest)/server-rendering/server-sessions.mdx +++ b/site/content/docs/(latest)/server-rendering/server-sessions.mdx @@ -4,8 +4,8 @@ description: How the server keeps the session in every framework, from the cooki --- This page covers what every server-rendered setup shares: the cookie and its -secret, a request's session, refreshes, sign-out, and limits. Read it once your app -works, to deploy it. The setup guides show the code: +secret, a request's session, refreshes, sign-out, and limits. Read it once +your app works, to deploy it. The setup guides show the code: [TanStack Start](/docs/setups/tanstack-start), [Next.js](/docs/setups/next), and [React Router with server rendering](/docs/setups/react-router-ssr). @@ -18,7 +18,7 @@ Crypto. It's `httpOnly`, so page scripts can't read it, and `Secure` and `createAuth` does, except `storage` and `locking`, plus `secret`, `cookie` and `clientCredentials`. -Keep the module that creates it on the server: each setup page shows how +Keep the module that creates it on the server. Each setup guide shows how its framework keeps such a module out of the browser bundle. ## The secret @@ -72,11 +72,10 @@ a renewed one after a 401, and Effect's `Auth.layer` takes it Some requests can't set cookies: a Next.js Server Component rendering, or a React Router loader once its response has left the middleware. There, -nothing is saved, so `signIn`, `signOut` and `refreshIfDue` reject with -`INVALID_OPTIONS`, and an expired access token rejects with -`REFRESH_FAILED`. TanStack Start can't tell once a page has started -streaming, so a cookie set then is lost. Refresh before rendering, with the -middleware each setup guide adds: `refreshSession` in TanStack Start, +nothing is saved, so the methods that write reject, and an expired access +token rejects with `REFRESH_FAILED`. TanStack Start can't tell once a page +has started streaming, so a cookie set then is lost. Refresh before rendering, +with the middleware each setup guide adds: `refreshSession` in TanStack Start, `sessionMiddleware` in React Router, and `nextSession`'s `refresh` in Next.js's Proxy. @@ -86,7 +85,8 @@ Every `serverAuth` method also takes the request's `CookieJar` first: `serverAuth.getSession(jar)` does what a request's `getSession()` does, and `serverAuth.forRequest(jar)` gives that request's session. For a server without an adapter, build a [`CookieJar`](/docs/reference/server#cookiejar) -over its cookies. +over its cookies. Answer the browser client's session route with +`sessionHandler(serverAuth)`, called with the request and its jar. Use one jar per request. Calls with the same jar share what it read and wrote and one refresh, so a jar kept at module level would show one @@ -142,8 +142,8 @@ The session route answers your own site's pages only: see - **Plain http.** The cookie is `Secure` by default. Browsers accept that on `http://localhost` except Safari: pass `cookie: { secure: false }` for local development there, never in production. -- **Locking.** `locking` isn't available: the server keeps the tokens, so - there is nothing on the device to lock. +- **Locking.** `locking` isn't available. The server keeps the tokens, so + there's nothing on the device to lock. ## Next steps diff --git a/site/content/docs/(latest)/setups/expo.mdx b/site/content/docs/(latest)/setups/expo.mdx index c517bb3..a854ea4 100644 --- a/site/content/docs/(latest)/setups/expo.mdx +++ b/site/content/docs/(latest)/setups/expo.mdx @@ -25,7 +25,7 @@ covers what differs on Expo. - Expo SDK 53 or newer: Expo Router 5 or newer, and React Native 0.79 or newer. -- iOS and Android only. Expo web is not supported: on the web, use a +- iOS and Android only. Expo web is not supported. On the web, use a [web router setup](/docs/installation#pick-your-setup) with `webStorage()`. - Expo Go, which includes `expo-secure-store` and `expo-file-system`, or a development build with both installed. @@ -118,7 +118,7 @@ export async function signInWithPassword(username: string, password: string) { `SessionGate` goes inside `AuthProvider`, around the root navigator. Guard the screens with `Stack.Protected`. Signed-in users see the `(app)` group, and -everyone else sees `login`. Register the client's type here too, so the hooks +everyone else sees `login`. Register the client's type here, so the hooks from `@monarcode/session-kit/react` carry your user: ```tsx title="app/_layout.tsx" @@ -200,7 +200,7 @@ import { auth } from "../src/auth"; export const redirectSystemPath = deepLinkHandler(auth); ``` -It returns the path unchanged: the link still goes to Expo Router, which +It returns the path unchanged. The link still goes to Expo Router, which shows it right away when the user is signed in. If your `redirectSystemPath` does more, such as rewriting old links, call `rememberDeepLink(auth, path)` in it instead. @@ -271,41 +271,77 @@ export default function AppLayout() { } ``` -Its first screen shows the user's name, fetches their email, and signs out: +Its first screen shows the user's name, links to the profile, and signs out: ```tsx title="app/(app)/index.tsx" -import { useEffect, useState } from "react"; import { Button, Text, View } from "react-native"; import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; - -import { authFetch } from "../../src/auth"; +import { Link } from "expo-router"; export default function Home() { const firstName = useAuth((state) => state.user?.firstName); const auth = useAuthClient(); - const [email, setEmail] = useState(""); + return ( + + Welcome, {firstName} + Profile + {/* No navigation: Stack.Protected then shows the sign-in screen. */} + + {count !== null &&

{count} orders

} +
+ ); +} +``` + +The browser keeps the access token in memory, never the refresh token. After +a 401, the client asks the session route for a new token, and the server +refreshes with the cookie's refresh token. Server functions can still call +your API too, as the guide's +[Call your API](/docs/setups/tanstack-start#call-your-api) shows. + +## Things to know + +- **The refresh token passes through the browser once,** in your backend's + sign-in response, on its way to the server. After that, page scripts never + see it. If your backend's sign-in can run on the server, sign in there, as + the setup guides do. +- **Your backend must allow your site (CORS)** for its sign-in and the API + calls you make from the browser. Session kit's own requests go to your + session route, on your site. +- **Signing out** works as in the guide, through the session route. To end + the session at your backend too, give `createServerAuth` a `revoke`. +- **Security** has more on what the cookie's user can be trusted for, in + [Your backend decides what's allowed](/docs/security#your-backend-decides-whats-allowed). diff --git a/site/content/docs/(latest)/server-rendering/index.mdx b/site/content/docs/(latest)/server-rendering/index.mdx index 4af9695..8478a6b 100644 --- a/site/content/docs/(latest)/server-rendering/index.mdx +++ b/site/content/docs/(latest)/server-rendering/index.mdx @@ -58,3 +58,6 @@ the Next.js Pages Router, see calling your API. - [Server sessions](/docs/server-rendering/server-sessions): the secret, cookie jars, refreshes across server instances, sign-out, and limits. +- [Hybrid setup](/docs/server-rendering/hybrid): sign in with your backend + from the browser and call your API there, with the session still on the + server. diff --git a/site/content/docs/(latest)/server-rendering/meta.json b/site/content/docs/(latest)/server-rendering/meta.json index 0b89c35..f44b3d7 100644 --- a/site/content/docs/(latest)/server-rendering/meta.json +++ b/site/content/docs/(latest)/server-rendering/meta.json @@ -1,5 +1,5 @@ { "title": "Server rendering", "defaultOpen": true, - "pages": ["index", "server-sessions"] + "pages": ["index", "server-sessions", "hybrid"] } diff --git a/site/content/docs/(latest)/setups/next.mdx b/site/content/docs/(latest)/setups/next.mdx index 830e361..b768968 100644 --- a/site/content/docs/(latest)/setups/next.mdx +++ b/site/content/docs/(latest)/setups/next.mdx @@ -365,9 +365,8 @@ export function SignInForm() { In this guide, the server signs in with your backend, so the user in the cookie comes from the backend. If the browser signs in with the backend itself, have -`signInAction` take the tokens and the user instead, and read -[Your backend decides what's allowed](/docs/security#your-backend-decides-whats-allowed) -first. +`signInAction` take the tokens instead, as +[Hybrid setup](/docs/server-rendering/hybrid) shows for TanStack Start. ## Call your API diff --git a/site/content/docs/(latest)/setups/react-router-ssr.mdx b/site/content/docs/(latest)/setups/react-router-ssr.mdx index 922e664..11f70ed 100644 --- a/site/content/docs/(latest)/setups/react-router-ssr.mdx +++ b/site/content/docs/(latest)/setups/react-router-ssr.mdx @@ -355,9 +355,8 @@ loader to fetch, so the layout has one in case the routes nested in it don't. In this guide, the server signs in with your backend, so the user in the cookie comes from the backend. If the browser signs in with the backend itself, have -the action take the tokens and the user instead, and read -[Your backend decides what's allowed](/docs/security#your-backend-decides-whats-allowed) -first. +the action take the tokens instead, as +[Hybrid setup](/docs/server-rendering/hybrid) shows for TanStack Start. ## Call your API diff --git a/site/content/docs/(latest)/setups/tanstack-start.mdx b/site/content/docs/(latest)/setups/tanstack-start.mdx index 830ef74..451c34a 100644 --- a/site/content/docs/(latest)/setups/tanstack-start.mdx +++ b/site/content/docs/(latest)/setups/tanstack-start.mdx @@ -324,10 +324,8 @@ Give the sign-in route the `redirectIfSignedIn` guard, as in TanStack Router's In this guide, the server signs in with your backend, so the user in the cookie comes from the backend. If the browser signs in with the backend itself, for -example through a provider's SDK, have `signInFn` take the tokens and the user -instead and pass them to `session.signIn`, and read -[Your backend decides what's allowed](/docs/security#your-backend-decides-whats-allowed) -first. +example through a provider's SDK, have `signInFn` take the tokens instead, as +[Hybrid setup](/docs/server-rendering/hybrid) shows. ## Call your API diff --git a/src/core/mirror.ts b/src/core/mirror.ts index ba906bc..d90d6dc 100644 --- a/src/core/mirror.ts +++ b/src/core/mirror.ts @@ -101,7 +101,18 @@ export type MirrorCredentials = { * * @since 0.1.0 */ -export type MirrorAuthOptions = { +export type MirrorAuthOptions = MirrorAuthBaseOptions & + (EndpointOption | ServerFunctions); + +// Calls of `createMirrorAuth` take these through overloads rather than the +// union, because an editor shows no docs for an option a union declares. +type EndpointOption = { endpoint: string }; +type ServerFunctions = { + revalidate: () => Promise | null>; + signOut: () => Promise; +}; + +type MirrorAuthBaseOptions = { /** * Names this auth. Tabs tell each other about changes on the * `BroadcastChannel` `:auth`. Letters, digits, `_` or `-`, up to 64 @@ -117,8 +128,8 @@ export type MirrorAuthOptions = { * The path of your session route on this site, such as `"/api/session"`, * which answers with `sessionRoute` or `sessionHandler` from the server * entry points. The client reads the session, signs out and gets the - * access token through it. `revalidate`, `signOut` and `credentials` win - * when you pass them too. + * access token through it. Pass it, or `revalidate` and `signOut`. + * `revalidate`, `signOut` and `credentials` win when you pass them too. * * It's the full path, with your app's base path, such as React Router's * `basename` or Next's `basePath`. It's called from the browser only: on @@ -126,13 +137,20 @@ export type MirrorAuthOptions = { */ endpoint?: string | undefined; /** - * Reads the session on the server again, with `serverAuth.getSession`. + * Reads the session on your server again, with `serverAuth.getSession`, + * such as through a server function. Required without `endpoint`. + * + * The client calls it when the tab becomes visible after 10 seconds or + * more, when another tab signs in or out, and from `retry()` and + * `refresh()`. Pass one when the session is also read while the server + * renders, where `endpoint` can't be called, as in TanStack Start. * Default: a `GET` to `endpoint`. */ revalidate?: (() => Promise | null>) | undefined; /** - * Signs out on the server, with `serverAuth.signOut`. Default: through - * `endpoint`. + * Signs out on your server, with `serverAuth.signOut`. The client's + * `signOut()` calls it, then signs out this tab and the others. Required + * without `endpoint`. Default: a `POST` to `endpoint`. */ signOut?: (() => Promise) | undefined; /** @@ -152,18 +170,7 @@ export type MirrorAuthOptions = { credentials?: MirrorCredentials | undefined; /** Logs what the client does, like `createAuth`'s `debug`. */ debug?: AuthDebug | undefined; -} & ( - | { - /** Required unless you pass `revalidate` and `signOut`. */ - endpoint: string; - } - | { - /** Required without `endpoint`. */ - revalidate: () => Promise | null>; - /** Required without `endpoint`. */ - signOut: () => Promise; - } -); +}; type MirrorAuthBase = { /** @@ -391,6 +398,15 @@ function stateOf( * * @since 0.1.0 */ +export function createMirrorAuth( + options: MirrorAuthBaseOptions & EndpointOption, +): MirrorAuth; +export function createMirrorAuth( + options: MirrorAuthBaseOptions & ServerFunctions, +): MirrorAuth; +export function createMirrorAuth( + options: MirrorAuthOptions, +): MirrorAuth; export function createMirrorAuth( options: MirrorAuthOptions, ): MirrorAuth { diff --git a/src/server/auth.ts b/src/server/auth.ts index 4e58172..d74cd06 100644 --- a/src/server/auth.ts +++ b/src/server/auth.ts @@ -100,7 +100,7 @@ export type ServerAuthOptions = { * Where the user comes from: a schema that checks the `user` passed to * `signIn`, or `fromAccessToken(…)`. The cookie is trusted once sealed, * but `signIn` doesn't check its input with your backend - * ({@link ServerAuth} says what to do). + * ({@link RequestAuth}'s `signIn` says what to do). */ user: Src; /** @@ -241,17 +241,20 @@ type RequestAuthBase = { */ [requestAuth]: true; /** - * Resolves who is signed in, from the cookie, or `null`. An expired access - * token is refreshed first, and a refresh token your backend rejects signs - * out. Where the request can't set cookies, the session is returned as the - * cookie holds it. + * Resolves who is signed in, from the cookie, or `null`. It holds no + * tokens, so you can return it to the browser, such as from a server + * function or a loader. + * + * An expired access token is refreshed first, and a refresh token your + * backend rejects signs out. Where the request can't set cookies, the + * session is returned as the cookie holds it. */ getSession: () => Promise | null>; /** * Refreshes the access token when it has less than `within` seconds left - * ({@link RefreshIfDueOptions}), then resolves the session. Use it in - * middleware or a proxy that runs before rendering, so pages get a fresh - * token to read. + * ({@link RefreshIfDueOptions}), then resolves the session. Each adapter's + * middleware calls it before rendering, so pages get a fresh token to + * read. Call it yourself only in middleware of your own. * * It refreshes at most once per request. A failed refresh is ignored while * the access token still works. Rejects with `INVALID_OPTIONS` where the @@ -259,16 +262,46 @@ type RequestAuthBase = { */ refreshIfDue: (options?: RefreshIfDueOptions) => Promise | null>; /** - * Signs in with `input`, checked as the client's `signIn` does, and seals - * it into the cookie. Resolves the new session, which holds no tokens, so - * you can return it to the browser. Rejects with `INVALID_OPTIONS` where - * the request can't set cookies. + * Signs in by sealing your backend's tokens and the user into the cookie, + * replacing any session it held. Pass what your backend's sign-in + * returned: `accessToken`, `refreshToken` if there is one, and `user` + * unless the user comes from the access token. Resolves the new session, + * which holds no tokens, so you can return it to the browser. + * + * It never calls your backend, and trusts what it's given. If the browser + * signs in with your backend and sends the tokens and the user, the + * cookie's user is what the browser said, until a refresh or `updateUser` + * replaces it. Show it, but let your backend authorize with the access + * token. To trust it, check the input first, or sign in on the server. + * + * Rejects with `USER_VALIDATION_FAILED` for a user your schema rejects, + * with `INVALID_SESSION` for tokens that already expired, and with + * `INVALID_OPTIONS` where the request can't set cookies. + * + * @example + * ```ts + * import type { RequestAuth } from "@monarcode/session-kit/server"; + * + * type User = { id: number; firstName: string }; + * declare const session: RequestAuth; + * declare function login( + * username: string, + * password: string, + * ): Promise<{ accessToken: string; refreshToken: string; user: User }>; + * + * // Your backend checks the password, and signIn keeps the result. + * export async function signIn(username: string, password: string) { + * return session.signIn(await login(username, password)); + * } + * ``` */ signIn: (input: SignInInput) => Promise>; /** * Signs out by clearing the cookie, then calls `revoke` and waits for it. - * A failed `revoke` doesn't reject. Rejects with `INVALID_OPTIONS` where - * the request can't set cookies. + * A failed `revoke` doesn't reject. The browser's client signs out through + * your session route, so call it yourself only from server code of your + * own, such as an action. Rejects with `INVALID_OPTIONS` where the request + * can't set cookies. */ signOut: () => Promise; /** @@ -277,9 +310,11 @@ type RequestAuthBase = { */ credentials: Readonly<{ /** - * Resolves the current access token, or `null`, refreshing an expired - * one first. Where the request can't set cookies, an expired one rejects - * with `REFRESH_FAILED`. + * Resolves the current access token, or `null` when signed out, + * refreshing an expired one first. Use it with an HTTP client of your + * own. `createAuthFetch` from `@monarcode/session-kit/http` calls it, + * and `renew` after a 401, for you. Where the request can't set + * cookies, an expired token rejects with `REFRESH_FAILED`. */ get: () => Promise; /** @@ -378,9 +413,14 @@ export type RequestAuth = Readonly> & ? unknown : Readonly<{ /** - * Replaces the signed-in user and keeps the session, as the - * client's `updateUser` does, then resolves the session. Rejects - * with `INVALID_OPTIONS` where the request can't set cookies. + * Replaces the signed-in user in the cookie, such as after a + * profile edit, and resolves the session. Pass the user, or an + * async function that fetches it. The session ID stays. + * + * Rejects with `UNAUTHENTICATED` when signed out, and with + * `USER_VALIDATION_FAILED` for a user your schema rejects, or when + * the function rejects or times out. Rejects with + * `INVALID_OPTIONS` where the request can't set cookies. */ updateUser: (input: I | (() => Promise)) => Promise>; }>); @@ -464,11 +504,8 @@ type ServerAuthBase = { * module once per bundle, making several, so with rotating refresh tokens, * give your backend a short reuse window. * - * `signIn` seals what it's given. If the browser signs in with your backend - * and sends the tokens and the user, the cookie's user is what the browser - * said, until a refresh or `updateUser` replaces it. Show it, but let your - * backend authorize with the access token. To trust it, check the input - * before `signIn`, or sign in with your backend on the server. + * `signIn` trusts what it's given. {@link RequestAuth}'s `signIn` says what + * that means. * * @example * ```ts From fa6e332ead6cf4ad53b1ebc0248b243c2c6be449 Mon Sep 17 00:00:00 2001 From: monarcode Date: Sat, 14 Nov 2026 11:12:45 +0100 Subject: [PATCH 12/26] docs(react-router): explain when to use requireSessionLoader or requireSession - Use requireSessionLoader as a whole loader, usually a layout's - Use requireSession inside a loader that also loads data, since React Router runs nested loaders at the same time --- CHANGELOG.md | 5 ++ scripts/docs-pages.mjs | 7 ++- .../docs/(latest)/setups/react-router.mdx | 53 ++++++++++++++++++- src/react-router/guards.ts | 4 ++ 4 files changed, 66 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 915d007..2d4a621 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -288,6 +288,11 @@ calls your backend and trusts its input, and which errors `signIn` and `updateUser` reject with. `getSession`, `signOut` and `credentials.get` say where to use them. +- The React Router guide's Guards in loaders section says when to use + `requireSessionLoader` (the whole loader, usually a layout's) and + `requireSession` (inside a loader that loads data too). A page's loader that + calls your API checks the session itself, since React Router runs nested + routes' loaders at the same time. - A Hybrid setup page, under Server rendering: the browser signs in with your backend and calls your API, and the server keeps the session. It shows a server function that checks the tokens with your backend before diff --git a/scripts/docs-pages.mjs b/scripts/docs-pages.mjs index cae3b9c..d9ca3e9 100644 --- a/scripts/docs-pages.mjs +++ b/scripts/docs-pages.mjs @@ -217,7 +217,12 @@ export const documents = [ fixtures: {}, shared: { from: page("getting-started"), - files: ["src/backend.ts", "src/auth.ts", "src/sign-in.tsx"], + files: [ + "src/backend.ts", + "src/auth.ts", + "src/sign-in.tsx", + "src/api.ts", + ], // Framework mode keeps its code in `app`. directories: ["src", "app"], }, diff --git a/site/content/docs/(latest)/setups/react-router.mdx b/site/content/docs/(latest)/setups/react-router.mdx index def0fd8..25c5c5a 100644 --- a/site/content/docs/(latest)/setups/react-router.mdx +++ b/site/content/docs/(latest)/setups/react-router.mdx @@ -236,8 +236,9 @@ Three pieces work together: signed-out users to `/login` with `redirectTo`, and returns `{ session }` as the route's loader data. Pass `{ loginPath }` for another sign-in page. A failed refresh is rethrown for the route's error element instead, - because the user is still signed in. In a loader that does more, call - `requireSession(auth, { request })` and carry on. + because the user is still signed in. A loader that does more calls + `requireSession` instead, as [Guards in loaders](#guards-in-loaders) + shows. - **`useAuthRevalidation`** runs the loaders again after a sign-in, a sign-out, an account switch, or a profile update, so the guards run again. Call it once, in the root route. @@ -391,6 +392,54 @@ the root route starts nothing, and the browser restores the session. A complete app is in [`examples/react-router-framework-spa`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-framework-spa). +## Guards in loaders + +Two functions guard a loader, in data mode and in framework mode. Both send a +signed-out user to `/login`, with `redirectTo`, and resolve `{ session }`, +typed with your user: + +- **`requireSessionLoader(auth)`** is the whole loader. Use it on a route + that guards and loads nothing else, usually the layout route around your + private pages, as above. +- **`requireSession(auth, { request })`** is a call inside a loader of your + own. Use it when the loader loads data too: data only a signed-in user may + load, or data that needs who is signed in. + +React Router runs the loaders of nested routes at the same time, so a page's +loader doesn't wait for its layout's guard. A page whose loader calls your +API checks the session itself: + +```tsx title="app/routes/profile.tsx" +import { useLoaderData } from "react-router"; + +import { requireSession } from "@monarcode/session-kit/react-router"; + +import { fetchProfile } from "../api.js"; +import { auth } from "../auth.js"; + +export async function clientLoader({ request }: { request: Request }) { + const { session } = await requireSession(auth, { request }); + return { name: session.user.firstName, profile: await fetchProfile() }; +} + +export default function Profile() { + const { name, profile } = useLoaderData(); + return ( +

+ {name}, your email is {profile.email}. +

+ ); +} +``` + +A signed-out user is redirected before your API is called, rather than +after a request that fails. Pass `requireSession` the same `loginPath` and +`basename` as the layout's guard. + +The sign-in page has the same pair: `redirectIfSignedInLoader(auth)` as its +loader, or `redirectIfSignedIn(auth, { redirectTo })` in a loader that does +more. + ## Layouts around guarded pages A guarded route often has UI of its own around its pages, such as a sidebar diff --git a/src/react-router/guards.ts b/src/react-router/guards.ts index 18a711c..7541eff 100644 --- a/src/react-router/guards.ts +++ b/src/react-router/guards.ts @@ -100,6 +100,10 @@ export type RequireSessionLoader = (args: { * the loader does nothing else, use {@link requireSessionLoader} as the * loader instead. * + * Call it in a page's loader that calls your API, even under a guarded + * layout. React Router runs nested routes' loaders at the same time, so the + * page's doesn't wait for the layout's guard. + * * Signed-out users go to `loginPath`, with `?redirectTo=` set to the URL they * asked for. A locked session counts as signed out, as locking is for native * apps and the router adapters don't unlock. From 6bbabc78eb7551cb3cce3656adf82dfe5fb6c94b Mon Sep 17 00:00:00 2001 From: monarcode Date: Sat, 14 Nov 2026 12:07:27 +0100 Subject: [PATCH 13/26] refactor(examples): lay out the effetch example as the Effect guide does - Split it into backend, refresh, auth, layer, api and runtime modules - Remove FetchLive: the API and refresh clients turn off Effect's tracing headers themselves - Turn off tracing headers in the guide's refresh client too, since they fail CORS preflight --- CHANGELOG.md | 7 ++ examples/README.md | 11 +-- .../src/{api-client.ts => api.ts} | 23 +++--- .../tanstack-start-spa-effetch/src/auth.ts | 70 ++----------------- .../tanstack-start-spa-effetch/src/backend.ts | 31 ++++++++ .../src/endpoints.ts | 5 +- .../src/error-message.ts | 4 +- .../tanstack-start-spa-effetch/src/fetch.ts | 12 ---- .../tanstack-start-spa-effetch/src/layer.ts | 10 +++ .../tanstack-start-spa-effetch/src/query.ts | 5 +- .../tanstack-start-spa-effetch/src/refresh.ts | 37 ++++++++++ .../tanstack-start-spa-effetch/src/runtime.ts | 13 ++-- .../tanstack-start-spa-effetch/src/ui.tsx | 2 +- site/content/docs/(latest)/effect.mdx | 6 +- 14 files changed, 129 insertions(+), 107 deletions(-) rename examples/tanstack-start-spa-effetch/src/{api-client.ts => api.ts} (54%) create mode 100644 examples/tanstack-start-spa-effetch/src/backend.ts delete mode 100644 examples/tanstack-start-spa-effetch/src/fetch.ts create mode 100644 examples/tanstack-start-spa-effetch/src/layer.ts create mode 100644 examples/tanstack-start-spa-effetch/src/refresh.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d4a621..43a27be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -288,6 +288,13 @@ calls your backend and trusts its input, and which errors `signIn` and `updateUser` reject with. `getSession`, `signOut` and `credentials.get` say where to use them. +- The `tanstack-start-spa-effetch` example is laid out as the Effect guide + is, in `backend.ts`, `refresh.ts`, `auth.ts`, `layer.ts`, `api.ts` and + `runtime.ts`. Its `FetchLive` layer is gone: the API client and the + refresh client each turn off Effect's tracing headers themselves, and the + runtime provides plain `FetchHttpClient.layer`. The guide's refresh client + now turns them off too. It sent them, which fails the preflight of an API + that doesn't allow them. - The React Router guide's Guards in loaders section says when to use `requireSessionLoader` (the whole loader, usually a layout's) and `requireSession` (inside a loader that loads data too). A page's loader that diff --git a/examples/README.md b/examples/README.md index 2460a14..9c656b1 100644 --- a/examples/README.md +++ b/examples/README.md @@ -62,11 +62,12 @@ run ios` and `run android` build it natively. In CI it is only bundled, with saved session. - **TanStack Start with Effect** is the SPA app written with Effect, [effetch](https://github.com/monarcode/effetch) and - [effetch-query](https://github.com/monarcode/effetch-query). `src/auth.ts` - describes the user with an Effect Schema and refreshes through effetch. - `src/api-client.ts` is the API client, a service whose `sessionBearer` - plugin sends the access token, and `src/runtime.ts` composes the app's - layers into one runtime. `src/endpoints.ts` declares the sign-in mutation + [effetch-query](https://github.com/monarcode/effetch-query), laid out as + the guide is. `src/backend.ts` describes DummyJSON with Effect Schemas, + `src/refresh.ts` refreshes through effetch, and `src/auth.ts` reads the + user from the access token. `src/api.ts` is the API client, a service whose + `sessionBearer` plugin sends the access token, and `src/runtime.ts` + composes the app's layers into one runtime. `src/endpoints.ts` declares the sign-in mutation and the profile query, which `src/ui.tsx` uses with `useMutation` and `useQuery`, and the root route gives each session its own query cache. The hooks and the guards are the SPA app's. See diff --git a/examples/tanstack-start-spa-effetch/src/api-client.ts b/examples/tanstack-start-spa-effetch/src/api.ts similarity index 54% rename from examples/tanstack-start-spa-effetch/src/api-client.ts rename to examples/tanstack-start-spa-effetch/src/api.ts index 83f289c..4b2c0a5 100644 --- a/examples/tanstack-start-spa-effetch/src/api-client.ts +++ b/examples/tanstack-start-spa-effetch/src/api.ts @@ -1,24 +1,24 @@ import * as Fetch from "@monarcode/effetch"; import { sessionBearer } from "@monarcode/session-kit/effetch"; import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; import * as Layer from "effect/Layer"; -import * as Schema from "effect/Schema"; -import { API_BASE_URL } from "./auth"; - -/** DummyJSON explains an error in its body: `{ "message": "…" }`. */ -export const ApiErrorBody = Schema.Struct({ message: Schema.String }); -export type ApiErrorBody = Schema.Schema.Type; +import { API_BASE_URL, ApiError } from "./backend"; const make = Fetch.make({ baseUrl: API_BASE_URL, - defaultError: ApiErrorBody, + defaultError: ApiError, // Sends the access token to DummyJSON only. After a 401 it refreshes, then - // replays a GET or HEAD once. `optional`: a call made while signed out, - // such as the sign-in itself, goes without a token. + // sends a GET or HEAD again once. `optional`: a call made while signed out + // goes without a token. plugins: [sessionBearer({ baseUrl: API_BASE_URL, optional: true })], -}); +}).pipe( + // Effect adds tracing headers to every request, which fail the preflight + // of an API that doesn't allow them. + Effect.provideService(HttpClient.TracerPropagationEnabled, false), +); /** The app's API client: effetch's `get`, `post` and the rest, for DummyJSON. */ export class ApiClient extends Context.Service< @@ -26,4 +26,5 @@ export class ApiClient extends Context.Service< Effect.Success >()("ApiClient") {} +/** The API client, over whichever `Auth` is provided. */ export const ApiClientLive = Layer.effect(ApiClient, make); diff --git a/examples/tanstack-start-spa-effetch/src/auth.ts b/examples/tanstack-start-spa-effetch/src/auth.ts index a902523..3222067 100644 --- a/examples/tanstack-start-spa-effetch/src/auth.ts +++ b/examples/tanstack-start-spa-effetch/src/auth.ts @@ -1,84 +1,24 @@ -import * as Fetch from "@monarcode/effetch"; import { createAuth, fromAccessToken, webStorage, } from "@monarcode/session-kit"; -import { Auth } from "@monarcode/session-kit/effect"; -import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -import { FetchLive } from "./fetch"; - -/** DummyJSON's auth API: https://dummyjson.com/docs/auth */ -export const API_BASE_URL = "https://dummyjson.com"; - -/** One-minute tokens make the early refresh visible after about 30 seconds. */ -export const expiresInMins = 1; - -export const SessionTokens = Schema.Struct({ - accessToken: Schema.String, - refreshToken: Schema.String, -}); - -/** - * DummyJSON's access tokens are JWTs carrying the user, so this app reads the - * user from the token instead of the login response. A struct drops the - * claims it doesn't list, such as `exp` and `iat`, which change on every - * refresh. - */ -export const SessionUser = Schema.Struct({ - id: Schema.Finite, - username: Schema.String, - email: Schema.String, - firstName: Schema.String, - lastName: Schema.String, - image: Schema.String, -}); - -// Not the app's API client: its session plugin waits for this refresh. -const makeRefreshClient = Fetch.make({ baseUrl: API_BASE_URL }); - -/** - * Exchanges the refresh token for new tokens. DummyJSON answers 403 for an - * invalid or expired refresh token and 401 for a missing one: both mean - * "sign in again", so succeed with `null`. Other failures fail: the session - * is kept and the error shows in `state.error`. - */ -const refreshSession = (refreshToken: string) => - Effect.gen(function* () { - const client = yield* makeRefreshClient; - return yield* client.post("/auth/refresh", { - body: { refreshToken, expiresInMins }, - output: SessionTokens, - }); - }).pipe( - Effect.catchTag("HttpError", (error) => - error.status === 401 || error.status === 403 - ? Effect.succeed(null) - : Effect.fail(error), - ), - Effect.provide(FetchLive), - ); +import { SessionUser } from "./backend"; +import { refreshSession } from "./refresh"; export const auth = createAuth({ name: "session-kit-example", user: fromAccessToken(Schema.toStandardSchemaV1(SessionUser)), storage: webStorage(), - refresh: ({ refreshToken, signal }) => - Effect.runPromise(refreshSession(refreshToken), { signal }), + refresh: ({ refreshToken, signal }) => refreshSession(refreshToken, signal), }); -// Registered once, so every `Auth` Effect is typed with this client's user. +// Registered once, so every `Auth` Effect, and the hooks, carry this +// client's user. declare module "@monarcode/session-kit" { interface Register { auth: typeof auth; } } - -/** - * The client as the `Auth` service, which the API client's `sessionBearer` - * reads the access token from. It doesn't mount the client: `connectAuth` - * does, in `router.tsx`. - */ -export const AuthLive = Auth.layer(auth); diff --git a/examples/tanstack-start-spa-effetch/src/backend.ts b/examples/tanstack-start-spa-effetch/src/backend.ts new file mode 100644 index 0000000..b94eef0 --- /dev/null +++ b/examples/tanstack-start-spa-effetch/src/backend.ts @@ -0,0 +1,31 @@ +import * as Schema from "effect/Schema"; + +/** DummyJSON's auth API: https://dummyjson.com/docs/auth */ +export const API_BASE_URL = "https://dummyjson.com"; + +/** One-minute tokens make the early refresh visible after about 30 seconds. */ +export const expiresInMins = 1; + +/** + * DummyJSON's access tokens are JWTs carrying the user, so this app reads the + * user from the token instead of the login response. A struct drops the + * claims it doesn't list, such as `exp` and `iat`, which change on every + * refresh. + */ +export const SessionUser = Schema.Struct({ + id: Schema.Finite, + username: Schema.String, + email: Schema.String, + firstName: Schema.String, + lastName: Schema.String, + image: Schema.String, +}); + +export const SessionTokens = Schema.Struct({ + accessToken: Schema.String, + refreshToken: Schema.String, +}); + +/** DummyJSON explains an error in its body: `{ "message": "…" }`. */ +export const ApiError = Schema.Struct({ message: Schema.String }); +export type ApiError = Schema.Schema.Type; diff --git a/examples/tanstack-start-spa-effetch/src/endpoints.ts b/examples/tanstack-start-spa-effetch/src/endpoints.ts index 4e47240..81fbafc 100644 --- a/examples/tanstack-start-spa-effetch/src/endpoints.ts +++ b/examples/tanstack-start-spa-effetch/src/endpoints.ts @@ -1,10 +1,10 @@ import * as Fetch from "@monarcode/effetch"; import * as Schema from "effect/Schema"; -import { SessionTokens } from "./auth"; +import { SessionTokens } from "./backend"; import { api } from "./query"; -/** Signs in with DummyJSON. Sent without a token: nobody is signed in yet. */ +/** Signs in with DummyJSON. Sent without a token, as it's how one is got. */ export const signInMutation = api.mutation( Fetch.endpoint("POST /auth/login", { input: Schema.Struct({ @@ -14,6 +14,7 @@ export const signInMutation = api.mutation( }), output: SessionTokens, }), + { plugins: { sessionBearer: false } }, ); /** The signed-in user's profile, requested with the access token. */ diff --git a/examples/tanstack-start-spa-effetch/src/error-message.ts b/examples/tanstack-start-spa-effetch/src/error-message.ts index d659a61..770f77c 100644 --- a/examples/tanstack-start-spa-effetch/src/error-message.ts +++ b/examples/tanstack-start-spa-effetch/src/error-message.ts @@ -4,10 +4,10 @@ import * as Cause from "effect/Cause"; import * as Match from "effect/Match"; import * as Option from "effect/Option"; -import type { ApiErrorBody } from "./api-client"; +import type { ApiError } from "./backend"; type ApiCallError = - | HttpError.With + | HttpError.With | NetworkError | DecodeError | AuthFailure; diff --git a/examples/tanstack-start-spa-effetch/src/fetch.ts b/examples/tanstack-start-spa-effetch/src/fetch.ts deleted file mode 100644 index 7449f61..0000000 --- a/examples/tanstack-start-spa-effetch/src/fetch.ts +++ /dev/null @@ -1,12 +0,0 @@ -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import * as HttpClient from "effect/http/HttpClient"; -import * as Layer from "effect/Layer"; - -/** - * `fetch`, without the tracing headers Effect adds to every request: from a - * browser, they fail the preflight of an API that doesn't allow them. - */ -export const FetchLive = Layer.merge( - FetchHttpClient.layer, - Layer.succeed(HttpClient.TracerPropagationEnabled, false), -); diff --git a/examples/tanstack-start-spa-effetch/src/layer.ts b/examples/tanstack-start-spa-effetch/src/layer.ts new file mode 100644 index 0000000..cc97ac2 --- /dev/null +++ b/examples/tanstack-start-spa-effetch/src/layer.ts @@ -0,0 +1,10 @@ +import { Auth } from "@monarcode/session-kit/effect"; + +import { auth } from "./auth"; + +/** + * The client as the `Auth` service, which the API client's `sessionBearer` + * reads the access token from. It doesn't mount the client: `connectAuth` + * does, in `router.tsx`. + */ +export const AuthLive = Auth.layer(auth); diff --git a/examples/tanstack-start-spa-effetch/src/query.ts b/examples/tanstack-start-spa-effetch/src/query.ts index f1ae09e..3d0972b 100644 --- a/examples/tanstack-start-spa-effetch/src/query.ts +++ b/examples/tanstack-start-spa-effetch/src/query.ts @@ -2,7 +2,8 @@ import { QueryClient } from "@monarcode/effetch-query"; import { endpoints } from "@monarcode/effetch-query/effetch"; import type * as ManagedRuntime from "effect/ManagedRuntime"; -import { ApiClient, ApiErrorBody } from "./api-client"; +import { ApiClient } from "./api"; +import { ApiError } from "./backend"; import { appRuntime, type AppRuntime } from "./runtime"; declare module "@monarcode/effetch-query" { @@ -12,7 +13,7 @@ declare module "@monarcode/effetch-query" { } /** Turns endpoints of the API client into queries and mutations. */ -export const api = endpoints(ApiClient, { defaultError: ApiErrorBody }); +export const api = endpoints(ApiClient, { defaultError: ApiError }); /** * Makes the query cache, which runs queries and mutations with `appRuntime`'s diff --git a/examples/tanstack-start-spa-effetch/src/refresh.ts b/examples/tanstack-start-spa-effetch/src/refresh.ts new file mode 100644 index 0000000..7ee2a68 --- /dev/null +++ b/examples/tanstack-start-spa-effetch/src/refresh.ts @@ -0,0 +1,37 @@ +import * as Fetch from "@monarcode/effetch"; +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as HttpClient from "effect/http/HttpClient"; + +import { API_BASE_URL, expiresInMins, SessionTokens } from "./backend"; + +// Not the app's API client: its session plugin waits for this refresh. +const makeRefreshClient = Fetch.make({ baseUrl: API_BASE_URL }).pipe( + // No tracing headers, as for the API client. + Effect.provideService(HttpClient.TracerPropagationEnabled, false), +); + +/** + * Exchanges the refresh token for new tokens. DummyJSON answers 403 for an + * invalid or expired refresh token and 401 for a missing one: both mean + * "sign in again", so it resolves `null`. Other failures reject, so the + * session is kept and the error shows in `state.error`. + */ +export const refreshSession = (refreshToken: string, signal: AbortSignal) => + Effect.runPromise( + Effect.gen(function* () { + const client = yield* makeRefreshClient; + return yield* client.post("/auth/refresh", { + body: { refreshToken, expiresInMins }, + output: SessionTokens, + }); + }).pipe( + Effect.catchTag("HttpError", (error) => + error.status === 401 || error.status === 403 + ? Effect.succeed(null) + : Effect.fail(error), + ), + Effect.provide(FetchHttpClient.layer), + ), + { signal }, + ); diff --git a/examples/tanstack-start-spa-effetch/src/runtime.ts b/examples/tanstack-start-spa-effetch/src/runtime.ts index 08890bf..e5fa748 100644 --- a/examples/tanstack-start-spa-effetch/src/runtime.ts +++ b/examples/tanstack-start-spa-effetch/src/runtime.ts @@ -1,17 +1,18 @@ +import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as Layer from "effect/Layer"; import * as ManagedRuntime from "effect/ManagedRuntime"; -import { ApiClientLive } from "./api-client"; -import { AuthLive } from "./auth"; -import { FetchLive } from "./fetch"; +import { ApiClientLive } from "./api"; +import { AuthLive } from "./layer"; /** - * The composition root: the app's services and what they depend on. A new - * service is added here. + * The composition root: the API client, the session, and the + * `FetchHttpClient` effetch sends with, each made once. A new service is + * added here. */ const AppLayer = ApiClientLive.pipe( Layer.provideMerge(AuthLive), - Layer.provide(FetchLive), + Layer.provide(FetchHttpClient.layer), ); /** One runtime for the app's lifetime. */ diff --git a/examples/tanstack-start-spa-effetch/src/ui.tsx b/examples/tanstack-start-spa-effetch/src/ui.tsx index 9306ff2..d35da42 100644 --- a/examples/tanstack-start-spa-effetch/src/ui.tsx +++ b/examples/tanstack-start-spa-effetch/src/ui.tsx @@ -5,7 +5,7 @@ import { useAuth, useAuthClient } from "@monarcode/session-kit/tanstack-router"; import * as Exit from "effect/Exit"; import * as AsyncResult from "effect/reactivity/AsyncResult"; -import { expiresInMins } from "./auth"; +import { expiresInMins } from "./backend"; import { profileQuery, signInMutation } from "./endpoints"; import { apiErrorMessage } from "./error-message"; diff --git a/site/content/docs/(latest)/effect.mdx b/site/content/docs/(latest)/effect.mdx index ebdeb61..89101de 100644 --- a/site/content/docs/(latest)/effect.mdx +++ b/site/content/docs/(latest)/effect.mdx @@ -106,11 +106,15 @@ explains. The server uses it too: import * as Fetch from "@monarcode/effetch"; import * as Effect from "effect/Effect"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as HttpClient from "effect/http/HttpClient"; import { API_BASE_URL, SessionTokens } from "./backend.js"; // Not the app's API client: its session plugin waits for this refresh. -const makeRefreshClient = Fetch.make({ baseUrl: API_BASE_URL }); +const makeRefreshClient = Fetch.make({ baseUrl: API_BASE_URL }).pipe( + // No tracing headers, as for the API client in step 6. + Effect.provideService(HttpClient.TracerPropagationEnabled, false), +); /** New tokens. `null` signs out; a failure keeps the session for a retry. */ export const refreshSession = (refreshToken: string, signal: AbortSignal) => From 26476650b5ff40fe390c227b5a2d29a8655216e6 Mon Sep 17 00:00:00 2001 From: monarcode Date: Sat, 14 Nov 2026 13:03:47 +0100 Subject: [PATCH 14/26] docs: check the hovers and guides against the code - Name the error codes each hover left out, and correct wrong statements - Add sections the guides lacked, such as Sign out for TanStack Start - Fix the Expo locking and Effect sign-in examples --- CHANGELOG.md | 23 +++++ README.md | 9 +- site/content/docs/(latest)/client/locking.mdx | 5 +- .../(latest)/client/other-http-clients.mdx | 2 +- .../content/docs/(latest)/client/requests.mdx | 15 ++- .../(latest)/client/signing-in-and-out.mdx | 5 +- site/content/docs/(latest)/client/state.mdx | 2 + .../(latest)/client/users-from-tokens.mdx | 2 + .../docs/(latest)/configuration/debugging.mdx | 2 +- .../docs/(latest)/configuration/errors.mdx | 7 +- .../docs/(latest)/configuration/index.mdx | 4 + .../docs/(latest)/configuration/storage.mdx | 4 +- site/content/docs/(latest)/effect.mdx | 32 ++++--- site/content/docs/(latest)/faq.mdx | 4 +- .../content/docs/(latest)/getting-started.mdx | 4 +- site/content/docs/(latest)/index.mdx | 2 +- .../docs/(latest)/reference/compatibility.mdx | 6 +- site/content/docs/(latest)/reference/core.mdx | 2 +- .../docs/(latest)/reference/error-codes.mdx | 8 +- site/content/docs/(latest)/reference/expo.mdx | 2 +- .../content/docs/(latest)/reference/index.mdx | 8 +- .../content/docs/(latest)/reference/react.mdx | 2 +- site/content/docs/(latest)/security.mdx | 24 +++-- .../docs/(latest)/server-rendering/hybrid.mdx | 6 +- .../docs/(latest)/server-rendering/index.mdx | 4 +- .../server-rendering/server-sessions.mdx | 29 +++--- site/content/docs/(latest)/setups/expo.mdx | 93 ++++++++++++------- site/content/docs/(latest)/setups/next.mdx | 9 +- .../docs/(latest)/setups/react-router-ssr.mdx | 44 ++++----- .../docs/(latest)/setups/react-router.mdx | 13 +-- .../docs/(latest)/setups/tanstack-router.mdx | 3 +- .../docs/(latest)/setups/tanstack-start.mdx | 37 +++++++- src/core/debug.ts | 11 ++- src/core/errors.ts | 19 ++-- src/core/mirror.ts | 17 ++-- src/core/persistence.ts | 5 +- src/core/return-to.ts | 6 +- src/core/storage.ts | 5 +- src/core/types.ts | 65 ++++++++----- src/effect/auth.ts | 8 +- src/effetch/index.ts | 12 ++- src/expo/deep-link.ts | 12 ++- src/expo/gate.ts | 5 +- src/expo/secure-storage.ts | 11 ++- src/http/index.ts | 21 +++-- src/next/index.ts | 4 +- src/react-router/guards.ts | 6 +- src/react-router/outlet.ts | 9 +- src/react-router/revalidation.ts | 6 +- src/react-router/server.ts | 18 ++-- src/react/hooks.ts | 13 ++- src/react/mirror.ts | 6 +- src/server/auth.ts | 24 +++-- src/server/handler.ts | 11 ++- src/tanstack-router/connect.ts | 3 + src/tanstack-router/guards.ts | 1 + src/tanstack-router/outlet.ts | 3 + 57 files changed, 466 insertions(+), 247 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 43a27be..d763630 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -314,6 +314,29 @@ sign-in shows the backend's own message for a failed sign-in, as the example apps do, and the secret-rotation example works once the old secret is removed. +- The hovers and the guides are checked line by line against the code. The + hovers name errors they left out: `PERSISTENCE_FAILED` from `signIn`, + `getSession` and `unlock`, `REFRESH_FAILED` and `SESSION_CHANGED` from + `credentials.renew`, `createAuthFetch` and `sessionBearer`, a request's + `getSession` and `refreshIfDue` on the server, the `INVALID_OPTIONS` that + guards, outlets and `sessionRoute` throw, and the session route's status + codes. `AuthErrorCode`'s docs cover a saved session older than `maxAge`, a + `locking.seal` that fails, and a refresh that times out. +- Corrected in the docs: `signOut()` waits for `revoke`. + `signOutOnRepeated401: false` only stops a second 401 from signing users + out, and without a refresh token the first one still does. A read-only + request's `getSession` resolves, and only `credentials.get` rejects once + the token has expired. React Router passes loaders `url` from 7.15, not + from 8. `AFTER_FIRST_UNLOCK` is for a refresh while the device is locked. + Remove an old `secret` once `maxAge` has passed since the change. +- The guides gain what they lacked: a Sign out section for TanStack Start, + `cacheControl` and the two sets of guards for React Router with server + rendering, the session route's checks on the Security page, storage that + can't be read on the Errors page, and what `secureStorage`, `SessionGate` + and `deepLinkHandler` do on the Expo page. The Expo guide's locking example + throws when a change to the device's biometrics made the key unreadable, + as its comment says, where it made a new key. The Effect guide's sign-in + button awaits `auth.signIn`, where a failed sign-in went unhandled. ## 0.1.0-alpha.8 diff --git a/README.md b/README.md index 5f540e3..2faf12a 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,8 @@ server with TanStack Start, Next.js, and React Router, and comes with an ## Installation +To install the package, run the following command: + ```sh pnpm add @monarcode/session-kit ``` @@ -55,8 +57,9 @@ supported versions. ## Quick start -Session kit never calls your backend. Write the requests you'd write anyway: -one that signs in, and one that exchanges a refresh token for new tokens. +Session kit never calls your backend. Write the two requests you'd write +anyway, one that signs in and one that exchanges a refresh token for new +tokens: @@ -152,7 +155,7 @@ one step at a time, against a real test backend. | React Router, framework mode with SSR | [React Router with SSR](https://session-kit.pages.dev/docs/setups/react-router-ssr) | | Next.js 16, App Router | [Next.js](https://session-kit.pages.dev/docs/setups/next) | | Expo Router on iOS and Android, SDK 53+ | [Expo Router](https://session-kit.pages.dev/docs/setups/expo) | -| Effect and effetch, with any of the above | [Effect and effetch](https://session-kit.pages.dev/docs/effect) | +| Effect and effetch, with any setup | [Effect and effetch](https://session-kit.pages.dev/docs/effect) | All but the first have a runnable app in [`examples/`](./examples). diff --git a/site/content/docs/(latest)/client/locking.mdx b/site/content/docs/(latest)/client/locking.mdx index 2c2a86b..dda1516 100644 --- a/site/content/docs/(latest)/client/locking.mdx +++ b/site/content/docs/(latest)/client/locking.mdx @@ -7,7 +7,8 @@ Locking is for native apps that ask a returning user to unlock, for example with biometrics, before the app opens. With the `locking` option, a saved session restores as `locked`. `user` and `sessionId` are set, so a "Welcome back" screen can greet the user, but the tokens wait for -`auth.unlock()`. +`auth.unlock()`. The following client encrypts its saved tokens with a key +the app holds: ```ts title="src/locked-auth.ts" import { createAuth, type AuthStorage } from "@monarcode/session-kit"; @@ -40,6 +41,8 @@ export const unlockApp = () => lockedAuth.unlock(); export const lockApp = () => lockedAuth.lock(); ``` +Locking comes with these rules: + - **Sealing is yours.** Session kit depends on no crypto or biometrics library. The user and session ID are saved beside the sealed tokens, readable while locked. `locking: true` stores the tokens as they are, for a diff --git a/site/content/docs/(latest)/client/other-http-clients.mdx b/site/content/docs/(latest)/client/other-http-clients.mdx index e2f3128..50a4dad 100644 --- a/site/content/docs/(latest)/client/other-http-clients.mdx +++ b/site/content/docs/(latest)/client/other-http-clients.mdx @@ -89,7 +89,7 @@ calls, and a client with its own transport can use the same ones: requests failed, they share one refresh. It resolves `null` when the user was signed out instead. 3. **After a second 401**, `auth.credentials.reject(credentials)` ends the - session, unless a newer one has replaced it. + session, unless newer credentials have replaced the ones you pass. An axios instance that keeps its default adapter does it with two interceptors: diff --git a/site/content/docs/(latest)/client/requests.mdx b/site/content/docs/(latest)/client/requests.mdx index a0066c8..7942eb6 100644 --- a/site/content/docs/(latest)/client/requests.mdx +++ b/site/content/docs/(latest)/client/requests.mdx @@ -11,11 +11,12 @@ built so that a token can't leak and a user can't be signed out by accident: | The request is for another origin, or has a username or password in its URL | Rejects with `INVALID_OPTIONS`. The token goes only to `baseUrl`'s origin. | | The response is a redirect | Rejects rather than following it. | | The response is a 401 | Refreshes once, then sends a GET or HEAD again with the new token. | -| Any other method gets a 401 | Refreshes, and resolves the 401. It never sends a request twice on its own. | +| Any other method gets a 401 | Refreshes, and resolves the 401. It never sends a write twice on its own. | | The replayed request gets a 401 too | Signs out, unless `signOutOnRepeated401` is `false`. | | The session changes during the request | Rejects with `SESSION_CHANGED` rather than resolve another account's answer. | | Nobody is signed in | Rejects with `UNAUTHENTICATED`, unless `optional` is `true`. | | The session is locked | Rejects with `LOCKED`, even when `optional` is `true`. | +| A refresh fails | Rejects with that failure, such as `REFRESH_FAILED`. | | The network fails | Rejects as `fetch` does, unchanged. | Call it with a path, which is resolved against `baseUrl` as a link is @@ -23,8 +24,8 @@ against a page's address. End `baseUrl` with `/`, so that `authFetch("orders")` lands under it. It also takes a `URL` or a `Request`, as `fetch` does, so an HTTP client with a `fetch` option can send its requests through it. See [Other HTTP clients](/docs/client/other-http-clients). -A `Request` with a body is used up once sent, so read -[`AuthFetch`](/docs/reference/http#authfetch) before you retry one. +A `Request` with a body can be sent once, as with `fetch`. To retry a write +after a 401, send a clone you kept. Because a write is never replayed for you, retry it yourself where sending it twice is safe. By then the token has been refreshed: @@ -63,8 +64,12 @@ export const publicFetch = createAuthFetch(auth, { // One `fetch` for public and private endpoints: signed out, requests are // sent without a token instead of rejecting. optional: true, - // For APIs that answer 401 for reasons other than a rejected token, so one - // of those endpoints can't sign users out. + // For APIs that answer 401 for reasons other than a rejected token, so a + // second 401 from one of those endpoints doesn't sign users out. signOutOnRepeated401: false, }); ``` + +Without a refresh token or a `refresh` option, there's nothing to refresh +with, so the first 401 signs the user out, whatever `signOutOnRepeated401` +is. diff --git a/site/content/docs/(latest)/client/signing-in-and-out.mdx b/site/content/docs/(latest)/client/signing-in-and-out.mdx index 947633b..0fa5134 100644 --- a/site/content/docs/(latest)/client/signing-in-and-out.mdx +++ b/site/content/docs/(latest)/client/signing-in-and-out.mdx @@ -15,7 +15,7 @@ when the storage reports changes, as `webStorage()` does, and `locking` is off. If your backend can revoke tokens, give the client a `revoke` callback. It -receives the ended tokens after the user is signed out. +receives the ended tokens after the user is signed out: ```ts title="src/revoke.ts" import type { RevokeFn } from "@monarcode/session-kit"; @@ -33,6 +33,9 @@ export const revoke: RevokeFn = async ({ refreshToken, signal }) => { }; ``` +`signOut()` resolves once `revoke` settles, so await it before a full-page +redirect, which would cancel the request. + A failed revocation shows in `state.error` as `REVOKE_FAILED`, and the sign-out stands. The user asked to leave, and has. The client doesn't revoke a session the backend already rejected. diff --git a/site/content/docs/(latest)/client/state.mdx b/site/content/docs/(latest)/client/state.mdx index 03fc9a7..5681df1 100644 --- a/site/content/docs/(latest)/client/state.mdx +++ b/site/content/docs/(latest)/client/state.mdx @@ -25,6 +25,8 @@ export function logStatus() { throws doesn't interrupt auth. Its error is rethrown asynchronously, where error reporting can catch it. +The state holds these fields: + | Field | Holds | | ----------- | ------------------------------------------------------------------------------------- | | `status` | Where the session stands. [How it works](/docs#how-it-works) lists each one. | diff --git a/site/content/docs/(latest)/client/users-from-tokens.mdx b/site/content/docs/(latest)/client/users-from-tokens.mdx index 53987ed..f82f8da 100644 --- a/site/content/docs/(latest)/client/users-from-tokens.mdx +++ b/site/content/docs/(latest)/client/users-from-tokens.mdx @@ -33,6 +33,8 @@ export const signInWithTokens = (tokens: { }) => tokenAuth.signIn(tokens); ``` +Reading the user from the token changes a few things: + - **No `updateUser`.** The token is the only source of the user, so call `auth.refresh()` to pick up a change. - **The signature isn't verified.** That suits a browser, which trusts a user diff --git a/site/content/docs/(latest)/configuration/debugging.mdx b/site/content/docs/(latest)/configuration/debugging.mdx index ba5a940..9714c89 100644 --- a/site/content/docs/(latest)/configuration/debugging.mdx +++ b/site/content/docs/(latest)/configuration/debugging.mdx @@ -44,7 +44,7 @@ export const debug: AuthDebug = (event) => Events leave out tokens, saved values and the user's fields. A session appears as its `sessionId`, and an error as its code and message, without -its `cause`. +its `cause` or `issues`. To include them, pass `{ sensitive: true }`. Anyone who reads such logs can act as the user, so keep it to development builds. To set both, pass diff --git a/site/content/docs/(latest)/configuration/errors.mdx b/site/content/docs/(latest)/configuration/errors.mdx index e3fb211..5a2b2ea 100644 --- a/site/content/docs/(latest)/configuration/errors.mdx +++ b/site/content/docs/(latest)/configuration/errors.mdx @@ -6,7 +6,7 @@ description: How Session kit's errors reach your app, how to show them to users, Every error from Session kit's own logic is an `AuthError`, whether a method throws it, rejects with it, or publishes it in `state.error`. This page shows how to match on them, how to turn them into messages for your users, and the -two storage failures you need to handle. +storage failures you need to handle. ## Error codes @@ -42,8 +42,11 @@ usually aren't `AuthError`s, so `errorMessage` shows their own message. ## Handle storage failures -Two storage failures need a decision from you: +Three storage failures need a decision from you: +- **Storage can't be read.** `status` becomes `unavailable`, with the error + in `state.error`. The saved session stays as it is, and the next + `getSession()` or `retry()` reads it again. - **Storage can't be written.** The client ends the session and publishes the error. That way, no one stays signed in to a session that would vanish on reload. diff --git a/site/content/docs/(latest)/configuration/index.mdx b/site/content/docs/(latest)/configuration/index.mdx index 4ada43d..79ac59c 100644 --- a/site/content/docs/(latest)/configuration/index.mdx +++ b/site/content/docs/(latest)/configuration/index.mdx @@ -22,6 +22,10 @@ longer fit your app. | `debug` | No | [Reports what the client does](/docs/configuration/debugging). Default: off. | | `locking` | No | [Restores a saved session as `locked`](/docs/client/locking), for native apps. Default: off. | +`createAuth` throws an `AuthError` with the code `INVALID_OPTIONS` for an +option it can't use, such as a `name` with other characters, or a `maxAge` +that isn't a positive whole number. + ## Pages in this section Each page covers one part of the client: how it checks users, gets new diff --git a/site/content/docs/(latest)/configuration/storage.mdx b/site/content/docs/(latest)/configuration/storage.mdx index c504358..f6e6367 100644 --- a/site/content/docs/(latest)/configuration/storage.mdx +++ b/site/content/docs/(latest)/configuration/storage.mdx @@ -19,8 +19,8 @@ implements `AuthStorage`: | `memoryStorage()` | Memory | Tests, and sessions that shouldn't outlive the page. | | Your own `AuthStorage` | Anywhere | Another store. Its operations may return promises. | -For Expo, `secureStorage()` splits a session larger than SecureStore's -2048-byte limit across several keys. See +For Expo, `secureStorage()` splits a session larger than 2048 bytes, which +some iOS releases refuse to store in one value, across several keys. See [Secure storage](/docs/setups/expo#secure-storage) in the Expo guide. ## Rotating refresh tokens diff --git a/site/content/docs/(latest)/effect.mdx b/site/content/docs/(latest)/effect.mdx index 89101de..869fa0f 100644 --- a/site/content/docs/(latest)/effect.mdx +++ b/site/content/docs/(latest)/effect.mdx @@ -55,7 +55,7 @@ This is the backend from [Getting started](/docs/getting-started#1-talk-to-your-backend), as Effect Schemas: the user, the tokens, and the body DummyJSON explains a failure with. They're schemas only, with no client, so the rest of the app, and the -[server](#on-the-server), import them from one place. +[server](#on-the-server), import them from one place: ```ts title="src/backend.ts" import * as Schema from "effect/Schema"; @@ -334,8 +334,10 @@ export const accountName = Auth.session.pipe( ); ``` -Code outside `Auth` that rejects with an `AuthError`, such as -`createAuthFetch`, converts it with `Auth.fromAuthError`. +A client method that `Auth` doesn't wrap, such as `auth.unlock()`, rejects +with an `AuthError`. `Auth.fromAuthError` turns it into an `AuthFailure`. +Anything else it's given, such as a network error from `createAuthFetch`, is +a defect. ## Update the user @@ -434,6 +436,7 @@ queries and mutations made of them: import * as Fetch from "@monarcode/effetch"; import { useMutation, useQuery } from "@monarcode/effetch-query/react"; import { useAuthClient } from "@monarcode/session-kit/react"; +import * as Exit from "effect/Exit"; import * as AsyncResult from "effect/reactivity/AsyncResult"; import * as Schema from "effect/Schema"; @@ -455,19 +458,22 @@ const profileQuery = api.query( export function SignInButton() { const auth = useAuthClient(); const { result, run } = useMutation(signInMutation); + + async function signIn() { + const exit = await run({ + // DummyJSON's documented test user. + body: { username: "emilys", password: "emilyspass" }, + }); + // A failed request shows in `result`. + if (Exit.isFailure(exit)) return; + const { accessToken, refreshToken, ...user } = exit.value; + await auth.signIn({ accessToken, refreshToken, user }); + } + return ( diff --git a/site/content/docs/(latest)/faq.mdx b/site/content/docs/(latest)/faq.mdx index 6bee967..573a0c6 100644 --- a/site/content/docs/(latest)/faq.mdx +++ b/site/content/docs/(latest)/faq.mdx @@ -40,7 +40,9 @@ does. ## What if some endpoints answer 401 for other reasons? Set `signOutOnRepeated401: false` in `createAuthFetch`'s options, beside -`baseUrl`, so that those endpoints can't sign users out. See +`baseUrl`, so that a second 401 from those endpoints, after a refresh, +doesn't sign users out. Without a refresh token or a `refresh` callback, +any 401 still signs the user out. See [Authenticated requests](/docs/client/requests). ## How much does it add to my bundle? diff --git a/site/content/docs/(latest)/getting-started.mdx b/site/content/docs/(latest)/getting-started.mdx index 289b9f2..370a1f6 100644 --- a/site/content/docs/(latest)/getting-started.mdx +++ b/site/content/docs/(latest)/getting-started.mdx @@ -247,6 +247,8 @@ function AuthError() { } ``` +Each part of this file has a job: + - `AuthProvider` mounts the client. It restores the saved session, starts the refresh timer, and follows other tabs. - `useAuth()` returns the whole state. `useAuth(selector)` returns a part of @@ -255,7 +257,7 @@ function AuthError() { - With more than one client in an app, create hooks for each with `createAuthHooks()` instead. - `isSignedIn(state)` is `true` while `authenticated` or `refreshing`. Pass it - to `useAuth` to read just that: `useAuth(isSignedIn)`. It comes from + to `useAuth` to read only that: `useAuth(isSignedIn)`. It comes from `@monarcode/session-kit`. - `retry` and `signOut` reject when they fail, and publish the same failure in `state.error`. `AuthError` shows it, so the handlers have nothing left to diff --git a/site/content/docs/(latest)/index.mdx b/site/content/docs/(latest)/index.mdx index d296be8..2503263 100644 --- a/site/content/docs/(latest)/index.mdx +++ b/site/content/docs/(latest)/index.mdx @@ -87,7 +87,7 @@ Five terms come up throughout: | `status` | Meaning | `user` | | ----------------- | ------------------------------------------------------------------------- | ------ | -| `initializing` | The saved session is being restored. | `null` | +| `initializing` | The saved session hasn't been restored yet. | `null` | | `authenticated` | Access is usable. | Set | | `refreshing` | A refresh is replacing expired or rejected access. | Set | | `locked` | With `locking`, a session is saved, but its tokens wait for `unlock()`. | Set | diff --git a/site/content/docs/(latest)/reference/compatibility.mdx b/site/content/docs/(latest)/reference/compatibility.mdx index e7b73ff..2118a4a 100644 --- a/site/content/docs/(latest)/reference/compatibility.mdx +++ b/site/content/docs/(latest)/reference/compatibility.mdx @@ -25,6 +25,8 @@ import use: | `expo-file-system` | `^18.1.0` through `^58` | `/expo` | | `react-native` | `>=0.79.0` | `/expo` | +Three things to know about these peers: + - **Expo.** The Expo ranges cover Expo SDK 53 and newer. Install them with `npx expo install`, so that they match your SDK, as the [Expo guide](/docs/setups/expo#installation) shows. @@ -42,7 +44,9 @@ publishes no `exports` map, so its types don't resolve under NodeNext. ## Runtimes Session kit runs in browsers, in React Native (Expo SDK 53 and newer, with -Hermes and Metro), and in Node.js 20 and newer: +Hermes and Metro), and in Node.js 20 and newer. Your framework can need a +newer Node.js: React Router 8 needs 22.22. Session kit uses these platform +features: - **`AbortController`** is required. - **`crypto.randomUUID`** makes session IDs when present. Without it, the diff --git a/site/content/docs/(latest)/reference/core.mdx b/site/content/docs/(latest)/reference/core.mdx index 510114a..91a7b2c 100644 --- a/site/content/docs/(latest)/reference/core.mdx +++ b/site/content/docs/(latest)/reference/core.mdx @@ -41,7 +41,7 @@ Makes a "send me back here after sign-in" path safe to redirect to, such as a `? ### webStorage -Saves the session in the browser's `localStorage`, or in `sessionStorage` with `{ area: "session" }`. Tabs follow each other's changes, such as a sign-out, and take turns to refresh where the browser supports Web Locks. +Saves the session in the browser's `localStorage`, or in `sessionStorage` with `{ area: "session" }`. With `localStorage`, tabs follow each other's changes, such as a sign-out. Tabs take turns to refresh where the browser supports Web Locks. ## Classes diff --git a/site/content/docs/(latest)/reference/error-codes.mdx b/site/content/docs/(latest)/reference/error-codes.mdx index 92b403c..24b3899 100644 --- a/site/content/docs/(latest)/reference/error-codes.mdx +++ b/site/content/docs/(latest)/reference/error-codes.mdx @@ -23,15 +23,15 @@ The user couldn't be accepted. `issues` holds the schema's issues when it reject ## INVALID_SESSION -Tokens or a saved session that can't be used, such as an access token that already expired at sign-in. +Tokens or a saved session that can't be used, such as an access token that already expired at sign-in, or a saved session older than `maxAge`. In the browser of a server-rendered app, your server answered with something other than a session or an access token. ## PERSISTENCE_FAILED -Storage couldn't be read, written or cleared. In the browser of a server-rendered app, signing out on the server failed. +Storage couldn't be read, written or cleared, or `locking.seal` failed. In the browser of a server-rendered app, signing out on the server failed. ## REFRESH_FAILED -The refresh failed: your refresh callback threw, or there was no `refresh` option or refresh token to use. In the browser of a server-rendered app, reading the session or the access token from the server failed. +The refresh failed: your refresh callback threw or timed out, or there was no `refresh` option or refresh token to use. In the browser of a server-rendered app, reading the session or the access token from the server failed. On the server, the access token needed a refresh in a request that can't set cookies. ## REVOKE_FAILED @@ -55,4 +55,4 @@ The session is locked. Call `unlock()` first. ## INVALID_OPTIONS -An option or argument Session kit can't use, or a method called without the option it needs. +An option or argument Session kit can't use, or a method called without the option it needs or where it can't work, such as a server `signIn` in a request that can't set cookies. diff --git a/site/content/docs/(latest)/reference/expo.mdx b/site/content/docs/(latest)/reference/expo.mdx index 6c14fde..ed9c412 100644 --- a/site/content/docs/(latest)/reference/expo.mdx +++ b/site/content/docs/(latest)/reference/expo.mdx @@ -37,7 +37,7 @@ The `redirectSystemPath` that [`deepLinkHandler`](#deeplinkhandler) makes, for ` ### RememberDeepLinkOptions -Options for [`rememberDeepLink`](#rememberdeeplink), the same as `safeReturnTo`'s. Set `loginPath` when your sign-in screen isn't `/login`, so links to it are dropped rather than kept. +Options for [`rememberDeepLink`](#rememberdeeplink) and [`deepLinkHandler`](#deeplinkhandler), the same as `safeReturnTo`'s. Set `loginPath` when your sign-in screen isn't `/login`, so links to it are dropped rather than kept. } > @@ -394,47 +396,53 @@ To check the app: ## Secure storage -`secureStorage()` saves the session with `expo-secure-store`, in the iOS -keychain and in Keystore-encrypted storage on Android. The -[reference](/docs/reference/expo#securestorage) covers how it splits large -sessions, starts a reinstalled app signed out, and handles data Android can't -decrypt. Its options are in +[`secureStorage()`](/docs/reference/expo#securestorage) saves the session +with `expo-secure-store`, in the iOS keychain and in Keystore-encrypted +storage on Android. A session over 2048 bytes, which some iOS releases refuse +to store in one value, is split across several keys, up to 128 KB. By +default, a reinstalled app starts signed out. So does an app whose saved +session Android can't decrypt, as after a backup is restored onto another +device. Its options are in [`SecureStorageOptions`](/docs/reference/expo#securestorageoptions). Two things depend on your app: -- **Background refreshes.** While the iOS keychain can't be read, the session - is `unavailable`, never signed out. An app that refreshes in a background - task before the device's first unlock needs +- **Background refreshes.** By default, iOS lets the app read the keychain + only while the device is unlocked. While the keychain can't be read, the + session is `unavailable`, never signed out. An app that refreshes in a + background task while the device is locked needs `secureStorage({ keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK })`. - **Android backups.** The `expo-secure-store` config plugin from [Installation](#installation) keeps the session out of Auto Backup. ## SessionGate -`SessionGate` adds what `Stack.Protected` lacks. It holds the splash screen -while the session is restored, shows `unavailable` when access can't be used, -checks the session again when the app returns to the foreground, and opens -deep links kept for after sign-in. The -[reference](/docs/reference/expo#sessiongate) says what it does in each -state, and [`SessionGateProps`](/docs/reference/expo#sessiongateprops) +[`SessionGate`](/docs/reference/expo#sessiongate) adds what `Stack.Protected` +lacks. It holds the splash screen while the session is restored, shows +`unavailable` when access can't be used, checks the session again when the +app returns to the foreground, and opens deep links kept for after sign-in. +While the session is locked, it renders the navigator, so your guards can +show an unlock screen. When one account replaces another without a sign-out +between them, it remounts the navigator, so no screen keeps the previous +account's state. [`SessionGateProps`](/docs/reference/expo#sessiongateprops) covers `ready` and `unavailable`. ## Deep links -`deepLinkHandler` keeps one link at a time, and `SessionGate` opens it after -the next sign-in or unlock. The -[reference](/docs/reference/expo#rememberdeeplink) says when a link is -opened, dropped or ignored. A link to a screen anyone may see is dropped once +[`deepLinkHandler`](/docs/reference/expo#deeplinkhandler) keeps one link at a +time, and `SessionGate` opens it after the next sign-in or unlock. A link to +the root or the sign-in screen is ignored, as is one that could leave the +app. A link that arrives while the user is signed in is dropped, since Expo +Router opens it as usual. A link to a screen anyone may see is dropped once that screen shows. If the app launched with it, it's dropped at the sign-in instead, unopened. -Pass `deepLinkHandler(auth, { loginPath: "/sign-in" })` if your sign-in -screen isn't `/login`. +If your sign-in screen isn't `/login`, pass +`deepLinkHandler(auth, { loginPath: "/sign-in" })`. -`Stack.Protected`'s `redirectTo` only chooses the screen a turned-away link -goes to, such as `/login`. It doesn't keep the link, so `deepLinkHandler` is -still what opens it after the sign-in. +Where `Stack.Protected` takes a `redirectTo`, as in Expo SDK 58, it only +chooses the screen a turned-away link goes to, such as `/login`. It doesn't +keep the link, so `deepLinkHandler` is still what opens it after the sign-in. There is no `?redirectTo=` parameter on Expo. The link waits in memory, not in the URL, and an app restart forgets it. @@ -468,8 +476,12 @@ with `user` and `sessionId` set and its tokens sealed by a key your app holds. Expo side. Keep a random key in a SecureStore item that needs biometrics to read, and -seal the tokens with AES-GCM. This example uses `@noble/ciphers` and -`expo-crypto`, your app's dependencies, not Session kit's: +seal the tokens with AES-GCM. SecureStore's biometric prompt needs a +development build on a real device. Expo Go doesn't support it, and +simulators don't ask for biometrics. On iOS, the `expo-secure-store` config +plugin from [Installation](#installation) adds the Face ID permission. This +example uses `@noble/ciphers` and `expo-crypto`, your app's dependencies, not +Session kit's: ```ts title="src/session-key.ts" import { Platform } from "react-native"; @@ -486,7 +498,7 @@ import { getRandomBytes } from "expo-crypto"; import * as SecureStore from "expo-secure-store"; const KEY_ITEM = "session-key"; -// Whether the key needs biometrics: it must be read the way it was saved. +// Whether the key was saved behind biometrics, so it's read the same way. const BIOMETRIC_ITEM = "session-key-biometric"; function keyOptions(biometric: boolean): SecureStore.SecureStoreOptions { @@ -515,11 +527,21 @@ async function saveKey(next: Uint8Array): Promise { await SecureStore.setItemAsync(BIOMETRIC_ITEM, String(biometric)); } -/** Reads the key, which shows the prompt when it needs biometrics. */ +/** + * Reads the key, which shows the prompt when it needs biometrics. Resolves + * `null` when no key was saved yet. + */ async function readKey(): Promise { const biometric = await SecureStore.getItemAsync(BIOMETRIC_ITEM); if (biometric === null) return null; - return SecureStore.getItemAsync(KEY_ITEM, keyOptions(biometric === "true")); + const saved = await SecureStore.getItemAsync( + KEY_ITEM, + keyOptions(biometric === "true"), + ); + // SecureStore reads `null` for a key that a change to the device's + // biometrics made unreadable. + if (saved === null) throw new Error("The session key can't be read"); + return saved; } /** @@ -536,8 +558,7 @@ export async function loadKey(): Promise { // iOS, saving doesn't prompt, so read it back to show the prompt. const next = getRandomBytes(32); await saveKey(next); - if (Platform.OS === "ios" && !(await readKey())) - throw new Error("Could not read the new session key"); + if (Platform.OS === "ios") await readKey(); key = next; } diff --git a/site/content/docs/(latest)/setups/next.mdx b/site/content/docs/(latest)/setups/next.mdx index b768968..376f9b8 100644 --- a/site/content/docs/(latest)/setups/next.mdx +++ b/site/content/docs/(latest)/setups/next.mdx @@ -92,8 +92,8 @@ setup shares. ## 2. Read the session in Server Components `nextSession` from `@monarcode/session-kit/next` gives your app its session -over Next's cookies. Pass it Next's own `cookies` and `redirect`, and create -it in a server-only module too: +over Next's cookies. Session kit doesn't import `next`, so pass it Next's own +`cookies` and `redirect`. Create it in a server-only module too: ```ts title="lib/auth/session.ts" import "server-only"; @@ -428,8 +428,9 @@ The example app does this. Server Functions rarely need to. - **A `basePath`.** Next doesn't add it to `fetch`, so the client's `endpoint` includes it: `"/app/api/session"`. -- **Rendering.** Reading cookies makes a page dynamic. Next sends such pages - with `Cache-Control: no-store`, and plain `use cache` can't read cookies. +- **Rendering.** Reading cookies makes a page dynamic, and the root layout + reads the session, so every page is dynamic. Next sends such pages with + `Cache-Control: no-store`, and plain `use cache` can't read cookies. Keep pages that read the session on the Node.js runtime, the default. Next may not pass Proxy's refreshed cookie on to Edge runtime pages. - **Tabs.** Signing in or out in one tab reaches the others, which ask the diff --git a/site/content/docs/(latest)/setups/react-router-ssr.mdx b/site/content/docs/(latest)/setups/react-router-ssr.mdx index 11f70ed..3a299e4 100644 --- a/site/content/docs/(latest)/setups/react-router-ssr.mdx +++ b/site/content/docs/(latest)/setups/react-router-ssr.mdx @@ -4,12 +4,12 @@ description: Keep the session in an encrypted cookie in React Router's framework --- In this guide, you keep the session in an encrypted cookie in React Router's -framework mode. Actions sign in and out, middleware refreshes the tokens, and -loaders read the session. The first response already shows the signed-in -page, so the browser never shows a "Checking session…" state or a flash of -signed-out content. Components get a small client that mirrors the session, -and the [hooks](/docs/getting-started#4-read-the-session-in-react) work with -it. +framework mode. An action signs in, a session route answers the browser, +middleware refreshes the tokens, and loaders read the session. The first +response already shows the signed-in page, so the browser never shows a +"Checking session…" state or a flash of signed-out content. Components get a +small client that mirrors the session, and the +[hooks](/docs/getting-started#4-read-the-session-in-react) work with it. [Server rendering](/docs/server-rendering) explains how the pieces fit. For framework mode with `ssr: false`, follow @@ -20,9 +20,9 @@ instead. A complete app is in ## Before you begin - React Router's middleware: React Router 8, or 7.9 and later with - `future.v8_middleware`. The code on this page is for React Router 8. On 7, - read the URL with `new URL(request.url)` where the code uses the `url` - argument. + `future.v8_middleware`. The code on this page is for React Router 8. On + 7.14 and earlier, read the URL with `new URL(request.url)` where the code + uses the `url` argument. - A secret of 32 or more random characters to seal the cookie, set as `SESSION_SECRET` on the server. To make one, run `openssl rand -base64 32`. `react-router build` doesn't need it. @@ -32,19 +32,11 @@ instead. A complete app is in To install the packages, run the following command: ```npm -npm install @monarcode/session-kit zod +npm install @monarcode/session-kit react-router zod ``` ## 1. Create the server engine -Put the user schema in a module that the server and the browser both import: - -```ts title="app/auth/user.ts" -import { z } from "zod"; - -export const userSchema = z.object({ id: z.number(), firstName: z.string() }); -``` - `createServerAuth` from `@monarcode/session-kit/server` keeps the session in a cookie sealed with your `secret`, and refreshes it with your backend. `routerAuth` gives a request's session by its `context`, and @@ -59,10 +51,9 @@ import { import { createServerAuth } from "@monarcode/session-kit/server"; import { z } from "zod"; -import { userSchema } from "./user"; - const API = "https://api.example.com"; +const userSchema = z.object({ id: z.number(), firstName: z.string() }); const tokens = z.object({ accessToken: z.string(), refreshToken: z.string() }); export const serverAuth = createServerAuth({ @@ -302,8 +293,9 @@ export const action = route.action; ``` Add it to `app/routes.ts` as `route("auth/session", "routes/auth.session.ts")`. -Export the loader and action one by one, as above. React Router's build fails -on a destructured `export const { loader, action }`. The route answers your +Export the loader and action one by one, as `app/routes/auth.session.ts` +does. React Router's build fails on a destructured +`export const { loader, action }`. The route answers your own site's pages only, so another site can't sign the user out: see [Security](/docs/security). @@ -416,6 +408,14 @@ The example app does this. refreshes before that. - **One session per request.** `auth(context)` returns the same session for every call with the same `context`, which React Router makes per request. +- **Caching.** `sessionMiddleware` leaves a response that sets its own + `Cache-Control` as it is. Pass `cacheControl` to send another value, or + `{ cacheControl: false }` to leave every response as it is. +- **Guards with the same names.** `requireSession` and `redirectIfSignedIn` + on this page come from `@monarcode/session-kit/react-router/server`. + `@monarcode/session-kit/react-router` exports guards with the same names + that take the browser's client, for apps without server rendering: see + [React Router](/docs/setups/react-router). - **A `basename`.** Pass it to the guard too, as `requireSession(serverAuth, { basename: "/app" })`. React Router adds it to loaders' and actions' redirects, but not to middleware's, so the guard adds diff --git a/site/content/docs/(latest)/setups/react-router.mdx b/site/content/docs/(latest)/setups/react-router.mdx index 25c5c5a..5d97f02 100644 --- a/site/content/docs/(latest)/setups/react-router.mdx +++ b/site/content/docs/(latest)/setups/react-router.mdx @@ -34,9 +34,10 @@ React Router 7 and 8 both work. ## Add a page to protect -In every mode, `AuthProvider` goes around the router. It mounts the client in -a layout effect, so with `localStorage` and a synchronous schema, the session -is restored before the first paint. Nothing starts on a server. Register the +In declarative and data mode, `AuthProvider` goes around the router. In +framework mode, it goes in the root route. It mounts the client in a layout +effect, so with `localStorage` and a synchronous schema, the session is +restored before the first paint. Nothing starts on a server. Register the client where you render it, as step 4 of Getting started shows, and the hooks from `@monarcode/session-kit/react` carry your user. @@ -146,7 +147,7 @@ A complete app is in ## Data mode In data mode, loaders run before a route renders, so the guard goes there. A -private route's data is never fetched for a signed-out user: +signed-out user is redirected before a private route renders: ```tsx title="src/router.tsx" import { createBrowserRouter, Outlet, useRouteError } from "react-router"; @@ -206,7 +207,7 @@ Then render the router inside the provider, in `src/main.tsx`: ```tsx import { StrictMode } from "react"; -import { RouterProvider } from "react-router"; +import { RouterProvider } from "react-router/dom"; import { AuthProvider } from "@monarcode/session-kit/react"; import { createRoot } from "react-dom/client"; @@ -400,7 +401,7 @@ typed with your user: - **`requireSessionLoader(auth)`** is the whole loader. Use it on a route that guards and loads nothing else, usually the layout route around your - private pages, as above. + private pages, as in [Data mode](#data-mode). - **`requireSession(auth, { request })`** is a call inside a loader of your own. Use it when the loader loads data too: data only a signed-in user may load, or data that needs who is signed in. diff --git a/site/content/docs/(latest)/setups/tanstack-router.mdx b/site/content/docs/(latest)/setups/tanstack-router.mdx index 9fa0f57..0be218f 100644 --- a/site/content/docs/(latest)/setups/tanstack-router.mdx +++ b/site/content/docs/(latest)/setups/tanstack-router.mdx @@ -359,8 +359,7 @@ written with Effect and effetch, in signed-in user never sees the sign-in page. - **Stopping.** Call `disconnectAuth` on app teardown or hot-module disposal. It stops background work without signing out. In Start's SPA mode, - `getRouter()` above doesn't keep it, as the Router lasts as long as the - page. + `getRouter()` doesn't keep it, as the Router lasts as long as the page. - **A failed refresh is not a redirect.** `requireSession` rethrows it for the route's error component, which can offer `auth.retry()`. The user is still signed in. diff --git a/site/content/docs/(latest)/setups/tanstack-start.mdx b/site/content/docs/(latest)/setups/tanstack-start.mdx index 451c34a..f13024a 100644 --- a/site/content/docs/(latest)/setups/tanstack-start.mdx +++ b/site/content/docs/(latest)/setups/tanstack-start.mdx @@ -28,7 +28,7 @@ instead. A complete app is in To install the packages, run the following command: ```npm -npm install @monarcode/session-kit @tanstack/react-start zod +npm install @monarcode/session-kit @tanstack/react-start @tanstack/react-router zod ``` ## 1. Create the server engine @@ -114,7 +114,7 @@ export const Route = createFileRoute("/api/session")({ ``` It answers your own site's pages only, so another site can't sign the user -out: see [Security](/docs/security). +out: see [The session route](/docs/security#the-session-route). Two server functions do the rest. Signing in takes your form's input. Reading the session is a server function too, because `loadSession` reads it while @@ -180,6 +180,10 @@ export const startInstance = createStart(() => ({ })); ``` +It refreshes access that expires within 60 seconds. Access tokens that live +a minute or less are refreshed on every request, so pass a smaller `within` +for them, such as `refreshSession(serverAuth, { within: 15 })`. + A failed refresh doesn't fail the request. Routes read the session as usual, and an error there reaches the route's error component. @@ -266,6 +270,11 @@ export const Route = createRootRouteWithContext<{ auth: AppAuth }>()({ }); ``` +When the server can't read the session, such as after a failed refresh, +`loadSession` rejects, and the root route's `errorComponent` shows. In the +example app, it offers a retry with `router.invalidate()`, which runs +`loadSession` again. + Guards are the ones from `@monarcode/session-kit/tanstack-router`. On the server, a redirect is a real HTTP redirect: @@ -284,7 +293,8 @@ export const Route = createFileRoute("/_authenticated")({ ``` [Guard private routes](/docs/setups/tanstack-router#3-guard-private-routes) -explains `SessionOutlet`, and an error component for a failed refresh. +explains `SessionOutlet`. Its error component isn't needed here, as +`loadSession` reports a failed refresh first. Guards decide what a page shows. Server functions that return private data must check the session themselves, with `session.getSession()` or @@ -327,6 +337,27 @@ comes from the backend. If the browser signs in with the backend itself, for example through a provider's SDK, have `signInFn` take the tokens instead, as [Hybrid setup](/docs/server-rendering/hybrid) shows. +## Sign out + +The client's `signOut()` signs out on the server through the session route, +which clears the cookie and calls your `revoke` option, when +`createServerAuth` has one. It then signs out this tab and tells the others. +Guards run again, so `requireSession` sends the user to the sign-in page: + +```tsx title="src/sign-out.tsx" +import { useAuthClient } from "@monarcode/session-kit/tanstack-router"; + +export function SignOutButton() { + const auth = useAuthClient(); + // A failed sign-out keeps the session, and shows in `state.error`. + return ( + + ); +} +``` + ## Call your API Call your API with `createAuthFetch` from `@monarcode/session-kit/http`. diff --git a/src/core/debug.ts b/src/core/debug.ts index 02a4aa6..b3c14f6 100644 --- a/src/core/debug.ts +++ b/src/core/debug.ts @@ -4,6 +4,10 @@ import { AuthError } from "./errors.js"; * Which part of auth an {@link AuthDebugEvent} comes from, such as `refresh` * or `storage`. These names don't change between releases, so filter on them. * + * `sync` events report changes from other tabs and, with server rendering, + * from the server. `gate`, `deep-link` and `foreground` events come from + * `@monarcode/session-kit/expo`. + * * @example * ```ts * import type { AuthDebugEvent, AuthDebugType } from "@monarcode/session-kit"; @@ -56,7 +60,7 @@ export type AuthDebugType = * @since 0.1.0 */ export type AuthDebugEvent = Readonly<{ - /** The `name` passed to `createAuth`. */ + /** The `name` option of the client that reports it. */ name: string; /** Which part of auth it comes from. */ type: AuthDebugType; @@ -65,9 +69,8 @@ export type AuthDebugEvent = Readonly<{ /** Details, such as `status`, `sessionId`, or `durationMs`. */ data?: Readonly> | undefined; /** - * The failure, when the event reports one. Without `sensitive`, only its - * `code` and `message` are kept, as `cause` and `issues` can hold tokens - * or user fields. + * The failure, when the event reports one. Without `sensitive`, it comes + * without its `cause` and `issues`, which can hold tokens or user fields. */ error?: AuthError | undefined; }>; diff --git a/src/core/errors.ts b/src/core/errors.ts index 1aa3795..2a03772 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -26,19 +26,23 @@ export type AuthErrorCode = | "USER_VALIDATION_FAILED" /** * Tokens or a saved session that can't be used, such as an access token - * that already expired at sign-in. + * that already expired at sign-in, or a saved session older than `maxAge`. + * In the browser of a server-rendered app, your server answered with + * something other than a session or an access token. */ | "INVALID_SESSION" /** - * Storage couldn't be read, written or cleared. In the browser of a - * server-rendered app, signing out on the server failed. + * Storage couldn't be read, written or cleared, or `locking.seal` failed. + * In the browser of a server-rendered app, signing out on the server + * failed. */ | "PERSISTENCE_FAILED" /** - * The refresh failed: your refresh callback threw, or there was no - * `refresh` option or refresh token to use. In the browser of a + * The refresh failed: your refresh callback threw or timed out, or there + * was no `refresh` option or refresh token to use. In the browser of a * server-rendered app, reading the session or the access token from the - * server failed. + * server failed. On the server, the access token needed a refresh in a + * request that can't set cookies. */ | "REFRESH_FAILED" /** @@ -59,7 +63,8 @@ export type AuthErrorCode = | "UNLOCK_FAILED" /** * An option or argument Session kit can't use, or a method called without - * the option it needs. + * the option it needs or where it can't work, such as a server `signIn` in + * a request that can't set cookies. */ | "INVALID_OPTIONS"; diff --git a/src/core/mirror.ts b/src/core/mirror.ts index d90d6dc..a98b383 100644 --- a/src/core/mirror.ts +++ b/src/core/mirror.ts @@ -140,11 +140,11 @@ type MirrorAuthBaseOptions = { * Reads the session on your server again, with `serverAuth.getSession`, * such as through a server function. Required without `endpoint`. * - * The client calls it when the tab becomes visible after 10 seconds or - * more, when another tab signs in or out, and from `retry()` and - * `refresh()`. Pass one when the session is also read while the server - * renders, where `endpoint` can't be called, as in TanStack Start. - * Default: a `GET` to `endpoint`. + * The client calls it when the tab becomes visible again, unless the + * server answered in the last 10 seconds, when another tab signs in or + * out, and from `retry()` and `refresh()`. Pass one when the session is + * also read while the server renders, where `endpoint` can't be called, + * as in TanStack Start. Default: a `GET` to `endpoint`. */ revalidate?: (() => Promise | null>) | undefined; /** @@ -242,7 +242,9 @@ type MirrorAuthBase = { * Resolves the current access token, or `null` when signed out. Calls * that overlap share one request. Rejects with `REFRESH_FAILED` when * your server fails, or with the session route's own code, such as - * `INVALID_OPTIONS` without `clientCredentials`. + * `INVALID_OPTIONS` without `clientCredentials`. Rejects with + * `SESSION_CHANGED` when the session changed meanwhile, here or on the + * server. */ get: () => Promise; /** @@ -369,7 +371,8 @@ function stateOf( * * Let TypeScript infer its types from the options. With an explicit * `createMirrorAuth(…)`, `signIn` drops out of the type. Throws - * `INVALID_OPTIONS` for options it can't use. + * `INVALID_OPTIONS` for options it can't use, and `INVALID_SESSION` for a + * `session` that isn't a session or `null`. * * @example * ```ts diff --git a/src/core/persistence.ts b/src/core/persistence.ts index c63d8c5..e4711f5 100644 --- a/src/core/persistence.ts +++ b/src/core/persistence.ts @@ -189,8 +189,9 @@ export function createPersistence( /** * The saved session in `entry`, opening sealed tokens with `sealing.open`. - * Rejects with `UNLOCK_FAILED` when `open` throws, and `INVALID_SESSION` - * when what it returns isn't this entry's tokens. + * Fails with `UNLOCK_FAILED` when `open` throws or doesn't return a + * string, and with `INVALID_SESSION` when what it returns isn't this + * entry's tokens. */ function open(entry: SavedEntry): MaybePromise { if (entry.tokens) diff --git a/src/core/return-to.ts b/src/core/return-to.ts index e0ea9d9..397f141 100644 --- a/src/core/return-to.ts +++ b/src/core/return-to.ts @@ -53,9 +53,9 @@ export function sameRoute(a: string, b: string): boolean { * leads somewhere in your app, query and fragment included. * * Anything else returns `"/"`: - * - another site, including protocol-relative `//host` paths; - * - a path with backslashes, spaces or control characters; - * - the sign-in page itself, so a stale `redirectTo` can't loop. + * - Another site, including protocol-relative `//host` paths. + * - A path with backslashes, spaces or control characters. + * - The sign-in page itself, so a stale `redirectTo` can't loop. * * Throws `INVALID_OPTIONS` when a `loginPath` doesn't start with `/`. * diff --git a/src/core/storage.ts b/src/core/storage.ts index 9d946ec..cf56ec2 100644 --- a/src/core/storage.ts +++ b/src/core/storage.ts @@ -120,8 +120,9 @@ export type WebStorageOptions = { /** * Saves the session in the browser's `localStorage`, or in `sessionStorage` - * with `{ area: "session" }`. Tabs follow each other's changes, such as a - * sign-out, and take turns to refresh where the browser supports Web Locks. + * with `{ area: "session" }`. With `localStorage`, tabs follow each other's + * changes, such as a sign-out. Tabs take turns to refresh where the browser + * supports Web Locks. * * It touches browser storage only when auth reads or saves, so creating auth * in code that also runs on a server is safe. Reading the session on a server diff --git a/src/core/types.ts b/src/core/types.ts index b996cbd..7997fe9 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -205,8 +205,8 @@ export type RefreshResult = * Auth calls it whenever it needs a new access token: shortly before the * current one expires (while mounted), once it has expired, when your API * rejects it, on `refresh()`, and on `retry()` once it has expired. It never - * runs two at once. - * Callers that need a refresh while one runs share its result. + * runs two at once. Callers that need a refresh while one runs share its + * result. * * @example * ```ts @@ -249,9 +249,10 @@ export type RefreshFn = (context: { * Asks your backend to revoke the tokens of a session that just signed out. * It's the `revoke` option of {@link AuthOptions}. * - * `signOut()` calls it after the user is already signed out, so the UI never - * waits for it. If it fails, `state.error` shows `REVOKE_FAILED`, and - * `signOut()` still resolves. + * `signOut()` calls it after the user is already signed out, so a UI that + * follows the state never waits for it. `signOut()` itself resolves once it + * settles. If it fails, `state.error` shows `REVOKE_FAILED`, and `signOut()` + * still resolves. * * It isn't called when your backend ended the session itself, or when a * `locked` session signs out, as its tokens aren't in memory. @@ -413,8 +414,8 @@ type SignedOutState = StateFields & { * tokens. * * Check `status`, not `user`, to know whether requests can be made. `user` - * stays set while `refreshing` or `locked`. Checking `status` also narrows - * `user`, so TypeScript knows when it's set. + * stays set while `locked`, when they can't. `isSignedIn` is that check. + * Checking `status` also narrows `user`, so TypeScript knows when it's set. * * @example * ```ts @@ -474,17 +475,20 @@ type AuthClientBase = { * Signs in with the tokens your backend issued, and saves the session. It * replaces any current session, even a locked one. * - * Rejects with `INVALID_SESSION` for tokens that already expired, and with - * `USER_VALIDATION_FAILED` for a user the schema rejects. The previous - * session then stays. If `signIn` or `signOut()` is called again while it's - * still checking the user, it rejects with `SESSION_CHANGED`, as the latest - * call wins. + * Rejects with `INVALID_SESSION` for tokens it can't use, such as ones that + * already expired, and with `USER_VALIDATION_FAILED` for a user the schema + * rejects. The previous session then stays. If `signIn` or `signOut()` is + * called again while it's still checking the user, it rejects with + * `SESSION_CHANGED`, as the latest call wins. + * + * If the session can't be saved, it rejects with `PERSISTENCE_FAILED`, and + * no one is signed in. */ signIn: (input: SignInInput) => Promise; /** * Signs out at once, clears the saved session, then calls your `revoke` - * option. Other tabs that share the storage sign out too, when it reports - * changes (`subscribe`) and `locking` is off. + * option and waits for it. Other tabs that share the storage sign out too, + * when it reports changes (`subscribe`) and `locking` is off. * * If `revoke` fails, `state.error` shows `REVOKE_FAILED`, and `signOut()` * still resolves. If storage can't be cleared, it rejects with @@ -497,7 +501,9 @@ type AuthClientBase = { * session first if needed, and refreshes an expired access token. * * After a refresh fails, it rejects with that failure until `retry()`, - * `signIn` or `signOut()`. Rejects with `LOCKED` while locked. + * `signIn` or `signOut()`. Rejects with `PERSISTENCE_FAILED` when the saved + * session can't be read, with `SESSION_CHANGED` when the session changes + * while it runs, and with `LOCKED` while locked. */ getSession: () => Promise | null>; /** @@ -540,8 +546,11 @@ type AuthClientBase = { * `getSession()`. Overlapping calls share one unlock. * * If `open` throws or doesn't return a string, it rejects with - * `UNLOCK_FAILED`, and the session stays locked. If the saved session can't - * be used, it signs out and rejects with `INVALID_SESSION`. + * `UNLOCK_FAILED`, and the session stays locked. If storage can't be read, + * it rejects with `PERSISTENCE_FAILED`, and the session stays locked too. + * + * If the saved session can't be used, it signs out and rejects with + * `INVALID_SESSION`. If it's gone, it signs out and resolves `null`. * * An expired access token is refreshed at once. If your backend rejects the * refresh token, it signs out and resolves `null`. If the refresh fails @@ -572,6 +581,9 @@ type AuthClientBase = { * Gets a new access token after your API rejected `credentials`, such as * with a 401. Calls that overlap share one refresh. Without a `refresh` * option or a refresh token, it signs out and resolves `null`. + * + * Rejects with `REFRESH_FAILED` when the refresh fails, and with + * `SESSION_CHANGED` when another session has replaced theirs. */ renew: (credentials: Credentials) => Promise; /** @@ -618,8 +630,9 @@ export type AuthClient = AuthClientBase & * * Rejects with `UNAUTHENTICATED` when signed out, and with * `USER_VALIDATION_FAILED` for a user the schema rejects, or when - * the function rejects or times out. If calls overlap, the latest - * wins and the others reject with `SESSION_CHANGED`. + * the function rejects or takes more than 15 seconds. If calls + * overlap, the latest wins and the others reject with + * `SESSION_CHANGED`. */ updateUser: (input: I | (() => Promise)) => Promise; }); @@ -649,7 +662,11 @@ export type AuthClient = AuthClientBase & * @since 0.1.0 */ export type AuthLocking = { - /** Encrypts the tokens, given as a JSON string. */ + /** + * Encrypts the tokens, given as a JSON string. If it throws while a + * session is saved, the save fails with `PERSISTENCE_FAILED`, which signs + * the user out. + */ seal: (payload: string) => string | Promise; /** Decrypts what `seal` returned. It must throw when it can't. */ open: (sealed: string) => string | Promise; @@ -715,8 +732,10 @@ export type AuthOptions = { */ revoke?: RevokeFn | undefined; /** - * How long a saved session lasts, in seconds. Each save, such as after a - * refresh, starts it again. Default: 30 days. + * How long a saved session lasts, in whole seconds. Each save, such as + * after a refresh, starts it again. A session saved longer ago isn't + * restored: the user is signed out, with `INVALID_SESSION` in + * `state.error`. Default: 30 days. */ maxAge?: number | undefined; /** @@ -727,6 +746,8 @@ export type AuthOptions = { * Tokens, user fields, saved values and error details are left out unless * you pass `{ sensitive: true }`. Pass a development flag, such as Expo's * `__DEV__`, to keep it out of production. + * + * @default false */ debug?: AuthDebug | undefined; /** diff --git a/src/effect/auth.ts b/src/effect/auth.ts index ed5f04e..4117ea5 100644 --- a/src/effect/auth.ts +++ b/src/effect/auth.ts @@ -294,7 +294,9 @@ export class Auth extends Context.Service()( * with a 401. Calls at the same time share one refresh. * * Fails with `UNAUTHENTICATED` when the session ended instead, and with - * `SESSION_CHANGED` when another session replaced it. + * `SESSION_CHANGED` when another session replaced it. It fails with + * `LOCKED` while locked, and with the refresh's own failure, such as + * `REFRESH_FAILED`. * * `sessionBearer` from `@monarcode/session-kit/effetch` renews on a 401 * by itself. @@ -365,6 +367,10 @@ export class Auth extends Context.Service()( * client is signed out anyway when only its storage couldn't be cleared, * and a failed `revoke` doesn't fail it. A `createMirrorAuth` client * stays signed in when your server's sign-out fails. + * + * Dies with a request's session on the server where the request can't set + * cookies, such as in a Next.js page. Sign out in an action or a route + * handler. */ static readonly signOut: Effect.Effect = Auth.use( (client) => fromPromise(() => client.signOut()), diff --git a/src/effetch/index.ts b/src/effetch/index.ts index 03bc962..927d015 100644 --- a/src/effetch/index.ts +++ b/src/effetch/index.ts @@ -35,8 +35,9 @@ import { */ export interface SessionBearerOptions { /** - * Your API's URL, usually the effetch client's `baseUrl`. The access token - * goes only to requests on its origin. + * Your API's URL, usually the effetch client's `baseUrl`. It must be + * absolute, such as `https://api.example.com`. The access token goes only + * to requests on its origin. */ baseUrl: string; /** @@ -107,8 +108,11 @@ const refuseRedirects = ( * * Calls fail with `AuthFailure`, before sending anything: `UNAUTHENTICATED` * when signed out, unless `optional` sends them without a token, and - * `LOCKED` while locked. If the session changes during a call, it fails with - * `SESSION_CHANGED` rather than return a response meant for another account. + * `LOCKED` while locked. When a refresh fails, the call fails with that + * failure, such as `REFRESH_FAILED`. + * + * If the session changes during a call, it fails with `SESSION_CHANGED` + * rather than return a response meant for another account. * * The token never leaves your API. A request on another origin, or with a * username or password in its URL, dies with `INVALID_OPTIONS`. With diff --git a/src/expo/deep-link.ts b/src/expo/deep-link.ts index 6ad98e1..606d5d9 100644 --- a/src/expo/deep-link.ts +++ b/src/expo/deep-link.ts @@ -14,9 +14,9 @@ import type { AuthStatus } from "../core/types.js"; import type { AuthSource } from "../react/context.js"; /** - * Options for {@link rememberDeepLink}, the same as `safeReturnTo`'s. Set - * `loginPath` when your sign-in screen isn't `/login`, so links to it are - * dropped rather than kept. + * Options for {@link rememberDeepLink} and {@link deepLinkHandler}, the same + * as `safeReturnTo`'s. Set `loginPath` when your sign-in screen isn't + * `/login`, so links to it are dropped rather than kept. * * @example * ```ts @@ -108,6 +108,10 @@ export function deepLinkPath(url: string): string { * sign-in or unlock, once `SessionGate`'s `ready` is `true`. * - **A screen anyone may see**: drops it once that screen is showing. * + * Throws `INVALID_OPTIONS` for a `loginPath` that doesn't start with `/`. + * Expo Router warns that a throw in `redirectSystemPath` can crash the app. + * {@link deepLinkHandler} throws when it's made instead. + * * @example * ```ts * // app/+native-intent.tsx @@ -193,6 +197,8 @@ export type DeepLinkHandler = (event: { * export const redirectSystemPath = deepLinkHandler(auth); * ``` * + * @see {@link RememberDeepLinkOptions} to set your sign-in screen's path + * * @since 0.1.0 */ export function deepLinkHandler( diff --git a/src/expo/gate.ts b/src/expo/gate.ts index 1e8d9f2..fb81788 100644 --- a/src/expo/gate.ts +++ b/src/expo/gate.ts @@ -143,6 +143,7 @@ function useAccountKey(sessionId: string | null): number { * for after sign-in. * * Render it inside `AuthProvider`, or pass a `client`, which it mounts. + * Without either, it throws `INVALID_OPTIONS`. * * - **While the session is restored**, and until `ready`, it renders * nothing, so the splash screen stays up, and hides the splash screen once @@ -156,7 +157,9 @@ function useAccountKey(sessionId: string | null): number { * unlock screen. Neither unlocking nor a password sign-in from the lock * screen remounts the navigator. * - **When the app returns to the foreground** it re-checks the session, - * because timers don't run while iOS suspends the app. + * because timers don't run while iOS suspends the app. An access token that + * expired meanwhile is refreshed. A refresh that already failed stays + * failed until `retry()`. * - **After a sign-in or unlock** it opens the deep link * `rememberDeepLink` kept, with `router.replace`, once `ready`. * - **When one account replaces another** without a sign-out between them, it diff --git a/src/expo/secure-storage.ts b/src/expo/secure-storage.ts index 2ac62da..93d0e69 100644 --- a/src/expo/secure-storage.ts +++ b/src/expo/secure-storage.ts @@ -19,7 +19,7 @@ import type { AuthStorage } from "../core/storage.js"; * import { secureStorage } from "@monarcode/session-kit/expo"; * import { AFTER_FIRST_UNLOCK } from "expo-secure-store"; * - * // For an app that refreshes in a background task before the first unlock. + * // For an app that refreshes in a background task while the device is locked. * export const storage = secureStorage({ * keychainAccessible: AFTER_FIRST_UNLOCK, * }); @@ -31,7 +31,7 @@ export type SecureStorageOptions = { /** * When iOS lets the app read the session: one of SecureStore's constants, * such as `AFTER_FIRST_UNLOCK`. An app that refreshes in a background task - * before the device's first unlock needs `AFTER_FIRST_UNLOCK`. Passed to + * while the device is locked needs `AFTER_FIRST_UNLOCK`. Passed to * SecureStore unchanged. * * While the keychain can't be read, the session is `unavailable`, not @@ -120,9 +120,10 @@ const undecryptable = (error: unknown) => * encrypted with an Android Keystore key on Android. Pass it as * `createAuth`'s `storage` in Expo apps. * - * - Values over SecureStore's 2048-byte limit are split across keys. A write - * cut short, for example when the app is killed, keeps the previous value - * whole. + * - Values over 2048 bytes, which some iOS releases refuse to store, are + * split across keys. A write cut short, for example when the app is killed, + * keeps the previous value whole. A value over 128 KB fails to save, with + * `PERSISTENCE_FAILED`. * - Reads are synchronous, so with a synchronous user schema the session is * restored before the first render. Writes and removals are asynchronous. * - On iOS, a session left in the keychain by an earlier install is removed diff --git a/src/http/index.ts b/src/http/index.ts index a3712b4..1057d08 100644 --- a/src/http/index.ts +++ b/src/http/index.ts @@ -45,8 +45,9 @@ export type AuthFetchClient = Pick< */ export type AuthFetchOptions = { /** - * Your API's base URL. The access token goes only to requests on its - * origin. A path is resolved against it as a link is against a page's + * Your API's base URL. It must be absolute, such as + * `https://api.example.com/`. The access token goes only to requests on + * its origin. A path is resolved against it as a link is against a page's * address. End it with `/`, so that `"orders"` lands under it. */ baseUrl: string; @@ -62,7 +63,9 @@ export type AuthFetchOptions = { /** * Whether a second 401, after a successful refresh, signs the user out. * Set `false` when some endpoints answer 401 for reasons other than a - * rejected token, so they can't sign users out. + * rejected token, so a second 401 from them doesn't sign users out. + * Without a refresh token or a `refresh` option, the first 401 still does. + * * @default true */ signOutOnRepeated401?: boolean | undefined; @@ -114,9 +117,11 @@ async function discard(response: Response) { * the user is signed out, unless `signOutOnRepeated401` is off. * * Rejects with `UNAUTHENTICATED` when signed out, unless `optional` sends the - * request without a token, and with `LOCKED` while locked. If the session - * changes during a request, it rejects with `SESSION_CHANGED` rather than - * resolve a response meant for another account. + * request without a token, and with `LOCKED` while locked. When a refresh + * fails, it rejects with that failure, such as `REFRESH_FAILED`. + * + * If the session changes during a request, it rejects with `SESSION_CHANGED` + * rather than resolve a response meant for another account. * * The token never leaves your API. A request for another origin, with a * username or password in its URL, or with an invalid URL rejects with @@ -128,8 +133,8 @@ async function discard(response: Response) { * `Request` refuses, reject as `fetch` and `Request` do. * * An HTTP client that takes a custom `fetch`, such as ky or openapi-fetch, - * can take this one. Its requests are then sent, and sent again after a 401, - * as above. + * can take this one. Its requests then get the same checks, and the same + * handling of a 401. * * @example * ```ts diff --git a/src/next/index.ts b/src/next/index.ts index 1be417c..4ca36bf 100644 --- a/src/next/index.ts +++ b/src/next/index.ts @@ -333,7 +333,7 @@ export type NextSession = { * Server Functions and Route Handlers sign in and out through `writable()`. * `proxy.ts` refreshes with `refresh`, as rendering can't set cookies. * - * Throws `INVALID_OPTIONS` without `cookies` and `redirect`, when + * Throws `INVALID_OPTIONS` without `cookies` or `redirect`, when * `loginPath` doesn't start with `/`, or when `within` is negative. * * @example @@ -450,6 +450,8 @@ export type NextSessionRouteOptions = { * when `createServerAuth` has `clientCredentials`. Sign-in stays your own * Server Function. * + * Throws `INVALID_OPTIONS` without `cookies`. + * * @example * ```ts * import { sessionRoute } from "@monarcode/session-kit/next"; diff --git a/src/react-router/guards.ts b/src/react-router/guards.ts index 7541eff..8c29bfb 100644 --- a/src/react-router/guards.ts +++ b/src/react-router/guards.ts @@ -110,8 +110,8 @@ export type RequireSessionLoader = (args: { * * Other errors, such as `REFRESH_FAILED` after a failed refresh, are * rethrown to the route's error element, which can offer `auth.retry()`. - * A `loginPath` that doesn't start with `/`, or a bad `basename`, rejects - * with `INVALID_OPTIONS`. + * A `loginPath` or `basename` that doesn't start with `/` rejects with + * `INVALID_OPTIONS`. * * Use `SessionOutlet` as the route's element, and call * `useAuthRevalidation`, so the loader runs again when the session changes. @@ -146,7 +146,7 @@ export async function requireSession( * client's user, and works as {@link requireSession} does. * * Pass `loginPath` or `basename` when they aren't the defaults. A - * `loginPath` that doesn't start with `/`, or a bad `basename`, throws + * `loginPath` or `basename` that doesn't start with `/` throws * `INVALID_OPTIONS` when the loader is made. * * @example diff --git a/src/react-router/outlet.ts b/src/react-router/outlet.ts index 0081cdd..cc1e3a3 100644 --- a/src/react-router/outlet.ts +++ b/src/react-router/outlet.ts @@ -53,8 +53,8 @@ export type SessionOutletProps = { */ loginPath?: string | undefined; /** - * Shown while the saved session is read and, in data mode, until the - * loader has accepted a new session. + * Shown while the saved session is read and, in data or framework mode, + * until the loader has accepted a new session. */ pending?: ReactNode | undefined; /** @@ -95,7 +95,7 @@ function useGuardedSessionId(): string | undefined { * `?redirectTo=` set to where they were. In declarative mode, that makes it * the guard. * - * In data mode, use it as the element of a route whose loader returns + * In data or framework mode, render it from a route whose loader returns * `requireSession`'s result. When the account changes, it shows * `pending` until the loader has run again, so no child sees the last * account's data. @@ -105,6 +105,9 @@ function useGuardedSessionId(): string | undefined { * sidebar, isn't guarded this way. Read the user there from state, where it * may be `null`. * + * Throws `INVALID_OPTIONS` when it has neither an `AuthProvider` around it + * nor a `client`. + * * @example * ```tsx * import { Route, Routes } from "react-router"; diff --git a/src/react-router/revalidation.ts b/src/react-router/revalidation.ts index c5ab6f8..b7d106a 100644 --- a/src/react-router/revalidation.ts +++ b/src/react-router/revalidation.ts @@ -16,8 +16,10 @@ import { * refresh while the token is still valid. * * Call it once in the root layout, in data or framework mode. Declarative - * mode has no loaders. It watches `client`, or the nearest `AuthProvider`'s, - * and doesn't mount the client itself. + * mode has no loaders, and React Router throws when the hook runs there. + * + * It watches `client`, or the nearest `AuthProvider`'s, and doesn't mount + * the client itself. Throws `INVALID_OPTIONS` without either. * * @example * ```tsx diff --git a/src/react-router/server.ts b/src/react-router/server.ts index ad23d60..7b07fe0 100644 --- a/src/react-router/server.ts +++ b/src/react-router/server.ts @@ -214,8 +214,8 @@ export type RouterArgs = { request: Request; context: RouterContextLike; /** - * The URL without React Router's `.data` suffix, from React Router 8. - * React Router 7 removes the suffix from `request.url` instead. + * The URL without React Router's `.data` suffix, from React Router 7.15. + * Earlier versions remove the suffix from `request.url` instead. */ url?: URL | undefined; }; @@ -247,7 +247,8 @@ export type RouterMiddleware = ( /** The URL the request asked for, without React Router's `.data` suffix. */ function urlOf({ request, url }: RouterArgs): URL { if (url) return url; - // React Router 7 passes no `url`. `_routes` is only ever its own param. + // Before 7.15, React Router passes no `url`. `_routes` is only ever its + // own param. const fromRequest = new URL(request.url); fromRequest.searchParams.delete("_routes"); return fromRequest; @@ -270,7 +271,8 @@ function redirectTo(location: string): Response { * boundary. * * It sets `Cache-Control` to `private, no-store` on each response that - * doesn't set its own, unless you pass `cacheControl`. + * doesn't set its own. Pass `cacheControl` for another value, or `false` to + * leave every response as it is ({@link SessionMiddlewareOptions}). * * It's {@link cookieJarMiddleware} followed by the refresh, and needs React * Router 8, or 7.9 and later with `future.v8_middleware`. @@ -489,6 +491,8 @@ export type RouterLoader = (args: RouterArgs) => Promise; * * Throws `INVALID_OPTIONS` when a `loginPath` doesn't start with `/`. * + * It needs {@link sessionMiddleware} in the root route. + * * @example * ```ts * import type { ServerAuth } from "@monarcode/session-kit/server"; @@ -551,9 +555,9 @@ export type RouterSessionRoute = { * when `createServerAuth` has `clientCredentials`. Sign-in stays your own * action. * - * Export the loader and action one by one, as below. React Router's build - * can't remove a destructured `export const { loader }` from the browser's - * bundle, and fails. + * Export the loader and action one by one, as the example does. React + * Router's build can't remove a destructured `export const { loader }` from + * the browser's bundle, and fails. * * @example * ```ts diff --git a/src/react/hooks.ts b/src/react/hooks.ts index f8f6f1f..bedb130 100644 --- a/src/react/hooks.ts +++ b/src/react/hooks.ts @@ -39,13 +39,15 @@ export type AuthHooksOptions = { * Finds the client some other way than `AuthProvider`, such as from a * context of your own. It's called as a hook, inside every hook, on every * render. The hooks then need no `AuthProvider`, so mount the client - * another way. Default: reads the nearest `AuthProvider`. + * another way. Default: the client of the nearest `AuthProvider` from the + * same `createAuthHooks` call. */ useClient?: (() => Client) | undefined; }; /** - * Props for the `AuthProvider` that {@link createAuthHooks} returns. + * Props for {@link AuthProvider}, and for the one that + * {@link createAuthHooks} returns. * * @example * ```tsx @@ -208,8 +210,8 @@ export function createAuthHooks( * register in `Register`, from `@monarcode/session-kit`. * * Until you register one, it's any client, with what every client has: its - * state, `getSession`, `signOut`, `isCurrent` and `credentials`. Its user is - * then `unknown`. + * state, `mount`, `getSession`, `signOut`, `isCurrent` and `credentials`. + * Its user is then `unknown`. * * @example * ```ts @@ -278,6 +280,9 @@ export function AuthProvider( * when it changes. With a selector, it re-renders only when that part * changes. * + * The part is compared with `Object.is`. A selector that returns a new + * object or array each time re-renders on every change. + * * It reads the client of the nearest {@link AuthProvider}, typed by the * client you register in `Register`, from `@monarcode/session-kit`. * diff --git a/src/react/mirror.ts b/src/react/mirror.ts index 64615f0..2780d30 100644 --- a/src/react/mirror.ts +++ b/src/react/mirror.ts @@ -67,10 +67,7 @@ export interface UseMirrorAuthOptions> { * @example * ```tsx * import { createMirrorAuth, type Session } from "@monarcode/session-kit"; - * import { - * createAuthHooks, - * useMirrorAuth, - * } from "@monarcode/session-kit/react"; + * import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react"; * import { Outlet, useLoaderData, useRevalidator } from "react-router"; * * type User = { id: number; firstName: string }; @@ -85,7 +82,6 @@ export interface UseMirrorAuthOptions> { * revalidate: fetchSession, * signOut: postSignOut, * }); - * const { AuthProvider } = createAuthHooks>(); * * export default function App() { * const { session } = useLoaderData(); diff --git a/src/server/auth.ts b/src/server/auth.ts index d74cd06..94d520b 100644 --- a/src/server/auth.ts +++ b/src/server/auth.ts @@ -112,7 +112,7 @@ export type ServerAuthOptions = { * It's checked when a method first runs, not at creation, so build tools * that load your module without it, such as `next build`, still work. * Without a valid secret, every method rejects with `INVALID_OPTIONS`, and - * `forRequest`'s view reports `unavailable`. + * a request's `state` is `unavailable`. */ secret: string | readonly string[]; /** @@ -246,8 +246,9 @@ type RequestAuthBase = { * function or a loader. * * An expired access token is refreshed first, and a refresh token your - * backend rejects signs out. Where the request can't set cookies, the - * session is returned as the cookie holds it. + * backend rejects signs out. Rejects with `REFRESH_FAILED` when that + * refresh fails. Where the request can't set cookies, the session is + * returned as the cookie holds it. */ getSession: () => Promise | null>; /** @@ -257,8 +258,9 @@ type RequestAuthBase = { * read. Call it yourself only in middleware of your own. * * It refreshes at most once per request. A failed refresh is ignored while - * the access token still works. Rejects with `INVALID_OPTIONS` where the - * request can't set cookies. + * the access token still works. Once the token has expired, it rejects + * with `REFRESH_FAILED`. Rejects with `INVALID_OPTIONS` for a negative + * `within`, or where the request can't set cookies. */ refreshIfDue: (options?: RefreshIfDueOptions) => Promise | null>; /** @@ -276,7 +278,8 @@ type RequestAuthBase = { * * Rejects with `USER_VALIDATION_FAILED` for a user your schema rejects, * with `INVALID_SESSION` for tokens that already expired, and with - * `INVALID_OPTIONS` where the request can't set cookies. + * `PERSISTENCE_FAILED` for a session too large for the cookie. Rejects + * with `INVALID_OPTIONS` where the request can't set cookies. * * @example * ```ts @@ -389,9 +392,9 @@ type Members = Omit, typeof requestAuth> & { * Some requests can't set cookies: a Next.js page, or a React Router loader * once its response has left the middleware. There, nothing can be saved, so * `signIn`, `signOut`, `updateUser` and `refreshIfDue` reject with - * `INVALID_OPTIONS`, and an expired access token rejects with - * `REFRESH_FAILED`. Refresh first, in middleware or a proxy, with - * `refreshIfDue`. + * `INVALID_OPTIONS`. `getSession` still resolves, and `credentials.get` + * rejects with `REFRESH_FAILED` once the access token has expired. Refresh + * first, in middleware or a proxy, with `refreshIfDue`. * * @example * ```ts @@ -493,7 +496,8 @@ type ServerAuthBase = { * Your framework's adapter gives you one request's session * ({@link RequestAuth}), with every method and no cookie jar. Its methods * are here too, each taking the request's {@link CookieJar}, for a server - * without an adapter. `forRequest(jar)` gives that request's session. + * without an adapter. `forRequest(jar)` gives that request's session, which + * alone has `isCurrent` and `state`. * * `U` is the user, and `I` is the user `signIn` accepts, or `never` with * `fromAccessToken`. Write `typeof serverAuth` rather than spelling them out. diff --git a/src/server/handler.ts b/src/server/handler.ts index c582fcf..9ad5295 100644 --- a/src/server/handler.ts +++ b/src/server/handler.ts @@ -86,15 +86,20 @@ async function readAction(request: Request) { * * It answers only this site's own pages, by the `Sec-Fetch-Site` header, so * another site can't sign the user out or ask for a token. Browsers send it - * to https and localhost pages, since 2023 (Safari 16.4). On plain http, a - * `POST` needs an `Origin` header that matches the request's URL. Anything - * else is refused with 403. Every answer has `Cache-Control: no-store`. + * to https and localhost pages, since 2023 (Safari 16.4). Without it, as on + * plain http, a `GET` is answered, and a `POST` needs an `Origin` header + * that matches the request's URL. Anything else is refused with 403. Every + * answer has `Cache-Control: no-store`. * * The access token is served only when `createServerAuth` has * `clientCredentials`. A failure answers with its `AuthErrorCode`, which the * browser client rejects with. Anything that isn't an `AuthError` is thrown, * for your framework to log. * + * A failure's status is 400 for `INVALID_OPTIONS`, 401 for `UNAUTHENTICATED`, + * 409 for `SESSION_CHANGED` and 500 for any other code. A method other than + * `GET` or `POST` answers 405. + * * Each framework's `sessionRoute` wraps it in a route. Use it directly on a * server without an adapter, with the request's cookie jar. * diff --git a/src/tanstack-router/connect.ts b/src/tanstack-router/connect.ts index 923cedf..bc71af0 100644 --- a/src/tanstack-router/connect.ts +++ b/src/tanstack-router/connect.ts @@ -16,6 +16,9 @@ const connections = new WeakMap void>(); * guards such as `requireSession` again when the session changes. Call it * once, beside the Router. * + * When the session changes, it also clears the Router's cached and preloaded + * route data, so one account's data never shows for the next. + * * It returns a function that stops. Calling it again for the same Router * returns that same function. * diff --git a/src/tanstack-router/guards.ts b/src/tanstack-router/guards.ts index 2db9699..783e46e 100644 --- a/src/tanstack-router/guards.ts +++ b/src/tanstack-router/guards.ts @@ -51,6 +51,7 @@ export type RequireSessionOptions = { * * Other errors, such as `REFRESH_FAILED` after a failed refresh, are * rethrown to the route's error component, which can offer `auth.retry()`. + * A `loginPath` that doesn't start with `/` rejects with `INVALID_OPTIONS`. * * Render the route's children with `SessionOutlet`, and call `connectAuth`, * so the guard runs again when the session changes. diff --git a/src/tanstack-router/outlet.ts b/src/tanstack-router/outlet.ts index 5f0f9cb..37424f1 100644 --- a/src/tanstack-router/outlet.ts +++ b/src/tanstack-router/outlet.ts @@ -60,6 +60,9 @@ export type SessionOutletProps = { * UI the route renders around the outlet, such as a sidebar, isn't guarded * this way. Read the user there from state, where it may be `null`. * + * Throws `INVALID_OPTIONS` when neither an `AuthProvider` nor Router context + * has a client. + * * @example * ```tsx * import { From 7bc2b44bfbc87e38664d4d544052c4f98f97f0e5 Mon Sep 17 00:00:00 2001 From: monarcode Date: Sat, 14 Nov 2026 14:05:12 +0100 Subject: [PATCH 15/26] fix!: fix sign-out, guard and session-route edge cases - Revoke tokens on signOut() before restore, and drop INVALID_SESSION for an expired or outdated saved session - Reject bad loginPath, missing auth context and foreign Request objects with INVALID_OPTIONS, and answer 500 for setup errors in the session route - Add AuthRouter, and align example apps and docs with their guides --- CHANGELOG.md | 41 +++++++++++ examples/expo-router/src/auth.ts | 7 +- examples/next-app/proxy.ts | 6 +- examples/react-router-data/src/main.tsx | 8 +-- .../react-router-framework-spa/tsconfig.json | 3 +- .../app/routes/login.tsx | 13 ++-- .../react-router-framework-ssr/tsconfig.json | 3 +- examples/tanstack-router/src/router.tsx | 5 +- examples/tanstack-router/src/routes/login.tsx | 2 +- examples/tanstack-router/src/ui.tsx | 16 +++-- .../tanstack-start-spa-effetch/src/api.ts | 7 +- .../src/routes/__root.tsx | 4 +- .../src/routes/login.tsx | 2 +- .../tanstack-start-spa-effetch/src/ui.tsx | 16 +++-- .../tanstack-start-spa/src/routes/login.tsx | 2 +- examples/tanstack-start-spa/src/ui.tsx | 16 +++-- .../tanstack-start-ssr/src/routes/login.tsx | 2 +- .../docs/(latest)/reference/error-codes.mdx | 2 +- .../docs/(latest)/reference/react-router.mdx | 2 +- .../(latest)/reference/tanstack-router.mdx | 4 ++ .../server-rendering/server-sessions.mdx | 6 ++ site/content/docs/(latest)/setups/next.mdx | 4 +- .../docs/(latest)/setups/react-router-ssr.mdx | 11 ++- src/core/client.ts | 55 ++++++++++----- src/core/errors.ts | 2 +- src/core/persistence.ts | 27 ++++++-- src/core/return-to.ts | 6 +- src/core/types.ts | 7 +- src/http/index.ts | 12 +++- src/next/index.ts | 7 +- src/react-router/guards.ts | 20 ++++-- src/server/handler.ts | 30 +++++--- src/tanstack-router/connect.ts | 38 ++++++++++- src/tanstack-router/guards.ts | 5 +- src/tanstack-router/index.ts | 1 + tests/consumer.ts | 4 ++ tests/effect.test.ts | 9 ++- tests/expiry.test.ts | 18 +++++ tests/http.test.ts | 37 ++++++++++ tests/lock.test.ts | 68 +++++++++++++++---- tests/next.test.ts | 4 ++ tests/react-router-server.test.ts | 2 +- tests/react-router.test.ts | 8 +++ tests/return-to.test.ts | 3 + tests/router.test.ts | 15 ++++ tests/server.test.ts | 9 ++- tests/session.test.ts | 49 ++++++++++++- 47 files changed, 500 insertions(+), 118 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d763630..4cabdc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -137,9 +137,22 @@ - `deepLinkHandler(auth, options?)` in `@monarcode/session-kit/expo` makes `redirectSystemPath` for `app/+native-intent.tsx` (`DeepLinkHandler`). `rememberDeepLink` stays, for a `redirectSystemPath` that does more. +- `AuthRouter` in `@monarcode/session-kit/tanstack-router`, the Router type + `connectAuth` takes, for typing a function that takes your Router. ### Changed +- **Breaking:** the session route answers 500, not 400, for an + `INVALID_OPTIONS` that comes from the server's setup, such as a missing + secret, `clientCredentials` not turned on, or React Router's middleware + not added. A request it can't read still answers 400. +- A saved session past `maxAge`, or saved by another version, signs out + without an error, and `unlock()` resolves `null` for one. It set + `INVALID_SESSION` in `state.error`, which an app showing errors showed + after 30 idle days or an upgrade. A malformed saved session still does. +- The Server sessions page says how to read the secret on Cloudflare + Workers. + - **Breaking:** `createAuthFetch` takes the base URL as an option, as `sessionBearer` does. A missing `baseUrl` throws `INVALID_OPTIONS`. @@ -338,6 +351,34 @@ as its comment says, where it made a new key. The Effect guide's sign-in button awaits `auth.signIn`, where a failed sign-in went unhandled. +### Fixed + +- `signOut()` before the saved session is restored, such as with + asynchronous storage or before the first `mount()`, revokes the saved + tokens. It cleared them without revoking, so the refresh token stayed + valid at the backend. A locked session still isn't revoked. +- `safeReturnTo` matches a `loginPath` that has a query, such as + `"/login?tab=1"`, by its path. It returned the sign-in page as safe. +- `redirectIfSignedIn` (both routers) rejects a `loginPath` that doesn't start + with `/` for every visitor, and `redirectIfSignedInLoader` when the loader + is made. It failed only once someone signed in. +- `connectAuth` throws `INVALID_OPTIONS` when the Router's context has no + client as `auth`, and `nextSession` when called without options, where + each threw a `TypeError`. +- `authFetch` rejects a `Request` from another realm or a polyfill with + `INVALID_OPTIONS`. It was sent as the path `"[object Request]"` under + `baseUrl`. +- The docs say that React Router's loader guards can't keep a `#fragment`, + and that a Next.js Route Handler should answer 401 rather than call + `require` under a `basePath`. +- The example apps match their guides. React Router's data mode imports + `RouterProvider` from `react-router/dom`, and the framework apps generate + route types. The effetch app retries before `sessionBearer` and resets + per account. The TanStack apps read the user from the guarded route's + context and keep `disconnectAuth`. A failed sign-in in React Router with + server rendering returns status 400, in the example and the guide, so the + loaders don't run again. Stale comments are corrected. + ## 0.1.0-alpha.8 ### Added diff --git a/examples/expo-router/src/auth.ts b/examples/expo-router/src/auth.ts index da6a18d..aea131d 100644 --- a/examples/expo-router/src/auth.ts +++ b/examples/expo-router/src/auth.ts @@ -28,9 +28,10 @@ export const auth = createAuth({ name: "expo-example", user: userSchema, // The iOS keychain, or Keystore-encrypted storage on Android. Two JWTs and - // a user exceed SecureStore's 2048-byte value limit, so the value is split - // across keys. The defaults are `clearOnReinstall: true` and SecureStore's - // own `keychainAccessible` (`WHEN_UNLOCKED`). + // a user can pass 2048 bytes, which some iOS releases refuse to store in + // one value, so the value is split across keys. The defaults are + // `clearOnReinstall: true` and SecureStore's own `keychainAccessible` + // (`WHEN_UNLOCKED`). storage: secureStorage(), // Logs restores, refreshes, timers, and the gate's decisions to Metro in // development. Tokens and user fields stay out of the log. diff --git a/examples/next-app/proxy.ts b/examples/next-app/proxy.ts index 4378229..11d9465 100644 --- a/examples/next-app/proxy.ts +++ b/examples/next-app/proxy.ts @@ -3,9 +3,9 @@ import { NextResponse, type NextRequest } from "next/server"; import { session } from "./lib/auth/session"; /** - * Refreshes access that is about to expire before Server Components and - * Server Functions read it: they can't set cookies while rendering, but - * Proxy can, and Next passes the new cookie on to them. A failed refresh is + * Refreshes access that is about to expire before any page or Server + * Function reads it. Server Components can't set cookies while rendering, so + * Proxy sets the new one, and Next passes it on to them. A failed refresh is * left for the page, which then reads the session as it was. */ export function proxy(request: NextRequest) { diff --git a/examples/react-router-data/src/main.tsx b/examples/react-router-data/src/main.tsx index 2f8e48b..0a2f53a 100644 --- a/examples/react-router-data/src/main.tsx +++ b/examples/react-router-data/src/main.tsx @@ -1,10 +1,5 @@ import { StrictMode } from "react"; -import { - createBrowserRouter, - Outlet, - RouterProvider, - useRouteError, -} from "react-router"; +import { createBrowserRouter, Outlet, useRouteError } from "react-router"; import { AuthProvider } from "@monarcode/session-kit/react"; import { @@ -14,6 +9,7 @@ import { useAuthRevalidation, } from "@monarcode/session-kit/react-router"; import { createRoot } from "react-dom/client"; +import { RouterProvider } from "react-router/dom"; import { auth } from "./auth"; import { LoginForm, Pending, Profile, Unavailable } from "./ui"; diff --git a/examples/react-router-framework-spa/tsconfig.json b/examples/react-router-framework-spa/tsconfig.json index a10bd69..2a32730 100644 --- a/examples/react-router-framework-spa/tsconfig.json +++ b/examples/react-router-framework-spa/tsconfig.json @@ -9,7 +9,8 @@ "skipLibCheck": true, "noEmit": true, "isolatedModules": true, + "rootDirs": [".", "./.react-router/types"], "types": ["vite/client"] }, - "include": ["app", "*.ts"] + "include": ["app", "*.ts", ".react-router/types/**/*"] } diff --git a/examples/react-router-framework-ssr/app/routes/login.tsx b/examples/react-router-framework-ssr/app/routes/login.tsx index bd7d11f..d1fb1a8 100644 --- a/examples/react-router-framework-ssr/app/routes/login.tsx +++ b/examples/react-router-framework-ssr/app/routes/login.tsx @@ -1,4 +1,5 @@ import { + data, redirect, useActionData, useNavigation, @@ -18,7 +19,8 @@ export const loader = redirectIfSignedIn(serverAuth); /** * Signs in with DummyJSON on the server and sets the cookie. React Router * checks that the form came from this site. A failure is returned for the - * form to show. + * form to show, with status 400, so React Router skips running the loaders + * again. */ export async function action({ request, context, url }: ActionFunctionArgs) { const form = await request.formData(); @@ -30,9 +32,12 @@ export async function action({ request, context, url }: ActionFunctionArgs) { ), ); } catch (error) { - return { - error: error instanceof Error ? error.message : "Could not sign in", - }; + return data( + { + error: error instanceof Error ? error.message : "Could not sign in", + }, + { status: 400 }, + ); } throw redirect(safeReturnTo(url.searchParams.get("redirectTo"))); } diff --git a/examples/react-router-framework-ssr/tsconfig.json b/examples/react-router-framework-ssr/tsconfig.json index 5af911a..a125136 100644 --- a/examples/react-router-framework-ssr/tsconfig.json +++ b/examples/react-router-framework-ssr/tsconfig.json @@ -9,7 +9,8 @@ "skipLibCheck": true, "noEmit": true, "isolatedModules": true, + "rootDirs": [".", "./.react-router/types"], "types": ["vite/client", "node"] }, - "include": ["app", "*.ts"] + "include": ["app", "*.ts", ".react-router/types/**/*"] } diff --git a/examples/tanstack-router/src/router.tsx b/examples/tanstack-router/src/router.tsx index 2465c7f..bc704ba 100644 --- a/examples/tanstack-router/src/router.tsx +++ b/examples/tanstack-router/src/router.tsx @@ -11,8 +11,9 @@ export const router = createRouter({ defaultPendingComponent: Pending, }); -// Restores the session, runs expiry timers and tab sync, and re-runs guards. -connectAuth(router); +// Restores the session, runs expiry timers and tab sync, and re-runs guards +// when auth changes. Call it once, beside the Router. +export const disconnectAuth = connectAuth(router); declare module "@tanstack/react-router" { interface Register { diff --git a/examples/tanstack-router/src/routes/login.tsx b/examples/tanstack-router/src/routes/login.tsx index 3553fd4..2806f36 100644 --- a/examples/tanstack-router/src/routes/login.tsx +++ b/examples/tanstack-router/src/routes/login.tsx @@ -8,7 +8,7 @@ export const Route = createFileRoute("/login")({ validateSearch: (search: Record) => ({ redirectTo: safeReturnTo(search.redirectTo), }), - // Runs again after a sign-in, as connectAuth runs the guards again. + // Runs again after a sign-in, which runs the guards again. beforeLoad: ({ context, search }) => redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }), component: LoginForm, diff --git a/examples/tanstack-router/src/ui.tsx b/examples/tanstack-router/src/ui.tsx index fccf796..6d8c893 100644 --- a/examples/tanstack-router/src/ui.tsx +++ b/examples/tanstack-router/src/ui.tsx @@ -1,6 +1,7 @@ import { useState, type FormEvent } from "react"; -import { useAuth, useAuthClient } from "@monarcode/session-kit/tanstack-router"; +import { useAuthClient } from "@monarcode/session-kit/tanstack-router"; +import { getRouteApi } from "@tanstack/react-router"; import { authFetch, signInWithPassword } from "./auth"; @@ -65,9 +66,14 @@ const emailOf = (value: unknown) => ? String(value.email) : ""; -/** The signed-in user, a request using the access token, and sign-out. */ +const authenticated = getRouteApi("/_authenticated"); + +/** + * The signed-in user, a request using the access token, and sign-out. It + * renders under the guarded layout, whose route context holds the session. + */ export function Profile() { - const user = useAuth((state) => state.user); + const { user } = authenticated.useRouteContext().session; const auth = useAuthClient(); const [fromApi, setFromApi] = useState(""); @@ -82,8 +88,8 @@ export function Profile() { return (
-

Welcome, {user?.firstName}

-

Signed in as {user?.username}

+

Welcome, {user.firstName}

+

Signed in as {user.username}

{showEmail && } - ); - default: - // Signed in: "authenticated", or "refreshing" with the user on screen. - return ( -
-

Welcome, {user.firstName}

- -
- ); + if (session.status === "initializing") return

Restoring your session…

; + if (session.status === "unauthenticated") return ; + if (session.status === "unavailable") { + // The session couldn't be restored or refreshed, say while offline. + return ( + + ); } + return ( +
+

Welcome, {session.user.name}

+ +
+ ); } ``` -[Getting started](https://session-kit.pages.dev/docs/getting-started) builds this into a working app -one step at a time, against a real test backend. +To call your API, `createAuthFetch` from `@monarcode/session-kit/http` adds +the access token to each request and refreshes it after a 401. +[Getting started](https://session-kit.pages.dev/docs/getting-started) builds +this app step by step against a real test backend, and the guides below add +your router's guards or server rendering. ## Pick your setup diff --git a/scripts/docs-pages.mjs b/scripts/docs-pages.mjs index 6ef7e25..3a5291d 100644 --- a/scripts/docs-pages.mjs +++ b/scripts/docs-pages.mjs @@ -194,6 +194,16 @@ const clientPage = (slug) => ({ * `requires` skips a page when an installed package is older than it needs. */ export const documents = [ + { + // The README's quick start: a small app of its own, not an excerpt. + path: "README.md", + resolutions: ["NodeNext", "Bundler"], + dom: true, + fixtures: { + "src/sign-in-form.tsx": + "export function SignInForm() { return null; }", + }, + }, { path: page("getting-started"), resolutions: ["NodeNext", "Bundler"], From 56bb1289650e38668077cbc0b33aab68d67e2a6b Mon Sep 17 00:00:00 2001 From: monarcode Date: Sun, 15 Nov 2026 07:02:17 +0100 Subject: [PATCH 26/26] docs(readme): show the tree-shaken bundle size and a types badge --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5923a02..f281f1b 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ [![npm](https://img.shields.io/npm/v/@monarcode/session-kit)](https://www.npmjs.com/package/@monarcode/session-kit) [![CI](https://github.com/monarcode/session-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/monarcode/session-kit/actions/workflows/ci.yml) -[![bundle size](https://deno.bundlejs.com/badge?q=@monarcode/session-kit)](https://bundlejs.com/?q=@monarcode/session-kit) -[![tree-shakeable](https://img.shields.io/badge/tree--shakeable-yes-brightgreen)](https://bundlejs.com/?q=@monarcode/session-kit&treeshake=%5B%7BcreateAuth%2CwebStorage%7D%5D) +[![bundle size](https://deno.bundlejs.com/badge?q=@monarcode/session-kit&treeshake=%5B%7BcreateAuth%2CwebStorage%7D%5D)](https://bundlejs.com/?q=@monarcode/session-kit&treeshake=%5B%7BcreateAuth%2CwebStorage%7D%5D) +[![types](https://img.shields.io/npm/types/@monarcode/session-kit)](https://www.npmjs.com/package/@monarcode/session-kit) [![provenance](https://img.shields.io/badge/provenance-verified-brightgreen?logo=npm)](https://www.npmjs.com/package/@monarcode/session-kit#provenance) [![license](https://img.shields.io/npm/l/@monarcode/session-kit)](./LICENSE)