diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ded4828..080b9f0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,4 +1,4 @@ -name: Release alpha +name: Release env: HUSKY: 0 @@ -7,7 +7,7 @@ on: workflow_dispatch: inputs: version: - description: Alpha version already committed in package.json (without v) + description: Alpha or release candidate version already committed in package.json (without v) required: true type: string @@ -84,7 +84,7 @@ jobs: - name: Check npm supports trusted publishing run: | node --input-type=module -e 'import { execFileSync } from "node:child_process"; const [major, minor, patch] = execFileSync("npm", ["--version"], { encoding: "utf8" }).trim().split(".").map(Number); if (!(major > 11 || (major === 11 && (minor > 5 || (minor === 5 && patch >= 1))))) throw new Error("npm >=11.5.1 is required");' - - name: Publish alpha to npm + - name: Publish to npm env: RELEASE_VERSION: ${{ inputs.version }} run: npm publish "$RUNNER_TEMP/release/monarcode-session-kit-$RELEASE_VERSION.tgz" --tag latest --access public --ignore-scripts diff --git a/AGENTS.md b/AGENTS.md index 14d0ad0..ddccf75 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,7 +82,9 @@ Consumers import from the root and from subpaths: (`INVALID_OPTIONS`). Wrap a failure at the operation's boundary with `toAuthError(code, message, cause)`, where the operation knows its code; a `cause` is whatever failed, and doesn't need to be an `AuthError`. - `fetch`'s and `Request`'s own failures pass through `authFetch`. + `fetch`'s and `Request`'s own failures pass through `authFetch`, and the + app's own sign-in errors pass through a `createMirrorAuth` client's + `signIn`. - Source imports use explicit `.js` extensions. Because `exactOptionalPropertyTypes` is on, write optional props as `foo?: T | undefined`. `readonly` is a separate, per-type choice: outputs @@ -168,9 +170,12 @@ developers, not for us. Every comment ships: keep it short, plain and true. `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 README example marked `` - is an excerpt of that page's examples, and the check fails when the two - differ: edit the page, then copy. +- 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 + `` is an excerpt of that + page's examples instead, and the check fails when the two differ: edit the + page, then copy. - The reference pages in `site/content/docs/(latest)/reference/` (one per entry point, and the error codes) are generated from the JSDoc by `pnpm run docs:reference`, except the entry points index and diff --git a/CHANGELOG.md b/CHANGELOG.md index dd94901..10e20d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,272 @@ # Changelog -## Unreleased +## 0.1.0-rc.0 + +The first release candidate for `0.1.0`. The public API is now frozen, and +later `0.1` releases only add to it. + +### Added + +- `authFetch` takes a `URL` or a `Request` as well as a path, as `fetch` + does. An HTTP client with a `fetch` option can now send its requests + through it, and they keep its safeguards: the token stays on one origin, a + 401 refreshes once, and only a GET or HEAD is sent again. The + [Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients) + page shows ky, axios with its `fetch` adapter, and openapi-fetch. It + replaces the ky recipe built on hooks, and keeps the axios interceptors for + an instance on axios's default adapter. +- `UseMirrorAuthOptions`, the type of `useMirrorAuth`'s options. +- Hooks without a hooks file. `@monarcode/session-kit/react` exports + `AuthProvider`, `useAuth` and `useAuthClient`, typed by the client you + register once in `Register`, from `@monarcode/session-kit`. Until you + register one, `AuthProvider` takes any client, and the user is `unknown`. + `ProvidedAuth` names the client they use. + `createAuthHooks` stays, for an app with several clients. + + ```ts + declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } + } + ``` + +- `@monarcode/session-kit/tanstack-router` exports `useAuth` and + `useAuthClient`, which read the client from Router context and are typed + by the Router you register. They need no `AuthProvider` and no + registration of their own. +- One request's session on the server, without passing its cookie jar. + `startAuth(serverAuth)` in `@monarcode/session-kit/tanstack-start/server` + finds the request on each call, so it's made once, at module level, and + one `createAuthFetch` over it serves every request. + `routerAuth(serverAuth)` in `@monarcode/session-kit/react-router/server` + takes the route's `context`. The guides use these. The jar-first methods + stay, for servers without an adapter. + + ```ts + // Before + await serverAuth.signIn(startJar(), tokens); + // After + export const session = startAuth(serverAuth); + await session.signIn(tokens); + ``` + +- `serverAuth.forRequest(jar)` has every method now: `signIn`, + `updateUser`, `refreshIfDue` and `clientCredentials` join the rest. +- `SessionOf` and `UserOf` in `@monarcode/session-kit` give the + session and user types of any client: one from `createAuth`, + `createMirrorAuth` or `createServerAuth`, or a request's session. + + ```ts + type AppSession = SessionOf; // { sessionId, user } + ``` + +- Middleware and server guards for the server-rendered setups, in place of + the code the guides had you copy. Each refreshes before rendering, while a + cookie can still be set, and ignores a failed refresh. The TanStack Start + and React Router middleware also mark each response that doesn't set its + own `Cache-Control` as `private, no-store` (`cacheControl` changes or + skips it). Next.js marks pages that read cookies `no-store` itself. + - TanStack Start: `refreshSession(serverAuth, options?)` in + `@monarcode/session-kit/tanstack-start/server`, a handler for Start's + `createMiddleware({ type: "request" }).server()`. Start strips what's in + `.server()` from the browser bundle, `serverAuth` included. + - React Router: `sessionMiddleware(serverAuth, options?)` for the root + route, `requireSession(serverAuth, { loginPath, basename })` for guarded + routes, whose `session(context)` gives their loaders a session that's + never `null`, and `redirectIfSignedIn(serverAuth, options?)` as the + sign-in page's loader, in `@monarcode/session-kit/react-router/server`. + - Next.js: `nextSession(serverAuth, { cookies, redirect })` in + `@monarcode/session-kit/next`, with `get()`, `require(path)` and + `redirectIfSignedIn(redirectTo)` for Server Components, `readOnly()` and + `writable()` for the request's session, and `refresh(request, response)` + for `proxy.ts`. You pass Next's own `cookies` and `redirect`. + + ```ts + // app/root.tsx + export const middleware = sessionMiddleware(serverAuth); + // app/routes/protected.tsx + export const middleware = [signedIn]; // signedIn = requireSession(serverAuth) + ``` + +- `loginHref(loginPath, returnTo)` in `@monarcode/session-kit` builds the + sign-in page's URL with `?redirectTo=`, for a guard of your own. +- `SessionMiddlewareOptions` in `@monarcode/session-kit/server`: `within` + and `cacheControl`, for `refreshSession` and `sessionMiddleware`. +- A session route, in place of the server functions, Server Functions and + resource routes the guides had you write for the browser's client. It + reads the session, signs out, and gets or renews the access token when + `createServerAuth` has `clientCredentials`. It answers your own site's + pages only (by `Sec-Fetch-Site`, or a `POST`'s `Origin` on plain http), + with `Cache-Control: no-store`. Signing in stays your own code. + - `createMirrorAuth({ endpoint })` calls it. `revalidate`, `signOut` and + `credentials` are optional now, and win over `endpoint` when given. The + options' type needs `endpoint`, or `revalidate` and `signOut`. A failure + the server reports rejects with its `AuthErrorCode`. + - `sessionHandler(serverAuth)` in `@monarcode/session-kit/server` answers + it, for a request and its cookie jar (`SessionHandler`). + - `sessionRoute(serverAuth)` wraps it for each framework: a server route's + `handlers` in `@monarcode/session-kit/tanstack-start/server` + (`StartSessionRoute`), a resource route's `loader` and `action` in + `@monarcode/session-kit/react-router/server` (`RouterSessionRoute`), and + a Route Handler's `GET` and `POST` in `@monarcode/session-kit/next`, with + Next's `cookies` in `NextSessionRouteOptions` (`NextSessionRoute`). + + ```ts + // app/api/session/route.ts + export const { GET, POST } = sessionRoute(serverAuth, { cookies }); + // lib/auth/client.ts + createMirrorAuth({ name: "app", session, endpoint: "/api/session", signIn }); + ``` + +- `isSignedIn(state)` in `@monarcode/session-kit`: `true` while + `authenticated` or `refreshing`, and `false` while `locked`. It narrows + `user`, and works as a selector: `useAuth(isSignedIn)`. +- `requireSessionLoader(auth, options?)` and + `redirectIfSignedInLoader(auth, options?)` in + `@monarcode/session-kit/react-router` make the guards' loaders, for + `loader` or `clientLoader`. The second reads `?redirectTo=` from the URL. + Their options are `RequireSessionLoaderOptions` and + `RedirectIfSignedInLoaderOptions`, and they return `RequireSessionLoader` + and `RedirectIfSignedInLoader`. `requireSession` and `redirectIfSignedIn` + stay, for a loader that does more. + + ```ts + export const clientLoader = requireSessionLoader(auth); + ``` + +- `loginPath` defaults to `"/login"` in `requireSession` for TanStack Router + and React Router, and in React Router's `SessionOutlet`. +- `deepLinkHandler(auth, options?)` in `@monarcode/session-kit/expo` makes + `redirectSystemPath` for `app/+native-intent.tsx` (`DeepLinkHandler`). + `rememberDeepLink` stays, for a `redirectSystemPath` that does more. +- `AuthRouter` in `@monarcode/session-kit/tanstack-router`, the Router type + `connectAuth` takes, for typing a function that takes your Router. +- `NextSession` has `signIn`, `signOut` and, with a user schema, + `updateUser`, so a Server Function writes `await session.signIn(tokens)` + rather than `await (await session.writable()).signIn(tokens)`. The Next.js + guide and example use them. ### Changed +- **Breaking:** the session route answers 500, not 400, for an + `INVALID_OPTIONS` that comes from the server's setup, such as a missing + secret, `clientCredentials` not turned on, or React Router's middleware + not added. A request it can't read still answers 400. +- A saved session past `maxAge`, or saved by another version, signs out + without an error, and `unlock()` resolves `null` for one. It set + `INVALID_SESSION` in `state.error`, which an app showing errors showed + after 30 idle days or an upgrade. A malformed saved session still does. +- The Server sessions page says how to read the secret on Cloudflare + Workers. + +- **Breaking:** `createAuthFetch` takes the base URL as an option, as + `sessionBearer` does. A missing `baseUrl` throws `INVALID_OPTIONS`. + + ```ts + // Before + createAuthFetch(auth, "https://api.example.com/", { optional: true }); + // After + createAuthFetch(auth, { + baseUrl: "https://api.example.com/", + optional: true, + }); + ``` + +- **Breaking:** `AuthFetch`'s first parameter is `string | URL | Request`, + not `string`. Only code that implements the type is affected, such as a + test fake that declares `(path: string) => …`: widen its parameter. +- `authFetch` rejects with `INVALID_OPTIONS` when called with no path. It + used to request `undefined` under the base URL. +- `authFetch` asks for the credentials before it builds the request. Signed + out or locked, a call with an `init` that `Request` refuses now rejects + with `UNAUTHENTICATED` or `LOCKED`, not with `Request`'s `TypeError`. +- **Breaking:** the `signIn` of a `createMirrorAuth` client rejects with what + your `signIn` option threw, unchanged, as a sign-in in a single-page app + does. It used to wrap it in a `USER_VALIDATION_FAILED` `AuthError`, so a + sign-in form had to read the message from `cause`. A result that isn't a + session still rejects with `INVALID_SESSION`. + + ```ts + // Before + const reason = error instanceof Error ? error.cause : undefined; + setError(reason instanceof Error ? reason.message : "Could not sign in"); + // After + setError(error instanceof Error ? error.message : "Could not sign in"); + ``` + +- **Breaking:** `useMirrorAuth` takes one options object, and throws + `INVALID_OPTIONS` without `create` or `onChange`. + + ```ts + // Before + useMirrorAuth(createAppAuth, session, () => router.refresh()); + // After + useMirrorAuth({ + create: createAppAuth, + session, + onChange: () => router.refresh(), + }); + ``` + +- **Breaking:** TanStack Start's `connectSession(router)` replaces + `sessionHydration(auth)` and the `connectAuth(router)` beside it. It keeps + the router's own `dehydrate` and `hydrate`, which `...sessionHydration(auth)` + replaced, or was replaced by, depending on the order of the spread. + `sessionHydration`, `SessionHydration` and `DehydratedSession` are removed. + + ```ts + // Before + const router = createRouter({ + routeTree, + context: { auth }, + ...sessionHydration(auth), + }); + connectAuth(router); + // After + const router = createRouter({ routeTree, context: { auth } }); + connectSession(router); + ``` + +- **Breaking:** `Register` and `RegisteredAuth` moved from + `@monarcode/session-kit/effect` to `@monarcode/session-kit`, so one + registration types the hooks and the Effect service. Change the module you + augment. The other `Registered…` types stay in `./effect`. Register a + client from `createAuth` or `createMirrorAuth`: anything else now types the + hooks and the Effect service as `never`, where the Effect service used to + fall back to an `unknown` user. + + ```ts + // Before + declare module "@monarcode/session-kit/effect" { + interface Register { + auth: typeof auth; + } + } + // After + declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } + } + ``` + +- **Breaking:** in `@monarcode/session-kit/tanstack-router`, `useRouterAuth` + is now `useAuthClient`, and `RegisteredAuth` is now `RouterAuth`, so it + isn't confused with the main entry point's. When `auth` is optional in + Router context, `useAuthClient` returns the client without `undefined`, as + it throws when there's none. A hooks file made with + `createAuthHooks({ useClient: useRouterAuth })` can go: import `useAuth` + and `useAuthClient` from `@monarcode/session-kit/tanstack-router` instead. +- **Breaking:** `RequestAuth` takes the user `signIn` accepts as a second + type parameter, as `ServerAuth` does: `RequestAuth`, or + `RequestAuth` when the user comes from the access token. Most + apps write `SessionOf` or `UserOf` instead. +- Effect's `Auth.layer` binds a session from `startAuth` to the request + that's current when it's called, and throws `INVALID_OPTIONS` outside + one. `Auth.signIn` and `Auth.updateUser` still die on a request's session, + and now point at its own `signIn` and `updateUser`. + - The guides moved to the documentation site, [session-kit.pages.dev](https://session-kit.pages.dev), with an API reference for every entry point and every error code. The README is now a @@ -22,10 +285,9 @@ `defaultError` to effetch-query's `endpoints`. `sessionBearer`'s example calls the client's methods too. - `AuthErrorCode`'s docs say which codes the browser client of a - server-rendered app rejects with: `USER_VALIDATION_FAILED` when signing in - on the server fails, `PERSISTENCE_FAILED` when signing out there fails, and - `REFRESH_FAILED` when reading the session or the access token from the - server fails. + server-rendered app rejects with: `PERSISTENCE_FAILED` when signing out on + the server fails, and `REFRESH_FAILED` when reading the session or the + access token from the server fails. - The setup guides are corrected against the code and the example apps. The TanStack Start guard renders `SessionOutlet`, the Next.js guard sends users back to the page they asked for after sign-in, and the React Router layout @@ -37,11 +299,100 @@ - The compatibility page lists `effect` as a peer of `./effetch` as well as `./effect`, and the entry points page orders the entry points as the reference does. +- The router guides' sign-in pages no longer navigate after a sign-in. The + sign-in page's guard runs again and sends the user on, so a form only signs + in. The server-rendering guides call the API with `createAuthFetch` over the + request's session, and the Expo guide adds the profile screen its deep-link + steps open. +- The hovers on a request's session say what `signIn` takes, that it never + calls your backend and trusts its input, and which errors `signIn` and + `updateUser` reject with. `getSession`, `signOut` and `credentials.get` say + where to use them. +- The `tanstack-start-spa-effetch` example is laid out as the Effect guide + is, in `backend.ts`, `refresh.ts`, `auth.ts`, `layer.ts`, `api.ts` and + `runtime.ts`. Its `FetchLive` layer is gone: the API client and the + refresh client each turn off Effect's tracing headers themselves, and the + runtime provides plain `FetchHttpClient.layer`. The guide's refresh client + now turns them off too. It sent them, which fails the preflight of an API + that doesn't allow them. +- The React Router guide's Guards in loaders section says when to use + `requireSessionLoader` (the whole loader, usually a layout's) and + `requireSession` (inside a loader that loads data too). A page's loader that + calls your API checks the session itself, since React Router runs nested + routes' loaders at the same time. +- A Hybrid setup page, under Server rendering: the browser signs in with + your backend and calls your API, and the server keeps the session. It shows + a server function that checks the tokens with your backend before + `session.signIn`, and one that passes them on unchecked, with when that's + safe. +- `createMirrorAuth`'s `endpoint`, `revalidate` and `signOut` options show + their docs in editor hovers, which showed none. `revalidate`'s say when the + client calls it: when the tab becomes visible after 10 seconds or more, and + when another tab signs in or out. - The reference lists the members of `AuthStorage`, `Tokens` and `CookieJar`, the types an app builds itself. The server-rendering guides' sign-in shows the backend's own message for a failed sign-in, as the example apps do, and the secret-rotation example works once the old secret is removed. +- The hovers and the guides are checked line by line against the code. The + hovers name errors they left out: `PERSISTENCE_FAILED` from `signIn`, + `getSession` and `unlock`, `REFRESH_FAILED` and `SESSION_CHANGED` from + `credentials.renew`, `createAuthFetch` and `sessionBearer`, a request's + `getSession` and `refreshIfDue` on the server, the `INVALID_OPTIONS` that + guards, outlets and `sessionRoute` throw, and the session route's status + codes. `AuthErrorCode`'s docs cover a saved session older than `maxAge`, a + `locking.seal` that fails, and a refresh that times out. +- Corrected in the docs: `signOut()` waits for `revoke`. + `signOutOnRepeated401: false` only stops a second 401 from signing users + out, and without a refresh token the first one still does. A read-only + request's `getSession` resolves, and only `credentials.get` rejects once + the token has expired. React Router passes loaders `url` from 7.15, not + from 8. `AFTER_FIRST_UNLOCK` is for a refresh while the device is locked. + Remove an old `secret` once `maxAge` has passed since the change. +- The guides gain what they lacked: a Sign out section for TanStack Start, + `cacheControl` and the two sets of guards for React Router with server + rendering, the session route's checks on the Security page, storage that + can't be read on the Errors page, and what `secureStorage`, `SessionGate` + and `deepLinkHandler` do on the Expo page. The Expo guide's locking example + throws when a change to the device's biometrics made the key unreadable, + as its comment says, where it made a new key. The Effect guide's sign-in + button awaits `auth.signIn`, where a failed sign-in went unhandled. + +### Fixed + +- With a user read from the access token, `ServerAuth`, `RequestAuth` and + `NextSession` keep their names in editors and declaration files. Editors + showed internal names, and exporting such a value from a module that emits + declarations failed with TS4023. A session with a user schema is no longer + assignable to a token user's type, such as `RequestAuth`, + since their `signIn` takes different input. +- The guides and examples call `login` on its own line before `signIn`, + rather than nesting the `await`. +- `signOut()` before the saved session is restored, such as with + asynchronous storage or before the first `mount()`, revokes the saved + tokens. It cleared them without revoking, so the refresh token stayed + valid at the backend. A locked session still isn't revoked. +- `safeReturnTo` matches a `loginPath` that has a query, such as + `"/login?tab=1"`, by its path. It returned the sign-in page as safe. +- `redirectIfSignedIn` (both routers) rejects a `loginPath` that doesn't start + with `/` for every visitor, and `redirectIfSignedInLoader` when the loader + is made. It failed only once someone signed in. +- `connectAuth` throws `INVALID_OPTIONS` when the Router's context has no + client as `auth`, and `nextSession` when called without options, where + each threw a `TypeError`. +- `authFetch` rejects a `Request` from another realm or a polyfill with + `INVALID_OPTIONS`. It was sent as the path `"[object Request]"` under + `baseUrl`. +- The docs say that React Router's loader guards can't keep a `#fragment`, + and that a Next.js Route Handler should answer 401 rather than call + `require` under a `basePath`. +- The example apps match their guides. React Router's data mode imports + `RouterProvider` from `react-router/dom`, and the framework apps generate + route types. The effetch app retries before `sessionBearer` and resets + per account. The TanStack apps read the user from the guarded route's + context and keep `disconnectAuth`. A failed sign-in in React Router with + server rendering returns status 400, in the example and the guide, so the + loaders don't run again. Stale comments are corrected. ## 0.1.0-alpha.8 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 531ec5c..413cf4f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -25,8 +25,10 @@ example: - **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. -- **The README.** A block marked with a `from:` comment is an excerpt of a - page's examples, and must match it. +- **The README.** Its quick start is a small app of its own: each block + marked `` is a file, and they compile together. A block + marked with a `from:` comment is an excerpt of a page's examples instead, + and must match it. `pnpm test` runs the runtime tests twice: with synchronous storage, and with storage that settles every operation late, removals last, to catch ordering diff --git a/README.md b/README.md index 5d8d678..f281f1b 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ -![session-kit](https://raw.githubusercontent.com/monarcode/session-kit/main/assets/sk-banner.png) +![Session kit: schema-driven, type-safe sessions for React apps](https://raw.githubusercontent.com/monarcode/session-kit/main/assets/sk-banner.png) [![npm](https://img.shields.io/npm/v/@monarcode/session-kit)](https://www.npmjs.com/package/@monarcode/session-kit) [![CI](https://github.com/monarcode/session-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/monarcode/session-kit/actions/workflows/ci.yml) -[![bundle size](https://deno.bundlejs.com/badge?q=@monarcode/session-kit)](https://bundlejs.com/?q=@monarcode/session-kit) -[![tree-shakeable](https://img.shields.io/badge/tree--shakeable-yes-brightgreen)](https://bundlejs.com/?q=@monarcode/session-kit&treeshake=%5B%7BcreateAuth%2CwebStorage%7D%5D) +[![bundle size](https://deno.bundlejs.com/badge?q=@monarcode/session-kit&treeshake=%5B%7BcreateAuth%2CwebStorage%7D%5D)](https://bundlejs.com/?q=@monarcode/session-kit&treeshake=%5B%7BcreateAuth%2CwebStorage%7D%5D) +[![types](https://img.shields.io/npm/types/@monarcode/session-kit)](https://www.npmjs.com/package/@monarcode/session-kit) [![provenance](https://img.shields.io/badge/provenance-verified-brightgreen?logo=npm)](https://www.npmjs.com/package/@monarcode/session-kit#provenance) [![license](https://img.shields.io/npm/l/@monarcode/session-kit)](./LICENSE) @@ -15,142 +15,171 @@ [![Expo](https://img.shields.io/badge/Expo-20232a?logo=expo&logoColor=white)](https://session-kit.pages.dev/docs/setups/expo) [![Effect](https://img.shields.io/badge/Effect-20232a?logo=effect&logoColor=white)](https://session-kit.pages.dev/docs/effect) -**Your backend signs users in. Session kit handles everything after.** +**Every sign-in ends in a session. Make yours type-safe and predictable.** Session kit is the session layer for React apps that have their own backend. -Hand it the tokens your sign-in endpoint returns, and it saves the session, +Give it the tokens your sign-in endpoint returns, and it saves the session, restores it on reload, refreshes tokens before they expire, keeps every tab in -step, and guards your routes. +sync, and guards your routes. It never signs users in: your backend does, and +Session kit takes over from its response. It works with TanStack Router, React Router, and Expo Router, renders on the server with TanStack Start, Next.js, and React Router, and comes with an [Effect](https://effect.website) service and an [effetch](https://github.com/monarcode/effetch) plugin. -> **Alpha.** Early development: the API may change between releases, and it -> isn't ready for production. See the [release notes](./CHANGELOG.md). +> **Release candidate.** The API is frozen for 0.1, and later 0.1 releases +> only add to it. See the [release notes](./CHANGELOG.md). **Documentation: [session-kit.pages.dev](https://session-kit.pages.dev)** ## Installation ```sh -pnpm add @monarcode/session-kit +npm install @monarcode/session-kit zod ``` -Alpha releases are published to the `latest` distribution tag and may change -the public API, so pin an exact version and read the -[release notes](./CHANGELOG.md) before upgrading. - Any [Standard Schema](https://standardschema.dev) library describes users. -The examples use Zod: - -```sh -pnpm add zod -``` +The examples use Zod. Peer dependencies such as React and your router are +optional: install the ones your setup uses. +[Compatibility](https://session-kit.pages.dev/docs/reference/compatibility) +lists the supported versions. -Every peer dependency is optional: install React and the router your setup -uses. [Compatibility](https://session-kit.pages.dev/docs/reference/compatibility) lists the -supported versions. +Release candidates are published to the `latest` tag, so pin an exact version +and read the [release notes](./CHANGELOG.md) before upgrading. ## Quick start -Session kit never calls your backend. Write the requests you'd write anyway: -one that signs in, and one that exchanges a refresh token for new tokens. +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. + +**1. Create the client.** It checks every user against your schema, saves the +session, and calls your `refresh` before the access token expires: - + ```ts -/** Checks the password, and resolves the tokens and the user. */ -export async function login(username: string, password: string) { - const response = await post("/auth/login", { username, password }); - if (!response.ok) throw new Error(`Sign-in failed (${response.status})`); - // DummyJSON returns the user's fields beside the tokens. - const body: unknown = await response.json(); - return { ...tokensSchema.parse(body), user: userSchema.parse(body) }; -} +import { createAuth, webStorage } from "@monarcode/session-kit"; +import { z } from "zod"; -/** - * Exchanges a refresh token for new tokens. Resolves `null` when the backend - * rejects the token, and throws for any other failure. - */ -export async function refresh(refreshToken: string, signal: AbortSignal) { - const response = await post("/auth/refresh", { refreshToken }, { signal }); - // DummyJSON answers 403 for an invalid token and 401 for a missing one. - 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 auth = createAuth({ + // Keeps this app's saved session apart from others on the same origin. + name: "my-app", + // Every user is checked against this schema, and typed by it. + user: z.object({ id: z.string(), name: z.string() }), + // Saves the session in localStorage, so it survives reloads. + storage: webStorage(), + refresh: async ({ refreshToken, signal }) => { + const response = await fetch("/api/auth/refresh", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ refreshToken }), + signal, + }); + if (response.status === 401) return null; // rejected: sign out + if (!response.ok) throw new Error(`Refresh failed (${response.status})`); + return response.json(); + }, +}); + +// Types the React hooks with this client's user. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } } ``` -Then create the client. It saves the session, restores it on reload, and -refreshes the tokens with your `refresh`: +**2. Sign in.** Pass `signIn` what your backend's sign-in returned, the tokens +and the user: - + ```ts -export const auth = createAuth({ - // Keeps this app's saved session apart from any other on the same origin. - name: "my-app", - // Every user is checked against this schema, and typed by it. - user: userSchema, - // Where the session is saved: `localStorage`. - storage: webStorage(), - // How expired access is replaced. - refresh: ({ refreshToken, signal }) => refresh(refreshToken, signal), -}); +import { auth } from "./auth.js"; + +export async function signIn(email: string, password: string) { + const response = await fetch("/api/auth/login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email, password }), + }); + if (!response.ok) throw new Error(`Sign-in failed (${response.status})`); + // { accessToken, refreshToken, expiresIn, user } + const tokens = await response.json(); + await auth.signIn(tokens); +} ``` -And render by the session's status: +**3. Render by the session's status.** `useAuth` re-renders when it changes, +in this tab or another: - + ```tsx -function Screen() { - const { status, user } = useAuth(); +import { + AuthProvider, + useAuth, + useAuthClient, +} from "@monarcode/session-kit/react"; + +import { auth } from "./auth.js"; +import { SignInForm } from "./sign-in-form.js"; // your form, calling signIn + +export function App() { + return ( + + + + ); +} + +function Home() { + const session = useAuth(); const client = useAuthClient(); - switch (status) { - case "initializing": - return

Restoring your session…

; - case "unauthenticated": - return ; - case "unavailable": - // Access couldn't be restored or refreshed: offer another try. - return ( - - ); - default: - // Signed in: "authenticated", or "refreshing" with the user on screen. - return ( -
-

Welcome, {user.firstName}

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

Restoring your session…

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

Welcome, {session.user.name}

+ +
+ ); } ``` -[Getting started](https://session-kit.pages.dev/docs/getting-started) builds this into a working app -one step at a time, against a real test backend. +To call your API, `createAuthFetch` from `@monarcode/session-kit/http` adds +the access token to each request and refreshes it after a 401. +[Getting started](https://session-kit.pages.dev/docs/getting-started) builds +this app step by step against a real test backend, and the guides below add +your router's guards or server rendering. ## Pick your setup -| Setup | Guide | -| ----------------------------------------------- | ----------------------------------------------------------------------------------- | -| React without a router | [Getting started](https://session-kit.pages.dev/docs/getting-started) | -| TanStack Router, and TanStack Start in SPA mode | [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 SSR | [React Router with SSR](https://session-kit.pages.dev/docs/setups/react-router-ssr) | -| Next.js 16, App Router | [Next.js](https://session-kit.pages.dev/docs/setups/next) | -| Expo Router on iOS and Android, SDK 53+ | [Expo Router](https://session-kit.pages.dev/docs/setups/expo) | -| Effect and effetch, with any of the above | [Effect and effetch](https://session-kit.pages.dev/docs/effect) | +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). diff --git a/RELEASING.md b/RELEASING.md index 1e339e4..2af3f02 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,7 +1,8 @@ # Releasing session-kit -The `Release alpha` workflow is manually triggered. It releases an alpha version -already committed to `main`; it does not change versions or commit files. +The `Release` workflow is manually triggered. It releases an alpha or release +candidate version already committed to `main`; it does not change versions or +commit files. It checks and packs with pnpm, publishes the verified tarball to npm using `latest`, then creates a Git tag and GitHub prerelease at the workflow's commit. @@ -25,19 +26,21 @@ See [npm's trusted publishing documentation](https://docs.npmjs.com/trusted-publ The workflow runs on GitHub-hosted runners with Node.js 24 and npm >=11.5.1. For this public repository/package, trusted publishing also generates provenance. -## Release an alpha +## Release an alpha or release candidate -1. Make the intended package changes. Set `package.json` to a new alpha version, - such as `0.1.0-alpha.1`, and add its `## 0.1.0-alpha.1` section to `CHANGELOG.md`. +1. Make the intended package changes. Set `package.json` to the new version, + such as `0.1.0-rc.0`, and rename `CHANGELOG.md`'s `## Unreleased` heading + to `## 0.1.0-rc.0`. 2. Run `pnpm run check`, then commit and push those changes to `main`. -3. Open GitHub Actions → **Release alpha** → **Run workflow**. Choose `main` +3. Open GitHub Actions → **Release** → **Run workflow**. Choose `main` and enter the exact package version, without a `v` prefix. 4. Verify the run succeeds, npm exposes the version through `latest`, and the matching GitHub prerelease exists. The workflow rejects a different branch, invalid or mismatched versions, missing -release notes, an existing npm version, and an existing Git tag. It does not -support stable releases yet. The published `0.1.0-alpha.0` cannot be republished. +release notes, an existing npm version, and an existing Git tag. It takes +`-alpha.N` and `-rc.N` versions only, not stable releases yet. The published +`0.1.0-alpha.0` cannot be republished. The build job has read-only repository permissions. Only the publishing job receives OIDC and release-write permissions. Its tarball and release notes come diff --git a/assets/sk-banner.png b/assets/sk-banner.png index 317c39d..468a1d7 100644 Binary files a/assets/sk-banner.png and b/assets/sk-banner.png differ diff --git a/examples/README.md b/examples/README.md index 91083ed..9c656b1 100644 --- a/examples/README.md +++ b/examples/README.md @@ -53,19 +53,21 @@ run ios` and `run android` build it natively. In CI it is only bundled, with Tokens last one minute, so the early refresh runs after about 30 seconds. Requests omit `credentials: "include"`, which DummyJSON's own snippets use, because session-kit keeps tokens out of cookies. -- **Guards**: `requireSession` and `SessionOutlet` for TanStack Router and - Start, `SessionOutlet` alone in React Router's declarative mode, and loader - guards with `useAuthRevalidation` in data and framework mode. +- **Guards**: `requireSession`, `redirectIfSignedIn` and `SessionOutlet` for + TanStack Router and Start. `SessionOutlet` alone in React Router's + declarative mode. `requireSessionLoader`, `redirectIfSignedInLoader`, + `SessionOutlet` and `useAuthRevalidation` in data and framework mode. - **TanStack Start** sets `defaultSsr: false` in `src/start.ts`. Start's own server still renders requests in SPA mode, and the guards need the browser's saved session. - **TanStack Start with Effect** is the SPA app written with Effect, [effetch](https://github.com/monarcode/effetch) and - [effetch-query](https://github.com/monarcode/effetch-query). `src/auth.ts` - describes the user with an Effect Schema and refreshes through effetch. - `src/api-client.ts` is the API client, a service whose `sessionBearer` - plugin sends the access token, and `src/runtime.ts` composes the app's - layers into one runtime. `src/endpoints.ts` declares the sign-in mutation + [effetch-query](https://github.com/monarcode/effetch-query), laid out as + the guide is. `src/backend.ts` describes DummyJSON with Effect Schemas, + `src/refresh.ts` refreshes through effetch, and `src/auth.ts` reads the + user from the access token. `src/api.ts` is the API client, a service whose + `sessionBearer` plugin sends the access token, and `src/runtime.ts` + composes the app's layers into one runtime. `src/endpoints.ts` declares the sign-in mutation and the profile query, which `src/ui.tsx` uses with `useMutation` and `useQuery`, and the root route gives each session its own query cache. The hooks and the guards are the SPA app's. See @@ -74,31 +76,34 @@ run ios` and `run android` build it natively. In CI it is only bundled, with `httpOnly` cookie with `createServerAuth` (`src/auth/server.ts`), signs in with DummyJSON from a server function, and refreshes in request middleware (`src/start.ts`). `createMirrorAuth` gives the routes and components a - client, filled by `loadSession` on the server and `sessionHydration` in the - browser. `auth/me` is called both from a server function and, with - `clientCredentials`, from the browser. Set `SESSION_SECRET` (32 or more - random characters) to run `vite preview`; `vite dev` uses a development - secret. The cookie is `Secure` outside `vite dev`, which Safari refuses - over `http://localhost`: try `vite preview` in another browser. See + client, filled by `loadSession` on the server and `connectSession` in the + browser. The browser signs out and gets the access token through the + session route (`src/routes/api/session.ts`). `auth/me` is called both from + a server function and, with `clientCredentials`, from the browser. Set + `SESSION_SECRET` (32 or more random characters) to run `vite preview`; + `vite dev` uses a development secret. The cookie is `Secure` outside + `vite dev`, which Safari refuses over `http://localhost`: try + `vite preview` in another browser. See [the guide](https://session-kit.pages.dev/docs/setups/tanstack-start). - **Next.js** keeps the session the same way: Proxy refreshes it (`proxy.ts`), Server Components read it through `lib/auth/session.ts`, and - Server Functions in `app/actions.ts` sign in and out. `useMirrorAuth` in + a Server Function in `app/actions.ts` signs in. `useMirrorAuth` in `app/providers.tsx` gives Client Components the client and renders the page again when the session changes in the browser, so the pages' - redirects run. The browser gets the access token from a Route Handler. + redirects run. The browser reads the session, signs out and gets the + access token through the session route (`app/api/session/route.ts`). `SESSION_SECRET` and Safari work as for TanStack Start, with `next start` and `next dev`. See [the guide](https://session-kit.pages.dev/docs/setups/next). - **React Router with server rendering** keeps the session the same way. - Root middleware (`app/auth/middleware.server.ts`) gives each request a - cookie jar and refreshes, the root loader reads the session, and the sign-in - route's action signs in with a plain form that works before scripts load. + The root route's `sessionMiddleware` gives each request a cookie jar and + refreshes, the root loader reads the session, and the sign-in route's + action signs in with a plain form that works before scripts load. `useMirrorAuth` in `app/root.tsx` gives the components the client and runs the loaders again when the session changes in the browser, so the - protected route's middleware redirects. The browser signs out, revalidates - and gets the access token through the resource routes in - `app/routes/auth.*.ts`. `SESSION_SECRET` and Safari work as for TanStack - Start, with `pnpm start` (after `pnpm build`) and `react-router dev`. See + protected route's `requireSession` guard redirects. The browser reads the + session, signs out and gets the access token through the session route in + `app/routes/auth.session.ts`. `SESSION_SECRET` and Safari work as for + TanStack Start, with `pnpm start` (after `pnpm build`) and `react-router dev`. See [the guide](https://session-kit.pages.dev/docs/setups/react-router-ssr). - **Expo Router** saves the session with `secureStorage()`. `SessionGate` in `app/_layout.tsx` holds the splash screen, shows `src/unavailable.tsx` @@ -108,7 +113,8 @@ run ios` and `run android` build it natively. In CI it is only bundled, with `expo-secure-store` config plugin keeps the session out of Android backups. Each app is self-contained, so it can be copied out on its own. That is why -the client-side web apps have the same `ui.tsx` rather than sharing one. The +the client-side web apps have the same `ui.tsx`, apart from where the hooks +come from, rather than sharing one. The server-rendered apps have their own, since they sign in on the server, and so does the Effect app, whose handlers run Effects. The apps differ in where the user comes from on purpose, so both user sources appear: the login response, diff --git a/examples/expo-router/app/(app)/index.tsx b/examples/expo-router/app/(app)/index.tsx index 8a51498..a3caeaa 100644 --- a/examples/expo-router/app/(app)/index.tsx +++ b/examples/expo-router/app/(app)/index.tsx @@ -1,9 +1,8 @@ import { Button, Text, View } from "react-native"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; import { Link } from "expo-router"; -import { useAuth, useAuthClient } from "../../src/auth"; - export default function Home() { const firstName = useAuth((state) => state.user?.firstName); const auth = useAuthClient(); diff --git a/examples/expo-router/app/+native-intent.tsx b/examples/expo-router/app/+native-intent.tsx index fc97214..6681e7a 100644 --- a/examples/expo-router/app/+native-intent.tsx +++ b/examples/expo-router/app/+native-intent.tsx @@ -1,18 +1,10 @@ -import { rememberDeepLink } from "@monarcode/session-kit/expo"; +import { deepLinkHandler } from "@monarcode/session-kit/expo"; import { auth } from "../src/auth"; /** * Expo Router calls this with every URL that opens the app, before routing. - * Remembers the link, so SessionGate can open it after a sign-in if + * It remembers the link, so SessionGate can open it after a sign-in if * Stack.Protected turns it away now, and routes it unchanged. */ -export function redirectSystemPath({ - path, -}: { - path: string; - initial: boolean; -}) { - rememberDeepLink(auth, path); - return path; -} +export const redirectSystemPath = deepLinkHandler(auth); diff --git a/examples/expo-router/app/_layout.tsx b/examples/expo-router/app/_layout.tsx index 4ac89dd..4180f4d 100644 --- a/examples/expo-router/app/_layout.tsx +++ b/examples/expo-router/app/_layout.tsx @@ -1,9 +1,19 @@ +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, AuthProvider, useAuth } from "../src/auth"; +import { auth } from "../src/auth"; import { Unavailable } from "../src/unavailable"; +// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` +// with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + // Keeps the splash screen up until SessionGate hides it. void SplashScreen.preventAutoHideAsync(); @@ -18,12 +28,9 @@ export default function RootLayout() { } function RootStack() { - // Check `status`, not `user`: a locked session keeps its user. SessionGate + // A locked session isn't signed in, though it keeps its user. SessionGate // handles `initializing` and `unavailable` before this renders. - const signedIn = useAuth( - (state) => - state.status === "authenticated" || state.status === "refreshing", - ); + const signedIn = useAuth(isSignedIn); return ( diff --git a/examples/expo-router/src/auth.ts b/examples/expo-router/src/auth.ts index 64daf06..aea131d 100644 --- a/examples/expo-router/src/auth.ts +++ b/examples/expo-router/src/auth.ts @@ -1,7 +1,6 @@ import { createAuth } from "@monarcode/session-kit"; import { secureStorage } from "@monarcode/session-kit/expo"; import { createAuthFetch } from "@monarcode/session-kit/http"; -import { createAuthHooks } from "@monarcode/session-kit/react"; import { z } from "zod"; /** DummyJSON's auth API: https://dummyjson.com/docs/auth */ @@ -29,9 +28,10 @@ export const auth = createAuth({ name: "expo-example", user: userSchema, // The iOS keychain, or Keystore-encrypted storage on Android. Two JWTs and - // a user exceed SecureStore's 2048-byte value limit, so the value is split - // across keys. The defaults are `clearOnReinstall: true` and SecureStore's - // own `keychainAccessible` (`WHEN_UNLOCKED`). + // a user can pass 2048 bytes, which some iOS releases refuse to store in + // one value, so the value is split across keys. The defaults are + // `clearOnReinstall: true` and SecureStore's own `keychainAccessible` + // (`WHEN_UNLOCKED`). storage: secureStorage(), // Logs restores, refreshes, timers, and the gate's decisions to Metro in // development. Tokens and user fields stay out of the log. @@ -55,14 +55,11 @@ export const auth = createAuth({ }, }); -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); - /** * Sends requests to DummyJSON with the access token. After a 401 it * refreshes, then replays a GET or HEAD once. */ -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); /** Signs in with DummyJSON, then saves the tokens and the user it returned. */ export async function signInWithPassword(username: string, password: string) { diff --git a/examples/next-app/app/actions.ts b/examples/next-app/app/actions.ts index bafbdeb..f0e5509 100644 --- a/examples/next-app/app/actions.ts +++ b/examples/next-app/app/actions.ts @@ -1,22 +1,12 @@ "use server"; -// Server Functions the browser calls. Each is a public endpoint: Next checks -// that calls come from this site, and each one checks its own input. -import { nextJar } from "@monarcode/session-kit/next"; -import { cookies } from "next/headers"; +// The sign-in the browser calls: a public endpoint. Next checks that calls +// come from this site, and it checks its own input. The session route in +// `api/session/route.ts` does the rest. import { z } from "zod"; import { login } from "../lib/auth/backend"; -import { serverAuth } from "../lib/auth/server"; - -async function jar() { - return nextJar(await cookies(), { writable: true }); -} - -/** Who is signed in, from the cookie. Holds no tokens. */ -export async function getSessionAction() { - return serverAuth.getSession(await jar()); -} +import { session } from "../lib/auth/session"; const credentials = z.object({ username: z.string(), password: z.string() }); @@ -28,20 +18,11 @@ const credentials = z.object({ username: z.string(), password: z.string() }); export async function signInAction(input: unknown) { const { username, password } = credentials.parse(input); try { - return { - session: await serverAuth.signIn( - await jar(), - await login(username, password), - ), - }; + const tokens = await login(username, password); + return { session: await session.signIn(tokens) }; } catch (error) { return { error: error instanceof Error ? error.message : "Could not sign in", }; } } - -/** Clears the cookie. */ -export async function signOutAction() { - await serverAuth.signOut(await jar()); -} diff --git a/examples/next-app/app/api/auth/credentials/route.ts b/examples/next-app/app/api/auth/credentials/route.ts deleted file mode 100644 index 6a9d4d1..0000000 --- a/examples/next-app/app/api/auth/credentials/route.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { nextJar } from "@monarcode/session-kit/next"; -import { cookies } from "next/headers"; -import { z } from "zod"; - -import { serverAuth } from "../../../../lib/auth/server"; - -const rejected = z.object({ sessionId: z.string(), accessToken: z.string() }); - -/** - * The access token for the browser's own requests, never the refresh token: - * a POST with no body gets it, and one with the token DummyJSON rejected - * renews it. A route handler rather than a Server Function, so these calls - * don't wait behind other Server Functions or render the page again. - */ -export async function POST(request: Request) { - // Route handlers get no CSRF check from Next: accept this site only. - if (request.headers.get("sec-fetch-site") !== "same-origin") - return new Response(null, { status: 403 }); - const jar = nextJar(await cookies(), { writable: true }); - const body = rejected.safeParse(await request.json().catch(() => null)); - const credentials = body.success - ? await serverAuth.clientCredentials.renew(jar, body.data) - : await serverAuth.clientCredentials.get(jar); - return Response.json(credentials, { - headers: { "Cache-Control": "no-store" }, - }); -} diff --git a/examples/next-app/app/api/session/route.ts b/examples/next-app/app/api/session/route.ts new file mode 100644 index 0000000..7c82f2b --- /dev/null +++ b/examples/next-app/app/api/session/route.ts @@ -0,0 +1,10 @@ +import { sessionRoute } from "@monarcode/session-kit/next"; +import { cookies } from "next/headers"; + +import { serverAuth } from "../../../lib/auth/server"; + +/** + * The session route the browser's client calls: it reads the session, signs + * out, and gets the access token. It answers this site's own pages only. + */ +export const { GET, POST } = sessionRoute(serverAuth, { cookies }); diff --git a/examples/next-app/app/hooks.ts b/examples/next-app/app/hooks.ts deleted file mode 100644 index ad697b9..0000000 --- a/examples/next-app/app/hooks.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { AppAuth } from "../lib/auth/client"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); diff --git a/examples/next-app/app/layout.tsx b/examples/next-app/app/layout.tsx index 93950ac..54ff386 100644 --- a/examples/next-app/app/layout.tsx +++ b/examples/next-app/app/layout.tsx @@ -1,6 +1,6 @@ import type { ReactNode } from "react"; -import { getSession } from "../lib/auth/session"; +import { session } from "../lib/auth/session"; import { Providers } from "./providers"; export const metadata = { title: "session-kit with Next.js" }; @@ -10,11 +10,11 @@ export default async function RootLayout({ }: { children: ReactNode; }) { - const session = await getSession(); + const current = await session.get(); return ( - {children} + {children} ); diff --git a/examples/next-app/app/login/page.tsx b/examples/next-app/app/login/page.tsx index 8751832..c620fc2 100644 --- a/examples/next-app/app/login/page.tsx +++ b/examples/next-app/app/login/page.tsx @@ -1,7 +1,4 @@ -import { safeReturnTo } from "@monarcode/session-kit"; -import { redirect } from "next/navigation"; - -import { getSession } from "../../lib/auth/session"; +import { session } from "../../lib/auth/session"; import { LoginForm } from "../ui"; export default async function Login({ @@ -10,7 +7,6 @@ export default async function Login({ searchParams: Promise>; }) { // Signed in, before or after the form: the server sends the user on. - if (await getSession()) - redirect(safeReturnTo((await searchParams).redirectTo)); + await session.redirectIfSignedIn((await searchParams).redirectTo); return ; } diff --git a/examples/next-app/app/page.tsx b/examples/next-app/app/page.tsx index 1696a39..d79fff5 100644 --- a/examples/next-app/app/page.tsx +++ b/examples/next-app/app/page.tsx @@ -1,29 +1,24 @@ -import { nextJar } from "@monarcode/session-kit/next"; -import { cookies } from "next/headers"; +import { createAuthFetch } from "@monarcode/session-kit/http"; import { z } from "zod"; import { API } from "../lib/auth/api"; -import { serverAuth } from "../lib/auth/server"; -import { requireSession } from "../lib/auth/session"; +import { session } from "../lib/auth/session"; import { Profile } from "./ui"; /** Calls DummyJSON's `auth/me` while rendering, with the cookie's token. */ async function profileEmail() { // Read-only: Proxy refreshed the token before this render. - const credentials = await serverAuth.credentials.get( - nextJar(await cookies()), - ); - if (!credentials) return "Signed out"; - const response = await fetch(`${API}/auth/me`, { - headers: { Authorization: `Bearer ${credentials.accessToken}` }, + const apiFetch = createAuthFetch(await session.readOnly(), { + baseUrl: `${API}/`, }); + const response = await apiFetch("auth/me"); if (!response.ok) return `HTTP ${response.status}`; const profile = z.object({ email: z.string() }).parse(await response.json()); return profile.email; } export default async function Home() { - await requireSession("/"); + await session.require("/"); const fromServer = await profileEmail().catch( (error: unknown) => (error as Error).message, ); diff --git a/examples/next-app/app/providers.tsx b/examples/next-app/app/providers.tsx index 7203995..2e7aaca 100644 --- a/examples/next-app/app/providers.tsx +++ b/examples/next-app/app/providers.tsx @@ -2,17 +2,28 @@ import type { ReactNode } from "react"; -import { useMirrorAuth } from "@monarcode/session-kit/react"; +import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react"; import { useRouter } from "next/navigation"; -import { createAppAuth, type AppSession } from "../lib/auth/client"; -import { AuthProvider } from "./hooks"; +import { + createAppAuth, + type AppAuth, + type AppSession, +} from "../lib/auth/client"; + +// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` +// with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: AppAuth; + } +} /** * Gives Client Components the session the layout read. `useMirrorAuth` * follows the server's session when the page renders again, and renders it - * again with `router.refresh()` when the session changes in the browser, as after a sign-out here - * or in another tab, so the pages' redirects run. + * again with `router.refresh()` when the session changes in the browser, as + * after a sign-out here or in another tab, so the pages' redirects run. */ export function Providers({ session, @@ -22,6 +33,10 @@ export function Providers({ children: ReactNode; }) { const router = useRouter(); - const auth = useMirrorAuth(createAppAuth, session, () => router.refresh()); + const auth = useMirrorAuth({ + create: createAppAuth, + session, + onChange: () => router.refresh(), + }); return {children}; } diff --git a/examples/next-app/app/ui.tsx b/examples/next-app/app/ui.tsx index 6de59f1..1cbfa69 100644 --- a/examples/next-app/app/ui.tsx +++ b/examples/next-app/app/ui.tsx @@ -3,9 +3,9 @@ import { useMemo, useState, type FormEvent } from "react"; import { createAuthFetch } from "@monarcode/session-kit/http"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; import { API } from "../lib/auth/api"; -import { useAuth, useAuthClient } from "./hooks"; /** * The sign-in form, prefilled with DummyJSON's documented test user. Once @@ -29,10 +29,7 @@ export function LoginForm() { }); } catch (cause) { // The Server Function's own message, such as a wrong password. - const reason = cause instanceof Error ? cause.cause : undefined; - setError( - reason instanceof Error ? reason.message : "Could not sign in", - ); + setError(cause instanceof Error ? cause.message : "Could not sign in"); setPending(false); } } @@ -80,7 +77,10 @@ export function Profile({ fromServer }: { fromServer: string }) { const user = useAuth((state) => state.user); const auth = useAuthClient(); // The browser's requests get the access token from the server, in memory. - const authFetch = useMemo(() => createAuthFetch(auth, `${API}/`), [auth]); + const authFetch = useMemo( + () => createAuthFetch(auth, { baseUrl: `${API}/` }), + [auth], + ); const [fromBrowser, setFromBrowser] = useState(""); async function loadProfile() { @@ -107,7 +107,9 @@ export function Profile({ fromServer }: { fromServer: string }) { Load profile in the browser {fromBrowser &&

auth/me in the browser: {fromBrowser}

} - + ); } diff --git a/examples/next-app/lib/auth/client.ts b/examples/next-app/lib/auth/client.ts index 68f1ae7..e41f603 100644 --- a/examples/next-app/lib/auth/client.ts +++ b/examples/next-app/lib/auth/client.ts @@ -1,48 +1,27 @@ -import { - createMirrorAuth, - type ClientCredentials, -} from "@monarcode/session-kit"; +import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit"; -import { - getSessionAction, - signInAction, - signOutAction, -} from "../../app/actions"; +import { signInAction } from "../../app/actions"; +// Types only: erased from the browser's bundle. +import type { serverAuth } from "./server"; -export type AppSession = NonNullable< - Awaited> ->; - -/** Asks the route handler for the access token, or renews `rejected`. */ -async function credentials(rejected?: object) { - const response = await fetch("/api/auth/credentials", { - method: "POST", - body: JSON.stringify(rejected ?? null), - }); - if (!response.ok) throw new Error(`Credentials failed (${response.status})`); - return (await response.json()) as ClientCredentials | null; -} +export type AppSession = SessionOf; /** * The client the components use. It mirrors the session the server keeps in - * its cookie, starting from the one the layout rendered. `useMirrorAuth` - * creates it, once per request on the server and once in the browser. + * its cookie, starting from the one the layout rendered, and calls the + * session route in `app/api/session/route.ts`. `useMirrorAuth` creates it, + * once per request on the server and once in the browser. */ export function createAppAuth(session: AppSession | null) { return createMirrorAuth({ name: "session-kit-example", session, - revalidate: getSessionAction, + endpoint: "/api/session", signIn: async (input: { username: string; password: string }) => { const result = await signInAction(input); if ("error" in result) throw new Error(result.error); return result.session; }, - signOut: signOutAction, - credentials: { - get: () => credentials(), - renew: (rejected) => credentials(rejected), - }, }); } diff --git a/examples/next-app/lib/auth/server.ts b/examples/next-app/lib/auth/server.ts index 3d82a8a..00abba8 100644 --- a/examples/next-app/lib/auth/server.ts +++ b/examples/next-app/lib/auth/server.ts @@ -21,7 +21,7 @@ function sessionSecret(): string { /** * Keeps both tokens and the user in an encrypted, httpOnly cookie. With * `clientCredentials`, the browser can ask for the access token too, through - * the route handler in `app/api/auth/credentials`; the refresh token stays + * the session route in `app/api/session`; the refresh token stays * here. */ export const serverAuth = createServerAuth({ diff --git a/examples/next-app/lib/auth/session.ts b/examples/next-app/lib/auth/session.ts index 9d5fa3c..9fb40fd 100644 --- a/examples/next-app/lib/auth/session.ts +++ b/examples/next-app/lib/auth/session.ts @@ -1,26 +1,19 @@ -// The data access layer: how Server Components read the session. +// How server code reads and changes the session. import "server-only"; -import { cache } from "react"; - -import { safeReturnTo } from "@monarcode/session-kit"; -import { nextJar } from "@monarcode/session-kit/next"; +import { nextSession } from "@monarcode/session-kit/next"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; import { serverAuth } from "./server"; /** - * The session from the cookie, once per render. The jar is read-only, as - * Server Components can't set cookies: Proxy refreshed it first. + * The session for Server Components, Server Functions, Route Handlers and + * Proxy. Server Components read it with `get` and `require`, which can't set + * cookies: Proxy refreshed it first, with `refresh`. */ -export const getSession = cache(async () => - serverAuth.getSession(nextJar(await cookies())), -); - -/** The session, or a redirect to the sign-in page that comes back to `path`. */ -export async function requireSession(path: string) { - const session = await getSession(); - if (!session) - redirect(`/login?redirectTo=${encodeURIComponent(safeReturnTo(path))}`); - return session; -} +export const session = nextSession(serverAuth, { + cookies, + redirect, + // The example's tokens live a minute: refresh in their last 15 seconds. + within: 15, +}); diff --git a/examples/next-app/proxy.ts b/examples/next-app/proxy.ts index ee0a211..11d9465 100644 --- a/examples/next-app/proxy.ts +++ b/examples/next-app/proxy.ts @@ -1,21 +1,15 @@ -import { proxyJar } from "@monarcode/session-kit/next"; import { NextResponse, type NextRequest } from "next/server"; -import { serverAuth } from "./lib/auth/server"; +import { session } from "./lib/auth/session"; /** - * Refreshes access that is about to expire before Server Components and - * Server Functions read it: they can't set cookies while rendering, but - * Proxy can, and Next passes the new cookie on to them. A failed refresh is + * Refreshes access that is about to expire before any page or Server + * Function reads it. Server Components can't set cookies while rendering, so + * Proxy sets the new one, and Next passes it on to them. A failed refresh is * left for the page, which then reads the session as it was. */ -export async function proxy(request: NextRequest) { - const response = NextResponse.next(); - // The example's tokens live a minute: refresh in their last 15 seconds. - await serverAuth - .refreshIfDue(proxyJar(request, response), { within: 15 }) - .catch(() => {}); - return response; +export function proxy(request: NextRequest) { + return session.refresh(request, NextResponse.next()); } export const config = { diff --git a/examples/react-router-data/src/auth.ts b/examples/react-router-data/src/auth.ts index f509524..aeab929 100644 --- a/examples/react-router-data/src/auth.ts +++ b/examples/react-router-data/src/auth.ts @@ -38,7 +38,8 @@ export const auth = createAuth({ /** Signs in with DummyJSON and saves the tokens, which carry the user. */ export async function signInWithPassword(username: string, password: string) { - await auth.signIn(tokens.parse(await login(username, password))); + const response = await login(username, password); + await auth.signIn(tokens.parse(response)); } /** @@ -88,4 +89,4 @@ async function login(username: string, password: string): Promise { * Sends requests to DummyJSON with the access token. After a 401 it * refreshes, then replays a GET or HEAD once. */ -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); diff --git a/examples/react-router-data/src/hooks.ts b/examples/react-router-data/src/hooks.ts deleted file mode 100644 index 615afc3..0000000 --- a/examples/react-router-data/src/hooks.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { auth } from "./auth"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); diff --git a/examples/react-router-data/src/main.tsx b/examples/react-router-data/src/main.tsx index 629d8e5..0a2f53a 100644 --- a/examples/react-router-data/src/main.tsx +++ b/examples/react-router-data/src/main.tsx @@ -1,26 +1,27 @@ import { StrictMode } from "react"; -import { - createBrowserRouter, - Outlet, - RouterProvider, - useNavigate, - useRouteError, - useSearchParams, -} from "react-router"; +import { createBrowserRouter, Outlet, useRouteError } from "react-router"; -import { safeReturnTo } from "@monarcode/session-kit"; +import { AuthProvider } from "@monarcode/session-kit/react"; import { - redirectIfSignedIn, - requireSession, + redirectIfSignedInLoader, + requireSessionLoader, SessionOutlet, useAuthRevalidation, } from "@monarcode/session-kit/react-router"; import { createRoot } from "react-dom/client"; +import { RouterProvider } from "react-router/dom"; import { auth } from "./auth"; -import { AuthProvider } from "./hooks"; import { LoginForm, Pending, Profile, Unavailable } from "./ui"; +// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` +// with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + /** * Re-runs the guards in loaders after a sign-in, sign-out, account switch, * profile update, or a refresh that fails once access has expired. Token @@ -31,18 +32,6 @@ function Root() { return ; } -function Login() { - const navigate = useNavigate(); - const [search] = useSearchParams(); - return ( - - navigate(safeReturnTo(search.get("redirectTo")), { replace: true }) - } - /> - ); -} - function RouteError() { return ; } @@ -54,20 +43,13 @@ const router = createBrowserRouter([ children: [ { path: "/login", - loader: async ({ request }) => { - const redirectTo = new URL(request.url).searchParams.get( - "redirectTo", - ); - await redirectIfSignedIn(auth, { redirectTo }); - return null; - }, - element: , + loader: redirectIfSignedInLoader(auth), + element: , }, { - loader: ({ request }) => - requireSession(auth, { request, loginPath: "/login" }), + loader: requireSessionLoader(auth), errorElement: , - element: } />, + element: } />, children: [{ index: true, element: }], }, ], diff --git a/examples/react-router-data/src/ui.tsx b/examples/react-router-data/src/ui.tsx index c368f48..38d17ff 100644 --- a/examples/react-router-data/src/ui.tsx +++ b/examples/react-router-data/src/ui.tsx @@ -1,10 +1,15 @@ import { useState, type FormEvent } from "react"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; + import { authFetch, signInWithPassword } from "./auth"; -import { useAuth, useAuthClient } from "./hooks"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -18,7 +23,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { String(form.get("username")), String(form.get("password")), ); - await onSignedIn(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { @@ -90,7 +94,9 @@ export function Profile() { Load profile {fromApi &&

auth/me: {fromApi}

} - + ); } diff --git a/examples/react-router-declarative/src/auth.ts b/examples/react-router-declarative/src/auth.ts index 9ec9c05..95a7da4 100644 --- a/examples/react-router-declarative/src/auth.ts +++ b/examples/react-router-declarative/src/auth.ts @@ -31,9 +31,8 @@ export const auth = createAuth({ /** Signs in with DummyJSON, then saves the tokens and the user it returned. */ export async function signInWithPassword(username: string, password: string) { - const { accessToken, refreshToken, ...user } = loginResponse.parse( - await login(username, password), - ); + const response = await login(username, password); + const { accessToken, refreshToken, ...user } = loginResponse.parse(response); await auth.signIn({ accessToken, refreshToken, user }); } @@ -84,4 +83,4 @@ async function login(username: string, password: string): Promise { * Sends requests to DummyJSON with the access token. After a 401 it * refreshes, then replays a GET or HEAD once. */ -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); diff --git a/examples/react-router-declarative/src/hooks.ts b/examples/react-router-declarative/src/hooks.ts deleted file mode 100644 index 615afc3..0000000 --- a/examples/react-router-declarative/src/hooks.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { auth } from "./auth"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); diff --git a/examples/react-router-declarative/src/main.tsx b/examples/react-router-declarative/src/main.tsx index de5e719..1fb8cb5 100644 --- a/examples/react-router-declarative/src/main.tsx +++ b/examples/react-router-declarative/src/main.tsx @@ -7,27 +7,32 @@ import { useSearchParams, } from "react-router"; -import { safeReturnTo } from "@monarcode/session-kit"; +import { isSignedIn, safeReturnTo } from "@monarcode/session-kit"; +import { AuthProvider, useAuth } from "@monarcode/session-kit/react"; import { SessionOutlet } from "@monarcode/session-kit/react-router"; import { createRoot } from "react-dom/client"; import { auth } from "./auth"; -import { AuthProvider, useAuth } from "./hooks"; import { LoginForm, Pending, Profile, Unavailable } from "./ui"; +// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` +// with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + /** * Doesn't navigate after `signIn`: the state change re-renders this page, * which then redirects. */ function Login() { - const signedIn = useAuth( - (state) => - state.status === "authenticated" || state.status === "refreshing", - ); + const signedIn = useAuth(isSignedIn); const [search] = useSearchParams(); if (signedIn) return ; - return {}} />; + return ; } createRoot(document.getElementById("root")!).render( @@ -39,7 +44,6 @@ createRoot(document.getElementById("root")!).render( } unavailable={({ error }) => ( diff --git a/examples/react-router-declarative/src/ui.tsx b/examples/react-router-declarative/src/ui.tsx index c368f48..38d17ff 100644 --- a/examples/react-router-declarative/src/ui.tsx +++ b/examples/react-router-declarative/src/ui.tsx @@ -1,10 +1,15 @@ import { useState, type FormEvent } from "react"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; + import { authFetch, signInWithPassword } from "./auth"; -import { useAuth, useAuthClient } from "./hooks"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -18,7 +23,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { String(form.get("username")), String(form.get("password")), ); - await onSignedIn(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { @@ -90,7 +94,9 @@ export function Profile() { Load profile {fromApi &&

auth/me: {fromApi}

} - + ); } diff --git a/examples/react-router-framework-spa/app/auth.ts b/examples/react-router-framework-spa/app/auth.ts index 9ec9c05..95a7da4 100644 --- a/examples/react-router-framework-spa/app/auth.ts +++ b/examples/react-router-framework-spa/app/auth.ts @@ -31,9 +31,8 @@ export const auth = createAuth({ /** Signs in with DummyJSON, then saves the tokens and the user it returned. */ export async function signInWithPassword(username: string, password: string) { - const { accessToken, refreshToken, ...user } = loginResponse.parse( - await login(username, password), - ); + const response = await login(username, password); + const { accessToken, refreshToken, ...user } = loginResponse.parse(response); await auth.signIn({ accessToken, refreshToken, user }); } @@ -84,4 +83,4 @@ async function login(username: string, password: string): Promise { * Sends requests to DummyJSON with the access token. After a 401 it * refreshes, then replays a GET or HEAD once. */ -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); diff --git a/examples/react-router-framework-spa/app/hooks.ts b/examples/react-router-framework-spa/app/hooks.ts deleted file mode 100644 index 615afc3..0000000 --- a/examples/react-router-framework-spa/app/hooks.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { auth } from "./auth"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); diff --git a/examples/react-router-framework-spa/app/root.tsx b/examples/react-router-framework-spa/app/root.tsx index 5aaf93d..cd0b337 100644 --- a/examples/react-router-framework-spa/app/root.tsx +++ b/examples/react-router-framework-spa/app/root.tsx @@ -1,12 +1,20 @@ import type { ReactNode } from "react"; import { Links, Meta, Outlet, Scripts, ScrollRestoration } from "react-router"; +import { AuthProvider } from "@monarcode/session-kit/react"; import { useAuthRevalidation } from "@monarcode/session-kit/react-router"; import { auth } from "./auth"; -import { AuthProvider } from "./hooks"; import { Pending } from "./ui"; +// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` +// with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + export function Layout({ children }: { children: ReactNode }) { return ( diff --git a/examples/react-router-framework-spa/app/routes/login.tsx b/examples/react-router-framework-spa/app/routes/login.tsx index 9494bd1..e2be783 100644 --- a/examples/react-router-framework-spa/app/routes/login.tsx +++ b/examples/react-router-framework-spa/app/routes/login.tsx @@ -1,25 +1,9 @@ -import { useNavigate, useSearchParams } from "react-router"; - -import { safeReturnTo } from "@monarcode/session-kit"; -import { redirectIfSignedIn } from "@monarcode/session-kit/react-router"; +import { redirectIfSignedInLoader } from "@monarcode/session-kit/react-router"; import { auth } from "../auth"; import { LoginForm } from "../ui"; -export async function clientLoader({ request }: { request: Request }) { - const redirectTo = new URL(request.url).searchParams.get("redirectTo"); - await redirectIfSignedIn(auth, { redirectTo }); - return null; -} +// Runs again after a sign-in, as useAuthRevalidation runs the loaders again. +export const clientLoader = redirectIfSignedInLoader(auth); -export default function Login() { - const navigate = useNavigate(); - const [search] = useSearchParams(); - return ( - - navigate(safeReturnTo(search.get("redirectTo")), { replace: true }) - } - /> - ); -} +export default LoginForm; diff --git a/examples/react-router-framework-spa/app/routes/protected.tsx b/examples/react-router-framework-spa/app/routes/protected.tsx index f40eea3..3cda2ed 100644 --- a/examples/react-router-framework-spa/app/routes/protected.tsx +++ b/examples/react-router-framework-spa/app/routes/protected.tsx @@ -1,19 +1,17 @@ import { useRouteError } from "react-router"; import { - requireSession, + requireSessionLoader, SessionOutlet, } from "@monarcode/session-kit/react-router"; import { auth } from "../auth"; import { Pending, Unavailable } from "../ui"; -export function clientLoader({ request }: { request: Request }) { - return requireSession(auth, { request, loginPath: "/login" }); -} +export const clientLoader = requireSessionLoader(auth); export default function Protected() { - return } />; + return } />; } export function ErrorBoundary() { diff --git a/examples/react-router-framework-spa/app/ui.tsx b/examples/react-router-framework-spa/app/ui.tsx index c368f48..38d17ff 100644 --- a/examples/react-router-framework-spa/app/ui.tsx +++ b/examples/react-router-framework-spa/app/ui.tsx @@ -1,10 +1,15 @@ import { useState, type FormEvent } from "react"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; + import { authFetch, signInWithPassword } from "./auth"; -import { useAuth, useAuthClient } from "./hooks"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -18,7 +23,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { String(form.get("username")), String(form.get("password")), ); - await onSignedIn(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { @@ -90,7 +94,9 @@ export function Profile() { Load profile {fromApi &&

auth/me: {fromApi}

} - + ); } diff --git a/examples/react-router-framework-spa/tsconfig.json b/examples/react-router-framework-spa/tsconfig.json index a10bd69..2a32730 100644 --- a/examples/react-router-framework-spa/tsconfig.json +++ b/examples/react-router-framework-spa/tsconfig.json @@ -9,7 +9,8 @@ "skipLibCheck": true, "noEmit": true, "isolatedModules": true, + "rootDirs": [".", "./.react-router/types"], "types": ["vite/client"] }, - "include": ["app", "*.ts"] + "include": ["app", "*.ts", ".react-router/types/**/*"] } diff --git a/examples/react-router-framework-ssr/app/auth/client.ts b/examples/react-router-framework-ssr/app/auth/client.ts index eac0160..5410bc0 100644 --- a/examples/react-router-framework-ssr/app/auth/client.ts +++ b/examples/react-router-framework-ssr/app/auth/client.ts @@ -1,46 +1,21 @@ -import { - createMirrorAuth, - type ClientCredentials, - type Session, -} from "@monarcode/session-kit"; +import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit"; -import type { User } from "./backend"; +// Types only: erased from the browser's bundle. +import type { serverAuth } from "./session.server"; -export type AppSession = Session; - -/** Calls one of the resource routes in `routes/auth.*.ts`. */ -async function call(method: "GET" | "POST", path: string, body?: object) { - const response = await fetch(path, { - method, - ...(body && { - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }), - }); - if (!response.ok) throw new Error(`${path} failed (${response.status})`); - return (await response.json()) as T; -} +export type AppSession = SessionOf; /** * The client the components use. It mirrors the session the server keeps in - * its cookie, starting from the one the root loader read. `useMirrorAuth` - * creates it, once per request on the server and once in the browser. + * its cookie, starting from the one the root loader read, and calls the + * session route in `routes/auth.session.ts`. `useMirrorAuth` creates it, + * once per request on the server and once in the browser. */ export function createAppAuth(session: AppSession | null) { return createMirrorAuth({ name: "session-kit-example", session, - revalidate: () => call("GET", "/auth/session"), - signOut: () => call("POST", "/auth/session"), - credentials: { - get: () => call("POST", "/auth/credentials"), - renew: (rejected) => - call( - "POST", - "/auth/credentials", - rejected, - ), - }, + endpoint: "/auth/session", }); } diff --git a/examples/react-router-framework-ssr/app/auth/middleware.server.ts b/examples/react-router-framework-ssr/app/auth/middleware.server.ts deleted file mode 100644 index d07b597..0000000 --- a/examples/react-router-framework-ssr/app/auth/middleware.server.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { redirect, type MiddlewareFunction } from "react-router"; - -import { - cookieJarMiddleware, - routerJar, -} from "@monarcode/session-kit/react-router/server"; - -import { serverAuth } from "./session.server"; - -/** - * Refreshes access that is about to expire before loaders and actions read - * it, while the response can still set the cookie. A failed refresh is left - * for the loaders, which then read the session as it was. - */ -const refreshSession: MiddlewareFunction = async ( - { context }, - next, -) => { - // The example's tokens live a minute: refresh in their last 15 seconds. - await serverAuth - .refreshIfDue(routerJar(context), { within: 15 }) - .catch(() => {}); - const response = await next(); - // Every page and resource route here depends on who is signed in. A - // copy: some responses, such as `fetch`'s, can't change their headers. - const page = new Response(response.body, response); - page.headers.set("Cache-Control", "private, no-store"); - return page; -}; - -/** - * The root route's middleware. The jar comes first: it sets the cookies the - * rest write on the response. - */ -export const sessionMiddleware = [cookieJarMiddleware, refreshSession]; - -/** - * Sends signed-out users to the sign-in page, which brings them back. As - * middleware, it runs on the server before any loader or action below the - * route, for documents and for data requests alike. - */ -export const requireSession: MiddlewareFunction = async ({ - context, - url, -}) => { - if (!(await serverAuth.getSession(routerJar(context)))) - throw redirect( - `/login?redirectTo=${encodeURIComponent(url.pathname + url.search)}`, - ); -}; diff --git a/examples/react-router-framework-ssr/app/auth/session.server.ts b/examples/react-router-framework-ssr/app/auth/session.server.ts index dd4c1e6..27ced94 100644 --- a/examples/react-router-framework-ssr/app/auth/session.server.ts +++ b/examples/react-router-framework-ssr/app/auth/session.server.ts @@ -1,5 +1,9 @@ // Holds the secret and the tokens: the `.server` name keeps it out of the // browser's bundle, and the build fails if browser code imports it. +import { + requireSession, + routerAuth, +} from "@monarcode/session-kit/react-router/server"; import { createServerAuth } from "@monarcode/session-kit/server"; import { refresh, userSchema } from "./backend"; @@ -19,7 +23,7 @@ function sessionSecret(): string { /** * Keeps both tokens and the user in an encrypted, httpOnly cookie. With * `clientCredentials`, the browser can ask for the access token too, through - * the resource route in `routes/auth.credentials.ts`; the refresh token stays + * the session route in `routes/auth.session.ts`; the refresh token stays * here. */ export const serverAuth = createServerAuth({ @@ -31,3 +35,17 @@ export const serverAuth = createServerAuth({ // `react-router dev` serves plain http; Safari drops Secure cookies there. cookie: { secure: !import.meta.env.DEV }, }); + +/** + * The session of the request React Router is handling, by its `context`: + * `auth(context).getSession()` in a loader, action or middleware. + */ +export const auth = routerAuth(serverAuth); + +/** + * Lets only signed-in users through to the routes it guards, as middleware: + * it runs on the server before their loaders and actions, for page loads and + * navigation alike. Signed-out users go to the sign-in page, which brings + * them back. `signedIn.session(context)` gives those loaders the session. + */ +export const signedIn = requireSession(serverAuth); diff --git a/examples/react-router-framework-ssr/app/hooks.ts b/examples/react-router-framework-ssr/app/hooks.ts deleted file mode 100644 index 7a7c0b9..0000000 --- a/examples/react-router-framework-ssr/app/hooks.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { AppAuth } from "./auth/client"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); diff --git a/examples/react-router-framework-ssr/app/root.tsx b/examples/react-router-framework-ssr/app/root.tsx index fd3d839..7a9caee 100644 --- a/examples/react-router-framework-ssr/app/root.tsx +++ b/examples/react-router-framework-ssr/app/root.tsx @@ -11,19 +11,34 @@ import { type LoaderFunctionArgs, } from "react-router"; -import { useMirrorAuth } from "@monarcode/session-kit/react"; -import { routerJar } from "@monarcode/session-kit/react-router/server"; +import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react"; +import { sessionMiddleware } from "@monarcode/session-kit/react-router/server"; -import { createAppAuth } from "./auth/client"; -import { sessionMiddleware } from "./auth/middleware.server"; -import { serverAuth } from "./auth/session.server"; -import { AuthProvider } from "./hooks"; +import { createAppAuth, type AppAuth } from "./auth/client"; +import { auth, serverAuth } from "./auth/session.server"; -export const middleware = sessionMiddleware; +// Types `AuthProvider` and the hooks from `@monarcode/session-kit/react` +// with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: AppAuth; + } +} + +/** + * Gives each request its cookies, then refreshes access that is about to + * expire before loaders and actions read it, while the response can still + * set the cookie. Every response is marked private, as each one depends on + * who is signed in. + */ +export const middleware = sessionMiddleware(serverAuth, { + // The example's tokens live a minute: refresh in their last 15 seconds. + within: 15, +}); /** Who is signed in, from the cookie. Holds no tokens. */ export async function loader({ context }: LoaderFunctionArgs) { - return { session: await serverAuth.getSession(routerJar(context)) }; + return { session: await auth(context).getSession() }; } export function Layout({ children }: { children: ReactNode }) { @@ -57,7 +72,11 @@ export function Layout({ children }: { children: ReactNode }) { export default function App() { const { session } = useLoaderData(); const { revalidate } = useRevalidator(); - const auth = useMirrorAuth(createAppAuth, session, revalidate); + const auth = useMirrorAuth({ + create: createAppAuth, + session, + onChange: revalidate, + }); return ( diff --git a/examples/react-router-framework-ssr/app/routes.ts b/examples/react-router-framework-ssr/app/routes.ts index 4a6f0db..9bf6255 100644 --- a/examples/react-router-framework-ssr/app/routes.ts +++ b/examples/react-router-framework-ssr/app/routes.ts @@ -8,7 +8,6 @@ import { export default [ route("login", "routes/login.tsx"), layout("routes/protected.tsx", [index("routes/home.tsx")]), - // Resource routes the browser's client calls. + // The session route the browser's client calls. route("auth/session", "routes/auth.session.ts"), - route("auth/credentials", "routes/auth.credentials.ts"), ] satisfies RouteConfig; diff --git a/examples/react-router-framework-ssr/app/routes/auth.credentials.ts b/examples/react-router-framework-ssr/app/routes/auth.credentials.ts deleted file mode 100644 index 444d489..0000000 --- a/examples/react-router-framework-ssr/app/routes/auth.credentials.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { ActionFunctionArgs } from "react-router"; - -import { routerJar } from "@monarcode/session-kit/react-router/server"; -import { z } from "zod"; - -import { serverAuth } from "../auth/session.server"; - -const rejected = z.object({ sessionId: z.string(), accessToken: z.string() }); - -/** - * The access token for the browser's own requests, never the refresh token: - * a POST with no body gets it, and one with the token DummyJSON rejected - * renews it. React Router checks no origin for resource routes: accept this - * site only. - */ -export async function action({ request, context }: ActionFunctionArgs) { - if (request.headers.get("sec-fetch-site") !== "same-origin") - return new Response(null, { status: 403 }); - const jar = routerJar(context); - const body = rejected.safeParse(await request.json().catch(() => null)); - return Response.json( - body.success - ? await serverAuth.clientCredentials.renew(jar, body.data) - : await serverAuth.clientCredentials.get(jar), - ); -} diff --git a/examples/react-router-framework-ssr/app/routes/auth.session.ts b/examples/react-router-framework-ssr/app/routes/auth.session.ts index 2dedf40..aa4efa8 100644 --- a/examples/react-router-framework-ssr/app/routes/auth.session.ts +++ b/examples/react-router-framework-ssr/app/routes/auth.session.ts @@ -1,21 +1,13 @@ -import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router"; - -import { routerJar } from "@monarcode/session-kit/react-router/server"; +import { sessionRoute } from "@monarcode/session-kit/react-router/server"; import { serverAuth } from "../auth/session.server"; -/** Who is signed in, from the cookie, for the client's `revalidate`. */ -export async function loader({ context }: LoaderFunctionArgs) { - return Response.json(await serverAuth.getSession(routerJar(context))); -} - /** - * Signs out, for the client's `signOut`. React Router checks the origin of - * route actions, but not of resource routes': accept this site only. + * The session route the browser's client calls: it reads the session, signs + * out, and gets the access token. It answers this site's own pages only. */ -export async function action({ request, context }: ActionFunctionArgs) { - if (request.headers.get("sec-fetch-site") !== "same-origin") - return new Response(null, { status: 403 }); - await serverAuth.signOut(routerJar(context)); - return Response.json(null); -} +const route = sessionRoute(serverAuth); + +// One by one: React Router's build can't remove a destructured export. +export const loader = route.loader; +export const action = route.action; diff --git a/examples/react-router-framework-ssr/app/routes/home.tsx b/examples/react-router-framework-ssr/app/routes/home.tsx index a4ced29..069df04 100644 --- a/examples/react-router-framework-ssr/app/routes/home.tsx +++ b/examples/react-router-framework-ssr/app/routes/home.tsx @@ -1,35 +1,22 @@ import { useLoaderData, type LoaderFunctionArgs } from "react-router"; -import { routerJar } from "@monarcode/session-kit/react-router/server"; +import { createAuthFetch } from "@monarcode/session-kit/http"; import { z } from "zod"; import { API } from "../auth/api"; -import { serverAuth } from "../auth/session.server"; +import { auth } from "../auth/session.server"; import { Profile } from "../ui"; /** Calls DummyJSON's `auth/me` from the server, with the cookie's token. */ export async function loader({ context }: LoaderFunctionArgs) { - const jar = routerJar(context); - const credentials = await serverAuth.credentials.get(jar); - if (!credentials) return { email: "Signed out" }; - let response = await me(credentials.accessToken); - if (response.status === 401) { - // Refreshes once, then tries again. - const renewed = await serverAuth.credentials.renew(jar, credentials); - if (!renewed) return { email: "Signed out" }; - response = await me(renewed.accessToken); - } + // After a 401, it renews the token, saves it in the cookie, and tries again. + const apiFetch = createAuthFetch(auth(context), { baseUrl: `${API}/` }); + const response = await apiFetch("auth/me"); if (!response.ok) return { email: `HTTP ${response.status}` }; const profile = z.object({ email: z.string() }).parse(await response.json()); return { email: profile.email }; } -function me(accessToken: string) { - return fetch(`${API}/auth/me`, { - headers: { Authorization: `Bearer ${accessToken}` }, - }); -} - export default function Home() { const { email } = useLoaderData(); return ; diff --git a/examples/react-router-framework-ssr/app/routes/login.tsx b/examples/react-router-framework-ssr/app/routes/login.tsx index e1352a2..0026ad1 100644 --- a/examples/react-router-framework-ssr/app/routes/login.tsx +++ b/examples/react-router-framework-ssr/app/routes/login.tsx @@ -1,44 +1,42 @@ import { + data, redirect, useActionData, useNavigation, type ActionFunctionArgs, - type LoaderFunctionArgs, } from "react-router"; import { safeReturnTo } from "@monarcode/session-kit"; -import { routerJar } from "@monarcode/session-kit/react-router/server"; +import { redirectIfSignedIn } from "@monarcode/session-kit/react-router/server"; import { login } from "../auth/backend"; -import { serverAuth } from "../auth/session.server"; +import { auth, serverAuth } from "../auth/session.server"; import { LoginForm } from "../ui"; -/** Signed in, before or after the form: the server sends the user on. */ -export async function loader({ context, url }: LoaderFunctionArgs) { - if (await serverAuth.getSession(routerJar(context))) - throw redirect(safeReturnTo(url.searchParams.get("redirectTo"))); - return null; -} +/** Signed in already: the server sends the user on to `redirectTo`. */ +export const loader = redirectIfSignedIn(serverAuth); /** * Signs in with DummyJSON on the server and sets the cookie. React Router * checks that the form came from this site. A failure is returned for the - * form to show. + * form to show, with status 400, so React Router skips running the loaders + * again. */ export async function action({ request, context, url }: ActionFunctionArgs) { const form = await request.formData(); try { - await serverAuth.signIn( - routerJar(context), - await login( - String(form.get("username")), - String(form.get("password")), - ), + const tokens = await login( + String(form.get("username")), + String(form.get("password")), ); + await auth(context).signIn(tokens); } catch (error) { - return { - error: error instanceof Error ? error.message : "Could not sign in", - }; + return data( + { + error: error instanceof Error ? error.message : "Could not sign in", + }, + { status: 400 }, + ); } throw redirect(safeReturnTo(url.searchParams.get("redirectTo"))); } diff --git a/examples/react-router-framework-ssr/app/routes/protected.tsx b/examples/react-router-framework-ssr/app/routes/protected.tsx index 9d2050f..351fd3d 100644 --- a/examples/react-router-framework-ssr/app/routes/protected.tsx +++ b/examples/react-router-framework-ssr/app/routes/protected.tsx @@ -1,8 +1,12 @@ import { Outlet } from "react-router"; -import { requireSession } from "../auth/middleware.server"; +import { signedIn } from "../auth/session.server"; -export const middleware = [requireSession]; +export const middleware = [signedIn]; + +// So navigation in the browser runs the middleware, whatever the routes +// nested here load. +export const loader = () => null; export default function Protected() { return ; diff --git a/examples/react-router-framework-ssr/app/ui.tsx b/examples/react-router-framework-ssr/app/ui.tsx index 80ea9f4..bbc3ebd 100644 --- a/examples/react-router-framework-ssr/app/ui.tsx +++ b/examples/react-router-framework-ssr/app/ui.tsx @@ -2,9 +2,9 @@ import { useMemo, useState } from "react"; import { Form } from "react-router"; import { createAuthFetch } from "@monarcode/session-kit/http"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; import { API } from "./auth/api"; -import { useAuth, useAuthClient } from "./hooks"; /** * The sign-in form, prefilled with DummyJSON's documented test user. It @@ -60,7 +60,10 @@ export function Profile({ fromServer }: { fromServer: string }) { const user = useAuth((state) => state.user); const auth = useAuthClient(); // The browser's requests get the access token from the server, in memory. - const authFetch = useMemo(() => createAuthFetch(auth, `${API}/`), [auth]); + const authFetch = useMemo( + () => createAuthFetch(auth, { baseUrl: `${API}/` }), + [auth], + ); const [fromBrowser, setFromBrowser] = useState(""); async function loadProfile() { @@ -87,7 +90,9 @@ export function Profile({ fromServer }: { fromServer: string }) { Load profile in the browser {fromBrowser &&

auth/me in the browser: {fromBrowser}

} - + ); } diff --git a/examples/react-router-framework-ssr/tsconfig.json b/examples/react-router-framework-ssr/tsconfig.json index 5af911a..a125136 100644 --- a/examples/react-router-framework-ssr/tsconfig.json +++ b/examples/react-router-framework-ssr/tsconfig.json @@ -9,7 +9,8 @@ "skipLibCheck": true, "noEmit": true, "isolatedModules": true, + "rootDirs": [".", "./.react-router/types"], "types": ["vite/client", "node"] }, - "include": ["app", "*.ts"] + "include": ["app", "*.ts", ".react-router/types/**/*"] } diff --git a/examples/tanstack-router/src/auth.ts b/examples/tanstack-router/src/auth.ts index 9ec9c05..95a7da4 100644 --- a/examples/tanstack-router/src/auth.ts +++ b/examples/tanstack-router/src/auth.ts @@ -31,9 +31,8 @@ export const auth = createAuth({ /** Signs in with DummyJSON, then saves the tokens and the user it returned. */ export async function signInWithPassword(username: string, password: string) { - const { accessToken, refreshToken, ...user } = loginResponse.parse( - await login(username, password), - ); + const response = await login(username, password); + const { accessToken, refreshToken, ...user } = loginResponse.parse(response); await auth.signIn({ accessToken, refreshToken, user }); } @@ -84,4 +83,4 @@ async function login(username: string, password: string): Promise { * Sends requests to DummyJSON with the access token. After a 401 it * refreshes, then replays a GET or HEAD once. */ -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); diff --git a/examples/tanstack-router/src/hooks.ts b/examples/tanstack-router/src/hooks.ts deleted file mode 100644 index a6294ae..0000000 --- a/examples/tanstack-router/src/hooks.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; -import { useRouterAuth } from "@monarcode/session-kit/tanstack-router"; - -// Reads the client from Router context, so no provider is needed. -export const { useAuth, useAuthClient } = createAuthHooks({ - useClient: useRouterAuth, -}); diff --git a/examples/tanstack-router/src/router.tsx b/examples/tanstack-router/src/router.tsx index 2465c7f..bc704ba 100644 --- a/examples/tanstack-router/src/router.tsx +++ b/examples/tanstack-router/src/router.tsx @@ -11,8 +11,9 @@ export const router = createRouter({ defaultPendingComponent: Pending, }); -// Restores the session, runs expiry timers and tab sync, and re-runs guards. -connectAuth(router); +// Restores the session, runs expiry timers and tab sync, and re-runs guards +// when auth changes. Call it once, beside the Router. +export const disconnectAuth = connectAuth(router); declare module "@tanstack/react-router" { interface Register { diff --git a/examples/tanstack-router/src/routes/_authenticated.tsx b/examples/tanstack-router/src/routes/_authenticated.tsx index eef8802..11e5f0c 100644 --- a/examples/tanstack-router/src/routes/_authenticated.tsx +++ b/examples/tanstack-router/src/routes/_authenticated.tsx @@ -8,7 +8,7 @@ import { Pending, Unavailable } from "../ui"; export const Route = createFileRoute("/_authenticated")({ beforeLoad: ({ context, location }) => - requireSession(context.auth, { location, loginPath: "/login" }), + requireSession(context.auth, { location }), errorComponent: ({ error }) => , component: () => } />, }); diff --git a/examples/tanstack-router/src/routes/login.tsx b/examples/tanstack-router/src/routes/login.tsx index 06976a2..2806f36 100644 --- a/examples/tanstack-router/src/routes/login.tsx +++ b/examples/tanstack-router/src/routes/login.tsx @@ -1,6 +1,6 @@ import { safeReturnTo } from "@monarcode/session-kit"; import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router"; -import { createFileRoute, useRouter } from "@tanstack/react-router"; +import { createFileRoute } from "@tanstack/react-router"; import { LoginForm } from "../ui"; @@ -8,17 +8,8 @@ export const Route = createFileRoute("/login")({ validateSearch: (search: Record) => ({ redirectTo: safeReturnTo(search.redirectTo), }), + // Runs again after a sign-in, which runs the guards again. beforeLoad: ({ context, search }) => redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }), - component: Login, + component: LoginForm, }); - -function Login() { - const router = useRouter(); - const { redirectTo } = Route.useSearch(); - return ( - router.navigate({ href: redirectTo, replace: true })} - /> - ); -} diff --git a/examples/tanstack-router/src/ui.tsx b/examples/tanstack-router/src/ui.tsx index c368f48..6d8c893 100644 --- a/examples/tanstack-router/src/ui.tsx +++ b/examples/tanstack-router/src/ui.tsx @@ -1,10 +1,16 @@ import { useState, type FormEvent } from "react"; +import { useAuthClient } from "@monarcode/session-kit/tanstack-router"; +import { getRouteApi } from "@tanstack/react-router"; + import { authFetch, signInWithPassword } from "./auth"; -import { useAuth, useAuthClient } from "./hooks"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -18,7 +24,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { String(form.get("username")), String(form.get("password")), ); - await onSignedIn(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { @@ -61,9 +66,14 @@ const emailOf = (value: unknown) => ? String(value.email) : ""; -/** The signed-in user, a request using the access token, and sign-out. */ +const authenticated = getRouteApi("/_authenticated"); + +/** + * The signed-in user, a request using the access token, and sign-out. It + * renders under the guarded layout, whose route context holds the session. + */ export function Profile() { - const user = useAuth((state) => state.user); + const { user } = authenticated.useRouteContext().session; const auth = useAuthClient(); const [fromApi, setFromApi] = useState(""); @@ -78,8 +88,8 @@ export function Profile() { return (
-

Welcome, {user?.firstName}

-

Signed in as {user?.username}

+

Welcome, {user.firstName}

+

Signed in as {user.username}

{fromApi &&

auth/me: {fromApi}

} - +
); } diff --git a/examples/tanstack-start-spa-effetch/src/api-client.ts b/examples/tanstack-start-spa-effetch/src/api-client.ts deleted file mode 100644 index 83f289c..0000000 --- a/examples/tanstack-start-spa-effetch/src/api-client.ts +++ /dev/null @@ -1,29 +0,0 @@ -import * as Fetch from "@monarcode/effetch"; -import { sessionBearer } from "@monarcode/session-kit/effetch"; -import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Schema from "effect/Schema"; - -import { API_BASE_URL } from "./auth"; - -/** DummyJSON explains an error in its body: `{ "message": "…" }`. */ -export const ApiErrorBody = Schema.Struct({ message: Schema.String }); -export type ApiErrorBody = Schema.Schema.Type; - -const make = Fetch.make({ - baseUrl: API_BASE_URL, - defaultError: ApiErrorBody, - // Sends the access token to DummyJSON only. After a 401 it refreshes, then - // replays a GET or HEAD once. `optional`: a call made while signed out, - // such as the sign-in itself, goes without a token. - plugins: [sessionBearer({ baseUrl: API_BASE_URL, optional: true })], -}); - -/** The app's API client: effetch's `get`, `post` and the rest, for DummyJSON. */ -export class ApiClient extends Context.Service< - ApiClient, - Effect.Success ->()("ApiClient") {} - -export const ApiClientLive = Layer.effect(ApiClient, make); diff --git a/examples/tanstack-start-spa-effetch/src/api.ts b/examples/tanstack-start-spa-effetch/src/api.ts new file mode 100644 index 0000000..7d465af --- /dev/null +++ b/examples/tanstack-start-spa-effetch/src/api.ts @@ -0,0 +1,33 @@ +import * as Fetch from "@monarcode/effetch"; +import { retry } from "@monarcode/effetch/plugins"; +import { sessionBearer } from "@monarcode/session-kit/effetch"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; +import * as Layer from "effect/Layer"; + +import { API_BASE_URL, ApiError } from "./backend"; + +const make = Fetch.make({ + baseUrl: API_BASE_URL, + defaultError: ApiError, + // `retry` resends a GET after a network error or a status such as 503. + // `sessionBearer` comes after it, so each attempt reads the current token. + // It sends the token to DummyJSON only. After a 401 it refreshes, then + // sends a GET or HEAD again once. `optional`: a call made while signed out + // goes without a token. + plugins: [retry(), sessionBearer({ baseUrl: API_BASE_URL, optional: true })], +}).pipe( + // Effect adds tracing headers to every request, which fail the preflight + // of an API that doesn't allow them. + Effect.provideService(HttpClient.TracerPropagationEnabled, false), +); + +/** The app's API client: effetch's `get`, `post` and the rest, for DummyJSON. */ +export class ApiClient extends Context.Service< + ApiClient, + Effect.Success +>()("ApiClient") {} + +/** The API client, over whichever `Auth` is provided. */ +export const ApiClientLive = Layer.effect(ApiClient, make); diff --git a/examples/tanstack-start-spa-effetch/src/auth.ts b/examples/tanstack-start-spa-effetch/src/auth.ts index 1bc6a65..3222067 100644 --- a/examples/tanstack-start-spa-effetch/src/auth.ts +++ b/examples/tanstack-start-spa-effetch/src/auth.ts @@ -1,84 +1,24 @@ -import * as Fetch from "@monarcode/effetch"; import { createAuth, fromAccessToken, webStorage, } from "@monarcode/session-kit"; -import { Auth } from "@monarcode/session-kit/effect"; -import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -import { FetchLive } from "./fetch"; - -/** DummyJSON's auth API: https://dummyjson.com/docs/auth */ -export const API_BASE_URL = "https://dummyjson.com"; - -/** One-minute tokens make the early refresh visible after about 30 seconds. */ -export const expiresInMins = 1; - -export const SessionTokens = Schema.Struct({ - accessToken: Schema.String, - refreshToken: Schema.String, -}); - -/** - * DummyJSON's access tokens are JWTs carrying the user, so this app reads the - * user from the token instead of the login response. A struct drops the - * claims it doesn't list, such as `exp` and `iat`, which change on every - * refresh. - */ -export const SessionUser = Schema.Struct({ - id: Schema.Finite, - username: Schema.String, - email: Schema.String, - firstName: Schema.String, - lastName: Schema.String, - image: Schema.String, -}); - -// Not the app's API client: its session plugin waits for this refresh. -const makeRefreshClient = Fetch.make({ baseUrl: API_BASE_URL }); - -/** - * Exchanges the refresh token for new tokens. DummyJSON answers 403 for an - * invalid or expired refresh token and 401 for a missing one: both mean - * "sign in again", so succeed with `null`. Other failures fail: the session - * is kept and the error shows in `state.error`. - */ -const refreshSession = (refreshToken: string) => - Effect.gen(function* () { - const client = yield* makeRefreshClient; - return yield* client.post("/auth/refresh", { - body: { refreshToken, expiresInMins }, - output: SessionTokens, - }); - }).pipe( - Effect.catchTag("HttpError", (error) => - error.status === 401 || error.status === 403 - ? Effect.succeed(null) - : Effect.fail(error), - ), - Effect.provide(FetchLive), - ); +import { SessionUser } from "./backend"; +import { refreshSession } from "./refresh"; export const auth = createAuth({ name: "session-kit-example", user: fromAccessToken(Schema.toStandardSchemaV1(SessionUser)), storage: webStorage(), - refresh: ({ refreshToken, signal }) => - Effect.runPromise(refreshSession(refreshToken), { signal }), + refresh: ({ refreshToken, signal }) => refreshSession(refreshToken, signal), }); -// Registered once, so every `Auth` Effect is typed with this client's user. -declare module "@monarcode/session-kit/effect" { +// Registered once, so every `Auth` Effect, and the hooks, carry this +// client's user. +declare module "@monarcode/session-kit" { interface Register { auth: typeof auth; } } - -/** - * The client as the `Auth` service, which the API client's `sessionBearer` - * reads the access token from. It doesn't mount the client: `connectAuth` - * does, in `router.tsx`. - */ -export const AuthLive = Auth.layer(auth); diff --git a/examples/tanstack-start-spa-effetch/src/backend.ts b/examples/tanstack-start-spa-effetch/src/backend.ts new file mode 100644 index 0000000..b94eef0 --- /dev/null +++ b/examples/tanstack-start-spa-effetch/src/backend.ts @@ -0,0 +1,31 @@ +import * as Schema from "effect/Schema"; + +/** DummyJSON's auth API: https://dummyjson.com/docs/auth */ +export const API_BASE_URL = "https://dummyjson.com"; + +/** One-minute tokens make the early refresh visible after about 30 seconds. */ +export const expiresInMins = 1; + +/** + * DummyJSON's access tokens are JWTs carrying the user, so this app reads the + * user from the token instead of the login response. A struct drops the + * claims it doesn't list, such as `exp` and `iat`, which change on every + * refresh. + */ +export const SessionUser = Schema.Struct({ + id: Schema.Finite, + username: Schema.String, + email: Schema.String, + firstName: Schema.String, + lastName: Schema.String, + image: Schema.String, +}); + +export const SessionTokens = Schema.Struct({ + accessToken: Schema.String, + refreshToken: Schema.String, +}); + +/** DummyJSON explains an error in its body: `{ "message": "…" }`. */ +export const ApiError = Schema.Struct({ message: Schema.String }); +export type ApiError = Schema.Schema.Type; diff --git a/examples/tanstack-start-spa-effetch/src/endpoints.ts b/examples/tanstack-start-spa-effetch/src/endpoints.ts index 4e47240..81fbafc 100644 --- a/examples/tanstack-start-spa-effetch/src/endpoints.ts +++ b/examples/tanstack-start-spa-effetch/src/endpoints.ts @@ -1,10 +1,10 @@ import * as Fetch from "@monarcode/effetch"; import * as Schema from "effect/Schema"; -import { SessionTokens } from "./auth"; +import { SessionTokens } from "./backend"; import { api } from "./query"; -/** Signs in with DummyJSON. Sent without a token: nobody is signed in yet. */ +/** Signs in with DummyJSON. Sent without a token, as it's how one is got. */ export const signInMutation = api.mutation( Fetch.endpoint("POST /auth/login", { input: Schema.Struct({ @@ -14,6 +14,7 @@ export const signInMutation = api.mutation( }), output: SessionTokens, }), + { plugins: { sessionBearer: false } }, ); /** The signed-in user's profile, requested with the access token. */ diff --git a/examples/tanstack-start-spa-effetch/src/error-message.ts b/examples/tanstack-start-spa-effetch/src/error-message.ts index d659a61..770f77c 100644 --- a/examples/tanstack-start-spa-effetch/src/error-message.ts +++ b/examples/tanstack-start-spa-effetch/src/error-message.ts @@ -4,10 +4,10 @@ import * as Cause from "effect/Cause"; import * as Match from "effect/Match"; import * as Option from "effect/Option"; -import type { ApiErrorBody } from "./api-client"; +import type { ApiError } from "./backend"; type ApiCallError = - | HttpError.With + | HttpError.With | NetworkError | DecodeError | AuthFailure; diff --git a/examples/tanstack-start-spa-effetch/src/fetch.ts b/examples/tanstack-start-spa-effetch/src/fetch.ts deleted file mode 100644 index 7449f61..0000000 --- a/examples/tanstack-start-spa-effetch/src/fetch.ts +++ /dev/null @@ -1,12 +0,0 @@ -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import * as HttpClient from "effect/http/HttpClient"; -import * as Layer from "effect/Layer"; - -/** - * `fetch`, without the tracing headers Effect adds to every request: from a - * browser, they fail the preflight of an API that doesn't allow them. - */ -export const FetchLive = Layer.merge( - FetchHttpClient.layer, - Layer.succeed(HttpClient.TracerPropagationEnabled, false), -); diff --git a/examples/tanstack-start-spa-effetch/src/hooks.ts b/examples/tanstack-start-spa-effetch/src/hooks.ts deleted file mode 100644 index a6294ae..0000000 --- a/examples/tanstack-start-spa-effetch/src/hooks.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; -import { useRouterAuth } from "@monarcode/session-kit/tanstack-router"; - -// Reads the client from Router context, so no provider is needed. -export const { useAuth, useAuthClient } = createAuthHooks({ - useClient: useRouterAuth, -}); diff --git a/examples/tanstack-start-spa-effetch/src/layer.ts b/examples/tanstack-start-spa-effetch/src/layer.ts new file mode 100644 index 0000000..cc97ac2 --- /dev/null +++ b/examples/tanstack-start-spa-effetch/src/layer.ts @@ -0,0 +1,10 @@ +import { Auth } from "@monarcode/session-kit/effect"; + +import { auth } from "./auth"; + +/** + * The client as the `Auth` service, which the API client's `sessionBearer` + * reads the access token from. It doesn't mount the client: `connectAuth` + * does, in `router.tsx`. + */ +export const AuthLive = Auth.layer(auth); diff --git a/examples/tanstack-start-spa-effetch/src/query.ts b/examples/tanstack-start-spa-effetch/src/query.ts index f1ae09e..3d0972b 100644 --- a/examples/tanstack-start-spa-effetch/src/query.ts +++ b/examples/tanstack-start-spa-effetch/src/query.ts @@ -2,7 +2,8 @@ import { QueryClient } from "@monarcode/effetch-query"; import { endpoints } from "@monarcode/effetch-query/effetch"; import type * as ManagedRuntime from "effect/ManagedRuntime"; -import { ApiClient, ApiErrorBody } from "./api-client"; +import { ApiClient } from "./api"; +import { ApiError } from "./backend"; import { appRuntime, type AppRuntime } from "./runtime"; declare module "@monarcode/effetch-query" { @@ -12,7 +13,7 @@ declare module "@monarcode/effetch-query" { } /** Turns endpoints of the API client into queries and mutations. */ -export const api = endpoints(ApiClient, { defaultError: ApiErrorBody }); +export const api = endpoints(ApiClient, { defaultError: ApiError }); /** * Makes the query cache, which runs queries and mutations with `appRuntime`'s diff --git a/examples/tanstack-start-spa-effetch/src/refresh.ts b/examples/tanstack-start-spa-effetch/src/refresh.ts new file mode 100644 index 0000000..7ee2a68 --- /dev/null +++ b/examples/tanstack-start-spa-effetch/src/refresh.ts @@ -0,0 +1,37 @@ +import * as Fetch from "@monarcode/effetch"; +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as HttpClient from "effect/http/HttpClient"; + +import { API_BASE_URL, expiresInMins, SessionTokens } from "./backend"; + +// Not the app's API client: its session plugin waits for this refresh. +const makeRefreshClient = Fetch.make({ baseUrl: API_BASE_URL }).pipe( + // No tracing headers, as for the API client. + Effect.provideService(HttpClient.TracerPropagationEnabled, false), +); + +/** + * Exchanges the refresh token for new tokens. DummyJSON answers 403 for an + * invalid or expired refresh token and 401 for a missing one: both mean + * "sign in again", so it resolves `null`. Other failures reject, so the + * session is kept and the error shows in `state.error`. + */ +export const refreshSession = (refreshToken: string, signal: AbortSignal) => + Effect.runPromise( + Effect.gen(function* () { + const client = yield* makeRefreshClient; + return yield* client.post("/auth/refresh", { + body: { refreshToken, expiresInMins }, + output: SessionTokens, + }); + }).pipe( + Effect.catchTag("HttpError", (error) => + error.status === 401 || error.status === 403 + ? Effect.succeed(null) + : Effect.fail(error), + ), + Effect.provide(FetchHttpClient.layer), + ), + { signal }, + ); diff --git a/examples/tanstack-start-spa-effetch/src/routes/__root.tsx b/examples/tanstack-start-spa-effetch/src/routes/__root.tsx index 41ed42d..6d3a957 100644 --- a/examples/tanstack-start-spa-effetch/src/routes/__root.tsx +++ b/examples/tanstack-start-spa-effetch/src/routes/__root.tsx @@ -2,6 +2,7 @@ import type { ReactNode } from "react"; import { QueryProvider } from "@monarcode/effetch-query/react"; +import { useAuth } from "@monarcode/session-kit/tanstack-router"; import { createRootRouteWithContext, HeadContent, @@ -10,7 +11,6 @@ import { } from "@tanstack/react-router"; import type { auth } from "../auth"; -import { useAuth } from "../hooks"; import { makeQueryClient } from "../query"; export const Route = createRootRouteWithContext<{ auth: typeof auth }>()({ @@ -27,9 +27,9 @@ export const Route = createRootRouteWithContext<{ auth: typeof auth }>()({ /** A query cache for each session, so no account sees another's data. */ function Root() { - const sessionId = useAuth((state) => state.sessionId); + const account = useAuth((state) => state.sessionId ?? "signed-out"); return ( - + ); diff --git a/examples/tanstack-start-spa-effetch/src/routes/_authenticated.tsx b/examples/tanstack-start-spa-effetch/src/routes/_authenticated.tsx index eef8802..11e5f0c 100644 --- a/examples/tanstack-start-spa-effetch/src/routes/_authenticated.tsx +++ b/examples/tanstack-start-spa-effetch/src/routes/_authenticated.tsx @@ -8,7 +8,7 @@ import { Pending, Unavailable } from "../ui"; export const Route = createFileRoute("/_authenticated")({ beforeLoad: ({ context, location }) => - requireSession(context.auth, { location, loginPath: "/login" }), + requireSession(context.auth, { location }), errorComponent: ({ error }) => , component: () => } />, }); diff --git a/examples/tanstack-start-spa-effetch/src/routes/login.tsx b/examples/tanstack-start-spa-effetch/src/routes/login.tsx index 06976a2..2806f36 100644 --- a/examples/tanstack-start-spa-effetch/src/routes/login.tsx +++ b/examples/tanstack-start-spa-effetch/src/routes/login.tsx @@ -1,6 +1,6 @@ import { safeReturnTo } from "@monarcode/session-kit"; import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router"; -import { createFileRoute, useRouter } from "@tanstack/react-router"; +import { createFileRoute } from "@tanstack/react-router"; import { LoginForm } from "../ui"; @@ -8,17 +8,8 @@ export const Route = createFileRoute("/login")({ validateSearch: (search: Record) => ({ redirectTo: safeReturnTo(search.redirectTo), }), + // Runs again after a sign-in, which runs the guards again. beforeLoad: ({ context, search }) => redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }), - component: Login, + component: LoginForm, }); - -function Login() { - const router = useRouter(); - const { redirectTo } = Route.useSearch(); - return ( - router.navigate({ href: redirectTo, replace: true })} - /> - ); -} diff --git a/examples/tanstack-start-spa-effetch/src/runtime.ts b/examples/tanstack-start-spa-effetch/src/runtime.ts index 08890bf..e5fa748 100644 --- a/examples/tanstack-start-spa-effetch/src/runtime.ts +++ b/examples/tanstack-start-spa-effetch/src/runtime.ts @@ -1,17 +1,18 @@ +import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as Layer from "effect/Layer"; import * as ManagedRuntime from "effect/ManagedRuntime"; -import { ApiClientLive } from "./api-client"; -import { AuthLive } from "./auth"; -import { FetchLive } from "./fetch"; +import { ApiClientLive } from "./api"; +import { AuthLive } from "./layer"; /** - * The composition root: the app's services and what they depend on. A new - * service is added here. + * The composition root: the API client, the session, and the + * `FetchHttpClient` effetch sends with, each made once. A new service is + * added here. */ const AppLayer = ApiClientLive.pipe( Layer.provideMerge(AuthLive), - Layer.provide(FetchLive), + Layer.provide(FetchHttpClient.layer), ); /** One runtime for the app's lifetime. */ diff --git a/examples/tanstack-start-spa-effetch/src/ui.tsx b/examples/tanstack-start-spa-effetch/src/ui.tsx index 07b81d5..732f9da 100644 --- a/examples/tanstack-start-spa-effetch/src/ui.tsx +++ b/examples/tanstack-start-spa-effetch/src/ui.tsx @@ -1,16 +1,21 @@ import { useState, type FormEvent } from "react"; import { useMutation, useQuery } from "@monarcode/effetch-query/react"; +import { useAuthClient } from "@monarcode/session-kit/tanstack-router"; +import { getRouteApi } from "@tanstack/react-router"; import * as Exit from "effect/Exit"; import * as AsyncResult from "effect/reactivity/AsyncResult"; -import { expiresInMins } from "./auth"; +import { expiresInMins } from "./backend"; import { profileQuery, signInMutation } from "./endpoints"; import { apiErrorMessage } from "./error-message"; -import { useAuth, useAuthClient } from "./hooks"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const auth = useAuthClient(); const signIn = useMutation(signInMutation); const [error, setError] = useState(""); @@ -33,7 +38,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { try { // The tokens carry the user, so they are all the client needs. await auth.signIn(exit.value); - await onSignedIn(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } @@ -81,19 +85,26 @@ function ProfileEmail() { }); } -/** The signed-in user, a request using the access token, and sign-out. */ +const authenticated = getRouteApi("/_authenticated"); + +/** + * The signed-in user, a request using the access token, and sign-out. It + * renders under the guarded layout, whose route context holds the session. + */ export function Profile() { - const user = useAuth((state) => state.user); + const { user } = authenticated.useRouteContext().session; const auth = useAuthClient(); const [showEmail, setShowEmail] = useState(false); return (
-

Welcome, {user?.firstName}

-

Signed in as {user?.username}

+

Welcome, {user.firstName}

+

Signed in as {user.username}

{showEmail && } - +
); } diff --git a/examples/tanstack-start-spa/src/auth.ts b/examples/tanstack-start-spa/src/auth.ts index f509524..aeab929 100644 --- a/examples/tanstack-start-spa/src/auth.ts +++ b/examples/tanstack-start-spa/src/auth.ts @@ -38,7 +38,8 @@ export const auth = createAuth({ /** Signs in with DummyJSON and saves the tokens, which carry the user. */ export async function signInWithPassword(username: string, password: string) { - await auth.signIn(tokens.parse(await login(username, password))); + const response = await login(username, password); + await auth.signIn(tokens.parse(response)); } /** @@ -88,4 +89,4 @@ async function login(username: string, password: string): Promise { * Sends requests to DummyJSON with the access token. After a 401 it * refreshes, then replays a GET or HEAD once. */ -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); diff --git a/examples/tanstack-start-spa/src/hooks.ts b/examples/tanstack-start-spa/src/hooks.ts deleted file mode 100644 index a6294ae..0000000 --- a/examples/tanstack-start-spa/src/hooks.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; -import { useRouterAuth } from "@monarcode/session-kit/tanstack-router"; - -// Reads the client from Router context, so no provider is needed. -export const { useAuth, useAuthClient } = createAuthHooks({ - useClient: useRouterAuth, -}); diff --git a/examples/tanstack-start-spa/src/routes/_authenticated.tsx b/examples/tanstack-start-spa/src/routes/_authenticated.tsx index eef8802..11e5f0c 100644 --- a/examples/tanstack-start-spa/src/routes/_authenticated.tsx +++ b/examples/tanstack-start-spa/src/routes/_authenticated.tsx @@ -8,7 +8,7 @@ import { Pending, Unavailable } from "../ui"; export const Route = createFileRoute("/_authenticated")({ beforeLoad: ({ context, location }) => - requireSession(context.auth, { location, loginPath: "/login" }), + requireSession(context.auth, { location }), errorComponent: ({ error }) => , component: () => } />, }); diff --git a/examples/tanstack-start-spa/src/routes/login.tsx b/examples/tanstack-start-spa/src/routes/login.tsx index 06976a2..2806f36 100644 --- a/examples/tanstack-start-spa/src/routes/login.tsx +++ b/examples/tanstack-start-spa/src/routes/login.tsx @@ -1,6 +1,6 @@ import { safeReturnTo } from "@monarcode/session-kit"; import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router"; -import { createFileRoute, useRouter } from "@tanstack/react-router"; +import { createFileRoute } from "@tanstack/react-router"; import { LoginForm } from "../ui"; @@ -8,17 +8,8 @@ export const Route = createFileRoute("/login")({ validateSearch: (search: Record) => ({ redirectTo: safeReturnTo(search.redirectTo), }), + // Runs again after a sign-in, which runs the guards again. beforeLoad: ({ context, search }) => redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }), - component: Login, + component: LoginForm, }); - -function Login() { - const router = useRouter(); - const { redirectTo } = Route.useSearch(); - return ( - router.navigate({ href: redirectTo, replace: true })} - /> - ); -} diff --git a/examples/tanstack-start-spa/src/ui.tsx b/examples/tanstack-start-spa/src/ui.tsx index c368f48..6d8c893 100644 --- a/examples/tanstack-start-spa/src/ui.tsx +++ b/examples/tanstack-start-spa/src/ui.tsx @@ -1,10 +1,16 @@ import { useState, type FormEvent } from "react"; +import { useAuthClient } from "@monarcode/session-kit/tanstack-router"; +import { getRouteApi } from "@tanstack/react-router"; + import { authFetch, signInWithPassword } from "./auth"; -import { useAuth, useAuthClient } from "./hooks"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -18,7 +24,6 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { String(form.get("username")), String(form.get("password")), ); - await onSignedIn(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { @@ -61,9 +66,14 @@ const emailOf = (value: unknown) => ? String(value.email) : ""; -/** The signed-in user, a request using the access token, and sign-out. */ +const authenticated = getRouteApi("/_authenticated"); + +/** + * The signed-in user, a request using the access token, and sign-out. It + * renders under the guarded layout, whose route context holds the session. + */ export function Profile() { - const user = useAuth((state) => state.user); + const { user } = authenticated.useRouteContext().session; const auth = useAuthClient(); const [fromApi, setFromApi] = useState(""); @@ -78,8 +88,8 @@ export function Profile() { return (
-

Welcome, {user?.firstName}

-

Signed in as {user?.username}

+

Welcome, {user.firstName}

+

Signed in as {user.username}

{fromApi &&

auth/me: {fromApi}

} - +
); } diff --git a/examples/tanstack-start-ssr/src/auth/client.ts b/examples/tanstack-start-ssr/src/auth/client.ts index b3bb1a8..0417a9a 100644 --- a/examples/tanstack-start-ssr/src/auth/client.ts +++ b/examples/tanstack-start-ssr/src/auth/client.ts @@ -1,31 +1,22 @@ import { createMirrorAuth } from "@monarcode/session-kit"; -import { - getCredentialsFn, - getSessionFn, - renewCredentialsFn, - signInFn, - signOutFn, -} from "./functions"; +import { getSessionFn, signInFn } from "./functions"; /** * The client the routes and components use. It mirrors the session the * server keeps in its cookie: `loadSession` fills it on the server, and - * `sessionHydration` carries that to the browser. Create one per router: on - * the server, that is one per request. + * `connectSession` carries that to the browser. It signs out and gets the + * access token through the session route in `routes/api/session.ts`. Create + * one per router: on the server, that is one per request. */ export function createAppAuth() { return createMirrorAuth({ name: "session-kit-example", session: null, + endpoint: "/api/session", revalidate: () => getSessionFn(), signIn: (data: { username: string; password: string }) => signInFn({ data }), - signOut: () => signOutFn(), - credentials: { - get: () => getCredentialsFn(), - renew: (rejected) => renewCredentialsFn({ data: rejected }), - }, }); } diff --git a/examples/tanstack-start-ssr/src/auth/functions.ts b/examples/tanstack-start-ssr/src/auth/functions.ts index 8171c47..e48b1ea 100644 --- a/examples/tanstack-start-ssr/src/auth/functions.ts +++ b/examples/tanstack-start-ssr/src/auth/functions.ts @@ -1,60 +1,33 @@ -import { startJar } from "@monarcode/session-kit/tanstack-start/server"; import { createServerFn } from "@tanstack/react-start"; import { z } from "zod"; -import { API } from "./api"; import { login } from "./backend"; -import { serverAuth } from "./server"; +import { apiFetch, session } from "./server"; // Each handler runs on the server; Start's compiler replaces it with a fetch -// in the browser, and leaves `startJar` and `serverAuth` out of that bundle. +// in the browser, and leaves `session` out of that bundle. -/** Who is signed in, from the cookie. Holds no tokens. */ +/** + * Who is signed in, from the cookie. Holds no tokens. The client's + * `revalidate`: `loadSession` calls it while Start renders on the server, + * where the client can't call the session route. + */ export const getSessionFn = createServerFn().handler(() => - serverAuth.getSession(startJar()), + session.getSession(), ); /** Signs in with DummyJSON on the server and sets the cookie. */ export const signInFn = createServerFn({ method: "POST" }) .validator(z.object({ username: z.string(), password: z.string() })) - .handler(async ({ data }) => - serverAuth.signIn(startJar(), await login(data.username, data.password)), - ); - -/** Clears the cookie. */ -export const signOutFn = createServerFn({ method: "POST" }).handler(() => - serverAuth.signOut(startJar()), -); - -/** The access token for the browser's own requests, never the refresh token. */ -export const getCredentialsFn = createServerFn({ method: "POST" }).handler(() => - serverAuth.clientCredentials.get(startJar()), -); - -/** New access after DummyJSON rejected the browser's token. */ -export const renewCredentialsFn = createServerFn({ method: "POST" }) - .validator(z.object({ sessionId: z.string(), accessToken: z.string() })) - .handler(({ data }) => serverAuth.clientCredentials.renew(startJar(), data)); + .handler(async ({ data }) => { + const tokens = await login(data.username, data.password); + return session.signIn(tokens); + }); /** Calls DummyJSON's `auth/me` from the server, with the cookie's token. */ export const getProfileFn = createServerFn().handler(async () => { - const jar = startJar(); - const credentials = await serverAuth.credentials.get(jar); - if (!credentials) return { email: "Signed out" }; - let response = await me(credentials.accessToken); - if (response.status === 401) { - // Refreshes once, then tries again. - const renewed = await serverAuth.credentials.renew(jar, credentials); - if (!renewed) return { email: "Signed out" }; - response = await me(renewed.accessToken); - } + const response = await apiFetch("auth/me"); if (!response.ok) return { email: `HTTP ${response.status}` }; const profile = z.object({ email: z.string() }).parse(await response.json()); return { email: profile.email }; }); - -function me(accessToken: string) { - return fetch(`${API}/auth/me`, { - headers: { Authorization: `Bearer ${accessToken}` }, - }); -} diff --git a/examples/tanstack-start-ssr/src/auth/server.ts b/examples/tanstack-start-ssr/src/auth/server.ts index e6a21a0..c113df4 100644 --- a/examples/tanstack-start-ssr/src/auth/server.ts +++ b/examples/tanstack-start-ssr/src/auth/server.ts @@ -1,7 +1,10 @@ // Holds the secret and the tokens: Start refuses to bundle it for the browser. import "@tanstack/react-start/server-only"; +import { createAuthFetch } from "@monarcode/session-kit/http"; import { createServerAuth } from "@monarcode/session-kit/server"; +import { startAuth } from "@monarcode/session-kit/tanstack-start/server"; +import { API } from "./api"; import { refresh, userSchema } from "./backend"; /** @@ -19,7 +22,7 @@ function sessionSecret(): string { /** * Keeps both tokens and the user in an encrypted, httpOnly cookie. With * `clientCredentials`, the browser can ask for the access token too, through - * the server functions in `functions.ts`; the refresh token stays here. + * the session route in `routes/api/session.ts`; the refresh token stays here. */ export const serverAuth = createServerAuth({ name: "session-kit-example", @@ -30,3 +33,15 @@ export const serverAuth = createServerAuth({ // `vite dev` serves plain http; Safari drops Secure cookies there. cookie: { secure: !import.meta.env.DEV }, }); + +/** + * The session of the request Start is handling: each call finds it, so one + * object serves every request. + */ +export const session = startAuth(serverAuth); + +/** + * Calls DummyJSON with the cookie's access token. After a 401, it renews the + * token, saves it in the cookie, and sends a `GET` again. + */ +export const apiFetch = createAuthFetch(session, { baseUrl: `${API}/` }); diff --git a/examples/tanstack-start-ssr/src/hooks.ts b/examples/tanstack-start-ssr/src/hooks.ts deleted file mode 100644 index a6294ae..0000000 --- a/examples/tanstack-start-ssr/src/hooks.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { createAuthHooks } from "@monarcode/session-kit/react"; -import { useRouterAuth } from "@monarcode/session-kit/tanstack-router"; - -// Reads the client from Router context, so no provider is needed. -export const { useAuth, useAuthClient } = createAuthHooks({ - useClient: useRouterAuth, -}); diff --git a/examples/tanstack-start-ssr/src/router.tsx b/examples/tanstack-start-ssr/src/router.tsx index 777d5bb..66fcbf5 100644 --- a/examples/tanstack-start-ssr/src/router.tsx +++ b/examples/tanstack-start-ssr/src/router.tsx @@ -1,5 +1,4 @@ -import { connectAuth } from "@monarcode/session-kit/tanstack-router"; -import { sessionHydration } from "@monarcode/session-kit/tanstack-start"; +import { connectSession } from "@monarcode/session-kit/tanstack-start"; import { createRouter } from "@tanstack/react-router"; import { createAppAuth } from "./auth/client"; @@ -13,11 +12,10 @@ export function getRouter() { context: { auth }, defaultPendingComponent: Pending, scrollRestoration: true, - // Sends the session the server read to the browser, without tokens. - ...sessionHydration(auth), }); - // Re-runs guards when the session changes. Does nothing on the server. - connectAuth(router); + // Sends the session the server read to the browser, without tokens, and + // re-runs guards when it changes there. + connectSession(router); return router; } diff --git a/examples/tanstack-start-ssr/src/routes/_authenticated.tsx b/examples/tanstack-start-ssr/src/routes/_authenticated.tsx index eef8802..11e5f0c 100644 --- a/examples/tanstack-start-ssr/src/routes/_authenticated.tsx +++ b/examples/tanstack-start-ssr/src/routes/_authenticated.tsx @@ -8,7 +8,7 @@ import { Pending, Unavailable } from "../ui"; export const Route = createFileRoute("/_authenticated")({ beforeLoad: ({ context, location }) => - requireSession(context.auth, { location, loginPath: "/login" }), + requireSession(context.auth, { location }), errorComponent: ({ error }) => , component: () => } />, }); diff --git a/examples/tanstack-start-ssr/src/routes/api/session.ts b/examples/tanstack-start-ssr/src/routes/api/session.ts new file mode 100644 index 0000000..7dd014e --- /dev/null +++ b/examples/tanstack-start-ssr/src/routes/api/session.ts @@ -0,0 +1,13 @@ +import { sessionRoute } from "@monarcode/session-kit/tanstack-start/server"; +import { createFileRoute } from "@tanstack/react-router"; + +import { serverAuth } from "../../auth/server"; + +/** + * The session route the browser's client calls to sign out and get the + * access token. It answers this site's own pages only. Start keeps + * `server.handlers` out of the browser bundle, `serverAuth` included. + */ +export const Route = createFileRoute("/api/session")({ + server: { handlers: sessionRoute(serverAuth) }, +}); diff --git a/examples/tanstack-start-ssr/src/routes/login.tsx b/examples/tanstack-start-ssr/src/routes/login.tsx index 06976a2..2806f36 100644 --- a/examples/tanstack-start-ssr/src/routes/login.tsx +++ b/examples/tanstack-start-ssr/src/routes/login.tsx @@ -1,6 +1,6 @@ import { safeReturnTo } from "@monarcode/session-kit"; import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router"; -import { createFileRoute, useRouter } from "@tanstack/react-router"; +import { createFileRoute } from "@tanstack/react-router"; import { LoginForm } from "../ui"; @@ -8,17 +8,8 @@ export const Route = createFileRoute("/login")({ validateSearch: (search: Record) => ({ redirectTo: safeReturnTo(search.redirectTo), }), + // Runs again after a sign-in, which runs the guards again. beforeLoad: ({ context, search }) => redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }), - component: Login, + component: LoginForm, }); - -function Login() { - const router = useRouter(); - const { redirectTo } = Route.useSearch(); - return ( - router.navigate({ href: redirectTo, replace: true })} - /> - ); -} diff --git a/examples/tanstack-start-ssr/src/start.ts b/examples/tanstack-start-ssr/src/start.ts index 05942ed..50a67f1 100644 --- a/examples/tanstack-start-ssr/src/start.ts +++ b/examples/tanstack-start-ssr/src/start.ts @@ -1,27 +1,21 @@ -import { startJar } from "@monarcode/session-kit/tanstack-start/server"; +import { refreshSession } from "@monarcode/session-kit/tanstack-start/server"; import { createCsrfMiddleware, createMiddleware, createStart, } from "@tanstack/react-start"; -import { setResponseHeader } from "@tanstack/react-start/server"; import { serverAuth } from "./auth/server"; /** * Refreshes access that is about to expire before routes and server - * functions read it, while the response can still set the cookie. A failed - * refresh is left for the route: `loadSession` then rejects, and the root - * route's error component offers a retry. + * functions read it, while the response can still set the cookie. Start + * keeps what's inside `.server()` out of the browser bundle, `serverAuth` + * included. */ const sessionMiddleware = createMiddleware({ type: "request" }).server( - async ({ next }) => { - // Every page and server function here depends on who is signed in. - setResponseHeader("Cache-Control", "private, no-store"); - // The example's tokens live a minute: refresh in their last 15 seconds. - await serverAuth.refreshIfDue(startJar(), { within: 15 }).catch(() => {}); - return next(); - }, + // The example's tokens live a minute: refresh in their last 15 seconds. + refreshSession(serverAuth, { within: 15 }), ); export const startInstance = createStart(() => ({ diff --git a/examples/tanstack-start-ssr/src/ui.tsx b/examples/tanstack-start-ssr/src/ui.tsx index 6a7f602..36f3de3 100644 --- a/examples/tanstack-start-ssr/src/ui.tsx +++ b/examples/tanstack-start-ssr/src/ui.tsx @@ -1,13 +1,17 @@ import { useMemo, useState, type FormEvent } from "react"; import { createAuthFetch } from "@monarcode/session-kit/http"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/tanstack-router"; import { useRouter } from "@tanstack/react-router"; import { API } from "./auth/api"; -import { useAuth, useAuthClient } from "./hooks"; -/** The sign-in form, prefilled with DummyJSON's documented test user. */ -export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { +/** + * The sign-in form, prefilled with DummyJSON's documented test user. It + * doesn't navigate: a sign-in runs the guards again, and the sign-in page's + * guard sends the user on. + */ +export function LoginForm() { const auth = useAuthClient(); const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -23,13 +27,9 @@ export function LoginForm({ onSignedIn }: { onSignedIn: () => unknown }) { username: String(form.get("username")), password: String(form.get("password")), }); - await onSignedIn(); } catch (cause) { // The server function's own message, such as a wrong password. - const reason = cause instanceof Error ? cause.cause : undefined; - setError( - reason instanceof Error ? reason.message : "Could not sign in", - ); + setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { setPending(false); } @@ -78,7 +78,10 @@ export function Profile({ fromServer }: { fromServer: string }) { const user = useAuth((state) => state.user); const auth = useAuthClient(); // The browser's requests get the access token from the server, in memory. - const authFetch = useMemo(() => createAuthFetch(auth, `${API}/`), [auth]); + const authFetch = useMemo( + () => createAuthFetch(auth, { baseUrl: `${API}/` }), + [auth], + ); const [fromBrowser, setFromBrowser] = useState(""); async function loadProfile() { @@ -105,7 +108,9 @@ export function Profile({ fromServer }: { fromServer: string }) { Load profile in the browser {fromBrowser &&

auth/me in the browser: {fromBrowser}

} - + ); } diff --git a/package.json b/package.json index 0aa96ea..bf0436f 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@monarcode/session-kit", - "version": "0.1.0-alpha.8", - "description": "Schema-driven sessions for React, with TanStack Router, React Router, and Expo Router support, and server rendering with TanStack Start, Next.js, and React Router", + "version": "0.1.0-rc.0", + "description": "Schema-driven, type-safe sessions for React, with TanStack Router, React Router, Expo Router, Next.js, TanStack Start, and Effect support", "keywords": [ "auth", "effect", @@ -111,7 +111,7 @@ "test": "pnpm run test:sync && pnpm run test:async", "test:sync": "node --conditions=development --test tests/*.test.ts", "test:async": "node --env-file=tests/async-storage.env --conditions=development --test tests/*.test.ts", - "test:types": "tsc -p tests/tsconfig.tests.json && tsc -p tests/tsconfig.json && tsc -p tests/tsconfig.bundler.json && tsc -p tests/tsconfig.json --exactOptionalPropertyTypes false && tsc -p tests/tsconfig.mirror.json && tsc -p tests/tsconfig.mirror.bundler.json && tsc -p tests/tsconfig.mirror.json --exactOptionalPropertyTypes false && pnpm run test:docs", + "test:types": "tsc -p tests/tsconfig.tests.json && tsc -p tests/tsconfig.json && tsc -p tests/tsconfig.bundler.json && tsc -p tests/tsconfig.json --exactOptionalPropertyTypes false && tsc -p tests/tsconfig.mirror.json && tsc -p tests/tsconfig.mirror.bundler.json && tsc -p tests/tsconfig.mirror.json --exactOptionalPropertyTypes false && tsc -p tests/tsconfig.unregistered.json && tsc -p tests/tsconfig.unregistered.bundler.json && tsc -p tests/tsconfig.unregistered.json --exactOptionalPropertyTypes false && node scripts/check-middleware-types.mjs && pnpm run test:docs", "test:docs": "node scripts/check-docs.mjs", "docs:reference": "node scripts/reference-docs.mjs && oxfmt --write \"site/content/docs/(latest)/reference\"", "check": "pnpm run lint && pnpm run format:check && pnpm run build && pnpm test && pnpm run test:types", diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjs index 188f503..3e1ba02 100644 --- a/scripts/check-docs.mjs +++ b/scripts/check-docs.mjs @@ -157,29 +157,55 @@ function checkExportDocs(program) { if (missing.length > 0) problems.push(`${locate(node)}: ${name} needs ${missing.join(", ")}`); }; - const requireMemberDocs = (name, members) => { + // A member that another part of the same type documents may be declared + // again without docs, such as to make an option required: editors show + // the documented one. + const requireMemberDocs = (name, members, documented = new Set()) => { for (const member of members) { if (member.name === undefined || !ts.isPropertySignature(member)) continue; - if (!docOf(member).description) + if ( + !docOf(member).description && + !documented.has(member.name.getText()) + ) problems.push( `${locate(member)}: ${name}.${member.name.getText()} needs a description`, ); } }; - // Object types, also when joined with `&` or `|`. - const literalsOf = (type) => - ts.isTypeLiteralNode(type) - ? [type] - : ts.isIntersectionTypeNode(type) || ts.isUnionTypeNode(type) - ? type.types.flatMap(literalsOf) - : ts.isParenthesizedTypeNode(type) - ? literalsOf(type.type) - : []; + // Object types, also when joined with `&` or `|`, or behind a type alias + // that isn't exported, whose members only show through this one. + const literalsOf = (type, seenAliases = new Set()) => { + if (ts.isTypeLiteralNode(type)) return [type]; + if (ts.isIntersectionTypeNode(type) || ts.isUnionTypeNode(type)) + return type.types.flatMap((part) => literalsOf(part, seenAliases)); + if (ts.isParenthesizedTypeNode(type)) + return literalsOf(type.type, seenAliases); + if (ts.isTypeReferenceNode(type)) { + const alias = checker + .getSymbolAtLocation(type.typeName) + ?.declarations?.find(ts.isTypeAliasDeclaration); + const exported = alias?.modifiers?.some( + (modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword, + ); + if (!alias || exported || seenAliases.has(alias)) return []; + seenAliases.add(alias); + return literalsOf(alias.type, seenAliases); + } + return []; + }; const isOverloadImplementation = (node) => ts.isFunctionDeclaration(node) && node.body !== undefined && checker.getSymbolAtLocation(node.name)?.declarations?.length > 1; + // Editors show the first overload's JSDoc for an overload that has none. + const isLaterOverload = (node, symbol) => + ts.isFunctionDeclaration(node) && + node.body === undefined && + !docOf(node).description && + symbol.declarations.find( + (other) => ts.isFunctionDeclaration(other) && other.body === undefined, + ) !== node; const seen = new Set(); for (const subpath of subpaths) { const moduleSymbol = checker.getSymbolAtLocation( @@ -193,14 +219,29 @@ function checkExportDocs(program) { if (seen.has(symbol)) continue; seen.add(symbol); for (const declaration of symbol.declarations ?? []) { - if (isOverloadImplementation(declaration)) continue; + if ( + isOverloadImplementation(declaration) || + isLaterOverload(declaration, symbol) + ) + continue; requireFull(exported.name, declaration); if (!/(Options|Props)$/.test(exported.name)) continue; if (ts.isInterfaceDeclaration(declaration)) requireMemberDocs(exported.name, declaration.members); - if (ts.isTypeAliasDeclaration(declaration)) - for (const literal of literalsOf(declaration.type)) - requireMemberDocs(exported.name, literal.members); + if (ts.isTypeAliasDeclaration(declaration)) { + const literals = literalsOf(declaration.type); + const documented = new Set( + literals.flatMap((literal) => + literal.members + .filter( + (member) => member.name && docOf(member).description, + ) + .map((member) => member.name.getText()), + ), + ); + for (const literal of literals) + requireMemberDocs(exported.name, literal.members, documented); + } } } } diff --git a/scripts/check-middleware-types.mjs b/scripts/check-middleware-types.mjs new file mode 100644 index 0000000..966d1f5 --- /dev/null +++ b/scripts/check-middleware-types.mjs @@ -0,0 +1,24 @@ +import { execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +import { installedAtLeast } from "./docs-pages.mjs"; + +// The CI job for the oldest supported peers installs React Router 7.0, which +// `./react-router` supports and `./react-router/server` doesn't: its +// middleware needs 7.9. +if (!installedAtLeast("react-router", "7.9")) { + console.log( + "- tests/react-router-middleware.ts skipped: it needs react-router 7.9 or later", + ); +} else { + const tsc = fileURLToPath( + new URL("../node_modules/typescript/bin/tsc", import.meta.url), + ); + for (const project of [ + "tests/tsconfig.react-router-middleware.json", + "tests/tsconfig.react-router-middleware.bundler.json", + ]) + execFileSync(process.execPath, [tsc, "-p", project], { + stdio: "inherit", + }); +} diff --git a/scripts/docs-pages.mjs b/scripts/docs-pages.mjs index 456faf2..3a5291d 100644 --- a/scripts/docs-pages.mjs +++ b/scripts/docs-pages.mjs @@ -92,13 +92,22 @@ declare module "expo-crypto" { const START_ROUTE_TREE = ` import { Route as rootRoute } from "./routes/__root"; import { Route as authenticatedRouteImport } from "./routes/_authenticated"; +import { Route as apiSessionRouteImport } from "./routes/api/session"; const authenticatedRoute = authenticatedRouteImport.update({ id: "/_authenticated", getParentRoute: () => rootRoute, } as any); +const apiSessionRoute = apiSessionRouteImport.update({ + id: "/api/session", + path: "/api/session", + getParentRoute: () => rootRoute, +} as any); -export const routeTree = rootRoute.addChildren([authenticatedRoute]); +export const routeTree = rootRoute.addChildren([ + authenticatedRoute, + apiSessionRoute, +]); declare module "@tanstack/react-router" { interface FileRoutesByPath { @@ -109,6 +118,13 @@ declare module "@tanstack/react-router" { preLoaderRoute: typeof authenticatedRouteImport; parentRoute: typeof rootRoute; }; + "/api/session": { + id: "/api/session"; + path: "/api/session"; + fullPath: "/api/session"; + preLoaderRoute: typeof apiSessionRouteImport; + parentRoute: typeof rootRoute; + }; } } `; @@ -155,7 +171,6 @@ const GETTING_STARTED = { "src/backend.ts", "src/auth.ts", "src/sign-in.tsx", - "src/hooks.ts", "src/app.tsx", "src/api.ts", ], @@ -179,6 +194,16 @@ const clientPage = (slug) => ({ * `requires` skips a page when an installed package is older than it needs. */ export const documents = [ + { + // The README's quick start: a small app of its own, not an excerpt. + path: "README.md", + resolutions: ["NodeNext", "Bundler"], + dom: true, + fixtures: { + "src/sign-in-form.tsx": + "export function SignInForm() { return null; }", + }, + }, { path: page("getting-started"), resolutions: ["NodeNext", "Bundler"], @@ -205,8 +230,8 @@ export const documents = [ files: [ "src/backend.ts", "src/auth.ts", - "src/hooks.ts", "src/sign-in.tsx", + "src/api.ts", ], // Framework mode keeps its code in `app`. directories: ["src", "app"], @@ -224,6 +249,8 @@ export const documents = [ path: page("setups/tanstack-start"), // Vite resolves like a bundler, and Start apps import without extensions. resolutions: ["Bundler"], + // Start depends on the router its server routes need: 1.170 and later. + requires: { "@tanstack/react-router": "1.170" }, dom: true, fixtures: { "src/routeTree.gen.ts": START_ROUTE_TREE, @@ -258,6 +285,28 @@ export const documents = [ dom: true, fixtures: { "src/env.d.ts": SERVER_ENV }, }, + { + path: page("server-rendering/hybrid"), + // It builds on the TanStack Start guide's app. + resolutions: ["Bundler"], + requires: { "@tanstack/react-router": "1.170" }, + dom: true, + fixtures: { + "src/routeTree.gen.ts": START_ROUTE_TREE, + "src/env.d.ts": SERVER_ENV, + }, + shared: { + from: page("setups/tanstack-start"), + files: [ + "src/auth/server.ts", + "src/routes/api/session.ts", + "src/start.ts", + "src/router.tsx", + "src/routes/__root.tsx", + "src/routes/_authenticated.tsx", + ], + }, + }, { path: page("effect"), resolutions: ["NodeNext", "Bundler"], diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs index 42d8bbd..2b4f25d 100644 --- a/scripts/prepare-release.mjs +++ b/scripts/prepare-release.mjs @@ -4,16 +4,16 @@ import { pathToFileURL } from "node:url"; export function prepareRelease(manifest, changelog, version) { const number = "(?:0|[1-9][0-9]*)"; - const alpha = new RegExp( - `^${number}\\.${number}\\.${number}-alpha\\.${number}$`, + const prerelease = new RegExp( + `^${number}\\.${number}\\.${number}-(?:alpha|rc)\\.${number}$`, ); if ( typeof version !== "string" || version.trim() !== version || - !alpha.test(version) + !prerelease.test(version) ) { throw new Error( - "Use an alpha version such as 0.1.0-alpha.1, without a v prefix.", + "Use a prerelease version such as 0.1.0-rc.0, without a v prefix.", ); } if (manifest.version !== version) diff --git a/scripts/reference-docs.mjs b/scripts/reference-docs.mjs index 62ab7d2..aa80785 100644 --- a/scripts/reference-docs.mjs +++ b/scripts/reference-docs.mjs @@ -184,8 +184,8 @@ title: Error codes description: Every AuthErrorCode, what it means and when you'll see it. --- -Every error Session kit throws or reports is an \`AuthError\`. Match on its -\`code\`; the \`message\` is for people, and may change. +Every error from Session kit's own logic is an \`AuthError\`. Match on its +\`code\`. The \`message\` is for people, and may change. \`\`\`ts title="src/error-codes.ts" import { AuthError } from "@monarcode/session-kit"; diff --git a/site/DESIGN.md b/site/DESIGN.md index f37a1df..e5955e8 100644 --- a/site/DESIGN.md +++ b/site/DESIGN.md @@ -142,8 +142,8 @@ components: The page is a code buffer at stage scale. The buffer is set in Geist Mono, numbered down a line-number gutter, and divided by hairline rules; only the plain-prose leads under section heads switch to Geist, the family's sans. Headings are comments, with a dim `//` in front. Copy is -comments. The hero opens with the pitch, a lead comment and the install -prompt at the column's edge, unnumbered; the line numbers start with the +comments. The hero opens with the pitch, two lead comments (what it is, and the +setups it supports) and the install prompt at the column's edge, unnumbered; the line numbers start with the code: the real `createAuth` call from Getting started, lines 01 to 06, whose `refresh` line (05) is live. Under it, one illustrative hour plays as five lanes (signed in, refresh, storage, other tabs, route guard). @@ -308,8 +308,8 @@ code starts to the right of it, so it reads as a block set into the page. A live left of its number, so the numbers stay in one column. The hero runs as three groups set apart by space, with tight spacing -inside each: the pitch (the H1, then the lead 12–16px under it, at most -72ch), the actions 20–24px below (the package-manager switch, the install +inside each: the pitch (the H1, then the two lead comments 12–16px under it, at +most 72ch), the actions 20–24px below (the package-manager switch, the install row, Get started, GitHub), and the demo 28–32px below that (the config, then a hairline with 20px either side, then the lanes). The hero opens 32px (40px from 640px) under the navbar. Sections @@ -322,9 +322,9 @@ is its own link, to that setup's app in the repository. Below the hero the page runs: the tour, the "What it doesn't do" block comment 48px (64px from 640px) under it, the setups, the features, and a -closing section that repeats the hero's shape: a comment headline, two -comment lines of evidence (npm provenance, the bundle size), then the install -prompt and Get started. +closing section that repeats the hero's shape: a comment headline, three +comment lines of evidence (npm provenance, the tests, the bundle size), then +the install prompt and Get started. The hour's lanes are a two-column grid: lane names (5.5rem, 8rem from 640px), then 68 equal cells with a 1px gap (3px from 640px): two for the @@ -485,6 +485,19 @@ world's vocabulary. Scoped by `.docs-source`. the name in Geist Mono 600, the description in quiet grey. - **Links and inline code:** links as on the landing. Inline code is Geist Mono on the lane-empty fill, square, no border. +- **How it works figure** (`HowItWorks`, the Introduction): three flat + panels, your backend, Session kit and your components, each with a name, + a comment caption and three mono rows between hairlines. Session kit's + panel takes the `buffer-mark` outline and a foreground name, never lime. + Between the panels, hairline arrows label what crosses (tokens, state, + request, token). From 36rem of container width they run beside the panels, + level with their rows. Below that the panels stack with a two-headed arrow + between them. It is HTML, not an image, and the page's Markdown keeps a + text diagram in its place. **Motion:** once, when the figure first scrolls + into view, a 5px foreground square crosses each arrow in its direction + (450ms; both ways on a two-headed arrow), in the order a sign-in and then + a request travel, about 2.7s in all. Reduced motion leaves the arrows + still. - **Prev/next:** two square rows between hairlines, titles in the mono. - **Not found:** the home layout with one comment-voice line, "// 404: nothing at this path.", at the hero's scale, a quiet line pointing to diff --git a/site/PRODUCT.md b/site/PRODUCT.md index 6676b19..8f3a85f 100644 --- a/site/PRODUCT.md +++ b/site/PRODUCT.md @@ -86,8 +86,10 @@ those same checked examples, so the code shown is code that compiles. ## Brand Commitments -- **Pitch:** "Your backend signs users in. Session kit handles everything - after." +- **Pitch:** "Every sign-in ends in a session. Make yours type-safe and + predictable." Under it, the hero says what Session kit is ("Define, + validate, and manage application sessions with a schema-driven toolkit + built for React and meta frameworks") and which setups it supports. - **Wordmark:** "Session Kit" with the brace-and-dot mark, `assets/Session-kit-logo.svg`. The site's top bar and the docs sidebar show it, with the name in the text colour. diff --git a/site/content/docs/(latest)/client/index.mdx b/site/content/docs/(latest)/client/index.mdx index d7951e6..3c7a24d 100644 --- a/site/content/docs/(latest)/client/index.mdx +++ b/site/content/docs/(latest)/client/index.mdx @@ -8,25 +8,30 @@ session with hooks. Everything else, such as loaders, event handlers, and request code, calls the client that `createAuth` returned. These are its methods: -| Call | What it does | -| ---------------------------------- | -------------------------------------------------------------------------- | -| `auth.state.get()`, `.subscribe()` | Reads the [state](/docs/client/state), or follows its changes. | -| `auth.getSession()` | Resolves who is signed in, restoring or refreshing first, or `null`. | -| `auth.signIn(tokens)` | Saves a new session, replacing any current one. | -| `auth.signOut()` | Ends the session, clears storage, and tells other tabs. | -| `auth.updateUser(user)` | Replaces the user and keeps the session. | -| `auth.refresh()` | Refreshes now, even while the access token is usable. | -| `auth.retry()` | Tries again after a failed refresh. | -| `auth.isCurrent(session)` | Tells whether a session is still the signed-in one. | -| `auth.credentials.get()` | Resolves the access token, for code that sends requests. | -| `auth.lock()`, `auth.unlock()` | Locks and unlocks a saved session, with [`locking`](/docs/client/locking). | -| `auth.mount()` | Starts timers and tab sync. `AuthProvider` and the routers call it. | +| Call | What it does | +| ------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| `auth.state.get()`, `.subscribe()` | Reads the [state](/docs/client/state), or follows its changes. | +| `auth.getSession()` | Resolves who is signed in, restoring or refreshing first, or `null`. | +| `auth.signIn({ ...tokens, user })` | Saves a new session, replacing any current one. | +| `auth.signOut()` | Ends the session, clears storage, and tells other tabs. | +| `auth.updateUser(user)` | Replaces the user and keeps the session. | +| `auth.refresh()` | Refreshes now, even while the access token is usable. | +| `auth.retry()` | Tries again after a failed refresh. | +| `auth.isCurrent(session)` | Tells whether a session is still the signed-in one. | +| `auth.credentials.get()`, `.renew()`, `.reject()` | Resolves the access token, and replaces or ends it after a 401, for code that sends requests. | +| `auth.lock()`, `auth.unlock()` | Locks and unlocks a saved session, with [`locking`](/docs/client/locking). | +| `auth.mount()` | Starts timers and tab sync. `AuthProvider` and the routers call it. | Each method's JSDoc says what it resolves and which `AuthError` it rejects with, so your editor shows the details where you use them. +With server rendering, the browser's client comes from `createMirrorAuth`. It +has the same state, `getSession`, `signOut`, `isCurrent` and `credentials`, +but no `lock`, `unlock` or `updateUser`. See +[Server rendering](/docs/server-rendering). + The examples in this section build on the app from -[Getting started](/docs/getting-started): `auth` is its client, and +[Getting started](/docs/getting-started). `auth` is its client, and `authFetch` its `fetch`. @@ -58,7 +63,7 @@ The examples in this section build on the app from lockedAuth.unlock(); export const lockApp = () => lockedAuth.lock(); ``` +Locking comes with these rules: + - **Sealing is yours.** Session kit depends on no crypto or biometrics library. The user and session ID are saved beside the sealed tokens, readable while locked. `locking: true` stores the tokens as they are, for a @@ -47,9 +50,10 @@ export const lockApp = () => lockedAuth.lock(); - **While locked, nothing waits.** `getSession`, `retry`, `refresh`, `updateUser`, `credentials.get`, and `credentials.renew` reject with `LOCKED` instead of waiting for an unlock that may never come. Nothing - refreshes, and timers are off. `signIn` replaces the session, which is the - password path. After `lock()` resolves, `signOut` clears it without - calling `revoke`, since no tokens are left in memory. + refreshes, and timers are off. `signIn` still works and replaces the + locked session, so a user who can't unlock can sign in again. After + `lock()` resolves, `signOut` clears it without calling `revoke`, since no + tokens are left in memory. - **A failed unlock isn't always still locked.** When `open` throws, `unlock()` rejects with `UNLOCK_FAILED` and the session stays locked. But a refresh that fails after the tokens were opened rejects with diff --git a/site/content/docs/(latest)/client/other-http-clients.mdx b/site/content/docs/(latest)/client/other-http-clients.mdx index c40fd7e..50a4dad 100644 --- a/site/content/docs/(latest)/client/other-http-clients.mdx +++ b/site/content/docs/(latest)/client/other-http-clients.mdx @@ -1,11 +1,85 @@ --- title: Other HTTP clients -description: Attach the access token with axios, ky, or any other HTTP client, using the client's credentials calls. +description: Send the access token with ky, axios, openapi-fetch or any other HTTP client. --- -[`createAuthFetch`](/docs/client/requests) and the +[`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. + +A client with its own transport uses +[the calls `authFetch` is built on](#clients-without-a-fetch-option) instead. + +## Clients that take a `fetch` + +With [ky](https://github.com/sindresorhus/ky), pass `authFetch` as `fetch`: + +```ts title="src/ky.ts" +import ky from "ky"; + +import { authFetch } from "./api.js"; +import { API } from "./backend.js"; + +export const api = ky.create({ baseUrl: `${API}/`, fetch: authFetch }); + +export async function fetchCarts(userId: number): Promise { + return api.get(`auth/carts/user/${userId}`).json(); +} +``` + +With [axios](https://axios-http.com), choose its `fetch` adapter and pass +`authFetch` in `env`: + +```ts title="src/axios.ts" +import axios from "axios"; + +import { authFetch } from "./api.js"; +import { API } from "./backend.js"; + +export const http = axios.create({ + baseURL: API, + adapter: "fetch", + env: { fetch: authFetch }, +}); +``` + +[openapi-fetch](https://openapi-ts.dev/openapi-fetch/) takes it the same way +as ky: + +```ts +const client = createClient({ baseUrl: API, fetch: authFetch }); +``` + +What changes for the client's calls: + +- **Give the client the same API.** Its base URL must be on the origin that + `authFetch` was created for. A request for another origin rejects with + `INVALID_OPTIONS`, and the token isn't sent. +- **Signed out, every call rejects** with `UNAUTHENTICATED`. If the client + also calls public endpoints, such as your sign-in, create `authFetch` with + [`optional: true`](/docs/client/requests). Those requests then go without + a token. +- **A 401 reaches the client after the refresh.** For a GET or HEAD, the + client sees the answer to the request that was sent again. For a write, it + sees the 401, as ky's `HTTPError` or axios's `AxiosError`. Retry it where + sending it twice is safe. +- **Session kit's errors keep their code.** ky rejects with the `AuthError` + itself. axios wraps it in an `AxiosError` that has the same `code`, with + the `AuthError` as its `cause`. Match on `error.code`, which works with + both, rather than on `instanceof AuthError`. +- **`authFetch` sets `Authorization`.** While signed in, it replaces a + header the client set itself. +- **Only what a `Request` holds is sent.** ky hands `fetch` the options it + doesn't know itself, such as Next.js's `next`. `authFetch` doesn't pass + those on. + +## Clients without a `fetch` option + +`createAuthFetch` and the [effetch plugin](/docs/effect#6-call-your-api-with-effetch) are built on three -calls, and any other HTTP client can use the same ones: +calls, and a client with its own transport can use the same ones: 1. **Before a request**, `auth.credentials.get()` resolves the credentials to send, waiting for a restore or a refresh that is under way. It resolves @@ -15,11 +89,12 @@ calls, and any other HTTP client can use the same ones: requests failed, they share one refresh. It resolves `null` when the user was signed out instead. 3. **After a second 401**, `auth.credentials.reject(credentials)` ends the - session, unless a newer one has replaced it. + session, unless newer credentials have replaced the ones you pass. -With [axios](https://axios-http.com), that's two interceptors: +An axios instance that keeps its default adapter does it with two +interceptors: -```ts title="src/axios.ts" +```ts title="src/axios-interceptors.ts" import type { Credentials } from "@monarcode/session-kit"; import axios, { type InternalAxiosRequestConfig } from "axios"; @@ -64,60 +139,12 @@ http.interceptors.response.use(undefined, async (error: unknown) => { }); ``` -With [ky](https://github.com/sindresorhus/ky), two hooks do the same. The -request's `context` carries the credentials from one hook to the other: - -```ts title="src/ky.ts" -import type { Credentials } from "@monarcode/session-kit"; -import ky from "ky"; - -import { auth } from "./auth.js"; -import { API } from "./backend.js"; - -export const api = ky.create({ - baseUrl: `${API}/`, - hooks: { - beforeRequest: [ - async ({ request, options }) => { - const credentials = await auth.credentials.get(); - if (!credentials) return; - options.context.credentials = credentials; - request.headers.set( - "Authorization", - `Bearer ${credentials.accessToken}`, - ); - }, - ], - afterResponse: [ - async ({ request, options, response }) => { - const used = options.context.credentials as Credentials | undefined; - if (response.status !== 401 || !used) return; - - if (options.context.replayed) { - // The new token was refused too: end the session. - await auth.credentials.reject(used); - return; - } - const fresh = await auth.credentials.renew(used); - // As with authFetch, only a GET or HEAD is sent twice. - if (!fresh || !["GET", "HEAD"].includes(request.method)) return; - options.context.credentials = fresh; - options.context.replayed = true; - const headers = new Headers(request.headers); - headers.set("Authorization", `Bearer ${fresh.accessToken}`); - return ky.retry({ request: new Request(request, { headers }) }); - }, - ], - }, -}); -``` - Three things `createAuthFetch` does for you are yours to keep here: - **Keep the token on one origin.** Give the client one base URL, and don't pass it absolute URLs to other hosts. - **Don't read the token early.** Ask for credentials in the request hook, - never once at startup: a token saved in a variable goes stale at the next + never once at startup. A token saved in a variable goes stale at the next refresh. - **Check the account after slow work.** `auth.isCurrent(credentials)` tells whether the session that sent a request is still the signed-in one, before diff --git a/site/content/docs/(latest)/client/requests.mdx b/site/content/docs/(latest)/client/requests.mdx index 5e0b77e..7942eb6 100644 --- a/site/content/docs/(latest)/client/requests.mdx +++ b/site/content/docs/(latest)/client/requests.mdx @@ -3,19 +3,29 @@ title: Authenticated requests description: A fetch that sends the access token to one API, refreshes on a 401, and never leaks the token. --- -`createAuthFetch(auth, baseUrl)` returns a `fetch` for one API. It's built so -that a token can't leak and a user can't be signed out by accident: - -| When… | `authFetch`… | -| --------------------------------------- | ---------------------------------------------------------------------------- | -| The path is on another origin | Rejects with `INVALID_OPTIONS`. The token goes only to `baseUrl`'s origin. | -| The response is a redirect | Rejects rather than following it. | -| The response is a 401 | Refreshes once, then sends a GET or HEAD again with the new token. | -| A POST, PUT, PATCH or DELETE gets a 401 | Refreshes, and resolves the 401. It never sends a request twice on its own. | -| The replayed request gets a 401 too | Signs out, unless `signOutOnRepeated401` is `false`. | -| The session changes during the request | Rejects with `SESSION_CHANGED` rather than resolve another account's answer. | -| Nobody is signed in | Rejects with `UNAUTHENTICATED`, unless `optional` is `true`. | -| The network fails | Rejects as `fetch` does, unchanged. | +`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: @@ -41,7 +51,7 @@ export async function addToCart(userId: number, productId: number) { } ``` -Two options change the defaults: +Two more options change the defaults: ```ts title="src/public-api.ts" import { createAuthFetch } from "@monarcode/session-kit/http"; @@ -49,12 +59,17 @@ import { createAuthFetch } from "@monarcode/session-kit/http"; import { auth } from "./auth.js"; import { API } from "./backend.js"; -export const publicFetch = createAuthFetch(auth, `${API}/`, { +export const publicFetch = createAuthFetch(auth, { + baseUrl: `${API}/`, // One `fetch` for public and private endpoints: signed out, requests are // sent without a token instead of rejecting. optional: true, - // For APIs that answer 401 for reasons other than a rejected token, so one - // of those endpoints can't sign users out. + // For APIs that answer 401 for reasons other than a rejected token, so a + // second 401 from one of those endpoints doesn't sign users out. signOutOnRepeated401: false, }); ``` + +Without a refresh token or a `refresh` option, there's nothing to refresh +with, so the first 401 signs the user out, whatever `signOutOnRepeated401` +is. diff --git a/site/content/docs/(latest)/client/sessions.mdx b/site/content/docs/(latest)/client/sessions.mdx index 874b6ac..c45e4d6 100644 --- a/site/content/docs/(latest)/client/sessions.mdx +++ b/site/content/docs/(latest)/client/sessions.mdx @@ -24,11 +24,11 @@ export async function loadCart(): Promise { **Credentials** are the access token, `{ sessionId, accessToken, expiresAt }`, kept apart so that code which only needs the user never holds one. -[`createAuthFetch`](/docs/client/requests) reads them for you. Code that -sends requests another way uses `auth.credentials`: `get` before a request, -`renew` after a 401, and `reject` after a second one. -[Other HTTP clients](/docs/client/other-http-clients) explains the three, -with axios and ky. +[`createAuthFetch`](/docs/client/requests) reads them for you, and so does +an HTTP client that takes `authFetch` as its `fetch`. Code that sends +requests another way uses `auth.credentials`, as +[Other HTTP clients](/docs/client/other-http-clients#clients-without-a-fetch-option) +shows. `auth.isCurrent({ sessionId })` tells whether a session you're holding is still the signed-in one, for work that might finish after an account switch. diff --git a/site/content/docs/(latest)/client/signing-in-and-out.mdx b/site/content/docs/(latest)/client/signing-in-and-out.mdx index 8dc5bea..0fa5134 100644 --- a/site/content/docs/(latest)/client/signing-in-and-out.mdx +++ b/site/content/docs/(latest)/client/signing-in-and-out.mdx @@ -3,17 +3,19 @@ title: Signing in and out description: Save a new session, end it in every tab, and revoke the ended tokens on your backend. --- -`auth.signIn({ accessToken, refreshToken?, expiresIn?, user })` validates and -saves a new session, replacing any current one. The latest call wins, and -invalid input keeps the previous session. [Expiry](/docs/configuration/expiry) -covers how the token's lifetime is found. +`auth.signIn({ ...tokens, user })` validates and saves a new session, +replacing any current one, even a locked one. With +[`fromAccessToken`](/docs/client/users-from-tokens), leave out `user`. The +latest call wins, and invalid input keeps the previous session. +[Expiry](/docs/configuration/expiry) covers how the token's lifetime is +found. `auth.signOut()` ends the session and clears storage. Other tabs sign out too when the storage reports changes, as `webStorage()` does, and `locking` is off. -If your backend can revoke tokens, give the client a `revoke` callback: it -receives the ended tokens once the user is already signed out. +If your backend can revoke tokens, give the client a `revoke` callback. It +receives the ended tokens after the user is signed out: ```ts title="src/revoke.ts" import type { RevokeFn } from "@monarcode/session-kit"; @@ -31,6 +33,9 @@ export const revoke: RevokeFn = async ({ refreshToken, signal }) => { }; ``` -A failed revocation is reported in `state.error` as `REVOKE_FAILED` without -undoing the sign-out: the user asked to leave, and has. The client doesn't -revoke a session the backend already rejected. +`signOut()` resolves once `revoke` settles, so await it before a full-page +redirect, which would cancel the request. + +A failed revocation shows in `state.error` as `REVOKE_FAILED`, and the +sign-out stands. The user asked to leave, and has. The client doesn't revoke +a session the backend already rejected. diff --git a/site/content/docs/(latest)/client/state.mdx b/site/content/docs/(latest)/client/state.mdx index 4d18585..5681df1 100644 --- a/site/content/docs/(latest)/client/state.mdx +++ b/site/content/docs/(latest)/client/state.mdx @@ -22,9 +22,11 @@ export function logStatus() { ``` `subscribe` reports later changes, not the current value. A listener that -throws doesn't interrupt auth: its error is rethrown asynchronously, where +throws doesn't interrupt auth. Its error is rethrown asynchronously, where error reporting can catch it. +The state holds these fields: + | Field | Holds | | ----------- | ------------------------------------------------------------------------------------- | | `status` | Where the session stands. [How it works](/docs#how-it-works) lists each one. | @@ -38,4 +40,6 @@ Two habits follow from these fields: - **Scope private cached data to `sessionId`**, such as TanStack Query results, so one account never sees another's. - **Check `status`, not `user`, to know whether access is usable.** A - [locked](/docs/client/locking) session keeps its user. + [locked](/docs/client/locking) session keeps its user. `isSignedIn(state)` + is the check. It's `true` while `authenticated` or `refreshing`, and it + narrows `user`. `useAuth(isSignedIn)` reads it in a component. diff --git a/site/content/docs/(latest)/client/users-from-tokens.mdx b/site/content/docs/(latest)/client/users-from-tokens.mdx index 53987ed..f82f8da 100644 --- a/site/content/docs/(latest)/client/users-from-tokens.mdx +++ b/site/content/docs/(latest)/client/users-from-tokens.mdx @@ -33,6 +33,8 @@ export const signInWithTokens = (tokens: { }) => tokenAuth.signIn(tokens); ``` +Reading the user from the token changes a few things: + - **No `updateUser`.** The token is the only source of the user, so call `auth.refresh()` to pick up a change. - **The signature isn't verified.** That suits a browser, which trusts a user diff --git a/site/content/docs/(latest)/configuration/debugging.mdx b/site/content/docs/(latest)/configuration/debugging.mdx index ba5a940..9714c89 100644 --- a/site/content/docs/(latest)/configuration/debugging.mdx +++ b/site/content/docs/(latest)/configuration/debugging.mdx @@ -44,7 +44,7 @@ export const debug: AuthDebug = (event) => Events leave out tokens, saved values and the user's fields. A session appears as its `sessionId`, and an error as its code and message, without -its `cause`. +its `cause` or `issues`. To include them, pass `{ sensitive: true }`. Anyone who reads such logs can act as the user, so keep it to development builds. To set both, pass diff --git a/site/content/docs/(latest)/configuration/errors.mdx b/site/content/docs/(latest)/configuration/errors.mdx index bc23a29..5a2b2ea 100644 --- a/site/content/docs/(latest)/configuration/errors.mdx +++ b/site/content/docs/(latest)/configuration/errors.mdx @@ -1,31 +1,18 @@ --- title: Errors -description: The AuthError codes Session kit fails with, how to show them to users, and the storage failures that need your decision. +description: How Session kit's errors reach your app, how to show them to users, and the storage failures that need your decision. --- Every error from Session kit's own logic is an `AuthError`, whether a method -throws it, rejects with it, or publishes it in `state.error`. This page lists -the codes, shows how to turn them into messages for your users, and covers the -two storage failures you need to handle. +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. ## Error codes -Match on an error's `code`, not its message, which may change in any release: - -| Code | Meaning | -| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `UNAUTHENTICATED` | The operation needs a signed-in session, and there is none. | -| `REFRESH_FAILED` | The refresh callback threw, or there was no callback or refresh token to use. With server rendering, reading the session or the access token from the server failed. | -| `SESSION_CHANGED` | A newer sign-in, a sign-out, or another tab replaced the session while this ran. | -| `USER_VALIDATION_FAILED` | The user couldn't be accepted: the schema rejected it (`issues`), or, with server rendering, signing in on the server failed (`cause`). | -| `INVALID_SESSION` | Tokens or a saved session that can't be used, such as an expired token at sign-in. | -| `PERSISTENCE_FAILED` | Storage couldn't be read, written, or cleared. With server rendering, signing out on the server failed. | -| `REVOKE_FAILED` | The `revoke` callback failed. Published in `state.error`; `signOut()` still resolves. | -| `LOCKED` | The session is locked: `unlock()` it first. | -| `UNLOCK_FAILED` | `locking.open` failed, so the session stays locked. | -| `INVALID_OPTIONS` | Misuse: an option or argument Session kit can't use. | - -See [Error codes](/docs/reference/error-codes) for each code in full. +Match on an error's `code`, not its message, which may change in any +release. [Error codes](/docs/reference/error-codes) lists every code and what +it means. ## Show errors to users @@ -48,14 +35,18 @@ export function errorMessage(error: unknown): string { } ``` -`authFetch` lets the failures of `fetch` and `Request`, such as a network -error, through unchanged. They aren't `AuthError`s, so `errorMessage` shows -their own message. +`authFetch` passes on the failures of `fetch` and `Request`, such as a +network error, unchanged. With server rendering, the browser client's +`signIn` passes on what your sign-in function threw, unchanged too. These +usually aren't `AuthError`s, so `errorMessage` shows their own message. ## Handle storage failures -Two storage failures need a decision from you: +Three storage failures need a decision from you: +- **Storage can't be read.** `status` becomes `unavailable`, with the error + in `state.error`. The saved session stays as it is, and the next + `getSession()` or `retry()` reads it again. - **Storage can't be written.** The client ends the session and publishes the error. That way, no one stays signed in to a session that would vanish on reload. diff --git a/site/content/docs/(latest)/configuration/expiry.mdx b/site/content/docs/(latest)/configuration/expiry.mdx index 4ba8bb1..1174fae 100644 --- a/site/content/docs/(latest)/configuration/expiry.mdx +++ b/site/content/docs/(latest)/configuration/expiry.mdx @@ -21,7 +21,7 @@ counts it from when it receives the tokens, so a wrong device clock doesn't matter. A JWT with `iat` works the same way. Send `expiresAt` only when your backend gives no lifetime. -Pass `expiresIn` or `expiresAt`, not both: tokens with both are an +Pass `expiresIn` or `expiresAt`, not both. Tokens with both are an `INVALID_SESSION` error. See [`Tokens`](/docs/reference/core#tokens) for each field. diff --git a/site/content/docs/(latest)/configuration/index.mdx b/site/content/docs/(latest)/configuration/index.mdx index 7d4229f..79ac59c 100644 --- a/site/content/docs/(latest)/configuration/index.mdx +++ b/site/content/docs/(latest)/configuration/index.mdx @@ -11,16 +11,20 @@ longer fit your app. `createAuth` takes three required options and five optional ones: -| Option | Required | What it sets | -| --------- | -------- | ---------------------------------------------------------------------------------------------------------- | -| `name` | Yes | The storage namespace: letters, digits, `_` or `-`. Keeps two apps on one origin apart. | -| `user` | Yes | A [user schema](/docs/configuration/user-schemas), or [`fromAccessToken`](/docs/client/users-from-tokens). | -| `storage` | Yes | [Where the session is saved](/docs/configuration/storage). | -| `refresh` | No | [How to get new tokens](/docs/configuration/refresh). Without it, an expired token signs the user out. | -| `revoke` | No | [Revokes the ended tokens](/docs/client/signing-in-and-out) on your backend after a sign-out. | -| `maxAge` | No | How long a saved session can be restored, in seconds. Default: 30 days, counted again from each save. | -| `debug` | No | [Reports what the client does](/docs/configuration/debugging). Default: off. | -| `locking` | No | [Restores a saved session as `locked`](/docs/client/locking), for native apps. Default: off. | +| Option | Required | What it sets | +| --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| `name` | Yes | Names the saved session and the refresh lock: letters, digits, `_` or `-`, up to 64 characters. Keeps two apps on one origin apart. | +| `user` | Yes | A [user schema](/docs/configuration/user-schemas), or [`fromAccessToken`](/docs/client/users-from-tokens). | +| `storage` | Yes | [Where the session is saved](/docs/configuration/storage). | +| `refresh` | No | [How to get new tokens](/docs/configuration/refresh). Without it, an expired token signs the user out. | +| `revoke` | No | [Revokes the ended tokens](/docs/client/signing-in-and-out) on your backend after a sign-out. | +| `maxAge` | No | How long a saved session can be restored, in seconds. Default: 30 days, counted again from each save. | +| `debug` | No | [Reports what the client does](/docs/configuration/debugging). Default: off. | +| `locking` | No | [Restores a saved session as `locked`](/docs/client/locking), for native apps. Default: off. | + +`createAuth` throws an `AuthError` with the code `INVALID_OPTIONS` for an +option it can't use, such as a `name` with other characters, or a `maxAge` +that isn't a positive whole number. ## Pages in this section @@ -56,7 +60,7 @@ tokens, saves the session, follows other tabs, and reports what happens. :auth:session` entry. Each save is then a single write, which other tabs see whole. A [user read from the access token](/docs/client/users-from-tokens) isn't -saved: the client reads it from the token again on restore. - -Sessions saved by 0.1.0-alpha.3 or earlier aren't restored. Users of those -versions sign in once after upgrading. +saved. The client reads it from the token again on restore. diff --git a/site/content/docs/(latest)/configuration/tabs.mdx b/site/content/docs/(latest)/configuration/tabs.mdx index 1ae58cb..3dd5c54 100644 --- a/site/content/docs/(latest)/configuration/tabs.mdx +++ b/site/content/docs/(latest)/configuration/tabs.mdx @@ -15,6 +15,10 @@ through `storage` events: - A sign-in or an account switch switches every tab. - A profile update or a refresh shows in every tab. +With server rendering, `createMirrorAuth` clients follow each other over a +`BroadcastChannel` instead, as [Server rendering](/docs/server-rendering) +explains. + ## One refresh at a time The client refreshes under the `:auth:refresh` @@ -25,8 +29,8 @@ Rotating refresh tokens therefore work with several tabs open. Without Web Locks, two tabs that refresh at the same instant can both spend the token. A short reuse window on your backend covers that case. -## Expo apps and locking +## Expo apps An Expo app has one JavaScript context, so it has no tabs to follow and needs -no lock. With [`locking`](/docs/client/locking) on, tabs don't follow each -other. +no lock. In a browser, [`locking`](/docs/client/locking) stops tabs from +following each other. diff --git a/site/content/docs/(latest)/configuration/user-schemas.mdx b/site/content/docs/(latest)/configuration/user-schemas.mdx index ca12a67..5e5c02a 100644 --- a/site/content/docs/(latest)/configuration/user-schemas.mdx +++ b/site/content/docs/(latest)/configuration/user-schemas.mdx @@ -9,13 +9,14 @@ and the two rules it must follow so that a saved session can be restored. Any [Standard Schema](https://standardschema.dev) library works, such as Zod, Valibot or ArkType. If your backend puts the user in the access token -instead, see [Users from tokens](/docs/client/users-from-tokens). +instead, see [Users from the access token](/docs/client/users-from-tokens). ## When the schema runs The client runs the schema on every user it accepts: - At sign-in. +- When `updateUser` replaces the user. - After a refresh that returns a user. - When it restores a saved session. - When another tab saves a session. @@ -42,6 +43,11 @@ const { user } = auth.state.get(); // ^? ``` +To name the types elsewhere, use `UserOf` and +`SessionOf`. To type the hooks from +`@monarcode/session-kit/react`, register the client once, as +[Getting started](/docs/getting-started#4-read-the-session-in-react) shows. + ## Rules for restoring The client saves the user beside the tokens, and runs the schema on it again @@ -52,13 +58,13 @@ when it restores the session. That sets two rules for the schema: - **It accepts its own output and returns it unchanged.** A one-way transform, such as one that renames a field, breaks this rule. -`signIn` rejects a schema that breaks either rule with -`USER_VALIDATION_FAILED`. That way the problem shows up when you sign in, -not as users being signed out on their next reload. +A schema that breaks either rule is rejected with `USER_VALIDATION_FAILED` +the first time it accepts a user, usually at sign-in. That way the problem +shows up at once, not as users being signed out on their next reload. ## Users the schema rejects A deploy can change the schema so that it rejects users saved before it. The -client doesn't restore such a user: the user signs in again. A user saved by +client doesn't restore such a user, so the user signs in again. A user saved by another tab that the schema rejects signs every tab out, with `USER_VALIDATION_FAILED` in `state.error`. diff --git a/site/content/docs/(latest)/effect.mdx b/site/content/docs/(latest)/effect.mdx index d69c353..869fa0f 100644 --- a/site/content/docs/(latest)/effect.mdx +++ b/site/content/docs/(latest)/effect.mdx @@ -55,7 +55,7 @@ This is the backend from [Getting started](/docs/getting-started#1-talk-to-your-backend), as Effect Schemas: the user, the tokens, and the body DummyJSON explains a failure with. They're schemas only, with no client, so the rest of the app, and the -[server](#on-the-server), import them from one place. +[server](#on-the-server), import them from one place: ```ts title="src/backend.ts" import * as Schema from "effect/Schema"; @@ -106,11 +106,15 @@ explains. The server uses it too: import * as Fetch from "@monarcode/effetch"; import * as Effect from "effect/Effect"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as HttpClient from "effect/http/HttpClient"; import { API_BASE_URL, SessionTokens } from "./backend.js"; // Not the app's API client: its session plugin waits for this refresh. -const makeRefreshClient = Fetch.make({ baseUrl: API_BASE_URL }); +const makeRefreshClient = Fetch.make({ baseUrl: API_BASE_URL }).pipe( + // No tracing headers, as for the API client in step 6. + Effect.provideService(HttpClient.TracerPropagationEnabled, false), +); /** New tokens. `null` signs out; a failure keeps the session for a retry. */ export const refreshSession = (refreshToken: string, signal: AbortSignal) => @@ -136,11 +140,11 @@ export const refreshSession = (refreshToken: string, signal: AbortSignal) => ## 3. Register the client Create the client as usual, then register its type once, so every Effect -carries your user: +carries your user. The same registration types the hooks from +`@monarcode/session-kit/react`: ```ts title="src/auth.ts" import { createAuth, webStorage } from "@monarcode/session-kit"; -import { createAuthHooks } from "@monarcode/session-kit/react"; import { userSchema } from "./backend.js"; import { refreshSession } from "./refresh.js"; @@ -152,10 +156,7 @@ export const auth = createAuth({ refresh: ({ refreshToken, signal }) => refreshSession(refreshToken, signal), }); -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); - -declare module "@monarcode/session-kit/effect" { +declare module "@monarcode/session-kit" { interface Register { auth: typeof auth; } @@ -333,8 +334,10 @@ export const accountName = Auth.session.pipe( ); ``` -Code outside `Auth` that rejects with an `AuthError`, such as -`createAuthFetch`, converts it with `Auth.fromAuthError`. +A client method that `Auth` doesn't wrap, such as `auth.unlock()`, rejects +with an `AuthError`. `Auth.fromAuthError` turns it into an `AuthFailure`. +Anything else it's given, such as a network error from `createAuthFetch`, is +a defect. ## Update the user @@ -405,8 +408,8 @@ and its requests in flight, and renders the tree with a new one: import type { ReactNode } from "react"; import { QueryProvider } from "@monarcode/effetch-query/react"; +import { useAuth } from "@monarcode/session-kit/react"; -import { useAuth } from "./auth.js"; import { makeQueryClient } from "./query.js"; export function Queries({ children }: { children: ReactNode }) { @@ -432,10 +435,11 @@ queries and mutations made of them: ```tsx title="src/features/account.tsx" import * as Fetch from "@monarcode/effetch"; import { useMutation, useQuery } from "@monarcode/effetch-query/react"; +import { useAuthClient } from "@monarcode/session-kit/react"; +import * as Exit from "effect/Exit"; import * as AsyncResult from "effect/reactivity/AsyncResult"; import * as Schema from "effect/Schema"; -import { useAuthClient } from "../auth.js"; import { SessionUser, SignInResponse } from "../backend.js"; import { api } from "../query.js"; @@ -454,19 +458,22 @@ const profileQuery = api.query( export function SignInButton() { const auth = useAuthClient(); const { result, run } = useMutation(signInMutation); + + async function signIn() { + const exit = await run({ + // DummyJSON's documented test user. + body: { username: "emilys", password: "emilyspass" }, + }); + // A failed request shows in `result`. + if (Exit.isFailure(exit)) return; + const { accessToken, refreshToken, ...user } = exit.value; + await auth.signIn({ accessToken, refreshToken, user }); + } + return ( @@ -493,9 +500,10 @@ README describes. Make it on the server over that request's session, as With server rendering, server functions, actions and route handlers run Effects too, and the session they read is the cookie the server keeps ([Server sessions](/docs/server-rendering/server-sessions)). -`serverAuth.forRequest(jar)` is one request's session, and `Auth.layer` takes -it, so `Auth.session`, `Auth.credentials` and `sessionBearer` work there: -`sessionBearer` sends the cookie's token, and saves a renewed one after a 401. +Each framework's adapter gives one request's session (`RequestAuth`), and +`Auth.layer` takes it, so `Auth.session`, `Auth.credentials` and +`sessionBearer` work there: `sessionBearer` sends the cookie's token, and +saves a renewed one after a 401. On the server, the session comes from `createServerAuth`, with the user schema the app registers and the same refresh. The server's files build on @@ -524,6 +532,9 @@ export const serverAuth = createServerAuth({ secret, refresh: ({ refreshToken, signal }) => refreshSession(refreshToken, signal), }); + +/** One request's session, as your framework's adapter gives it. */ +export type ServerSession = ReturnType; ``` A request's session belongs to that request, and so does everything that @@ -532,30 +543,29 @@ user: ```ts title="src/server/run.ts" import { Auth } from "@monarcode/session-kit/effect"; -import type { CookieJar } from "@monarcode/session-kit/server"; import * as Effect from "effect/Effect"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as Layer from "effect/Layer"; import * as ManagedRuntime from "effect/ManagedRuntime"; import { type ApiClient, ApiClientLive } from "../api.js"; -import { serverAuth } from "./auth.js"; +import type { ServerSession } from "./auth.js"; /** Built once: what belongs to no user. */ const serverRuntime = ManagedRuntime.make(FetchHttpClient.layer); /** Built per request: its session, and the API client that uses it. */ -export const requestLayer = (jar: CookieJar) => - ApiClientLive.pipe( - Layer.provideMerge(Auth.layer(serverAuth.forRequest(jar))), - ); +export const requestLayer = (session: ServerSession) => + ApiClientLive.pipe(Layer.provideMerge(Auth.layer(session))); -/** Runs `effect` with the session of the request `jar` belongs to. */ +/** Runs `effect` with the request's `session`. */ export function runRequest( - jar: CookieJar, + session: ServerSession, effect: Effect.Effect, ): Promise { - return serverRuntime.runPromise(Effect.provide(effect, requestLayer(jar))); + return serverRuntime.runPromise( + Effect.provide(effect, requestLayer(session)), + ); } ``` @@ -564,43 +574,45 @@ doesn't compile until it goes through `runRequest`, and nothing a service keeps outlives its request. Building them is cheap next to the request your API answers. -Each framework's adapter gives the jar, in the server function, action or -handler: +Each framework's adapter gives the request's session, in the server +function, action or handler: ```ts title="src/server/profile.ts" -import type { CookieJar } from "@monarcode/session-kit/server"; - import { currentUser } from "../user.js"; +import type { ServerSession } from "./auth.js"; import { runRequest } from "./run.js"; -// TanStack Start: startJar(). React Router: routerJar(context). -// Next.js: nextJar(await cookies(), { writable: true }). -export const profileFor = (jar: CookieJar) => runRequest(jar, currentUser); +// TanStack Start: startAuth(serverAuth). React Router: +// routerAuth(serverAuth)(context). Next.js, 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 -`Auth.signIn` and `Auth.updateUser` aren't available on a request's session: -the user comes in through `serverAuth`. Ask your backend with an Effect, then +On a request's session, sign in with its own `signIn`, which takes the +tokens and the user, and update the user with its own `updateUser`. +`Auth.signIn` and `Auth.updateUser` take what the browser client's methods +do, so they aren't available there. Ask your backend with an Effect, then seal what it returns: ```ts title="src/server/sign-in.ts" -import type { CookieJar } from "@monarcode/session-kit/server"; - import { login } from "../user.js"; -import { serverAuth } from "./auth.js"; +import type { ServerSession } from "./auth.js"; import { runRequest } from "./run.js"; export async function signIn( - jar: CookieJar, + session: ServerSession, username: string, password: string, ) { const { accessToken, refreshToken, ...user } = await runRequest( - jar, + session, login(username, password), ); - return serverAuth.signIn(jar, { accessToken, refreshToken, user }); + return session.signIn({ accessToken, refreshToken, user }); } ``` @@ -611,15 +623,15 @@ server, over that request's layer, and dispose of it once the page is sent: ```ts title="src/server/query-client.ts" import { QueryClient } from "@monarcode/effetch-query"; -import type { CookieJar } from "@monarcode/session-kit/server"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as Layer from "effect/Layer"; +import type { ServerSession } from "./auth.js"; import { requestLayer } from "./run.js"; -export const queryClientFor = (jar: CookieJar) => +export const queryClientFor = (session: ServerSession) => QueryClient.make({ - layer: requestLayer(jar).pipe(Layer.provide(FetchHttpClient.layer)), + layer: requestLayer(session).pipe(Layer.provide(FetchHttpClient.layer)), }); ``` @@ -632,12 +644,13 @@ the mirror client. ### Things to know - **One registration.** An app with server rendering registers its mirror - client, and that registration types `Auth` on the server too: `Auth.layer` + client, and that registration types `Auth` on the server too. `Auth.layer` takes a request's session whose user is the registered one. In the browser, `Auth.layer(mirror)` is built where the mirror is created. - `Auth.signIn` needs the mirror's `signIn` option there, `sessionBearer` - its `credentials` option, and `Auth.updateUser` isn't available, since the - user comes from the server. + `Auth.signIn` needs the mirror's `signIn` option there. `sessionBearer` + needs `clientCredentials: true` in `createServerAuth`, or the mirror's + `credentials` option. `Auth.updateUser` isn't available, since the user + comes from the server. - **Keep server modules free of the browser client.** In this guide, the server's files import only `src/backend.ts`, `src/refresh.ts`, `src/api.ts` and `src/user.ts`, which create no Session kit client. Keep it that way in @@ -648,31 +661,31 @@ the mirror client. does, rather than inferring them from `requestLayer`. With a mirror registered, the registration depends on the server functions the mirror calls, which call `runRequest`, and TypeScript reports a circular type. For - the same reason, - the server functions the mirror is made from (its `revalidate`, `signIn` - and `signOut`) read the session with `serverAuth`, not `Auth.session`. + the same reason, the server functions the mirror is made from, such as its + `revalidate` and `signIn`, read the request's session directly, not + `Auth.session`. - **Keep a request's layer off a shared `memoMap`,** such as the runtime's or one passed to `QueryClient.make`. Layers are shared by identity there, so overlapping requests can get one build: a service that keeps `Auth` when it's built would then serve one request's session to another. -- **Read-only jars,** such as a Next.js Server Component's: `Auth.session` - returns the cookie's session as it is, while `Auth.credentials` and - `sessionBearer` fail with `REFRESH_FAILED` once access has expired, and - after a 401, which can't be renewed there unless the same request's - writable jar already renewed it. Refresh in middleware or a proxy first, - with `serverAuth.refreshIfDue`, as the framework guides do. Sign out in an - action or route handler. -- **Only `Auth`'s Effects.** A request's session has only what `Auth`'s - Effects use, so don't reach for other client methods through `Auth.use` - there. +- **Requests that can't set cookies,** such as a Next.js Server + Component's. `Auth.session` returns the cookie's session as it is. + `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, signing in and -updating the user are `serverAuth`'s. +`retry`, `mount`, and the client's options. On the server, a request's +session signs in and updates the user. ## Next steps diff --git a/site/content/docs/(latest)/faq.mdx b/site/content/docs/(latest)/faq.mdx index 0785502..573a0c6 100644 --- a/site/content/docs/(latest)/faq.mdx +++ b/site/content/docs/(latest)/faq.mdx @@ -39,8 +39,10 @@ does. ## What if some endpoints answer 401 for other reasons? -Pass `{ signOutOnRepeated401: false }` to `createAuthFetch`, so that those -endpoints can't sign users out. See +Set `signOutOnRepeated401: false` in `createAuthFetch`'s options, beside +`baseUrl`, so that a second 401 from those endpoints, after a refresh, +doesn't sign users out. Without a refresh token or a `refresh` callback, +any 401 still signs the user out. See [Authenticated requests](/docs/client/requests). ## How much does it add to my bundle? diff --git a/site/content/docs/(latest)/getting-started.mdx b/site/content/docs/(latest)/getting-started.mdx index 1726d0d..72f182b 100644 --- a/site/content/docs/(latest)/getting-started.mdx +++ b/site/content/docs/(latest)/getting-started.mdx @@ -4,10 +4,9 @@ description: Build a small app that signs in, stays signed in across reloads and --- In this guide, you build a small React app that signs in, stays signed in -across reloads and tabs, calls an API, and signs out. The six steps are the -same for every setup that keeps the session in the browser or on the device. -Server-rendered apps create their client differently, so start from -[Server rendering](/docs/server-rendering) instead. +across reloads and tabs, calls an API, and signs out. The web router guides +build on this app. Server-rendered apps create their client differently, so +start from [Server rendering](/docs/server-rendering) instead. The code signs in against [DummyJSON's auth API](https://dummyjson.com/docs/auth), a public test @@ -15,7 +14,7 @@ backend, so it runs as written. ## Before you begin -Install Session kit, Zod, and React, as +In a React app, install Session kit and Zod, as [Installation](/docs/installation) shows. ## 1. Talk to your backend @@ -71,7 +70,7 @@ export async function refresh(refreshToken: string, signal: AbortSignal) { } ``` -The schemas do two jobs: they check what the backend sent, and they give the +The schemas do two jobs. They check what the backend sent, and they give the rest of the app its types. Requests omit `credentials: "include"`, because Session kit keeps tokens out of cookies and attaches them itself. @@ -98,7 +97,8 @@ export const auth = createAuth({ /** Signs in with the backend, then hands the result to Session kit. */ export async function signInWithPassword(username: string, password: string) { - await auth.signIn(await login(username, password)); + const tokens = await login(username, password); + await auth.signIn(tokens); } export type AppAuth = typeof auth; @@ -111,7 +111,8 @@ doesn't sign anyone out. [Refresh](/docs/configuration/refresh) has the details, and [Storage](/docs/configuration/storage) lists the other places a session can be saved. -Create one client per `name` in each tab, once, as this module does. +Create the client once, at module level, as this file does. Give each client +in an app its own `name`. DummyJSON's tokens are JWTs, so their expiry comes from the `exp` and `iat` claims. [Expiry](/docs/configuration/expiry) covers backends that say it @@ -127,7 +128,7 @@ import { useState, type FormEvent } from "react"; import { signInWithPassword } from "./auth.js"; -export function SignIn({ onSignedIn }: { onSignedIn?: () => unknown }) { +export function SignIn() { const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -141,7 +142,6 @@ export function SignIn({ onSignedIn }: { onSignedIn?: () => unknown }) { String(form.get("username")), String(form.get("password")), ); - await onSignedIn?.(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not sign in"); } finally { @@ -173,33 +173,36 @@ export function SignIn({ onSignedIn }: { onSignedIn?: () => unknown }) { } ``` -The form doesn't have to do anything when it succeeds: signing in changes the -client's state, and the next step renders from that state. `onSignedIn` is for -routers, which use it to send the user on to the page they asked for. +The form doesn't have to do anything when it succeeds. Signing in changes the +client's state, and the next step renders from that state. With a router, the +sign-in page's guard runs again and sends the user on. ## 4. Read the session in React -Create the hooks once, typed by your client, and export them for every -component to share: - -```ts title="src/hooks.ts" -import { createAuthHooks } from "@monarcode/session-kit/react"; - -import type { auth } from "./auth.js"; - -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); -``` +The hooks come from `@monarcode/session-kit/react`. Register your client's +type once, where you render `AuthProvider`, and they carry your user. Then render by `status`. Each case is one of the states in [How it works](/docs#how-it-works). By the last case, TypeScript has narrowed `user` to a value that's set: ```tsx title="src/app.tsx" +import { + AuthProvider, + useAuth, + useAuthClient, +} from "@monarcode/session-kit/react"; + import { auth } from "./auth.js"; -import { AuthProvider, useAuth, useAuthClient } from "./hooks.js"; import { SignIn } from "./sign-in.js"; +// Types `AuthProvider` and the hooks with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + export function App() { return ( @@ -245,16 +248,23 @@ function AuthError() { } ``` -- `AuthProvider` mounts the client: it restores the saved session, starts the +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. +- 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. -With [`locking`](/docs/client/locking), give `locked` a case of its own: it +With [`locking`](/docs/client/locking), give `locked` a case of its own. It has a user too, but no usable access. That's a working app. To check it: @@ -275,7 +285,7 @@ import { createAuthFetch } from "@monarcode/session-kit/http"; import { auth } from "./auth.js"; import { API, userSchema } from "./backend.js"; -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); /** The signed-in user, fresh from the backend. */ export async function fetchProfile() { @@ -290,6 +300,9 @@ again. Other methods are never sent twice. [Authenticated requests](/docs/client/requests) covers the rest of its behaviour and its options. +Using ky, axios or openapi-fetch? Pass `authFetch` as the client's `fetch`: +see [Other HTTP clients](/docs/client/other-http-clients). + ## 6. Protect your routes The client is the same everywhere. What changes is how each router keeps @@ -300,8 +313,9 @@ your router: [TanStack Start in SPA mode](/docs/setups/tanstack-router#tanstack-start-in-spa-mode). - [React Router](/docs/setups/react-router), in declarative, data, or framework mode with `ssr: false`. -- [Expo Router](/docs/setups/expo), for iOS and Android. -- Without a router, you are done: render by `status`, as `Screen` does. +- [Expo Router](/docs/setups/expo), for iOS and Android. Its guide starts from + scratch. +- Without a router, you are done. Render by `status`, as `Screen` does. With Effect, the same client becomes a service: see [Effect and effetch](/docs/effect). diff --git a/site/content/docs/(latest)/index.mdx b/site/content/docs/(latest)/index.mdx index 0e738ab..4ca6dcf 100644 --- a/site/content/docs/(latest)/index.mdx +++ b/site/content/docs/(latest)/index.mdx @@ -1,12 +1,13 @@ --- title: Introduction -description: Session kit keeps your app signed in with your backend's tokens, through reloads, expired tokens, other tabs, and outages. +description: Define, validate, and manage your app's session from your backend's tokens, through reloads, expired tokens, other tabs, and outages. --- -Session kit is a React library for apps whose own backend signs users in and -issues access and refresh tokens. You hand it the tokens your backend -returns, and it manages the session from there. It works with TanStack -Router, React Router, Expo Router, TanStack Start, and Next.js. +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. 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). @@ -45,7 +46,7 @@ Session kit handles each of these moments for you: ### What it doesn't do Session kit doesn't sign users in. It has no sign-in form, no OAuth flow, and -no user database: it starts where your backend's sign-in response ends. If you +no user database. It starts where your backend's sign-in response ends. If you need those too, use an auth service or framework such as Auth.js, Better Auth, or Clerk, which manage their own sessions. @@ -54,6 +55,8 @@ or Clerk, which manage their own sessions. Session kit sits between your backend and your components. Tokens travel on the left, and only state reaches the right: + + ```text Your backend Session kit Your components ┌───────────────┐ ┌───────────────────┐ ┌──────────────────┐ @@ -64,6 +67,8 @@ the left, and only state reaches the right: issues tokens keeps the session state, never tokens ``` + + 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. @@ -87,7 +92,7 @@ Five terms come up throughout: | `status` | Meaning | `user` | | ----------------- | ------------------------------------------------------------------------- | ------ | -| `initializing` | The saved session is being restored. | `null` | +| `initializing` | The saved session hasn't been restored yet. | `null` | | `authenticated` | Access is usable. | Set | | `refreshing` | A refresh is replacing expired or rejected access. | Set | | `locked` | With `locking`, a session is saved, but its tokens wait for `unlock()`. | Set | diff --git a/site/content/docs/(latest)/installation.mdx b/site/content/docs/(latest)/installation.mdx index 7d983e1..bb84fef 100644 --- a/site/content/docs/(latest)/installation.mdx +++ b/site/content/docs/(latest)/installation.mdx @@ -55,10 +55,17 @@ Two guides apply to more than one setup: three server-rendered setups share. - [Effect and effetch](/docs/effect) works with any 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. + ## Next steps - For a setup that keeps the session in the browser or on the device, start - with [Getting started](/docs/getting-started). The router guides build on - its app. + with [Getting started](/docs/getting-started). The web router guides build + on its app. The Expo guide starts from scratch. - For a server-rendered setup, start with [Server rendering](/docs/server-rendering). diff --git a/site/content/docs/(latest)/reference/compatibility.mdx b/site/content/docs/(latest)/reference/compatibility.mdx index a9da827..2118a4a 100644 --- a/site/content/docs/(latest)/reference/compatibility.mdx +++ b/site/content/docs/(latest)/reference/compatibility.mdx @@ -25,6 +25,8 @@ import use: | `expo-file-system` | `^18.1.0` through `^58` | `/expo` | | `react-native` | `>=0.79.0` | `/expo` | +Three things to know about these peers: + - **Expo.** The Expo ranges cover Expo SDK 53 and newer. Install them with `npx expo install`, so that they match your SDK, as the [Expo guide](/docs/setups/expo#installation) shows. @@ -42,7 +44,9 @@ publishes no `exports` map, so its types don't resolve under NodeNext. ## Runtimes Session kit runs in browsers, in React Native (Expo SDK 53 and newer, with -Hermes and Metro), and in Node.js 20 and newer: +Hermes and Metro), and in Node.js 20 and newer. Your framework can need a +newer Node.js: React Router 8 needs 22.22. Session kit uses these platform +features: - **`AbortController`** is required. - **`crypto.randomUUID`** makes session IDs when present. Without it, the @@ -50,6 +54,8 @@ Hermes and Metro), and in Node.js 20 and newer: - **Web Locks** keep tabs to one refresh at a time when present. Without them, two tabs can refresh at the same instant, as [Tabs](/docs/configuration/tabs) explains. +- **`BroadcastChannel`** lets a `createMirrorAuth` client follow sign-ins and + sign-outs in other tabs, when present. - **Web Crypto** is required on the server by `@monarcode/session-kit/server`, as in Node.js 20 and newer. diff --git a/site/content/docs/(latest)/reference/core.mdx b/site/content/docs/(latest)/reference/core.mdx index e9e9d67..91a7b2c 100644 --- a/site/content/docs/(latest)/reference/core.mdx +++ b/site/content/docs/(latest)/reference/core.mdx @@ -23,6 +23,14 @@ Creates a browser client ([`MirrorAuth`](#mirrorauth)) for a session your server Reads the user from the access token, rather than from what `signIn` is given. Pass the result as `createAuth`'s `user` option. +### isSignedIn + +Whether someone is signed in: `true` while `authenticated` or `refreshing`. It narrows `state`, so `state.user` is set when it's `true`. + +### loginHref + +Builds the sign-in page's URL, with `?redirectTo=` set to `returnTo`, so the user comes back after signing in. The guards use it. Use it in a guard of your own, such as in a route handler. + ### 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. @@ -33,7 +41,7 @@ Makes a "send me back here after sign-in" path safe to redirect to, such as a `? ### webStorage -Saves the session in the browser's `localStorage`, or in `sessionStorage` with `{ area: "session" }`. Tabs follow each other's changes, such as a sign-out, and take turns to refresh where the browser supports Web Locks. +Saves the session in the browser's `localStorage`, or in `sessionStorage` with `{ area: "session" }`. With `localStorage`, tabs follow each other's changes, such as a sign-out. Tabs take turns to refresh where the browser supports Web Locks. ## Classes @@ -155,7 +163,7 @@ The browser client that [`createMirrorAuth`](#createmirrorauth) returns. It mirr ### MirrorAuthOptions -Options for [`createMirrorAuth`](#createmirrorauth). Each function is your own server function, action, or `fetch` to a route handler, which calls `serverAuth` from `@monarcode/session-kit/server`. +Options for [`createMirrorAuth`](#createmirrorauth). The client talks to your server through `endpoint`, your session route, or through functions of your own, such as server functions, which call `serverAuth` from `@monarcode/session-kit/server`. Pass `endpoint`, or `revalidate` and `signOut`. +### NextSession + +The session in a Next.js app, made by [`nextSession`](#nextsession): reads and guards for Server Components, the request's session for Server Functions and Route Handlers, and the refresh for Proxy. + +### NextSessionOptions + +Options for [`nextSession`](#nextsession). Pass Next's own `cookies` and `redirect`, as this entry point doesn't import `next`. + + + +### NextSessionRoute + +The Route Handlers [`sessionRoute`](#sessionroute) makes, for `GET` and `POST`. + +### NextSessionRouteOptions + +Options for [`sessionRoute`](#sessionroute). Pass Next's own `cookies`, as this entry point doesn't import `next`. + + + ### ProxyRequest The request [`proxyJar`](#proxyjar) reads cookies from. A `NextRequest` fits. diff --git a/site/content/docs/(latest)/reference/react-router-server.mdx b/site/content/docs/(latest)/reference/react-router-server.mdx index 9dd42e2..ece8586 100644 --- a/site/content/docs/(latest)/reference/react-router-server.mdx +++ b/site/content/docs/(latest)/reference/react-router-server.mdx @@ -15,12 +15,62 @@ Guide: [React Router with server rendering](/docs/setups/react-router-ssr). Server middleware that gives each request a `CookieJar`, found with [`routerJar`](#routerjar). It sets the cookies written to the jar on the response, redirects and error responses included. +### redirectIfSignedIn + +Makes the loader for your sign-in page, which sends a signed-in user on to the page's `redirectTo` search param, made safe with `safeReturnTo`. Signed-out users see the page. React Router adds the app's `basename` to the redirect. + +### requireSession + +Makes server middleware that lets only signed-in users through to a route and the routes nested in it ([`SessionGuard`](#sessionguard)). Their loaders and actions get the session from its `session(context)`, never `null`. + +### routerAuth + +Returns a function that gives the session of the request React Router is handling (`RequestAuth`), with every `serverAuth` method and no cookie jar. Call it with `context` in server middleware, loaders and actions, after [`cookieJarMiddleware`](#cookiejarmiddleware). Make it once, at module level. + ### routerJar -The `CookieJar` for the request React Router is handling, to pass to `serverAuth` from `@monarcode/session-kit/server`. Call it with `context` in server middleware, loaders and actions, after [`cookieJarMiddleware`](#cookiejarmiddleware). Every call during one request returns the same jar. +The `CookieJar` for the request React Router is handling, to pass to `serverAuth` from `@monarcode/session-kit/server`. [`routerAuth`](#routerauth) passes it for you. Call it with `context` in server middleware, loaders and actions, after [`cookieJarMiddleware`](#cookiejarmiddleware). Every call during one request returns the same jar. + +### 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. + +### sessionRoute + +Makes the loader and action of your session route, a resource route that answers `createMirrorAuth`'s `endpoint`: the browser client reads the session, signs out and gets the access token through it. It needs [`sessionMiddleware`](#sessionmiddleware) in the root route. ## Types +### RouterArgs + +The arguments React Router passes to server middleware and loaders, as far as the middleware and guards here read them. It's typed by its shape, like [`RouterContextLike`](#routercontextlike). + ### RouterContextLike -The `context` React Router passes to server middleware, loaders and actions in framework mode: a `RouterContextProvider`, one per request. [`routerJar`](#routerjar) and [`cookieJarMiddleware`](#cookiejarmiddleware) find the request's jar by it. It's typed by its shape, so this entry point doesn't depend on React Router's types. +The `context` React Router passes to server middleware, loaders and actions in framework mode: a `RouterContextProvider`, one per request. [`routerAuth`](#routerauth) and [`cookieJarMiddleware`](#cookiejarmiddleware) find the request by it. It's typed by its shape, so this entry point doesn't depend on React Router's types. + +### RouterLoader + +A loader typed by its shape, such as [`redirectIfSignedIn`](#redirectifsignedin)'s. + +### RouterMiddleware + +Server middleware for a route's `middleware`, typed by its shape. + +### RouterSessionRoute + +The loader and action [`sessionRoute`](#sessionroute) makes, for a resource route. + +### SessionGuard + +Server middleware that lets only signed-in users through, made by [`requireSession`](#requiresession). Call `session(context)` in the loaders and actions it guards for the session, which is never `null` there. + +### 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 0da0f1b..07b4c7b 100644 --- a/site/content/docs/(latest)/reference/react-router.mdx +++ b/site/content/docs/(latest)/reference/react-router.mdx @@ -13,11 +13,19 @@ Guide: [React Router](/docs/setups/react-router). ### redirectIfSignedIn -Guards your sign-in page in its loader, so a signed-in user goes straight to `redirectTo`, made safe with `safeReturnTo`. +Sends a signed-in user from your sign-in page straight to `redirectTo`, made safe with `safeReturnTo`, inside a loader of your own. When the loader does nothing else, use [`redirectIfSignedInLoader`](#redirectifsignedinloader) instead. + +### redirectIfSignedInLoader + +Makes the loader for your sign-in page, for `loader` or `clientLoader`. It reads `?redirectTo=` from the URL and works as [`redirectIfSignedIn`](#redirectifsignedin) does. A `loginPath` that doesn't start with `/` throws `INVALID_OPTIONS` when the loader is made. ### requireSession -Guards a route in its loader, in data or framework mode, so only signed-in users get through. They get `{ session }`, which holds no tokens. +Checks for a signed-in user inside a loader of your own, in data or framework mode, and resolves `{ session }`, which holds no tokens. When the loader does nothing else, use [`requireSessionLoader`](#requiresessionloader) as the loader instead. + +### requireSessionLoader + +Makes the loader that guards a route, for `loader` or `clientLoader`, so only signed-in users get through. It resolves `{ session }`, typed with the client's user, and works as [`requireSession`](#requiresession) does. ### useAuthRevalidation @@ -31,6 +39,20 @@ Renders child routes only while someone is signed in, in any mode. It needs an ` ## Types +### RedirectIfSignedInLoader + +The loader that [`redirectIfSignedInLoader`](#redirectifsignedinloader) makes. It reads `redirectTo` from the request's URL, and resolves `null` for a signed-out user. + +### RedirectIfSignedInLoaderOptions + +Options for [`redirectIfSignedInLoader`](#redirectifsignedinloader). + + + ### RedirectIfSignedInOptions Options for [`redirectIfSignedIn`](#redirectifsignedin). @@ -41,6 +63,20 @@ Options for [`redirectIfSignedIn`](#redirectifsignedin). name="RedirectIfSignedInOptions" /> +### RequireSessionLoader + +The loader that [`requireSessionLoader`](#requiresessionloader) makes. It resolves `{ session }`, typed with the client's user. + +### RequireSessionLoaderOptions + +Options for [`requireSessionLoader`](#requiresessionloader). + + + ### RequireSessionOptions Options for [`requireSession`](#requiresession). diff --git a/site/content/docs/(latest)/reference/react.mdx b/site/content/docs/(latest)/reference/react.mdx index 208af44..6770765 100644 --- a/site/content/docs/(latest)/reference/react.mdx +++ b/site/content/docs/(latest)/reference/react.mdx @@ -13,12 +13,26 @@ Guide: [Read the session in React](/docs/getting-started#4-read-the-session-in-r ### createAuthHooks -Creates React hooks typed for one auth client. Each call has its own context, so an app with several clients calls it once per client. With TanStack Router, pass `useRouterAuth` as `useClient` instead of rendering `AuthProvider`. See [`AuthHooksOptions`](#authhooksoptions). +Creates React hooks typed for one auth client. Use it when an app has several clients: each call has its own context, so call it once per client. With one client, register it and use [`useAuth`](#useauth), [`useAuthClient`](#useauthclient) and [`AuthProvider`](#authprovider) instead. + +### useAuth + +Reads the current auth state, or the part `selector` picks, and re-renders when it changes. With a selector, it re-renders only when that part changes. + +### useAuthClient + +Returns the client of the nearest [`AuthProvider`](#authprovider), for actions such as `signIn` and `signOut`. It's typed by the client you register in `Register`, from `@monarcode/session-kit` ([`ProvidedAuth`](#providedauth)). ### useMirrorAuth Creates a `createMirrorAuth` client once, from the session the page was rendered with, and keeps it in step with your server. Call it in the component that renders `AuthProvider`. +## Components + +### AuthProvider + +Gives a client to the hooks below it, and mounts it while rendered, which starts expiry timers and following other tabs. Render it once, around your app. + ## Types ### AuthHooks @@ -37,7 +51,7 @@ Options for [`createAuthHooks`](#createauthhooks). ### AuthProviderProps -Props for the `AuthProvider` that [`createAuthHooks`](#createauthhooks) returns. +Props for [`AuthProvider`](#authprovider), and for the one that [`createAuthHooks`](#createauthhooks) returns. diff --git a/site/content/docs/(latest)/reference/server.mdx b/site/content/docs/(latest)/reference/server.mdx index 81d161d..75e74f9 100644 --- a/site/content/docs/(latest)/reference/server.mdx +++ b/site/content/docs/(latest)/reference/server.mdx @@ -15,6 +15,10 @@ Guide: [Server sessions](/docs/server-rendering/server-sessions). Creates the server side of Session kit ([`ServerAuth`](#serverauth)). It keeps both tokens and the user in an encrypted, `httpOnly` cookie, so page scripts never see the refresh token. +### sessionHandler + +Makes the handler for your session route ([`SessionHandler`](#sessionhandler)), which answers `createMirrorAuth`'s `endpoint`. A `GET` reads the session. A `POST` signs out, or gets or renews the access token for page scripts. + ## Types ### ClientCredentials @@ -53,11 +57,11 @@ Options for [`ServerAuth`](#serverauth)'s `refreshIfDue`. ### RequestAuth -One request's session, shaped like a client. Get it from `serverAuth.forRequest(jar)`, and pass it to code that expects a client, such as `createAuthFetch` from `@monarcode/session-kit/http`. Make one per request, never at module level. +One request's session: what [`ServerAuth`](#serverauth) does for a request, without its [`CookieJar`](#cookiejar). `startAuth` from `@monarcode/session-kit/tanstack-start/server` and `routerAuth` from `@monarcode/session-kit/react-router/server` give you one, and so do `readOnly()` and `writable()` from `nextSession` in `@monarcode/session-kit/next`. Elsewhere, `serverAuth.forRequest(jar)` does. ### ServerAuth -The server side of Session kit, from [`createServerAuth`](#createserverauth). It keeps the session in an encrypted cookie. Each method takes the request's [`CookieJar`](#cookiejar), and `forRequest(jar)` gives one request's session shaped like a client ([`RequestAuth`](#requestauth)). +The server side of Session kit, from [`createServerAuth`](#createserverauth). It keeps the session in an encrypted cookie. ### ServerAuthOptions @@ -78,3 +82,17 @@ The session cookie's attributes: the `cookie` option of [`ServerAuthOptions`](#s path="node_modules/@monarcode/session-kit/dist/server/index.d.ts" name="SessionCookieOptions" /> + +### SessionHandler + +Answers the browser client's requests to your session route, for one request and its cookie jar. [`sessionHandler`](#sessionhandler) makes one. + +### SessionMiddlewareOptions + +Options for the middleware that refreshes before each request: `refreshSession` from `@monarcode/session-kit/tanstack-start/server` and `sessionMiddleware` from `@monarcode/session-kit/react-router/server`. + + diff --git a/site/content/docs/(latest)/reference/tanstack-router.mdx b/site/content/docs/(latest)/reference/tanstack-router.mdx index 09fed65..7a06b69 100644 --- a/site/content/docs/(latest)/reference/tanstack-router.mdx +++ b/site/content/docs/(latest)/reference/tanstack-router.mdx @@ -23,9 +23,13 @@ Guards your sign-in page in `beforeLoad`, so a signed-in user goes straight to ` Guards a route in `beforeLoad`, so only signed-in users get through. They get `{ session }` in route context, typed and never `null`, with no tokens in it. -### useRouterAuth +### useAuth -Reads the auth client from Router context, where it's `auth`. Pass it to `createAuthHooks` as `useClient`, so the hooks need no `AuthProvider`. Then mount the client with `connectAuth`. +Reads the current auth state of the client in Router context, or the part `selector` picks, and re-renders when it changes. With a selector, it re-renders only when that part changes. + +### useAuthClient + +Returns the auth client from Router context, where it's `auth`, for actions such as `signIn` and `signOut`. It needs no `AuthProvider`: `connectAuth` mounts the client. ## Components @@ -35,6 +39,10 @@ Renders the child routes of a route guarded by `requireSession`, but only while ## Types +### AuthRouter + +What [`connectAuth`](#connectauth) needs from a TanStack Router: the client in its context as `auth`, and the methods that run guards again and clear cached route data. A Router made by `createRouter` with `context: { auth }` fits. + ### RedirectIfSignedInOptions Options for [`redirectIfSignedIn`](#redirectifsignedin). @@ -45,10 +53,6 @@ Options for [`redirectIfSignedIn`](#redirectifsignedin). name="RedirectIfSignedInOptions" /> -### RegisteredAuth - -The auth client type in your registered Router's context, which [`useRouterAuth`](#userouterauth) returns. It's `never` until the Router is registered. - ### RequireSessionOptions Options for [`requireSession`](#requiresession). @@ -59,6 +63,10 @@ Options for [`requireSession`](#requiresession). name="RequireSessionOptions" /> +### RouterAuth + +The auth client type in your registered Router's context, as `auth`, which [`useAuthClient`](#useauthclient) returns. It's `never` until the Router is registered. + ### SessionOutletProps Props for [`SessionOutlet`](#sessionoutlet). diff --git a/site/content/docs/(latest)/reference/tanstack-start-server.mdx b/site/content/docs/(latest)/reference/tanstack-start-server.mdx index d46da0c..a3d7bb4 100644 --- a/site/content/docs/(latest)/reference/tanstack-start-server.mdx +++ b/site/content/docs/(latest)/reference/tanstack-start-server.mdx @@ -11,6 +11,24 @@ Guide: [TanStack Start](/docs/setups/tanstack-start). ## Functions +### refreshSession + +Refreshes the session before each request, while the response can still set the cookie. Pass it to Start's `createMiddleware().server()`, and list that middleware in `requestMiddleware` in `src/start.ts`. + +### sessionRoute + +Makes the handlers of your session route, a server route that answers `createMirrorAuth`'s `endpoint`: the browser client signs out and gets the access token through it. Pass them as the route's `server.handlers`. + +### startAuth + +The session of the request TanStack Start is handling (`RequestAuth`), with every `serverAuth` method and no cookie jar. Each call finds the current request, so make it once, at module level, beside `serverAuth`. + ### startJar -The `CookieJar` for the request TanStack Start is handling, to pass to `serverAuth` from `@monarcode/session-kit/server`. Use it in a server function, request middleware, a server route, or `beforeLoad` and loaders while they run on the server. Every call during one request returns the same jar. +The `CookieJar` for the request TanStack Start is handling, to pass to `serverAuth` from `@monarcode/session-kit/server`. [`startAuth`](#startauth) passes it for you. Use it in a server function, request middleware, a server route, or `beforeLoad` and loaders while they run on the server. Every call during one request returns the same jar. + +## Types + +### StartSessionRoute + +The handlers [`sessionRoute`](#sessionroute) makes, for a server route's `GET` and `POST`. diff --git a/site/content/docs/(latest)/reference/tanstack-start.mdx b/site/content/docs/(latest)/reference/tanstack-start.mdx index befc923..42919ae 100644 --- a/site/content/docs/(latest)/reference/tanstack-start.mdx +++ b/site/content/docs/(latest)/reference/tanstack-start.mdx @@ -11,20 +11,10 @@ Guide: [TanStack Start](/docs/setups/tanstack-start). ## Functions -### loadSession - -Reads this request's session into the client. Call it in the root route's `beforeLoad`. - -### sessionHydration - -Router options that carry the session from the server render to the browser. Spread them into `createRouter`. +### connectSession -## Types +Connects a TanStack Start router to the browser client in its context, as `auth`. Call it once in `getRouter`, after `createRouter`. -### DehydratedSession - -The session the server render sends to the browser, from [`sessionHydration`](#sessionhydration)'s `dehydrate`. It holds no tokens. - -### SessionHydration +### loadSession -The router options [`sessionHydration`](#sessionhydration) returns, for `createRouter`. +Reads this request's session into the client. Call it in the root route's `beforeLoad`. diff --git a/site/content/docs/(latest)/security.mdx b/site/content/docs/(latest)/security.mdx index 145ea1a..d3313b4 100644 --- a/site/content/docs/(latest)/security.mdx +++ b/site/content/docs/(latest)/security.mdx @@ -13,6 +13,12 @@ Your backend must authenticate every request and authorize private operations. Route guards, screen guards and the user's fields in the client decide what to show, not what's allowed. +With server rendering, `signIn` seals what it's given. If the browser signs +in with your backend and sends the tokens and the user, the cookie's user is +what the browser sent, until a refresh or `updateUser` replaces it. Use it to +show who is signed in. Let your backend authorize requests with the access +token, or check the tokens before `signIn`. + ## Where tokens live Each setup saves the tokens in a different place: @@ -23,18 +29,41 @@ Each setup saves the tokens in a different place: | [Server rendering](/docs/server-rendering) | An encrypted `httpOnly` cookie | | [Expo app](/docs/setups/expo) | The iOS keychain, or encrypted with an Android Keystore key | +Each place protects the tokens differently: + - **In a browser app**, any JavaScript on your origin can read the tokens, as with any credential a browser saves. They never go in cookies, so the browser doesn't send them on its own. - **With server rendering**, page scripts can't read the cookie. Only the access token reaches page scripts, and only with `clientCredentials`. -- **In an Expo app**, `secureStorage()` keeps the session out of Android - backups with the `expo-secure-store` config plugin. It also removes a - session that an earlier install left in the iOS keychain. +- **In an Expo app**, the `expo-secure-store` config plugin keeps the + session out of Android backups. `secureStorage()` removes a session that + an earlier install left in the iOS keychain. + +## The session route + +With server rendering, the browser's client signs out and gets the access +token through your session route, and reads the session there in most +setups. `sessionHandler` from `@monarcode/session-kit/server` answers it, +through each framework's `sessionRoute`. + +It answers your own site's pages only, so another site can't sign the user +out or ask for the access token. It makes two checks, and answers 403 to a +request that fails one: + +- A `Sec-Fetch-Site` header, when the request has one, must be + `same-origin`. Browsers send it with requests to https and localhost sites. +- On plain http, where browsers don't send that header, a `POST` must have + an `Origin` header that matches the request's URL. A `GET` passes: it + changes nothing, and another site can't read the answer. + +Signing in stays your own server code. A route of your own that changes the +session must refuse other sites too, where the framework doesn't check. Make +the same two checks there. ## Where tokens go -[`authFetch`](/docs/client/requests) and the effetch plugin +[`createAuthFetch`](/docs/client/requests) and the effetch plugin [`sessionBearer`](/docs/effect#6-call-your-api-with-effetch) send the access token only to your API's origin: diff --git a/site/content/docs/(latest)/server-rendering/hybrid.mdx b/site/content/docs/(latest)/server-rendering/hybrid.mdx new file mode 100644 index 0000000..5e7436d --- /dev/null +++ b/site/content/docs/(latest)/server-rendering/hybrid.mdx @@ -0,0 +1,254 @@ +--- +title: Hybrid setup +description: Sign in with your backend from the browser and call your API there, while the server keeps the session in its cookie. +--- + +In a hybrid setup, the browser talks to your backend: it signs in, and calls +your API with the access token. The server still keeps the session in its +cookie, refreshes it, and renders who is signed in. Use it when your +backend's sign-in has to run in the browser, such as a provider's SDK, or when +your pages call your API themselves. + +Two things change from a server-rendered setup: + +- **Signing in.** The browser gets the tokens from your backend and sends + them to a server function, which seals them into the cookie with + `session.signIn`. +- **Calling your API.** The session route gives the browser the access token, + and `createAuthFetch` sends it. The refresh token stays in the cookie. + +This page builds on the [TanStack Start](/docs/setups/tanstack-start) guide. +With Next.js or React Router, do the same in a Server Function or an action. + +## Before you begin + +Follow the [TanStack Start](/docs/setups/tanstack-start) guide through step 5. +This page replaces its `src/auth/functions.ts`, `src/auth/client.ts` and +`src/sign-in.ts`. + +Then let the session route serve the access token, with `clientCredentials` +in `createServerAuth`, in `src/auth/server.ts`: + +```ts +export const serverAuth = createServerAuth({ + // …the options from the guide + clientCredentials: true, +}); +``` + +## 1. Sign in with your backend in the browser + +The browser calls your backend's sign-in, which must allow requests from your +site (CORS): + +```ts title="src/backend.ts" +import { z } from "zod"; + +const API = "https://api.example.com"; + +const tokensSchema = z.object({ + accessToken: z.string(), + refreshToken: z.string(), +}); +const userSchema = z.object({ id: z.number(), firstName: z.string() }); + +/** Signs in with your backend, from the browser. */ +export async function login(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 body: unknown = await response.json(); + return { ...tokensSchema.parse(body), user: userSchema.parse(body) }; +} +``` + +## 2. 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 +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: + +```ts title="src/auth/functions.ts" +import { createServerFn } from "@tanstack/react-start"; +import { z } from "zod"; + +import { session } from "./server"; + +const API = "https://api.example.com"; + +export const getSessionFn = createServerFn().handler(() => + session.getSession(), +); + +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. + 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); + return session.signIn({ ...data, user }); + }); +``` + +The client's `signIn` takes the tokens, and sends them to `signInFn`: + +```ts title="src/auth/client.ts" +import { createMirrorAuth } from "@monarcode/session-kit"; + +import { getSessionFn, signInFn } from "./functions"; + +export function createAppAuth() { + return createMirrorAuth({ + name: "app", + session: null, // filled by loadSession, then by hydration + endpoint: "/api/session", + revalidate: () => getSessionFn(), + signIn: (tokens: { accessToken: string; refreshToken: string }) => + signInFn({ data: tokens }), + }); +} + +export type AppAuth = ReturnType; +``` + +The form signs in with your backend, then with the client. The sign-in +page's guard sends the user on, so the form doesn't navigate: + +```ts title="src/sign-in.ts" +import type { AppAuth } from "./auth/client"; +import { login } from "./backend"; + +/** Signs in, and resolves the message to show when it fails. */ +export async function signIn( + auth: AppAuth, + username: string, + password: string, +): Promise { + try { + const { accessToken, refreshToken } = await login(username, password); + await auth.signIn({ accessToken, refreshToken }); + return null; + } catch (error) { + return error instanceof Error ? error.message : "Could not sign in"; + } +} +``` + +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. + +### Pass the tokens without a check + +The server function takes the tokens and the user the browser sends, and +seals them as they are: + +```ts title="src/auth/trusting-sign-in.ts" +import { createServerFn } from "@tanstack/react-start"; +import { z } from "zod"; + +import { session } from "./server"; + +export const trustingSignInFn = createServerFn({ method: "POST" }) + .validator( + z.object({ + accessToken: z.string(), + refreshToken: z.string(), + user: z.object({ id: z.number(), firstName: z.string() }), + }), + ) + .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: + +```ts +signIn: (result: Awaited>) => + trustingSignInFn({ data: result }), +``` + +Anyone can then put any user in their own cookie, with tokens of their own. +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. + +When in doubt, check the tokens first. It costs one request at sign-in. + +## 3. 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 +once per page load: + +```tsx title="src/orders.tsx" +import { useMemo, useState } from "react"; + +import { createAuthFetch } from "@monarcode/session-kit/http"; +import { useAuthClient } from "@monarcode/session-kit/tanstack-router"; + +export function Orders() { + const auth = useAuthClient(); + const apiFetch = useMemo( + () => createAuthFetch(auth, { baseUrl: "https://api.example.com/" }), + [auth], + ); + const [count, setCount] = useState(null); + + async function load() { + const response = await apiFetch("orders"); + if (!response.ok) throw new Error(`Orders failed (${response.status})`); + const orders: unknown = await response.json(); + setCount(Array.isArray(orders) ? orders.length : 0); + } + + return ( +
+ + {count !== null &&

{count} orders

} +
+ ); +} +``` + +With ky, axios or openapi-fetch, pass `apiFetch` as the client's `fetch`: see +[Other HTTP clients](/docs/client/other-http-clients). + +The browser keeps the access token in memory, never the refresh token. After +a 401, the client asks the session route for a new token, and the server +refreshes with the cookie's refresh token. Server functions can still call +your API too, as the guide's +[Call your API](/docs/setups/tanstack-start#call-your-api) shows. + +## Things to know + +- **The refresh token passes through the browser once,** in your backend's + sign-in response, on its way to the server. After that, page scripts never + see it. If your backend's sign-in can run on the server, sign in there, as + the setup guides do. +- **Your backend must allow your site (CORS)** for its sign-in and the API + calls you make from the browser. Session kit's own requests go to your + session route, on your site. +- **Signing out** works as in the guide'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). diff --git a/site/content/docs/(latest)/server-rendering/index.mdx b/site/content/docs/(latest)/server-rendering/index.mdx index 18a3fa7..e346e01 100644 --- a/site/content/docs/(latest)/server-rendering/index.mdx +++ b/site/content/docs/(latest)/server-rendering/index.mdx @@ -8,47 +8,49 @@ 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 `httpOnly` cookie that page scripts can't -read, so the refresh token never reaches the browser. The server refreshes +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 and refreshes before rendering. Each of - its methods takes the request's cookie jar, which each framework's adapter - gives you. + seals the cookie with your secret. Each framework's adapter gives one + request's session over it, and middleware that refreshes before + rendering. - **In the browser**, `createMirrorAuth` makes a client that starts from the session the server rendered. `AuthProvider`, the hooks, and the TanStack Router guards work with it, and sign-ins and sign-outs reach every tab. -- **Your server code** signs in and out with your backend and calls your API - with the access token. `serverAuth.forRequest(jar)` gives code written for - a client, such as `createAuthFetch` or Effect's `Auth`, one request's - session. To call your API from the browser too, opt in with - `clientCredentials`: page scripts then get the access token in memory, +- **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: +The engine is the same `createServerAuth` call in every framework. [Create the server engine](/docs/setups/tanstack-start#1-create-the-server-engine) on the TanStack Start page shows one. The browser's client mirrors what the -server rendered, and asks the server to sign in and out through your own -server code, as in +server rendered. It signs out and gets the access token through a session +route, which each adapter's `sessionRoute` makes. It reads the session there +too, except in TanStack Start, where a server function reads it, as the +server render needs. It signs in through your own server code, as in [Create the browser client](/docs/setups/tanstack-start#4-create-the-browser-client). ## Frameworks -What differs between frameworks is how the cookie jar reaches the engine, and -how the session reaches the browser: +What differs between frameworks is how server code gets a request's +session, and how the session reaches the browser: -| Framework | On the server | In the browser | Setup | -| ------------------------------------- | ----------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------- | -| TanStack Start | `startJar()`, refreshing in request middleware | `sessionHydration`, `loadSession` | [TanStack Start](/docs/setups/tanstack-start) | -| Next.js 16, App Router | `nextJar(await cookies())`, `proxyJar` in Proxy | `useMirrorAuth` from `@monarcode/session-kit/react` | [Next.js](/docs/setups/next) | -| React Router framework mode, with SSR | `cookieJarMiddleware`, `routerJar(context)` | `useMirrorAuth` from `@monarcode/session-kit/react` | [React Router with server rendering](/docs/setups/react-router-ssr) | +| Framework | On the server | In the browser | Setup | +| ------------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------- | +| TanStack Start | `startAuth(serverAuth)`, with `refreshSession` in request middleware | `connectSession`, `loadSession` | [TanStack Start](/docs/setups/tanstack-start) | +| Next.js 16, App Router | `nextSession(serverAuth, { cookies, redirect })`, with its `refresh` in Proxy | `useMirrorAuth` from `@monarcode/session-kit/react` | [Next.js](/docs/setups/next) | +| React Router framework mode, with SSR | `routerAuth(serverAuth)`, with `sessionMiddleware` in the root route | `useMirrorAuth` from `@monarcode/session-kit/react` | [React Router with server rendering](/docs/setups/react-router-ssr) | Locking isn't available with server rendering. For another server, such as -the Next.js Pages Router, build a `CookieJar` over its cookies and use -`createServerAuth` directly. +the Next.js Pages Router, see +[Servers without an adapter](/docs/server-rendering/server-sessions#servers-without-an-adapter). ## Next steps @@ -56,3 +58,6 @@ the Next.js Pages Router, build a `CookieJar` over its cookies and use calling your API. - [Server sessions](/docs/server-rendering/server-sessions): the secret, cookie jars, refreshes across server instances, sign-out, and limits. +- [Hybrid setup](/docs/server-rendering/hybrid): sign in with your backend + from the browser and call your API there, with the session still on the + server. diff --git a/site/content/docs/(latest)/server-rendering/meta.json b/site/content/docs/(latest)/server-rendering/meta.json index 0b89c35..f44b3d7 100644 --- a/site/content/docs/(latest)/server-rendering/meta.json +++ b/site/content/docs/(latest)/server-rendering/meta.json @@ -1,5 +1,5 @@ { "title": "Server rendering", "defaultOpen": true, - "pages": ["index", "server-sessions"] + "pages": ["index", "server-sessions", "hybrid"] } diff --git a/site/content/docs/(latest)/server-rendering/server-sessions.mdx b/site/content/docs/(latest)/server-rendering/server-sessions.mdx index 89c1dab..59176d9 100644 --- a/site/content/docs/(latest)/server-rendering/server-sessions.mdx +++ b/site/content/docs/(latest)/server-rendering/server-sessions.mdx @@ -4,8 +4,8 @@ description: How the server keeps the session in every framework, from the cooki --- This page covers what every server-rendered setup shares: the cookie and its -secret, cookie jars, refreshes, sign-out, and limits. Read it once your app -works, to deploy it. The setup guides show the code: +secret, a request's session, refreshes, sign-out, and limits. Read it once +your app works, to deploy it. The setup guides show the code: [TanStack Start](/docs/setups/tanstack-start), [Next.js](/docs/setups/next), and [React Router with server rendering](/docs/setups/react-router-ssr). @@ -18,7 +18,7 @@ Crypto. It's `httpOnly`, so page scripts can't read it, and `Secure` and `createAuth` does, except `storage` and `locking`, plus `secret`, `cookie` and `clientCredentials`. -Keep the module that creates it on the server: each setup page shows how +Keep the module that creates it on the server. Each setup guide shows how its framework keeps such a module out of the browser bundle. ## The secret @@ -28,6 +28,12 @@ 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. +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. + 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: @@ -46,37 +52,63 @@ export const serverAuth = createServerAuth({ }); ``` -Remove `OLD_SESSION_SECRET` once the sessions it sealed have expired. A cookie -that no listed secret opens reads as signed out. - -## Cookie jars - -Every `serverAuth` method takes the request's `CookieJar`, which each -framework's adapter gives you. Use one jar per request: calls with the same -jar share what it read and wrote and one refresh, so a jar kept at module -level would show one request's session to the next. - -A jar is read-only where the framework can't set cookies, as while a Server -Component renders or a page streams. There, nothing is refreshed or saved: -see `CookieJar.writable` for which calls reject and with what. Refresh before -rendering, in middleware or a proxy, with `serverAuth.refreshIfDue`. For -another server, build a [`CookieJar`](/docs/reference/server#cookiejar) over -its cookies. - -## Code that takes a client - -`serverAuth.forRequest(jar)` is one request's session shaped like a client -(`RequestAuth`). Code written for a client works on the server with it: -`createAuthFetch(serverAuth.forRequest(jar), baseUrl)` sends the cookie's -token and saves a renewed one after a 401, and Effect's `Auth.layer` takes -it ([Effect on the server](/docs/effect#on-the-server)). Make it per request, -like the jar. +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. + +## A request's session + +Your server code reads and changes the session through one request's +session (`RequestAuth`). It has every `serverAuth` method, without the +request's cookie jar to pass: + +- **TanStack Start:** `startAuth(serverAuth)`, made once at module level. + Each call finds the request Start is handling. +- **React Router:** `routerAuth(serverAuth)` makes a function you call with + a loader's, action's or middleware's `context`. +- **Next.js:** `nextSession(serverAuth, { cookies, redirect })`, whose + `writable()` gives it in Server Functions and Route Handlers, and + `readOnly()` in Server Components. +- **Servers without an adapter:** `serverAuth.forRequest(jar)`, over the + request's cookie jar. + +It's shaped like a client, so code written for one works on the server with +it. `createAuthFetch(session, { baseUrl })` sends the cookie's token and saves +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. + +## Servers without an adapter + +Every `serverAuth` method also takes the request's `CookieJar` first: +`serverAuth.getSession(jar)` does what a request's `getSession()` does, and +`serverAuth.forRequest(jar)` gives that request's session. For a server +without an adapter, build a [`CookieJar`](/docs/reference/server#cookiejar) +over its cookies. Answer the browser client's session route with +`sessionHandler(serverAuth)`, called with the request and its jar. + +Use one jar per request. Calls with the same jar share what it read and +wrote and one refresh, so a jar kept at module level would show one +request's session to the next. A jar that can't set cookies says so with +`writable: false`. ## Token refresh 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. +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. Each `createServerAuth` call is its own instance, and a framework may make several on one server, one per bundle. Separate processes, servers, and @@ -86,7 +118,7 @@ instances that refresh the same session then don't sign it out. ## Sign-out -`serverAuth.signOut` clears the cookie in this browser, then calls your +A request's `signOut` clears the cookie in this browser, then calls your `revoke`. The cookie holds the whole session and the server keeps no list of sessions, so a copy of the cookie made before sign-out still reads as signed in. For ten seconds, the instance that signed out treats such a copy as @@ -100,30 +132,31 @@ revocation. ## The access token in the browser -Server code calls your API with `serverAuth.credentials`. To call it from the -browser too, with `createAuthFetch` or effetch's `sessionBearer`, opt in with -`clientCredentials: true` and expose `serverAuth.clientCredentials.get` and -`.renew` through your own same-origin endpoint, passed to `createMirrorAuth` -as `credentials`. Page scripts then hold the access token in memory, never the -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. +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. -Accept requests to that endpoint from your own site only. Where the framework -doesn't check, compare `Sec-Fetch-Site` to `same-origin`: browsers send it -since 2023 (Safari 16.4), and older ones are refused. +The session route answers your own site's pages only: see +[The session route](/docs/security#the-session-route). ## Limits - **Size.** The cookie can take about 7.5 KB across two cookies, 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. A larger user rejects at sign-in - with `PERSISTENCE_FAILED`, so keep the user small. + every page until the cookie is cleared. That holds about 5.5 KB of tokens + and user before encryption. A larger session rejects at sign-in with + `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 local development there, never in production. -- **Locking.** `locking` isn't available: the server keeps the tokens, so - there is nothing on the device to lock. +- **Locking.** `locking` isn't available. The server keeps the tokens, so + there's nothing on the device to lock. ## Next steps diff --git a/site/content/docs/(latest)/setups/expo.mdx b/site/content/docs/(latest)/setups/expo.mdx index 1c9e2dd..ad2b961 100644 --- a/site/content/docs/(latest)/setups/expo.mdx +++ b/site/content/docs/(latest)/setups/expo.mdx @@ -15,8 +15,8 @@ This page builds the [`expo-router` example app](https://github.com/monarcode/session-kit/tree/main/examples/expo-router) from scratch. It signs in against [DummyJSON's auth API](https://dummyjson.com/docs/auth), so it runs as -written. Its `src/auth.ts` takes the place of Getting started's `backend.ts`, -`auth.ts` and `hooks.ts`. [Using the client](/docs/client), +written. Its `src/auth.ts` takes the place of Getting started's `backend.ts` +and `auth.ts`. [Using the client](/docs/client), [Refresh](/docs/configuration/refresh) and [Errors](/docs/configuration/errors) explain how the client works. This page covers what differs on Expo. @@ -25,7 +25,7 @@ covers what differs on Expo. - Expo SDK 53 or newer: Expo Router 5 or newer, and React Native 0.79 or newer. -- iOS and Android only. Expo web is not supported: on the web, use a +- iOS and Android only. Expo web is not supported. On the web, use a [web router setup](/docs/installation#pick-your-setup) with `webStorage()`. - Expo Go, which includes `expo-secure-store` and `expo-file-system`, or a development build with both installed. @@ -39,9 +39,10 @@ picks the peer versions that match your SDK: npx expo install @monarcode/session-kit expo-secure-store expo-file-system zod ``` -An Expo Router app already has `expo-router` and `react-native`. Add the -`expo-secure-store` config plugin to `app.json`, so Android Auto Backup leaves -the session out of backups: +An Expo Router app already has `expo-router` and `react-native`. Holding the +splash screen needs `expo-splash-screen`, so install it too if your app +doesn't have it. Add the `expo-secure-store` config plugin to `app.json`, so +Android Auto Backup leaves the session out of backups: ```json { @@ -63,7 +64,6 @@ as on the web: import { createAuth } from "@monarcode/session-kit"; import { secureStorage } from "@monarcode/session-kit/expo"; import { createAuthFetch } from "@monarcode/session-kit/http"; -import { createAuthHooks } from "@monarcode/session-kit/react"; import { z } from "zod"; const API = "https://dummyjson.com"; @@ -99,10 +99,7 @@ export const auth = createAuth({ }, }); -export const { AuthProvider, useAuth, useAuthClient } = - createAuthHooks(); - -export const authFetch = createAuthFetch(auth, `${API}/`); +export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` }); export async function signInWithPassword(username: string, password: string) { const response = await fetch(`${API}/auth/login`, { @@ -122,15 +119,25 @@ export async function signInWithPassword(username: string, password: string) { `SessionGate` goes inside `AuthProvider`, around the root navigator. Guard the screens with `Stack.Protected`. Signed-in users see the `(app)` group, and -everyone else sees `login`: +everyone else sees `login`. Register the client's type here, so the hooks +from `@monarcode/session-kit/react` carry your user: ```tsx title="app/_layout.tsx" +import { isSignedIn } from "@monarcode/session-kit"; import { SessionGate } from "@monarcode/session-kit/expo"; +import { AuthProvider, useAuth } from "@monarcode/session-kit/react"; import { SplashScreen, Stack } from "expo-router"; -import { auth, AuthProvider, useAuth } from "../src/auth"; +import { auth } from "../src/auth"; import { Unavailable } from "../src/unavailable"; +// Types `AuthProvider` and the hooks with this client. +declare module "@monarcode/session-kit" { + interface Register { + auth: typeof auth; + } +} + // Keeps the splash screen up until SessionGate hides it. void SplashScreen.preventAutoHideAsync(); @@ -145,9 +152,8 @@ export default function RootLayout() { } function RootStack() { - // `status`, not `user`: a locked session keeps its user. See Locking. - const status = useAuth((state) => state.status); - const signedIn = status === "authenticated" || status === "refreshing"; + // Not signed in while locked, though a locked session keeps its user. + const signedIn = useAuth(isSignedIn); return ( @@ -166,13 +172,14 @@ function RootStack() { guards never see `initializing`. If the first screen needs more than the session, such as fonts, pass `ready`. -The splash screen then stays up until both are done: +The splash screen then stays up until both are done. Count a failed load as +done, or the splash screen never hides: ```tsx -const [fontsLoaded] = useFonts(fonts); +const [fontsLoaded, fontError] = useFonts(fonts); } > @@ -183,28 +190,22 @@ const [fontsLoaded] = useFonts(fonts); `Stack.Protected` sends a link to a guarded screen to the first screen the user may see, so a signed-out user who opens `myapp://profile` lands on the -sign-in screen and the link is lost. `rememberDeepLink` keeps it, and +sign-in screen and the link is lost. `deepLinkHandler` keeps it, and `SessionGate` opens it after the sign-in. Expo Router calls `redirectSystemPath` with every URL that opens the app, before routing: ```tsx title="app/+native-intent.tsx" -import { rememberDeepLink } from "@monarcode/session-kit/expo"; +import { deepLinkHandler } from "@monarcode/session-kit/expo"; import { auth } from "../src/auth"; -export function redirectSystemPath({ - path, -}: { - path: string; - initial: boolean; -}) { - rememberDeepLink(auth, path); - return path; -} +export const redirectSystemPath = deepLinkHandler(auth); ``` -Return `path` unchanged: the link still goes to Expo Router, which shows it -right away when the user is signed in. +It returns the path unchanged. The link still goes to Expo Router, which +shows it right away when the user is signed in. If your `redirectSystemPath` +does more, such as rewriting old links, call `rememberDeepLink(auth, path)` +in it instead. ## 4. Add the sign-in screen @@ -261,8 +262,10 @@ deep link `SessionGate` opens. ## 5. Add the signed-in screens Screens inside the guarded group read the user with `useAuth`, and call the API -with `authFetch`, which attaches the access token and refreshes after a 401. The -group's layout is a plain stack: +with `authFetch`, which attaches the access token and refreshes after a 401. To +use axios or another HTTP client instead, see +[Other HTTP clients](/docs/client/other-http-clients). The group's layout is a +plain stack: ```tsx title="app/(app)/_layout.tsx" import { Stack } from "expo-router"; @@ -272,39 +275,77 @@ export default function AppLayout() { } ``` -Its first screen shows the user's name, fetches their email, and signs out: +Its first screen shows the user's name, links to the profile, and signs out: ```tsx title="app/(app)/index.tsx" -import { useEffect, useState } from "react"; import { Button, Text, View } from "react-native"; -import { authFetch, useAuth, useAuthClient } from "../../src/auth"; +import { useAuth, useAuthClient } from "@monarcode/session-kit/react"; +import { Link } from "expo-router"; export default function Home() { const firstName = useAuth((state) => state.user?.firstName); const auth = useAuthClient(); - const [email, setEmail] = useState(""); + return ( + + Welcome, {firstName} + Profile + {/* No navigation: Stack.Protected then shows the sign-in screen. */} + + ); +} +``` ## Call your API -On the server, get the access token in a server function. -`credentials.get` refreshes it first when it has expired: +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: + +```ts title="src/auth/api-fetch.ts" +import "@tanstack/react-start/server-only"; +import { createAuthFetch } from "@monarcode/session-kit/http"; + +import { session } from "./server"; + +export const apiFetch = createAuthFetch(session, { + baseUrl: "https://api.example.com/", +}); +``` + +Then call it in a server function. Signed out, it rejects with +`UNAUTHENTICATED`: ```ts title="src/orders.ts" -import { startJar } from "@monarcode/session-kit/tanstack-start/server"; import { createServerFn } from "@tanstack/react-start"; import { z } from "zod"; -import { serverAuth } from "./auth/server"; +import { apiFetch } from "./auth/api-fetch"; export const getOrdersFn = createServerFn().handler(async () => { - const credentials = await serverAuth.credentials.get(startJar()); - if (!credentials) throw new Error("Sign in first"); - const response = await fetch("https://api.example.com/orders", { - headers: { Authorization: `Bearer ${credentials.accessToken}` }, - }); + const response = await apiFetch("orders"); if (!response.ok) throw new Error(`Orders failed (${response.status})`); return z.array(z.object({ id: z.number() })).parse(await response.json()); }); ``` +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`. -Expose `serverAuth.clientCredentials.get` and `.renew` through two POST server -functions, and pass them as the client's `credentials`. The browser then -keeps the access token in memory, never the refresh token. The example app -does this. +The session route then serves the access token, and the client's +`credentials` get it there. The browser keeps the access token in memory, +never the refresh token. The example app does this. ## Things to know -- **Signing out ends the session only with `revoke`.** A copy of the cookie - works again ten seconds after sign-out: see +- **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 jar per request.** `startJar()` returns the same jar for every call - while Start handles a request. +- **One session per request.** Each call to `session` reads the request + Start is handling, and calls during one request share what it read and + one refresh. Outside a request, such as in the browser, they reject with + `INVALID_OPTIONS`. - **Caching.** Pages and server functions that read the session differ per - user, and Start sends no `Cache-Control` for them. Behind a CDN or proxy - that caches responses, mark them private, for example with - `setResponseHeader("Cache-Control", "private, no-store")` from - `@tanstack/react-start/server` in request middleware, as the example app - does. + user. `refreshSession` sends `Cache-Control: private, no-store` with each + response that doesn't set its own, so a CDN or proxy doesn't cache them. + To leave every response as it is, pass `{ cacheControl: false }`. - **Prerendering.** A prerendered page renders at build time, without a cookie, so it shows the signed-out state. Don't prerender pages that read the session. diff --git a/site/public/og.png b/site/public/og.png index 484864d..5309dd9 100644 Binary files a/site/public/og.png and b/site/public/og.png differ diff --git a/site/src/components/docs/how-it-works.tsx b/site/src/components/docs/how-it-works.tsx new file mode 100644 index 0000000..79b9e75 --- /dev/null +++ b/site/src/components/docs/how-it-works.tsx @@ -0,0 +1,240 @@ +import { Fragment, useEffect, useRef, type CSSProperties } from "react"; + +// The "How it works" figure on the Introduction: your backend, Session kit and +// your components as three flat panels, with what crosses between them drawn +// as hairline arrows. HTML rather than an image, so it reflows with the page, +// stays selectable, and takes the site's own type and colours. + +type Direction = "left" | "right" | "both"; + +type Crossing = { direction: Direction; label: string } | null; + +const COLUMNS = [ + { + name: "Your backend", + note: "issues tokens", + items: ["POST /login", "POST /refresh", "GET /orders"], + }, + { + name: "Session kit", + note: "keeps the session", + items: ["signIn()", "refresh, on time", "authFetch()"], + }, + { + name: "Your components", + note: "state, never tokens", + items: ["useAuth()", "route guards", "loaders, queries"], + }, +] as const; + +// For each row, what crosses the gap after the backend and the gap after +// Session kit. Tokens only ever cross the first. +const CROSSINGS: readonly [Crossing, Crossing][] = [ + [ + { direction: "right", label: "tokens" }, + { direction: "right", label: "state" }, + ], + [{ direction: "both", label: "tokens" }, null], + [ + { direction: "left", label: "token" }, + { direction: "left", label: "request" }, + ], +]; + +// When a packet sets off across each arrow, in ms, in the order a sign-in and +// then a request travel: the login row, the refresh, then the request out. +const DELAYS: readonly [number, number][] = [ + [0, 450], + [900, 0], + [2250, 1800], +]; + +const HEADER = "h-16"; +const ROW = "h-12"; + +/** + * Where tokens, state and requests travel between the backend, Session kit + * and the components, as a figure. + * + * The page puts a text diagram inside it. This component ignores that, and + * the page's Markdown keeps it. + */ +export function HowItWorks() { + const figure = useRef(null); + + // Plays the packets once, when the figure first scrolls into view. + useEffect(function playWhenSeen() { + const node = figure.current; + if (!node || typeof IntersectionObserver === "undefined") return; + const observer = new IntersectionObserver( + function onIntersect([entry]) { + if (!entry?.isIntersecting) return; + node.dataset.play = ""; + observer.disconnect(); + }, + { threshold: 0.4 }, + ); + observer.observe(node); + return function unwatch() { + observer.disconnect(); + }; + }, []); + + return ( +
+
+ {COLUMNS.map((column, index) => ( + + {index > 0 && ( + row[index - 1] ?? null, + )} + delays={DELAYS.map((row) => row[index - 1] ?? 0)} + /> + )} +
+
+ + {column.name} + + + + {column.note} + +
+ {column.items.map((item, row) => ( +
0 ? "border-t border-buffer-line" : "" + }`} + > + {item} +
+ ))} +
+
+ ))} +
+
+ ); +} + +/** What crosses between two panels: beside them from 36rem, between them below. */ +function Gap({ + crossings, + delays, +}: { + crossings: Crossing[]; + delays: number[]; +}) { + return ( + <> + + + + ); +} + +function Arrow({ + direction, + label, + delay, +}: { + direction: Direction; + label: string; + delay: number; +}) { + return ( +
+ + {label} + + {direction !== "right" && } + + + + {direction !== "left" && } +
+ ); +} + +/** The square that crosses an arrow once; `app.css` plays it. */ +function Packet({ + axis, + direction, + delay, +}: { + axis: "x" | "y"; + direction: Direction; + delay: number; +}) { + return ( + + ); +} + +function Arrowhead({ className = "" }: { className?: string }) { + return ( + + + + ); +} diff --git a/site/src/components/landing/closing.tsx b/site/src/components/landing/closing.tsx index 085f5ed..0a04fab 100644 --- a/site/src/components/landing/closing.tsx +++ b/site/src/components/landing/closing.tsx @@ -1,5 +1,7 @@ import { Link } from "@tanstack/react-router"; +import { gitConfig } from "@/lib/shared"; + import { COLUMN, PRIMARY_ACTION, SectionHead } from "./buffer"; import { Install } from "./install"; @@ -8,7 +10,7 @@ const INLINE_LINK = /** * Where the page ends: the hero's actions again, so a visitor who read to the - * bottom doesn't scroll back for them, under two facts they can check. + * bottom doesn't scroll back for them, under three facts they can check. */ export function Closing() { return ( @@ -28,6 +30,19 @@ export function Closing() {
.

+

+ + Each one passes{" "} + + the test suite + {" "} + twice, with synchronous and with asynchronous storage. +

- +
{FEATURES.map(([title, text]) => (