diff --git a/AGENTS.md b/AGENTS.md index ddccf75..0deea37 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -169,7 +169,11 @@ developers, not for us. Every comment ships: keep it short, plain and true. the JSDoc examples, in memory. Each page is listed in `documents` in `scripts/docs-pages.mjs`, which the site also reads for type hovers, and a page that builds on Getting started lists the files it uses as `shared`. - A new page with titled examples fails the check until it's listed. + A new page with titled examples fails the check until it's listed, and a + listed page without any fails too. Blocks with `app="name"` compile as + their own app, with the page's other files: use it for a second version of + a file, such as `src/main.tsx` for another mode, or for a file that can't + share the page's main app. - The README's quick start is its own small app: each block marked `` is a file, compiled together like a page's (`README.md` in `documents`). A README example marked diff --git a/CHANGELOG.md b/CHANGELOG.md index 4914875..7badbb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,53 @@ # Changelog +## 0.1.0-rc.3 + +Fixes for Expo SDK 53 to 57 and for redirects on React Native, and a +rewritten docs site. Session kit's API is unchanged. + +### Fixed + +- **Expo SDK 53 to 57:** signing in, refreshing, revoking and `updateUser` + failed on React Native 0.79 to 0.86. Their `AbortController` has no + `throwIfAborted` or `reason`, which the client relied on. It now keeps + the abort reason itself, so a sign-in cut short by a newer one still + rejects with `SESSION_CHANGED`. Expo SDK 58 wasn't affected. +- **`createAuthFetch` on React Native:** redirects are refused there too. + The redirect mode is now passed in `init`, which Expo's `fetch` reads. + Before Expo SDK 58, `fetch` follows redirects anyway, so a response from + another origin or path rejects with a `TypeError`, as a refused redirect + does in browsers. The redirected request has already gone out by then. +- **`createAuthFetch` keeps a `Request`'s `referrerPolicy` and + `referrer`.** Copying the request to add the token reset them. + +### Docs + +- The JSDoc names more of the cases behind each error code: what + `REFRESH_FAILED`, `INVALID_SESSION`, `USER_VALIDATION_FAILED`, + `SESSION_CHANGED`, `PERSISTENCE_FAILED` and `INVALID_OPTIONS` cover, and + what `credentials.renew` and `updateUser` reject with. +- `keychainAccessible` no longer says a locked iOS keychain never signs the + user out: a refresh that can't save its tokens does. +- `sessionBearer` says that `fetch` follows redirects on React Native before + Expo SDK 58. +- The API reference shows each export's whole description and its `@see` + links, and lists the members of the client and server types with their + descriptions, which say what each method rejects with. +- `sessionBearer` says that a 401 it doesn't send again fails the call as + an `HttpError`, and `updateUser` that an `AuthError` its function throws + keeps its own code. +- The docs site is rewritten. Every page was checked against the source, + and every code sample on it compiles, the setup guides' config files + included. The sidebar is grouped into Get started, Setups, Guides, Going + further and Reference. Effect has three pages (`/docs/effect`, + `/docs/effect/browser` and `/docs/effect/server`), and Expo has an + "Unlock with biometrics" guide + (`/docs/setups/expo-locking`). Every old page URL still works. Some + section anchors changed, such as the old `/docs/effect` steps; no link in + the docs, the README or the examples points at one. +- Compatibility states the TypeScript floor (5.4, and 5.9 for Effect), the + framework's own Node.js and React floors, and which runtimes CI tests. + ## 0.1.0-rc.2 For effetch `0.1.0-rc.4`, whose main entry now exports only the `Fetch` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 413cf4f..e21536f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,7 +21,9 @@ example: resolution, the server-rendering guides under Bundler resolution, and the Expo guide under Bundler resolution without DOM types, as Metro resolves. `scripts/docs-pages.mjs` lists each page, for `scripts/check-docs.mjs` - and for the site's type hovers. + and for the site's type hovers. Blocks with `app="name"` compile as their + own app, with the page's other files, such as a second version of a file + for another mode. - **The reference.** The API reference pages are generated from the JSDoc by `pnpm run docs:reference`, and the check fails when they're out of date. Run it after changing a public export or its JSDoc. diff --git a/README.md b/README.md index f281f1b..4a49e2c 100644 --- a/README.md +++ b/README.md @@ -35,13 +35,16 @@ server with TanStack Start, Next.js, and React Router, and comes with an ## Installation +Install the package and a schema library: + ```sh npm install @monarcode/session-kit zod ``` Any [Standard Schema](https://standardschema.dev) library describes users. The examples use Zod. Peer dependencies such as React and your router are -optional: install the ones your setup uses. +optional: install the ones your setup uses. Session kit needs TypeScript 5.4 +or newer (Effect asks for 5.9), and [Compatibility](https://session-kit.pages.dev/docs/reference/compatibility) lists the supported versions. @@ -52,7 +55,7 @@ and read the [release notes](./CHANGELOG.md) before upgrading. Your backend keeps its sign-in and refresh endpoints. Session kit takes the tokens they return and manages the session from there. A React app needs -three files. +three files, plus your own sign-in form. **1. Create the client.** It checks every user against your schema, saves the session, and calls your `refresh` before the access token expires: @@ -163,25 +166,14 @@ function Home() { 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 +this app step by step against a real test backend, and the setup guides add your router's guards or server rendering. ## Pick your setup -Each setup has a guide: - -| Setup | Guide | -| -------------------------------------------------------------- | ----------------------------------------------------------------------------------- | -| React without a router | [Getting started](https://session-kit.pages.dev/docs/getting-started) | -| TanStack Router, and TanStack Start as a single-page app (SPA) | [TanStack Router](https://session-kit.pages.dev/docs/setups/tanstack-router) | -| TanStack Start with server rendering | [TanStack Start](https://session-kit.pages.dev/docs/setups/tanstack-start) | -| React Router: declarative, data, framework SPA | [React Router](https://session-kit.pages.dev/docs/setups/react-router) | -| React Router, framework mode with server rendering | [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 setup | [Effect and effetch](https://session-kit.pages.dev/docs/effect) | - -All but the first have a runnable app in [`examples/`](./examples). +Each setup, from plain React to Next.js, Expo Router and Effect, has a guide: +see [Pick your setup](https://session-kit.pages.dev/docs/installation#pick-your-setup). +Every setup but plain React has a runnable app in [`examples/`](./examples). ## Contributing diff --git a/package.json b/package.json index 94c8666..7a5d58e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@monarcode/session-kit", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "description": "Schema-driven, type-safe sessions for React, with TanStack Router, React Router, Expo Router, Next.js, TanStack Start, and Effect support", "keywords": [ "auth", diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjs index 3e1ba02..caeb18a 100644 --- a/scripts/check-docs.mjs +++ b/scripts/check-docs.mjs @@ -9,7 +9,7 @@ import { installedAtLeast, markedExamples, PAGES, - pageApp, + pageApps, root, } from "./docs-pages.mjs"; import { renderReference } from "./reference-docs.mjs"; @@ -95,7 +95,9 @@ checkPagesListed(); checkLinks(); if (problems.length > 0) { - console.error(problems.map((problem) => `✗ ${problem}`).join("\n")); + // A page's main files compile again in each of its named apps. + const unique = [...new Set(problems)]; + console.error(unique.map((problem) => `✗ ${problem}`).join("\n")); process.exit(1); } console.log( @@ -370,6 +372,7 @@ function checkDocument({ fixtures, shared, requires = {}, + appRequires = {}, }) { const missing = Object.entries(requires).find( ([name, minimum]) => !installedAtLeast(name, minimum), @@ -381,9 +384,22 @@ function checkDocument({ return false; } const report = (message) => problems.push(message); - const files = pageApp({ path, dom, fixtures, shared }, report); - if (files.length === 0) return true; - compileExamples(path, files, resolutions, { together: true }); + const apps = pageApps({ path, dom, fixtures, shared }, report); + for (const [name, files] of apps) { + const needs = Object.entries(appRequires[name] ?? {}).find( + ([dependency, minimum]) => !installedAtLeast(dependency, minimum), + ); + if (needs) { + console.log( + `- ${path} app "${name}" skipped: it needs ${needs[0]} ${needs[1]} or later`, + ); + continue; + } + if (files.length > 0) + compileExamples(name ? `${path}#${name}` : path, files, resolutions, { + together: true, + }); + } return true; } @@ -395,6 +411,9 @@ function checkDocument({ */ function compileExamples(label, files, resolutions, { together = false } = {}) { const directory = join(scratch, label.replace(/[^\w]+/g, "-")); + // A page's named app is labelled `path#name`. + const app = label.includes("#") ? label.slice(label.indexOf("#") + 1) : ""; + const where = app ? `, app "${app}"` : ""; const virtual = new Map( files.map((file) => [join(directory, file.path), file]), ); @@ -439,7 +458,7 @@ function compileExamples(label, files, resolutions, { together = false } = {}) { diagnostic.start ?? 0, ); problems.push( - `${relative(root, file.origin)}:${file.line + line} (${file.path}, ${resolution}): TS${diagnostic.code} ${message}`, + `${relative(root, file.origin)}:${file.line + line} (${file.path}${where}, ${resolution}): TS${diagnostic.code} ${message}`, ); } } diff --git a/scripts/docs-pages.d.mts b/scripts/docs-pages.d.mts index 766031b..4f5a472 100644 --- a/scripts/docs-pages.d.mts +++ b/scripts/docs-pages.d.mts @@ -6,6 +6,7 @@ export interface PageFile { origin: string; line: number; path: string; + app?: string | undefined; dom: boolean; code: string; fixture?: boolean | undefined; @@ -21,12 +22,14 @@ export interface PageDocument { | { from: string; files: string[]; directories?: string[] | undefined } | undefined; requires?: Record | undefined; + appRequires?: Record> | undefined; } export const root: string; export const PAGES: string; export const MARKERS: { md: RegExp; mdx: RegExp }; export const TITLE: RegExp; +export const APP: RegExp; export const documents: PageDocument[]; export function markedExamples(path: string, dom: boolean): PageFile[]; @@ -35,6 +38,10 @@ export function pageApp( document: Pick, report: (message: string) => void, ): PageFile[]; +export function pageApps( + document: Pick, + report: (message: string) => void, +): Map; export function compilerSettings( resolution: "NodeNext" | "Bundler", dom: boolean, diff --git a/scripts/docs-pages.mjs b/scripts/docs-pages.mjs index 3a5291d..6e1cdc7 100644 --- a/scripts/docs-pages.mjs +++ b/scripts/docs-pages.mjs @@ -63,8 +63,8 @@ declare module "@tanstack/react-router" { `; /** - * The parts of `@noble/ciphers` and `expo-crypto` the Expo guide's locking - * example uses. They are the app's dependencies, not session-kit's. + * The parts of `@noble/ciphers` and `expo-crypto` the Unlock with biometrics + * page uses. They are the app's dependencies, not session-kit's. */ const LOCKING_DEPS = ` declare module "@noble/ciphers/aes.js" { @@ -129,6 +129,125 @@ declare module "@tanstack/react-router" { } `; +/** + * The Start guide's own routes: `START_ROUTE_TREE`, plus its sign-in route. + * The Hybrid page keeps `START_ROUTE_TREE`, as it has no sign-in route. + */ +const START_GUIDE_ROUTE_TREE = ` +import { Route as rootRoute } from "./routes/__root"; +import { Route as loginRouteImport } from "./routes/login"; +import { Route as authenticatedRouteImport } from "./routes/_authenticated"; +import { Route as apiSessionRouteImport } from "./routes/api/session"; + +const loginRoute = loginRouteImport.update({ + id: "/login", + path: "/login", + getParentRoute: () => rootRoute, +} as any); +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([ + loginRoute, + authenticatedRoute, + apiSessionRoute, +]); + +declare module "@tanstack/react-router" { + interface FileRoutesByPath { + "/login": { + id: "/login"; + path: "/login"; + fullPath: "/login"; + preLoaderRoute: typeof loginRouteImport; + parentRoute: typeof rootRoute; + }; + "/_authenticated": { + id: "/_authenticated"; + path: ""; + fullPath: "/"; + preLoaderRoute: typeof authenticatedRouteImport; + parentRoute: typeof rootRoute; + }; + "/api/session": { + id: "/api/session"; + path: "/api/session"; + fullPath: "/api/session"; + preLoaderRoute: typeof apiSessionRouteImport; + parentRoute: typeof rootRoute; + }; + } +} +`; + +/** + * The parts of Vite and its plugins the TanStack Router guide's + * `vite.config.ts` uses. They are the app's dev dependencies, not + * session-kit's. Start's own plugin is installed, and reads `vite` from here. + */ +const SPA_VITE_DEPS = ` +declare module "vite" { + export interface Plugin { + name: string; + } + export type PluginOption = Plugin | PluginOption[] | false | null | undefined; + export interface UserConfig { + plugins?: PluginOption[]; + } + export function defineConfig(config: UserConfig): UserConfig; +} +declare module "@vitejs/plugin-react" { + import type { Plugin } from "vite"; + export default function react(): Plugin[]; +} +declare module "@tanstack/router-plugin/vite" { + export function tanstackRouter(options?: { + target?: "react" | "solid" | "vue"; + autoCodeSplitting?: boolean; + }): import("vite").Plugin; +} +`; + +/** + * The parts of `@react-router/dev` the React Router guide's framework-mode + * config uses. It's the app's dev dependency, not session-kit's. + */ +const SPA_REACT_ROUTER_DEV = ` +declare module "@react-router/dev/config" { + export interface Config { + ssr?: boolean; + basename?: string; + } +} +declare module "@react-router/dev/routes" { + export interface RouteConfigEntry { + id?: string; + path?: string; + index?: boolean; + file: string; + children?: RouteConfigEntry[]; + } + export type RouteConfig = RouteConfigEntry[] | Promise; + export function index(file: string): RouteConfigEntry; + export function layout( + file: string, + children?: RouteConfigEntry[], + ): RouteConfigEntry; + export function route( + path: string | null | undefined, + file: string, + children?: RouteConfigEntry[], + ): RouteConfigEntry; +} +`; + /** The part of Node's types the server guides' code uses. */ const SERVER_ENV = ` declare const process: { env: Record }; @@ -158,6 +277,15 @@ export const MARKERS = { /** An example's path in a fence's meta, as `MARKERS.mdx` reads it. */ export const TITLE = new RegExp(`(?:^|\\s)title="(${PATH})"`); +/** + * The app an example belongs to, in a fence's meta: `app="data"`. A page's + * examples without one form its main app. Each named app is compiled + * separately, from the main app's files and its own, which replace any of + * the same path. It lets a page show two versions of one file, such as a + * `src/main.tsx` for each of React Router's modes. + */ +export const APP = /(?:^|\s)app="([\w-]+)"/; + /** Where the site's pages for the current release line live. */ export const PAGES = "site/content/docs/(latest)"; @@ -191,7 +319,8 @@ const clientPage = (slug) => ({ * `fixtures` standing in for generated files and the app's other * dependencies. A page that builds on another page's app names the files it * uses as `shared`; its own file replaces a shared one of the same path. - * `requires` skips a page when an installed package is older than it needs. + * `requires` skips a page when an installed package is older than it needs, + * and `appRequires` skips one of its named apps. */ export const documents = [ { @@ -210,21 +339,32 @@ export const documents = [ dom: true, fixtures: {}, }, + { + path: page("security"), + resolutions: ["NodeNext", "Bundler"], + dom: true, + fixtures: {}, + }, { path: page("setups/tanstack-router"), resolutions: ["NodeNext", "Bundler"], dom: true, - fixtures: { "src/routeTree.gen.ts": ROUTE_TREE }, + fixtures: { + "src/routeTree.gen.ts": ROUTE_TREE, + "src/vite-deps.d.ts": SPA_VITE_DEPS, + }, shared: { from: page("getting-started"), files: ["src/backend.ts", "src/auth.ts", "src/sign-in.tsx"], }, + // Start in SPA mode needs the router Start itself depends on. + appRequires: { start: { "@tanstack/react-router": "1.170" } }, }, { path: page("setups/react-router"), resolutions: ["NodeNext", "Bundler"], dom: true, - fixtures: {}, + fixtures: { "app/react-router-dev.d.ts": SPA_REACT_ROUTER_DEV }, shared: { from: page("getting-started"), files: [ @@ -243,7 +383,22 @@ export const documents = [ resolutions: ["Bundler"], // No DOM, so browser-only code fails as it would on a device. dom: false, + fixtures: {}, + }, + { + path: page("setups/expo-locking"), + resolutions: ["Bundler"], + dom: false, fixtures: { "src/locking-deps.d.ts": LOCKING_DEPS }, + // It adds locking to the Expo guide's app. + shared: { + from: page("setups/expo"), + files: [ + "app/+native-intent.tsx", + "app/login.tsx", + "app/(app)/profile.tsx", + ], + }, }, { path: page("setups/tanstack-start"), @@ -253,7 +408,7 @@ export const documents = [ requires: { "@tanstack/react-router": "1.170" }, dom: true, fixtures: { - "src/routeTree.gen.ts": START_ROUTE_TREE, + "src/routeTree.gen.ts": START_GUIDE_ROUTE_TREE, "src/env.d.ts": SERVER_ENV, }, }, @@ -277,13 +432,26 @@ export const documents = [ // The guide's code is React Router 8's, with the `url` argument. requires: { "react-router": "8.0" }, dom: true, - fixtures: { "app/env.d.ts": SERVER_ENV }, + fixtures: { + "app/env.d.ts": SERVER_ENV, + "app/react-router-dev.d.ts": SPA_REACT_ROUTER_DEV, + }, }, { path: page("server-rendering/server-sessions"), resolutions: ["NodeNext", "Bundler"], dom: true, - fixtures: { "src/env.d.ts": SERVER_ENV }, + fixtures: { + "src/env.d.ts": SERVER_ENV, + // The app's own server render, for servers without an adapter. + "src/server/render.ts": ` +import type { Session } from "@monarcode/session-kit"; + +export declare function renderPage( + session: Session<{ id: number; firstName: string }> | null, +): Promise; +`, + }, }, { path: page("server-rendering/hybrid"), @@ -304,15 +472,37 @@ export const documents = [ "src/router.tsx", "src/routes/__root.tsx", "src/routes/_authenticated.tsx", + // The guide's Call your API code must compile with hybrid's server.ts. + "src/auth/auth-fetch.ts", ], }, }, { - path: page("effect"), + path: page("effect/browser"), resolutions: ["NodeNext", "Bundler"], dom: true, fixtures: {}, }, + { + path: page("effect/server"), + resolutions: ["NodeNext", "Bundler"], + dom: true, + fixtures: {}, + shared: { + from: page("effect/browser"), + // The server's files, and the client and query cache it registers. + files: [ + "src/backend.ts", + "src/refresh.ts", + "src/api.ts", + "src/user.ts", + "src/auth.ts", + "src/layer.ts", + "src/runtime.ts", + "src/query.ts", + ], + }, + }, clientPage("client/state"), clientPage("client/sessions"), clientPage("client/signing-in-and-out"), @@ -321,6 +511,8 @@ export const documents = [ clientPage("client/other-http-clients"), clientPage("client/users-from-tokens"), clientPage("client/locking"), + clientPage("configuration/user-schemas"), + clientPage("configuration/refresh"), clientPage("configuration/expiry"), clientPage("configuration/storage"), clientPage("configuration/errors"), @@ -339,10 +531,12 @@ export function markedExamples(path, dom) { const files = []; for (const match of text.matchAll(MARKERS[markerOf(path)])) { const fenceStart = match.index + match[0].indexOf("```"); + const fence = match[0].slice(match[0].indexOf("```")).split("\n")[0]; files.push({ origin: join(root, path), line: text.slice(0, fenceStart).split("\n").length + 1, path: match[1], + app: APP.exec(fence)?.[1], dom, code: match[2], }); @@ -362,7 +556,10 @@ function markerOf(path) { function sharedExamples(path, { from, files, directories }, dom, report) { const theirs = markedExamples(from, dom); return files.flatMap((name) => { - const file = theirs.find((candidate) => candidate.path === name); + // The page's main version, not a named app's version of the file. + const file = theirs.find( + (candidate) => candidate.path === name && candidate.app === undefined, + ); if (!file) { report(`${path}: ${from} has no example named ${name}`); return []; @@ -423,19 +620,41 @@ export function pageApp({ path, dom, fixtures, shared }, report) { }); const names = new Set(); for (const file of files) { - if (names.has(file.path)) + const key = `${file.app ?? ""}:${file.path}`; + if (names.has(key)) report(`${path}: two examples are named ${file.path}`); - names.add(file.path); + names.add(key); } if (shared) files.push( - ...sharedExamples(path, shared, dom, report).filter( - (file) => !names.has(file.path), - ), + ...sharedExamples(path, shared, dom, report) + .filter((file) => !names.has(`:${file.path}`)) + .map((file) => ({ ...file, app: undefined })), ); return files; } +/** + * A document's apps, by name: the main app (`""`), and one for each `app` + * an example names, made of the main app's files and its own, which replace + * any of the same path. A page that names none has only the main app. + */ +export function pageApps(document, report) { + const files = pageApp(document, report); + const main = files.filter((file) => file.app === undefined); + const apps = new Map([["", main]]); + for (const name of new Set(files.map((file) => file.app))) + if (name !== undefined) { + const own = files.filter((file) => file.app === name); + const paths = new Set(own.map((file) => file.path)); + apps.set(name, [ + ...main.filter((file) => !paths.has(file.path)), + ...own, + ]); + } + return apps; +} + /** * The compiler options examples compile with, in `tsconfig.json` form, under * `NodeNext` or `Bundler` resolution, with or without DOM types. diff --git a/scripts/reference-docs.mjs b/scripts/reference-docs.mjs index aa80785..58b66b5 100644 --- a/scripts/reference-docs.mjs +++ b/scripts/reference-docs.mjs @@ -1,5 +1,5 @@ // Writes the site's API reference from the JSDoc: a page per entry point, -// listing each export with its summary, and the error codes page. +// listing each export with its description, and the error codes page. // // pnpm run docs:reference // @@ -66,13 +66,13 @@ const PAGES = { "./tanstack-start": [ "tanstack-start", "TanStack Start", - "Server sessions and hydration for TanStack Start.", + "The browser's side of TanStack Start with server rendering: connecting the Router and loading the session.", ["TanStack Start", "/docs/setups/tanstack-start"], ], "./tanstack-start/server": [ "tanstack-start-server", "TanStack Start server", - "TanStack Start's server-side cookie access.", + "The server's side of TanStack Start: the request's session, the refresh middleware and the session route.", ["TanStack Start", "/docs/setups/tanstack-start"], ], "./next": [ @@ -109,6 +109,23 @@ const GROUPS = ["Functions", "Components", "Classes", "Values", "Types"]; */ const BUILT_BY_APPS = new Set(["AuthStorage", "CookieJar", "Tokens"]); +/** + * Types an app calls methods on, so their entry lists each member with its + * own description, which says what it rejects with. Type tables can't: they + * drop members behind a conditional type, such as `updateUser`. + */ +const CALLED_BY_APPS = new Set([ + "AuthClient", + "AuthLocking", + "Credentials", + "MirrorAuth", + "NextSession", + "RequestAuth", + "ServerAuth", + "Session", + "SessionGuard", +]); + /** * The reference pages, by path from the repository root. `program` covers * each entry point's source file; one is created when it's left out. @@ -141,6 +158,9 @@ export function renderReference(program = createProgram()) { table: /(Options|Props)$/.test(exported.name) || BUILT_BY_APPS.has(exported.name), + members: CALLED_BY_APPS.has(exported.name) + ? membersOf(checker, declaration, names) + : [], }); } const importPath = @@ -151,17 +171,16 @@ title: ${JSON.stringify(title)} description: ${JSON.stringify(description)} --- -\`\`\`ts -import { … } from "${importPath}"; -\`\`\` - -Guide: [${guide}](${guideUrl}). +Import these from \`${importPath}\`. To set it up, see +[${guide}](${guideUrl}). `; for (const [group, items] of groups) { if (items.length === 0) continue; body += `\n## ${group}\n`; for (const item of items) { body += `\n### ${item.name}\n\n${item.summary}\n`; + if (item.members.length > 0) + body += `\nMembers:\n\n${item.members.join("\n")}\n`; if (item.table) body += `\n\n`; } @@ -185,7 +204,8 @@ description: Every AuthErrorCode, what it means and when you'll see it. --- Every error from Session kit's own logic is an \`AuthError\`. Match on its -\`code\`. The \`message\` is for people, and may change. +\`code\`, because the \`message\` is for people and can change. For +example, to check for a locked session: \`\`\`ts title="src/error-codes.ts" import { AuthError } from "@monarcode/session-kit"; @@ -211,7 +231,11 @@ How errors reach your app, and how to show them: .map((line) => line.replace(/^\s*\*\s?/, "")) .join("\n") .trim(); - body += `\n## ${member.literal.text}\n\n${toMarkdown(text)}\n`; + const paragraphs = text + .split(/\n\s*\n/) + .map(toMarkdown) + .join("\n\n"); + body += `\n## ${member.literal.text}\n\n${paragraphs}\n`; } return body; } @@ -258,12 +282,81 @@ function groupOf(name, declaration) { } /** - * A declaration's first paragraph, with a list that it introduces. A link to - * an export on the same page becomes an anchor; others become code spans. + * A declaration's description, then its `@see` lines. A link to an export on + * the same page becomes an anchor; others become code spans. */ function summaryOf(node, names) { const doc = ts.getJSDocCommentsAndTags(node).filter(ts.isJSDoc).at(-1); - const comment = doc?.comment; + const blocks = textOf(doc?.comment, names) + .trim() + .split(/\n\s*\n/); + for (const tag of doc?.tags ?? []) + if (tag.tagName.text === "see") + blocks.push( + `See ${textOf(tag.comment, names).trim().replace(/\.$/, "")}.`, + ); + return blocks.filter(Boolean).map(toMarkdown).join("\n\n"); +} + +/** + * The members a type alias declares, as list items: `name` and its + * description. It follows intersections, both branches of a conditional, a + * mapped type's source and the module's own aliases, and lists the methods + * of a member that is itself an object, such as `credentials.get`. + */ +function membersOf(checker, declaration, names, prefix = "") { + const items = []; + const seen = new Set(); + const visit = (node) => { + if (!node) return; + if (ts.isTypeAliasDeclaration(node)) return visit(node.type); + if (ts.isParenthesizedTypeNode(node) || ts.isTypeOperatorNode(node)) + return visit(node.type); + if (ts.isIntersectionTypeNode(node)) return node.types.forEach(visit); + if (ts.isConditionalTypeNode(node)) { + visit(node.trueType); + return visit(node.falseType); + } + if (ts.isMappedTypeNode(node)) + return visit(node.typeParameter.constraint); + if (ts.isTypeReferenceNode(node)) { + // `Readonly<{ … }>` and the module's own aliases, not other packages'. + if (node.typeName.getText() === "Readonly") + return visit(node.typeArguments?.[0]); + const symbol = checker.getSymbolAtLocation(node.typeName); + const alias = symbol?.declarations?.find(ts.isTypeAliasDeclaration); + if (alias && !alias.getSourceFile().isDeclarationFile) visit(alias); + return; + } + if (!ts.isTypeLiteralNode(node)) return; + for (const member of node.members) { + if (!member.name || !ts.isIdentifier(member.name)) continue; + const name = `${prefix}${member.name.text}`; + if (seen.has(name)) continue; + seen.add(name); + const doc = ts + .getJSDocCommentsAndTags(member) + .filter(ts.isJSDoc) + .at(-1); + const text = textOf(doc?.comment, names).trim(); + items.push( + text + ? `- \`${name}\`: ${text + .split(/\n\s*\n/) + .map(toMarkdown) + .join(" ")}` + : `- \`${name}\``, + ); + if (member.type && ts.isTypeLiteralNode(member.type)) + items.push(...membersOf(checker, member.type, names, `${name}.`)); + } + }; + visit(declaration); + return items; +} + +/** JSDoc text, with each `{@link}` as an anchor or a code span. */ +function textOf(comment, names) { let text = ""; for (const part of typeof comment === "string" ? [{ text: comment }] @@ -279,19 +372,14 @@ function summaryOf(node, names) { : `\`${name}\``; } else text += part.text; } - const blocks = text.trim().split(/\n\s*\n/); - const kept = [blocks[0] ?? ""]; - // A first paragraph ending in a colon introduces a list. - if (/:\s*$/.test(blocks[0] ?? "") && /^\s*- /.test(blocks[1] ?? "")) - kept.push(blocks[1]); - return kept.map(toMarkdown).join("\n\n"); + return text; } /** One block of JSDoc text as Markdown: list items keep their own lines. */ function toMarkdown(block) { const lines = []; for (const line of block.split("\n").map((part) => part.trim())) { - if (lines.length === 0 || line.startsWith("- ")) lines.push(line); + if (lines.length === 0 || /^(- |\d+\. )/.test(line)) lines.push(line); else lines[lines.length - 1] += ` ${line}`; } return lines.map(escapeMdx).join("\n"); diff --git a/site/PRODUCT.md b/site/PRODUCT.md index 8f3a85f..0a76ab2 100644 --- a/site/PRODUCT.md +++ b/site/PRODUCT.md @@ -57,13 +57,13 @@ those same checked examples, so the code shown is code that compiles. `/docs/…`; older lines are snapshots at `/docs//…`, switched with a version dropdown. The live site shows the newest release (Cloudflare's production branch `site`); `main` deploys as a preview. -- The site ships with `0.1.0-rc.0`. The package is pre-1.0: alpha releases - until now, release candidates next. +- The package is pre-1.0 and in release candidates: the 0.1 API is frozen, + and later 0.1 releases only add to it. ## Capabilities and Constraints - Fumadocs on TanStack Start, fully prerendered to static files - (`site/dist/client`), hosted on Cloudflare Pages. Light and dark mode, full + (`site/dist/client`), hosted on Cloudflare Pages. Dark only, full text search, per-version search, `llms.txt`. - Guides live in `site/content/docs/(latest)/` as MDX. A `ts` or `tsx` block with `title="path"` is a checked example; each page's examples compile as @@ -108,7 +108,7 @@ those same checked examples, so the code shown is code that compiles. ## Evidence on Hand -- The test suite: 415 tests, run with both synchronous and asynchronous +- The test suite, run with both synchronous and asynchronous storage (`tests/`), plus type tests against the built package. - Type-checked examples in the site's pages, the README and the JSDoc (`scripts/check-docs.mjs`). diff --git a/site/content/docs/(latest)/client/index.mdx b/site/content/docs/(latest)/client/index.mdx index 3c7a24d..c0ab338 100644 --- a/site/content/docs/(latest)/client/index.mdx +++ b/site/content/docs/(latest)/client/index.mdx @@ -1,64 +1,79 @@ --- title: Using the client -description: The client's methods at a glance, for loaders, event handlers, request code, and anything else outside React. +description: The client's methods at a glance, for loaders, event handlers and request code, and the options that change how it holds the user. --- -This section is for code outside React components. Components read the -session with hooks. Everything else, such as loaders, event handlers, and -request code, calls the client that `createAuth` returned. These are its -methods: +Your components read the session with hooks, but some of your code runs +outside React: a route loader, a click handler, the code that calls your API. +That code talks to the client that `createAuth` returned, which these docs +call `auth`. -| 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. | +This section covers the client itself: the methods that code outside React +calls, and two `createAuth` options that change how the client holds the +user, reading it from the access token and locking. The examples build on the +app from [Getting started](/docs/getting-started), where `auth` is the client +and `authFetch` its `fetch`. + +## The client's methods + +Here's what each method does: + +| 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, or `null`. It reads the saved session first if needed, and refreshes an access token that expired. | +| `auth.signIn({ ...tokens, user })` | Saves a new session, replacing any current one. | +| `auth.signOut()` | Ends the session and clears the saved one. Other tabs sign out too, when the storage reports changes and `locking` is off. | +| `auth.updateUser(user)` | Replaces the user and keeps the session. A client that reads the user from the access token doesn't have it. | +| `auth.refresh()` | Refreshes now, even while the access token still works. | +| `auth.retry()` | Tries again after a refresh failed. | +| `auth.isCurrent(session)` | Checks whether a session is still the signed-in one. | +| `auth.credentials.get()`, `.renew()`, `.reject()` | Resolves the access token, and replaces it or ends the session after a 401, for code that sends requests. | +| `auth.lock()`, `auth.unlock()` | Locks and unlocks a saved session, with the [`locking`](/docs/client/locking) option. | +| `auth.mount()` | Starts the expiry timers and following other tabs. `AuthProvider`, TanStack Router's `connectAuth`, React Router's `SessionOutlet` and Expo's `SessionGate` call it for you. | 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, so your editor shows the details where you call it. The +[`AuthClient` reference](/docs/reference/core#authclient) has the same +text. + +## With server rendering -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). +When the session lives on the server, the browser's client comes from +`createMirrorAuth` instead. It reads the state and the session the same way, +but it has no `lock`, `unlock` or `updateUser`, and its `signIn` and +`credentials` need options of their own. +[Server rendering](/docs/server-rendering) covers what it can do. -The examples in this section build on the app from -[Getting started](/docs/getting-started). `auth` is its client, and -`authFetch` its `fetch`. +## In this section + +Each page covers one job: + +## Next steps + +- [Sessions and credentials](/docs/client/sessions): ask who is signed in + from a loader or an event handler. +- [Authenticated requests](/docs/client/requests): call your API with the + access token. +- [Configuring the client](/docs/configuration): change how the client saves, + refreshes and reports errors. diff --git a/site/content/docs/(latest)/client/locking.mdx b/site/content/docs/(latest)/client/locking.mdx index dda1516..f0f632e 100644 --- a/site/content/docs/(latest)/client/locking.mdx +++ b/site/content/docs/(latest)/client/locking.mdx @@ -3,20 +3,28 @@ title: Locking description: Restore a saved session as locked until the user unlocks it, for example with biometrics, in native apps. --- -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()`. The following client encrypts its saved tokens with a key -the app holds: +A banking or health app often asks a returning user to unlock it, with Face +ID, a fingerprint or a passcode, before it shows anything. The user is still +signed in, but the app shouldn't use their tokens until they prove it's +them. Locking gives you that: a saved session restores as **locked**, with +the user known and the tokens sealed until your app unlocks them. + +This page explains what locked means, what you provide, and how unlocking +and locking again behave. For the Expo how-to, with a key behind the +device's biometrics, see [Unlock with biometrics](/docs/setups/expo-locking). + +## Turn on locking + +Pass a `locking` option to `createAuth`, with a `seal` function that encrypts +the tokens and an `open` function that decrypts them: ```ts title="src/locked-auth.ts" import { createAuth, type AuthStorage } from "@monarcode/session-kit"; import { userSchema } from "./backend.js"; -// Your app's own: a native secure store, and encryption with a key it holds -// in memory only while unlocked. +// Your app's own: a native secure store, and encryption with a key it loads +// when the user unlocks. declare const storage: AuthStorage; declare const key: CryptoKey; declare function encrypt(key: CryptoKey, plain: string): Promise; @@ -34,43 +42,117 @@ export const lockedAuth = createAuth({ }, }); -/** Once the app has its key: resolves the session, now `authenticated`. */ +/** After the app has its key: resolves the session, `authenticated`. */ export const unlockApp = () => lockedAuth.unlock(); /** `locked` again. The saved session stays, and the tokens leave memory. */ 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 - lock screen in front of an otherwise ordinary session. -- **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` 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 - `REFRESH_FAILED` and leaves the session unlocked and `unavailable` until - `retry()`. Check `status` after a rejection. -- **Keep the key until `lock()` settles.** A refresh already running still - saves its tokens, and saving seals them. -- **Native apps only.** Locking is built for one JavaScript context. In a - browser, tabs don't follow each other with `locking`, and the router - adapters treat a locked session as signed out. It also needs a user schema: - a user read from the access token can't be shown without its token. -- **Turning it on and off.** A session saved before `locking` was added - restores as `locked` too, and is sealed when unlocked. Turning - `locking` off later makes sealed sessions unreadable, which signs those - users out. +Sealing is yours: Session kit depends on no crypto or biometrics library. +The user and the session ID are saved beside the sealed tokens, where they +can be read while locked. `locking: true` saves the tokens as they are, for +a lock screen in front of an otherwise ordinary session. + +## What locked means + +A saved session restores as `locked`. `user` and `sessionId` are set, so a +"Welcome back" screen can greet the user by name, but the tokens stay sealed +until `auth.unlock()`. + +While the session is locked, nothing waits for an unlock that might never +come: + +- `getSession`, `retry`, `refresh`, `updateUser`, `credentials.get` and + `credentials.renew` reject with `LOCKED`. So does + [`authFetch`](/docs/client/requests#when-it-rejects). +- Nothing refreshes, and the expiry timers are off. +- The router adapters treat a locked session as signed out. +- `user` is still set, so check `status`, not `user`, to know whether the + app has access. [State](/docs/client/state#check-status-not-user) shows + how. + +Two calls still work while locked: + +- **`signIn`** replaces the locked session, so a user who can't unlock can + sign in again. +- **`signOut`** ends it, without calling your `revoke` option: the tokens + aren't in memory to revoke. A session that `lock()` is still locking, while + a refresh finishes, is revoked as usual. + +## Seal with a key + +With `seal` and `open` in `locking`, every save calls `seal`: a sign-in's, a +refresh's and a profile update's. If `seal` throws, as it does when your app +doesn't have the key, the save fails with `PERSISTENCE_FAILED`, and no one is +signed in. The one exception is a session saved before locking was turned +on: unlocking seals it, and if that `seal` fails, the user stays signed in +and the saved session stays as it was until the next save. + +So your app needs the key whenever it saves, not only when it unlocks: + +- **On a password sign-in,** make a new key before you call `signIn`, as + `withNewKey` does in [Unlock with biometrics](/docs/setups/expo-locking). +- **While locking,** keep the key until `lock()` settles. A refresh already + running when you call `lock()` still saves its tokens, and saving seals + them. + +## Unlock + +`auth.unlock()` reads the saved tokens, opens them with your `open` function, +and resolves the session, `authenticated` again. If the access token has +expired, it refreshes it first. Overlapping calls share one unlock, and when +the session isn't locked, `unlock()` acts like `getSession()`. + +A failed unlock doesn't always leave the session locked. Here's what each +outcome does, so you can check `status` after a rejection: + +| When… | `unlock()`… | The session afterwards | +| ------------------------------------------------- | --------------------------------- | ------------------------------------------- | +| `open` throws, or doesn't return a string | Rejects with `UNLOCK_FAILED` | Still locked | +| Storage can't be read | Rejects with `PERSISTENCE_FAILED` | Still locked | +| What `open` returns isn't this session's tokens | Rejects with `INVALID_SESSION` | Signed out | +| The saved session is gone, or older than `maxAge` | Resolves `null` | Signed out | +| The backend rejects the refresh token | Resolves `null` | Signed out | +| The refresh fails for another reason | Rejects with `REFRESH_FAILED` | Unlocked, and `unavailable` until `retry()` | +| The user signs in or out while it runs | Rejects with `SESSION_CHANGED` | The new session, or signed out | + +## Lock again + +`auth.lock()` locks a session that's in use, such as when the app goes to +the background. `status` turns `locked` at once, and the timers stop. The +saved session and `user` stay. + +The tokens leave memory when `lock()` resolves. If a refresh is running, +`lock()` waits for it to save its tokens first: cancelling it could lose a +refresh token your backend has already replaced. + +`lock()` does nothing when no one is signed in or the session is already +locked. + +`lock()` and `unlock()` reject with `INVALID_OPTIONS` on a client created +without `locking`. + +## Limits + +- **Native apps only.** Locking is built for one JavaScript context. With + `locking`, tabs don't follow each other, and the client doesn't check for + changes that another context saved. +- **It needs a user schema.** A user read from the access token can't be + shown without its token, so `createAuth` throws `INVALID_OPTIONS` for + `locking` with + [`fromAccessToken`](/docs/client/users-from-tokens). +- **Not with server rendering.** The browser's client for a session kept on + the server has no `lock` or `unlock`. +- **Turning it on later** works: a session saved before `locking` was added + restores as `locked` too, and is sealed when it's unlocked. +- **Turning it off later** makes sealed sessions unreadable. Those users are + signed out, with `INVALID_SESSION` in `state.error`. ## Next steps -The [Expo guide](/docs/setups/expo#locking) has a worked example: a key behind -the device's biometrics, AES-GCM sealing, and a welcome-back screen. +- [Unlock with biometrics](/docs/setups/expo-locking): a key behind the + device's biometrics, AES-GCM sealing, and a welcome-back screen in Expo. +- [Expo Router](/docs/setups/expo): set up the app the lock screen sits in. +- [`AuthLocking` reference](/docs/reference/core#authlocking): `seal` and + `open`. diff --git a/site/content/docs/(latest)/client/other-http-clients.mdx b/site/content/docs/(latest)/client/other-http-clients.mdx index 50a4dad..841a909 100644 --- a/site/content/docs/(latest)/client/other-http-clients.mdx +++ b/site/content/docs/(latest)/client/other-http-clients.mdx @@ -3,17 +3,21 @@ title: Other HTTP clients description: Send the access token with ky, axios, openapi-fetch or any other HTTP client. --- -[`authFetch`](/docs/client/requests) takes a `URL` or a `Request` as well as -a path, as `fetch` does. An HTTP client that lets you choose its `fetch` can -send its requests through it, and they get everything `authFetch` does: the -token stays on your API's origin, a 401 refreshes once, and only a GET or -HEAD is sent again. +Your app might already call its API through an HTTP client such as ky, axios +or openapi-fetch. You don't have to replace it to send the access token. Most +clients let you choose the `fetch` they call, and `authFetch` can be that +`fetch`. A client with its own transport can use the three calls `authFetch` +is built on. -A client with its own transport uses -[the calls `authFetch` is built on](#clients-without-a-fetch-option) instead. +This page shows both ways, and what each one leaves to you. ## Clients that take a `fetch` +[`authFetch`](/docs/client/requests) takes a `URL` or a `Request` as well as +a path, as `fetch` does. A client that sends its requests through it gets +everything `authFetch` does: the token goes only to your API's origin, a 401 +refreshes the token one time, and only a `GET` or `HEAD` is sent again. + With [ky](https://github.com/sindresorhus/ky), pass `authFetch` as `fetch`: ```ts title="src/ky.ts" @@ -29,8 +33,8 @@ export async function fetchCarts(userId: number): Promise { } ``` -With [axios](https://axios-http.com), choose its `fetch` adapter and pass -`authFetch` in `env`: +With [axios](https://axios-http.com), choose its `fetch` adapter, and pass +`authFetch` as `env.fetch`: ```ts title="src/axios.ts" import axios from "axios"; @@ -45,52 +49,62 @@ export const http = axios.create({ }); ``` -[openapi-fetch](https://openapi-ts.dev/openapi-fetch/) takes it the same way -as ky: - -```ts -const client = createClient({ baseUrl: API, fetch: authFetch }); -``` +With [openapi-fetch](https://openapi-ts.dev/openapi-fetch/), pass `authFetch` +as the `fetch` option of `createClient`, with your API as its `baseUrl`, the +same way as with ky. -What changes for the client's calls: +Here's 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 + [`optional: true`](/docs/client/requests#send-requests-while-signed-out). + Those requests then go out without a token. +- **A 401 reaches the client after the refresh.** For a `GET` or `HEAD`, the + client gets the answer to the request that was sent again. For a write, it + gets 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 + itself. axios wraps it in an `AxiosError` with the same `code`, and the + `AuthError` as its `cause`. Match on `error.code`, which works with both, + rather than on `instanceof AuthError`. +- **`authFetch` sets the `Authorization` header,** in place of one the client + set itself. [Authenticated requests](/docs/client/requests) has the rest of + its rules. +- **Only what a `Request` holds is sent.** ky passes `fetch` the options it + doesn't use 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 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 - `null` when nobody is signed in. -2. **After a 401**, `auth.credentials.renew(credentials)` takes the - credentials that request was sent with, and resolves new ones. However many - 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 +`createAuthFetch` and effetch's [`sessionBearer` plugin](/docs/effect#how-sessionbearer-differs-from-createauthfetch) are +built on three 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. It waits for the saved session to be read, and refreshes an access + token that has expired first. It resolves `null` when no one is signed in. +2. **After a 401,** `auth.credentials.renew(credentials)` takes the + credentials that request was sent with, and resolves new ones. Requests + that fail at the same time 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 newer credentials have replaced the ones you pass. +`get` and `renew` reject in these cases: + +- **`LOCKED`** while the session is [locked](/docs/client/locking). +- **The refresh's failure,** such as `REFRESH_FAILED`, when a refresh fails. +- **`SESSION_CHANGED`** when another session replaces the one they're working + for. +- **`PERSISTENCE_FAILED`** when the saved session can't be read, or the new + tokens can't be saved. + +Thrown from an axios interceptor, these errors reach your code as the +`AuthError` itself, not as an `AxiosError`. + An axios instance that keeps its default adapter does it with two interceptors: @@ -139,13 +153,31 @@ http.interceptors.response.use(undefined, async (error: unknown) => { }); ``` -Three things `createAuthFetch` does for you are yours to keep here: +## What's left to you + +Without `authFetch`, a few things it does for you are yours to do: - **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 - 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 - you show its answer. + 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)` + checks whether the session that sent a request is still the signed-in one, + before you show its answer. +- **Don't follow redirects with the token.** `authFetch` refuses a redirect, + as [Authenticated requests](/docs/client/requests#when-it-rejects) + explains. axios's default adapters follow it, so don't let your API + redirect requests that carry a token. +- **Decide about signed-out requests.** `authFetch` rejects them with + `UNAUTHENTICATED`, unless it was created with `optional: true`. The + interceptor above sends them without a token instead. Throw in the request + interceptor if your API should never get one. + +## Next steps + +- [Authenticated requests](/docs/client/requests): what `authFetch` does + after a 401, and when it rejects. +- [Effect and effetch](/docs/effect): send the token from Effect code with + `sessionBearer`. +- [Errors](/docs/configuration/errors): show a failed refresh to the user. diff --git a/site/content/docs/(latest)/client/requests.mdx b/site/content/docs/(latest)/client/requests.mdx index 7942eb6..a8c42dd 100644 --- a/site/content/docs/(latest)/client/requests.mdx +++ b/site/content/docs/(latest)/client/requests.mdx @@ -1,34 +1,74 @@ --- title: Authenticated requests -description: A fetch that sends the access token to one API, refreshes on a 401, and never leaks the token. +description: Call your API with the access token, get a new one after a 401, and keep the token away from every other server. --- -`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, 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 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 -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 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: +Your API wants the access token on every request, and it answers 401 when the +token has expired or been revoked. `createAuthFetch` gives you a `fetch` that +adds the token, gets a new one after a 401, and sends the token only to your +API, so your request code doesn't have to. + +This page shows how to send requests with it, what happens after a 401, and +when it rejects. It builds on the `authFetch` from +[Getting started](/docs/getting-started#5-call-your-api). + +## Send a request + +`authFetch` takes the same arguments as `fetch`. Pass a path, and it's +resolved against `baseUrl`, the way a link is resolved against a page's +address: + +```ts title="src/orders.ts" +import { authFetch } from "./api.js"; + +export async function loadOrders(userId: number) { + // https://dummyjson.com/auth/carts/user/1, with the access token. + const response = await authFetch(`auth/carts/user/${userId}`); + if (!response.ok) throw new Error(`Orders failed (${response.status})`); + return response.json(); +} +``` + +Here's what to know about the URL and the headers: + +- `baseUrl` must be an absolute URL. End it with `/`, so that + `authFetch("orders")` lands under it rather than beside it. +- `authFetch` also takes a `URL` or a `Request`, so an HTTP client with a + `fetch` option can send its requests through it. See + [Other HTTP clients](/docs/client/other-http-clients). +- While the user is signed in, `authFetch` sets `Authorization: Bearer …`. It + replaces any `Authorization` header the request already has. +- A `Request` with a body can be sent only one time, as with `fetch`. To send + a write again, keep a clone. + +## After a 401 + +When your API answers 401, `authFetch` gets a new access token and sends the +request again. It does that only for `GET` and `HEAD`, which are safe to send +twice. A `POST` or any other method comes back with its 401, for you to +decide. + +The rest of the 401 handling: + +- Requests that get a 401 at the same time share one refresh. If another + request or another tab has already replaced the token, `authFetch` uses the + new one without a refresh. +- If the request sent again gets a 401 too, your API has rejected the new + token as well, so the user is signed out. If your API also answers 401 for + other reasons, set `signOutOnRepeated401` to `false`, as + [below](#keep-users-signed-in-after-a-second-401). +- 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. +- If your backend rejects the refresh token, the user is signed out, and + `authFetch` resolves the original 401. If the user signs out or switches + account while the refresh runs, it rejects with `SESSION_CHANGED`. + +## Retry a write + +Because `authFetch` never sends a write twice, retry it yourself where +sending it twice is safe. After the 401, the token has already been +refreshed: ```ts title="src/add-to-cart.ts" import { authFetch } from "./api.js"; @@ -51,7 +91,38 @@ export async function addToCart(userId: number, productId: number) { } ``` -Two more options change the defaults: +## When it rejects + +`authFetch` rejects rather than send the token somewhere it shouldn't go, or +resolve a response meant for another account. Here's when it rejects, and +with what: + +| When… | `authFetch` rejects with… | +| ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | +| The URL is on another origin, has a username or password in it, or isn't a valid URL | `INVALID_OPTIONS`. The token goes only to `baseUrl`'s origin. | +| The `Request` comes from a polyfill or another realm, such as an iframe | `INVALID_OPTIONS` | +| The user is signed out | `UNAUTHENTICATED`, unless `optional` is `true` | +| The session is locked | `LOCKED`, even when `optional` is `true` | +| The saved session can't be read | `PERSISTENCE_FAILED` | +| A refresh fails | That failure, such as `REFRESH_FAILED`, until a retry, a refresh, new tokens from another tab, or a sign-in or sign-out | +| The user signs out or switches account while the request runs | `SESSION_CHANGED` | +| The response is a redirect | A `TypeError`, as `fetch` gives when it refuses a redirect | +| The network fails | `fetch`'s own error, usually a `TypeError` | + +The last two aren't `AuthError`s, so code that matches on `code` doesn't +catch them. To show these failures, see [Errors](/docs/configuration/errors). + +A redirect isn't followed, so the token never reaches a server your API +redirects to. On React Native before Expo SDK 58, `fetch` follows a redirect +whatever it's told. `authFetch` still refuses the response, but the +redirected request has already gone out. Don't let your API +redirect requests that carry a token. + +## Send requests while signed out + +Some apps call one API for public and private endpoints alike. With +`optional: true`, a signed-out request goes out without a token instead of +rejecting: ```ts title="src/public-api.ts" import { createAuthFetch } from "@monarcode/session-kit/http"; @@ -61,15 +132,36 @@ import { API } from "./backend.js"; 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, - // 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. +}); +``` + +A request sent without a token keeps its own `Authorization` header, if it +has one. A 401 to it comes back as it is, with no refresh and no sign-out. + +## Keep users signed in after a second 401 + +Some APIs answer 401 for reasons other than a rejected token, such as a +resource the user can't see. With `signOutOnRepeated401: false`, a second +401 to the same request comes back as it is, and the user stays signed in: + +```ts title="src/reports-api.ts" +import { createAuthFetch } from "@monarcode/session-kit/http"; + +import { auth } from "./auth.js"; +import { API } from "./backend.js"; + +export const reportsFetch = createAuthFetch(auth, { + baseUrl: `${API}/`, 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. +## Next steps + +- [Other HTTP clients](/docs/client/other-http-clients): send ky, axios or + openapi-fetch requests through `authFetch`, or add the token yourself. +- [Errors](/docs/configuration/errors): show a failed refresh or an outage to + the user. +- [`createAuthFetch` reference](/docs/reference/http#createauthfetch): every + option and error. diff --git a/site/content/docs/(latest)/client/sessions.mdx b/site/content/docs/(latest)/client/sessions.mdx index c45e4d6..0916c9d 100644 --- a/site/content/docs/(latest)/client/sessions.mdx +++ b/site/content/docs/(latest)/client/sessions.mdx @@ -3,10 +3,19 @@ title: Sessions and credentials description: Ask the client who is signed in, and keep the access token apart from code that only needs the user. --- -A **session** is who is signed in, `{ sessionId, user }`, and never holds -tokens. `getSession()` is how code outside React asks for it. It waits for a -restore or a refresh that is under way, so a loader never acts on a stale -answer: +A route loader or an event handler often needs to know who is signed in +before it does anything. Reading the state isn't always enough: right after a +reload, the saved session might not have been read yet, and the access token +might have expired. `auth.getSession()` takes care of both, then answers. + +This page shows how to ask for the session, what to do when that fails, and +how the access token is kept apart from code that only needs the user. + +## Ask who is signed in + +A **session** is who is signed in: `{ sessionId, user }`. It holds no tokens, +so it's safe to keep in route context or pass around. Ask for it with +`getSession()`, which resolves `null` when no one is signed in: ```ts title="src/cart.ts" import { authFetch } from "./api.js"; @@ -22,13 +31,58 @@ 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 `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. +`getSession()` waits for the saved session to be read. If the access token +has expired, it refreshes it first, or waits for the refresh that's already +running. While the token still works, it answers at once, even if an early +refresh is running in the background. + +## When `getSession` rejects + +`getSession()` rejects rather than answer with a session it can't vouch for. +Here's when it rejects, and with what: + +| When… | `getSession()` rejects with… | +| --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| The saved session can't be read | `PERSISTENCE_FAILED` | +| The access token expired, and the refresh failed | That failure, such as `REFRESH_FAILED`, until a retry, a refresh, new tokens from another tab, or a sign-in or sign-out | +| The session is [locked](/docs/client/locking) | `LOCKED` | +| The session changes while it waits, such as a new sign-in | `SESSION_CHANGED` | + +When the refresh of an expired access token fails, the session is +`unavailable`, and `getSession()` rejects with the same failure without +trying again. `auth.retry()` resolves +the session as `getSession()` does, but tries the refresh again first. Use it +for a "Try again" button. [Errors](/docs/configuration/errors) shows how to +present these failures. + +## Keep the access token apart + +**Credentials** are the access token, with the session it belongs to: +`{ sessionId, accessToken, expiresAt }`. The client keeps them apart from the +session, so code that only needs the user never holds a token. + +Most code never reads credentials itself: + +- [`createAuthFetch`](/docs/client/requests) reads them for every request. +- An HTTP client that takes `authFetch` as its `fetch` gets them the same + way. +- Code that sends requests another way uses `auth.credentials`, as + [Other HTTP clients](/docs/client/other-http-clients#clients-without-a-fetch-option) + shows. + +## Check the session after slow work + +The user can sign out, or switch account in another tab, while your code +waits. `auth.isCurrent(session)` checks whether a session you're holding, or +the credentials a request was sent with, is still the signed-in one. Check it +before you show the result of work that took a while, so one account's +result never appears for another. `authFetch` makes that check for its own +requests. + +## Next steps -`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. +- [Authenticated requests](/docs/client/requests): call your API with the + access token, and refresh after a 401. +- [State](/docs/client/state): scope cached data to `sessionId`. +- [Errors](/docs/configuration/errors): show a failed refresh, and offer + `retry()`. 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 0fa5134..6614eaa 100644 --- a/site/content/docs/(latest)/client/signing-in-and-out.mdx +++ b/site/content/docs/(latest)/client/signing-in-and-out.mdx @@ -3,19 +3,88 @@ 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({ ...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. +Your backend signs the user in and answers with tokens. From there, the +client takes over: `auth.signIn` saves the session, and `auth.signOut` ends +it, in this tab and the others. Session kit never checks a password itself. -`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. +This page shows what each call does, when it rejects, and how to revoke the +ended tokens on your backend. -If your backend can revoke tokens, give the client a `revoke` callback. It -receives the ended tokens after the user is signed out: +## Sign in + +Pass `auth.signIn` the tokens your backend issued and the user, as +`signInWithPassword` does in +[Getting started](/docs/getting-started#2-create-the-client): + +```ts title="src/switch-account.ts" +import { auth } from "./auth.js"; +import { login } from "./backend.js"; + +/** Signs in as another user, replacing the current session. */ +export async function switchAccount(username: string, password: string) { + const { accessToken, refreshToken, user } = await login(username, password); + await auth.signIn({ accessToken, refreshToken, user }); +} +``` + +`signIn` checks the tokens and the user first, then saves the new session in +place of any current one, even a [locked](/docs/client/locking) one. With +[`fromAccessToken`](/docs/client/users-from-tokens), leave out `user`: the +client reads it from the access token. [Expiry](/docs/configuration/expiry) +covers how the client finds out when the access token expires. + +`signIn` doesn't navigate. The state changes, and your guards or your +components render from it, so a sign-in page has nothing to do when it +succeeds. + +## When `signIn` rejects + +A failed check leaves the current session as it was, so a mistake in a +sign-in never signs anyone out. A failed save is different. Here's when +`signIn` rejects, and what happens to the session: + +| When… | `signIn` rejects with… | The session afterwards | +| ------------------------------------------------------------------ | ------------------------ | ---------------------- | +| The tokens can't be used, such as an access token that has expired | `INVALID_SESSION` | Unchanged | +| The user schema rejects the user | `USER_VALIDATION_FAILED` | Unchanged | +| Another `signIn` or a `signOut()` starts while it checks the user | `SESSION_CHANGED` | The latest call's | +| The session can't be saved | `PERSISTENCE_FAILED` | Signed out | + +The latest call wins: a newer `signIn` or `signOut()` makes a pending sign-in +reject, so an earlier, slower sign-in never replaces a later one. + +With a [`locking`](/docs/client/locking) option that has `seal`, every save +seals the tokens. If your `seal` throws, as it does without its key, the save fails with +`PERSISTENCE_FAILED` and no one is signed in. + +## Sign out + +`auth.signOut()` signs the user out at once, then clears the saved session: + +```ts title="src/sign-out.ts" +import { auth } from "./auth.js"; + +export async function signOutAndLeave() { + // Resolves after `revoke`, if you set it, has finished. + await auth.signOut(); + window.location.assign("/login"); +} +``` + +Other tabs that share the storage sign out too, when the storage reports +changes, as `webStorage()` does, and `locking` is off. +[Tabs](/docs/configuration/tabs) explains how tabs follow each other. + +If the saved session can't be cleared, `signOut()` rejects with +`PERSISTENCE_FAILED`. The app is signed out anyway, but the next load would +restore the session, so call `signOut()` again later. + +## Revoke tokens on your backend + +Signing out in the app doesn't end the tokens on your backend: until they +expire, anyone holding them can still use them. If your backend can revoke +tokens, give `createAuth` a `revoke` option. It receives the ended tokens +after the user is signed out: ```ts title="src/revoke.ts" import type { RevokeFn } from "@monarcode/session-kit"; @@ -33,9 +102,30 @@ 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. +The user is signed out before `revoke` runs, so a UI that follows the state +never waits for it. `signOut()` itself resolves after `revoke` settles, or +after 15 seconds, when `signal` aborts. Await it before a full-page redirect, +which would cancel the request. + +A failed revocation shows in `state.error` as `REVOKE_FAILED`, and +`signOut()` still resolves. The sign-out stands: the user asked to leave, and +has. + +`revoke` isn't called in two cases: + +- **The backend already ended the session,** such as by rejecting the + refresh token. +- **The session is locked,** whether it was restored locked or locked by a + `lock()` that has resolved. Its tokens aren't in memory. + +A sign-out before the saved session has been read still revokes that saved +session, unless `locking` is on. + +## Next steps -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. +- [Tabs](/docs/configuration/tabs): how a sign-in or sign-out reaches every + tab. +- [Updating the user](/docs/client/updating-the-user): change the user + without signing in again. +- [Errors](/docs/configuration/errors): show `REVOKE_FAILED` and other + failures. diff --git a/site/content/docs/(latest)/client/state.mdx b/site/content/docs/(latest)/client/state.mdx index 5681df1..dc924ff 100644 --- a/site/content/docs/(latest)/client/state.mdx +++ b/site/content/docs/(latest)/client/state.mdx @@ -1,10 +1,20 @@ --- title: State -description: Read the client's state outside React, follow its changes, and know what each field holds. +description: Read the client's state outside React, follow its changes, scope cached data to the session, and know what each field holds. --- -`auth.state` holds what `useAuth` reads in components. Outside React, read it -once with `get`, or follow it with `subscribe`: +In a component, `useAuth` reads the state and re-renders when it changes. +Code outside React, such as a logger, a cache or an analytics hook, reads the +same state from `auth.state`. It holds who is signed in and where the session +stands, never a token. + +This page shows how to read and follow the state, what each field holds, and +how to keep one account's data away from the next. + +## Read and follow the state + +Read the state at any moment with `get`, and follow its changes with +`subscribe`: ```ts title="src/status-log.ts" import { auth } from "./auth.js"; @@ -21,25 +31,109 @@ 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 -error reporting can catch it. +`subscribe` calls the listener on each later change, not with the current +state, so read the current state with `get` first, as `logStatus` does. + +A listener that throws doesn't interrupt the client. Its error is thrown +again asynchronously, where your error reporting can catch it. + +## What the state holds + +The state has these fields: + +| Field | Holds | +| ----------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| `status` | Where the session stands, such as `authenticated` or `unavailable`. [How it works](/docs#how-it-works) lists each one. | +| `user` | The signed-in user, or `null`. Checking `status` tells TypeScript whether it's set. | +| `sessionId` | The ID of this sign-in, or `null` when signed out. It's new on every sign-in, and stays the same across refreshes and profile updates. | +| `error` | The latest failure, as an [`AuthError`](/docs/configuration/errors), or `null`. The next successful change clears it. | +| `version` | A number that changes when route guards must check the session again. `connectAuth` and `useAuthRevalidation` watch it. | + +`version` changes on a sign-in, a sign-out, a new user or a change of status. +A token refresh doesn't change it, even while the status is `refreshing`, so +guards don't run again for one. + +## Scope cached data to the session + +An account switch is a sign-out followed by a sign-in, and it can happen in +another tab. Data cached for the first account must never show for the +second. Because `sessionId` is new on every sign-in, it's the key to cache +private data under. + +This cache keeps each session's orders under its `sessionId`, and drops them +when the session ends: + +```ts title="src/orders-cache.ts" +import { authFetch } from "./api.js"; +import { auth } from "./auth.js"; + +const cache = new Map>(); + +// After a sign-out or an account switch, drop the old session's entries. +auth.state.subscribe(({ sessionId }) => { + for (const id of cache.keys()) if (id !== sessionId) cache.delete(id); +}); + +async function fetchOrders(userId: number): Promise { + const response = await authFetch(`auth/carts/user/${userId}`); + if (!response.ok) throw new Error(`Orders failed (${response.status})`); + return response.json(); +} + +export async function cachedOrders(): Promise { + const session = await auth.getSession(); + if (!session) return null; + let orders = cache.get(session.sessionId); + if (!orders) { + orders = fetchOrders(session.user.id); + cache.set(session.sessionId, orders); + // A failed load isn't kept, so the next call tries again. + orders.catch(() => cache.delete(session.sessionId)); + } + return orders; +} +``` + +The same idea applies to other caches: + +- **TanStack Query and similar libraries:** put `sessionId` in the key of + every private query, so each account gets its own entries. +- **Components:** `SessionOutlet` and Expo's `SessionGate` remount the pages + under them when the account changes. For a layout outside them, such as a + sidebar, pass `key={sessionId}`, as the + [TanStack Router guide](/docs/setups/tanstack-router) shows. +- **Slow work:** `auth.isCurrent(session)` checks that a session is still the + signed-in one before you use a result that took a while. See + [Sessions and credentials](/docs/client/sessions). + +## Check `status`, not `user` -The state holds these fields: +`user` is set while the session is `authenticated` or `refreshing`, and also +while it's [locked](/docs/client/locking). A locked session can show who is +signed in, but it can't make requests. To know whether the user has access, +check `status`. + +`isSignedIn(state)` is that check. It's `true` while `authenticated` or +`refreshing`, and it tells TypeScript that `user` is set: + +```ts title="src/greeting.ts" +import { isSignedIn } from "@monarcode/session-kit"; + +import { auth } from "./auth.js"; + +export function greeting(): string { + const state = auth.state.get(); + return isSignedIn(state) ? `Hi, ${state.user.firstName}` : "Please sign in"; +} +``` -| Field | Holds | -| ----------- | ------------------------------------------------------------------------------------- | -| `status` | Where the session stands. [How it works](/docs#how-it-works) lists each one. | -| `user` | The signed-in user, or `null`. Checking `status` narrows it. | -| `sessionId` | New on every sign-in, and stable across refreshes and profile updates. | -| `error` | The latest failure, as an [`AuthError`](/docs/configuration/errors), or `null`. | -| `version` | Changes when guards must run again. `connectAuth` and `useAuthRevalidation` watch it. | +In a component, `useAuth(isSignedIn)` reads the same check. -Two habits follow from these fields: +## Next steps -- **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. `isSignedIn(state)` - is the check. It's `true` while `authenticated` or `refreshing`, and it - narrows `user`. `useAuth(isSignedIn)` reads it in a component. +- [Errors](/docs/configuration/errors): show `state.error` to the user, and + know which failures appear there. +- [Sessions and credentials](/docs/client/sessions): ask who is signed in + from a loader, and wait for the saved session to be read. +- [Core reference](/docs/reference/core#authstate): the `AuthState` type and + each status. diff --git a/site/content/docs/(latest)/client/updating-the-user.mdx b/site/content/docs/(latest)/client/updating-the-user.mdx index f4ce965..9f8d685 100644 --- a/site/content/docs/(latest)/client/updating-the-user.mdx +++ b/site/content/docs/(latest)/client/updating-the-user.mdx @@ -1,17 +1,48 @@ --- title: Updating the user -description: Replace the signed-in user without ending the session, safely across account switches. +description: Replace the signed-in user without ending the session, and handle each way it can fail. --- -`auth.updateUser` replaces the user and keeps the session. When you already -have the new user, such as from a form's response, pass it directly: -`auth.updateUser(user)`. +After a profile edit, the signed-in user has changed but the session hasn't. +Signing in again would be wrong: the tokens are still good. `auth.updateUser` +replaces the user, saves it and keeps the session, so every component that +reads the user shows the change. + +This page shows the two ways to call it, what happens when calls overlap, and +each way it can fail. + +## Pass the new user + +When you already have the new user, such as after your backend saved a +profile form, pass it to `updateUser`: + +```ts title="src/rename.ts" +import { authFetch } from "./api.js"; +import { auth } from "./auth.js"; + +/** Saves a new first name, then shows it without signing in again. */ +export async function rename(firstName: string) { + const session = await auth.getSession(); + if (!session) return; + const response = await authFetch(`users/${session.user.id}`, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ firstName }), + }); + if (!response.ok) throw new Error(`Rename failed (${response.status})`); + await auth.updateUser({ ...session.user, firstName }); +} +``` + +The user is checked against your user schema, as on sign-in. The session ID +stays the same, so data you [cached under it](/docs/client/state) stays +valid. + +## Fetch the new user When the new user comes from a request, pass a function that fetches it -instead. The client notes the session before the function runs. If the -session changes meanwhile, `updateUser` rejects with `SESSION_CHANGED`, and -the user it fetched never lands on another account. `fetchProfile` is the -request from [Getting started](/docs/getting-started#5-call-your-api): +instead. `fetchProfile` is the request from +[Getting started](/docs/getting-started#5-call-your-api): ```ts title="src/profile.ts" import { fetchProfile } from "./api.js"; @@ -19,3 +50,56 @@ import { auth } from "./auth.js"; export const reloadProfile = () => auth.updateUser(fetchProfile); ``` + +The client notes the session before the function runs. If the user signs +out or switches account while it runs, `updateUser` rejects with +`SESSION_CHANGED`, and the user it fetched never lands on another account. +The function has 15 seconds to finish. + +## Overlapping calls + +When `updateUser` calls overlap, such as two quick saves of a form, the latest +call wins. The earlier ones reject with `SESSION_CHANGED`, so an older user +never replaces a newer one. + +A token refresh that runs at the same time keeps the updated user, even when +your refresh callback returns a user of its own. + +## When `updateUser` rejects + +`updateUser` rejects rather than save a user to the wrong session. Here's +when, and with what: + +| When… | `updateUser` rejects with… | +| -------------------------------------------------------------------------------------------- | ------------------------------------------------ | +| No one is signed in | `UNAUTHENTICATED` | +| The session is [locked](/docs/client/locking) | `LOCKED` | +| The access token expired, and refreshing it failed | That failure, such as `REFRESH_FAILED` | +| The saved session can't be read | `PERSISTENCE_FAILED` | +| The user schema rejects the user | `USER_VALIDATION_FAILED` | +| The function rejects, or takes more than 15 seconds | `USER_VALIDATION_FAILED`, with the cause | +| The user signs out or switches account, or the access token expires, while the function runs | `SESSION_CHANGED` | +| A newer `updateUser` call starts | `SESSION_CHANGED` | +| The new user can't be saved | `PERSISTENCE_FAILED`, and the user is signed out | + +Only the last case changes the session. In the others, `updateUser` leaves +the user as it was. + +A function that rejects with an `AuthError` keeps its code. If the +`authFetch` call in `fetchProfile` rejects with `LOCKED`, for example, so +does `updateUser`. + +## With users from the access token + +A client that reads the user from the access token, with +[`fromAccessToken`](/docs/client/users-from-tokens), has no `updateUser`. The +token is the only source of the user there, so call `auth.refresh()` to pick +up a change. + +## Next steps + +- [State](/docs/client/state): scope cached data to `sessionId`, which an + update keeps. +- [Errors](/docs/configuration/errors): show a failure to the user. +- [`AuthClient` reference](/docs/reference/core#authclient): `updateUser` + and the client's other methods. diff --git a/site/content/docs/(latest)/client/users-from-tokens.mdx b/site/content/docs/(latest)/client/users-from-tokens.mdx index f82f8da..6cceb36 100644 --- a/site/content/docs/(latest)/client/users-from-tokens.mdx +++ b/site/content/docs/(latest)/client/users-from-tokens.mdx @@ -3,9 +3,18 @@ title: Users from the access token description: Read the user from a JWT access token's claims, instead of from your backend's sign-in response. --- -If your backend puts the user in a JWT access token, read it from there with -`fromAccessToken`. `signIn` then takes tokens only, the refresh callback -returns them, and the user changes whenever the token does: +Some backends answer a sign-in with tokens only, and put the user in the +access token: a JWT whose claims hold the user's ID, email and roles. Then +there's no user object to pass to `signIn`, and the user can change on every +refresh. `fromAccessToken` reads the user from the token's claims instead. + +This page shows how to set it up, what changes for the client, and how to +verify the token on a server. + +## Read the user from the token + +Pass `fromAccessToken` as the `user` option. Its first argument is a schema +for the claims, and its second turns them into the user your app sees: ```ts title="src/token-auth.ts" import { @@ -33,20 +42,84 @@ export const signInWithTokens = (tokens: { }) => tokenAuth.signIn(tokens); ``` +`signIn` takes tokens only, and your refresh callback returns tokens only. +Without the second argument, the claims are the user. + +## What changes + Reading the user from the token changes a few things: +- **The user is read from every token:** on sign-in, on each refresh, from + tokens another tab saved, and on every load. Only the tokens are saved, so + the user is read again each time the session is restored. - **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 - object in a JSON response to the same degree. Pass `{ decode }` as the third - argument to verify or decode the token yourself. -- **Leave out claims that change on every refresh**, such as `exp`, `iat`, or - `jti`, so the user stays the same object across refreshes. +- **Locking isn't available.** A locked session shows its user without + opening its tokens, so [locking](/docs/client/locking) needs a user schema. + `createAuth` throws `INVALID_OPTIONS` when you pass both. - **For backends you control.** OAuth providers can change their access token format without notice. +## Keep the mapping stable + +The mapping runs every time a token is read, so it has to give the same user +for the same claims: + +- **Keep it pure and synchronous.** Don't fetch or read the clock in it. +- **Leave out claims that change on every refresh,** such as `exp`, `iat` or + `jti`. Then the user stays the same object across refreshes, and + components that compare users don't re-render. + +## When the token can't be read + +A token that isn't a readable JWT, or whose claims the schema rejects, fails +with `USER_VALIDATION_FAILED`. What happens next depends on where the token +came from: + +| The token came from… | What happens | +| -------------------------- | ---------------------------------------------------------------------------------------- | +| `signIn` | `signIn` rejects, and the current session stays. | +| The saved session, on load | The user is signed out, and `state.error` shows the error. | +| Another tab | The user is signed out, and `state.error` shows the error. | +| A refresh | The refresh fails with that error, and the session is kept, as after any failed refresh. | + +## Verify the token on a server + +By default, the claims are read without checking the token's signature. That +suits a browser, which trusts a user object in a JSON response from its own +backend just as much. On a server, such as with +[server sessions](/docs/server-rendering), verify the token: pass a `decode` +function as the third argument: + +```ts title="src/verified-user.ts" +import { fromAccessToken } from "@monarcode/session-kit"; +import { z } from "zod"; + +// Your own check, with your JWT library: it throws for a bad signature. +declare function verifyJwt(accessToken: string): Promise; + +export const verifiedUser = fromAccessToken( + z.object({ sub: z.string(), email: z.string() }), + (claims) => ({ id: claims.sub, email: claims.email }), + { decode: verifyJwt }, +); +``` + +`decode` returns the claims, and the schema checks them as before. It may +return a promise, as `verifyJwt` does. In a browser, that stops a saved +session from showing before the first render. + The [`tanstack-start-spa`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa) and [`react-router-data`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-data) -examples read their user this way. +examples read their user from the access token. + +## Next steps + +- [Signing in and out](/docs/client/signing-in-and-out): what `signIn` does + with the tokens. +- [Refresh](/docs/configuration/refresh): return tokens from your refresh + callback, and handle a failed refresh. +- [`fromAccessToken` reference](/docs/reference/core#fromaccesstoken): its + arguments and options. diff --git a/site/content/docs/(latest)/configuration/debugging.mdx b/site/content/docs/(latest)/configuration/debugging.mdx index 9714c89..b24737c 100644 --- a/site/content/docs/(latest)/configuration/debugging.mdx +++ b/site/content/docs/(latest)/configuration/debugging.mdx @@ -3,24 +3,50 @@ title: Debugging description: Log what the client does, or send each event to your error reporting, without exposing tokens. --- -`createAuth`'s `debug` option reports what the client does: restores, -refreshes and why they ran, timers, storage operations and how long they -took, other tabs' changes, state changes, and what ended a session. Use it to -find out why a session ended, or why a refresh ran. +A user was signed out and you don't know why, or a refresh ran when you +didn't expect one. `createAuth`'s `debug` option reports what the client +does, so you can follow it step by step: + +- restores, and refreshes with the reason they ran; +- timers; +- storage operations, and how long they took; +- other tabs' changes; +- state changes, and what ended a session. + +This page shows how to log these events, send them to your error reporting, +and keep tokens out of them. ## Log to the console -To log each event as one `console.info` line, pass `debug: true`. A refresh -logs a line like this one: +To log each event as one `console.info` line, pass `debug: true`. To keep +logging out of production, pass a development flag instead, such as Vite's +`import.meta.env.DEV` or Expo's `__DEV__`. + +Each line starts with `[session-kit:] : `, where +`` is your client's `name`. Any details follow as an object, which the +console formats. For example, a sign-in followed by an early refresh logs +lines like these in Node.js, among others: ```text -[session-kit:my-app] refresh: started (proactive) { sessionId: "…", reason: "proactive" } +[session-kit:my-app] sign-in: signed in { sessionId: '54940f07-…' } +[session-kit:my-app] timer: early refresh fired +[session-kit:my-app] refresh: started (proactive) { + sessionId: '54940f07-…', + reason: 'proactive' +} +[session-kit:my-app] refresh: saved new tokens { + sessionId: '54940f07-…', + durationMs: 3, + expiresInMs: 900000 +} ``` +A browser console shows the same lines, with each object ready to expand. + ## Send events to your error reporting -To receive each event instead of logging it, pass a function. For example, to -leave breadcrumbs in your error reporting: +To receive each event instead of logging it, pass a function. For example, +to leave breadcrumbs in your error reporting: ```ts title="src/debug.ts" import type { AuthDebug } from "@monarcode/session-kit"; @@ -40,21 +66,33 @@ export const debug: AuthDebug = (event) => }); ``` -## Tokens and user data +## Keep tokens and user data out -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` or `issues`. +By default, 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` 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 `{ log, sensitive }`, where `log` is your function. -## What stays stable +## Filter on the event type An event's `type` is one of a fixed set, such as `"refresh"` or `"storage"`, -so you can filter on it. The wording of `message` and the fields in `data` -may change in any release. +so you can filter on it. [`AuthDebugType`](/docs/reference/core#authdebugtype) +lists them all. The wording of `message` and the fields in `data` can change +in any release, so read them, but don't match on them. + +A store can add its own events through the optional `debug` member of +[`AuthStorage`](/docs/reference/core#authstorage). They arrive with the type +`"storage"`, beside the client's own storage events. `secureStorage()` uses +it to report, for example, a saved session it removed after a reinstall, as +the [Expo guide](/docs/setups/expo#debugging) shows. + +## Next steps -A storage adapter can add its own events through the optional `debug` member -of `AuthStorage`, as [`secureStorage()`](/docs/setups/expo#debugging) does. +- [Errors](/docs/configuration/errors): show the failures the log reports to + your users. +- [Refresh](/docs/configuration/refresh): see when each kind of refresh runs. +- [`AuthDebugEvent` reference](/docs/reference/core#authdebugevent): every + field an event carries. diff --git a/site/content/docs/(latest)/configuration/errors.mdx b/site/content/docs/(latest)/configuration/errors.mdx index 5a2b2ea..eb819c7 100644 --- a/site/content/docs/(latest)/configuration/errors.mdx +++ b/site/content/docs/(latest)/configuration/errors.mdx @@ -1,24 +1,50 @@ --- title: Errors -description: How Session kit's errors reach your app, how to show them to users, and the storage failures that need your decision. +description: Where Session kit's errors appear, 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 shows -how to match on them, how to turn them into messages for your users, and the -storage failures you need to handle. +Sooner or later a refresh fails because your backend is down, or the browser +refuses to save the session. Your app needs to notice, and tell the user +something useful. Every error from Session kit's own logic is an +`AuthError`, with a `code` you can match on. -## Error codes +This page shows where errors appear, how to turn them into messages, and the +failures that need a decision from you. -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. +## Where errors appear + +A failure shows up in one of two places, or in both: + +- **The call rejects** when you asked for something the client couldn't do, + such as `signIn` with a user your schema rejects. +- **`state.error` shows it** when the session itself is affected, such as a + refresh that failed. Your components read it with `useAuth`, so it reaches + the screen even when no call of yours was waiting. + +Here's where each common failure appears: + +| When… | The call rejects | `state.error` shows it | +| ------------------------------------------------------- | --------------------------------------------------------------------- | ---------------------- | +| `signIn` or `updateUser` gets a user the schema rejects | Yes | No | +| `unlock()` fails with `UNLOCK_FAILED` | Yes | No | +| An early refresh fails in the background | No call is waiting | Yes | +| A refresh the session needed fails | Yes, every call waiting for it, such as `getSession()` or `authFetch` | Yes | +| The saved session can't be read | Yes, every call that needs it, such as `getSession()` or `retry()` | Yes | +| The session can't be saved | Yes, the call that saved it, such as `signIn` | Yes | +| The saved session can't be cleared on sign-out | Yes, `signOut()` | Yes | +| `revoke` fails after a sign-out | No: `signOut()` resolves | Yes, `REVOKE_FAILED` | +| Another tab saves a user this tab's schema rejects | No call is waiting | Yes | + +`state.error` holds the latest failure. The next successful change clears +it, such as a refresh that works, a sign-in or a sign-out. While a retry +runs, the error stays until the retry succeeds. ## Show errors to users -An error's `cause` holds whatever failed underneath, such as the error your -refresh callback threw. To keep messages out of your components, map codes -to your own wording: +Match on an error's `code`, not its message, which can change in any +release. [Error codes](/docs/reference/error-codes) lists every code and what +it means. To keep wording out of your components, map codes to your own +messages: ```ts title="src/error-message.ts" import { AuthError, type AuthErrorCode } from "@monarcode/session-kit"; @@ -35,22 +61,89 @@ export function errorMessage(error: unknown): string { } ``` -`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. +Then show `state.error` near the top of your app, with a way to try again +when access is `unavailable`: + +```tsx title="src/session-alert.tsx" +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; + +import { errorMessage } from "./error-message.js"; + +export function SessionAlert() { + const { status, error } = useAuth(); + const client = useAuthClient(); + if (!error) return null; + return ( +
+

{errorMessage(error)}

+ {status === "unavailable" && ( + + )} +
+ ); +} +``` + +`retry()` rejects again if it fails, and the new failure shows in +`state.error`, so the button can ignore the rejection. + +An error's `cause` holds whatever failed underneath, such as the error your +refresh callback threw. Log it, or send it to your error reporting. + +A few failures pass through unchanged, so they usually aren't `AuthError`s, +and `errorMessage` shows their own message: + +- `authFetch` passes on the failures of `fetch` and `Request`, such as a + network error. +- With server rendering, the browser client's `signIn` passes on what your + sign-in function threw. ## Handle storage failures -Three storage failures need a decision from you: +Storage can fail: a full disk, a browser that blocks storage, or an iOS +keychain that's locked. Each of these three failures needs 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. + `getSession()` or `retry()` reads it again. Show a **Try again** button + that calls `retry()`, as `SessionAlert` does. +- **Storage can't be written.** The client signs the user out, clears the + saved session, and publishes the error. That way, no one stays signed in + to a session that would vanish on reload. This happens on a refresh too, + when its new tokens can't be saved: on iOS, a refresh while the keychain is + locked signs the user out. Show the error, and let the user sign in again. - **Storage can't be cleared.** Sign-out still takes effect in this tab, but `signOut()` rejects and `state.error` keeps the error. The saved credentials could restore the session on reload, so call `signOut()` again - once storage works. + after storage works again. + +## Saved sessions the client can't use + +Sometimes storage works, but the session it holds can't be used. When the +client restores such a session, it signs the user out and clears it: + +- **A malformed saved session**, such as one edited by hand, gives + `INVALID_SESSION` in `state.error`. +- **A saved user your schema rejects**, such as after a deploy that changed + the schema, gives `USER_VALIDATION_FAILED` in `state.error`. See + [User schemas](/docs/configuration/user-schemas#change-the-schema-safely) + to avoid it. +- **A session past `maxAge`**, or saved in another format by an older or + newer version of Session kit, signs out with no error. Running out is + routine, as + [Storage](/docs/configuration/storage#how-long-a-saved-session-lasts) + explains. + +In each case, the user signs in again. + +## Next steps + +- [Error codes](/docs/reference/error-codes): what each code means, and + which calls give it. +- [Refresh](/docs/configuration/refresh#when-a-refresh-fails): what happens + when a refresh fails, and how long the failure lasts. +- [Debugging](/docs/configuration/debugging): log what the client did before + an error appeared. diff --git a/site/content/docs/(latest)/configuration/expiry.mdx b/site/content/docs/(latest)/configuration/expiry.mdx index 1174fae..0dbdd6f 100644 --- a/site/content/docs/(latest)/configuration/expiry.mdx +++ b/site/content/docs/(latest)/configuration/expiry.mdx @@ -3,30 +3,17 @@ title: Expiry description: How the client finds out when the access token expires, and which of your backend's answers to prefer. --- -The client refreshes the access token before it expires, so it needs to know -when that is. This page explains where it reads the expiry from, and which -field to send. +The client refreshes the access token before it expires, so it reads when +that is from your tokens. Your backend can say so in a few ways: a lifetime +in the sign-in response, a fixed time, or claims inside a JWT. -## Where the expiry comes from - -The client takes the expiry from the first of these that your tokens have: +This page shows where the client reads the expiry from, which field to send, +and what happens when there's none. -1. `expiresIn`, in seconds as in OAuth, or `expiresAt`, in Unix - milliseconds. -2. A JWT access token's `exp` and `iat` claims, as a lifetime. -3. A JWT access token's `exp` claim alone, as a time. +## Send the token's lifetime -Send `expiresIn` when your backend gives a lifetime, as most do. The client -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 -`INVALID_SESSION` error. See [`Tokens`](/docs/reference/core#tokens) for -each field. - -To map an OAuth-style response to `Tokens`, pass `expires_in` as -`expiresIn`: +Most backends answer with a lifetime, such as OAuth's `expires_in`. Pass it +as `expiresIn`, in seconds: ```ts title="src/tokens.ts" import type { Tokens } from "@monarcode/session-kit"; @@ -44,6 +31,28 @@ export const toTokens = (body: TokenResponse): Tokens => ({ }); ``` +The client counts `expiresIn` from when it receives the tokens, so a wrong +device clock doesn't matter. Send `expiresAt`, in Unix milliseconds, only +when your backend gives no lifetime. + +Pass `expiresIn` or `expiresAt`, not both. Tokens with both are an +`INVALID_SESSION` error. See [`Tokens`](/docs/reference/core#tokens) for +each field. + +## Where the expiry comes from + +When your tokens hold more than one of these, the client uses the first it +finds: + +1. `expiresIn` or `expiresAt`. +2. A JWT access token's `exp` and `iat` claims, as a lifetime, when `exp` is + later than `iat`. +3. A JWT access token's `exp` claim alone, as a time. + +A JWT with `iat` works like `expiresIn`: the client counts the lifetime from +when it receives the token. So if your access token is a JWT with both +claims, you don't need to send an expiry at all. + ## Fixed times and device clocks `expiresAt` and a JWT's `exp` alone are fixed times, which the client @@ -55,4 +64,13 @@ it with `INVALID_SESSION`. When the client can't tell when the token expires, it uses the token until your API rejects it. [`authFetch`](/docs/client/requests) then refreshes after -the 401. +the 401. There's no early refresh, since there's nothing to count down to. + +## Next steps + +- [Refresh](/docs/configuration/refresh): see when the client refreshes, and + what it does when a refresh fails. +- [Authenticated requests](/docs/client/requests): send the access token + with each request, and refresh after a 401. +- [`Tokens` reference](/docs/reference/core#tokens): every field `signIn` + and your refresh callback take. diff --git a/site/content/docs/(latest)/configuration/index.mdx b/site/content/docs/(latest)/configuration/index.mdx index 79ac59c..58c9657 100644 --- a/site/content/docs/(latest)/configuration/index.mdx +++ b/site/content/docs/(latest)/configuration/index.mdx @@ -3,27 +3,32 @@ title: Configuring the client description: Every option createAuth takes, with a page for each part of the client you can configure. --- -`createAuth` builds the client from a few options. This section explains each -one, for when the defaults in [Getting started](/docs/getting-started) no -longer fit your app. +The client from [Getting started](/docs/getting-started) sets a few +options and leaves the rest to their defaults. When your app outgrows them, +because your backend sends tokens differently, sessions must last longer, or +you need to see why a user was signed out, the options passed to +`createAuth` are where you change it. + +This page lists every option, and the pages in this section explain each +part of the client in turn. ## Options `createAuth` takes three required options and five optional ones: -| 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. | +| 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, the user is signed out when the access token expires or your API rejects it. | +| `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 lasts](/docs/configuration/storage#how-long-a-saved-session-lasts), in seconds. Default: 30 days, counted 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. | -`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` +`createAuth` throws an `AuthError` with the code `INVALID_OPTIONS` when it +can't use an option, such as a `name` with other characters, or a `maxAge` that isn't a positive whole number. ## Pages in this section @@ -35,12 +40,12 @@ tokens, saves the session, follows other tabs, and reports what happens. + +## Next steps + +- [Refresh](/docs/configuration/refresh): check that your refresh callback + tells a rejected token from an outage. +- [Storage](/docs/configuration/storage): choose where the session is saved, + and for how long. +- [Errors](/docs/configuration/errors): show failed refreshes and storage + problems to your users. diff --git a/site/content/docs/(latest)/configuration/refresh.mdx b/site/content/docs/(latest)/configuration/refresh.mdx index 8e11367..c9f461f 100644 --- a/site/content/docs/(latest)/configuration/refresh.mdx +++ b/site/content/docs/(latest)/configuration/refresh.mdx @@ -3,52 +3,127 @@ title: Refresh description: What the refresh callback's results mean, when a refresh runs, and why an outage never signs anyone out. --- -`createAuth`'s `refresh` option is a callback that exchanges the refresh -token for new tokens. This page explains what its results mean and when the -client calls it. For a callback to start from, see `refresh` in -[Getting started](/docs/getting-started#1-talk-to-your-backend). +Access tokens last minutes, and users stay for hours. `createAuth`'s +`refresh` option is a callback that exchanges the refresh token for new +tokens, so the user stays signed in when the access token expires. + +This page shows what the callback should return, when the client calls it, +and what happens when it fails. The callback in +[Getting started](/docs/getting-started#1-talk-to-your-backend) is a good +place to start. ## What the callback returns -The callback ends in one of three ways, and the client handles each -differently: +The callback tells the client one of three things: here are new tokens, the +backend rejected the refresh token, or the backend couldn't answer. For +example, against DummyJSON: + +```ts title="src/refresh.ts" +import type { RefreshFn } from "@monarcode/session-kit"; + +import { API } from "./backend.js"; + +type RefreshBody = { accessToken: string; refreshToken: string }; + +export const refresh: RefreshFn = async ({ refreshToken, signal }) => { + const response = await fetch(`${API}/auth/refresh`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ refreshToken }), + signal, + }); + // The backend rejected the refresh token: sign the user out. + if (response.status === 401 || response.status === 403) return null; + // Anything else is an outage: keep the session. + if (!response.ok) throw new Error(`Refresh failed (${response.status})`); + const body = (await response.json()) as RefreshBody; + return { accessToken: body.accessToken, refreshToken: body.refreshToken }; +}; +``` + +Pass it as `refresh` when you create the client. Here's what the client does +with each result: | The callback | What the client does | | -------------- | -------------------------------------------------------------------------------------------------------------------------- | | Returns tokens | Saves them. A refresh token or user it leaves out keeps the current one. | -| Returns `null` | Treats the refresh token as rejected: signs the user out and clears storage. | +| Returns `null` | Treats the refresh token as rejected: signs the user out and clears the saved session. | | Throws | Treats it as an outage: keeps the session and reports `REFRESH_FAILED`. See [When a refresh fails](#when-a-refresh-fails). | -When the client can tell -[when the new access token expires](/docs/configuration/expiry), the token -must last at least five seconds. A shorter one is an `INVALID_SESSION` error. - Return `null` only when your backend rejected the refresh token, such as with a 401. Throw for anything else, such as a network error or a 500, so that an outage doesn't sign anyone out. To sign the user out on every failure, return -`null` instead of throwing. +`null` instead of throwing. An `AuthError` you throw keeps its own code. + +The client also checks the tokens and the user you return. It refuses them +in these cases, and counts the refresh as failed, with the session kept: + +- When the client can tell + [when the new access token expires](/docs/configuration/expiry), the token + must last at least five seconds. A shorter one, or one that has already + expired, fails with `INVALID_SESSION`. +- Tokens with both `expiresIn` and `expiresAt` fail with `INVALID_SESSION`. +- The access token your API rejected, returned again, fails with + `INVALID_SESSION`. +- A user that the [user schema](/docs/configuration/user-schemas) rejects + fails with `USER_VALIDATION_FAILED`. + +These keep their own code in `state.error`, rather than `REFRESH_FAILED`. ## When a refresh runs The client refreshes at one of three moments: -- **Early.** While the client is mounted, 60 seconds before the access token - expires, or halfway through when the token lasts under two minutes. It - tries once per token. If that fails, the token stays usable until it - expires. +- **Early.** While the client is mounted, it refreshes 60 seconds before the + access token expires. When less than two minutes are left, it refreshes + halfway through the time that's left instead. It tries once per token. - **At expiry, or after a 401.** `status` is `refreshing` while it runs, and the user stays on screen. -- **On request.** `auth.refresh()` runs one now. +- **On request.** `auth.refresh()` runs one straight away. It rejects with + `REFRESH_FAILED` when there's nothing to refresh with: no `refresh` option, + or no refresh token. + +Only one refresh runs at a time. A request that needs one while it runs +waits for it, and tabs take turns, as [Tabs](/docs/configuration/tabs) +explains. + +Without a `refresh` option or a refresh token, there's nothing to refresh +with. The user is signed out, with no error, when the access token expires +or your API rejects it. ## When a refresh fails -If a refresh the session needed fails, `status` becomes `unavailable`. -`getSession()` then rejects with the same error until you call `auth.retry()`, -or the user signs in or out. Guards that run again therefore can't start a -refresh loop. +What a failure means depends on whether the access token still works. + +If an early refresh fails, the access token stays usable until it expires. +The user stays `authenticated`, and `state.error` shows the failure, usually +`REFRESH_FAILED`. When the token expires, the client refreshes again. + +If a refresh the session needed fails, because the access token expired or +was rejected, `status` becomes `unavailable`. The saved session is kept, so +access can come back without a new sign-in. `getSession()` rejects with the +same error until one of these happens: + +- You call `auth.retry()` or `auth.refresh()`. +- The user signs in or out. +- Another tab saves new tokens. + +Guards that run again therefore can't start a refresh loop. To offer the +user a way out, show a **Try again** button that calls `auth.retry()`, as +[Errors](/docs/configuration/errors) shows. ## Deadlines -The client gives each refresh, and each check of a user, 15 seconds. The -callback's `signal` aborts when that time runs out or when the session -changes, such as on sign-out. Pass it to `fetch`. +The client gives each refresh 15 seconds. The callback's `signal` aborts +when that time runs out, or when the session changes, such as on sign-out. +Pass it to `fetch`, as the example does. A refresh that runs out of time +fails like an outage, with `REFRESH_FAILED`. + +## Next steps + +- [Expiry](/docs/configuration/expiry): make sure the client can tell when the + access token expires, so it can refresh early. +- [Errors](/docs/configuration/errors): show a failed refresh to the user, + and let them try again. +- [Authenticated requests](/docs/client/requests): see how `authFetch` + refreshes after a 401. diff --git a/site/content/docs/(latest)/configuration/storage.mdx b/site/content/docs/(latest)/configuration/storage.mdx index f6e6367..0bad96c 100644 --- a/site/content/docs/(latest)/configuration/storage.mdx +++ b/site/content/docs/(latest)/configuration/storage.mdx @@ -1,44 +1,66 @@ --- title: Storage -description: Where the client saves the session, from localStorage to the device's secure store or your own. +description: Where the client saves the session, how long a saved session lasts, and how to write your own store. --- -`createAuth`'s `storage` option chooses where the client saves the session. -This page helps you pick a built-in store, or write your own. +A user who reloads the page, or opens your app the next day, expects to +still be signed in. That works because the client saves the session, and +`createAuth`'s `storage` option chooses where. -## Built-in stores +This page helps you pick a built-in store, set how long a saved session +lasts, or write a store of your own. + +## Pick a store The `storage` option takes one of Session kit's stores, or any object that implements `AuthStorage`: -| Storage | Saved in | Use it for | -| --------------------------------- | ----------------------------------------- | ---------------------------------------------------- | -| `webStorage()` | `localStorage` | Browsers. One session, shared by every tab. | -| `webStorage({ area: "session" })` | `sessionStorage` | One session per tab, ending with the tab. | -| `secureStorage()` | The iOS keychain, or encrypted on Android | Expo apps. From `@monarcode/session-kit/expo`. | -| `memoryStorage()` | Memory | Tests, and sessions that shouldn't outlive the page. | -| Your own `AuthStorage` | Anywhere | Another store. Its operations may return promises. | +| Storage | Saved in | Use it for | +| --------------------------------- | ----------------------------------------------------------- | ---------------------------------------------------- | +| `webStorage()` | `localStorage` | Browsers. One session, shared by every tab. | +| `webStorage({ area: "session" })` | `sessionStorage` | One session per tab, ending with the tab. | +| `secureStorage()` | The iOS keychain, or encrypted with an Android Keystore key | Expo apps. From `@monarcode/session-kit/expo`. | +| `memoryStorage()` | Memory | Tests, and sessions that shouldn't outlive the page. | +| Your own `AuthStorage` | Anywhere | Another store. Its operations can return promises. | -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. +`secureStorage()` splits a large session across several keys, since some +iOS releases refuse long values. Its +[reference](/docs/reference/expo#securestorage) has the details. -## Rotating refresh tokens +### Use localStorage with rotating refresh tokens -If your backend rotates refresh tokens, use `localStorage`, not -`sessionStorage`. A browser copies `sessionStorage` into a duplicated tab, and -into a window opened with `window.open`. Both then start with the same -refresh token but never see each other's saves. The second to refresh sends a -spent token and is signed out. With reuse detection on the backend, both are. +If your backend rotates refresh tokens, issuing a new one with each refresh, +use `localStorage`, not `sessionStorage`. -## Write your own store +A browser copies `sessionStorage` into a duplicated tab, and into a window +opened with `window.open`. Both then start with the same refresh token but +never see each other's saves. The second to refresh sends a spent token and +is signed out. With reuse detection on the backend, both are. + +## How long a saved session lasts + +A saved session lasts 30 days from the last time it was saved. To change +that, pass `maxAge` to `createAuth`, in whole seconds: `7 * 24 * 60 * 60` for +a week. + +Every save starts the count again, and the client saves at each sign-in, +refresh and profile update. A user who comes back within `maxAge` finds the +session restored, and one who's been away longer signs in again. -An `AuthStorage` needs three operations: `get`, `set` and `remove`. Each can -return a promise. `set` also receives `expiresAt`: when the saved session -stops being valid, `maxAge` after this save, in Unix milliseconds. +The client checks `maxAge` when it restores a saved session, such as on a +reload. Each save records its expiry, so a lower `maxAge` applies to a saved +session from its next save. A session saved longer ago isn't restored: the client clears it, and +the user is signed out without an error. So is a session saved in another +format by an older or newer version of Session kit. -For example, to save the session in a key-value store your app already has, -which removes each entry when it expires: +`maxAge` must be a positive whole number. Anything else makes `createAuth` +throw `INVALID_OPTIONS`. + +## Write your own store + +To save the session somewhere else, write an `AuthStorage`. For example, to +save it in a key-value store your app already has, which removes each entry +when it expires: ```ts title="src/storage.ts" import type { AuthStorage } from "@monarcode/session-kit"; @@ -55,15 +77,31 @@ declare const store: { export const kvStorage: AuthStorage = { get: async (key) => (await store.get(key)) ?? null, - // The store drops the session itself once it's no longer valid. + // The store drops the session itself when it's no longer valid. set: (key, value, { expiresAt }) => store.put(key, value, { expiresAt }), remove: (key) => store.delete(key), }; ``` -The client runs your store's operations one at a time, in the order it -issued them. A store that several tabs share also needs `subscribe` and -`lock`, so that [tabs follow each other](/docs/configuration/tabs). See +An `AuthStorage` needs three operations: `get`, `set` and `remove`. Here's +what to know about them: + +- Each can return a promise. A `get` that answers synchronously lets a saved + session restore before the first render. +- `set` also receives `expiresAt`: when the saved session stops being valid, + `maxAge` after this save, in Unix milliseconds. +- The client runs your store's operations one at a time, in the order it + issued them, so a store that answers out of order is still safe. +- To report a failure, throw or reject. The client turns it into a + `PERSISTENCE_FAILED` error, and + [Handle storage failures](/docs/configuration/errors#handle-storage-failures) + explains what happens next. + +A store that several tabs share needs two more members, as `webStorage()` +has. `subscribe` tells the client when another tab changes the session, so +that [tabs follow each other](/docs/configuration/tabs). `lock` lets the tabs +take turns to refresh. An optional `debug` member adds your store's own +events to the [debug log](/docs/configuration/debugging). See [`AuthStorage`](/docs/reference/core#authstorage) for each member. ## What the client saves @@ -72,3 +110,11 @@ The client saves the tokens and the user in one `: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. + +## Next steps + +- [Tabs](/docs/configuration/tabs): see how tabs that share `localStorage` + stay in step. +- [Errors](/docs/configuration/errors#handle-storage-failures): decide what + to show when storage can't be read, written or cleared. +- [Security](/docs/security): compare how each place protects the tokens. diff --git a/site/content/docs/(latest)/configuration/tabs.mdx b/site/content/docs/(latest)/configuration/tabs.mdx index 3dd5c54..94d6b6f 100644 --- a/site/content/docs/(latest)/configuration/tabs.mdx +++ b/site/content/docs/(latest)/configuration/tabs.mdx @@ -1,36 +1,77 @@ --- title: Tabs -description: How open tabs follow each other's sign-ins and sign-outs, and share one refresh between them. +description: How open tabs follow each other's sign-ins and sign-outs, and take turns to refresh. --- -In a browser, each open tab runs its own client over the same saved session. -This page explains how the tabs stay in step, and how they share one refresh. +Users open your app in several tabs, then sign out in one and expect the +others to follow. In a browser with `webStorage()`, which saves the session +in `localStorage`, each open tab runs its own client over the same saved +session, and the tabs keep each other in step. -## Sign-ins and sign-outs +This page shows what tabs share, how they take turns to refresh, and the +setups where tabs don't follow each other. -While the client is [mounted](/docs/client), each tab follows the others -through `storage` events: +## How tabs stay in step + +While the client is [mounted](/docs/client), each tab follows the changes +the others save: - A sign-out in one tab signs out every tab. - 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. +A tab hears about these through the browser's `storage` events, which the +store's `subscribe` member listens to. A tab that mounts again checks the +saved session, so it catches up on anything it missed while unmounted. + +Tabs share a session only when they share the store: + +- **`webStorage({ area: "session" })`** gives each tab its own + `sessionStorage`, so each tab has its own session and nothing to follow. +- **`memoryStorage()`** keeps the session in one page, and no other tab can + read it. +- **Your own store** needs a `subscribe` member that reports other tabs' + changes, as [Storage](/docs/configuration/storage#write-your-own-store) + explains. ## One refresh at a time -The client refreshes under the `:auth:refresh` -[Web Lock](https://developer.mozilla.org/docs/Web/API/Web_Locks_API). One tab -at a time spends the refresh token, and the others reuse the tokens it saved. -Rotating refresh tokens therefore work with several tabs open. +Tabs that share a session also share its refresh token. The client refreshes +under the `:auth:refresh` +[Web Lock](https://developer.mozilla.org/docs/Web/API/Web_Locks_API), through +the store's `lock` member. One tab at a time spends the refresh token, and +the others reuse the tokens it saved. 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. +## Server rendering + +With server rendering, the session lives in a cookie, and the browser's +`createMirrorAuth` clients don't use storage events. When one tab signs in or +out, it tells the others over a `BroadcastChannel`, and they ask the server +for the session again. [Server rendering](/docs/server-rendering) has the +rest. + +## Locking + +With [`locking`](/docs/client/locking), tabs stop following each other. A +sign-in, sign-out or lock in one tab doesn't reach the others. With rotating +refresh tokens, two tabs that refresh the same session can sign one of them +out. Locking is meant for native apps, which have no tabs. + ## Expo apps -An Expo app has one JavaScript context, so it has no tabs to follow and needs -no lock. In a browser, [`locking`](/docs/client/locking) stops tabs from -following each other. +An Expo app has one JavaScript context, so it has no tabs to follow and +needs no lock. `secureStorage()` has no `subscribe` or `lock` member for +that reason. + +## Next steps + +- [Storage](/docs/configuration/storage): choose a store, or write one that + several tabs can share. +- [Refresh](/docs/configuration/refresh): see when a refresh runs, and what + happens when it fails. +- [Server rendering](/docs/server-rendering): keep the session on the server + instead. diff --git a/site/content/docs/(latest)/configuration/user-schemas.mdx b/site/content/docs/(latest)/configuration/user-schemas.mdx index 5e5c02a..5511988 100644 --- a/site/content/docs/(latest)/configuration/user-schemas.mdx +++ b/site/content/docs/(latest)/configuration/user-schemas.mdx @@ -1,16 +1,45 @@ --- title: User schemas -description: How the user schema checks every user the client accepts, and what restoring a session requires of it. +description: How the user schema checks every user the client accepts, and what restoring a session asks of it. --- -The schema you pass as `createAuth`'s `user` option checks each user the -client accepts and gives the user its type. This page explains when it runs, -and the two rules it must follow so that a saved session can be restored. +Your backend answers a sign-in with the user's fields, and your components +render them. The schema you pass as `createAuth`'s `user` option sits +between the two: it checks each user the client accepts, and gives the user +its type in your code. + +This page shows when the schema runs, the two rules it must follow so that a +saved session can be restored, and how to change it without signing anyone +out. 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 the access token](/docs/client/users-from-tokens). +## The user's type + +`createAuth` infers the user's type from the schema's output. With the +schema from [Getting started](/docs/getting-started#2-create-the-client), +hover `user` to see it: + +```ts title="src/user-type.ts" +import type { SessionOf, UserOf } from "@monarcode/session-kit"; + +import { auth } from "./auth.js"; + +const { user } = auth.state.get(); +// ^? + +// The same types, named for the rest of your code. +export type AppUser = UserOf; +export type AppSession = SessionOf; +``` + +`user` is `null` unless the session is `authenticated`, `refreshing` or +`locked`, and checking `status` narrows it. To type the hooks from `@monarcode/session-kit/react`, register the +client one time, as +[Getting started](/docs/getting-started#4-read-the-session-in-react) shows. + ## When the schema runs The client runs the schema on every user it accepts: @@ -24,29 +53,11 @@ The client runs the schema on every user it accepts: It keeps a frozen copy of each user it accepts. To change the user, call [`updateUser`](/docs/client/updating-the-user). -## The user's type - -`createAuth` infers the user's type from the schema's output. Hover `user` to -see it: - -```ts twoslash -import { createAuth, memoryStorage } from "@monarcode/session-kit"; -import { z } from "zod"; - -const auth = createAuth({ - name: "my-app", - user: z.object({ id: z.number(), firstName: z.string() }), - storage: memoryStorage(), -}); - -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. +An asynchronous schema, such as one with an async refinement, has 15 seconds +to answer each check, and a check that takes longer fails. During a refresh, +the check shares the refresh's 15 seconds. It also means a +saved session can't be restored before the first render, as the +[Introduction](/docs) explains: the app shows `initializing` first. ## Rules for restoring @@ -60,11 +71,29 @@ when it restores the session. That sets two rules for the schema: 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. +shows up right away, not as users being signed out on their next reload. + +## Change the schema safely + +A deploy can change the schema so that it rejects users saved before it. +When the client restores such a user, it signs them out and clears the saved +session, with `USER_VALIDATION_FAILED` in `state.error`. The user then signs +in again. + +To add a field without signing anyone out, make it optional or give it a +default. A saved user without the field still passes, and a default fills +it in on restore. + +A user that another tab saved, and that this tab's schema rejects, signs +every tab out the same way. That can happen while two versions of your app +are open in different tabs. [Errors](/docs/configuration/errors) covers this +and the other saved sessions the client can't use. -## Users the schema rejects +## Next steps -A deploy can change the schema so that it rejects users saved before it. The -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`. +- [Users from the access token](/docs/client/users-from-tokens): read the + user from a JWT instead of a schema. +- [Updating the user](/docs/client/updating-the-user): change the signed-in + user's fields after sign-in. +- [Errors](/docs/configuration/errors): show `USER_VALIDATION_FAILED` and + the other errors to your users. diff --git a/site/content/docs/(latest)/effect.mdx b/site/content/docs/(latest)/effect.mdx deleted file mode 100644 index bfcd619..0000000 --- a/site/content/docs/(latest)/effect.mdx +++ /dev/null @@ -1,695 +0,0 @@ ---- -title: Effect and effetch -description: Use the session as an Effect service, call your API with effetch, and cache each account's data with effetch-query. ---- - -In this guide, you use the session from an [Effect](https://effect.website) -app. You read it as a service, call your API with -[effetch](https://github.com/monarcode/effetch), and cache each account's data -with [effetch-query](https://github.com/monarcode/effetch-query). Two entry -points do this: - -- **`@monarcode/session-kit/effect`** gives your Effects the session as the - `Auth` service. It wraps the client you already have, so React, your router - and your Effects share one session. Its Effects fail with a tagged - `AuthFailure`, which `Effect.catchTag` handles like your own errors. -- **`@monarcode/session-kit/effetch`** has the `sessionBearer` plugin. It - sends the access token with each effetch call, and refreshes after a 401. - -A complete app is in -[`examples/tanstack-start-spa-effetch`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa-effetch). -Every export is listed in the reference for -[`./effect`](/docs/reference/effect) and [`./effetch`](/docs/reference/effetch). - -## Before you begin - -- Read [Getting started](/docs/getting-started). This guide builds the same - app with Effect Schemas and effetch. [Refresh](/docs/configuration/refresh) - and [Errors](/docs/configuration/errors) explain how the client renews and - fails. -- Know Effect's generators, services and layers. - -## Installation - -To install the packages, run the following command: - -```npm -npm install @monarcode/session-kit effect @monarcode/effetch -``` - -`effect` and `@monarcode/effetch` are optional peer dependencies of Session -kit. `./effect` and `./effetch` need `effect` 4.1 or newer, and `./effetch` -also needs `@monarcode/effetch` 0.1.0-rc.4 or newer. - -To [cache with effetch-query](#cache-with-effetch-query), also install -effetch-query 0.1.0-rc.4 or newer, and its `@effect/atom-react` peer for -React: - -```npm -npm install @monarcode/effetch-query @effect/atom-react -``` - -## 1. Describe your backend - -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: - -```ts title="src/backend.ts" -import * as Schema from "effect/Schema"; - -export const API_BASE_URL = "https://dummyjson.com"; - -export const SessionUser = Schema.Struct({ - id: Schema.Finite, - username: Schema.String, - email: Schema.String, - firstName: Schema.String, -}); - -/** The user, as Session kit's `user` option takes it. */ -export const userSchema = Schema.toStandardSchemaV1(SessionUser); - -export const SessionTokens = Schema.Struct({ - accessToken: Schema.String, - refreshToken: Schema.String, -}); - -/** DummyJSON returns the user's fields beside the tokens. */ -export const SignInResponse = Schema.Struct({ - ...SessionTokens.fields, - ...SessionUser.fields, -}); - -export const ApiError = Schema.Struct({ message: Schema.String }); -``` - -## 2. Refresh with effetch - -The refresh gets an effetch client of its own, made with its own -`Fetch.make`, for two reasons: - -- The app's API client - [waits for a refresh](#6-call-your-api-with-effetch) after a 401. A refresh - sent through it would wait for itself. -- The app's runtime is built on the session client this refresh belongs to, - so the refresh can't run in it. It provides the `FetchHttpClient` effetch - sends with itself. - -`refreshSession` resolves `null` when the backend rejects the refresh token, -and fails for anything else, as [Refresh](/docs/configuration/refresh) -explains. The server uses it too: - -```ts title="src/refresh.ts" -import { 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 }).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) => - Effect.runPromise( - Effect.gen(function* () { - const client = yield* makeRefreshClient; - return yield* client.post("/auth/refresh", { - body: { refreshToken }, - output: SessionTokens, - }); - }).pipe( - Fetch.catchStatus([401, 403], () => Effect.succeed(null)), - Effect.provide(FetchHttpClient.layer), - ), - { signal }, - ); -``` - -## 3. Register the client - -Create the client as usual, then register its type once, so every Effect -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 { userSchema } from "./backend.js"; -import { refreshSession } from "./refresh.js"; - -export const auth = createAuth({ - name: "app", - user: userSchema, - storage: webStorage(), - refresh: ({ refreshToken, signal }) => refreshSession(refreshToken, signal), -}); - -declare module "@monarcode/session-kit" { - interface Register { - auth: typeof auth; - } -} -``` - -## 4. Provide the service - -`Auth.layer` provides the client as the `Auth` service. It doesn't mount the -client: `AuthProvider`, `SessionGate` or the router adapters still do that. -To provide it, create the layer once: - -```ts title="src/layer.ts" -import { Auth } from "@monarcode/session-kit/effect"; - -import { auth } from "./auth.js"; - -export const AuthLive = Auth.layer(auth); -``` - -In tests, provide a layer over another client instead. - -## 5. Read the session - -`Auth.session` is the current session. If the access token expired, it -refreshes first. It fails with `UNAUTHENTICATED` when no one is signed in. -For code that also runs signed out, `Auth.sessionOption` gives -`Option.none()` instead: - -```ts title="src/greeting.ts" -import { Auth } from "@monarcode/session-kit/effect"; -import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; - -import { AuthLive } from "./layer.js"; - -export const greeting = Auth.sessionOption.pipe( - Effect.map( - Option.match({ - onNone: () => "Welcome", - onSome: (session) => `Welcome back, ${session.user.firstName}`, - }), - ), -); - -export const showGreeting = () => - Effect.runPromise(Effect.provide(greeting, AuthLive)); -``` - -## 6. Call your API with effetch - -Make the app's API client as an effetch `Fetch.Service`: the backend's base -URL, its error body, and the plugins every call goes through. The -`sessionBearer` plugin does what [`createAuthFetch`](/docs/client/requests) -does: it sends the access token, and refreshes after a 401. - -Put `sessionBearer` last, so that a retry reads the current token. Give it the -client's `baseUrl`, since the token goes only to that origin. The client's -layer then needs the `Auth` service, once: - -```ts title="src/api.ts" -import { Fetch } from "@monarcode/effetch"; -import { retry } from "@monarcode/effetch/plugins"; -import { sessionBearer } from "@monarcode/session-kit/effetch"; -import * as HttpClient from "effect/http/HttpClient"; -import * as Layer from "effect/Layer"; - -import { API_BASE_URL, ApiError } from "./backend.js"; - -export class ApiClient extends Fetch.Service()("ApiClient", { - baseUrl: API_BASE_URL, - defaultError: ApiError, - plugins: [retry(), sessionBearer({ baseUrl: API_BASE_URL, optional: true })], -}) {} - -/** The API client, over whichever `Auth` is provided. */ -export const ApiClientLive = ApiClient.layer.pipe( - // Effect adds tracing headers to every request, which fail the preflight - // of an API that doesn't allow them. - Layer.provide(Layer.succeed(HttpClient.TracerPropagationEnabled)(false)), -); -``` - -Calls can fail with `AuthFailure`. When one client serves public and private -endpoints, as this one does, give the plugin `optional: true`: a call made -while signed out is then sent without a token, and a private endpoint -answers with its own 401. A locked client still fails with `LOCKED`. - -effetch's own `bearer` plugin can refresh after a 401 too, with its -`refresh` option, but it doesn't know the session. `sessionBearer` reads it -from Session kit. A call fails with `SESSION_CHANGED` if the account changes -while it runs, and a second 401 signs the user out. Its -[reference](/docs/reference/effetch#sessionbearer) lists the rest. - -After a refresh, `bearer` sends a request of any method again, a `POST` -included. `sessionBearer` sends only a `GET` or `HEAD` again, as -`createAuthFetch` does, and returns the 401 of any other request for you to -retry. - -Effect code yields the client and calls its methods, such as `get` and -`post`. The sign-in call skips the plugin with `sessionBearer: false`, -because it's how the user gets a token. To read the current user and to sign -in, add `src/user.ts`: - -```ts title="src/user.ts" -import * as Effect from "effect/Effect"; - -import { ApiClient } from "./api.js"; -import { SessionUser, SignInResponse } from "./backend.js"; - -export const currentUser = Effect.gen(function* () { - const client = yield* ApiClient; - return yield* client.get("/auth/me", { output: SessionUser }); -}); - -export const login = (username: string, password: string) => - Effect.gen(function* () { - const client = yield* ApiClient; - return yield* client.post("/auth/login", { - body: { username, password }, - output: SignInResponse, - plugins: { sessionBearer: false }, - }); - }); -``` - -With [another HTTP client](/docs/client/other-http-clients), use -`Auth.credentials`, the access token. It's kept apart from `Auth.session`, so -code that only needs the user never holds a token. After a 401, -`Auth.renew(credentials)` gets new credentials once for every caller. - -## 7. Run Effects in one runtime - -Compose the app's layers in one place: the API client, the session, and the -`FetchHttpClient` effetch sends with, each made once: - -```ts title="src/runtime.ts" -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import * as Layer from "effect/Layer"; -import * as ManagedRuntime from "effect/ManagedRuntime"; - -import { ApiClientLive } from "./api.js"; -import { AuthLive } from "./layer.js"; - -const AppLayer = ApiClientLive.pipe( - Layer.provideMerge(AuthLive), - Layer.provide(FetchHttpClient.layer), -); - -/** One runtime for the app's lifetime. */ -export const appRuntime = ManagedRuntime.make(AppLayer); -export type AppRuntime = typeof appRuntime; -``` - -Run every Effect with this runtime, as in -`appRuntime.runPromise(currentUser)`, instead of providing `AuthLive` as -step 5 does. - -## Handle failures - -Every `Auth` Effect fails with `AuthFailure`. Its `code` is the client's -[`AuthErrorCode`](/docs/configuration/errors), and its `cause` is the -`AuthError` itself. Misuse, which the client reports as `INVALID_OPTIONS`, is -a defect rather than a failure. - -For example, to show "Guest" when no one is signed in: - -```ts title="src/account.ts" -import { Auth } from "@monarcode/session-kit/effect"; -import * as Effect from "effect/Effect"; - -export const accountName = Auth.session.pipe( - Effect.map((session) => session.user.firstName), - Effect.catchTag("AuthFailure", (failure) => - failure.code === "UNAUTHENTICATED" - ? Effect.succeed("Guest") - : Effect.fail(failure), - ), -); -``` - -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 - -`Auth.updateUser` takes the user, or an Effect that fetches it. The session is -captured before the Effect runs, so a profile fetched for one account fails -with `SESSION_CHANGED` instead of landing on another. The Effect's own -failure comes through unchanged: - -```ts title="src/profile.ts" -import { Auth } from "@monarcode/session-kit/effect"; - -import { currentUser } from "./user.js"; - -export const reloadProfile = Auth.updateUser(currentUser); -``` - -## Watch the session - -`Auth.changes` is a `Stream` of the client's `AuthState`: the current state, -then every change, until the stream ends: - -```ts title="src/watch.ts" -import { Auth } from "@monarcode/session-kit/effect"; -import * as Effect from "effect/Effect"; -import * as Stream from "effect/Stream"; - -export const logStatus = Auth.changes.pipe( - Stream.map((state) => state.status), - Stream.changes, - Stream.runForEach((status) => Effect.log(`Auth is ${status}`)), -); -``` - -## Cache with effetch-query - -effetch-query caches endpoints: a route and its schemas, defined with -`Fetch.endpoint`, which it calls with the app's API client. Its queries and -mutations run with the app's runtime, so components never run an Effect by -hand. `fromClient` reads the client's `defaultError` from its class: - -```ts title="src/query.ts" -import { QueryClient } from "@monarcode/effetch-query"; -import { fromClient } from "@monarcode/effetch-query/effetch"; -import type * as ManagedRuntime from "effect/ManagedRuntime"; - -import { ApiClient } from "./api.js"; -import { appRuntime, type AppRuntime } from "./runtime.js"; - -declare module "@monarcode/effetch-query" { - interface Register { - readonly services: ManagedRuntime.ManagedRuntime.Services; - } -} - -export const api = fromClient(ApiClient); - -export const makeQueryClient = () => QueryClient.make({ runtime: appRuntime }); -``` - -A cache must not outlive the account that filled it. Let `QueryProvider` own -its client (`make` instead of `client`) and pass the session ID as `resetKey`. -Signing out or switching accounts then disposes the client, with its cache -and its requests in flight, and renders the tree with a new one: - -```tsx title="src/query-provider.tsx" -import type { ReactNode } from "react"; - -import { QueryProvider } from "@monarcode/effetch-query/react"; -import { useAuth } from "@monarcode/session-kit/react"; - -import { makeQueryClient } from "./query.js"; - -export function Queries({ children }: { children: ReactNode }) { - const account = useAuth((state) => state.sessionId ?? "signed-out"); - return ( - - {children} - - ); -} -``` - -Render it inside `AuthProvider` or `SessionGate`, above every `Suspense` -boundary. A refresh, a failed refresh or a profile update keeps the -`sessionId`, and so the cache. So does locking: queries that need a token -fail with `LOCKED` until `unlock()`, then refetch as usual. Until a saved -session is restored, the key is `"signed-out"`, and the restore replaces -that client. - -A feature defines the endpoints it caches, and its components use the -queries and mutations made of them: - -```tsx title="src/features/account.tsx" -import { 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"; - -import { SessionUser, SignInResponse } from "../backend.js"; -import { api } from "../query.js"; - -const signInMutation = api.mutation( - Fetch.endpoint("POST /auth/login", { - input: Schema.Struct({ username: Schema.String, password: Schema.String }), - output: SignInResponse, - }), - { plugins: { sessionBearer: false } }, -); - -const profileQuery = api.query( - Fetch.endpoint("GET /auth/me", { output: SessionUser }), -); - -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 ( - - ); -} - -export function Email() { - const result = useQuery(profileQuery()); - return AsyncResult.match(result, { - onInitial: () =>

Loading…

, - onFailure: () =>

Couldn't load your profile.

, - onSuccess: ({ value }) =>

{value.email}

, - }); -} -``` - -The owned client is for the browser and React Native. With server rendering, -give `QueryProvider` a `client` per request instead, as effetch-query's -README describes. Make it on the server over that request's session, as -[Render queries on the server](#render-queries-on-the-server) shows. - -## On the server - -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)). -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 -`src/backend.ts`, `src/refresh.ts`, `src/api.ts` and `src/user.ts` from the -earlier steps. - -In a server-rendered app, the registered client is the browser's -`createMirrorAuth` client, not `createAuth`. Each framework's guide sets it -up: [TanStack Start](/docs/setups/tanstack-start), -[Next.js](/docs/setups/next) and -[React Router](/docs/setups/react-router-ssr). - -To create the server's session engine, add `src/server/auth.ts`: - -```ts title="src/server/auth.ts" -import { createServerAuth } from "@monarcode/session-kit/server"; - -import { userSchema } from "../backend.js"; -import { refreshSession } from "../refresh.js"; - -declare const secret: string; // from the environment - -export const serverAuth = createServerAuth({ - name: "app", - user: userSchema, - 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 -uses it. Build those per request, and keep a runtime for what belongs to no -user: - -```ts title="src/server/run.ts" -import { Auth } from "@monarcode/session-kit/effect"; -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 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 = (session: ServerSession) => - ApiClientLive.pipe(Layer.provideMerge(Auth.layer(session))); - -/** Runs `effect` with the request's `session`. */ -export function runRequest( - session: ServerSession, - effect: Effect.Effect, -): Promise { - return serverRuntime.runPromise( - Effect.provide(effect, requestLayer(session)), - ); -} -``` - -The runtime has no `Auth` and no API client, so an Effect that needs them -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 request's session, in the server -function, action or handler: - -```ts title="src/server/profile.ts" -import { currentUser } from "../user.js"; -import type { ServerSession } from "./auth.js"; -import { runRequest } from "./run.js"; - -// TanStack Start: startAuth(serverAuth). React Router: -// 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); -``` - -### Sign in on the server - -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 { login } from "../user.js"; -import type { ServerSession } from "./auth.js"; -import { runRequest } from "./run.js"; - -export async function signIn( - session: ServerSession, - username: string, - password: string, -) { - const { accessToken, refreshToken, ...user } = await runRequest( - session, - login(username, password), - ); - return session.signIn({ accessToken, refreshToken, user }); -} -``` - -### Render queries on the server - -To render a page with its data, make a query cache per request, on the -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 * 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 = (session: ServerSession) => - QueryClient.make({ - layer: requestLayer(session).pipe(Layer.provide(FetchHttpClient.layer)), - }); -``` - -Give it no `memoMap` ([Things to know](#things-to-know) says why). Prefetch -before the page starts streaming, or refresh in middleware first, since a -cookie set once streaming has begun is lost. In the browser, the cache is the -owned one from [Cache with effetch-query](#cache-with-effetch-query), over -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` - 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` - 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 - your app. A module the server imports, such as the one that defines - `ApiClientLive` or the user schema, mustn't also create a browser client or - its layer, or the server loads it too. -- **Name the services in `runRequest`'s signature,** as `src/server/run.ts` - 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, 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` - 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. - `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. -- **`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, a request's -session signs in and updates the user. - -## Next steps - -- [Server sessions](/docs/server-rendering/server-sessions): how the server - keeps the session in a cookie, and refreshes it. -- [Locking](/docs/client/locking): lock a native app's session. `Auth.session` - and `sessionBearer` then fail with `LOCKED` until it's unlocked. -- [Other HTTP clients](/docs/client/other-http-clients): the calls - `sessionBearer` is built on, for any other client. diff --git a/site/content/docs/(latest)/effect/browser.mdx b/site/content/docs/(latest)/effect/browser.mdx new file mode 100644 index 0000000..507b4f8 --- /dev/null +++ b/site/content/docs/(latest)/effect/browser.mdx @@ -0,0 +1,628 @@ +--- +title: Use Effect in the browser +description: Read the session as an Effect service, call your API with effetch, and cache each account's data with effetch-query, in a browser or Expo app. +--- + +Your app runs its logic as [Effect](https://effect.website) programs, and +they need to know who is signed in and to send the access token with every +API call. This guide sets that up in a single-page app or an Expo app. Your +Effects read the session as the `Auth` service, call your API with +[effetch](https://github.com/monarcode/effetch), and, if you want, cache each +account's data with +[effetch-query](https://github.com/monarcode/effetch-query). + +The guide builds the app from [Getting started](/docs/getting-started) again, +with Effect Schemas and effetch. [Effect and effetch](/docs/effect) explains +the two entry points it uses. The browser half of this guide, with TanStack +Router and a user read from the access token, runs in +[`examples/tanstack-start-spa-effetch`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa-effetch). + +With server rendering, your framework's guide creates and registers the +browser's client in place of step 3. Build the layer and runtime of steps 4 +and 7 where that client is created. +[Use Effect on the server](/docs/effect/server) covers the server's side. + +## Before you begin + +- Read [Getting started](/docs/getting-started). + [Refresh](/docs/configuration/refresh) and + [Errors](/docs/configuration/errors) explain how the client renews and + fails. +- Know Effect's generators, services and layers. +- Effect asks for TypeScript 5.9 or newer. +- To cache with effetch-query, you need React 19: its React bindings don't + support React 18. [Compatibility](/docs/reference/compatibility) lists + every version. + +## Installation + +To install the packages, run the following command: + +```npm +npm install @monarcode/session-kit effect @monarcode/effetch +``` + +`effect` and `@monarcode/effetch` are optional peer dependencies of Session +kit. `./effect` and `./effetch` need `effect` 4.1 or newer, and `./effetch` +also needs `@monarcode/effetch` 0.1.0-rc.4 or newer. effetch-query has its +own install, in [Cache with effetch-query](#cache-with-effetch-query). + +## 1. Describe your backend + +Start with 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. The file holds schemas only, with no client, so the rest of the app +and the [server](/docs/effect/server) can import them from one place: + +```ts title="src/backend.ts" +import * as Schema from "effect/Schema"; + +export const API_BASE_URL = "https://dummyjson.com"; + +export const SessionUser = Schema.Struct({ + id: Schema.Finite, + username: Schema.String, + email: Schema.String, + firstName: Schema.String, +}); + +/** The user, as Session kit's `user` option takes it. */ +export const userSchema = Schema.toStandardSchemaV1(SessionUser); + +export const SessionTokens = Schema.Struct({ + accessToken: Schema.String, + refreshToken: Schema.String, +}); + +/** DummyJSON returns the user's fields beside the tokens. */ +export const SignInResponse = Schema.Struct({ + ...SessionTokens.fields, + ...SessionUser.fields, +}); + +export const ApiError = Schema.Struct({ message: Schema.String }); +``` + +## 2. Refresh with effetch + +The refresh exchanges the refresh token for new tokens. It gets an effetch +client of its own, made with its own `Fetch.make`: + +```ts title="src/refresh.ts" +import { 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 }).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) => + Effect.runPromise( + Effect.gen(function* () { + const client = yield* makeRefreshClient; + return yield* client.post("/auth/refresh", { + body: { refreshToken }, + output: SessionTokens, + }); + }).pipe( + Fetch.catchStatus([401, 403], () => Effect.succeed(null)), + Effect.provide(FetchHttpClient.layer), + ), + { signal }, + ); +``` + +The refresh can't use the app's API client or its runtime, for two reasons: + +- After a 401, the app's API client + [waits for a refresh](#6-call-your-api-with-effetch). A refresh sent + through it would wait for itself. +- The app's runtime is built on the session client this refresh belongs + to, so the refresh can't run in it. It provides its own + `FetchHttpClient`, which effetch sends requests with. + +`refreshSession` resolves `null` when the backend rejects the refresh token, +which signs the user out. It fails for anything else, such as an outage, and +the session is kept for a retry. [Refresh](/docs/configuration/refresh) +explains both. The server uses this function too. + +## 3. Register the client + +Create the client as usual, then register its type once, so that every +Effect 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 { userSchema } from "./backend.js"; +import { refreshSession } from "./refresh.js"; + +export const auth = createAuth({ + name: "app", + user: userSchema, + storage: webStorage(), + refresh: ({ refreshToken, signal }) => refreshSession(refreshToken, signal), +}); + +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} +``` + +## 4. Provide the service + +`Auth.layer` provides the client as the `Auth` service. Create the layer +once: + +```ts title="src/layer.ts" +import { Auth } from "@monarcode/session-kit/effect"; + +import { auth } from "./auth.js"; + +export const AuthLive = Auth.layer(auth); +``` + +The layer doesn't mount the client. `AuthProvider`, `SessionGate` or the +router adapters still do that, as your setup guide shows. + +In tests, provide a layer over another `createAuth` client with the same +`user`, such as one that keeps the session in memory. After you register +your client, `Auth.layer` takes only a client of that type: + +```ts title="src/test-layer.ts" +import { createAuth, memoryStorage } from "@monarcode/session-kit"; +import { Auth } from "@monarcode/session-kit/effect"; + +import { userSchema } from "./backend.js"; + +export const testAuth = createAuth({ + name: "test", + user: userSchema, + storage: memoryStorage(), +}); + +export const AuthTest = Auth.layer(testAuth); +``` + +## 5. Read the session + +`Auth.session` is the current session. If the access token has expired, it +refreshes first, and it fails with `UNAUTHENTICATED` when no one is signed +in. For code that also runs signed out, `Auth.sessionOption` gives +`Option.none()` instead: + +```ts title="src/greeting.ts" +import { Auth } from "@monarcode/session-kit/effect"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +export const greeting = Auth.sessionOption.pipe( + Effect.map( + Option.match({ + onNone: () => "Welcome", + onSome: (session) => `Welcome back, ${session.user.firstName}`, + }), + ), +); +``` + +`greeting` needs the `Auth` service to run. Step 7 runs it with the rest of +the app's services. + +## 6. Call your API with effetch + +Make the app's API client as an effetch `Fetch.Service`: the backend's base +URL, its error body, and the plugins every call goes through. The +`sessionBearer` plugin sends the access token, and gets a new one after a +401: + +```ts title="src/api.ts" +import { Fetch } from "@monarcode/effetch"; +import { retry } from "@monarcode/effetch/plugins"; +import { sessionBearer } from "@monarcode/session-kit/effetch"; +import * as HttpClient from "effect/http/HttpClient"; +import * as Layer from "effect/Layer"; + +import { API_BASE_URL, ApiError } from "./backend.js"; + +export class ApiClient extends Fetch.Service()("ApiClient", { + baseUrl: API_BASE_URL, + defaultError: ApiError, + plugins: [retry(), sessionBearer({ baseUrl: API_BASE_URL, optional: true })], +}) {} + +/** The API client, over whichever `Auth` is provided. */ +export const ApiClientLive = ApiClient.layer.pipe( + // Effect adds tracing headers to every request, which fail the preflight + // of an API that doesn't allow them. + Layer.provide(Layer.succeed(HttpClient.TracerPropagationEnabled)(false)), +); +``` + +Here's what the plugin's options and place do: + +- **Last in `plugins`.** A retry then reads the current token. +- **`baseUrl`.** The token goes only to that origin, so give it the + client's `baseUrl`. +- **`optional: true`.** One client here serves public and private + endpoints. A call made while signed out is then sent without a token, and + a private endpoint answers with its own 401. A locked client still fails + with `LOCKED`. +- **The `Auth` service.** The client's layer needs it, once. Calls don't. + +`sessionBearer` handles a 401 the way +[Authenticated requests](/docs/client/requests#after-a-401) describes for +`createAuthFetch`. One rule matters most: if a `GET` or `HEAD` sent again +with the new token gets a 401 too, the user is signed out. For an API that +also answers 401 for other reasons, such as a missing permission, pass +`signOutOnRepeated401: false`. Its failures and a few other details differ +from `createAuthFetch`'s, as +[How `sessionBearer` differs from `createAuthFetch`](/docs/effect#how-sessionbearer-differs-from-createauthfetch) +lists. + +Effect code yields the client and calls its methods, such as `get` and +`post`. To read the current user and to sign in, add `src/user.ts`: + +```ts title="src/user.ts" +import * as Effect from "effect/Effect"; + +import { ApiClient } from "./api.js"; +import { SessionUser, SignInResponse } from "./backend.js"; + +export const currentUser = Effect.gen(function* () { + const client = yield* ApiClient; + return yield* client.get("/auth/me", { output: SessionUser }); +}); + +export const login = (username: string, password: string) => + Effect.gen(function* () { + const client = yield* ApiClient; + return yield* client.post("/auth/login", { + body: { username, password }, + output: SignInResponse, + plugins: { sessionBearer: false }, + }); + }); +``` + +The sign-in call skips the plugin with `sessionBearer: false`, because it's +how the user gets a token. + +After a refresh, `sessionBearer` sends only a `GET` or `HEAD` again. A +`POST` or any other method that got the 401 fails with an `HttpError` whose +`status` is 401, after the token is renewed. Where sending it twice is safe, +catch that status with `Fetch.catchStatus` and call again, since the next +call reads the new token: + +```ts title="src/cart.ts" +import { Fetch } from "@monarcode/effetch"; +import * as Effect from "effect/Effect"; + +import { ApiClient } from "./api.js"; + +export const addToCart = (userId: number, productId: number) => { + const add = Effect.gen(function* () { + const client = yield* ApiClient; + return yield* client.post("/auth/carts/add", { + body: { userId, products: [{ id: productId, quantity: 1 }] }, + }); + }); + // The 401 refreshed the token, so one more try uses the new one. + return add.pipe(Fetch.catchStatus(401, () => add)); +}; +``` + +With [another HTTP client](/docs/client/other-http-clients), use +`Auth.credentials`, the access token. It's kept apart from `Auth.session`, +so code that only needs the user never holds a token. After a 401, +`Auth.renew(credentials)` gets new credentials once for every caller. + +## 7. Run Effects in one runtime + +Compose the app's layers in one place: the API client, the session, and the +`FetchHttpClient` effetch sends requests with, each made once: + +```ts title="src/runtime.ts" +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; +import * as ManagedRuntime from "effect/ManagedRuntime"; + +import { ApiClientLive } from "./api.js"; +import { AuthLive } from "./layer.js"; + +const AppLayer = ApiClientLive.pipe( + Layer.provideMerge(AuthLive), + Layer.provide(FetchHttpClient.layer), +); + +/** One runtime for the app's lifetime. */ +export const appRuntime = ManagedRuntime.make(AppLayer); +export type AppRuntime = typeof appRuntime; +``` + +Run every Effect with this runtime. For example, +`appRuntime.runPromise(greeting)` resolves `"Welcome back, Emily"` while +`emilys` is signed in, and `appRuntime.runPromise(currentUser)` fetches her +profile. + +## 8. Sign in and out + +Session kit doesn't sign users in: your backend checks the password. Ask it +with `login`, then save what it returns with `Auth.signIn`, which takes what +the client's `signIn` takes. `Auth.signOut` signs out: + +```ts title="src/sign-in.ts" +import { Auth } from "@monarcode/session-kit/effect"; +import * as Effect from "effect/Effect"; + +import { appRuntime } from "./runtime.js"; +import { login } from "./user.js"; + +export const signIn = (username: string, password: string) => + appRuntime.runPromise( + Effect.gen(function* () { + const response = yield* login(username, password); + const { accessToken, refreshToken, ...user } = response; + yield* Auth.signIn({ accessToken, refreshToken, user }); + }), + ); + +export const signOut = () => appRuntime.runPromise(Auth.signOut); +``` + +Your sign-in form calls `signIn("emilys", "emilyspass")`. A wrong password +fails `login` with an `HttpError`, and no one is signed in. When the +response can't be saved, `Auth.signIn` fails with an `AuthFailure`, such as +`USER_VALIDATION_FAILED` for a user your schema rejects. +[Signing in and out](/docs/client/signing-in-and-out) explains what each +call does to the session. + +That completes the setup. The rest of this page covers failures, the user +and changes to the session, then optional caching. + +## Handle failures + +Every `Auth` Effect fails with `AuthFailure`, whose `code` is the client's +`AuthErrorCode`, and misuse is a defect. +[How Effects fail](/docs/effect#how-effects-fail) explains both. Handle it +with `Effect.catchTag`, as you do your own errors. For example, to show +"Guest" when no one is signed in: + +```ts title="src/account.ts" +import { Auth } from "@monarcode/session-kit/effect"; +import * as Effect from "effect/Effect"; + +export const accountName = Auth.session.pipe( + Effect.map((session) => session.user.firstName), + Effect.catchTag("AuthFailure", (failure) => + failure.code === "UNAUTHENTICATED" + ? Effect.succeed("Guest") + : Effect.fail(failure), + ), +); +``` + +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 + +`Auth.updateUser` takes the user, or an Effect that fetches it: + +```ts title="src/profile.ts" +import { Auth } from "@monarcode/session-kit/effect"; + +import { currentUser } from "./user.js"; + +export const reloadProfile = Auth.updateUser(currentUser); +``` + +The client notes the session before the Effect runs, so a profile fetched +for one account never lands on another: + +- **The session changes first.** The fetch is interrupted, and the update + fails with `SESSION_CHANGED`. +- **The fetch takes more than 15 seconds.** It's interrupted, and the update + fails with `USER_VALIDATION_FAILED`, whose `cause` is the timeout. +- **The fetch fails.** Its own failure, such as an `HttpError`, comes + through unchanged. + +[Updating the user](/docs/client/updating-the-user) covers the rest, such as +a user your schema rejects. + +## Watch the session + +`Auth.changes` is a `Stream` of the client's `AuthState`: the current state, +then every change, until the stream ends: + +```ts title="src/watch.ts" +import { Auth } from "@monarcode/session-kit/effect"; +import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; + +export const logStatus = Auth.changes.pipe( + Stream.map((state) => state.status), + Stream.changes, + Stream.runForEach((status) => Effect.log(`Auth is ${status}`)), +); +``` + +## Cache with effetch-query + +effetch-query keeps what your endpoints return in a cache, and your +components read it from there. The steps in this section are optional, and +need React 19. To install effetch-query 0.1.0-rc.4 or newer, with its +`@effect/atom-react` peer for React, run the following command: + +```npm +npm install @monarcode/effetch-query @effect/atom-react +``` + +### Optional: Create the query client + +effetch-query calls endpoints, each a route and its schemas defined with +`Fetch.endpoint`, through the app's API client. Its queries and mutations +run with the app's runtime, so components never run an Effect by hand. +`fromClient` reads the client's `defaultError` from its class: + +```ts title="src/query.ts" +import { QueryClient } from "@monarcode/effetch-query"; +import { fromClient } from "@monarcode/effetch-query/effetch"; +import type * as ManagedRuntime from "effect/ManagedRuntime"; + +import { ApiClient } from "./api.js"; +import { appRuntime, type AppRuntime } from "./runtime.js"; + +declare module "@monarcode/effetch-query" { + interface Register { + readonly services: ManagedRuntime.ManagedRuntime.Services; + } +} + +export const api = fromClient(ApiClient); + +export const makeQueryClient = () => QueryClient.make({ runtime: appRuntime }); +``` + +### Optional: Give each account its own cache + +A cache must not outlive the account that filled it. Let `QueryProvider` own +its client (`make` instead of `client`) and pass the session ID as +`resetKey`. Signing out or switching accounts then disposes the client, +with its cache and any requests still running, and renders the tree with a +new one: + +```tsx title="src/query-provider.tsx" +import type { ReactNode } from "react"; + +import { QueryProvider } from "@monarcode/effetch-query/react"; +import { useAuth } from "@monarcode/session-kit/react"; + +import { makeQueryClient } from "./query.js"; + +export function Queries({ children }: { children: ReactNode }) { + const account = useAuth((state) => state.sessionId ?? "signed-out"); + return ( + + {children} + + ); +} +``` + +Render `Queries` inside `AuthProvider`, above every `Suspense` boundary. On +Expo, that's inside the `AuthProvider` around `SessionGate`. With TanStack +Router, there's no `AuthProvider`: import `useAuth` from +`@monarcode/session-kit/tanstack-router` instead, and render `Queries` in +the root route, as the example app does. + +The cache follows the session ID, so these keep it: + +- **A refresh, a failed refresh or a profile update.** The session ID + stays the same. +- **Locking.** The session ID stays the same. Queries that need a token + fail with `LOCKED` until `unlock()`, then refetch on their next trigger, + such as the app coming back into focus. + +Until a saved session is restored, the key is `"signed-out"`, and the +restore replaces that client. + +The owned client is for the browser and React Native. On the server, give +`QueryProvider` a `client` per request instead, as +[Use Effect on the server](/docs/effect/server#5-optional-render-queries-on-the-server) +shows. In the browser, an app with server rendering keeps the owned client, +over its mirror client. + +### Optional: Query and mutate endpoints + +A feature defines the endpoints it caches, and its components use the +queries and mutations made of them: + +```tsx title="src/features/account.tsx" +import { 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"; + +import { SessionUser, SignInResponse } from "../backend.js"; +import { api } from "../query.js"; + +const signInMutation = api.mutation( + Fetch.endpoint("POST /auth/login", { + input: Schema.Struct({ username: Schema.String, password: Schema.String }), + output: SignInResponse, + }), + { plugins: { sessionBearer: false } }, +); + +const profileQuery = api.query( + Fetch.endpoint("GET /auth/me", { output: SessionUser }), +); + +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 ( + + ); +} + +export function Email() { + const result = useQuery(profileQuery()); + return AsyncResult.match(result, { + onInitial: () =>

Loading…

, + onFailure: () =>

Couldn't load your profile.

, + onSuccess: ({ value }) =>

{value.email}

, + }); +} +``` + +The sign-in mutation saves the session with the client's own `signIn`, +which `useAuthClient` returns. With TanStack Router, import `useAuthClient` +from `@monarcode/session-kit/tanstack-router` too. + +## Next steps + +- [Use Effect on the server](/docs/effect/server): run the same Effects in + server functions and route handlers, with each request's session. +- [Effect and effetch](/docs/effect): what `Auth` covers, and how + `sessionBearer` differs from `createAuthFetch`. +- [Other HTTP clients](/docs/client/other-http-clients): the calls + `sessionBearer` is built on, for any other client. +- [Locking](/docs/client/locking): lock a native app's session. + `Auth.session` and `sessionBearer` then fail with `LOCKED` until it's + unlocked. +- [`./effect` reference](/docs/reference/effect) and + [`./effetch` reference](/docs/reference/effetch): every export. diff --git a/site/content/docs/(latest)/effect/index.mdx b/site/content/docs/(latest)/effect/index.mdx new file mode 100644 index 0000000..68adb97 --- /dev/null +++ b/site/content/docs/(latest)/effect/index.mdx @@ -0,0 +1,154 @@ +--- +title: Effect and effetch +description: Read the session as an Effect service, and call your API with effetch's sessionBearer plugin, which sends the access token and renews it after a 401. +--- + +If your app is written with [Effect](https://effect.website), your Effects +need the session too: who is signed in, and an access token for your API. +Session kit gives them both, from the same client that React and your +router use, so there's one session for all of them. Your API calls go +through [effetch](https://github.com/monarcode/effetch), with a plugin that +sends the token and gets a new one after a 401. + +This page shows what the two entry points give you and where they differ +from the rest of Session kit. To set them up, follow +[Use Effect in the browser](/docs/effect/browser), then, with server +rendering, [Use Effect on the server](/docs/effect/server). + +## What `./effect` and `./effetch` give you + +Two entry points connect Session kit to Effect: + +- **`@monarcode/session-kit/effect`** gives your Effects the session as the + `Auth` service. It wraps the client you already have, so React, your + router and your Effects share one session. `Auth.layer(auth)` provides it. +- **`@monarcode/session-kit/effetch`** has the `sessionBearer` plugin for + effetch clients. It sends the access token with each call, and gets a new + one after a 401. + +`effect` and `@monarcode/effetch` are optional peer dependencies. +[effetch-query](https://github.com/monarcode/effetch-query), which caches +each account's data, works with them but isn't needed. + +### The `Auth` service at a glance + +Here's what `Auth` gives your Effects: + +| Member | What it does | +| ------------------------- | --------------------------------------------------------------------------------------------------------------- | +| `Auth.layer(client)` | Provides the client, or on the server one request's session, as the `Auth` service. It doesn't mount it. | +| `Auth.session` | The current session, refreshed first if the access token expired. Fails with `UNAUTHENTICATED` when signed out. | +| `Auth.sessionOption` | The same, with `Option.none()` when no one is signed in. | +| `Auth.credentials` | The access token and session ID, for a request. | +| `Auth.renew(credentials)` | New credentials after your API rejected these. Calls at the same time share one refresh. | +| `Auth.signIn(input)` | Saves a new session, as the client's `signIn` does. | +| `Auth.signOut` | Signs out, as the client's `signOut` does. | +| `Auth.updateUser(input)` | Replaces the user with the one given, or with what an Effect fetches. | +| `Auth.changes` | A `Stream` of the client's state: the current state, then every change. | +| `Auth.fromAuthError` | Turns an `AuthError` from a client method `Auth` doesn't wrap into an `AuthFailure`. | + +Register your client's type once, as +[Register the client](/docs/effect/browser#3-register-the-client) shows, so +these carry your user. The [`./effect` reference](/docs/reference/effect) +lists every failure. + +## How Effects fail + +Every `Auth` Effect fails with `AuthFailure`, a tagged error that +`Effect.catchTag("AuthFailure", …)` handles like your own errors. Its +`code` is the client's [`AuthErrorCode`](/docs/configuration/errors), such +as `UNAUTHENTICATED` or `REFRESH_FAILED`. Its `cause` is the `AuthError` +itself. + +Misuse, which the client reports as `INVALID_OPTIONS`, isn't an +`AuthFailure`. The Effect dies with it instead, as a defect: it's a mistake +in the code to fix, not a failure to handle. So `AuthFailure`'s `code` is +never `INVALID_OPTIONS`. + +## Why `sessionBearer`, not effetch's `bearer` + +effetch has a `bearer` plugin of its own, which can take its token and its +refresh from `Auth`. It's built for any token, though, so +it has no rules about where the token goes. Here's what `bearer` does that +`sessionBearer` doesn't: + +- **It sends the token to any URL a call names.** An absolute URL skips the + client's `baseUrl`, and gets the token all the same. +- **It follows redirects,** so the token can follow one to another server. +- **It sends a `POST` again after a refresh,** and any other method that + got the 401. +- **It doesn't check the account.** A response to a request sent for an + account that has since signed out comes back as it is. + +`sessionBearer` sends the token only to your API's origin, and with +Effect's `FetchHttpClient` it refuses redirects. It sends only a `GET` or +`HEAD` again, and fails with `SESSION_CHANGED` rather than return a response +meant for another account. + +## How `sessionBearer` differs from `createAuthFetch` + +`sessionBearer` follows the same rules as `createAuthFetch`, which +[Authenticated requests](/docs/client/requests) explains: when the token is +sent, what happens after a 401, and when the user is signed out after a +second one. Here's what's different with `sessionBearer`: + +- **Failures are `AuthFailure`s,** in the Effect's error channel, rather + than a rejected `AuthError`. +- **A 401 it hands back is an `HttpError`.** Where `authFetch` resolves a + 401 response, such as for a `POST` after a refresh, the call fails with + an `HttpError` whose `status` is 401. A client's `statusErrors` turns it + into your own error instead. +- **Another origin dies rather than fails.** A request for another origin, + or with a username or password in its URL, dies with `INVALID_OPTIONS`, + so `Effect.catch` and `Effect.catchTag` don't see it. +- **A redirect fails as a `Fetch.NetworkError`,** with Effect's + `FetchHttpClient`, rather than a `TypeError`. On React Native before Expo + SDK 58, `fetch` follows redirects whatever it's told, so the redirected + request has already gone out. `authFetch` still refuses the response, and + `sessionBearer` returns it. Don't let your API redirect requests that + carry a token. +- **A request that already has an `Authorization` header passes + through.** While signed in, `authFetch` replaces the header. + `sessionBearer` sends the request as it is, with no token, no refresh, and + none of the checks: not the origin or redirect check, and no + `UNAUTHENTICATED`, `LOCKED` or `SESSION_CHANGED`. + +Streams, such as `api.sse` or a stream endpoint, go through the same checks +up to the response's headers. As with a body `authFetch` returns, one that's +open when the user signs out or switches accounts keeps reading until it +ends, so stop it yourself if it mustn't outlive the session. + +The [`sessionBearer` reference](/docs/reference/effetch#sessionbearer) +lists its options. + +## What `Auth` covers + +`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, a request's +session signs in and updates the user with its own methods. + +## On the server + +With server rendering, `Auth.layer` takes one request's session, so +`Auth.session`, `Auth.credentials` and `sessionBearer` work in server +functions, actions and route handlers too. There, `sessionBearer` sends the +cookie's token, and saves a renewed one after a 401. +[Use Effect on the server](/docs/effect/server) sets it up, step by step. + +## Cache with effetch-query + +effetch-query caches what your endpoints return, with a client per account, +so no account sees another's data. Its React bindings need React 19. +[Cache with effetch-query](/docs/effect/browser#cache-with-effetch-query), +on the browser guide, sets it up. + +## Next steps + +- [Use Effect in the browser](/docs/effect/browser): set up `Auth`, + `sessionBearer` and the runtime in a single-page or Expo app. +- [Use Effect on the server](/docs/effect/server): run Effects with each + request's session. +- [Authenticated requests](/docs/client/requests): the 401 rules + `sessionBearer` shares with `createAuthFetch`. diff --git a/site/content/docs/(latest)/effect/meta.json b/site/content/docs/(latest)/effect/meta.json new file mode 100644 index 0000000..d5410cb --- /dev/null +++ b/site/content/docs/(latest)/effect/meta.json @@ -0,0 +1,4 @@ +{ + "title": "Effect and effetch", + "pages": ["index", "browser", "server"] +} diff --git a/site/content/docs/(latest)/effect/server.mdx b/site/content/docs/(latest)/effect/server.mdx new file mode 100644 index 0000000..c5c12d9 --- /dev/null +++ b/site/content/docs/(latest)/effect/server.mdx @@ -0,0 +1,261 @@ +--- +title: Use Effect on the server +description: Run Effects with each request's session in server functions, actions and route handlers, sign in on the server, and render queries per request. +--- + +With server rendering, your server functions, actions and route handlers +run Effects too. There, the session is the encrypted cookie the server +keeps ([Server sessions](/docs/server-rendering/server-sessions)), and each +request has its own. This guide runs your Effects with that request's +session, so `Auth.session`, `Auth.credentials` and `sessionBearer` work on +the server as they do in the browser. `sessionBearer` sends the cookie's +access token, and saves a renewed one after a 401. + +Each framework's adapter gives one request's session (`RequestAuth`), and +`Auth.layer` takes it. The rule that shapes this page: a request's session +belongs to that request, and so does everything that uses it. + +## Before you begin + +- Follow your framework's guide, which creates the server engine and + registers the browser's `createMirrorAuth` client: + [TanStack Start](/docs/setups/tanstack-start), + [Next.js](/docs/setups/next) or + [React Router](/docs/setups/react-router-ssr). +- Follow steps 1, 2 and 6 of + [Use Effect in the browser](/docs/effect/browser). The server's files + build on the `src/backend.ts`, `src/refresh.ts`, `src/api.ts` and + `src/user.ts` they add. +- Effect asks for TypeScript 5.9 or newer. +- To render queries with effetch-query in step 5, you need React 19: its + React bindings don't support React 18. + [Compatibility](/docs/reference/compatibility) lists every version. + +## 1. Create the server engine + +On the server, the session comes from `createServerAuth`, with the user +schema the app registers and the same refresh as the browser. Your +framework's guide creates `serverAuth`. Build it from `userSchema` and +`refreshSession`, as this `src/server/auth.ts` does: + +```ts title="src/server/auth.ts" +import { createServerAuth } from "@monarcode/session-kit/server"; + +import { userSchema } from "../backend.js"; +import { refreshSession } from "../refresh.js"; + +declare const secret: string; // from the environment + +export const serverAuth = createServerAuth({ + name: "app", + user: userSchema, + secret, + refresh: ({ refreshToken, signal }) => refreshSession(refreshToken, signal), +}); + +/** One request's session, as your framework's adapter gives it. */ +export type ServerSession = ReturnType; +``` + +## 2. Run Effects per request + +Build the session's layer and the API client per request, and keep one +runtime for what belongs to no user: + +```ts title="src/server/run.ts" +import { Auth } from "@monarcode/session-kit/effect"; +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 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 = (session: ServerSession) => + ApiClientLive.pipe(Layer.provideMerge(Auth.layer(session))); + +/** Runs `effect` with the request's `session`. */ +export function runRequest( + session: ServerSession, + effect: Effect.Effect, +): Promise
{ + return serverRuntime.runPromise( + Effect.provide(effect, requestLayer(session)), + ); +} +``` + +The runtime has no `Auth` and no API client. So an Effect that needs them +doesn't compile until it goes through `runRequest`, and nothing a service +keeps outlives its request. + +## 3. Call your API from a server function + +Each framework's adapter gives the request's session in the server +function, action or handler. Pass it to `runRequest` with the Effect: + +```ts title="src/server/profile.ts" +import { currentUser } from "../user.js"; +import type { ServerSession } from "./auth.js"; +import { runRequest } from "./run.js"; + +// TanStack Start: startAuth(serverAuth). React Router: +// 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); +``` + +[A request's session](/docs/server-rendering/server-sessions#a-requests-session) +explains each adapter. + +## 4. Sign in on the server + +`Auth.signIn` and `Auth.updateUser` take what the browser client's methods +take, so they aren't available on a request's session. Sign in with the +session's own `signIn`, which takes the tokens and the user, and update the +user with its own `updateUser`. Ask your backend with an Effect, then save +what it returns with the session's `signIn`: + +```ts title="src/server/sign-in.ts" +import { login } from "../user.js"; +import type { ServerSession } from "./auth.js"; +import { runRequest } from "./run.js"; + +export async function signIn( + session: ServerSession, + username: string, + password: string, +) { + const { accessToken, refreshToken, ...user } = await runRequest( + session, + login(username, password), + ); + return session.signIn({ accessToken, refreshToken, user }); +} +``` + +## 5. Optional: Render queries on the server + +To render a page with its data from effetch-query, make a query client per +request, on the server, over that request's layer: + +```ts title="src/server/query-client.ts" +import { QueryClient } from "@monarcode/effetch-query"; +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 = (session: ServerSession) => + QueryClient.make({ + layer: requestLayer(session).pipe(Layer.provide(FetchHttpClient.layer)), + }); +``` + +Give it no `memoMap`: [Things to know](#things-to-know) says why. Pass it to +`QueryProvider` as `client` while the page renders, and dispose of it after +the page is sent. For a server that answers with a streamed `Response`, +`QueryClient.disposeAfter` does that: + +```ts title="src/server/respond.ts" +import { QueryClient } from "@monarcode/effetch-query"; + +import type { ServerSession } from "./auth.js"; +import { queryClientFor } from "./query-client.js"; + +/** `render` gives `` its tree. */ +export async function respondWithQueries( + session: ServerSession, + render: (queryClient: QueryClient.QueryClient) => Promise, +): Promise { + const queryClient = queryClientFor(session); + try { + return QueryClient.disposeAfter(queryClient, await render(queryClient)); + } catch (error) { + await queryClient.dispose(); + throw error; + } +} +``` + +Each framework has its own place for the client and its disposal, which +effetch-query's +[Frameworks](https://github.com/monarcode/effetch-query#frameworks) section +shows: + +- **TanStack Start:** make the client in `getRouter`, and + `connectQueryClient` disposes it when the request ends. +- **Next.js:** make it with React's `cache()`, and dispose of it in + `after()`. +- **React Router:** make it in middleware, and wrap the response in + `QueryClient.disposeAfter`, as `respondWithQueries` does. + +A page's render can't always save a renewed cookie: a Next.js Server +Component never can, and TanStack Start loses a cookie set after the page +starts streaming. So refresh before the page renders, in middleware or +Proxy, as each framework guide does. In TanStack Start, a prefetch that +runs before the page starts streaming can also save a renewed cookie. In +the browser, the cache is the +owned one from +[Give each account its own cache](/docs/effect/browser#optional-give-each-account-its-own-cache), +over 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` takes a request's session whose user is the registered one. + In the browser, build `Auth.layer(mirror)` where the mirror is created. + There, `Auth.signIn` needs the mirror's `signIn` option, and + `Auth.updateUser` isn't available, since the user comes from the server. + `sessionBearer` in the browser needs `clientCredentials: true` in + `createServerAuth`, or the mirror's `credentials` option + ([The access token in the browser](/docs/server-rendering/server-sessions#the-access-token-in-the-browser)). +- **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 your app. A module the server imports, such as the one + that defines `ApiClientLive` or the user schema, mustn't also create a + browser client or its layer, or the server loads it too. +- **Name the services in `runRequest`'s signature,** as `src/server/run.ts` + 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, 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` + 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. + `Auth.credentials` and `sessionBearer` fail with `REFRESH_FAILED` after + 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. + `Auth.signOut` dies there with `INVALID_OPTIONS`, so sign out in an + action or route handler. + [A request's session](/docs/server-rendering/server-sessions#a-requests-session) + lists which requests these are. +- **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. + Outside a request, it throws `INVALID_OPTIONS`. + +## Next steps + +- [Server sessions](/docs/server-rendering/server-sessions): how the server + keeps the session in a cookie, and refreshes it. +- [Effect and effetch](/docs/effect): what `Auth` covers, and how + `sessionBearer` differs from `createAuthFetch`. +- [`./effect` reference](/docs/reference/effect): `Auth.layer` and every + other export. diff --git a/site/content/docs/(latest)/faq.mdx b/site/content/docs/(latest)/faq.mdx index 573a0c6..18466f9 100644 --- a/site/content/docs/(latest)/faq.mdx +++ b/site/content/docs/(latest)/faq.mdx @@ -3,13 +3,15 @@ title: Common questions description: Short answers about refresh tokens, expiry, storing tokens, caches, bundle size, and other ways to sign in. --- -These are short answers to questions that come up when you adopt Session kit. -Each links to the page with the full answer. +These questions come up when you adopt Session kit. Each answer is short, and +links to the page that covers the subject in full. ## Do I need a refresh token? No. Without a refresh token or a `refresh` callback, the user is signed out -when the access token expires or your API rejects it. +when the access token expires, or when `authFetch` gets a 401. See +[Authenticated requests](/docs/client/requests) for what happens after a 401, +and [Refresh](/docs/configuration/refresh) to add a refresh later. ## What if my backend doesn't say when the token expires? @@ -19,8 +21,12 @@ the client looks for the expiry, and what it does when it finds none. ## Is it safe to keep tokens in `localStorage`? Any script on your origin can read them, as [Security](/docs/security) -explains. If that isn't acceptable, keep the session on the server with -[server rendering](/docs/server-rendering). +explains. If that isn't acceptable for your app, you have two options: + +- Keep the session on the server, in an `httpOnly` cookie, with + [server rendering](/docs/server-rendering). +- Keep the tokens off disk with `memoryStorage()`. The session then ends when + the page unloads. See [Storage](/docs/configuration/storage). ## How do I use it with TanStack Query, or another cache? @@ -39,11 +45,11 @@ does. ## What if some endpoints answer 401 for other reasons? -Set `signOutOnRepeated401: false` in `createAuthFetch`'s options, beside -`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). +Turn off `signOutOnRepeated401` in `createAuthFetch`'s options. A second 401 +from those endpoints then comes back to your code instead of signing the user +out. Without a refresh token or a `refresh` callback, the first 401 still +signs the user out. See +[Keep users signed in after a second 401](/docs/client/requests#keep-users-signed-in-after-a-second-401). ## How much does it add to my bundle? @@ -57,3 +63,10 @@ the server, it's about 5 kB. The routers you don't use add nothing: see Yes, through your backend. Whatever your backend does to sign a user in, Session kit starts from the tokens it answers with. See [What it doesn't do](/docs#what-it-doesnt-do). + +## Next steps + +- [Security](/docs/security): what Session kit protects, and what stays your + backend's job. +- [Compatibility](/docs/reference/compatibility): the runtimes and versions + Session kit supports. diff --git a/site/content/docs/(latest)/getting-started.mdx b/site/content/docs/(latest)/getting-started.mdx index 72f182b..67e1873 100644 --- a/site/content/docs/(latest)/getting-started.mdx +++ b/site/content/docs/(latest)/getting-started.mdx @@ -3,24 +3,27 @@ title: Getting started description: Build a small app that signs in, stays signed in across reloads and tabs, calls an API, and signs out. --- -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 web router guides -build on this app. Server-rendered apps create their client differently, so -start from [Server rendering](/docs/server-rendering) instead. +Your backend signs users in and answers with an access token and a refresh +token. In this tutorial, you build a small React app around those tokens. It +signs in, stays signed in across reloads and tabs, calls an API with the +access token, and signs out. The code signs in against [DummyJSON's auth API](https://dummyjson.com/docs/auth), a public test -backend, so it runs as written. +backend, so it runs as written. The web router guides build on this app. If +your app renders on the server, it creates its client differently: start +from [Server rendering](/docs/server-rendering) instead. ## Before you begin -In a React app, install Session kit and Zod, as -[Installation](/docs/installation) shows. +- A React app. A router is optional: step 6 links to the guide for yours. +- Session kit and Zod, installed as [Installation](/docs/installation) + shows. ## 1. Talk to your backend Session kit never calls your backend for you, so start with the two requests -you would write anyway: one that signs in, and one that exchanges a refresh +you'd write anyway. One signs in, and the other exchanges a refresh token for new tokens. Nothing in this file imports Session kit: ```ts title="src/backend.ts" @@ -71,8 +74,12 @@ export async function refresh(refreshToken: string, signal: AbortSignal) { ``` 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. +rest of the app its types. + +DummyJSON's docs add `credentials: "include"` to these requests, to send its +cookies. This file leaves it out: Session kit keeps the tokens in storage, +not in cookies, and in step 5 `authFetch` adds the access token to your API +calls. ## 2. Create the client @@ -104,15 +111,19 @@ export async function signInWithPassword(username: string, password: string) { export type AppAuth = typeof auth; ``` -`refresh` tells two failures apart. `null` means the backend rejected the -refresh token, so the user is signed out. A throw means something else failed, -so the session is kept and the error reported. That split is why an outage -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 the client one time, at module level, as this file does. If an app has +more than one client, give each its own `name`. + +`refresh` tells two failures apart, so an outage doesn't sign anyone out: + +- `null` means the backend rejected the refresh token, so the user is signed + out. +- A throw means something else failed, such as the network. The session is + kept, and the error reported. -Create the client once, at module level, as this file does. Give each client -in an app its own `name`. +[Refresh](/docs/configuration/refresh) has the details, and +[Storage](/docs/configuration/storage) lists the other places a session can +be saved. DummyJSON's tokens are JWTs, so their expiry comes from the `exp` and `iat` claims. [Expiry](/docs/configuration/expiry) covers backends that say it @@ -120,8 +131,8 @@ another way. ## 3. Add a sign-in form -`signInWithPassword` is all a form needs. The form has no Session kit code -of its own: +The form calls `signInWithPassword` from `src/auth.ts`, and has no Session +kit code of its own: ```tsx title="src/sign-in.tsx" import { useState, type FormEvent } from "react"; @@ -173,18 +184,19 @@ export function SignIn() { } ``` -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. +The form doesn't navigate after it signs in. 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 The hooks come from `@monarcode/session-kit/react`. Register your client's -type once, where you render `AuthProvider`, and they carry your user. +type one time, in the file that renders `AuthProvider`, and the hooks carry +your user's type. 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: +`user`, so it's never `null` there: ```tsx title="src/app.tsx" import { @@ -206,7 +218,7 @@ declare module "@monarcode/session-kit" { export function App() { return ( - + ); @@ -242,7 +254,7 @@ function Screen() { } /** The latest failure, such as a refresh the backend couldn't answer. */ -function AuthError() { +function AuthErrorMessage() { const error = useAuth((state) => state.error); return error ?

{error.message}

: null; } @@ -253,16 +265,25 @@ 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 - it, and re-renders only when that part changes, as `AuthError` does. -- `useAuthClient()` returns the client, for actions. + it, and re-renders only when that part changes, as `AuthErrorMessage` does. +- `useAuthClient()` returns the client, for actions such as `retry` and + `signOut`. +- `AuthErrorMessage` shows `state.error`, where failures appear. + +The buttons ignore a rejection because `AuthErrorMessage` already shows the +failure. `retry` rejects when it fails, and the failure also appears in +`state.error`. `signOut` signs the user out even when your backend can't +revoke the tokens: that failure only appears in `state.error`. `signOut` +rejects only when it can't clear the saved session. +[Errors](/docs/configuration/errors) covers where each failure appears. + +Two more helpers are useful as the app grows: + +- `isSignedIn(state)`, from `@monarcode/session-kit`, is `true` while the + status is `authenticated` or `refreshing`. Pass it to `useAuth` to read only + that: `useAuth(isSignedIn)`. - 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 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 - do. + `createAuthHooks()` instead of registering one. With [`locking`](/docs/client/locking), give `locked` a case of its own. It has a user too, but no usable access. @@ -276,8 +297,8 @@ That's a working app. To check it: ## 5. Call your API -`createAuthFetch` makes a `fetch` that sends the access token to one origin, -and to no other: +Your API wants the access token on each request. `createAuthFetch` makes a +`fetch` that adds it, and sends it to your API's origin and to no other: ```ts title="src/api.ts" import { createAuthFetch } from "@monarcode/session-kit/http"; @@ -295,13 +316,48 @@ export async function fetchProfile() { } ``` -When a request gets a 401, `authFetch` refreshes, then sends a GET or HEAD -again. Other methods are never sent twice. +When a request gets a 401, `authFetch` refreshes, then sends a `GET` or +`HEAD` again. It never sends other methods twice. [Authenticated requests](/docs/client/requests) covers the rest of its -behaviour and its options. +behavior and its options. + +To see it work, add a button that loads the profile: + +```tsx title="src/profile.tsx" +import { useState } from "react"; + +import { fetchProfile } from "./api.js"; + +export function ProfileButton() { + const [email, setEmail] = useState(""); + const [error, setError] = useState(""); + + async function load() { + setError(""); + try { + setEmail((await fetchProfile()).email); + } catch (cause) { + setError(cause instanceof Error ? cause.message : "Could not load"); + } + } + + return ( +
+ + {email &&

{email}

} + {error &&

{error}

} +
+ ); +} +``` + +Render `` in `Screen`'s signed-in case, under the welcome +message. Sign in, then select **Load my profile**. Emily's email address +appears, from a request that carried the access token. -Using ky, axios or openapi-fetch? Pass `authFetch` as the client's `fetch`: -see [Other HTTP clients](/docs/client/other-http-clients). +ky, axios and openapi-fetch can each send their requests through +`authFetch`. [Other HTTP clients](/docs/client/other-http-clients) shows +how for each one. ## 6. Protect your routes @@ -315,7 +371,7 @@ your router: framework mode with `ssr: false`. - [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. +- Without a router, you're done. Render by `status`, as `Screen` does. With Effect, the same client becomes a service: see [Effect and effetch](/docs/effect). @@ -325,3 +381,5 @@ With Effect, the same client becomes a service: see - [Using the client](/docs/client): what else the client does, such as updating the user and locking. - [Configuring the client](/docs/configuration): the rest of its options. +- [Security](/docs/security): what Session kit protects, and what stays your + backend's job. diff --git a/site/content/docs/(latest)/index.mdx b/site/content/docs/(latest)/index.mdx index 4ca6dcf..112d18b 100644 --- a/site/content/docs/(latest)/index.mdx +++ b/site/content/docs/(latest)/index.mdx @@ -1,59 +1,60 @@ --- title: Introduction -description: Define, validate, and manage your app's session from your backend's tokens, through reloads, expired tokens, other tabs, and outages. +description: Keep a React app signed in with the tokens your backend issues, through reloads, expired tokens, other tabs and outages. --- -Session kit is a schema-driven toolkit for defining, validating, and managing -the session in a React app whose own backend signs users in and issues access -and refresh tokens. You give it the tokens your backend returns, and it -manages the session from there. It supports TanStack Router and Start, React -Router, Next.js, Expo Router on iOS and Android, and Effect. +Your backend already signs users in: it checks a password and answers with +an access token and a refresh token. Session kit takes those tokens and keeps +the app signed in from there. It saves the session, restores it on reload, +refreshes tokens before they expire, keeps every tab in step, and guards your +routes. It works with plain React, TanStack Router and Start, React Router, +Next.js, Expo Router on iOS and Android, and Effect. -This page explains why it exists, what it does, and the terms the rest of the -docs use. To start using it, see [Installation](/docs/installation). +This page shows what Session kit takes care of, what it leaves to you, and +the few terms the rest of the docs use. To start using it, see +[Installation](/docs/installation). ## Why Session kit -Signing in is the easy part. Your backend checks a password and answers with -an access token and a refresh token, and for a moment the app is done. +Signing in is the easy part. Then the user reloads the page. The access token +expires halfway through a form. They open a second tab, sign out of one, and +switch accounts in the other. The backend goes down for a minute, just as a +refresh was due. -Then the user reloads the page. The access token expires halfway through a -form. They open a second tab, sign out of one, and switch accounts in the -other. The backend goes down for a minute, just as a refresh was due. - -Every app with its own backend has to get these moments right. It usually -takes a few hundred lines spread across an auth context, a fetch wrapper, and -the route guards, and one or two cases stay missing until a user finds them. -Session kit is that code, written once and tested with the routers and -frameworks it supports. +Every app with its own backend has to get these moments right. The code for +them usually ends up spread across an auth context, a fetch wrapper and the +route guards, and one or two cases stay missing until a user finds them. +Session kit is that code, written once and tested with each router and +framework it supports. ### What it does -Session kit handles each of these moments for you: +Here's what Session kit does in each of those moments: -| When… | Session kit… | -| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | -| The page reloads | Restores the saved session and checks the user against your schema again. With `localStorage` and a synchronous schema, before the first paint. | -| The access token is about to expire | Refreshes it early, in the background, so requests don't wait. | -| A request gets a 401 anyway | Refreshes once, however many requests failed, then replays the safe ones. | -| Two tabs need a refresh at the same moment | Lets one tab spend the refresh token and the other reuse what it saved, where the browser supports Web Locks. | -| The user signs out or switches account in one tab | Follows in every tab, and remounts guarded pages so nothing of the previous account stays on screen. | -| The backend rejects the refresh token | Signs out in every tab and clears storage. | -| The backend is down when a refresh is due | Keeps the session, reports the error, and waits for a retry. An outage is not a sign-out. | -| A signed-out user opens a private page | Sends them to sign-in, and back to where they were going afterwards. | -| The page renders on the server | Reads the session from an encrypted cookie, so the first response is already signed in. | +| When… | Session kit… | +| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| The page reloads | Restores the saved session and checks the user against your schema again. With synchronous storage, such as `localStorage`, and a synchronous schema, that happens before the first paint. | +| The access token is about to expire | Refreshes it early, in the background, so requests don't wait. | +| A request gets a 401 anyway | Refreshes once, however many requests got the 401, then sends the `GET` and `HEAD` requests again. | +| Two tabs need a refresh at the same moment | Lets one tab use the refresh token while the other waits and reuses the tokens it saved, in browsers with Web Locks. | +| The user signs out or switches account in one tab | Follows in every other tab, and remounts the pages under `SessionOutlet` (or `SessionGate` on Expo), so nothing from the previous account stays on screen. | +| The backend rejects the refresh token | Signs out in every tab and clears the saved session. | +| The backend is down when a refresh is due | Keeps the session and reports the error. While the access token still works, the user stays signed in. After it expires, the session waits for a retry. An outage is never a sign-out. | +| A signed-out user opens a private page | Sends them to your sign-in page, and back to where they were going after they sign in. | +| The page renders on the server | Reads the session from an encrypted cookie, so the first response is already signed in. | ### 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 -need those too, use an auth service or framework such as Auth.js, Better Auth, -or Clerk, which manage their own sessions. +Session kit never signs 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 need those too, use an auth service or framework such as Auth.js, Better +Auth or Clerk, which manage their own sessions. ## How it works -Session kit sits between your backend and your components. Tokens travel on -the left, and only state reaches the right: +Session kit sits between your backend and your components. Tokens move +between Session kit and your backend, and only the session's state reaches +your components: @@ -70,45 +71,49 @@ the left, and only state reaches the right: Your backend issues the tokens. Session kit saves them, refreshes them on -time, and attaches them to your requests. Your components and route guards -read the session's state, and never see a token. +time, and adds the access token to your API requests. Your components and +route guards read who is signed in, and never handle a token. -Five terms come up throughout: +Five terms come up on every page: - **Tokens** are what your backend issues. The access token goes with each - request and is short-lived. The refresh token, if there is one, is exchanged - for a new access token when the old one expires. + request and lasts a short time. The refresh token, if there is one, is + exchanged for a new access token when the old one expires. - **The client**, from `createAuth`, holds the tokens and does the work: - saving, restoring, refreshing, and telling other tabs. An app usually has - one. -- **A session** is who is signed in: `{ sessionId, user }`. It never holds - tokens, so it is safe to render and to pass around. -- **State** is what components read: `status`, `user`, `sessionId`, and - `error`, updated as the session changes. -- **Credentials** are the access token and its expiry, given only to code that - attaches them to requests, such as `createAuthFetch`. - -`status` says where the session stands, and checking it narrows `user`: - -| `status` | Meaning | `user` | -| ----------------- | ------------------------------------------------------------------------- | ------ | -| `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 | -| `unauthenticated` | No session; sign-in is needed. | `null` | -| `unavailable` | Restoring failed, or a failed refresh left no usable access; see `error`. | `null` | - -The session is kept in one of two places, depending on where your app renders: - -| | In the browser or on the device | On the server | -| ----------------- | -------------------------------------------------------------------------------- | ---------------------------------------------------------- | -| For | Single-page apps and Expo apps | TanStack Start, Next.js, React Router with SSR | -| Client | `createAuth` | `createServerAuth`, with `createMirrorAuth` in the browser | -| Saved in | `localStorage`, `sessionStorage`, the iOS keychain, or Android encrypted storage | An encrypted `httpOnly` cookie | -| The refresh token | Stays in that storage | Never reaches the browser | - -Hooks, guards, and tab sync work the same in both. + saving, restoring, refreshing and following other tabs. An app usually has + one, named `auth` in these docs. +- **A session** is who is signed in: `{ sessionId, user }`. It holds no + tokens, so it's safe to render and to pass around. +- **State** is what components read: `status`, `user`, `sessionId` and + `error`. It updates as the session changes. +- **Credentials** are the session ID, the access token and when it expires. + `createAuthFetch` reads them to add the token to your requests, and your own + request code can too. + +`status` says where the session stands, and checking it tells TypeScript +whether `user` is set: + +| `status` | Meaning | `user` | +| ----------------- | -------------------------------------------------------------------------------------------------------- | ------ | +| `initializing` | The saved session hasn't been read yet. | `null` | +| `authenticated` | Signed in, with an access token that hasn't expired or been rejected. | Set | +| `refreshing` | Signed in, and replacing an access token that expired or was rejected. | Set | +| `locked` | Signed in with `locking`, and the tokens wait for `unlock()`. | Set | +| `unauthenticated` | Signed out. | `null` | +| `unavailable` | The access token couldn't be refreshed, or the saved session couldn't be read. `error` usually says why. | `null` | + +Where the session is kept depends on where your app renders: + +| Where it's kept | In the browser or on the device | On the server | +| ----------------- | ---------------------------------------------------------------------------------- | ----------------------------------------------------------- | +| For | Single-page apps and Expo apps | TanStack Start, Next.js, React Router with server rendering | +| Client | `createAuth` | `createServerAuth`, with `createMirrorAuth` in the browser | +| Saved in | `localStorage`, `sessionStorage`, the iOS keychain, or Android's encrypted storage | An encrypted, `httpOnly` cookie | +| The refresh token | Stays in that storage | Sealed in the cookie, where page scripts can't read it | + +The hooks, the route guards and tab sync work the same in both. +[Storage](/docs/configuration/storage) says more about each kind of storage, +and [Server rendering](/docs/server-rendering) about the cookie. ## Next steps @@ -117,4 +122,4 @@ Hooks, guards, and tab sync work the same in both. - [Getting started](/docs/getting-started): build a small app that signs in, stays signed in, and calls an API. - [Server rendering](/docs/server-rendering): keep the session on the server - with TanStack Start, Next.js, or React Router. + with TanStack Start, Next.js or React Router. diff --git a/site/content/docs/(latest)/installation.mdx b/site/content/docs/(latest)/installation.mdx index bb84fef..64d09b7 100644 --- a/site/content/docs/(latest)/installation.mdx +++ b/site/content/docs/(latest)/installation.mdx @@ -3,17 +3,19 @@ title: Installation description: Install Session kit and a schema library, then find the guide and example app for your setup. --- -Install Session kit, a schema library, and the packages your setup needs, then -follow the guide for that setup. +Your app needs Session kit, a schema library to describe your users, and the +packages your setup already uses, such as React and your router. Install the +first two here, then follow the guide for your setup. -To install the package, run the following command: +To install Session kit, run the following command: ```npm npm install @monarcode/session-kit ``` -Alpha releases are published to the `latest` distribution tag and may change -the public API, so pin an exact version and read the +Release candidates are published to the `latest` distribution tag. The API +is frozen for 0.1: later 0.1 releases only add to it. Pin an exact version, +and read the [release notes](https://github.com/monarcode/session-kit/blob/main/CHANGELOG.md) before upgrading. @@ -25,14 +27,18 @@ To install it, run the following command: npm install zod ``` -Then install React, and the router or framework your setup uses. -[Compatibility](/docs/reference/compatibility) lists every optional peer -dependency and the versions it supports. +Then install React, and the router or framework your setup uses. Each is an +optional peer dependency, so install only the ones your setup imports. + +Session kit needs TypeScript 5.4 or newer, and Effect asks for 5.9 or newer. +[Compatibility](/docs/reference/compatibility) lists the runtimes and the +peer dependency versions it supports. ## Pick your setup -Find your setup in the following table. Each one has an import path and a -guide. All but the first also have a runnable app in +Find your setup in the following table. Each row names the entry point for +your router or framework, and the guide to follow. All but the first also +have a runnable app in [`examples/`](https://github.com/monarcode/session-kit/tree/main/examples) that signs in against DummyJSON's public test API: @@ -49,6 +55,11 @@ that signs in against DummyJSON's public test API: | Next.js 16, App Router | `@monarcode/session-kit/next` | [Next.js](/docs/setups/next) | [`next-app`](https://github.com/monarcode/session-kit/tree/main/examples/next-app) | | Expo Router on iOS and Android, SDK 53+ | `@monarcode/session-kit/expo` | [Expo Router](/docs/setups/expo) | [`expo-router`](https://github.com/monarcode/session-kit/tree/main/examples/expo-router) | +Every setup also imports its client from `@monarcode/session-kit`: +`createAuth`, or with server rendering, `createMirrorAuth`. Server-rendered +setups import more on the server, and each guide shows what. +[Entry points](/docs/reference) lists every import path. + Two guides apply to more than one setup: - [Server sessions](/docs/server-rendering/server-sessions) covers what the @@ -57,15 +68,16 @@ Two guides apply to more than one setup: ## Docs for coding assistants -These docs are also plain Markdown, for AI coding assistants. Point yours at -[`/llms.txt`](/llms.txt), which links every page in reading order, or -[`/llms-full.txt`](/llms-full.txt), which holds them all in one file. Add -`.md` to a page's URL for that page alone. +These docs are also available as plain Markdown, for AI coding assistants. +Point yours at [`/llms.txt`](/llms.txt), which links every page in reading +order, or at [`/llms-full.txt`](/llms-full.txt), which holds them all in one +file. For one page alone, add `.md` to its URL. ## Next steps -- For a setup that keeps the session in the browser or on the device, start - 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). +- [Getting started](/docs/getting-started): start here for a setup that + keeps the session in the browser. The web router guides build on its app. +- [Expo Router](/docs/setups/expo): start here for an iOS or Android app. The + guide starts from scratch. +- [Server rendering](/docs/server-rendering): start here for TanStack Start, + Next.js, or React Router with server rendering. diff --git a/site/content/docs/(latest)/meta.json b/site/content/docs/(latest)/meta.json index 0adb9b3..42796e5 100644 --- a/site/content/docs/(latest)/meta.json +++ b/site/content/docs/(latest)/meta.json @@ -2,16 +2,21 @@ "title": "Latest", "root": "version", "pages": [ + "---Get started---", "index", "installation", "getting-started", - "setups", - "server-rendering", + "---Setups---", + "...setups", + "---Guides---", "client", "configuration", + "server-rendering", "effect", - "reference", + "---Going further---", + "security", "faq", - "security" + "---Reference---", + "...reference" ] } diff --git a/site/content/docs/(latest)/reference/compatibility.mdx b/site/content/docs/(latest)/reference/compatibility.mdx index ceb2ff8..0542403 100644 --- a/site/content/docs/(latest)/reference/compatibility.mdx +++ b/site/content/docs/(latest)/reference/compatibility.mdx @@ -1,54 +1,66 @@ --- title: Compatibility -description: The peer dependency versions, runtimes, and TypeScript settings Session kit supports and is tested with. +description: The peer dependency versions, runtimes and TypeScript versions Session kit supports, and which of them CI tests. --- -Check this page before you upgrade a framework that Session kit works with, -or to see whether your runtime is supported. +Before you upgrade React, a router or a framework, check here that Session kit +supports the new version. This page also lists the runtimes Session kit is +built for, and which of them CI tests. ## Peer dependencies -Every peer dependency is optional. Install only the ones the entry points you -import use: - -| Peer | Range | Used by | -| ------------------------ | ----------------------- | ------------------------------------------------------ | -| `react` | `^18.0.0 \|\| ^19.0.0` | `/react`, `/tanstack-router`, `/react-router`, `/expo` | -| `@tanstack/react-router` | `^1.132.0` | `/tanstack-router` | -| `@tanstack/react-start` | `^1.169.0` | `/tanstack-start/server` | -| `react-router` | `^7.0.0 \|\| ^8.0.0` | `/react-router`, `/react-router/server` | -| `next` | `^16.0.0` | `/next` | -| `effect` | `^4.1.0` | `/effect`, `/effetch` | -| `@monarcode/effetch` | `^0.1.0-rc.4` | `/effetch` | -| `expo-router` | `^5.0.2` through `^58` | `/expo` | -| `expo-secure-store` | `^14.2.0` through `^58` | `/expo` | -| `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 +Every peer dependency is optional. Install only the ones used by the entry +points you import: + +| Peer | Range | Used by | +| ------------------------ | ----------------------- | ------------------------------------------------------------------------- | +| `react` | `^18.0.0 \|\| ^19.0.0` | `/react`, `/tanstack-router`, `/tanstack-start`, `/react-router`, `/expo` | +| `@tanstack/react-router` | `^1.132.0` | `/tanstack-router` | +| `@tanstack/react-start` | `^1.169.0` | `/tanstack-start/server` | +| `react-router` | `^7.0.0 \|\| ^8.0.0` | `/react-router`, `/react-router/server` | +| `next` | `^16.0.0` | `/next` | +| `effect` | `^4.1.0` | `/effect`, `/effetch` | +| `@monarcode/effetch` | `^0.1.0-rc.4` | `/effetch` | +| `expo-router` | `^5.0.2` through `^58` | `/expo` | +| `expo-secure-store` | `^14.2.0` through `^58` | `/expo` | +| `expo-file-system` | `^18.1.0` through `^58` | `/expo` | +| `react-native` | `>=0.79.0` | `/expo` | + +Things to know about these peers: + +- **Expo.** The Expo ranges cover Expo SDK 53 to 58. Install them with `npx expo install`, so that they match your SDK, as the [Expo guide](/docs/setups/expo#installation) shows. +- **React Router 8** needs React 19.2.7 or newer. With React 18, use React + Router 7. +- **Next.js 16** needs React 18.2 or newer. - **React Router with server rendering.** `/react-router/server` needs React Router's middleware: React Router 8, or 7.9 and later with `future.v8_middleware`. +- **effetch-query**, for caching Effect queries, needs React 19. - **React DOM.** No entry point imports React DOM. -## Tested versions +## Runtimes -CI tests the oldest and the newest version in each range, with one -exception: it tests `expo-file-system` only at its newest. Version 18.1 -publishes no `exports` map, so its types don't resolve under NodeNext. +Session kit is built for these runtimes: -## Runtimes +- browsers; +- React Native through Expo SDK 53 to 58, with Hermes and Metro; +- Node.js 20 and newer, for server rendering and for the server entry + points. + +Your framework can need a newer Node.js than Session kit does. React Router +8.5 needs Node.js 22.22, TanStack Start 1.169 needs 22.12, and Next.js 16.4 +needs 20.9. -Session kit runs in browsers, in React Native (Expo SDK 53 and newer, with -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: +Session kit uses these platform features: -- **`AbortController`** is required. +- **`AbortController`** is required. React Native's, which can't carry an + abort reason, works too. +- **`atob`** decodes JWTs, to read an access token's expiry and for + `fromAccessToken`. Every runtime above has it. +- **`fetch`, `Request` and `Response`** are required by + `@monarcode/session-kit/http` and by the server entry points. - **`crypto.randomUUID`** makes session IDs when present. Without it, the client uses `crypto.getRandomValues`, or `Math.random` as a last resort. - **Web Locks** keep tabs to one refresh at a time when present. Without @@ -59,7 +71,26 @@ features: - **Web Crypto** is required on the server by `@monarcode/session-kit/server`, as in Node.js 20 and newer. +## What CI tests + +CI runs every test on Node.js 24, twice: + +- with the peer versions in the repository's lockfile, which can be behind + the newest releases; +- with the oldest version in each peer range, such as React 18.0 and React + Router 7.0, and Expo SDK 53's packages. `expo-file-system` stays at the + lockfile's version, because 18.1 publishes no `exports` map, so its types + don't resolve under NodeNext. + +CI also builds each example app, and bundles the Expo app for iOS and +Android. It doesn't run Node.js 20 or 22, browsers or a device. Those are +built for, but not tested in CI. + ## TypeScript -The package is ESM-only. It's checked with TypeScript 6.0.3 under NodeNext -and Bundler resolution, with `exactOptionalPropertyTypes` both on and off. +Session kit's types need TypeScript 5.4 or newer. `/effect` and `/effetch` +also load Effect's types, and Effect asks for TypeScript 5.9 or newer. + +The package is ESM-only. CI checks its types with TypeScript 6.0.3 under +NodeNext and Bundler resolution, with `exactOptionalPropertyTypes` both on +and off. diff --git a/site/content/docs/(latest)/reference/core.mdx b/site/content/docs/(latest)/reference/core.mdx index 91a7b2c..7ba0965 100644 --- a/site/content/docs/(latest)/reference/core.mdx +++ b/site/content/docs/(latest)/reference/core.mdx @@ -3,11 +3,8 @@ title: "Core" description: "The client and storage: create one auth client per app." --- -```ts -import { … } from "@monarcode/session-kit"; -``` - -Guide: [Getting started](/docs/getting-started). +Import these from `@monarcode/session-kit`. To set it up, see +[Getting started](/docs/getting-started). ## Functions @@ -15,22 +12,51 @@ Guide: [Getting started](/docs/getting-started). Creates an auth client. It keeps the session your backend issued, saves it, refreshes its tokens, and tells your app when it changes. +Create one client per `name`. Throws `INVALID_OPTIONS` for options it can't use. To keep sessions on your server instead, in a cookie, use `createServerAuth` from `@monarcode/session-kit/server`. + +The saved session is read on the first `mount()`, which `AuthProvider` and the router adapters call, or by the first method that needs it, such as `getSession()`. Until then, `state.status` is `initializing`. + +See [`AuthOptions`](#authoptions) for every option. + +See [`AuthClient`](#authclient) for what the client does. + ### createMirrorAuth Creates a browser client ([`MirrorAuth`](#mirrorauth)) for a session your server keeps in an encrypted cookie, with `createServerAuth` from `@monarcode/session-kit/server`. +It starts from the session the page was rendered with, so there's no loading state, and it never sees the refresh token. Create one per page load in the browser, and one per request on the server, never at module level. `useMirrorAuth` does this for you. + +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, and `INVALID_SESSION` for a `session` that isn't a session or `null`. + +See [`MirrorAuthOptions`](#mirrorauthoptions) for every option. + ### fromAccessToken Reads the user from the access token, rather than from what `signIn` is given. Pass the result as `createAuth`'s `user` option. +The `claims` schema checks the token's claims, and `map` turns them into the user. Without `map`, the claims are the user. + +The client then works a little differently: + +- `signIn` takes tokens only, and your refresh callback returns tokens only. +- There's no `updateUser`. The user changes when the token does, so call `auth.refresh()` to pick up a change. + +`map` runs on every restore and every new token, so keep it pure and synchronous. The same claims must give the same user. Leave out claims that change on every refresh, such as `exp`, `iat` or `jti`. A token that can't be read, or whose claims the schema rejects, fails with `USER_VALIDATION_FAILED`. + +See [`FromAccessTokenOptions`](#fromaccesstokenoptions) to verify the token yourself. + ### isSignedIn 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. + ### 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. +`returnTo` is encoded as is. Pass a path you read from the request through [`safeReturnTo`](#safereturnto) first. Throws `INVALID_OPTIONS` when `loginPath` doesn't start with `/`. + ### 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. @@ -39,16 +65,28 @@ Keeps the session in memory only. It ends when the page unloads, and other tabs Makes a "send me back here after sign-in" path safe to redirect to, such as a `?redirectTo=` search param. It returns the path, normalized, when it 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. + +Throws `INVALID_OPTIONS` when a `loginPath` doesn't start with `/`. + ### webStorage 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. +It touches browser storage only when the client reads or saves, so creating a client in code that also runs on a server is safe. Reading the session on a server fails with `PERSISTENCE_FAILED`. + ## Classes ### AuthError The error Session kit throws, rejects with, or shows in `state.error`. +`code` says what went wrong ([`AuthErrorCode`](#autherrorcode)). `cause` holds what failed underneath, such as your refresh callback's error, and `issues` holds the schema's issues when the user was rejected. + ## Types ### AccessTokenUser @@ -59,6 +97,28 @@ A user read from the access token, made by [`fromAccessToken`](#fromaccesstoken) The auth client that `createAuth` returns. It holds the session, saves it, refreshes it, and tells your app when it changes. +`U` is the user ([`User`](#user)) and `I` is the user `signIn` accepts ([`UserInput`](#userinput)). With `fromAccessToken`, `I` is `never` and there's no `updateUser`. Write `typeof auth` rather than spelling out both. + +Members: + +- `state`: The current [`AuthState`](#authstate), and a way to listen for changes. In React, read it with `useAuth`. `subscribe` calls the listener on each later change, not with the current state. A listener that throws doesn't break auth. Its error is rethrown asynchronously. +- `state.get` +- `state.subscribe` +- `signIn`: 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 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. +- `signOut`: Signs out at once, clears the saved session, then calls your `revoke` 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 `PERSISTENCE_FAILED`. The app is signed out anyway, but the next load would restore the session, so call it again later. +- `getSession`: Resolves who is signed in, or `null` when signed out. It reads the saved 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 `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. +- `retry`: Like `getSession()`, but tries a failed refresh again instead of rejecting with its error. Use it for a "Try again" button. +- `refresh`: Refreshes the tokens now, even if the access token is still valid, for example to pick up changes to the user. Resolves `null` when signed out. Rejects with `REFRESH_FAILED` when there's no `refresh` option or no refresh token, and with `LOCKED` while locked. +- `isCurrent`: Whether `session` is still the signed-in one, by its `sessionId`. Use it to drop a response that arrives after the user signed out or switched accounts. +- `lock`: Locks the session (with `locking`). The tokens leave memory and timers stop, but the saved session and `state.user` stay. `state.status` turns `locked` at once. While locked, `getSession`, `retry`, `refresh`, `updateUser`, `credentials.get` and `credentials.renew` reject with `LOCKED`. Call `unlock()` to continue, or `signOut()`. A refresh already running still saves its tokens, and `lock()` resolves after that save. Keep the key `seal` needs until then. Does nothing when signed out or already locked. Rejects with `INVALID_OPTIONS` without `locking`. +- `unlock`: Unlocks a `locked` session and resolves it. It reads the saved tokens and opens them with `locking.open`. When not locked, it acts like `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 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, or past `maxAge`, 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 otherwise, it rejects with `REFRESH_FAILED`. The session is then unlocked, but `unavailable` until `retry()`. Rejects with `INVALID_OPTIONS` without `locking`. +- `mount`: Starts the background work: expiry timers, and following other tabs. Returns a function that stops it. `AuthProvider` and the router adapters call it for you. Calls are counted, and the work stops when the last one is stopped. Each call also checks the session again. It reads the saved session if that hasn't worked yet, and refreshes an access token that expired. +- `credentials`: The access token ([`Credentials`](#credentials)), for code that sends it with requests, such as `createAuthFetch`. +- `credentials.get`: Like `getSession()`, but resolves the current access token. +- `credentials.renew`: 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 the refresh's failure, such as `REFRESH_FAILED`, or `INVALID_SESSION` and `USER_VALIDATION_FAILED` for tokens or a user the client can't use. Rejects with `SESSION_CHANGED` when another session has replaced theirs, and with `LOCKED` while locked. +- `credentials.reject`: Signs out because your API rejected `credentials` for good. Does nothing if they're no longer current, such as after a refresh. +- `updateUser`: Replaces the signed-in user, such as after a profile edit. 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 the schema rejects, or when the function rejects or takes more than 15 seconds. An `AuthError` the function throws keeps its own `code`. If calls overlap, the latest wins and the others reject with `SESSION_CHANGED`. It reads the session as `getSession()` does first, so it rejects with `LOCKED` while locked, and with a refresh's failure, such as `REFRESH_FAILED`. If the new user can't be saved, it rejects with `PERSISTENCE_FAILED` and signs out. + ### AuthDebug What `createAuth`'s `debug` option takes: @@ -70,7 +130,9 @@ What `createAuth`'s `debug` option takes: ### AuthDebugEvent -One thing auth did, sent to the `debug` option ([`AuthDebug`](#authdebug)). +One thing the client did, sent to the `debug` option ([`AuthDebug`](#authdebug)). + +Filter on `type`, which doesn't change between releases. `message` and `data` are for reading, and may change in any release. Events are frozen, so copy one before changing it. ### AuthDebugOptions @@ -84,7 +146,9 @@ The object form of `createAuth`'s `debug` option ([`AuthDebug`](#authdebug)): wh ### AuthDebugType -Which part of auth an [`AuthDebugEvent`](#authdebugevent) comes from, such as `refresh` or `storage`. These names don't change between releases, so filter on them. +Which part of Session kit an [`AuthDebugEvent`](#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`. ### AuthErrorCode @@ -104,6 +168,13 @@ Options for creating an [`AuthError`](#autherror) yourself, such as in a test or Encrypts the saved tokens with a key your app holds, such as one behind Face ID. Pass it as the `locking` option of [`AuthOptions`](#authoptions). +The client calls `seal` whenever it saves tokens, and `open` only from `unlock()`. The user and session ID are saved unencrypted, so a locked session can still show who is signed in. + +Members: + +- `seal`: 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. +- `open`: Decrypts what `seal` returned. It must throw when it can't. + ### AuthOptions Options for `createAuth`. The client's user types ([`User`](#user), [`UserInput`](#userinput)) are inferred from the `user` option. @@ -118,6 +189,8 @@ Options for `createAuth`. The client's user types ([`User`](#user), [`UserInput` The current auth state, from `state.get()` or `useAuth()`. It holds no tokens. +Check `status`, not `user`, to know whether requests can be made. `user` stays set while `locked`, when they can't. `isSignedIn` is that check. Checking `status` also narrows `user`, so TypeScript knows when it's set. + ### AuthStatus Where the session stands: `state.status` ([`AuthState`](#authstate)). @@ -129,9 +202,13 @@ Where the session stands: `state.status` ([`AuthState`](#authstate)). - `unauthenticated`: signed out. - `unavailable`: the access token expired or was rejected and couldn't be refreshed, or the saved session couldn't be read. `state.error` usually says why. On a client, `retry()` tries again. +`user` is set while `authenticated`, `refreshing` or `locked`. + ### AuthStorage -Where auth saves the session: `createAuth`'s `storage` option. Use [`webStorage`](#webstorage) in browsers, `secureStorage()` from `@monarcode/session-kit/expo` in Expo apps, and [`memoryStorage`](#memorystorage) in tests. Implement it yourself for another store. +Where Session kit saves the session: `createAuth`'s `storage` option. Use [`webStorage`](#webstorage) in browsers, `secureStorage()` from `@monarcode/session-kit/expo` in Expo apps, and [`memoryStorage`](#memorystorage) in tests. Implement it yourself for another store. + +Values are strings in a format Session kit owns. Methods may return promises. Session kit runs them one at a time, in order, so a store that answers out of order is still safe. `. 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. + +See [`RegisteredAuth`](#registeredauth) for the type it gives. + ### 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. @@ -198,6 +317,10 @@ The client registered in [`Register`](#register), or a client with an `unknown` Asks your backend to revoke the tokens of a session that just signed out. It's the `revoke` option of [`AuthOptions`](#authoptions). +`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. + ### SafeReturnToOptions Options for [`safeReturnTo`](#safereturnto). @@ -212,10 +335,21 @@ 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. +See [`Credentials`](#credentials) for the access token. + +Members: + +- `sessionId`: Identifies this sign-in. It stays the same across refreshes and profile updates, and is new on every sign-in. +- `user` + ### 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. +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. + +See [`UserOf`](#userof) for the user alone. + ### SignInInput What `signIn` takes: the [`Tokens`](#tokens), plus the `user` when a schema validates it. With `fromAccessToken` (`I` is `never`), it takes tokens only. @@ -224,6 +358,16 @@ What `signIn` takes: the [`Tokens`](#tokens), plus the `user` when a schema vali The tokens your backend issues. Pass them to `signIn`, and return them from your refresh callback ([`RefreshFn`](#refreshfn)). +When the access token expires comes from the first of these that is set: + +1. `expiresIn` or `expiresAt`. Pass one, not both. +2. A JWT access token's `exp - iat`, counted from when the client receives it. +3. A JWT access token's `exp` alone, compared with the device's clock. + +With none of them, the token never expires on its own. It's replaced only after your API rejects it. + +Prefer `expiresIn`, or a JWT with `iat`. Device clocks can be minutes off, and a clock that runs fast makes a fixed deadline look already passed, so `signIn` would reject the tokens. + null`. + +Throws `INVALID_OPTIONS` when `loginPath` or `basename` doesn't start with `/`. + +See [`redirectIfSignedIn`](#redirectifsignedin) for the sign-in page. + ### 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. +Calling it throws `INVALID_OPTIONS` when the middleware hasn't run for `context`, as [`routerJar`](#routerjar) does. + ### routerJar 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. +Throws `INVALID_OPTIONS` when the middleware hasn't run for `context`, such as in a client loader. + ### 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. +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. Pass `cacheControl` for another value, or `false` to leave every response as it is (`SessionMiddlewareOptions`). + +It's [`cookieJarMiddleware`](#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. + +See [`requireSession`](#requiresession) to let only signed-in users through. + ### 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. +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 the example does. React Router's build can't remove a destructured `export const { loader }` from the browser's bundle, and fails. + ## Types ### RouterArgs @@ -65,6 +98,10 @@ The loader and action [`sessionRoute`](#sessionroute) makes, for a resource rout 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. +Members: + +- `session`: 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. + ### SessionGuardOptions Options for [`requireSession`](#requiresession). diff --git a/site/content/docs/(latest)/reference/react-router.mdx b/site/content/docs/(latest)/reference/react-router.mdx index 07b4c7b..54c6ade 100644 --- a/site/content/docs/(latest)/reference/react-router.mdx +++ b/site/content/docs/(latest)/reference/react-router.mdx @@ -3,11 +3,8 @@ title: "React Router" description: "Route guards and revalidation for React Router." --- -```ts -import { … } from "@monarcode/session-kit/react-router"; -``` - -Guide: [React Router](/docs/setups/react-router). +Import these from `@monarcode/session-kit/react-router`. To set it up, see +[React Router](/docs/setups/react-router). ## Functions @@ -15,6 +12,8 @@ Guide: [React Router](/docs/setups/react-router). 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. +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. A `loginPath` that doesn't start with `/` rejects with `INVALID_OPTIONS`. + ### 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. A `loginPath` that doesn't start with `/` throws `INVALID_OPTIONS` when the loader is made. @@ -23,20 +22,42 @@ Makes the loader for your sign-in page, for `loader` or `clientLoader`. It reads 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. +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 path and query they asked for. React Router leaves the `#fragment` out of a loader's request, so it isn't kept. A locked session counts as signed out, as locking is for native apps and the router adapters don't unlock. + +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` 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. + ### 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. +Pass `loginPath` or `basename` when they aren't the defaults. A `loginPath` or `basename` that doesn't start with `/` throws `INVALID_OPTIONS` when the loader is made. + ### useAuthRevalidation Runs your loaders again when the session changes, so guards such as `requireSession` check it again. That's on sign-in, sign-out, a switch of account, a profile update, a lock, or a refresh that fails once the access token has expired. A token refresh alone doesn't, nor does a failed refresh while the token is still valid. +Call it once in the root layout, in data or framework mode. Declarative 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. + ## Components ### SessionOutlet Renders child routes only while someone is signed in, in any mode. It needs an `AuthProvider` above it, or a `client`. +Signed-out users, and a locked session, go to `loginPath`, with `?redirectTo=` set to where they were. In declarative mode, that makes it the guard. + +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. + +Child routes remount for each account, but not on token refreshes or profile updates. 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 it has neither an `AuthProvider` around it nor a `client`. + ## Types ### RedirectIfSignedInLoader diff --git a/site/content/docs/(latest)/reference/react.mdx b/site/content/docs/(latest)/reference/react.mdx index 6770765..e31d08a 100644 --- a/site/content/docs/(latest)/reference/react.mdx +++ b/site/content/docs/(latest)/reference/react.mdx @@ -3,11 +3,8 @@ title: "React" description: "React hooks and the provider that read a client's state." --- -```ts -import { … } from "@monarcode/session-kit/react"; -``` - -Guide: [Read the session in React](/docs/getting-started#4-read-the-session-in-react). +Import these from `@monarcode/session-kit/react`. To set it up, see +[Read the session in React](/docs/getting-started#4-read-the-session-in-react). ## Functions @@ -15,24 +12,48 @@ Guide: [Read the session in React](/docs/getting-started#4-read-the-session-in-r 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. +See [`AuthHooksOptions`](#authhooksoptions) to find the client without `AuthProvider`. + ### 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. +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 [`AuthProvider`](#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`. + ### 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)). +Throws `INVALID_OPTIONS` without an `AuthProvider` above, as [`useAuth`](#useauth) does. + ### 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`. +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. When the session changes in the browser, it calls `onChange`. + +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. + +See [`UseMirrorAuthOptions`](#usemirrorauthoptions) for `create`, `session` and `onChange`. + ## 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. +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 ([`ProvidedAuth`](#providedauth)). + +See [`useAuth`](#useauth) to read the session below it. + ## Types ### AuthHooks @@ -67,6 +88,8 @@ What the React bindings need from an auth client: its `state`, and `mount` to st 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, `mount`, `getSession`, `signOut`, `isCurrent` and `credentials`. Its user is then `unknown`. + ### StateOf The state type of a client: what `useAuth()` returns (`AuthState`). diff --git a/site/content/docs/(latest)/reference/server.mdx b/site/content/docs/(latest)/reference/server.mdx index 75e74f9..e02f224 100644 --- a/site/content/docs/(latest)/reference/server.mdx +++ b/site/content/docs/(latest)/reference/server.mdx @@ -3,11 +3,8 @@ title: "Server" description: "Sessions kept on the server, in an encrypted cookie." --- -```ts -import { … } from "@monarcode/session-kit/server"; -``` - -Guide: [Server sessions](/docs/server-rendering/server-sessions). +Import these from `@monarcode/session-kit/server`. To set it up, see +[Server sessions](/docs/server-rendering/server-sessions). ## Functions @@ -15,10 +12,22 @@ 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. +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. + +See [`ServerAuthOptions`](#serverauthoptions) for every option. + ### 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. +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). 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 request it can't read answers 400 with `INVALID_OPTIONS`. Otherwise a failure's status is 401 for `UNAUTHENTICATED`, 409 for `SESSION_CHANGED` and 500 for any other code. That includes `INVALID_OPTIONS` from the server's setup, such as a missing secret or middleware, so your monitoring sees it. 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. + ## Types ### ClientCredentials @@ -29,6 +38,8 @@ The access token as your server gives it to the browser, from `serverAuth.client Reads and writes one request's cookies, for `createServerAuth`'s methods. The framework adapters, such as `nextJar` and `startJar`, build one. Elsewhere, wrap the request's cookies and the response's `Set-Cookie`. +Make a new jar for each request, and pass it to every call while handling that request, so they share one refresh and see each other's writes. Never keep one at module level, or one request's session would show in the next. + { + const response = await fetch(`${API}/auth/refresh`, { + method: "POST", + signal, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ refreshToken }), + }); + // DummyJSON rejected the refresh token: sign out. + if (response.status === 401 || response.status === 403) return null; + if (!response.ok) throw new Error(`Refresh failed (${response.status})`); + return tokens.parse(await response.json()); + }, }); + +/** The session of the request Start is handling, found on each call. */ +export const session = startAuth(serverAuth); ``` -## 1. Sign in with your backend in the browser +## 2. Sign in with your backend in the browser -The browser calls your backend's sign-in, which must allow requests from your -site (CORS): +The browser calls your backend's sign-in, and gets the tokens and the user: ```ts title="src/backend.ts" import { z } from "zod"; -const API = "https://api.example.com"; +export const API = "https://dummyjson.com"; const tokensSchema = z.object({ accessToken: z.string(), refreshToken: z.string(), }); -const userSchema = z.object({ id: z.number(), firstName: z.string() }); +export const userSchema = z.object({ id: z.number(), firstName: z.string() }); + +export type LoginResult = Awaited>; /** Signs in with your backend, from the browser. */ export async function login(username: string, password: string) { @@ -65,7 +105,7 @@ export async function login(username: string, password: string) { } ``` -## 2. Send the tokens to the server +## 3. Send the tokens to the server `session.signIn` seals what it's given, and never asks your backend. So the server function decides what to trust. Check the tokens first, unless the @@ -73,18 +113,18 @@ cookie's user is only ever shown. ### Check the tokens first -The server function takes the tokens only, and asks your backend who they -belong to. A forged or expired token is refused, and the cookie's user comes -from your backend, not from the browser: +The server function takes the tokens only, and asks your backend whose they +are. A forged or expired access token is refused, and the cookie's user +comes from your backend, not from the browser. The refresh token isn't +checked until the first refresh: ```ts title="src/auth/functions.ts" import { createServerFn } from "@tanstack/react-start"; import { z } from "zod"; +import { API, userSchema } from "../backend"; import { session } from "./server"; -const API = "https://api.example.com"; - export const getSessionFn = createServerFn().handler(() => session.getSession(), ); @@ -92,22 +132,23 @@ export const getSessionFn = createServerFn().handler(() => export const signInFn = createServerFn({ method: "POST" }) .validator(z.object({ accessToken: z.string(), refreshToken: z.string() })) .handler(async ({ data }) => { - // Proves the access token is real, and reads its user. + // Your backend proves the access token is real, and says whose it is. const response = await fetch(`${API}/auth/me`, { headers: { Authorization: `Bearer ${data.accessToken}` }, }); if (!response.ok) throw new Error("Your backend refused the token"); - const me: unknown = await response.json(); - const user = z.object({ id: z.number(), firstName: z.string() }).parse(me); + const user = userSchema.parse(await response.json()); return session.signIn({ ...data, user }); }); ``` -The client's `signIn` takes the tokens, and sends them to `signInFn`: +The client's `signIn` takes what your backend's sign-in returned, and sends +only the tokens to `signInFn`: ```ts title="src/auth/client.ts" import { createMirrorAuth } from "@monarcode/session-kit"; +import type { LoginResult } from "../backend"; import { getSessionFn, signInFn } from "./functions"; export function createAppAuth() { @@ -116,8 +157,8 @@ export function createAppAuth() { session: null, // filled by loadSession, then by hydration endpoint: "/api/session", revalidate: () => getSessionFn(), - signIn: (tokens: { accessToken: string; refreshToken: string }) => - signInFn({ data: tokens }), + signIn: ({ accessToken, refreshToken }: LoginResult) => + signInFn({ data: { accessToken, refreshToken } }), }); } @@ -138,8 +179,7 @@ export async function signIn( password: string, ): Promise { try { - const { accessToken, refreshToken } = await login(username, password); - await auth.signIn({ accessToken, refreshToken }); + await auth.signIn(await login(username, password)); return null; } catch (error) { return error instanceof Error ? error.message : "Could not sign in"; @@ -147,38 +187,58 @@ export async function signIn( } ``` -With [`fromAccessToken`](/docs/client/users-from-tokens) as the server's -`user` option, the server reads the user from the access token instead. Give -it a `decode` that verifies the token's signature, and that's the check. +With `fromAccessToken` as the server's `user` option, the server reads the +user from the access token instead. Give it a `decode` that verifies the +token's signature, and that's the check: see +[Verify the token on a server](/docs/client/users-from-tokens#verify-the-token-on-a-server). ### Pass the tokens without a check -The server function takes the tokens and the user the browser sends, and -seals them as they are: +If the cookie's user is only ever shown, the server function can take the +tokens and the user the browser sends, and seal them as they are: -```ts title="src/auth/trusting-sign-in.ts" +```ts title="src/auth/functions.ts" app="trusting" import { createServerFn } from "@tanstack/react-start"; import { z } from "zod"; +import { userSchema } from "../backend"; import { session } from "./server"; -export const trustingSignInFn = createServerFn({ method: "POST" }) +export const getSessionFn = createServerFn().handler(() => + session.getSession(), +); + +export const signInFn = createServerFn({ method: "POST" }) .validator( z.object({ accessToken: z.string(), refreshToken: z.string(), - user: z.object({ id: z.number(), firstName: z.string() }), + user: userSchema, }), ) .handler(({ data }) => session.signIn(data)); ``` -The client's `signIn` takes what your backend's sign-in returned, so the -form passes it `login`'s result as it is: +The client's `signIn` then sends everything your backend's sign-in +returned. `src/sign-in.ts` stays as it is: + +```ts title="src/auth/client.ts" app="trusting" +import { createMirrorAuth } from "@monarcode/session-kit"; + +import type { LoginResult } from "../backend"; +import { getSessionFn, signInFn } from "./functions"; -```ts -signIn: (result: Awaited>) => - trustingSignInFn({ data: result }), +export function createAppAuth() { + return createMirrorAuth({ + name: "app", + session: null, // filled by loadSession, then by hydration + endpoint: "/api/session", + revalidate: () => getSessionFn(), + signIn: (result: LoginResult) => signInFn({ data: result }), + }); +} + +export type AppAuth = ReturnType; ``` Anyone can then put any user in their own cookie, with tokens of their own. @@ -187,12 +247,13 @@ That's safe only when the cookie's user is shown, never trusted: - **Your backend authorizes every request** with the access token, and nothing on your server acts on `session.user` alone, such as reading another account's data by its `id`. -- **A forged token gets nowhere.** Your API refuses it, and the first refresh - fails and signs the user out. +- **A forged token gets nowhere.** Your API refuses it. At the first + refresh, your backend refuses its refresh token too, and a `refresh` that + returns `null` for that, as this guide's does, signs the user out. When in doubt, check the tokens first. It costs one request at sign-in. -## 3. Call your API from the browser +## 4. Call your API from the browser `createAuthFetch` from `@monarcode/session-kit/http` sends the access token that the session route serves. Make one per client, since the client is made @@ -206,17 +267,19 @@ import { useAuthClient } from "@monarcode/session-kit/tanstack-router"; export function Orders() { const auth = useAuthClient(); - const apiFetch = useMemo( - () => createAuthFetch(auth, { baseUrl: "https://api.example.com/" }), + const authFetch = useMemo( + () => createAuthFetch(auth, { baseUrl: "https://dummyjson.com/" }), [auth], ); const [count, setCount] = useState(null); async function load() { - const response = await apiFetch("orders"); + // DummyJSON's carts stand in for your orders. + const response = await authFetch("auth/carts"); if (!response.ok) throw new Error(`Orders failed (${response.status})`); - const orders: unknown = await response.json(); - setCount(Array.isArray(orders) ? orders.length : 0); + const body: unknown = await response.json(); + const carts = (body as { carts?: unknown } | null)?.carts; + setCount(Array.isArray(carts) ? carts.length : 0); } return ( @@ -228,27 +291,64 @@ export function Orders() { } ``` -With ky, axios or openapi-fetch, pass `apiFetch` as the client's `fetch`: see -[Other HTTP clients](/docs/client/other-http-clients). +After a 401, the client asks the session route for a new access token, and +the server refreshes with the cookie's refresh token. +[The access token in the browser](/docs/server-rendering/server-sessions#the-access-token-in-the-browser) +says how the browser holds the token. -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 +ky, axios and openapi-fetch can send their requests through `authFetch`: +see [Other HTTP clients](/docs/client/other-http-clients). Server functions +can still call your API too, as the guide's [Call your API](/docs/setups/tanstack-start#call-your-api) shows. +## Other frameworks + +With Next.js or React Router, the steps are the same. What changes is where +each piece lives, and how the session reaches the browser after sign-in. + +In the [Next.js](/docs/setups/next) guide's app: + +- Add `clientCredentials: true` in `lib/auth/server.ts`. +- Have `signInAction` in `app/actions.ts` take the tokens, check them as in + step 3, and call `session.signIn`. +- The client in `lib/auth/client.ts` already reads the session through + `endpoint`, with no `revalidate`. Its `signIn` option calls + `signInAction` with the tokens. +- Components get the client with `useAuthClient` from + `@monarcode/session-kit/react`. + +In the [React Router with server rendering](/docs/setups/react-router-ssr) +guide's app: + +- Add `clientCredentials: true` in `app/auth/session.server.ts`. +- Give the sign-in route an action that takes the tokens, checks them as in + step 3, and calls `auth(context).signIn`. +- After your backend's sign-in, submit the tokens to that action from the + browser, such as with `useSubmit`. React Router runs the loaders again, + and `useMirrorAuth` takes the new session. +- Components get the client with `useAuthClient` from + `@monarcode/session-kit/react`. + ## 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. +- **The refresh token passes through page scripts during sign-in,** in + your backend's sign-in response, on its way to your server. Session kit's + client passes it on without keeping it, and never holds it again. A + provider's SDK may keep its own copy: check its storage settings. If your + backend's sign-in can run on the server, sign in there, as the setup + guides do. - **Signing out** works as in the guide's - [Sign out](/docs/setups/tanstack-start#sign-out), 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). + [Sign out](/docs/setups/tanstack-start#7-sign-out) step, through the + session route. To end the session at your backend too, give + `createServerAuth` a `revoke`. + +## Next steps + +- [Your backend decides what's allowed](/docs/security#your-backend-decides-whats-allowed): + what the cookie's user can be trusted for. +- [The access token in the browser](/docs/server-rendering/server-sessions#the-access-token-in-the-browser): + how page scripts get and renew the access token. +- [Other HTTP clients](/docs/client/other-http-clients): send ky, axios or + openapi-fetch requests through `authFetch`. +- [Server sessions](/docs/server-rendering/server-sessions): the cookie, its + secret and the limits every server-rendered setup shares. diff --git a/site/content/docs/(latest)/server-rendering/index.mdx b/site/content/docs/(latest)/server-rendering/index.mdx index e346e01..de51148 100644 --- a/site/content/docs/(latest)/server-rendering/index.mdx +++ b/site/content/docs/(latest)/server-rendering/index.mdx @@ -1,63 +1,136 @@ --- title: Overview -description: With server rendering, the session lives in an encrypted cookie on the server, and the first page renders signed in. +description: With server rendering, the session lives in a sealed cookie on the server, and the first page renders signed in. --- -If your app renders pages on the server, with TanStack Start, Next.js, or -React Router's framework mode, Session kit keeps the session on the server. -This page explains how the pieces fit, then sends you to your framework's -guide. - -Both tokens and the user sit in one encrypted, `httpOnly` cookie that page -scripts can't read, so they never see the refresh token. The server refreshes -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. 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. -- **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, - never the refresh token. - -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 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). +When your app renders pages on the server, with TanStack Start, Next.js or +React Router's framework mode, the first page should already show who is +signed in. Session kit does that by keeping the session on the server. Both +tokens and the user sit in a sealed cookie: it's encrypted with your secret, +so only your server can read or change it. These docs call this server +custody: the server holds the tokens, and by default the browser holds only +who is signed in. + +The cookie is `httpOnly`, so page scripts can't read it, and they never see +the refresh token. The server reads the session before rendering, and the +browser's client starts from it, so pages never show a "Checking session…" +state. This page shows how the pieces fit, then sends you to your +framework's guide. + +## How the pieces fit + +Three pieces work together: + +- **The server engine.** `createServerAuth` from + `@monarcode/session-kit/server` seals the cookie with your secret and + refreshes the tokens with your backend. It's the same call in every + framework. + [Create the server engine](/docs/setups/tanstack-start#1-create-the-server-engine) + on the TanStack Start page shows one. +- **A request's session.** Each framework's adapter gives your server code + the session of the request it's handling, and middleware that refreshes + the tokens before rendering. Your server code signs in with your backend + and calls your API through it. It's shaped like a client, so code written + for one, such as `createAuthFetch` or Effect's `Auth`, takes it. +- **The browser's client.** `createMirrorAuth` makes a client that mirrors + the session the server rendered. `AuthProvider`, the hooks and the route + guards work with it. + +The browser's client reaches your server in three ways: + +1. It reads the session with a `GET` to the session route: a route in your + app that the browser's client calls to read the session, sign out and get + the access token. Each adapter's `sessionRoute` makes it. In TanStack + Start, a server function reads the session instead, because the server + render reads it too, and a route can't be called from there. +2. It signs out, and gets the access token, with a `POST` to the session + route. +3. It signs in through your own server function or action, as in + [Create the browser client](/docs/setups/tanstack-start#4-create-the-browser-client). + +Your server code calls your API with the request's access token. To call +your API from the browser too, opt in with `clientCredentials`, as +[The access token in the browser](/docs/server-rendering/server-sessions#the-access-token-in-the-browser) +explains. ## Frameworks What differs between frameworks is how server code gets a request's -session, and how the session reaches the browser: +session, which guards protect pages, 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 })`, 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) | +| Framework | On the server | Guards | In the browser | Guide | +| ------------------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------- | +| TanStack Start | `startAuth(serverAuth)`, with `refreshSession` in request middleware | `requireSession` and `redirectIfSignedIn` from `@monarcode/session-kit/tanstack-router` | `connectSession` and `loadSession` | [TanStack Start](/docs/setups/tanstack-start) | +| Next.js 16, App Router | `nextSession(serverAuth, { cookies, redirect })`, with its `refresh` in Proxy | `session.require` and `session.redirectIfSignedIn`, from `nextSession` | `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 | `requireSession` and `redirectIfSignedIn` from `@monarcode/session-kit/react-router/server` | `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, see +For a server or framework without an adapter, see [Servers without an adapter](/docs/server-rendering/server-sessions#servers-without-an-adapter). +## The browser's client + +The client from `createMirrorAuth` is a mirror client: it follows the +session your server keeps, and holds no tokens of its own. It has the same +`state`, `getSession`, `isCurrent`, `signOut` and `credentials` as a client +from `createAuth`. `AuthProvider`, the hooks, the route guards, +`createAuthFetch` and effetch's `sessionBearer` all take it. + +It differs from a `createAuth` client in a few ways: + +- **Two statuses.** Its `status` is only ever `authenticated` or + `unauthenticated`. It starts from the rendered session, and the server + does the refreshing. When asking the server fails, the error shows in + `state.error`, and the session stays as it was. +- **`retry()` and `refresh()` ask the server again.** They read the session + from your server, which refreshes the tokens itself. +- **`signIn` only with the `signIn` option.** The option calls your own + server function. Without it, call your function, then pass the session it + returns to `adopt`. +- **No `lock`, `unlock` or `updateUser`.** + [Locking isn't available](/docs/server-rendering/server-sessions#limits) + with server rendering. + +### Change the signed-in user + +To change the user, such as after a profile edit, call the request's +`updateUser` on the server, in a server function or an action. Then pass the +session it resolves to the browser client's `adopt`. The client takes it, +runs the route guards again and tells other tabs. + +With `useMirrorAuth`, a new server render brings the session too, such as +when React Router runs the loaders again after an action, or +`router.refresh()` renders a Next.js page again. The client takes the new +session. With `fromAccessToken`, there's no `updateUser`: the user comes from +the access token. [Updating the user](/docs/client/updating-the-user) covers +what `updateUser` takes. + +### How tabs stay in step + +Every tab sends the same cookie, so they all share one session on the +server. What each tab needs is to show the latest one. When a tab signs in, +signs out or adopts a changed session, its client tells the other tabs over a +`BroadcastChannel` named `:auth`. Each of them then asks your server +for the session. + +A tab that comes back into view asks your server again too, unless the +server answered it in the last 10 seconds. When the answer differs, the tab +follows it: + +- **TanStack Start:** `connectSession` runs the route guards again. +- **Next.js and React Router:** `useMirrorAuth` calls `onChange`, which + renders on the server again, with `router.refresh()` or `revalidate`. + +The client listens while it's mounted. `AuthProvider` and the router +adapters mount it for you. [Tabs](/docs/configuration/tabs) covers tabs for +sessions saved in the browser. + ## Next steps - Follow the guide for your framework in the table, from installation to calling your API. -- [Server sessions](/docs/server-rendering/server-sessions): the secret, - cookie jars, refreshes across server instances, sign-out, and limits. +- [Server sessions](/docs/server-rendering/server-sessions): the cookie and + its secret, refreshing before rendering, signing 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/server-sessions.mdx b/site/content/docs/(latest)/server-rendering/server-sessions.mdx index 59176d9..70a0974 100644 --- a/site/content/docs/(latest)/server-rendering/server-sessions.mdx +++ b/site/content/docs/(latest)/server-rendering/server-sessions.mdx @@ -1,42 +1,73 @@ --- title: Server sessions -description: How the server keeps the session in every framework, from the cookie and its secret to refreshing, signing out and limits. +description: What every server-rendered setup shares, from the cookie and its secret to refreshing before rendering, signing out and limits. --- -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: -[TanStack Start](/docs/setups/tanstack-start), [Next.js](/docs/setups/next), +Your server-rendered app signs in and renders the signed-in page. Before you +deploy it, you need to know where the session lives, how to keep and rotate +its secret, what happens when a page can't set cookies, and what signing out +ends. Those answers are the same in TanStack Start, Next.js and React +Router, so they live on this page. + +Read it after your app works. 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). ## The cookie -`createServerAuth` from `@monarcode/session-kit/server` keeps both tokens and -the user in one cookie, `.session`, sealed with AES-256-GCM through Web -Crypto. It's `httpOnly`, so page scripts can't read it, and `Secure` and -`SameSite=Lax` unless you pass other `cookie` options. It takes the options -`createAuth` does, except `storage` and `locking`, plus `secret`, `cookie` -and `clientCredentials`. +`createServerAuth` from `@monarcode/session-kit/server` keeps both tokens +and the user in a sealed cookie: it's encrypted with AES-256-GCM through Web +Crypto, with a key derived from your secret, so only your server can read or +change it. + +The cookie is named after the `name` option: `app.session` in these docs. +A session too large for one cookie is split across `app.session.0` and +`app.session.1`, and `app.session` then only marks the split. If a proxy or +CDN passes on only the cookies it knows, give it all three names. + +The cookie is `httpOnly`, so page scripts can't read it. It's also `Secure`, +`SameSite=Lax` and sent to every path, unless you pass other `cookie` +options. + +It lasts for `maxAge` seconds, 30 days by default. Each save starts that +again: a sign-in, a refresh or an `updateUser`. When it runs out, the browser +drops the cookie, and the user is signed out. -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. +`createServerAuth` takes the options `createAuth` does, except `storage` and +`locking`, plus `secret`, `cookie` and `clientCredentials`. 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 -Use 32 or more random characters from an environment variable. To make one, -run `openssl rand -base64 32`. `createServerAuth` checks the secret on first -use, not when the module loads, so build steps that import the module without -the secret still work. +The secret is the key that seals the cookie. Use 32 or more random +characters, kept in an environment variable such as `SESSION_SECRET`. To make +one, run `openssl rand -base64 32`. -Your module still reads `process.env.SESSION_SECRET` when it loads. On -Cloudflare Workers, `process.env` has the secret at that point when Node.js -compatibility is on, the default from compatibility date 2025-04-01. Without -Node.js compatibility, read it with `import { env } from "cloudflare:workers"`, -which also works at the top of a module. +`createServerAuth` checks the secret when a method first runs, not when the +module loads. So build steps that import the module without the secret, such +as `next build`, still work. Your module still reads +`process.env.SESSION_SECRET` when it loads. On Cloudflare Workers, +`process.env` holds the secret at that point when Node.js compatibility is on +and the compatibility date is 2025-04-01 or later. Otherwise, read it with +`import { env } from "cloudflare:workers"`, which also works at the top of a +module. -To rotate the secret, pass a list. The first secret seals new cookies, and -any of them opens one, so sessions survive the change. For example, to read -the old secret from `OLD_SESSION_SECRET` only while it's set: +A missing or wrong secret shows up on the first request: + +- **Without a valid secret,** every method rejects with `INVALID_OPTIONS`, + and a request's `state` is `unavailable`. The session route (the route in + your app that the browser's client calls to read the session and sign + out) answers 500 with `INVALID_OPTIONS`, so your monitoring sees it. +- **A cookie that no secret opens** reads as signed out. Where the request + can set cookies, the cookie is also deleted. So putting back a secret you + removed doesn't bring back the sessions it sealed. + +### Rotate the secret + +To change the secret without signing everyone out, pass a list. The first +secret seals new cookies, and any of them opens one. For example, to read the +old secret from `OLD_SESSION_SECRET` only while it's set: ```ts title="src/auth/server.ts" import { createServerAuth } from "@monarcode/session-kit/server"; @@ -52,100 +83,280 @@ export const serverAuth = createServerAuth({ }); ``` -Each save seals the cookie with the first secret. Remove -`OLD_SESSION_SECRET` once `maxAge` has passed since the change, 30 days by -default. By then, every cookie it sealed has expired. A cookie that no listed -secret opens reads as signed out. +Then rotate in four steps: + +1. Set `OLD_SESSION_SECRET` to the current secret. +2. Set `SESSION_SECRET` to a new one, made with `openssl rand -base64 32`. +3. Deploy. New cookies are sealed with the new secret, and each save moves a + session onto it. Cookies sealed with the old secret still open. +4. After `maxAge` has passed since the deploy, 30 days by default, remove + `OLD_SESSION_SECRET`. By then, every cookie it sealed has expired. ## 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: +request's cookies to pass. Each adapter gives it to you: - **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:** `nextSession(serverAuth, { cookies, redirect })`, whose - `writable()` gives it in Server Functions and Route Handlers, and - `readOnly()` in Server Components. +- **Next.js:** `nextSession(serverAuth, { cookies, redirect })`. Its + `writable()` gives the request's session in Server Functions and Route + Handlers, and `readOnly()` in Server Components. - **Servers without an adapter:** `serverAuth.forRequest(jar)`, over the - request's cookie jar. + request's cookie jar. See + [Servers without an adapter](#servers-without-an-adapter). 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`, `updateUser` and `refreshIfDue` -reject with `INVALID_OPTIONS`. `getSession` still resolves, and -`credentials.get` rejects with `REFRESH_FAILED` once the access token has -expired. 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. +it. `createAuthFetch(session, { baseUrl })` sends the cookie's access token, +and saves a renewed one after a 401. Effect's `Auth.layer` takes it too: see +[Use Effect on the server](/docs/effect/server). + +## Requests that can't set cookies + +Some requests can't change the cookie: + +- **Next.js:** a Server Component rendering. +- **React Router:** a loader after its response has left the middleware, + such as deferred data that reads the session while the page streams. +- **TanStack Start:** a page that has started streaming. Start gives no + sign of it, so a cookie set then is lost. A refresh at that point would + spend the refresh token and drop the new one. + +In Next.js and React Router, where Session kit can tell, the request's +session saves nothing: + +- `signIn`, `signOut`, `updateUser` and `refreshIfDue` reject with + `INVALID_OPTIONS`. +- `getSession` still resolves, with the session as the cookie holds it. +- `credentials.get` rejects with `REFRESH_FAILED` after the access token has + expired, since a refreshed one couldn't be saved. + +The way around all three cases is to refresh first, while the response can +still set the cookie. + +## Refresh before rendering + +Each setup refreshes in middleware that runs before any route reads the +session. Here's the middleware for each: + +| Setup | Refreshes with | +| -------------------------- | ----------------------------------------------------------------- | +| TanStack Start | `refreshSession(serverAuth)`, in request middleware | +| React Router | `sessionMiddleware(serverAuth)`, in the root route | +| Next.js | `session.refresh(request, response)` from `nextSession`, in Proxy | +| Servers without an adapter | `serverAuth.refreshIfDue(jar)`, before rendering | + +The middleware refreshes when the access token expires within 60 seconds, so +it lasts through the request. A token that lives a minute or less would be +refreshed on every request, so pass a smaller `within` for it, such as +`refreshSession(serverAuth, { within: 15 })`. `sessionMiddleware` takes +`within` the same way, and `nextSession` in its options. + +What else the middleware does: + +- **It refreshes at most once per request.** Calls during the request share + that refresh. +- **A failed refresh doesn't fail the request.** While the access token + still works, the failure is ignored. After it expires, routes read the + session as usual, and the error reaches the route's error component or + error boundary. +- **It keeps shared caches out.** A page that reads the session differs per + user. `refreshSession` and `sessionMiddleware` send + `Cache-Control: private, no-store` with each response that doesn't set its + own, so a CDN or proxy doesn't cache it. Pass `cacheControl` for another + value, or `{ cacheControl: false }` to leave every response as it is. + `nextSession`'s `refresh` doesn't set the header: the + [Next.js](/docs/setups/next) guide says how Next caches pages that read the + session. + +## Refreshes across requests and servers + +Parallel requests to one instance that carry the same cookie share one +refresh. For 10 seconds afterwards, a request that still carries the old +cookie gets the new tokens rather than refreshing again. A refresh that +fails at your backend is shared too: for 10 seconds, requests that carry that +cookie reject with its error rather than call your backend again. + +An instance is one `createServerAuth` call, and instances share nothing. A +framework may make several on one server, one per bundle. Separate +processes, servers and serverless functions are separate instances too. With +rotating refresh tokens, give your backend a short reuse window, so that two +instances that refresh the same session don't sign it out. + +## Sign-out + +A request's `signOut` clears the cookie in this browser, then calls your +`revoke` and waits for it. A failed `revoke` doesn't make `signOut` reject. +The browser's client signs out through the session route, which calls it for +you. + +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 10 seconds, the instance that signed out treats such a copy as signed +out, as it treats an old cookie after a refresh. After that, the copy works +for as long as its tokens do. + +`revoke` is what ends the session. Have your backend revoke the refresh token +there, so a copy can't refresh. Keep access tokens short-lived too: your +backend accepts one until it expires, unless it checks for revocation. + +## The access token in the browser + +Server code calls your API with a request's `credentials`. To call your API +from the browser too, with `createAuthFetch` or effetch's `sessionBearer`, +pass `clientCredentials: true` to `createServerAuth`. The session route then +serves the access token, and the browser's client gets it there. + +Here's how the token behaves in the browser: + +- Page scripts hold the access token in memory, never the refresh token. + The client asks for a new one shortly before it expires. +- After a 401, the client asks the session route for a new token, and the + server refreshes with the cookie's refresh token. +- Without `clientCredentials`, the session route answers 500, and the + client's `credentials.get()` rejects with `INVALID_OPTIONS`. +- Without a session route, such as when your client calls server functions, + pass `createMirrorAuth`'s `credentials` option: two functions that call a + request's `clientCredentials.get` and `clientCredentials.renew` on the + server. + +A script injected into your page can then use your 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). ## Servers without an adapter -Every `serverAuth` method also takes the request's `CookieJar` first: +On a server with no adapter, such as a plain `fetch` handler that takes a +`Request` and returns a `Response`, you wire the same pieces yourself. Every +`serverAuth` method also takes the request's cookie jar +([`CookieJar`](/docs/reference/server#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. Answer the browser client's session route with -`sessionHandler(serverAuth)`, called with the request and its jar. +`serverAuth.forRequest(jar)` gives that request's session. + +### 1. Build a cookie jar for each request + +The jar reads the request's `Cookie` header and collects the `Set-Cookie` +lines for the response: + +```ts title="src/server/cookie-jar.ts" +import type { CookieJar, CookieOptions } from "@monarcode/session-kit/server"; + +function setCookie(name: string, value: string, options: CookieOptions) { + return [ + `${name}=${value}`, + `Path=${options.path}`, + `Max-Age=${options.maxAge ?? 0}`, + `SameSite=${options.sameSite}`, + ...(options.domain ? [`Domain=${options.domain}`] : []), + ...(options.secure ? ["Secure"] : []), + "HttpOnly", + ].join("; "); +} + +/** One request's cookie jar, and a function that answers with its cookies. */ +export function cookieJar(request: Request) { + const cookies = new Map(); + for (const pair of request.headers.get("Cookie")?.split(";") ?? []) { + const equals = pair.indexOf("="); + const name = pair.slice(0, equals).trim(); + if (equals > 0 && !cookies.has(name)) + cookies.set(name, pair.slice(equals + 1).trim()); + } + const written = new Map(); + let answered = false; + const jar: CookieJar = { + get writable() { + return !answered; + }, + get: (name) => cookies.get(name), + set: (name, value, options) => + written.set(name, setCookie(name, value, options)), + delete: (name, options) => + written.set(name, setCookie(name, "", { ...options, maxAge: 0 })), + }; + function respond(response: Response) { + answered = true; + for (const line of written.values()) + response.headers.append("Set-Cookie", line); + return response; + } + return { jar, respond }; +} +``` -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`. +Make a new jar for each 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. After `respond`, the jar's `writable` is +`false`, which tells Session kit that the request can't set cookies any more. + +### 2. Answer the session route, then render + +`sessionHandler(serverAuth)` answers the session route. For a page, refresh +first, then read the session and render with it: + +```ts title="src/server/handle.ts" +import { sessionHandler } from "@monarcode/session-kit/server"; + +import { serverAuth } from "../auth/server.js"; +import { cookieJar } from "./cookie-jar.js"; +import { renderPage } from "./render.js"; + +const handleSession = sessionHandler(serverAuth); + +export async function handle(request: Request): Promise { + const { jar, respond } = cookieJar(request); + if (new URL(request.url).pathname === "/api/session") + return respond(await handleSession(request, jar)); + // While the response can still set the cookie. A failure is ignored + // here: getSession rejects if the access token has expired. + await serverAuth.refreshIfDue(jar).catch(() => {}); + const session = await serverAuth.getSession(jar); + const page = await renderPage(session); + // The page differs per user, so no shared cache may keep it. + if (!page.headers.has("Cache-Control")) + page.headers.set("Cache-Control", "private, no-store"); + return respond(page); +} +``` -## Token refresh +Without an adapter, nothing marks the response as private, so set +`Cache-Control` yourself, as the adapters' middleware does +([Refresh before rendering](#refresh-before-rendering)). -Parallel requests to one instance that carry the same cookie share one -refresh. For ten seconds afterwards, a request still carrying the old cookie -gets the new tokens rather than refreshing again. A refresh that fails at -your backend is shared too. For ten seconds, requests carrying that cookie -reject with its error rather than call your backend again. +`renderPage` is your app's own server render. It puts the session in the +page, as frameworks do with a loader's data, so the browser's client can +start from it. -Each `createServerAuth` call is its own instance, and a framework may make -several on one server, one per bundle. Separate processes, servers, and -serverless functions are separate instances too. Instances share nothing, so -with rotating refresh tokens, give your backend a short reuse window. Two -instances that refresh the same session then don't sign it out. +### 3. Create the browser's client -## Sign-out +In the browser, create the client from the session the page was rendered +with, once per page load: -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 -signed out, as it treats an old cookie after a refresh. After that, the copy -works for as long as its tokens do. +```ts title="src/auth/client.ts" +import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit"; -`revoke` is what ends the session: have your backend revoke the refresh -token there, so a copy can't refresh, and keep access tokens short-lived, -since the backend accepts one until it expires unless it checks for -revocation. +// Types only: left out of the browser's bundle. +import type { serverAuth } from "./server.js"; -## The access token in the browser +export type AppSession = SessionOf; -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`. 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. +export function createAppAuth(session: AppSession | null) { + return createMirrorAuth({ name: "app", session, endpoint: "/api/session" }); +} +``` -The session route answers your own site's pages only: see -[The session route](/docs/security#the-session-route). +With React, create it with `useMirrorAuth` from +`@monarcode/session-kit/react`, and render `AuthProvider` with it. Its +`onChange` runs when the session changes in the browser, so you can render +the page on the server again. ## Limits -- **Size.** The cookie can take about 7.5 KB across two cookies, since +- **Size.** The cookie can take about 7.5 KB across its two parts, since servers and proxies refuse larger request headers (nginx: 8 KB for the `Cookie` line, shared with the site's other cookies), and go on refusing every page until the cookie is cleared. That holds about 5.5 KB of tokens @@ -153,14 +364,18 @@ The session route answers your own site's pages only: see `PERSISTENCE_FAILED`, so keep the user small. An `updateUser` or a refresh that outgrows the cookie rejects the same way, and signs the user out. - **Plain http.** The cookie is `Secure` by default. Browsers accept that on - `http://localhost` except Safari: pass `cookie: { secure: false }` for + `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's nothing on the device to lock. ## Next steps -- [Effect on the server](/docs/effect#on-the-server): run Effects with a +- [Hybrid setup](/docs/server-rendering/hybrid): sign in with your backend + from the browser, and call your API there. +- [Use Effect on the server](/docs/effect/server): run Effects with a request's session. - [Security](/docs/security): what Session kit protects, and what stays your backend's job. +- [`createServerAuth` reference](/docs/reference/server#createserverauth): + every option and method. diff --git a/site/content/docs/(latest)/setups/expo-locking.mdx b/site/content/docs/(latest)/setups/expo-locking.mdx new file mode 100644 index 0000000..e7823ea --- /dev/null +++ b/site/content/docs/(latest)/setups/expo-locking.mdx @@ -0,0 +1,523 @@ +--- +title: Unlock with biometrics +description: Ask a returning user for Face ID, Touch ID or a fingerprint before an Expo app opens, with the password as a fallback. +--- + +A saved session keeps your app signed in for weeks, so anyone who picks up +the unlocked phone can open it. Some apps ask the returning user to confirm +it's them first: a "Welcome back" screen with Face ID, Touch ID or a +fingerprint, and the password as a fallback. + +This page adds that screen to the app from the +[Expo Router guide](/docs/setups/expo). With the client's `locking` option, a +saved session restores as `locked`. The app can greet the user by name, but +the tokens stay sealed until the user unlocks them. +[Locking](/docs/client/locking) explains how a locked session behaves. This +page is the Expo side. + +Here's how the pieces fit together. A random key is kept in a SecureStore +item that needs biometrics to read, so reading it shows the biometric prompt. +The client seals the tokens with that key, using AES-GCM, each time it saves +them, and opens them when the user unlocks. + +## Before you begin + +- The app from the [Expo Router guide](/docs/setups/expo), with the + `expo-secure-store` config plugin in `app.json`. On iOS, the plugin adds + the Face ID permission that the prompt needs. +- A development build on a real device. Expo Go doesn't support SecureStore's + biometric prompt where biometrics are available, and simulators don't ask for + biometrics. + +## 1. Install the packages + +This page makes the key with `expo-crypto`, and seals the tokens with +`@noble/ciphers`. They're your app's dependencies, not Session kit's: + +```sh +npx expo install expo-crypto @noble/ciphers +``` + +## 2. Keep a key behind biometrics + +This file makes the key, saves it behind the device's biometrics, reads it +back to unlock, and seals the tokens with it: + +```ts title="src/session-key.ts" +import { Platform } from "react-native"; + +import type { AuthLocking } from "@monarcode/session-kit"; +import { gcm } from "@noble/ciphers/aes.js"; +import { + bytesToHex, + bytesToUtf8, + hexToBytes, + utf8ToBytes, +} from "@noble/ciphers/utils.js"; +import { getRandomBytes } from "expo-crypto"; +import * as SecureStore from "expo-secure-store"; + +const KEY_ITEM = "session-key"; +// 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 { + return biometric + ? { + requireAuthentication: true, + authenticationPrompt: "Unlock your account", + } + : {}; +} + +// In memory from an unlock or a password sign-in until the app locks. +let key: Uint8Array | undefined; + +/** + * Saves the key behind the device's biometrics, or, on a device with none + * enrolled, without them. On Android, saving shows the prompt. + */ +async function saveKey(next: Uint8Array): Promise { + const biometric = SecureStore.canUseBiometricAuthentication(); + // On iOS, replacing an item that needs biometrics shows the prompt, and + // saving a new one doesn't. So a password sign-in asks for nothing more. + await SecureStore.deleteItemAsync(KEY_ITEM); + await SecureStore.setItemAsync( + KEY_ITEM, + bytesToHex(next), + keyOptions(biometric), + ); + await SecureStore.setItemAsync(BIOMETRIC_ITEM, String(biometric)); +} + +/** + * 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; + 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; +} + +/** + * Loads the key to unlock. Throws when the user cancels the prompt, or when + * the device's biometrics changed and the key can't be read. + */ +export async function loadKey(): Promise { + const saved = await readKey(); + if (saved) { + key = hexToBytes(saved); + return; + } + // A session saved before locking was added has no key yet. Make one: on + // 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(); + key = next; +} + +/** + * Signs in with a new key, and saves it only after the sign-in succeeds: a + * failed sign-in keeps the key that the saved session is sealed with. + */ +export async function withNewKey(signIn: () => Promise): Promise { + const previous = key; + const next = getRandomBytes(32); + key = next; + let result: T; + try { + result = await signIn(); + } catch (error) { + if (key === next) key = previous; + throw error; + } + try { + await saveKey(next); + } catch (error) { + // The session works until the app closes; then the password unlocks it. + console.warn("Could not save the session key", error); + } + return result; +} + +/** Forgets the key in memory, after `auth.lock()` has settled. */ +export function dropKey(): void { + key = undefined; +} + +function loadedKey(): Uint8Array { + if (!key) throw new Error("The session key isn't loaded"); + return key; +} + +/** AES-256-GCM: a random 12-byte nonce, then the ciphertext, as hex. */ +export const sessionLocking: AuthLocking = { + seal(payload) { + const nonce = getRandomBytes(12); + const sealed = gcm(loadedKey(), nonce).encrypt(utf8ToBytes(payload)); + return bytesToHex(nonce) + bytesToHex(sealed); + }, + open(sealed) { + const bytes = hexToBytes(sealed); + const nonce = bytes.subarray(0, 12); + return bytesToUtf8(gcm(loadedKey(), nonce).decrypt(bytes.subarray(12))); + }, +}; +``` + +The rest of the app uses four of its exports: + +- `loadKey()` reads the key before an unlock, which shows the prompt. +- `withNewKey()` wraps a password sign-in, so the new session is sealed with + a new key. +- `dropKey()` forgets the key when the app locks or signs out. +- `sessionLocking` is the client's `locking` option. + +A device with no biometrics enrolled can't save an item that needs them. So +on those devices the key is saved without them, and unlocking asks for +nothing beyond the device's own lock screen. If your app needs more there, +sign out instead of locking. + +Users who signed in before you added locking need no migration. Their saved +session restores as `locked` too, and has no key yet, so `loadKey()` makes +one at their first unlock. + +## 3. Seal the session with the key + +Pass `sessionLocking` to the client as `locking`. Then sign in through +`withNewKey()`, and add a `signOut()` that forgets the key. The changed lines +are marked: + +```ts title="src/auth.ts" +import { createAuth } from "@monarcode/session-kit"; +import { secureStorage } from "@monarcode/session-kit/expo"; +import { createAuthFetch } from "@monarcode/session-kit/http"; +import { z } from "zod"; + +import { dropKey, sessionLocking, withNewKey } from "./session-key"; + +const API = "https://dummyjson.com"; + +export const userSchema = z.object({ + id: z.number(), + username: z.string(), + email: z.string(), + firstName: z.string(), +}); + +const tokensSchema = z.object({ + accessToken: z.string(), + refreshToken: z.string(), +}); +const loginResponseSchema = tokensSchema.extend(userSchema.shape); + +export const auth = createAuth({ + name: "my-app", + user: userSchema, + storage: secureStorage(), + debug: __DEV__, + // Changed: seals the saved tokens with the key. + locking: sessionLocking, + refresh: async ({ refreshToken, signal }) => { + const response = await fetch(`${API}/auth/refresh`, { + method: "POST", + signal, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ refreshToken }), + }); + // DummyJSON answers 401 or 403 when the refresh token is no good. + if (response.status === 401 || response.status === 403) return null; + if (!response.ok) throw new Error(`Refresh failed (${response.status})`); + return tokensSchema.parse(await response.json()); + }, +}); + +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); + +export async function signInWithPassword(username: string, password: string) { + const response = await fetch(`${API}/auth/login`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ username, password }), + }); + if (!response.ok) throw new Error(`Sign-in failed (${response.status})`); + const { accessToken, refreshToken, ...user } = loginResponseSchema.parse( + await response.json(), + ); + // Changed: the new session is sealed with a new key. + await withNewKey(() => auth.signIn({ accessToken, refreshToken, user })); +} + +/** Changed: signs out, and forgets the key. It works offline. */ +export async function signOut(): Promise { + await auth.signOut().catch(() => {}); + dropKey(); +} +``` + +Saving a session seals it, a sign-in's too, and `seal` throws while no key +is loaded. That's why every sign-in goes through `withNewKey()`. Without a +key, the sign-in would fail with `PERSISTENCE_FAILED`. + +## 4. Guard the unlock screen + +A locked session isn't signed in, but it keeps its user. So the stack needs +a third screen, and a guard for each state that's true in that state only: + +```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"; + +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(); + +export default function RootLayout() { + return ( + + }> + + + + ); +} + +function RootStack() { + const signedIn = useAuth(isSignedIn); + const locked = useAuth((state) => state.status === "locked"); + return ( + + + + + + + + {/* Not while locked, so a locked app opens on welcome-back. */} + + + + + ); +} +``` + +Each state needs exactly one screen open to it. When a guard turns the user +away, Expo Router sends them to the first screen they may see, in its own +order of routes, not in the order of your JSX. If the sign-in screen were +open to a locked user too, a locked app could open on it rather than on the +welcome-back screen. + +## 5. Add the welcome-back screen + +The welcome-back screen greets the user, reads the key, which shows the +biometric prompt, and unlocks. A user who can't unlock signs in with their +password on the same screen: + +```tsx title="app/welcome-back.tsx" +import { useState } from "react"; +import { Button, Text, View } from "react-native"; + +import { useAuth } from "@monarcode/session-kit/react"; + +import { auth } from "../src/auth"; +import { loadKey } from "../src/session-key"; +import Login from "./login"; + +export default function WelcomeBack() { + const name = useAuth((state) => state.user?.firstName); + const [failed, setFailed] = useState(false); + const [withPassword, setWithPassword] = useState(false); + + async function unlock() { + setFailed(false); + try { + await loadKey(); + await auth.unlock(); + // No navigation: Stack.Protected leaves this screen, and + // SessionGate opens the deep link the user was headed to. + } catch { + // Cancelled, or the biometrics changed: offer the password. A refresh + // that failed after unlocking leaves the session `unavailable`, which + // SessionGate shows instead. + if (auth.state.get().status === "locked") setFailed(true); + } + } + + // The sign-in form. Signing in replaces the locked session. + if (withPassword) return ; + + return ( + + + Welcome back{name ? `, ${name}` : ""} + + + ); +} +``` + +Without `revoke`, a copy of the cookie made before sign-out still works: see +[Sign-out](/docs/server-rendering/server-sessions#sign-out). ## Call your API -Call your API with `createAuthFetch` from `@monarcode/session-kit/http`. It -sends the request's access token to your API's origin only. In Server -Components, pass it `session.readOnly()`, the request's session that doesn't -set cookies. Proxy refreshed the token before the render. A token that -expired anyway rejects with `REFRESH_FAILED`, and so does a 401 from your API, -since nothing new can be saved: +Your server code calls your API with `createAuthFetch` from +`@monarcode/session-kit/http`, which sends the request's access token to your +API's origin only. In a Server Component, pass it `session.readOnly()`, the +request's session that doesn't set cookies: ```tsx title="app/orders/page.tsx" import { createAuthFetch } from "@monarcode/session-kit/http"; import { z } from "zod"; +import { API } from "../../lib/auth/server"; import { session } from "../../lib/auth/session"; +const orders = z.object({ carts: z.array(z.object({ id: z.number() })) }); + export default async function Orders() { - await session.require("/orders"); - const apiFetch = createAuthFetch(await session.readOnly(), { - baseUrl: "https://api.example.com/", + const { user } = await session.require("/orders"); + const authFetch = createAuthFetch(await session.readOnly(), { + baseUrl: `${API}/`, }); - const response = await apiFetch("orders"); + const response = await authFetch(`auth/carts/user/${user.id}`); if (!response.ok) throw new Error(`Orders failed (${response.status})`); - const orders = z - .array(z.object({ id: z.number() })) - .parse(await response.json()); - return

{orders.length} orders

; + const { carts } = orders.parse(await response.json()); + return

{carts.length} orders

; } ``` +Proxy refreshed the token before the render. A token that expired anyway +rejects with `REFRESH_FAILED`, and so does a 401 from your API, since a +Server Component can't save a new token: see +[Requests that can't set cookies](/docs/server-rendering/server-sessions#requests-that-cant-set-cookies). + In Server Functions and Route Handlers, pass `await session.writable()` -instead, the request's session that can set cookies. After a 401, it renews the token, saves it in the cookie, and sends a -`GET` again. With an HTTP client of your own, such as ky or axios, see -[Other HTTP clients](/docs/client/other-http-clients). A client without a -`fetch` option reads the token with `credentials.get()`. +instead, the request's session that can set cookies. When your API answers +401 there, `authFetch` gets a new access token and saves it in the cookie. It +sends a `GET` or `HEAD` again with the new token, as +[After a 401](/docs/client/requests#after-a-401) explains. -To call the API from the browser too, with `createAuthFetch` or effetch's -`sessionBearer`, opt in with `clientCredentials: true` in `createServerAuth`. -The session route then serves the access token, and the client's -`credentials` get it there. +With an HTTP client of your own, such as ky or axios, see +[Other HTTP clients](/docs/client/other-http-clients). A client without a +`fetch` option reads the token with `credentials.get()` on +`await session.readOnly()` or `await session.writable()`. -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). +To call your API from the browser too, turn on `clientCredentials` in +`createServerAuth`: see +[The access token in the browser](/docs/server-rendering/server-sessions#the-access-token-in-the-browser). The example app does this. ## Things to know -- **Signing out ends the session only with `revoke`.** Without it, a copy of - the cookie made before sign-out still works: see - [Sign-out](/docs/server-rendering/server-sessions#sign-out). - **Writes only where Next allows them.** Use `signIn`, `signOut`, `updateUser` and `writable()` in Server Functions and Route Handlers only. In a Server Component they can't set the cookie, and `writable()` would @@ -426,25 +479,28 @@ The example app does this. 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"`. Nor does it add it to a - Route Handler's redirects, so a Route Handler reads the session with - `get` and answers 401, rather than calling `require`. + `endpoint` includes it: `"/app/api/session"`. Nor does Next add it to a + Route Handler's redirects, so a Route Handler reads the session with `get` + and answers 401, rather than calling `require`. - **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 - server again and render their pages again. So does returning to a tab - after a while. -- **More.** Several server instances, the cookie's size, and plain http - during development: see +- **The Node.js runtime.** Keep pages that read the session on the Node.js + runtime, the default. Next might not pass Proxy's refreshed cookie on to + Edge runtime pages. +- **Other tabs.** Signing in or out in one tab reaches the others, which ask + the server for the session and render their pages again: see + [How tabs stay in step](/docs/server-rendering#how-tabs-stay-in-step). +- **Deploying.** Several server instances, the cookie's size, and plain http + during development are covered in [Server sessions](/docs/server-rendering/server-sessions). ## Next steps -- [Server sessions](/docs/server-rendering/server-sessions): the cookie, - signing out, and the limits every server-rendered setup shares. -- [Using the client](/docs/client): what the browser client can do. -- [Effect on the server](/docs/effect#on-the-server): run Effects with a +- [Server sessions](/docs/server-rendering/server-sessions): the cookie, the + secret, signing out, and the limits every server-rendered setup shares. +- [Hybrid setup](/docs/server-rendering/hybrid): sign in from the browser + and call your API there, with the session still on the server. +- [Using the client](/docs/client): what the browser's client can do. +- [Use Effect on the server](/docs/effect/server): run Effects with a request's session. diff --git a/site/content/docs/(latest)/setups/react-router-ssr.mdx b/site/content/docs/(latest)/setups/react-router-ssr.mdx index e769438..8489cde 100644 --- a/site/content/docs/(latest)/setups/react-router-ssr.mdx +++ b/site/content/docs/(latest)/setups/react-router-ssr.mdx @@ -3,29 +3,41 @@ title: React Router with server rendering description: Keep the session in an encrypted cookie in React Router's framework mode, where middleware refreshes it and loaders read it. --- -In this guide, you keep the session in an encrypted cookie in React Router's -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 -[React Router](/docs/setups/react-router#framework-mode-with-ssr-false) -instead. A complete app is in +Your React Router app runs in framework mode and renders pages on the server, +and you want the first response to show the signed-in page, with no "Checking +session…" state and no flash of signed-out content. To do that, the server +has to hold the session. In this guide, you keep it in an encrypted cookie: +an action signs in, middleware refreshes the tokens, and loaders read the +session. + +Components get a small client that mirrors the session the server rendered, +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. A +complete app is in [`examples/react-router-framework-ssr`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-framework-ssr). +If your app uses framework mode with `ssr: false`, follow +[React Router](/docs/setups/react-router#framework-mode-with-ssr-false) +instead. + ## 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 +- React Router 8, which needs Node.js 22.22 or newer and React 19.2.7 or + newer. See [Compatibility](/docs/reference/compatibility) for the other + versions. +- With React 18, use React Router 7, version 7.9 or later, and turn its + middleware on with `future: { v8_middleware: true }` in + `react-router.config.ts`. 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. +- A secret of 32 or more random characters to seal the cookie, such as the + output of `openssl rand -base64 32`, set as `SESSION_SECRET` on the server. + `react-router build` doesn't need it. + [The secret](/docs/server-rendering/server-sessions#the-secret) says how to + keep and rotate it. +- The code signs in with [DummyJSON](https://dummyjson.com/docs/auth)'s test + backend, as [Getting started](/docs/getting-started) does. Replace its URLs + with your backend's. ## Installation @@ -37,11 +49,13 @@ npm install @monarcode/session-kit react-router 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. -`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: +The server engine keeps the session in a cookie sealed with your secret, and +refreshes the tokens with your backend. `createServerAuth` from +`@monarcode/session-kit/server` makes it. From +`@monarcode/session-kit/react-router/server`, `routerAuth` gives you 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 { @@ -51,7 +65,7 @@ import { import { createServerAuth } from "@monarcode/session-kit/server"; import { z } from "zod"; -const API = "https://api.example.com"; +export const API = "https://dummyjson.com"; const userSchema = z.object({ id: z.number(), firstName: z.string() }); const tokens = z.object({ accessToken: z.string(), refreshToken: z.string() }); @@ -67,14 +81,14 @@ export const serverAuth = createServerAuth({ headers: { "Content-Type": "application/json" }, body: JSON.stringify({ refreshToken }), }); - // The backend rejected the refresh token: sign out. - if (response.status === 401) return null; + // DummyJSON rejected the refresh token: sign out. + if (response.status === 401 || response.status === 403) return null; if (!response.ok) throw new Error(`Refresh failed (${response.status})`); return tokens.parse(await response.json()); }, }); -/** The request's session: `auth(context)` in middleware, loaders and actions. */ +/** The request's session: `auth(context)` in middleware, loaders, actions. */ export const auth = routerAuth(serverAuth); /** Lets only signed-in users through to the routes it guards. */ @@ -101,24 +115,17 @@ export async function login(username: string, password: string) { } ``` -[Server sessions](/docs/server-rendering/server-sessions#the-cookie) covers -its other options, rotating the secret, signing out, and the limits every -setup shares. +`auth(context)` returns the same session for every call with the same +`context`, which React Router makes per request. [Server +sessions](/docs/server-rendering/server-sessions) covers the engine's other +options, the cookie, and signing out. ## 2. Add the root route -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 session route that step 3 adds: +The root route does three jobs: its middleware refreshes the session, its +loader reads it, and its component gives it to the browser's client. First, +the client, which `createMirrorAuth` makes from the session 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"; @@ -139,12 +146,7 @@ export function createAppAuth(session: AppSession | null) { export type AppAuth = ReturnType; ``` -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. When the session changes in the browser, -it calls `onChange`, here `revalidate` from `useRevalidator()`, which runs -the loaders again. Register the client's type here, where you render +Then the root route. Register the client's type here, where you render `AuthProvider`, so the hooks carry your user: ```tsx title="app/root.tsx" @@ -156,6 +158,7 @@ import { Scripts, useLoaderData, useRevalidator, + useRouteError, type LoaderFunctionArgs, } from "react-router"; @@ -207,22 +210,120 @@ export default function App() { ); } + +/** Shown when the session can't be read, such as after a failed refresh. */ +export function ErrorBoundary() { + const error = useRouteError(); + const { revalidate } = useRevalidator(); + return ( +
+

{error instanceof Error ? error.message : "Something went wrong"}

+ +
+ ); +} +``` + +Here's what each part does: + +- **`sessionMiddleware(serverAuth)`** reads each request's cookies and sets + the ones written on the response, redirects included. That's what lets + `auth(context)` work in middleware, loaders and actions. It then refreshes + tokens that are about to expire, before any loader reads them, while the + response can still set the cookie. +- **The loader** returns `getSession()`, which resolves + `{ sessionId, user }`, never tokens, so it's safe to send to the browser. +- **`useMirrorAuth`** from `@monarcode/session-kit/react` creates the client + once per request on the server, never at module level, and keeps it in + step with the server both ways. After an action signs in or out, the loader + reads the new session and the client takes it. When the session changes in + the browser, here or in another tab, it calls `onChange`. Here that's + `revalidate` from `useRevalidator()`, which runs the loaders again, so the + server's redirects run. The client-side guides add `useAuthRevalidation` + for this, and here `useMirrorAuth` does it. +- **`ErrorBoundary`** shows a session that can't be read, such as after a + failed refresh, and its button runs the loaders again. + +`sessionMiddleware` refreshes tokens that expire within 60 seconds. For +tokens that live a minute or less, pass a smaller `within`, such as +`sessionMiddleware(serverAuth, { within: 15 })`. +[Refresh before rendering](/docs/server-rendering/server-sessions#refresh-before-rendering) +says what happens when a refresh fails, and how the middleware sets +`Cache-Control`. + +## 3. Add the session route + +The browser's client reads the session and signs out through a session +route: a resource route in your app that the browser's client calls. +`sessionRoute` from `@monarcode/session-kit/react-router/server` makes its +loader and action: + +```ts title="app/routes/auth.session.ts" +import { sessionRoute } from "@monarcode/session-kit/react-router/server"; + +import { serverAuth } from "../auth/session.server"; + +const route = sessionRoute(serverAuth); + +export const loader = route.loader; +export const action = route.action; +``` + +Export the loader and action one by one, as this file does. React Router's +build fails on a destructured `export const { loader, action }`. + +The session route answers your own site's pages only, so another site can't +sign the user out: see [The session route](/docs/security#the-session-route). + +## 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: + +```tsx title="app/routes/protected.tsx" +import { Outlet } from "react-router"; + +import { signedIn } from "../auth/session.server"; + +export const middleware = [signedIn]; + +// So navigation in the browser runs the middleware. +export const loader = () => null; + +export default function Protected() { + return ; +} +``` + +A signed-out user who opens a page in the layout, such as `/orders`, lands on +`/login?redirectTo=%2Forders`. +During navigation in the browser, server middleware runs only when a route +has a loader to fetch. The layout has one in case the routes nested in it +don't. + +Pages nested in the layout read the user with the hooks, as any component +does: + +```tsx title="app/routes/home.tsx" +import { useAuth } from "@monarcode/session-kit/react"; + +export default function Home() { + const user = useAuth((state) => state.user); + return

Welcome, {user?.firstName}

; +} ``` -`getSession` resolves `{ sessionId, user }`, never tokens, so it's safe to -return from a loader. After 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, `onChange` runs the loaders again, so the server's -redirects run. The client-side guides add `useAuthRevalidation` for this. -Here, `useMirrorAuth` does it. +A loader nested in the layout gets the session from +`signedIn.session(context)`, which is never `null` there. [Call your +API](#call-your-api) uses it. -## 3. Sign in and out +## 5. Sign in 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, refuse them yourself at the start of the -action, as [The session route](/docs/security#the-session-route) explains. -The form works before the page's scripts load: +into the cookie. Its loader, `redirectIfSignedIn`, sends a user who is +already signed in on to `redirectTo`. The form works before the page's +scripts load: ```tsx title="app/routes/login.tsx" import { @@ -238,7 +339,6 @@ import { redirectIfSignedIn } from "@monarcode/session-kit/react-router/server"; import { auth, login, serverAuth } from "../auth/session.server"; -// A signed-in user goes on to `redirectTo`. export const loader = redirectIfSignedIn(serverAuth); export async function action({ request, context, url }: ActionFunctionArgs) { @@ -281,145 +381,146 @@ export default function Login() { } ``` -A failed sign-in returns its message with status 400 for the form to show. -React Router doesn't run the page's loaders again after a 4xx action. +To try it, sign in as `emilys` with the password `emilyspass`. The action +redirects to `redirectTo`, made safe with `safeReturnTo`. A failed sign-in +returns its message with status 400, for the form to show, and React Router +doesn't run the page's loaders again after a 4xx action. -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: +React Router 7.12 and later refuse route actions posted from other sites. On +7.9 to 7.11, refuse them yourself at the start of the action: see +[Check your own routes](/docs/security#check-your-own-routes). -```ts title="app/routes/auth.session.ts" -import { sessionRoute } from "@monarcode/session-kit/react-router/server"; +In this guide, the server signs in with your backend, so the user in the +cookie comes from the backend. If the browser has to sign in with the backend +itself, have the action take the tokens instead: +[Hybrid setup](/docs/server-rendering/hybrid) shows how. -import { serverAuth } from "../auth/session.server"; - -const route = sessionRoute(serverAuth); - -export const loader = route.loader; -export const action = route.action; -``` +## 6. Sign out -Add it to `app/routes.ts` as `route("auth/session", "routes/auth.session.ts")`. -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). - -## 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 { signedIn } from "../auth/session.server"; - -export const middleware = [signedIn]; +The client's `signOut()` signs out on the server through the session route, +which clears the cookie and calls your `revoke` option, if `createServerAuth` +has one. It then signs out this tab and tells the others. `useMirrorAuth` +runs the loaders again, so `signedIn` sends the user to the sign-in page. +Put a button like this one on any page under the layout: -// So navigation in the browser runs the middleware. -export const loader = () => null; +```tsx title="app/sign-out-button.tsx" +import { useAuthClient } from "@monarcode/session-kit/react"; -export default function Protected() { - return ; +export function SignOutButton() { + const auth = useAuthClient(); + // A failed sign-out keeps the session, and shows in `state.error`. + return ( + + ); } ``` -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: +Without `revoke`, a copy of the cookie made before sign-out still works: see +[Sign-out](/docs/server-rendering/server-sessions#sign-out). -```tsx title="app/routes/home.tsx" -import { useLoaderData, type LoaderFunctionArgs } from "react-router"; - -import { signedIn } from "../auth/session.server"; +## 7. Register the routes -export function loader({ context }: LoaderFunctionArgs) { - return { name: signedIn.session(context).user.firstName }; -} +Last, add the routes to `app/routes.ts`. The sign-in route sits outside the +layout, and the pages it protects sit inside: -export default function Home() { - const { name } = useLoaderData(); - return

Welcome, {name}

; -} +```ts title="app/routes.ts" +import { + index, + layout, + route, + type RouteConfig, +} from "@react-router/dev/routes"; + +export default [ + route("login", "routes/login.tsx"), + layout("routes/protected.tsx", [index("routes/home.tsx")]), + // The session route the browser's client calls. + route("auth/session", "routes/auth.session.ts"), +] satisfies RouteConfig; ``` -In `app/routes.ts`, nest the routes it protects: -`layout("routes/protected.tsx", [index("routes/home.tsx")])`. During -navigation in the browser, server middleware runs only when a route has a -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 instead, as -[Hybrid setup](/docs/server-rendering/hybrid) shows for TanStack Start. +The sign-in route's path matters: `signedIn` sends signed-out users to +`/login`. To use another path, pass `loginPath` to `requireSession`. ## Call your API -Call your API with `createAuthFetch` from `@monarcode/session-kit/http`. -Given the request's session, it sends the access token, refreshed first when -it has expired. After a 401, it renews the token, saves it in the cookie, and -sends a `GET` again: +Your loaders and actions call your API with `createAuthFetch` from +`@monarcode/session-kit/http`. Given the request's session, it sends the +access token, refreshed first if it has expired. This page sits inside the +layout, so its loader reads the user from `signedIn`: ```tsx title="app/routes/orders.tsx" -import { redirect, useLoaderData, type LoaderFunctionArgs } from "react-router"; +import { useLoaderData, type LoaderFunctionArgs } from "react-router"; -import { loginHref } from "@monarcode/session-kit"; import { createAuthFetch } from "@monarcode/session-kit/http"; import { z } from "zod"; -import { auth } from "../auth/session.server"; +import { API, auth, signedIn } from "../auth/session.server"; + +const orders = z.object({ carts: z.array(z.object({ id: z.number() })) }); export async function loader({ context }: LoaderFunctionArgs) { - const session = auth(context); - // Outside the guarded layout: send the user to sign in, then back here. - if (!(await session.getSession())) - throw redirect(loginHref("/login", "/orders")); - const apiFetch = createAuthFetch(session, { - baseUrl: "https://api.example.com/", - }); - const response = await apiFetch("orders"); + const { user } = signedIn.session(context); + const authFetch = createAuthFetch(auth(context), { baseUrl: `${API}/` }); + const response = await authFetch(`auth/carts/user/${user.id}`); if (!response.ok) throw new Error(`Orders failed (${response.status})`); - return z.array(z.object({ id: z.number() })).parse(await response.json()); + return orders.parse(await response.json()).carts; } export default function Orders() { - const orders = useLoaderData(); - return

{orders.length} orders

; + const carts = useLoaderData(); + return

{carts.length} orders

; } ``` +Then add it inside the layout in `app/routes.ts`: + +```ts title="app/routes.ts" app="orders" +import { + index, + layout, + route, + type RouteConfig, +} from "@react-router/dev/routes"; + +export default [ + route("login", "routes/login.tsx"), + layout("routes/protected.tsx", [ + index("routes/home.tsx"), + route("orders", "routes/orders.tsx"), + ]), + route("auth/session", "routes/auth.session.ts"), +] satisfies RouteConfig; +``` + +When your API answers 401, `authFetch` gets a new access token and saves it in +the cookie. It sends a `GET` or `HEAD` again with the new token, as +[After a 401](/docs/client/requests#after-a-401) explains. + +A loader outside the layout has no `signedIn` to rely on. It can check +`await auth(context).getSession()` itself, and throw +`redirect(loginHref("/login", "/orders"))` when it's `null`. `loginHref` from +`@monarcode/session-kit` builds `/login?redirectTo=%2Forders`, so the user +comes back after signing in. + With an HTTP client of your own, such as ky or axios, see [Other HTTP clients](/docs/client/other-http-clients). A client without a -`fetch` option reads the token with `credentials.get()`. - -To call the API from the browser too, with `createAuthFetch` or effetch's -`sessionBearer`, opt in with `clientCredentials: true` in `createServerAuth`. -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). +`fetch` option reads the token with `auth(context).credentials.get()`. + +To call your API from the browser too, turn on `clientCredentials` in +`createServerAuth`: see +[The access token in the browser](/docs/server-rendering/server-sessions#the-access-token-in-the-browser). The example app does this. ## Things to know -- **Signing out ends the session only with `revoke`.** Without it, a copy of - the cookie made before sign-out still works: see - [Sign-out](/docs/server-rendering/server-sessions#sign-out). -- **Refresh in middleware.** The request's session sets cookies until the +- **Deferred data.** The request's session can set cookies until the 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. -- **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. + way. Deferred data that reads the session while the page streams can't + save anything, so the middleware refreshes before that: see + [Requests that can't set cookies](/docs/server-rendering/server-sessions#requests-that-cant-set-cookies). - **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 @@ -430,17 +531,19 @@ The example app does this. loaders' and actions' redirects, but not to middleware's, so the guard adds 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. -- **More.** Several server instances, the cookie's size, and plain http - during development: see +- **Other tabs.** Signing in or out in one tab reaches the others, which ask + the server for the session and run their loaders again: see + [How tabs stay in step](/docs/server-rendering#how-tabs-stay-in-step). +- **Deploying.** Several server instances, the cookie's size, and plain http + during development are covered in [Server sessions](/docs/server-rendering/server-sessions). ## Next steps -- [Server sessions](/docs/server-rendering/server-sessions): the cookie, - signing out, and the limits every server-rendered setup shares. -- [Using the client](/docs/client): what the browser client can do. -- [Effect on the server](/docs/effect#on-the-server): run Effects with a +- [Server sessions](/docs/server-rendering/server-sessions): the cookie, the + secret, signing out, and the limits every server-rendered setup shares. +- [Hybrid setup](/docs/server-rendering/hybrid): sign in from the browser + and call your API there, with the session still on the server. +- [Using the client](/docs/client): what the browser's client can do. +- [Use Effect on the server](/docs/effect/server): run Effects with a request's session. diff --git a/site/content/docs/(latest)/setups/react-router.mdx b/site/content/docs/(latest)/setups/react-router.mdx index 50be29d..e59908a 100644 --- a/site/content/docs/(latest)/setups/react-router.mdx +++ b/site/content/docs/(latest)/setups/react-router.mdx @@ -3,9 +3,10 @@ title: React Router description: Guard routes in React Router's declarative, data or framework mode, with the session kept in the browser. --- -In this guide, you add React Router to the app from Getting started, in the -mode your app uses. React Router has three modes, and Session kit guards each -one the way that mode works: +Your app uses React Router, and some of its routes are for signed-in users +only. In this guide, you add Session kit to the app from Getting started, in +the mode your app uses. React Router has three modes, and Session kit guards +each one the way that mode works: | Mode | The guard | Beside it | | ---------------------------- | -------------------------------------------- | -------------------------------------- | @@ -19,29 +20,25 @@ rendering, follow ## Before you begin -Follow [Getting started](/docs/getting-started) through step 3. This guide -uses its client in `src/auth.ts` and its form in `src/sign-in.tsx`. +- The app from [Getting started](/docs/getting-started), through step 5. This + guide uses its client in `src/auth.ts`, its form in `src/sign-in.tsx`, and + `fetchProfile` from `src/api.ts`. +- React Router 7 or 8. React Router 8 needs React 19.2.7 or newer, so with + React 18, use React Router 7. [Compatibility](/docs/reference/compatibility) + lists the versions. ## Installation -To install the packages, run the following command: +Install Session kit, React Router and Zod: ```npm npm install @monarcode/session-kit react-router zod ``` -React Router 7 and 8 both work. - ## Add a page to protect -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. - -Every mode on this page protects the same page: +Every mode on this page protects the same page. It reads the user and the +client with the hooks from `@monarcode/session-kit/react`: ```tsx title="src/home.tsx" import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; @@ -60,11 +57,21 @@ export function Home() { } ``` +Each mode renders `AuthProvider` and registers the client's type, as step 4 +of Getting started does, so these hooks carry your user. A sign-out that +fails shows in an alert that each mode renders outside the private routes, so +the button can ignore the rejection. + +`AuthProvider` restores the saved session when it mounts. With `localStorage` +and a synchronous schema, that happens +[before the first paint](/docs#what-it-does). + ## Declarative mode Declarative mode has no loaders, so `SessionOutlet` is the guard. Render it as a layout route's element, `}>`, and the routes -inside it render only while someone is signed in: +inside it render only while someone is signed in. `AuthProvider` goes around +the router: ```tsx title="src/main.tsx" import { StrictMode } from "react"; @@ -116,9 +123,19 @@ function Login() { return ; } +/** + * Failures that outlive the page that caused them, such as a sign-out that + * couldn't clear storage. + */ +function AuthErrorMessage() { + const error = useAuth((state) => state.error); + return error ?

{error.message}

: null; +} + createRoot(document.getElementById("root")!).render( + } /> @@ -132,14 +149,19 @@ createRoot(document.getElementById("root")!).render( ); ``` -`SessionOutlet` shows `pending` while the saved session is restored, sends -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. +`SessionOutlet` shows `pending` while the saved session is restored. It sends +a signed-out user to `/login`, or the `loginPath` you pass, with `redirectTo` +set to where they were going. A signed-out user who opens `/orders?tab=2` +lands on `/login?redirectTo=%2Forders%3Ftab%3D2`, and returns there after +signing in. After a failed refresh, it renders `unavailable`. Without +`unavailable`, it throws the error to the nearest error boundary. -`safeReturnTo` accepts only same-origin paths and returns `/` for anything -else, including the sign-in page itself, so a stale `redirectTo` can't loop. +`Login` sends a signed-in user on to `redirectTo`, so the form doesn't +navigate after it signs in. `safeReturnTo` turns `redirectTo` into a path +that's safe to send the user to. Anything that leads out of your app, or back +to the sign-in page, becomes `/`, so a stale `redirectTo` can't loop. The +[`safeReturnTo` reference](/docs/reference/core#safereturnto) lists every +rule. A complete app is in [`examples/react-router-declarative`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-declarative). @@ -147,12 +169,18 @@ A complete app is in ## Data mode In data mode, loaders run before a route renders, so the guard goes there. A -signed-out user is redirected before a private route renders: +signed-out user is redirected before a private route renders. The router +goes in its own file, and `src/main.tsx` renders it. -```tsx title="src/router.tsx" +### 1. Create the router + +Guard the private routes with a loader, and keep the guards in step with the +session from the root route: + +```tsx title="src/router.tsx" app="data" import { createBrowserRouter, Outlet, useRouteError } from "react-router"; -import { useAuthClient } from "@monarcode/session-kit/react"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; import { redirectIfSignedInLoader, requireSessionLoader, @@ -164,10 +192,16 @@ import { auth } from "./auth.js"; import { Home } from "./home.js"; import { SignIn } from "./sign-in.js"; -/** Runs the loaders again when auth changes, and with them the guards. */ +/** Runs the loaders again when auth changes, and shows auth errors. */ function Root() { useAuthRevalidation(); - return ; + const error = useAuth((state) => state.error); + return ( + <> + {error &&

{error.message}

} + + + ); } /** Shown after a failed refresh; a repeated failure shows here again. */ @@ -203,9 +237,36 @@ export const router = createBrowserRouter([ ]); ``` -Then render the router inside the provider, in `src/main.tsx`: +Three pieces work together: + +- **`requireSessionLoader(auth)`** is the route's loader. It returns + `{ session }` as the route's loader data. It sends a signed-out user to + `/login`, or the `loginPath` you pass, with `redirectTo` set to the path + and query they asked for: `/orders?tab=2` lands on + `/login?redirectTo=%2Forders%3Ftab%3D2`. A failed refresh goes to the + route's error element instead, as + [Things to know](#things-to-know) explains. A loader that does more calls + `requireSession`, as [Guards in loaders](#guards-in-loaders) shows. +- **`useAuthRevalidation`** runs the loaders again when the session changes, + such as after a sign-in, a sign-out or an account switch, so the guards + check it again. Call it one time, in the root route. + [Its reference](/docs/reference/react-router#useauthrevalidation) lists + every change it reacts to. +- **`SessionOutlet`**, as the guarded route's element, renders child routes + only while the session the loader accepted is still the signed-in one. When + another account signs in, it shows `pending` until the loader has run for + the new session, so no page shows the previous account's loader data. + +The sign-in route's `redirectIfSignedInLoader` runs again after a sign-in, +and sends the user on to `redirectTo`, so the form doesn't navigate. The root +route's `HydrateFallback` shows until the first loaders finish, such as while +the saved session is restored. -```tsx +### 2. Render the router + +Render the router inside `AuthProvider`, in `src/main.tsx`: + +```tsx title="src/main.tsx" app="data" import { StrictMode } from "react"; import { RouterProvider } from "react-router/dom"; @@ -231,49 +292,39 @@ createRoot(document.getElementById("root")!).render( ); ``` -Three pieces work together: - -- **`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, - 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. -- **`SessionOutlet`**, as the guarded route's element, renders child routes - only while the session the loader accepted is still the signed-in one. When - another account signs in, it shows `pending` until the loader has run for - the new session, so no page sees the previous account's loader data. - -A complete app is in [`examples/react-router-data`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-data). +A complete app is in +[`examples/react-router-data`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-data). ## Framework mode with `ssr: false` Framework mode without a server is data mode with route modules. The guards -are the same, in `clientLoader`. Keep the files from Getting started, and -`home.tsx` from [Add a page to protect](#add-a-page-to-protect), in `app/`. -Framework mode also needs `@react-router/dev`, which a framework-mode app -already has. +are the same, as each route's `clientLoader`. Keep the files from Getting +started, and `home.tsx` from [Add a page to protect](#add-a-page-to-protect), +in `app/`. Framework mode also needs `@react-router/dev`, which a +framework-mode app already has. + +### 1. Turn off server rendering -Turn server rendering off: +In `react-router.config.ts`, set `ssr` to `false`. The build then prerenders +`index.html` from the root route, and everything else runs in the browser, +where the session is saved: -```ts -// react-router.config.ts +```ts title="react-router.config.ts" import type { Config } from "@react-router/dev/config"; export default { ssr: false } satisfies Config; ``` -Provide the client, and watch for auth changes, in the root route: +### 2. Provide the client in the root route + +In framework mode, `AuthProvider` goes in the root route. The root route also +keeps the guards in step with the session, and shows auth errors: ```tsx title="app/root.tsx" import type { ReactNode } from "react"; import { Links, Meta, Outlet, Scripts, ScrollRestoration } from "react-router"; -import { AuthProvider } from "@monarcode/session-kit/react"; +import { AuthProvider, useAuth } from "@monarcode/session-kit/react"; import { useAuthRevalidation } from "@monarcode/session-kit/react-router"; import { auth } from "./auth.js"; @@ -302,16 +353,22 @@ export function Layout({ children }: { children: ReactNode }) { ); } -/** Runs the client loaders again when auth changes, and with them the guards. */ -function Revalidate() { +/** Runs the client loaders again when auth changes, and shows auth errors. */ +function Root() { useAuthRevalidation(); - return ; + const error = useAuth((state) => state.error); + return ( + <> + {error &&

{error.message}

} + + + ); } export default function App() { return ( - + ); } @@ -322,7 +379,13 @@ export function HydrateFallback() { } ``` -Guard a layout route, and nest the private routes under it: +`AuthProvider` mounts the client in an effect, so the build-time prerender of +the root route starts nothing, and the browser restores the session. + +### 3. Guard a layout route + +Guard a layout route with `requireSessionLoader` as its `clientLoader`. The +private routes go under it in step 5: ```tsx title="app/routes/protected.tsx" import { useRouteError } from "react-router"; @@ -354,8 +417,10 @@ export function ErrorBoundary() { } ``` -Add the sign-in route, which sends signed-in users on to `redirectTo`. Its -loader runs again after a sign-in, so the form doesn't navigate: +### 4. Add the sign-in route + +The sign-in route sends a signed-in user on to `redirectTo`. Its loader runs +again after a sign-in, so the form doesn't navigate: ```tsx title="app/routes/login.tsx" import { redirectIfSignedInLoader } from "@monarcode/session-kit/react-router"; @@ -368,9 +433,11 @@ export const clientLoader = redirectIfSignedInLoader(auth); export default SignIn; ``` -In `app/routes.ts`, nest the routes the layout protects: +### 5. Register the routes + +In `app/routes.ts`, nest the private routes under the layout: -```ts +```ts title="app/routes.ts" import { index, layout, @@ -384,15 +451,21 @@ export default [ ] satisfies RouteConfig; ``` -`routes/home.tsx` is the page, as its default export: -`export { Home as default } from "../home.js";`. - -`AuthProvider` mounts the client in an effect, so the build-time prerender of -the root route starts nothing, and the browser restores the session. +`routes/home.tsx` is the page from Add a page to protect, as its default +export: `export { Home as default } from "../home.js";`. A complete app is in [`examples/react-router-framework-spa`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-framework-spa). +## Check the app + +Whichever mode you chose, check the app: + +1. Signed out, open `/`. You land on `/login?redirectTo=%2F`. +2. Sign in. You're back on `/`, with the welcome message. +3. Reload the page. You're still signed in. +4. Open a second tab and sign out there. The first tab goes to `/login`. + ## Guards in loaders Two functions guard a loader, in data mode and in framework mode. Both send a @@ -403,8 +476,8 @@ typed with your user: that guards and loads nothing else, usually the layout route around your 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. + own. Use it when the loader loads data too: data that only signed-in users + can 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 @@ -433,9 +506,10 @@ export default function Profile() { } ``` -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. +In framework mode, add the page beside the index route in `app/routes.ts`: +`route("profile", "routes/profile.tsx")`. 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 @@ -459,7 +533,7 @@ export function Dashboard() { return (
{user ? `Signed in as ${user.firstName}` : null}
- {/* Keyed by session, so one account's choices never show for the next. */} + {/* Keyed by session: one account's choices never show for the next. */}
Checking session…

} /> @@ -490,14 +564,24 @@ Three things follow from where `SessionOutlet` sits: - **A router `basename`.** Pass it to `requireSessionLoader` or `requireSession` too, so `redirectTo` leaves it out. Redirects add it again. `SessionOutlet` needs nothing. -- **A failed refresh is not a redirect.** In declarative mode, - `SessionOutlet` renders `unavailable`, or throws to the nearest error - boundary without it. In data and framework mode, the guard rethrows it for - the route's error element, which can offer `auth.retry()`. +- **A failed refresh is not a redirect.** When the access token has expired + and a refresh fails, such as while your backend is down, the status is + `unavailable`. The saved session is kept, and `auth.retry()` can restore + access, so the guards don't redirect. In declarative mode, `SessionOutlet` + renders `unavailable`, or throws to the nearest error boundary without it. + In data and framework mode, the guard rethrows the error for the route's + error element. If the retry fails too, the new error shows there again. +- **A route's own `shouldRevalidate`.** It decides whether that route's + loader runs again, even after the session changes. If it returns `false`, + the guard in that loader doesn't run. Return `defaultShouldRevalidate` for + the cases it doesn't handle. +- **The fragment.** A loader's request leaves out the URL's `#fragment`, so + the loader guards' `redirectTo` doesn't keep it. `SessionOutlet` keeps it. - **Locked sessions.** [Locking](/docs/client/locking) is for native apps, so the guards treat a locked session as signed out. -- **Cached data.** `state.sessionId` is new on every sign-in. Scope private - cached data, such as TanStack Query results, to it. +- **Cached data.** Scope private cached data, such as TanStack Query results, + to `state.sessionId`, which is new on every sign-in. See + [State](/docs/client/state). ## Next steps @@ -505,6 +589,9 @@ Three things follow from where `SessionOutlet` sits: in Getting started, or with [ky, axios or openapi-fetch](/docs/client/other-http-clients). It works unchanged with the router. -- [Using the client](/docs/client): updating the user, signing out, and the +- [Using the client](/docs/client): update the user, sign out, and use the client's other methods. -- [Effect and effetch](/docs/effect): the same client as an Effect service. +- [Effect and effetch](/docs/effect): use the same client as an Effect + service. +- [React Router reference](/docs/reference/react-router): every option of the + guards, `SessionOutlet` and `useAuthRevalidation`. diff --git a/site/content/docs/(latest)/setups/tanstack-router.mdx b/site/content/docs/(latest)/setups/tanstack-router.mdx index 759ffcc..db3ff2e 100644 --- a/site/content/docs/(latest)/setups/tanstack-router.mdx +++ b/site/content/docs/(latest)/setups/tanstack-router.mdx @@ -3,37 +3,43 @@ title: TanStack Router description: Keep the client in Router context, guard private routes before they load, and use the hooks without a provider. --- -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. The hooks come from -`@monarcode/session-kit/tanstack-router`, typed by the Router you register, -and need no `AuthProvider`. - -A complete app is in +Your app uses TanStack Router, and some of its routes are for signed-in users +only. In this guide, you add Session kit to the app from Getting started: a +sign-in route, private routes that send signed-out users to it, and hooks that +read the client from the Router. The guards run in `beforeLoad`, so a private +route never loads or renders for someone who isn't signed in. + +The hooks come from `@monarcode/session-kit/tanstack-router`. They're typed by +the Router you register, and they need no `AuthProvider`. A complete app is in [`examples/tanstack-router`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-router). -[TanStack Start in SPA mode](#tanstack-start-in-spa-mode) lists what changes -for Start. For TanStack Start with server rendering, follow -[TanStack Start](/docs/setups/tanstack-start) instead. + +For TanStack Start in SPA mode, follow this guide with +[the changes for Start](#tanstack-start-in-spa-mode). For TanStack Start with +server rendering, follow [TanStack Start](/docs/setups/tanstack-start) +instead. ## Before you begin -Follow [Getting started](/docs/getting-started) through step 3. This guide -uses its client in `src/auth.ts` and its form in `src/sign-in.tsx`. +- A Vite app with React, using `@vitejs/plugin-react`. Installation adds a + plugin to its `vite.config.ts`. +- The app from [Getting started](/docs/getting-started), through step 3. This + guide uses its client in `src/auth.ts` and its form in `src/sign-in.tsx`. ## Installation -To install the packages, run the following commands: +Install Session kit, the Router and Zod, and the Router's Vite plugin as a +dev dependency: ```npm npm install @monarcode/session-kit @tanstack/react-router zod npm install -D @tanstack/router-plugin ``` -This page uses file-based routing, so add the Router plugin before the React -plugin in `vite.config.ts`: +This guide uses file-based routing: the plugin generates +`src/routeTree.gen.ts` from the files under `src/routes`. Add it to +`vite.config.ts`, before the React plugin, or the build fails: -```ts +```ts title="vite.config.ts" import { tanstackRouter } from "@tanstack/router-plugin/vite"; import react from "@vitejs/plugin-react"; import { defineConfig } from "vite"; @@ -46,12 +52,11 @@ export default defineConfig({ }); ``` -The plugin generates `src/routeTree.gen.ts` from the files under `src/routes`. - ## 1. Type the root route The root route declares that Router context holds the client, so every guard -gets a typed `context.auth`: +gets a typed `context.auth`. It stays mounted while pages come and go, which +makes it the place to show auth errors: ```tsx title="src/routes/__root.tsx" import { useAuth } from "@monarcode/session-kit/tanstack-router"; @@ -76,11 +81,14 @@ function Root() { } ``` +`useAuth` reads the client's state from Router context. It's typed with your +user after you register the Router in step 4, and it's typed `never` until +then. + ## 2. Add the sign-in route The sign-in route renders the form from Getting started. Its guard sends a -signed-in user on to the page they asked for, and it runs again after a -sign-in, so the form doesn't navigate: +user who's already signed in on to the page they asked for: ```tsx title="src/routes/login.tsx" import { safeReturnTo } from "@monarcode/session-kit"; @@ -99,17 +107,21 @@ export const Route = createFileRoute("/login")({ }); ``` -`safeReturnTo` accepts only same-origin paths and returns `/` for anything -else, including the sign-in page itself, so a stale `redirectTo` can't loop. -If sign-in isn't at `/login`, pass the same `{ loginPath }` to -`safeReturnTo`, `redirectIfSignedIn` and `requireSession`. -`redirectIfSignedIn` sends signed-in users on to `redirectTo`, checked the -same way. `connectAuth` runs it again after a sign-in. +The form doesn't navigate after it signs in, because this guard does it. +When the session changes, the Router runs the guard again, and it sends the +signed-in user on. Step 4 sets that up. + +`redirectTo` is the search param that the private routes' guard sets. +`safeReturnTo` turns it into a path that's safe to send the user to. Anything +that leads out of your app, or back to the sign-in page, becomes `/`, so a +stale `redirectTo` can't loop. `redirectIfSignedIn` checks it the same way. +The [`safeReturnTo` reference](/docs/reference/core#safereturnto) lists every +rule. ## 3. Guard private routes -Guard private routes with a pathless layout. Its child routes are guarded -without `authenticated` appearing in their URLs: +Guard private routes with a pathless layout route. Its child routes are +guarded without `_authenticated` appearing in their URLs: ```tsx title="src/routes/_authenticated.tsx" import { @@ -129,7 +141,7 @@ export const Route = createFileRoute("/_authenticated")({ component: () => Checking session…

} />, }); -/** Shown after a failed refresh; a repeated failure stays in state.error. */ +/** Shown after a failed refresh; a repeated failure shows here again. */ function SessionError({ error }: ErrorComponentProps) { const auth = useAuthClient(); return ( @@ -141,17 +153,24 @@ function SessionError({ error }: ErrorComponentProps) { } ``` -`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. - -`SessionOutlet` renders child routes while the session the guard accepted is -still the signed-in one. After a sign-out or an account switch it shows -`pending` until the guard runs again, and remounts child routes for the new -account, so nothing from the previous one stays on screen. Profile updates and -token refreshes keep child routes mounted. +`requireSession` lets a signed-in user through, and puts `{ session }` in +route context. It sends a signed-out user to `/login`, or the `loginPath` you +pass, with `redirectTo` set to where they were going. A signed-out user who +opens `/orders?tab=2` lands on `/login?redirectTo=%2Forders%3Ftab%3D2`, and +returns to `/orders?tab=2` after signing in. + +A session that can't be used isn't a sign-out. When the access token has +expired and a refresh fails, such as while your backend is down, the status +is `unavailable`. The saved session is kept, and `auth.retry()` can restore +access. So `requireSession` doesn't redirect: it throws the error to the +route's error component, which offers a retry. If the retry fails too, the +new error shows there again. + +`SessionOutlet` renders the child routes while the session the guard accepted +is still the signed-in one. After a sign-out or an account switch, it shows +`pending` until the guard runs again. It also remounts the child routes for +the new account, so nothing from the previous one stays on screen. Profile +updates and token refreshes keep them mounted. Child routes read the session from route context, where `user` is typed and never `null`: @@ -178,6 +197,9 @@ function Home() { } ``` +A sign-out that fails shows in the root route's alert from step 1, so the +button can ignore the rejection. + ## 4. Create and connect the Router Create the Router with the client in its context, then connect the two: @@ -207,17 +229,21 @@ declare module "@tanstack/react-router" { ``` `connectAuth` does for the Router what `AuthProvider` does for a plain React -app, and one thing more. When the session changes, it runs the guards again, -so a sign-out in another tab redirects this one. +app: it restores the saved session, starts the refresh timer, and follows +other tabs. When the session changes, it does two more things: -Registering the Router also types `useAuth` and `useAuthClient` with your -client. Until it's registered, they're typed `never`. +- It clears the Router's cached and preloaded route data, so one account's + data never shows for the next. +- It runs the guards again, so a sign-in on the sign-in page sends the user + on, and a sign-out in another tab redirects this one. + +Registering the Router types `useAuth` and `useAuthClient` with your client. ## 5. Render the app -Render the Router: +Render the Router in `src/main.tsx`: -```tsx title="src/main.tsx" +```tsx title="src/main.tsx" app="vite" import { StrictMode } from "react"; import { RouterProvider } from "@tanstack/react-router"; @@ -234,9 +260,10 @@ createRoot(document.getElementById("root")!).render( To check the app: -1. Signed out, open `/`. The Router sends you to `/login`. +1. Signed out, open `/`. The Router sends you to `/login?redirectTo=%2F`. 2. Sign in. You're back on `/`, with the welcome message. -3. Open a second tab and sign out there. The first tab goes to `/login`. +3. Reload the page. You're still signed in. +4. Open a second tab and sign out there. The first tab goes to `/login`. ## Layouts around guarded pages @@ -257,7 +284,7 @@ export function Dashboard() { return (
{user ? `Signed in as ${user.firstName}` : null}
- {/* Keyed by session, so one account's choices never show for the next. */} + {/* Keyed by session: one account's choices never show for the next. */}
Checking session…

} /> @@ -295,21 +322,95 @@ route's guard accepted. Three things follow from where it sits: ## TanStack Start in SPA mode -TanStack Start's SPA mode is TanStack Router with a build-time shell. Steps 2 -and 3 apply as they are. Installation, step 1, step 4 and step 5 change: +TanStack Start's SPA mode is TanStack Router with an HTML shell that the build +prerenders. Start renders the whole document from the root route, and the +browser takes over from there. Steps 2 and 3 apply as they are. In place of +Installation and steps 1, 4 and 5, follow these steps. Complete apps are in +[`examples/tanstack-start-spa`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa) +and, written with Effect and effetch, in +[`examples/tanstack-start-spa-effetch`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa-effetch). -- Install `@tanstack/react-start` instead of `@tanstack/router-plugin`. -- In `vite.config.ts`, use Start's plugin, with SPA mode on, instead of the - Router plugin: - `plugins: [tanstackStart({ spa: { enabled: true } }), react()]`. -- Give the root route a `shellComponent` that renders ``, - `` and ``, as the example app does. Start renders - the app from it, so there is no `src/main.tsx`. +### 1. Install Start -In `src/router.tsx`, create the Router and connect auth inside -`getRouter()`, which Start calls: +Install Session kit, the Router and Zod, and Start in place of the Router's +Vite plugin: -```tsx +```npm +npm install @monarcode/session-kit @tanstack/react-router zod +npm install @tanstack/react-start +``` + +### 2. Use Start's Vite plugin + +In `vite.config.ts`, use Start's plugin with SPA mode on, in place of the +Router plugin: + +```ts title="vite.config.ts" app="start" +import { tanstackStart } from "@tanstack/react-start/plugin/vite"; +import react from "@vitejs/plugin-react"; +import { defineConfig } from "vite"; + +export default defineConfig({ + plugins: [tanstackStart({ spa: { enabled: true } }), react()], +}); +``` + +### 3. Render the document from the root route + +Give the root route a `shellComponent` that renders the document, with +`` and ``. Start renders the app from it, so delete +`src/main.tsx` and `index.html`: + +```tsx title="src/routes/__root.tsx" app="start" +import type { ReactNode } from "react"; + +import { useAuth } from "@monarcode/session-kit/tanstack-router"; +import { + createRootRouteWithContext, + HeadContent, + Outlet, + Scripts, +} from "@tanstack/react-router"; + +import type { AppAuth } from "../auth.js"; + +export const Route = createRootRouteWithContext<{ auth: AppAuth }>()({ + shellComponent: Document, + component: Root, +}); + +function Document({ children }: { children: ReactNode }) { + return ( + + + + + + {children} + + + + ); +} + +function Root() { + // Shows failures that outlive the page that caused them. + const error = useAuth((state) => state.error); + return ( + <> + {error &&

{error.message}

} + + + ); +} +``` + +### 4. Create the Router in `getRouter` + +Start creates the Router itself, by calling `getRouter()` from +`src/router.tsx`. Create the Router and connect auth there: + +```tsx title="src/router.tsx" app="start" import { connectAuth } from "@monarcode/session-kit/tanstack-router"; import { createRouter } from "@tanstack/react-router"; @@ -334,9 +435,18 @@ declare module "@tanstack/react-router" { } ``` -And turn server rendering off for routes, in `src/start.ts`: +`connectAuth` does nothing while the Router renders on a server, so the shell +that the build prerenders shows your pending component. `getRouter()` doesn't +keep the function that `connectAuth` returns, because the Router lasts as +long as the page. + +### 5. Turn off server rendering for routes + +Start's own server still answers requests in SPA mode, and it has no saved +session to check. Turn server rendering off for routes in `src/start.ts`, so +the guards run in the browser: -```ts title="src/start.ts" +```ts title="src/start.ts" app="start" import { createStart } from "@tanstack/react-start"; // The session is in browser storage, so guards must run in the browser. @@ -345,28 +455,21 @@ export const startInstance = createStart(() => ({ })); ``` -Start's own server still answers requests in SPA mode, and it has no saved -session to check. `connectAuth` does nothing while the Router renders on a -server, so the build-time shell shows your pending component. Complete apps -are in [`examples/tanstack-start-spa`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa) and, -written with Effect and effetch, in -[`examples/tanstack-start-spa-effetch`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa-effetch). - ## Things to know -- **The first render.** With synchronous storage and a synchronous schema, - `connectAuth` restores the saved session before the first render, so a - signed-in user never sees the sign-in page. +- **Another sign-in page.** If sign-in isn't at `/login`, pass the same + `loginPath` to `requireSession`, `redirectIfSignedIn` and `safeReturnTo`. +- **The first render.** The guards wait for the saved session, so a signed-in + user never sees the sign-in page. With synchronous storage and a + synchronous schema, the session is restored + [before the first paint](/docs#what-it-does). - **Stopping.** Call `disconnectAuth` on app teardown or hot-module disposal. - It stops background work without signing out. In Start's SPA mode, - `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. + It stops background work without signing out. - **Locked sessions.** [Locking](/docs/client/locking) is for native apps, so the guards treat a locked session as signed out. -- **Cached data.** `state.sessionId` is new on every sign-in. Scope private - cached data, such as TanStack Query results, to it. +- **Cached data.** `connectAuth` clears the Router's own cache. Scope your + other private caches, such as TanStack Query results, to `state.sessionId`, + which is new on every sign-in. See [State](/docs/client/state). ## Next steps @@ -374,6 +477,9 @@ written with Effect and effetch, in in Getting started, or with [ky, axios or openapi-fetch](/docs/client/other-http-clients). It works unchanged with the Router. -- [Using the client](/docs/client): updating the user, signing out, and the +- [Using the client](/docs/client): update the user, sign out, and use the client's other methods. -- [Effect and effetch](/docs/effect): the same client as an Effect service. +- [Effect and effetch](/docs/effect): use the same client as an Effect + service. +- [TanStack Router reference](/docs/reference/tanstack-router): every option + of the guards, `SessionOutlet` and `connectAuth`. diff --git a/site/content/docs/(latest)/setups/tanstack-start.mdx b/site/content/docs/(latest)/setups/tanstack-start.mdx index 2c5d0dd..9ff33f5 100644 --- a/site/content/docs/(latest)/setups/tanstack-start.mdx +++ b/site/content/docs/(latest)/setups/tanstack-start.mdx @@ -3,25 +3,35 @@ title: TanStack Start description: Keep the session in an encrypted cookie with TanStack Start, so the server renders the signed-in page first. --- -In this guide, you keep the session in an encrypted cookie with TanStack -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 -[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 -[TanStack Start in SPA mode](/docs/setups/tanstack-router#tanstack-start-in-spa-mode) -instead. A complete app is in +Your TanStack Start app renders pages on the server, and you want the first +response to show the signed-in page, with no "Checking session…" state and no +flash of signed-out content. To do that, the server has to hold the session. +In this guide, you keep it in an encrypted cookie: the server signs in, +refreshes the tokens before rendering, and sends the signed-in page first. + +The browser gets a small client that mirrors the session the server rendered, +and the [TanStack Router hooks and guards](/docs/setups/tanstack-router) work +with it. [Server rendering](/docs/server-rendering) explains how the pieces +fit. A complete app is in [`examples/tanstack-start-ssr`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-ssr). +If your Start app runs in SPA mode, where the browser keeps the session, +follow +[TanStack Start in SPA mode](/docs/setups/tanstack-router#tanstack-start-in-spa-mode) +instead. + ## Before you begin -- Node 22.12 or newer, which Start needs. -- 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`. +- Node.js 22.12 or newer, which TanStack Start needs. See + [Compatibility](/docs/reference/compatibility) for the other versions. +- A secret of 32 or more random characters to seal the cookie, such as the + output of `openssl rand -base64 32`, set as `SESSION_SECRET` on the server. + `vite build` doesn't need it. + [The secret](/docs/server-rendering/server-sessions#the-secret) says how to + keep and rotate it. +- The code signs in with [DummyJSON](https://dummyjson.com/docs/auth)'s test + backend, as [Getting started](/docs/getting-started) does. Replace its URLs + with your backend's. ## Installation @@ -33,10 +43,11 @@ npm install @monarcode/session-kit @tanstack/react-start @tanstack/react-router ## 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. -`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: +The server engine keeps the session in a cookie sealed with your secret, and +refreshes the tokens with your backend. `createServerAuth` from +`@monarcode/session-kit/server` makes it, and `startAuth` gives you 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"; @@ -44,7 +55,7 @@ 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"; +export const API = "https://dummyjson.com"; const userSchema = z.object({ id: z.number(), firstName: z.string() }); const tokens = z.object({ accessToken: z.string(), refreshToken: z.string() }); @@ -60,8 +71,8 @@ export const serverAuth = createServerAuth({ headers: { "Content-Type": "application/json" }, body: JSON.stringify({ refreshToken }), }); - // The backend rejected the refresh token: sign out. - if (response.status === 401) return null; + // DummyJSON rejected the refresh token: sign out. + if (response.status === 401 || response.status === 403) return null; if (!response.ok) throw new Error(`Refresh failed (${response.status})`); return tokens.parse(await response.json()); }, @@ -91,16 +102,18 @@ export async function login(username: string, password: string) { } ``` -[Server sessions](/docs/server-rendering/server-sessions#the-cookie) covers -its other options, rotating the secret, signing out, and the limits every -setup shares. +`session` finds the request each time it's called, so one object, made at +module level, serves every request. [Server +sessions](/docs/server-rendering/server-sessions) covers the engine's other +options, the cookie, and signing out. ## 2. Add the session route and server functions 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: +route: a route in your app that the browser's client calls. +`sessionRoute` from `@monarcode/session-kit/tanstack-start/server` makes its +`GET` and `POST` handlers. Start leaves a route's `server.handlers` out of the +browser bundle, and `serverAuth` with them: ```ts title="src/routes/api/session.ts" import { sessionRoute } from "@monarcode/session-kit/tanstack-start/server"; @@ -113,14 +126,12 @@ export const Route = createFileRoute("/api/session")({ }); ``` -It answers your own site's pages only, so another site can't sign the user -out: see [The session route](/docs/security#the-session-route). +The session route answers your own site's pages only, so another site can't +sign the user 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 -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: +Two server functions do the rest. One signs in with your form's input. The +other reads the session, because `loadSession` reads it while Start renders on +the server, where the client can't call a route on its own site: ```ts title="src/auth/functions.ts" import { createServerFn } from "@tanstack/react-start"; @@ -146,16 +157,12 @@ handler with a request in the browser bundle, and leaves `session` out of it. ## 3. Refresh before rendering -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. - -`refreshSession` from `@monarcode/session-kit/tanstack-start/server` does -the refresh. Pass it to Start's own `createMiddleware().server()`. Start -bundles `src/start.ts` for the browser too, but strips what's inside -`.server()`, so `serverAuth` stays on the server: +The server refreshes tokens that are about to expire before any route or +server function reads them, while the response can still set the cookie. +After Start starts streaming a page, a cookie set later is lost, and so are +the new tokens. `refreshSession` from +`@monarcode/session-kit/tanstack-start/server` does the refresh, in Start's +own request middleware: ```ts title="src/start.ts" import { refreshSession } from "@monarcode/session-kit/tanstack-start/server"; @@ -181,30 +188,32 @@ 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 })`. +Start bundles `src/start.ts` for the browser too, but strips what's inside +`.server()`, so `serverAuth` stays on the server. -A failed refresh doesn't fail the request. Routes read the session as -usual, and an error there reaches the route's error component. +`refreshSession` refreshes access tokens that expire within 60 seconds. For +tokens that live a minute or less, pass a smaller `within`, such as +`refreshSession(serverAuth, { within: 15 })`. +[Refresh before rendering](/docs/server-rendering/server-sessions#refresh-before-rendering) +says what happens when a refresh fails. -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. It leaves out server routes. -`sessionRoute` refuses other sites itself, and a server route of your own -that changes the session must too: see -[The session route](/docs/security#the-session-route). +`createCsrfMiddleware` protects your server functions, because an app that +defines `createStart` has no CSRF check until it adds one. Here's what it +covers: -## 4. Create the browser client +- Its `filter` limits the check to server-function calls. Without the filter, + it also refuses page loads from links on other sites and from the address + bar. +- Filtered this way, it doesn't check server routes. `sessionRoute` refuses + other sites itself. A server route of your own that changes the session + must check too: see + [Check your own routes](/docs/security#check-your-own-routes). -`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. `connectSession` sends the session the -server read to the browser with the page, and runs guards again when it -changes there. +## 4. Create the browser client -First, the client: +The client that routes and components use comes from `createMirrorAuth`. It +mirrors the session the server read, and calls your server functions and the +session route. Create it in a function, not at module level: ```ts title="src/auth/client.ts" import { createMirrorAuth } from "@monarcode/session-kit"; @@ -225,7 +234,13 @@ export function createAppAuth() { export type AppAuth = ReturnType; ``` -Then the Router, which creates it and connects it: +Let TypeScript infer the client's types from its options. With +`createMirrorAuth(…)`, `signIn` would be left out. + +The Router creates the client in `getRouter`, which Start calls once per +request on the server and once in the browser. `connectSession` sends the +session the server read to the browser with the page, and runs the guards +again when the session changes there: ```tsx title="src/router.tsx" import { connectSession } from "@monarcode/session-kit/tanstack-start"; @@ -248,36 +263,71 @@ declare module "@tanstack/react-router" { } ``` -Let TypeScript infer the client's types from its options. With -`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. +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 The root route's `beforeLoad` reads the request's session into the client -with `loadSession`, before any guard runs. In the browser, the hydrated -session is already there, so it doesn't call the server: +with `loadSession`, before any guard runs. In the browser, the session that +came with the page is already there, so it doesn't call the server. The root +route also renders the document, with `` so the page hydrates, and +an error component for when the session can't be read: ```tsx title="src/routes/__root.tsx" +import type { ReactNode } from "react"; + import { loadSession } from "@monarcode/session-kit/tanstack-start"; -import { createRootRouteWithContext, Outlet } from "@tanstack/react-router"; +import { + createRootRouteWithContext, + HeadContent, + Outlet, + Scripts, + useRouter, + type ErrorComponentProps, +} from "@tanstack/react-router"; import type { AppAuth } from "../auth/client"; export const Route = createRootRouteWithContext<{ auth: AppAuth }>()({ beforeLoad: ({ context }) => loadSession(context.auth), + shellComponent: Document, + errorComponent: SessionError, component: Outlet, }); + +function Document({ children }: { children: ReactNode }) { + return ( + + + + + + {children} + + + + ); +} + +function SessionError({ error }: ErrorComponentProps) { + const router = useRouter(); + return ( +
+

{error instanceof Error ? error.message : "Something went wrong"}

+ {/* Runs loadSession again. */} + +
+ ); +} ``` 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. +`loadSession` rejects and `SessionError` shows. Its button calls +`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: +server, a guard's redirect is a real HTTP redirect: ```tsx title="src/routes/_authenticated.tsx" import { @@ -293,18 +343,22 @@ export const Route = createFileRoute("/_authenticated")({ }); ``` +A signed-out user who opens a page under `_authenticated`, such as `/orders`, +lands on `/login?redirectTo=%2Forders`. [Guard private routes](/docs/setups/tanstack-router#3-guard-private-routes) -explains `SessionOutlet`. Its error component isn't needed here, as -`loadSession` reports a failed refresh first. +explains `SessionOutlet`. This route needs no error component of its own: +`loadSession` reports a failed read first, in the root route. -Guards decide what a page shows. Server functions that return private data -must check the session themselves, with `session.getSession()` or -`session.credentials.get()`. +Guards decide what a page shows. A server function that returns private data +must check the session itself, with `session.getSession()` or +`session.credentials.get()`, as `getOrdersFn` does in +[Call your API](#call-your-api). -## Sign in +## 6. Sign in -The client's `signIn` sends what it's given to your `signInFn`, then adopts -the session it returns, re-runs guards and tells other tabs: +The client's `signIn` sends what it's given to your `signInFn`, then takes the +session it returns, runs the guards again and tells other tabs. A small helper +turns a failure into the message to show: ```ts title="src/sign-in.ts" import type { AppAuth } from "./auth/client"; @@ -326,24 +380,80 @@ export async function signIn( } ``` -In a component, `useAuthClient` from `@monarcode/session-kit/tanstack-router` -gives you `auth`, from Router context. +The sign-in route has the `redirectIfSignedIn` guard, so a signed-in user goes +on to `redirectTo`. Its form gets the client with `useAuthClient`, from Router +context: + +```tsx title="src/routes/login.tsx" +import { useState, type FormEvent } from "react"; -Give the sign-in route the `redirectIfSignedIn` guard, as in TanStack Router's -[Add the sign-in route](/docs/setups/tanstack-router#2-add-the-sign-in-route). -`connectSession` runs it again after a sign-in, so the form doesn't navigate. +import { safeReturnTo } from "@monarcode/session-kit"; +import { + redirectIfSignedIn, + useAuthClient, +} from "@monarcode/session-kit/tanstack-router"; +import { createFileRoute } from "@tanstack/react-router"; + +import { signIn } from "../sign-in"; + +export const Route = createFileRoute("/login")({ + validateSearch: (search: Record) => ({ + redirectTo: safeReturnTo(search.redirectTo), + }), + beforeLoad: ({ context, search }) => + redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }), + component: Login, +}); + +function Login() { + const auth = useAuthClient(); + const [error, setError] = useState(null); + + async function submit(event: FormEvent) { + event.preventDefault(); + const form = new FormData(event.currentTarget); + const username = String(form.get("username")); + setError(await signIn(auth, username, String(form.get("password")))); + } -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 instead, as -[Hybrid setup](/docs/server-rendering/hybrid) shows. + return ( +
void submit(event)}> + + + {error &&

{error}

} + +
+ ); +} +``` + +The form doesn't navigate after a sign-in. `connectSession` runs the guards +again, and `redirectIfSignedIn` sends the user on. To try it, sign in as +`emilys` with the password `emilyspass`. A wrong password shows DummyJSON's +own message, which `login` threw. -## Sign out +In this guide, the server signs in with your backend, so the user in the +cookie comes from the backend. If the browser has to sign 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. + +## 7. 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: +which clears the cookie and calls your `revoke` option, if `createServerAuth` +has one. It then signs out this tab and tells the others. The guards run +again, so `requireSession` sends the user to the sign-in page. Put a button +like this one on any page under `_authenticated`: ```tsx title="src/sign-out.tsx" import { useAuthClient } from "@monarcode/session-kit/tanstack-router"; @@ -359,77 +469,87 @@ export function SignOutButton() { } ``` +Without `revoke`, a copy of the cookie made before sign-out still works: see +[Sign-out](/docs/server-rendering/server-sessions#sign-out). + ## Call your API -Call your API with `createAuthFetch` from `@monarcode/session-kit/http`. -Given `session`, it sends the access token of the request Start is handling, -refreshed first when it has expired. After a 401, it renews the token, saves -it in the cookie, and sends a `GET` again. Make it once, in a server-only -module: +Your server functions call your API with `createAuthFetch` from +`@monarcode/session-kit/http`. Given `session`, it sends the access token of +the request Start is handling, refreshed first if it has expired. Make it +once, in a server-only module: -```ts title="src/auth/api-fetch.ts" +```ts title="src/auth/auth-fetch.ts" import "@tanstack/react-start/server-only"; import { createAuthFetch } from "@monarcode/session-kit/http"; -import { session } from "./server"; +import { API, session } from "./server"; -export const apiFetch = createAuthFetch(session, { - baseUrl: "https://api.example.com/", -}); +export const authFetch = createAuthFetch(session, { baseUrl: `${API}/` }); ``` -Then call it in a server function. Signed out, it rejects with -`UNAUTHENTICATED`: +Then call it in a server function. This one checks the session first, so it +can ask for the signed-in user's orders: ```ts title="src/orders.ts" import { createServerFn } from "@tanstack/react-start"; import { z } from "zod"; -import { apiFetch } from "./auth/api-fetch"; +import { authFetch } from "./auth/auth-fetch"; +import { session } from "./auth/server"; + +const orders = z.object({ carts: z.array(z.object({ id: z.number() })) }); export const getOrdersFn = createServerFn().handler(async () => { - const response = await apiFetch("orders"); + const current = await session.getSession(); + if (!current) throw new Error("Sign in to see your orders"); + const response = await authFetch(`auth/carts/user/${current.user.id}`); if (!response.ok) throw new Error(`Orders failed (${response.status})`); - return z.array(z.object({ id: z.number() })).parse(await response.json()); + return orders.parse(await response.json()).carts; }); ``` +When the user is signed out, `authFetch` rejects with `UNAUTHENTICATED`. When +your API answers 401, it gets a new access token and saves it in the cookie. +It sends a `GET` or `HEAD` again with the new token, as +[After a 401](/docs/client/requests#after-a-401) explains. + With an HTTP client of your own, such as ky or axios, see [Other HTTP clients](/docs/client/other-http-clients). A client without a `fetch` option reads the token with `session.credentials.get()`. -To call the API from the browser too, with `createAuthFetch` or effetch's -`sessionBearer`, opt in with `clientCredentials: true` in `createServerAuth`. -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. +To call your API from the browser too, turn on `clientCredentials` in +`createServerAuth`: see +[The access token in the browser](/docs/server-rendering/server-sessions#the-access-token-in-the-browser). +The example app does this. ## Things to know -- **Signing out ends the session only with `revoke`.** Without it, a copy of - the cookie made before sign-out still works: see - [Sign-out](/docs/server-rendering/server-sessions#sign-out). -- **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. `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 }`. +- **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, its methods reject with + `INVALID_OPTIONS`, and `isCurrent` and `state` throw it. +- **Caching.** `refreshSession` sends `Cache-Control: private, no-store` + with each response that doesn't set its own, so shared caches keep no + user's page: see + [Refresh before rendering](/docs/server-rendering/server-sessions#refresh-before-rendering) + for `cacheControl`. - **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. -- **Tabs.** Signing in or out in one tab reaches the others, which ask the - server again. So does returning to a tab after a while. -- **More.** Several server instances, the cookie's size, and plain http - during development: see +- **Other tabs.** Signing in or out in one tab reaches the others, which ask + the server for the session and run the guards again: see + [How tabs stay in step](/docs/server-rendering#how-tabs-stay-in-step). +- **Deploying.** Several server instances, the cookie's size, and plain http + during development are covered in [Server sessions](/docs/server-rendering/server-sessions). ## Next steps -- [Server sessions](/docs/server-rendering/server-sessions): the cookie, - signing out, and the limits every server-rendered setup shares. -- [Using the client](/docs/client): what the browser client can do. -- [Effect on the server](/docs/effect#on-the-server): run Effects with a +- [Server sessions](/docs/server-rendering/server-sessions): the cookie, the + secret, signing out, and the limits every server-rendered setup shares. +- [Hybrid setup](/docs/server-rendering/hybrid): sign in from the browser + and call your API there, with the session still on the server. +- [Using the client](/docs/client): what the browser's client can do. +- [Use Effect on the server](/docs/effect/server): run Effects with a request's session. diff --git a/site/src/lib/page-apps.ts b/site/src/lib/page-apps.ts index aa94e04..35e0e3f 100644 --- a/site/src/lib/page-apps.ts +++ b/site/src/lib/page-apps.ts @@ -3,10 +3,11 @@ import { relative, sep } from "node:path"; import type { Element, ElementContent, Root, RootContent } from "hast"; import { + APP, compilerSettings, documents, installedAtLeast, - pageApp, + pageApps, root, TITLE, } from "../../../scripts/docs-pages.mjs"; @@ -66,14 +67,19 @@ export function rehypePageApps() { ); if (missing) return; // `check-docs` reports a page's problems; the site only reads it. - const app = pageApp(document, () => {}); + const apps = pageApps(document, () => {}); // The dev server rebuilds the page when a file it borrows from changes. - for (const origin of new Set(app.map((other) => other.origin))) + for (const origin of new Set( + [...apps.values()].flat().map((other) => other.origin), + )) file.data._compiler?.addDependency(origin); visitCode(tree, (code) => { const meta = String(code.data?.meta ?? ""); const title = TITLE.exec(meta)?.[1]; if (!title || OPT_OUT.test(meta)) return; + // The app `check-docs` compiles this example in. + const name = APP.exec(meta)?.[1] ?? ""; + const app = apps.get(name) ?? []; if (!app.some((other) => other.path === title)) return; const hidden = app .filter((other) => other.path !== title) @@ -88,7 +94,7 @@ export function rehypePageApps() { // program, where each copy of a page's `declare module` would // merge with the others. An export condition of its own, which // no package has, gives each block a program of its own. - `// @customConditions: ${document.path}#${title}`, + `// @customConditions: ${document.path}#${name}#${title}`, // The hidden files are `check-docs`' to report. "// @noErrorsCutted", ...(document.dom ? [] : [NO_DOM_LIB]), diff --git a/site/src/lib/tour.ts b/site/src/lib/tour.ts index f2eee53..af79e5c 100644 --- a/site/src/lib/tour.ts +++ b/site/src/lib/tour.ts @@ -8,7 +8,7 @@ import type { Element, ElementContent } from "hast"; import { codeThemes } from "@/lib/shared"; -import { MARKERS } from "../../../scripts/docs-pages.mjs"; +import { APP, MARKERS } from "../../../scripts/docs-pages.mjs"; /** * The landing page's code tour: one app, the TanStack Router setup, which @@ -50,8 +50,9 @@ async function readExample(page: string, file: string): Promise { join("content/docs/(latest)", `${page}.mdx`), "utf8", ); + // The page's main version, not a named app's version of the file. const example = [...text.matchAll(MARKERS.mdx)].find( - (match) => match[1] === file, + (match) => match[1] === file && !APP.test(match[0].split("\n")[0]!), ); if (!example) throw new Error(`${page}.mdx has no example titled ${file}`); return example[2]!; diff --git a/src/core/client.ts b/src/core/client.ts index 36fc4ce..bad0af9 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -22,7 +22,7 @@ import { type UserSource, } from "./sources.js"; import { countMounts, inBackground, stateView } from "./store.js"; -import { runTask } from "./task.js"; +import { abortWith, runTask } from "./task.js"; import { setLongTimeout, proactiveRefreshDelay } from "./timers.js"; import { receiveTokens, tokensOf, type SessionTokens } from "./tokens.js"; import type { @@ -430,7 +430,7 @@ export function createAuth( // A cancelled refresh never finished, so it doesn't use up the attempt. if (flight) refreshAttempted = false; epoch++; - controller.abort(sessionChanged()); + abortWith(controller, sessionChanged()); controller = new AbortController(); flight = undefined; initialization = undefined; @@ -810,7 +810,7 @@ export function createAuth( function cancelSignIn() { signInIntent++; - signInController.abort(sessionChanged()); + abortWith(signInController, sessionChanged()); signInController = new AbortController(); } diff --git a/src/core/debug.ts b/src/core/debug.ts index b3c14f6..3e0b766 100644 --- a/src/core/debug.ts +++ b/src/core/debug.ts @@ -1,8 +1,9 @@ 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. + * Which part of Session kit 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 @@ -37,7 +38,7 @@ export type AuthDebugType = | "lock"; /** - * One thing auth did, sent to the `debug` option ({@link AuthDebug}). + * One thing the client did, sent to the `debug` option ({@link AuthDebug}). * * Filter on `type`, which doesn't change between releases. `message` and * `data` are for reading, and may change in any release. Events are frozen, @@ -62,7 +63,7 @@ export type AuthDebugType = export type AuthDebugEvent = Readonly<{ /** The `name` option of the client that reports it. */ name: string; - /** Which part of auth it comes from. */ + /** Which part of Session kit it comes from. */ type: AuthDebugType; /** One readable line, such as `started (proactive)`. */ message: string; diff --git a/src/core/errors.ts b/src/core/errors.ts index c3c74ba..3ab243f 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -22,24 +22,34 @@ export type AuthErrorCode = * 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. + * + * It also covers a schema that doesn't return its own output unchanged + * (saved users are checked again when restored), an access token that + * `fromAccessToken` can't read, and a user your refresh callback returned + * that the schema rejects. */ | "USER_VALIDATION_FAILED" /** * 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 that's malformed. - * In the browser of a server-rendered app, your server answered with - * something other than a session or an access token. + * Tokens from your refresh callback fail with it too when they last + * under five seconds, have already expired, or repeat the access token + * your API rejected. 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, or `locking.seal` failed. - * In the browser of a server-rendered app, signing out on the server - * failed. + * That includes a session too large to save: over two cookies on the + * server, or more than `secureStorage` holds. In the browser of a + * server-rendered app, signing out on the server failed. */ | "PERSISTENCE_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 + * The refresh failed: your refresh callback threw or timed out, or + * `refresh()` was called without a `refresh` option or a refresh token. + * Without them, an access token that expires or that your API rejects + * signs the user out instead, with no error. 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. @@ -51,8 +61,9 @@ export type AuthErrorCode = */ | "REVOKE_FAILED" /** - * The session changed while the call ran: a newer sign-in, a sign-out, or - * another tab replaced it. + * The session changed while the call ran: a newer sign-in, a sign-out, a + * newer `updateUser` call, or another tab replaced it. A route guard + * rejects with it when the session kept changing while it was read. */ | "SESSION_CHANGED" /** The call needs someone signed in, and no one is. */ @@ -64,7 +75,9 @@ export type AuthErrorCode = /** * 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. + * a request that can't set cookies. In the browser of a server-rendered + * app, your session route refused the request, such as one from a page + * an older version of your app served. */ | "INVALID_OPTIONS"; diff --git a/src/core/storage.ts b/src/core/storage.ts index cf56ec2..2dbc57c 100644 --- a/src/core/storage.ts +++ b/src/core/storage.ts @@ -4,14 +4,14 @@ import { AuthError } from "./errors.js"; type MaybePromise = T | Promise; /** - * Where auth saves the session: `createAuth`'s `storage` option. Use + * Where Session kit saves the session: `createAuth`'s `storage` option. Use * {@link webStorage} in browsers, `secureStorage()` from * `@monarcode/session-kit/expo` in Expo apps, and {@link memoryStorage} in * tests. Implement it yourself for another store. * - * Values are strings in a format auth owns. Methods may return promises. Auth - * runs them one at a time, in order, so a store that answers out of order is - * still safe. + * Values are strings in a format Session kit owns. Methods may return + * promises. Session kit runs them one at a time, in order, so a store that + * answers out of order is still safe. * * @example * ```ts @@ -124,9 +124,9 @@ export type WebStorageOptions = { * 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 - * fails with `PERSISTENCE_FAILED`. + * It touches browser storage only when the client reads or saves, so + * creating a client in code that also runs on a server is safe. Reading the + * session on a server fails with `PERSISTENCE_FAILED`. * * @example * ```ts diff --git a/src/core/task.ts b/src/core/task.ts index 62614a0..1521684 100644 --- a/src/core/task.ts +++ b/src/core/task.ts @@ -1,6 +1,24 @@ /** Deadline for validation and refresh work. */ const TASK_TIMEOUT_MS = 15_000; +/** + * Why each signal was aborted. React Native before 0.87 polyfills + * `AbortController` without `reason` or `throwIfAborted`, so the client + * keeps the reason itself rather than read it back from the signal. + */ +const reasons = new WeakMap(); + +/** Aborts `controller` with `reason`, which {@link abortReason} returns. */ +export function abortWith(controller: AbortController, reason: unknown) { + if (!controller.signal.aborted) reasons.set(controller.signal, reason); + controller.abort(reason); +} + +/** Why `signal` was aborted, on every platform. */ +export function abortReason(signal: AbortSignal): unknown { + return reasons.has(signal) ? reasons.get(signal) : signal.reason; +} + /** * Runs `work` with a signal tied to `parent` and a timeout. Rejects on abort or * timeout even when `work` ignores the signal, so late results never commit. @@ -11,22 +29,23 @@ export function runTask( timeoutMs = TASK_TIMEOUT_MS, ): Promise { const controller = new AbortController(); - const abort = () => controller.abort(parent.reason); + const { signal } = controller; + const abort = () => abortWith(controller, abortReason(parent)); parent.addEventListener("abort", abort, { once: true }); if (parent.aborted) abort(); const timer = setTimeout( - () => controller.abort(new Error("Auth operation timed out")), + () => abortWith(controller, new Error("Auth operation timed out")), timeoutMs, ); return new Promise((resolve, reject) => { - const fail = () => reject(controller.signal.reason); - controller.signal.addEventListener("abort", fail, { once: true }); - if (controller.signal.aborted) fail(); + const fail = () => reject(abortReason(signal)); + signal.addEventListener("abort", fail, { once: true }); + if (signal.aborted) fail(); else Promise.resolve() .then(() => { - controller.signal.throwIfAborted(); - return work(controller.signal); + if (signal.aborted) throw abortReason(signal); + return work(signal); }) .then(resolve, reject); }).finally(() => { diff --git a/src/core/types.ts b/src/core/types.ts index c6a2c68..75784b3 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -67,7 +67,8 @@ export type UserInput = * * When the access token expires comes from the first of these that is set: * 1. `expiresIn` or `expiresAt`. Pass one, not both. - * 2. A JWT access token's `exp - iat`, counted from when auth receives it. + * 2. A JWT access token's `exp - iat`, counted from when the client + * receives it. * 3. A JWT access token's `exp` alone, compared with the device's clock. * * With none of them, the token never expires on its own. It's replaced only @@ -110,8 +111,8 @@ export type Tokens = { refreshToken?: string | undefined; /** * How long the access token lasts, in **seconds**, like OAuth's - * `expires_in` (`900` is 15 minutes). It's counted from when auth receives - * the token, so a wrong device clock doesn't matter. + * `expires_in` (`900` is 15 minutes). It's counted from when the client + * receives the token, so a wrong device clock doesn't matter. */ expiresIn?: number | undefined; /** @@ -149,7 +150,7 @@ export type SignInInput = [I] extends [never] : Tokens & { /** * The signed-in user, checked against the `user` schema. It must be a - * plain JSON object. Auth keeps a frozen copy. + * plain JSON object. The client keeps a frozen copy. */ user: I; }; @@ -162,7 +163,7 @@ export type SignInInput = [I] extends [never] * * For any other failure, such as a network error or a 5xx, throw. The session * is kept, and the failure shows as a `REFRESH_FAILED` error whose `cause` is - * what you threw. + * what you threw. An `AuthError` you throw keeps its own `code`. * * With `fromAccessToken`, return tokens only. The user is read from the new * access token. @@ -202,7 +203,7 @@ export type RefreshResult = * Exchanges a refresh token for new tokens. It's the `refresh` option of * {@link AuthOptions}. * - * Auth calls it whenever it needs a new access token: shortly before the + * The client 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 @@ -583,8 +584,10 @@ type AuthClientBase = { * 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. + * Rejects with the refresh's failure, such as `REFRESH_FAILED`, or + * `INVALID_SESSION` and `USER_VALIDATION_FAILED` for tokens or a user + * the client can't use. Rejects with `SESSION_CHANGED` when another + * session has replaced theirs, and with `LOCKED` while locked. */ renew: (credentials: Credentials) => Promise; /** @@ -631,9 +634,15 @@ 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 takes more than 15 seconds. If calls + * the function rejects or takes more than 15 seconds. An + * `AuthError` the function throws keeps its own `code`. If calls * overlap, the latest wins and the others reject with * `SESSION_CHANGED`. + * + * It reads the session as `getSession()` does first, so it rejects + * with `LOCKED` while locked, and with a refresh's failure, such as + * `REFRESH_FAILED`. If the new user can't be saved, it rejects with + * `PERSISTENCE_FAILED` and signs out. */ updateUser: (input: I | (() => Promise)) => Promise; }); @@ -642,7 +651,7 @@ export type AuthClient = AuthClientBase & * Encrypts the saved tokens with a key your app holds, such as one behind * Face ID. Pass it as the `locking` option of {@link AuthOptions}. * - * Auth calls `seal` whenever it saves tokens, and `open` only from + * The client calls `seal` whenever it saves tokens, and `open` only from * `unlock()`. The user and session ID are saved unencrypted, so a locked * session can still show who is signed in. * @@ -736,13 +745,14 @@ export type AuthOptions = { * 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, and the user is signed out without an error. So is a session - * saved by another version of session-kit. Default: 30 days. + * saved in another format by an older or newer version of Session kit. + * Default: 30 days. */ maxAge?: number | undefined; /** - * Logs what auth does, for debugging: restores, refreshes, timers, storage - * and state changes. `true` logs to the console, and a function receives - * each event instead ({@link AuthDebug}). + * Logs what the client does, for debugging: restores, refreshes, timers, + * storage and state changes. `true` logs to the console, and a function + * receives each event instead ({@link AuthDebug}). * * Tokens, user fields, saved values and error details are left out unless * you pass `{ sensitive: true }`. Pass a development flag, such as Expo's diff --git a/src/effect/auth.ts b/src/effect/auth.ts index 4117ea5..737a843 100644 --- a/src/effect/auth.ts +++ b/src/effect/auth.ts @@ -316,7 +316,7 @@ export class Auth extends Context.Service()( /** * Saves a new session from `input`, as the client's `signIn` does, for - * example after a login request. + * example after a sign-in request. * * Fails with `USER_VALIDATION_FAILED`, `INVALID_SESSION`, * `PERSISTENCE_FAILED` or `SESSION_CHANGED`. With a `createMirrorAuth` diff --git a/src/effetch/index.ts b/src/effetch/index.ts index 247db0d..8c054b8 100644 --- a/src/effetch/index.ts +++ b/src/effetch/index.ts @@ -101,10 +101,11 @@ const refuseRedirects = ( /** * An effetch plugin that sends the current access token as * `Authorization: Bearer`. After a 401, it gets a new access token once. - * `GET` and `HEAD` requests are then sent again; other requests return the - * 401 for you to retry. If the request sent again gets a 401 too, the user - * is signed out, unless `signOutOnRepeated401` is off. If the renewal ends - * the session, the call returns the 401. + * `GET` and `HEAD` requests are then sent again. Other requests keep their + * 401, which effetch fails the call with as an `HttpError`, for you to + * retry. If the request sent again gets a 401 too, the user is signed out, + * unless `signOutOnRepeated401` is off. If the renewal ends the session, the + * call fails with the 401 too. * * Calls fail with `AuthFailure`, before sending anything: `UNAUTHENTICATED` * when signed out, unless `optional` sends them without a token, and @@ -122,7 +123,9 @@ const refuseRedirects = ( * 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 * Effect's `FetchHttpClient`, a redirect fails as a `Fetch.NetworkError` - * rather than being followed. An invalid `baseUrl` throws `INVALID_OPTIONS`. + * rather than being followed, except on React Native before Expo SDK 58, + * whose `fetch` follows redirects whatever it's told. An invalid `baseUrl` + * throws `INVALID_OPTIONS`. * * A request that already has an `Authorization` header is sent as it is, as * effetch's `bearer` does. diff --git a/src/expo/secure-storage.ts b/src/expo/secure-storage.ts index 93d0e69..91773cc 100644 --- a/src/expo/secure-storage.ts +++ b/src/expo/secure-storage.ts @@ -34,8 +34,9 @@ export type SecureStorageOptions = { * 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 - * signed out. + * If the keychain can't be read when the app starts, the session is + * `unavailable`, not signed out. A refresh that runs while it's locked + * can't save the new tokens, and that signs the user out. * @default WHEN_UNLOCKED */ keychainAccessible?: KeychainAccessibilityConstant | undefined; diff --git a/src/http/index.ts b/src/http/index.ts index 021d66c..dd74d9a 100644 --- a/src/http/index.ts +++ b/src/http/index.ts @@ -109,6 +109,48 @@ async function discard(response: Response) { await response.body?.cancel().catch(() => {}); } +/** + * Sends `request` without following a redirect, which could carry the token + * elsewhere. `redirect` goes in `init` too: Expo's `fetch` reads it only + * there. React Native's `fetch` before Expo SDK 58 follows redirects + * whatever it's told, so a response from another origin or path rejects + * as a refused redirect does in browsers. + */ +async function sendOnce(request: Request): Promise { + const sent = new Request(request, { + redirect: "error", + // A `Request` copied with an `init` loses these otherwise. + referrer: request.referrer, + referrerPolicy: request.referrerPolicy, + }); + const response = await fetch(sent, { redirect: "error" }); + if (followedRedirect(response, sent.url)) { + await discard(response); + throw new TypeError("authFetch doesn't follow redirects"); + } + return response; +} + +/** + * Whether `response` came from a redirect. Platforms spell the same URL + * differently, such as `[` or `%5B` in a query, so only the origin and the + * decoded path are compared. + */ +function followedRedirect(response: Response, sent: string): boolean { + if (response.redirected) return true; + if (typeof response.url !== "string" || response.url === "") return false; + try { + const final = new URL(response.url); + const asked = new URL(sent); + return ( + final.origin !== asked.origin || + decodeURI(final.pathname) !== decodeURI(asked.pathname) + ); + } catch { + return false; + } +} + /** * Creates a `fetch` for your API ({@link AuthFetch}) that sends the current * access token as `Authorization: Bearer`. After a 401, it gets a new access @@ -126,10 +168,16 @@ async function discard(response: Response) { * 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`, as does a `Request` from another realm or a polyfill. - * A redirect rejects rather than being followed. A - * missing or invalid `baseUrl` throws `INVALID_OPTIONS`. While signed in, a + * A missing or invalid `baseUrl` throws `INVALID_OPTIONS`. While signed in, a * request's own `Authorization` header is replaced. * + * A redirect isn't followed: the request rejects as `fetch` does when it + * refuses one, with a `TypeError` in browsers and Node.js. On React Native + * before Expo SDK 58, `fetch` follows a redirect whatever it's told. The + * response is still refused, with a `TypeError`, but the redirected request + * has already gone out, so don't let your API redirect requests that carry + * a token. + * * `fetch`'s own failures, such as a network error, and an `init` that * `Request` refuses, reject as `fetch` and `Request` do. * @@ -203,15 +251,28 @@ export function createAuthFetch( // 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 request = new Request( + given ?? url, + given + ? { + referrer: given.referrer, + referrerPolicy: given.referrerPolicy, + ...init, + } + : init, + ); const canReplay = request.method === "GET" || request.method === "HEAD"; const send = async (session: Credentials) => { if (!auth.isCurrent(session)) throw sessionChanged(); const headers = new Headers(request.headers); headers.set("Authorization", `Bearer ${session.accessToken}`); - const response = await fetch( - new Request(request, { headers, redirect: "error" }), + const response = await sendOnce( + new Request(request, { + headers, + referrer: request.referrer, + referrerPolicy: request.referrerPolicy, + }), ); if (!auth.isCurrent(session)) { await discard(response); @@ -221,9 +282,7 @@ export function createAuthFetch( }; if (!captured) { - const response = await fetch( - new Request(request, { redirect: "error" }), - ); + const response = await sendOnce(request); // A 401 for the signed-out request must not reach a 401 handler that // would then sign out the account that just signed in. if (auth.state.get().sessionId !== null) { diff --git a/src/server/auth.ts b/src/server/auth.ts index 44600b8..2218ed2 100644 --- a/src/server/auth.ts +++ b/src/server/auth.ts @@ -143,7 +143,8 @@ export type ServerAuthOptions = { */ clientCredentials?: boolean | undefined; /** - * Logs what auth does on the server, like `createAuth`'s `debug` option. + * Logs what Session kit does on the server, like `createAuth`'s `debug` + * option. */ debug?: AuthDebug | undefined; }; diff --git a/tests/http.test.ts b/tests/http.test.ts index c6780f7..f374345 100644 --- a/tests/http.test.ts +++ b/tests/http.test.ts @@ -597,3 +597,73 @@ test("axios can take authFetch through its fetch adapter", async () => { await assert.rejects(http.get("me"), wraps("UNAUTHENTICATED")); assert.equal(sent.length, 3); }); + +/** A response as a `fetch` that followed a redirect returns it. */ +function redirectedResponse(url: string, flagged: boolean) { + const response = new Response("secret", { status: 200 }); + Object.defineProperty(response, "url", { value: url }); + Object.defineProperty(response, "redirected", { value: flagged }); + return response; +} + +test("a redirect that fetch followed anyway rejects, as on older React Native", async () => { + const auth = client(); + await auth.signIn(input()); + const inits: (RequestInit | undefined)[] = []; + const responses = [ + redirectedResponse("https://elsewhere.example/me", false), + redirectedResponse("https://api.example.com/login", true), + redirectedResponse("https://api.example.com/me", false), + ]; + setGlobal("fetch", async (_request: Request, init?: RequestInit) => { + inits.push(init); + return responses.shift(); + }); + const request = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); + await assert.rejects(request("/me"), TypeError); + await assert.rejects(request("/me"), TypeError); + // The same URL, less the fragment, isn't a redirect. + assert.equal((await request("/me#profile")).status, 200); + // Expo's `fetch` reads the redirect mode only from `init`. + assert.deepEqual( + inits.map((init) => init?.redirect), + ["error", "error", "error"], + ); +}); + +test("the redirect check ignores how the platform spells the same URL", async () => { + const auth = client(); + await auth.signIn(input()); + const responses: unknown[] = [ + redirectedResponse( + "https://api.example.com/orders?filter%5Bstatus%5D=open", + false, + ), + redirectedResponse("https://api.example.com/caf%C3%A9", false), + // A test fake that isn't a `Response` and has no `url`. + { status: 200, redirected: undefined, url: undefined }, + ]; + const policies: string[] = []; + setGlobal("fetch", async (request: Request) => { + policies.push(request.referrerPolicy); + return responses.shift(); + }); + const request = createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + }); + assert.equal( + ( + await request( + new Request("https://api.example.com/orders?filter[status]=open", { + referrerPolicy: "no-referrer", + }), + ) + ).status, + 200, + ); + assert.equal((await request("/café")).status, 200); + assert.equal((await request("/me")).status, 200); + assert.equal(policies[0], "no-referrer"); +}); diff --git a/tests/legacy-abort.test.ts b/tests/legacy-abort.test.ts new file mode 100644 index 0000000..5937be3 --- /dev/null +++ b/tests/legacy-abort.test.ts @@ -0,0 +1,79 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import type { StandardSchemaV1 } from "@standard-schema/spec"; + +import { client, code, cleanups, input, useBrowserMocks } from "./helpers.ts"; + +/** + * React Native before 0.87 installs `abort-controller` 3 as the global: its + * signals have no `reason` or `throwIfAborted`, and `abort()` drops the + * reason it's given. The client must work the same with it. + */ +class LegacySignal extends EventTarget { + aborted = false; + onabort: ((event: Event) => void) | null = null; +} + +class LegacyController { + readonly signal = new LegacySignal(); + abort() { + if (this.signal.aborted) return; + this.signal.aborted = true; + this.signal.dispatchEvent(new Event("abort")); + } +} + +Object.assign(globalThis, { + AbortController: LegacyController, + AbortSignal: LegacySignal, +}); + +useBrowserMocks(); + +type User = { id: string; email: string }; + +/** A user schema whose check waits for `release`. */ +function slowSchema(release: Promise): StandardSchemaV1 { + return { + "~standard": { + version: 1, + vendor: "test", + async validate(value) { + await release; + return { value: value as User }; + }, + }, + }; +} + +const user = { id: "alice", email: "alice@example.com" }; + +test("signs in and refreshes with React Native's legacy AbortController", async () => { + const auth = client({ + user: slowSchema(Promise.resolve()), + refresh: async () => ({ + accessToken: "access-2", + refreshToken: "refresh-2", + expiresIn: 3600, + }), + }); + cleanups.push(auth.mount()); + await auth.signIn(input({ user, expiresIn: 3600 })); + assert.equal(auth.state.get().status, "authenticated"); + await auth.refresh(); + assert.equal((await auth.credentials.get())?.accessToken, "access-2"); +}); + +test("a superseded sign-in rejects with SESSION_CHANGED", async () => { + let release!: () => void; + const waiting = new Promise((resolve) => (release = resolve)); + const auth = client({ user: slowSchema(waiting) }); + cleanups.push(auth.mount()); + const first = auth.signIn(input({ user })); + const second = auth.signIn(input({ user, accessToken: "access-2" })); + release(); + await assert.rejects(first, code("SESSION_CHANGED")); + await second; + assert.equal((await auth.credentials.get())?.accessToken, "access-2"); +});